runner-empty-delta-retry.test.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. runWithModelInvocationContext,
  4. type ModelNetworkStatusEvent,
  5. type ModelStreamEvent,
  6. } from "@zcode/contracts";
  7. import {
  8. createRegistryModelConfig,
  9. createRegistryProviderConfig,
  10. parseModelConfig,
  11. parseProviderConfig,
  12. } from "@zcode/provider";
  13. import { ProviderBusinessError } from "../src/model/model-execution.js";
  14. import { AiSdkModelAdapter, type AiSdkModelRuntime } from "../src/model/runner.js";
  15. import { createTestModelProperties } from "./test-model-format.js";
  16. const SIGNATURE = "opaque-signature\nbytes ";
  17. const STREAM_IDLE_TIMEOUT_MS = 5;
  18. const MAX_ATTEMPTS = 2;
  19. const MAX_OUTPUT_TOKENS = 32_000;
  20. type Chunk = Record<string, unknown>;
  21. type Failure = "sse-error" | "network-reset" | "idle-timeout" | "empty-eof" | "auth" | "cancel";
  22. type Prelude = "signature" | "empty-text";
  23. function prelude(kind: Prelude): Chunk[] {
  24. return kind === "signature"
  25. ? [
  26. { type: "start" },
  27. { type: "reasoning-start", id: "reasoning-failed" },
  28. {
  29. type: "reasoning-delta",
  30. id: "reasoning-failed",
  31. text: "",
  32. providerMetadata: { anthropic: { signature: SIGNATURE } },
  33. },
  34. { type: "reasoning-end", id: "reasoning-failed" },
  35. ]
  36. : [
  37. { type: "start" },
  38. { type: "text-start", id: "text-failed" },
  39. { type: "text-delta", id: "text-failed", text: "" },
  40. { type: "text-end", id: "text-failed" },
  41. ];
  42. }
  43. const TOOL_INPUT: Chunk[] = [
  44. { type: "tool-input-start", id: "call-failed", toolName: "Write" },
  45. { type: "tool-input-delta", id: "call-failed", delta: '{"file_path":"test.txt"' },
  46. ];
  47. const COMPLETE_TOOL: Chunk[] = [
  48. { type: "tool-input-start", id: "call-complete", toolName: "Write" },
  49. { type: "tool-input-end", id: "call-complete" },
  50. {
  51. type: "tool-call",
  52. toolCallId: "call-complete",
  53. toolName: "Write",
  54. input: { file_path: "test.txt", content: "hello" },
  55. },
  56. ];
  57. function finish(finishReason = "stop"): Chunk {
  58. return {
  59. type: "finish",
  60. finishReason,
  61. totalUsage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
  62. };
  63. }
  64. function harness(options: {
  65. chunks: Chunk[];
  66. failure?: Failure;
  67. failedAttempts?: number;
  68. preserveProviderStreamBoundaries?: boolean;
  69. }) {
  70. const status: ModelNetworkStatusEvent[] = [];
  71. const visible: ModelStreamEvent[] = [];
  72. const signals: AbortSignal[] = [];
  73. const caller = new AbortController();
  74. let attempts = 0;
  75. const runtime: AiSdkModelRuntime = {
  76. async generateText() {
  77. throw new Error("Expected streaming request");
  78. },
  79. streamText(request) {
  80. attempts += 1;
  81. const failed = attempts <= (options.failedAttempts ?? 1);
  82. const signal = request.abortSignal!;
  83. signals.push(signal);
  84. return {
  85. fullStream: (async function* () {
  86. if (!failed) {
  87. yield { type: "text-delta", id: "recovered", text: "ok" };
  88. yield finish();
  89. return;
  90. }
  91. yield* options.chunks;
  92. if (options.failure === "cancel") caller.abort();
  93. if (options.failure === "idle-timeout" || options.failure === "cancel") {
  94. await new Promise<void>((resolve) => {
  95. if (signal.aborted) resolve();
  96. else signal.addEventListener("abort", () => resolve(), { once: true });
  97. });
  98. return;
  99. }
  100. if (options.failure === "network-reset") {
  101. throw Object.assign(new Error("connection reset"), { code: "ECONNRESET" });
  102. }
  103. if (options.failure === "sse-error" || options.failure === "auth") {
  104. const statusCode = options.failure === "auth" ? 403 : 503;
  105. yield {
  106. type: "error",
  107. error: new ProviderBusinessError({
  108. providerId: "test",
  109. providerKind: "anthropic",
  110. providerCode: String(statusCode),
  111. providerMessage: "provider failure",
  112. responseStatus: 200,
  113. statusCode,
  114. }),
  115. };
  116. return;
  117. }
  118. yield finish(options.failure === "empty-eof" ? "other" : "stop");
  119. })(),
  120. } as never;
  121. },
  122. };
  123. const adapter = new AiSdkModelAdapter({
  124. env: { ZCODE_RUNTIME_ENV: "test" },
  125. runtime,
  126. retry: { maxAttempts: MAX_ATTEMPTS, baseDelayMs: 0, maxDelayMs: 0, jitter: false },
  127. streamIdleTimeoutMs: STREAM_IDLE_TIMEOUT_MS,
  128. });
  129. const provider = createRegistryProviderConfig(
  130. parseProviderConfig({
  131. group: "standard-personal",
  132. access: { type: "api-key", apiKey: "fixture-key" },
  133. api: { type: "anthropic-messages", baseUrl: "https://retry.invalid/v1" },
  134. }),
  135. );
  136. const config = createRegistryModelConfig(
  137. parseModelConfig({
  138. enabled: true,
  139. properties: createTestModelProperties(),
  140. optionSpecs: {
  141. reasoningLevel: { values: ["disabled"], map: "{}" },
  142. maxOutputTokens: { max: MAX_OUTPUT_TOKENS, map: '{"max_tokens": maxOutputTokens}' },
  143. },
  144. }),
  145. );
  146. if (!provider.ok || !config.ok) throw new Error("Invalid model fixture config");
  147. const model = adapter.createModel({
  148. providerId: "test",
  149. modelId: "model-a",
  150. providerConfig: provider.config,
  151. modelConfig: config.config,
  152. options: { maxOutputTokens: MAX_OUTPUT_TOKENS, reasoningLevel: "disabled" },
  153. });
  154. return {
  155. status,
  156. visible,
  157. signals,
  158. get attempts() {
  159. return attempts;
  160. },
  161. async read() {
  162. const stream = runWithModelInvocationContext(
  163. {
  164. preserveProviderStreamBoundaries: options.preserveProviderStreamBoundaries,
  165. statusSink: { publish: (event) => void status.push(event) },
  166. },
  167. () =>
  168. model.streamText({
  169. abortSignal: caller.signal,
  170. messages: [{ role: "user", content: "Write test.txt" }],
  171. }),
  172. );
  173. for await (const event of stream) {
  174. visible.push(event);
  175. }
  176. },
  177. };
  178. }
  179. describe.each<Prelude>(["signature", "empty-text"])("retry after %s only", (kind) => {
  180. it.each<Failure>(["sse-error", "network-reset", "idle-timeout", "empty-eof"])(
  181. "discards incomplete tool input and retries %s without leaking the failed attempt",
  182. async (failure) => {
  183. const run = harness({ chunks: [...prelude(kind), ...TOOL_INPUT], failure });
  184. await run.read();
  185. expect(run.attempts).toBe(MAX_ATTEMPTS);
  186. expect(run.visible).toEqual([
  187. { type: "text_delta", id: "recovered", text: "ok" },
  188. expect.objectContaining({ type: "finish", finishReason: "stop" }),
  189. ]);
  190. expect(run.status.filter((event) => event.type === "model_retry_scheduled")).toHaveLength(1);
  191. expect(run.status.find((event) => event.type === "model_request_failed")).toMatchObject({
  192. retryable: true,
  193. streamOutputCommitted: false,
  194. });
  195. if (failure !== "empty-eof") expect(run.signals[0]?.aborted).toBe(true);
  196. },
  197. );
  198. });
  199. describe("empty delta retry boundaries", () => {
  200. it("preserves the successful signature and event order before a complete tool call", async () => {
  201. const run = harness({ chunks: [...prelude("signature"), ...COMPLETE_TOOL] });
  202. await run.read();
  203. expect(run.attempts).toBe(1);
  204. expect(run.visible.map((event) => event.type)).toEqual([
  205. "start",
  206. "reasoning_start",
  207. "reasoning_delta",
  208. "reasoning_end",
  209. "tool_input_start",
  210. "tool_input_end",
  211. "tool_call",
  212. "finish",
  213. ]);
  214. expect(run.visible[2]).toMatchObject({
  215. text: "",
  216. providerMetadata: { anthropic: { signature: SIGNATURE } },
  217. });
  218. expect(run.visible[6]).toMatchObject({ toolCall: { id: "call-complete" } });
  219. });
  220. it.each([
  221. ["text", [{ type: "text-delta", id: "visible", text: " " }]],
  222. ["reasoning", [{ type: "reasoning-delta", id: "reasoning-failed", text: "thinking" }]],
  223. ["tool call", COMPLETE_TOOL],
  224. ] as const)("leaves failures after nonempty %s to core recovery", async (_name, chunks) => {
  225. const run = harness({ chunks: [...prelude("signature"), ...chunks], failure: "network-reset" });
  226. await expect(run.read()).rejects.toMatchObject({ name: "AiSdkModelAdapterError" });
  227. expect(run.attempts).toBe(1);
  228. expect(run.visible).not.toHaveLength(0);
  229. expect(run.status.some((event) => event.type === "model_retry_scheduled")).toBe(false);
  230. });
  231. it.each<Failure>(["auth", "cancel"])(
  232. "keeps %s terminal before visible output",
  233. async (failure) => {
  234. const run = harness({ chunks: [...prelude("signature"), ...TOOL_INPUT], failure });
  235. await expect(run.read()).rejects.toMatchObject({ name: "AiSdkModelAdapterError" });
  236. expect(run.attempts).toBe(1);
  237. expect(run.visible).toEqual([]);
  238. expect(run.status.some((event) => event.type === "model_retry_scheduled")).toBe(false);
  239. },
  240. );
  241. it("stops at the existing adapter retry budget without committing the failed prelude", async () => {
  242. const run = harness({
  243. chunks: [...prelude("signature"), ...TOOL_INPUT],
  244. failure: "network-reset",
  245. failedAttempts: MAX_ATTEMPTS,
  246. });
  247. await expect(run.read()).rejects.toMatchObject({ name: "AiSdkModelAdapterError" });
  248. expect(run.attempts).toBe(MAX_ATTEMPTS);
  249. expect(run.visible).toEqual([]);
  250. expect(
  251. run.status.filter((event) => event.type === "model_request_failed").at(-1),
  252. ).toMatchObject({
  253. retryable: false,
  254. });
  255. });
  256. it("preserves the stricter compact provider boundary", async () => {
  257. const run = harness({
  258. chunks: prelude("signature"),
  259. failure: "network-reset",
  260. preserveProviderStreamBoundaries: true,
  261. });
  262. await expect(run.read()).rejects.toMatchObject({ name: "AiSdkModelAdapterError" });
  263. expect(run.attempts).toBe(1);
  264. expect(run.visible[2]).toMatchObject({
  265. providerMetadata: { anthropic: { signature: SIGNATURE } },
  266. });
  267. });
  268. });