llm-retry.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { StreamFn } from "@earendil-works/pi-agent-core";
  3. import type {
  4. AssistantMessage,
  5. AssistantMessageEvent,
  6. AssistantMessageEventStream,
  7. Context,
  8. Model,
  9. } from "@earendil-works/pi-ai";
  10. import { LLM_ERROR_CODES } from "@mavis/shared/llm-error-classifier";
  11. import {
  12. DEFAULT_LLM_RETRY_POLICY,
  13. LLM_RETRY_REQUEST_SETTLED_OBSERVER,
  14. withLLMRetry,
  15. type LLMCallSettledEvent,
  16. type LLMRequestSettledEvent,
  17. type LLMRetryEvent,
  18. } from "../../../src/pi-turn-runner/llm-retry.js";
  19. function fakeModel(provider = "fake-provider"): Model<any> {
  20. return {
  21. id: "fake-model",
  22. name: "fake-model",
  23. api: "test-messages",
  24. provider,
  25. baseUrl: "https://example.invalid",
  26. reasoning: false,
  27. input: ["text"],
  28. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  29. contextWindow: 200_000,
  30. maxTokens: 8_192,
  31. } as Model<any>;
  32. }
  33. const CONTEXT: Context = { messages: [] };
  34. function assistant(
  35. stopReason: AssistantMessage["stopReason"],
  36. content: AssistantMessage["content"],
  37. errorMessage?: string,
  38. usage?: Partial<AssistantMessage["usage"]>,
  39. ): AssistantMessage {
  40. return {
  41. role: "assistant",
  42. content,
  43. api: "test-messages",
  44. provider: "fake-provider",
  45. model: "fake-model",
  46. usage: {
  47. input: 0,
  48. output: 0,
  49. cacheRead: 0,
  50. cacheWrite: 0,
  51. totalTokens: 0,
  52. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  53. ...(usage ?? {}),
  54. },
  55. stopReason,
  56. ...(errorMessage ? { errorMessage } : {}),
  57. timestamp: 0,
  58. } as AssistantMessage;
  59. }
  60. function stream(
  61. events: AssistantMessageEvent[],
  62. final: AssistantMessage,
  63. ): AssistantMessageEventStream {
  64. return {
  65. [Symbol.asyncIterator]() {
  66. let index = 0;
  67. return {
  68. async next() {
  69. if (index < events.length)
  70. return { value: events[index++], done: false };
  71. return { value: undefined, done: true };
  72. },
  73. } as AsyncIterableIterator<AssistantMessageEvent>;
  74. },
  75. async result() {
  76. return final;
  77. },
  78. } as unknown as AssistantMessageEventStream;
  79. }
  80. function successStream(text: string): AssistantMessageEventStream {
  81. const empty = assistant("stop", []);
  82. const partial = assistant("stop", [{ type: "text", text }]);
  83. const final = assistant("stop", [{ type: "text", text }]);
  84. return stream(
  85. [
  86. { type: "start", partial: empty },
  87. { type: "text_start", contentIndex: 0, partial: empty },
  88. { type: "text_delta", contentIndex: 0, delta: text, partial },
  89. { type: "text_end", contentIndex: 0, content: text, partial },
  90. { type: "done", reason: "stop", message: final },
  91. ],
  92. final,
  93. );
  94. }
  95. function errorStream(
  96. message: string,
  97. partialText = "",
  98. usage?: Partial<AssistantMessage["usage"]>,
  99. ): AssistantMessageEventStream {
  100. const empty = assistant("error", []);
  101. const content = partialText
  102. ? [{ type: "text" as const, text: partialText }]
  103. : [];
  104. const partial = assistant("error", content);
  105. const final = assistant("error", content, message, usage);
  106. return stream(
  107. [
  108. { type: "start", partial: empty },
  109. ...(partialText
  110. ? ([
  111. { type: "text_start", contentIndex: 0, partial: empty },
  112. {
  113. type: "text_delta",
  114. contentIndex: 0,
  115. delta: partialText,
  116. partial,
  117. },
  118. ] satisfies AssistantMessageEvent[])
  119. : []),
  120. { type: "error", reason: "error", error: final },
  121. ],
  122. final,
  123. );
  124. }
  125. async function collectEvents(
  126. value: Awaited<ReturnType<StreamFn>>,
  127. ): Promise<AssistantMessageEvent[]> {
  128. const events: AssistantMessageEvent[] = [];
  129. for await (const event of value) events.push(event);
  130. return events;
  131. }
  132. function retryOptions(overrides: Record<string, unknown> = {}) {
  133. return {
  134. sessionId: "session-1",
  135. turnId: "turn-1",
  136. scope: "agent" as const,
  137. generateCallId: () => "call-1",
  138. random: () => 0,
  139. nowMs: () => 1_000,
  140. sleep: vi.fn(async () => {}),
  141. ...overrides,
  142. };
  143. }
  144. describe("withLLMRetry", () => {
  145. it("observes each physical provider request, including a retry that fails first", async () => {
  146. let attempts = 0;
  147. const physical: LLMRequestSettledEvent[] = [];
  148. const inner = (async () => {
  149. attempts += 1;
  150. if (attempts === 1) {
  151. return errorStream("[Error] 429 Too Many Requests", "", {
  152. input: 11,
  153. output: 2,
  154. cacheRead: Number.NaN,
  155. cacheWrite: 4,
  156. });
  157. }
  158. const final = assistant(
  159. "stop",
  160. [{ type: "text", text: "ok" }],
  161. undefined,
  162. {
  163. input: 17,
  164. output: 3,
  165. cacheRead: 5,
  166. cacheWrite: 7,
  167. },
  168. );
  169. return stream([{ type: "done", reason: "stop", message: final }], final);
  170. }) as StreamFn;
  171. const wrapped = withLLMRetry(inner, retryOptions());
  172. const result = await wrapped(fakeModel(), CONTEXT, {
  173. [LLM_RETRY_REQUEST_SETTLED_OBSERVER]: (event: LLMRequestSettledEvent) => {
  174. physical.push(event);
  175. },
  176. });
  177. await collectEvents(result);
  178. expect(physical).toEqual([
  179. {
  180. requestAttempt: 1,
  181. outcome: "error",
  182. usage: { input: 11, output: 2, cacheRead: 0, cacheWrite: 4 },
  183. usageComplete: false,
  184. },
  185. {
  186. requestAttempt: 2,
  187. outcome: "success",
  188. usage: { input: 17, output: 3, cacheRead: 5, cacheWrite: 7 },
  189. usageComplete: true,
  190. },
  191. ]);
  192. });
  193. it("disables provider-native retries so the framework owns the request budget", async () => {
  194. const maxRetries: Array<number | undefined> = [];
  195. const inner = ((_model, _context, options) => {
  196. maxRetries.push(options?.maxRetries);
  197. return successStream("ok");
  198. }) as StreamFn;
  199. const wrapped = withLLMRetry(inner, retryOptions());
  200. const result = await wrapped(fakeModel(), CONTEXT, { maxRetries: 9 });
  201. await collectEvents(result);
  202. expect(maxRetries).toEqual([0]);
  203. });
  204. it("discards a pre-commit 429 attempt and exposes only the recovered stream", async () => {
  205. let attempts = 0;
  206. const observed: LLMRetryEvent[] = [];
  207. const settled: LLMCallSettledEvent[] = [];
  208. const inner = (async () => {
  209. attempts += 1;
  210. return attempts === 1
  211. ? errorStream("[Error] 429 Too Many Requests")
  212. : successStream("ok");
  213. }) as StreamFn;
  214. const sleep = vi.fn(async () => {});
  215. const wrapped = withLLMRetry(
  216. inner,
  217. retryOptions({
  218. sleep,
  219. observer: (event: LLMRetryEvent) => observed.push(event),
  220. onCallSettled: (event: LLMCallSettledEvent) => settled.push(event),
  221. }),
  222. );
  223. const result = await wrapped(fakeModel(), CONTEXT, {});
  224. const events = await collectEvents(result);
  225. expect(attempts).toBe(2);
  226. expect(events.map((event) => event.type)).toEqual([
  227. "start",
  228. "text_start",
  229. "text_delta",
  230. "text_end",
  231. "done",
  232. ]);
  233. expect(sleep).toHaveBeenCalledWith(500, undefined);
  234. expect(observed).toMatchObject([
  235. {
  236. callId: "call-1",
  237. status: "waiting",
  238. retryAttempt: 1,
  239. maxRetries: 5,
  240. requestAttempt: 2,
  241. delayMs: 500,
  242. error: { reason: "rate_limited" },
  243. },
  244. {
  245. callId: "call-1",
  246. status: "recovered",
  247. retryAttempt: 1,
  248. maxRetries: 5,
  249. requestAttempt: 2,
  250. },
  251. ]);
  252. await result.result();
  253. expect(settled).toMatchObject([
  254. {
  255. sessionId: "session-1",
  256. turnId: "turn-1",
  257. callId: "call-1",
  258. scope: "agent",
  259. provider: "fake-provider",
  260. model: "fake-model",
  261. final: { outcome: "success", errorKind: "none" },
  262. retryTriggered: true,
  263. retryReason: "rate_limited",
  264. requestAttempts: 2,
  265. // Successful calls carry the raw provider buckets; this fixture reports
  266. // an all-zero usage.
  267. usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  268. },
  269. ]);
  270. });
  271. it("settles a successful logical Call with only its normalized tool identities", async () => {
  272. const final = assistant("toolUse", [
  273. {
  274. type: "toolCall",
  275. id: "tool-1",
  276. name: "read",
  277. arguments: { path: "README.md" },
  278. },
  279. ]);
  280. const settled: LLMCallSettledEvent[] = [];
  281. const wrapped = withLLMRetry(
  282. (async () =>
  283. stream(
  284. [{ type: "done", reason: "toolUse", message: final }],
  285. final,
  286. )) as StreamFn,
  287. retryOptions({
  288. onCallSettled: (event: LLMCallSettledEvent) => settled.push(event),
  289. }),
  290. );
  291. await (await wrapped(fakeModel(), CONTEXT, {})).result();
  292. expect(settled[0]?.expectedTools).toEqual([
  293. { toolCallId: "tool-1", toolName: "read" },
  294. ]);
  295. expect(settled[0]).not.toHaveProperty("assistantMessage");
  296. expect(JSON.stringify(settled[0])).not.toContain("README.md");
  297. });
  298. it("does not count a committed retry stream as recovered when its final result fails", async () => {
  299. let attempts = 0;
  300. const observed: LLMRetryEvent[] = [];
  301. const settled: LLMCallSettledEvent[] = [];
  302. const inner = (async () => {
  303. attempts += 1;
  304. return attempts === 1
  305. ? errorStream("[Error] 429 Too Many Requests")
  306. : errorStream("ECONNRESET", "partial");
  307. }) as StreamFn;
  308. const wrapped = withLLMRetry(
  309. inner,
  310. retryOptions({
  311. observer: (event: LLMRetryEvent) => observed.push(event),
  312. onCallSettled: (event: LLMCallSettledEvent) => settled.push(event),
  313. }),
  314. );
  315. const result = await wrapped(fakeModel(), CONTEXT, {});
  316. await collectEvents(result);
  317. await result.result();
  318. expect(observed.map((event) => event.status)).toEqual([
  319. "waiting",
  320. "recovered",
  321. ]);
  322. expect(settled).toMatchObject([
  323. {
  324. final: { outcome: "error", errorKind: "network" },
  325. retryTriggered: true,
  326. retryReason: "rate_limited",
  327. requestAttempts: 2,
  328. },
  329. ]);
  330. });
  331. it.each([2056, 2067])(
  332. "never retries Token Plan exhaustion status %i even when the outer status looks transient",
  333. async (statusCode) => {
  334. let attempts = 0;
  335. const observed: LLMRetryEvent[] = [];
  336. const settled: LLMCallSettledEvent[] = [];
  337. const inner = (async () => {
  338. attempts += 1;
  339. return errorStream(
  340. `[Error] 429 {"status_code":${statusCode},"status_msg":"plan exhausted"}`,
  341. );
  342. }) as StreamFn;
  343. const wrapped = withLLMRetry(
  344. inner,
  345. retryOptions({
  346. observer: (event: LLMRetryEvent) => observed.push(event),
  347. onCallSettled: (event: LLMCallSettledEvent) => settled.push(event),
  348. }),
  349. );
  350. const result = await wrapped(fakeModel(), CONTEXT, {});
  351. const events = await collectEvents(result);
  352. expect(attempts).toBe(1);
  353. expect(events.at(-1)?.type).toBe("error");
  354. expect(observed).toEqual([]);
  355. await result.result();
  356. expect(settled).toMatchObject([
  357. {
  358. final: { outcome: "error", errorKind: "usage_limit" },
  359. retryTriggered: false,
  360. requestAttempts: 1,
  361. },
  362. ]);
  363. },
  364. );
  365. it("does not report recovered when a retry ends in a non-retryable quota error", async () => {
  366. let attempts = 0;
  367. const observed: LLMRetryEvent[] = [];
  368. const settled: LLMCallSettledEvent[] = [];
  369. const inner = (async () => {
  370. attempts += 1;
  371. return attempts === 1
  372. ? errorStream("[Error] 429 Too Many Requests")
  373. : errorStream(
  374. '[Error] 500 {"status_code":2056,"status_msg":"plan exhausted"}',
  375. );
  376. }) as StreamFn;
  377. const wrapped = withLLMRetry(
  378. inner,
  379. retryOptions({
  380. observer: (event: LLMRetryEvent) => observed.push(event),
  381. onCallSettled: (event: LLMCallSettledEvent) => settled.push(event),
  382. }),
  383. );
  384. const result = await wrapped(fakeModel(), CONTEXT, {});
  385. await collectEvents(result);
  386. expect(attempts).toBe(2);
  387. expect(observed.map((event) => event.status)).toEqual([
  388. "waiting",
  389. "exhausted",
  390. ]);
  391. expect(observed.at(-1)?.error).toEqual({
  392. reason: "usage_limit",
  393. code: LLM_ERROR_CODES.USAGE_LIMIT_EXCEEDED,
  394. message: "LLM usage limit reached",
  395. });
  396. await expect(result.result()).resolves.toMatchObject({
  397. errorMessage:
  398. '[Error] 500 {"status_code":2056,"status_msg":"plan exhausted"}',
  399. });
  400. expect(settled).toMatchObject([
  401. {
  402. final: { outcome: "error", errorKind: "usage_limit" },
  403. retryTriggered: true,
  404. retryReason: "rate_limited",
  405. requestAttempts: 2,
  406. },
  407. ]);
  408. });
  409. it.each([
  410. {
  411. finalError: "[Error] 401 invalid api key",
  412. expectedReason: "auth",
  413. expectedCode: LLM_ERROR_CODES.LLM_AUTH_ERROR,
  414. expectedMessage: "LLM provider authentication failed",
  415. },
  416. {
  417. finalError: "[Error] 503 upstream unavailable",
  418. expectedReason: "server_error",
  419. expectedCode: LLM_ERROR_CODES.LLM_UPSTREAM_ERROR,
  420. expectedMessage: "LLM provider request failed",
  421. },
  422. ])(
  423. "attributes an exhausted retry to the final $expectedReason failure",
  424. async ({ finalError, expectedReason, expectedCode, expectedMessage }) => {
  425. let attempts = 0;
  426. const observed: LLMRetryEvent[] = [];
  427. const settled: LLMCallSettledEvent[] = [];
  428. const inner = (async () => {
  429. attempts += 1;
  430. return attempts === 1
  431. ? errorStream("[Error] 429 Too Many Requests")
  432. : errorStream(finalError);
  433. }) as StreamFn;
  434. const wrapped = withLLMRetry(
  435. inner,
  436. retryOptions({
  437. observer: (event: LLMRetryEvent) => observed.push(event),
  438. onCallSettled: (event: LLMCallSettledEvent) => settled.push(event),
  439. }),
  440. );
  441. const result = await wrapped(fakeModel(), CONTEXT, {});
  442. await collectEvents(result);
  443. expect(attempts).toBe(2);
  444. expect(observed.at(-1)).toMatchObject({
  445. status: "exhausted",
  446. error: {
  447. reason: expectedReason,
  448. code: expectedCode,
  449. message: expectedMessage,
  450. },
  451. });
  452. await expect(result.result()).resolves.toMatchObject({
  453. errorMessage: finalError,
  454. });
  455. expect(settled).toMatchObject([
  456. {
  457. final: { outcome: "error", errorKind: expectedReason },
  458. retryTriggered: true,
  459. retryReason: "rate_limited",
  460. requestAttempts: 2,
  461. },
  462. ]);
  463. },
  464. );
  465. it("retries a network error thrown before a stream is returned", async () => {
  466. let attempts = 0;
  467. const inner = (async () => {
  468. attempts += 1;
  469. if (attempts === 1)
  470. throw Object.assign(new Error("socket reset"), { code: "ECONNRESET" });
  471. return successStream("ok");
  472. }) as StreamFn;
  473. const wrapped = withLLMRetry(inner, retryOptions());
  474. const result = await wrapped(fakeModel(), CONTEXT, {});
  475. expect((await collectEvents(result)).at(-1)?.type).toBe("done");
  476. expect(attempts).toBe(2);
  477. });
  478. it("uses five retries by default and emits exhausted after the sixth request", async () => {
  479. let attempts = 0;
  480. const observed: LLMRetryEvent[] = [];
  481. const settled: LLMCallSettledEvent[] = [];
  482. const sleep = vi.fn(async () => {});
  483. const inner = (async () => {
  484. attempts += 1;
  485. return errorStream("[Error] 529 overloaded");
  486. }) as StreamFn;
  487. const wrapped = withLLMRetry(
  488. inner,
  489. retryOptions({
  490. sleep,
  491. observer: (event: LLMRetryEvent) => observed.push(event),
  492. onCallSettled: (event: LLMCallSettledEvent) => settled.push(event),
  493. }),
  494. );
  495. const result = await wrapped(fakeModel(), CONTEXT, {});
  496. await collectEvents(result);
  497. expect(DEFAULT_LLM_RETRY_POLICY.maxRetries).toBe(5);
  498. expect(attempts).toBe(6);
  499. expect(sleep.mock.calls.map(([delayMs]) => delayMs)).toEqual([
  500. 500, 1_000, 2_000, 4_000, 8_000,
  501. ]);
  502. expect(observed.filter((event) => event.status === "waiting")).toHaveLength(
  503. 5,
  504. );
  505. expect(observed.at(-1)).toMatchObject({
  506. status: "exhausted",
  507. retryAttempt: 5,
  508. maxRetries: 5,
  509. requestAttempt: 6,
  510. error: { reason: "overloaded" },
  511. });
  512. await result.result();
  513. expect(settled).toMatchObject([
  514. {
  515. final: { outcome: "error", errorKind: "overloaded" },
  516. retryTriggered: true,
  517. retryReason: "overloaded",
  518. requestAttempts: 6,
  519. },
  520. ]);
  521. });
  522. it("limits BYOK errors to five retries regardless of error classification", async () => {
  523. let attempts = 0;
  524. const inner = (async () => {
  525. attempts += 1;
  526. return errorStream("[Error] 401 invalid api key");
  527. }) as StreamFn;
  528. const wrapped = withLLMRetry(
  529. inner,
  530. retryOptions({ sleep: vi.fn(async () => {}) }),
  531. );
  532. const result = await wrapped(fakeModel("minimax_api"), CONTEXT, {});
  533. await collectEvents(result);
  534. expect(attempts).toBe(6);
  535. });
  536. it("keeps the exhausted attempt open when returning its terminal failure stream", async () => {
  537. const attemptReturns: Array<ReturnType<typeof vi.fn>> = [];
  538. const inner = (async () => {
  539. const failed = errorStream("[Error] 529 overloaded");
  540. const iterator = failed[Symbol.asyncIterator]();
  541. let cancelled = false;
  542. const closeAttempt = vi.fn(async () => {
  543. cancelled = true;
  544. return { value: undefined, done: true as const };
  545. });
  546. attemptReturns.push(closeAttempt);
  547. return {
  548. [Symbol.asyncIterator]() {
  549. return { next: () => iterator.next(), return: closeAttempt };
  550. },
  551. async result() {
  552. if (cancelled) throw new Error("provider stream was cancelled");
  553. return failed.result();
  554. },
  555. } as unknown as AssistantMessageEventStream;
  556. }) as StreamFn;
  557. const wrapped = withLLMRetry(
  558. inner,
  559. retryOptions({ policy: { maxRetries: 1 }, sleep: vi.fn(async () => {}) }),
  560. );
  561. const result = await wrapped(fakeModel(), CONTEXT, {});
  562. const events = await collectEvents(result);
  563. expect(events.at(-1)?.type).toBe("error");
  564. await expect(result.result()).resolves.toMatchObject({
  565. stopReason: "error",
  566. errorMessage: "[Error] 529 overloaded",
  567. });
  568. expect(attemptReturns).toHaveLength(2);
  569. expect(attemptReturns[0]).toHaveBeenCalledOnce();
  570. expect(attemptReturns[1]).not.toHaveBeenCalled();
  571. });
  572. it("settles result-only calls when every attempt disconnects before the first token", async () => {
  573. const disconnect = Object.assign(
  574. new Error("socket reset before first token"),
  575. {
  576. code: "ECONNRESET",
  577. },
  578. );
  579. const settled: LLMCallSettledEvent[] = [];
  580. let attempts = 0;
  581. const inner = (async () => {
  582. attempts += 1;
  583. return {
  584. [Symbol.asyncIterator]() {
  585. return {
  586. async next(): Promise<IteratorResult<AssistantMessageEvent>> {
  587. throw disconnect;
  588. },
  589. };
  590. },
  591. result: () => new Promise<AssistantMessage>(() => {}),
  592. } as unknown as AssistantMessageEventStream;
  593. }) as StreamFn;
  594. const wrapped = withLLMRetry(
  595. inner,
  596. retryOptions({
  597. policy: { maxRetries: 1 },
  598. sleep: vi.fn(async () => {}),
  599. onCallSettled: (event: LLMCallSettledEvent) => settled.push(event),
  600. }),
  601. );
  602. const result = await wrapped(fakeModel(), CONTEXT, {});
  603. const timeout = Symbol("result timeout");
  604. const outcome = await Promise.race([
  605. result.result().catch((error: unknown) => error),
  606. new Promise<symbol>((resolve) => setTimeout(() => resolve(timeout), 100)),
  607. ]);
  608. expect(attempts).toBe(2);
  609. expect(outcome).toBe(disconnect);
  610. expect(settled).toMatchObject([
  611. {
  612. final: { outcome: "error", errorKind: "network" },
  613. retryTriggered: true,
  614. retryReason: "network",
  615. requestAttempts: 2,
  616. },
  617. ]);
  618. });
  619. it("stops before a backoff that would exceed the retry elapsed-time budget", async () => {
  620. let attempts = 0;
  621. const observed: LLMRetryEvent[] = [];
  622. const sleep = vi.fn(async () => {});
  623. const inner = (async () => {
  624. attempts += 1;
  625. return errorStream("[Error] 429 Too Many Requests");
  626. }) as StreamFn;
  627. const wrapped = withLLMRetry(
  628. inner,
  629. retryOptions({
  630. sleep,
  631. observer: (event: LLMRetryEvent) => observed.push(event),
  632. policy: { maxRetryElapsedMs: 499 },
  633. }),
  634. );
  635. const result = await wrapped(fakeModel(), CONTEXT, {});
  636. await collectEvents(result);
  637. expect(attempts).toBe(1);
  638. expect(sleep).not.toHaveBeenCalled();
  639. expect(observed).toMatchObject([
  640. { status: "exhausted", retryAttempt: 0, requestAttempt: 1 },
  641. ]);
  642. });
  643. it("initiates cleanup for a discarded attempt before the next provider request", async () => {
  644. let attempts = 0;
  645. const discardedReturn = vi.fn(async () => ({
  646. value: undefined,
  647. done: true as const,
  648. }));
  649. const inner = (async () => {
  650. attempts += 1;
  651. if (attempts > 1) return successStream("ok");
  652. const failed = errorStream("[Error] 429 Too Many Requests");
  653. return {
  654. [Symbol.asyncIterator]() {
  655. const iterator = failed[Symbol.asyncIterator]();
  656. return { next: () => iterator.next(), return: discardedReturn };
  657. },
  658. result: () => failed.result(),
  659. } as unknown as AssistantMessageEventStream;
  660. }) as StreamFn;
  661. const wrapped = withLLMRetry(inner, retryOptions());
  662. const result = await wrapped(fakeModel(), CONTEXT, {});
  663. await collectEvents(result);
  664. expect(discardedReturn).toHaveBeenCalledOnce();
  665. expect(attempts).toBe(2);
  666. });
  667. it("does not retry a disconnect after a visible text delta has committed", async () => {
  668. let attempts = 0;
  669. const observed: LLMRetryEvent[] = [];
  670. const inner = (async () => {
  671. attempts += 1;
  672. return errorStream("ECONNRESET", "partial");
  673. }) as StreamFn;
  674. const wrapped = withLLMRetry(
  675. inner,
  676. retryOptions({
  677. observer: (event: LLMRetryEvent) => observed.push(event),
  678. }),
  679. );
  680. const result = await wrapped(fakeModel(), CONTEXT, {});
  681. const events = await collectEvents(result);
  682. expect(attempts).toBe(1);
  683. expect(events.some((event) => event.type === "text_delta")).toBe(true);
  684. expect(events.at(-1)?.type).toBe("error");
  685. expect(observed).toEqual([]);
  686. });
  687. it("commits BYOK streaming after visible output in every host composition", async () => {
  688. let attempts = 0;
  689. const observed: LLMRetryEvent[] = [];
  690. const inner = (async () => {
  691. attempts += 1;
  692. return errorStream("[Error] 401 invalid api key", "partial");
  693. }) as StreamFn;
  694. const wrapped = withLLMRetry(
  695. inner,
  696. retryOptions({
  697. observer: (event: LLMRetryEvent) => observed.push(event),
  698. sleep: vi.fn(async () => {}),
  699. }),
  700. );
  701. const result = await wrapped(
  702. fakeModel("custom_provider:work"),
  703. CONTEXT,
  704. {},
  705. );
  706. const events = await collectEvents(result);
  707. expect(attempts).toBe(1);
  708. expect(events.some((event) => event.type === "text_delta")).toBe(true);
  709. expect(events.at(-1)?.type).toBe("error");
  710. expect(observed).toEqual([]);
  711. });
  712. it("retries a BYOK provider stream that ended without any message event", async () => {
  713. let attempts = 0;
  714. const observed: LLMRetryEvent[] = [];
  715. const inner = (async () => {
  716. attempts += 1;
  717. return attempts === 1
  718. ? errorStream(
  719. "Provider stream ended without any message events (rawEventCount=0; messageEventCount=0; firstEventAtMs=none; lastEventAtMs=none; eofAtMs=61000)",
  720. )
  721. : successStream("recovered");
  722. }) as StreamFn;
  723. const wrapped = withLLMRetry(
  724. inner,
  725. retryOptions({
  726. observer: (event: LLMRetryEvent) => observed.push(event),
  727. sleep: vi.fn(async () => {}),
  728. }),
  729. );
  730. const result = await wrapped(
  731. fakeModel("custom_provider:byok-gateway"),
  732. CONTEXT,
  733. {},
  734. );
  735. const events = await collectEvents(result);
  736. expect(attempts).toBe(2);
  737. expect(events.at(-1)?.type).toBe("done");
  738. expect(events.some((event) => event.type === "error")).toBe(false);
  739. expect((await result.result()).stopReason).toBe("stop");
  740. expect(observed).toMatchObject([
  741. {
  742. status: "waiting",
  743. retryAttempt: 1,
  744. requestAttempt: 2,
  745. error: { reason: "network" },
  746. },
  747. { status: "recovered", retryAttempt: 1, requestAttempt: 2 },
  748. ]);
  749. });
  750. it("returns a BYOK stream before the provider finishes after its first visible delta", async () => {
  751. const empty = assistant("error", []);
  752. const partial = assistant("error", [
  753. { type: "thinking", thinking: "live" },
  754. ]);
  755. const final = assistant(
  756. "error",
  757. [{ type: "thinking", thinking: "live" }],
  758. "late disconnect",
  759. );
  760. let releaseTail = () => undefined;
  761. const tail = new Promise<void>((resolve) => {
  762. releaseTail = resolve;
  763. });
  764. let attempts = 0;
  765. const inner = (async () => {
  766. attempts += 1;
  767. let index = 0;
  768. return {
  769. [Symbol.asyncIterator]() {
  770. return {
  771. async next(): Promise<IteratorResult<AssistantMessageEvent>> {
  772. index += 1;
  773. if (index === 1)
  774. return {
  775. value: { type: "start", partial: empty },
  776. done: false,
  777. };
  778. if (index === 2) {
  779. return {
  780. value: {
  781. type: "thinking_delta",
  782. contentIndex: 0,
  783. delta: "live",
  784. partial,
  785. },
  786. done: false,
  787. };
  788. }
  789. await tail;
  790. if (index === 3) {
  791. return {
  792. value: { type: "error", reason: "error", error: final },
  793. done: false,
  794. };
  795. }
  796. return { value: undefined, done: true };
  797. },
  798. };
  799. },
  800. async result() {
  801. await tail;
  802. return final;
  803. },
  804. } as AssistantMessageEventStream;
  805. }) as StreamFn;
  806. const order: string[] = [];
  807. const wrapped = withLLMRetry(
  808. inner,
  809. retryOptions({ sleep: vi.fn(async () => {}) }),
  810. );
  811. const committed = wrapped(
  812. fakeModel("custom_provider:work"),
  813. CONTEXT,
  814. {},
  815. ).then((result) => {
  816. order.push("committed");
  817. return result;
  818. });
  819. setTimeout(() => {
  820. order.push("tail");
  821. releaseTail();
  822. }, 0);
  823. const result = await committed;
  824. expect(order[0]).toBe("committed");
  825. expect(
  826. (await collectEvents(result)).some(
  827. (event) => event.type === "thinking_delta",
  828. ),
  829. ).toBe(true);
  830. expect(attempts).toBe(1);
  831. });
  832. it("honors a bounded Retry-After response header", async () => {
  833. let attempts = 0;
  834. const sleep = vi.fn(async () => {});
  835. const inner = (async (model, _context, options) => {
  836. attempts += 1;
  837. if (attempts === 1) {
  838. await options?.onResponse?.(
  839. { status: 429, headers: { "retry-after": "300" } },
  840. model,
  841. );
  842. return errorStream("provider throttled");
  843. }
  844. return successStream("ok");
  845. }) as StreamFn;
  846. const wrapped = withLLMRetry(inner, retryOptions({ sleep }));
  847. const result = await wrapped(fakeModel(), CONTEXT, {});
  848. await collectEvents(result);
  849. expect(sleep).toHaveBeenCalledWith(30_000, undefined);
  850. });
  851. it("cancels an in-flight backoff without starting another request", async () => {
  852. const controller = new AbortController();
  853. let attempts = 0;
  854. const observed: LLMRetryEvent[] = [];
  855. const settled: LLMCallSettledEvent[] = [];
  856. const sleep = vi.fn(
  857. async (_delayMs: number, signal?: AbortSignal) =>
  858. new Promise<void>((_resolve, reject) => {
  859. signal?.addEventListener(
  860. "abort",
  861. () => reject(new Error("sleep aborted")),
  862. { once: true },
  863. );
  864. }),
  865. );
  866. const inner = (async () => {
  867. attempts += 1;
  868. return errorStream("[Error] 429 Too Many Requests");
  869. }) as StreamFn;
  870. const wrapped = withLLMRetry(
  871. inner,
  872. retryOptions({
  873. sleep,
  874. observer: (event: LLMRetryEvent) => observed.push(event),
  875. onCallSettled: (event: LLMCallSettledEvent) => settled.push(event),
  876. }),
  877. );
  878. const pending = wrapped(fakeModel(), CONTEXT, {
  879. signal: controller.signal,
  880. });
  881. await vi.waitFor(() => expect(sleep).toHaveBeenCalledOnce());
  882. controller.abort("user_stop");
  883. await expect(pending).rejects.toThrow("sleep aborted");
  884. expect(attempts).toBe(1);
  885. expect(observed.at(-1)).toMatchObject({
  886. status: "cancelled",
  887. retryAttempt: 1,
  888. requestAttempt: 2,
  889. });
  890. expect(settled).toMatchObject([
  891. {
  892. final: { outcome: "abort", errorKind: "abort" },
  893. retryTriggered: true,
  894. retryReason: "rate_limited",
  895. requestAttempts: 1,
  896. },
  897. ]);
  898. });
  899. it("reports cancellation when the user aborts an active retry attempt", async () => {
  900. const controller = new AbortController();
  901. let attempts = 0;
  902. const observed: LLMRetryEvent[] = [];
  903. const inner = (async () => {
  904. attempts += 1;
  905. if (attempts === 1) return errorStream("[Error] 429 Too Many Requests");
  906. controller.abort("user_stop");
  907. throw new DOMException("The operation was aborted", "AbortError");
  908. }) as StreamFn;
  909. const wrapped = withLLMRetry(
  910. inner,
  911. retryOptions({
  912. observer: (event: LLMRetryEvent) => observed.push(event),
  913. }),
  914. );
  915. await expect(
  916. wrapped(fakeModel(), CONTEXT, { signal: controller.signal }),
  917. ).rejects.toThrow("aborted");
  918. expect(attempts).toBe(2);
  919. expect(observed.map((event) => event.status)).toEqual([
  920. "waiting",
  921. "cancelled",
  922. ]);
  923. });
  924. });