executor.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. import { describe, expect } from "bun:test"
  2. import { Effect, Layer, Ref } from "effect"
  3. import { Headers, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
  4. import { LLM, LLMError } from "../src"
  5. import { LLMClient, RequestExecutor } from "../src/route"
  6. import * as OpenAIChat from "../src/protocols/openai-chat"
  7. import { dynamicResponse } from "./lib/http"
  8. import { deltaChunk } from "./lib/openai-chunks"
  9. import { sseRaw } from "./lib/sse"
  10. import { it } from "./lib/effect"
  11. const request = HttpClientRequest.post("https://provider.test/v1/chat?api_key=secret&key=secret&debug=1").pipe(
  12. HttpClientRequest.setHeaders(Headers.fromInput({ authorization: "Bearer secret", "x-safe": "visible" })),
  13. )
  14. const secretRequest = HttpClientRequest.post("https://provider.test/v1/chat?api_key=query-secret-123&debug=1").pipe(
  15. HttpClientRequest.setHeaders(Headers.fromInput({ authorization: "Bearer header-secret-456" })),
  16. )
  17. const responsesLayer = (responses: ReadonlyArray<Response>) =>
  18. RequestExecutor.layer.pipe(
  19. Layer.provide(
  20. Layer.unwrap(
  21. Effect.gen(function* () {
  22. const cursor = yield* Ref.make(0)
  23. return Layer.succeed(
  24. HttpClient.HttpClient,
  25. HttpClient.make((request) =>
  26. Effect.gen(function* () {
  27. const index = yield* Ref.getAndUpdate(cursor, (value) => value + 1)
  28. return HttpClientResponse.fromWeb(request, responses[index] ?? responses[responses.length - 1])
  29. }),
  30. ),
  31. )
  32. }),
  33. ),
  34. ),
  35. )
  36. const countedResponsesLayer = (attempts: Ref.Ref<number>, responses: ReadonlyArray<Response>) =>
  37. RequestExecutor.layer.pipe(
  38. Layer.provide(
  39. Layer.unwrap(
  40. Effect.gen(function* () {
  41. const cursor = yield* Ref.make(0)
  42. return Layer.succeed(
  43. HttpClient.HttpClient,
  44. HttpClient.make((request) =>
  45. Effect.gen(function* () {
  46. yield* Ref.update(attempts, (value) => value + 1)
  47. const index = yield* Ref.getAndUpdate(cursor, (value) => value + 1)
  48. return HttpClientResponse.fromWeb(request, responses[index] ?? responses[responses.length - 1])
  49. }),
  50. ),
  51. )
  52. }),
  53. ),
  54. ),
  55. )
  56. const expectLLMError = (error: unknown) => {
  57. expect(error).toBeInstanceOf(LLMError)
  58. if (!(error instanceof LLMError)) throw new Error("expected LLMError")
  59. return error
  60. }
  61. const errorHttp = (error: LLMError) => ("http" in error.reason ? error.reason.http : undefined)
  62. describe("RequestExecutor", () => {
  63. it.effect("classifies context overflow responses", () =>
  64. Effect.gen(function* () {
  65. const executor = yield* RequestExecutor.Service
  66. const error = yield* executor.execute(request).pipe(Effect.flip)
  67. expectLLMError(error)
  68. expect(error.reason).toMatchObject({ _tag: "InvalidRequest", classification: "context-overflow" })
  69. }).pipe(
  70. Effect.provide(
  71. responsesLayer([
  72. new Response('{"error":{"code":"context_length_exceeded","message":"prompt too long"}}', {
  73. status: 400,
  74. }),
  75. ]),
  76. ),
  77. ),
  78. )
  79. it.effect("does not classify generic HTTP 413 payload errors as context overflow", () =>
  80. Effect.gen(function* () {
  81. const executor = yield* RequestExecutor.Service
  82. const error = yield* executor.execute(request).pipe(Effect.flip)
  83. expectLLMError(error)
  84. expect(error.reason).toMatchObject({ _tag: "InvalidRequest" })
  85. expect("classification" in error.reason ? error.reason.classification : undefined).toBeUndefined()
  86. }).pipe(Effect.provide(responsesLayer([new Response("request too large", { status: 413 })]))),
  87. )
  88. it.effect("does not classify ordinary invalid requests as context overflow", () =>
  89. Effect.gen(function* () {
  90. const executor = yield* RequestExecutor.Service
  91. const error = yield* executor.execute(request).pipe(Effect.flip)
  92. expectLLMError(error)
  93. expect(error.reason).toMatchObject({ _tag: "InvalidRequest" })
  94. expect("classification" in error.reason ? error.reason.classification : undefined).toBeUndefined()
  95. }).pipe(Effect.provide(responsesLayer([new Response("invalid parameter", { status: 400 })]))),
  96. )
  97. it.effect("returns redacted diagnostics for rate limits", () =>
  98. Effect.gen(function* () {
  99. const executor = yield* RequestExecutor.Service
  100. const error = yield* executor.execute(request).pipe(Effect.flip)
  101. expectLLMError(error)
  102. expect(error).toMatchObject({
  103. reason: {
  104. _tag: "RateLimit",
  105. retryAfterMs: 0,
  106. rateLimit: { retryAfterMs: 0 },
  107. http: {
  108. requestId: "req_123",
  109. request: {
  110. method: "POST",
  111. url: "https://provider.test/v1/chat?api_key=%3Credacted%3E&key=%3Credacted%3E&debug=1",
  112. headers: { authorization: "<redacted>", "x-safe": "visible" },
  113. },
  114. response: {
  115. status: 429,
  116. headers: {
  117. "retry-after-ms": "0",
  118. "x-request-id": "req_123",
  119. "x-api-key": "<redacted>",
  120. },
  121. },
  122. },
  123. },
  124. })
  125. expect(errorHttp(error)?.body).toBe("rate limited")
  126. }).pipe(
  127. Effect.provide(
  128. responsesLayer([
  129. new Response("rate limited", {
  130. status: 429,
  131. headers: { "retry-after-ms": "0", "x-request-id": "req_123", "x-api-key": "secret" },
  132. }),
  133. ]),
  134. ),
  135. ),
  136. )
  137. it.effect("honors current redacted header names in diagnostics", () =>
  138. Effect.gen(function* () {
  139. const executor = yield* RequestExecutor.Service
  140. const error = yield* executor.execute(request).pipe(Effect.flip)
  141. expectLLMError(error)
  142. expect(errorHttp(error)?.request.headers["x-safe"]).toBe("<redacted>")
  143. expect(errorHttp(error)?.response?.headers["x-safe"]).toBe("<redacted>")
  144. }).pipe(
  145. Effect.provide(responsesLayer([new Response("bad", { status: 400, headers: { "x-safe": "response-secret" } })])),
  146. Effect.provideService(Headers.CurrentRedactedNames, ["x-safe"]),
  147. ),
  148. )
  149. it.effect("extracts OpenAI-style rate-limit diagnostics", () =>
  150. Effect.gen(function* () {
  151. const executor = yield* RequestExecutor.Service
  152. const error = yield* executor.execute(request).pipe(Effect.flip)
  153. expectLLMError(error)
  154. expect(error.reason).toMatchObject({ _tag: "RateLimit" })
  155. expect(error.reason._tag === "RateLimit" ? error.reason.rateLimit : undefined).toEqual({
  156. retryAfterMs: 0,
  157. limit: { requests: "500", tokens: "30000" },
  158. remaining: { requests: "499", tokens: "29900" },
  159. reset: { requests: "1s", tokens: "10s" },
  160. })
  161. }).pipe(
  162. Effect.provide(
  163. responsesLayer([
  164. new Response("rate limited", {
  165. status: 429,
  166. headers: {
  167. "retry-after-ms": "0",
  168. "x-ratelimit-limit-requests": "500",
  169. "x-ratelimit-limit-tokens": "30000",
  170. "x-ratelimit-remaining-requests": "499",
  171. "x-ratelimit-remaining-tokens": "29900",
  172. "x-ratelimit-reset-requests": "1s",
  173. "x-ratelimit-reset-tokens": "10s",
  174. },
  175. }),
  176. ]),
  177. ),
  178. ),
  179. )
  180. it.effect("extracts Anthropic-style rate-limit diagnostics", () =>
  181. Effect.gen(function* () {
  182. const executor = yield* RequestExecutor.Service
  183. const error = yield* executor.execute(request).pipe(Effect.flip)
  184. expectLLMError(error)
  185. expect(error.reason).toMatchObject({ _tag: "ProviderInternal" })
  186. expect(errorHttp(error)?.rateLimit).toEqual({
  187. retryAfterMs: 0,
  188. limit: { requests: "100", "input-tokens": "10000" },
  189. remaining: { requests: "12", "input-tokens": "9000" },
  190. reset: { requests: "2026-05-06T12:00:00Z", "input-tokens": "2026-05-06T12:00:10Z" },
  191. })
  192. }).pipe(
  193. Effect.provide(
  194. responsesLayer([
  195. new Response("overloaded", {
  196. status: 529,
  197. headers: {
  198. "retry-after-ms": "0",
  199. "anthropic-ratelimit-requests-limit": "100",
  200. "anthropic-ratelimit-requests-remaining": "12",
  201. "anthropic-ratelimit-requests-reset": "2026-05-06T12:00:00Z",
  202. "anthropic-ratelimit-input-tokens-limit": "10000",
  203. "anthropic-ratelimit-input-tokens-remaining": "9000",
  204. "anthropic-ratelimit-input-tokens-reset": "2026-05-06T12:00:10Z",
  205. },
  206. }),
  207. ]),
  208. ),
  209. ),
  210. )
  211. it.effect("returns provider status failures without retrying", () =>
  212. Effect.gen(function* () {
  213. const attempts = yield* Ref.make(0)
  214. const error = yield* Effect.gen(function* () {
  215. const executor = yield* RequestExecutor.Service
  216. return yield* executor.execute(request).pipe(Effect.flip)
  217. }).pipe(
  218. Effect.provide(
  219. countedResponsesLayer(attempts, [
  220. new Response("busy", { status: 503, headers: { "retry-after-ms": "0" } }),
  221. new Response("ok", { status: 200 }),
  222. ]),
  223. ),
  224. )
  225. expectLLMError(error)
  226. expect(error.reason).toMatchObject({ _tag: "ProviderInternal", status: 503 })
  227. expect(yield* Ref.get(attempts)).toBe(1)
  228. }),
  229. )
  230. it.effect("marks 504 and 529 status responses as provider-internal", () =>
  231. Effect.gen(function* () {
  232. const failWith = (status: number) =>
  233. Effect.gen(function* () {
  234. const executor = yield* RequestExecutor.Service
  235. const error = yield* executor.execute(request).pipe(Effect.flip)
  236. expectLLMError(error)
  237. expect(error.reason).toMatchObject({ _tag: "ProviderInternal", status })
  238. }).pipe(
  239. Effect.provide(
  240. responsesLayer([
  241. new Response("provider failure", {
  242. status,
  243. headers: { "retry-after-ms": "0" },
  244. }),
  245. ]),
  246. ),
  247. )
  248. yield* failWith(504)
  249. yield* failWith(529)
  250. }),
  251. )
  252. it.effect("truncates large authentication error bodies", () =>
  253. Effect.gen(function* () {
  254. const executor = yield* RequestExecutor.Service
  255. const error = yield* executor.execute(request).pipe(Effect.flip)
  256. expectLLMError(error)
  257. expect(error.reason).toMatchObject({ _tag: "Authentication" })
  258. expect(errorHttp(error)?.bodyTruncated).toBe(true)
  259. expect(errorHttp(error)?.body).toHaveLength(16_384)
  260. }).pipe(
  261. Effect.provide(
  262. responsesLayer([
  263. new Response("x".repeat(20_000), { status: 401 }),
  264. new Response("should not retry", { status: 200 }),
  265. ]),
  266. ),
  267. ),
  268. )
  269. it.effect("redacts common secret fields in response bodies", () =>
  270. Effect.gen(function* () {
  271. const executor = yield* RequestExecutor.Service
  272. const error = yield* executor.execute(request).pipe(Effect.flip)
  273. expectLLMError(error)
  274. expect(errorHttp(error)?.body).toContain('"key":"<redacted>"')
  275. expect(errorHttp(error)?.body).toContain("api_key=<redacted>")
  276. expect(errorHttp(error)?.body).not.toContain("body-secret")
  277. expect(errorHttp(error)?.body).not.toContain("query-secret")
  278. }).pipe(
  279. Effect.provide(
  280. responsesLayer([
  281. new Response('{"error":{"message":"bad","key":"body-secret","detail":"api_key=query-secret"}}', {
  282. status: 400,
  283. }),
  284. ]),
  285. ),
  286. ),
  287. )
  288. it.effect("redacts echoed request secret values in response bodies", () =>
  289. Effect.gen(function* () {
  290. const executor = yield* RequestExecutor.Service
  291. const error = yield* executor.execute(secretRequest).pipe(Effect.flip)
  292. expectLLMError(error)
  293. expect(errorHttp(error)?.body).toContain("provider echoed <redacted>")
  294. expect(errorHttp(error)?.body).toContain("authorization <redacted>")
  295. expect(errorHttp(error)?.body).not.toContain("query-secret-123")
  296. expect(errorHttp(error)?.body).not.toContain("header-secret-456")
  297. }).pipe(
  298. Effect.provide(
  299. responsesLayer([
  300. new Response("provider echoed query-secret-123 and authorization header-secret-456", { status: 400 }),
  301. ]),
  302. ),
  303. ),
  304. )
  305. it.effect("does not re-execute after a successful response reaches stream parsing", () =>
  306. Effect.gen(function* () {
  307. const attempts = yield* Ref.make(0)
  308. const model = OpenAIChat.route
  309. .with({ endpoint: { baseURL: "https://api.openai.test/v1" } })
  310. .model({ id: "gpt-4o-mini" })
  311. const error = yield* LLMClient.generate(LLM.request({ model, prompt: "Say hello." })).pipe(
  312. Effect.provide(
  313. dynamicResponse((input) =>
  314. Ref.update(attempts, (value) => value + 1).pipe(
  315. Effect.as(
  316. input.respond(
  317. sseRaw(
  318. `data: ${JSON.stringify(deltaChunk({ role: "assistant", content: "Hello" }))}`,
  319. "data: not-json",
  320. ),
  321. { headers: { "content-type": "text/event-stream" } },
  322. ),
  323. ),
  324. ),
  325. ),
  326. ),
  327. Effect.flip,
  328. )
  329. expectLLMError(error)
  330. expect(error.reason).toMatchObject({ _tag: "InvalidProviderOutput" })
  331. expect(yield* Ref.get(attempts)).toBe(1)
  332. }),
  333. )
  334. })