runner-empty-completion-finish.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. ModelErrorCode,
  4. type ModelNetworkStatusEvent,
  5. type ModelStreamEvent,
  6. type ModelUsage,
  7. } from "@zcode/contracts";
  8. import type { AiSdkModelRuntime } from "../src/model/runner.js";
  9. import { executeAdapterGenerateText, executeAdapterStreamText } from "./test-adapter-model.js";
  10. import { TestAiSdkModelAdapter, TestProviderConfigFixture } from "./test-provider-config.js";
  11. const ZERO_USAGE = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
  12. const MAX_ATTEMPTS = 3;
  13. const EXCLUDED_FINISHES = [
  14. { finishReason: "length", rawFinishReason: "model_context_window_exceeded" },
  15. { finishReason: "other", rawFinishReason: "model_context_window_exceeded" },
  16. { finishReason: "other", rawFinishReason: "context_exceeded" },
  17. { finishReason: "other", rawFinishReason: "context_length_exceeded" },
  18. { finishReason: "other", rawFinishReason: "context_window_exceeded" },
  19. { finishReason: "other", rawFinishReason: "model_context_exceeded" },
  20. { finishReason: "other", rawFinishReason: "prompt_too_long" },
  21. { finishReason: "context_window_exceeded", rawFinishReason: undefined },
  22. { finishReason: "content-filter", rawFinishReason: undefined },
  23. { finishReason: "other", rawFinishReason: "content_filter" },
  24. { finishReason: "other", rawFinishReason: "refusal" },
  25. ] as const;
  26. function harness(
  27. finishReason: string,
  28. rawFinishReason: string | undefined,
  29. rawSource: "direct" | "metadata",
  30. generatedText = "",
  31. output: {
  32. usage?: ModelUsage;
  33. reasoning?: unknown[];
  34. toolCalls?: unknown[];
  35. chunks?: unknown[];
  36. } = {},
  37. ) {
  38. let attempts = 0;
  39. const status: ModelNetworkStatusEvent[] = [];
  40. const events: ModelStreamEvent[] = [];
  41. const providerMetadata = {
  42. fixture: { marker: "preserved" },
  43. ...(rawSource === "metadata" && rawFinishReason !== undefined ? { rawFinishReason } : {}),
  44. };
  45. const completion = {
  46. finishReason,
  47. providerMetadata,
  48. ...(rawSource === "direct" ? { rawFinishReason } : {}),
  49. };
  50. const runtime: AiSdkModelRuntime = {
  51. async generateText() {
  52. attempts += 1;
  53. return {
  54. ...completion,
  55. text: generatedText,
  56. reasoning: output.reasoning,
  57. toolCalls: output.toolCalls,
  58. usage: output.usage ?? ZERO_USAGE,
  59. } as never;
  60. },
  61. streamText() {
  62. attempts += 1;
  63. return {
  64. fullStream: (async function* () {
  65. yield { type: "start" };
  66. if (generatedText) yield { type: "text-delta", id: "text", text: generatedText };
  67. for (const chunk of output.chunks ?? []) yield chunk;
  68. yield { type: "finish", ...completion, totalUsage: output.usage ?? ZERO_USAGE };
  69. })(),
  70. } as never;
  71. },
  72. };
  73. const adapter = new TestAiSdkModelAdapter({
  74. registry: new TestProviderConfigFixture({
  75. providers: {
  76. test: { kind: "custom", createLanguageModel: (modelId) => ({ modelId }) as never },
  77. },
  78. }),
  79. runtime,
  80. retry: { maxAttempts: MAX_ATTEMPTS, baseDelayMs: 0, maxDelayMs: 0, jitter: false },
  81. });
  82. return {
  83. status,
  84. events,
  85. get attempts() {
  86. return attempts;
  87. },
  88. async read(mode: "stream" | "generate") {
  89. const request = {
  90. providerId: "test",
  91. modelId: "model-a",
  92. messages: [{ role: "user" as const, content: "Continue the task" }],
  93. statusSink: { publish: (event: ModelNetworkStatusEvent) => void status.push(event) },
  94. };
  95. if (mode === "generate") return executeAdapterGenerateText(adapter, request);
  96. for await (const event of executeAdapterStreamText(adapter, request)) events.push(event);
  97. expect(events.at(-1)?.type).toBe("finish");
  98. return events.at(-1);
  99. },
  100. };
  101. }
  102. it("normalizes context overflow when a streamed tool call never passed its completion gate", async () => {
  103. const run = harness("length", "model_context_window_exceeded", "direct", "", {
  104. chunks: [
  105. { type: "tool-input-start", id: "call", toolName: "Read" },
  106. { type: "tool-call", toolCallId: "call", toolName: "Read", input: { path: "example.txt" } },
  107. ],
  108. });
  109. await expect(run.read("stream")).rejects.toMatchObject({
  110. code: ModelErrorCode.ModelContextExceeded,
  111. });
  112. expect(run.events.some((event) => event.type === "tool_call" || event.type === "finish")).toBe(
  113. false,
  114. );
  115. });
  116. describe.each(["stream", "generate"] as const)("%s empty completion finish semantics", (mode) => {
  117. it.each([
  118. { finishReason: "other", rawFinishReason: "prompt_too_long", text: "Valid title" },
  119. { finishReason: "other", rawFinishReason: "context_exceeded", text: '{"passed":false}' },
  120. { finishReason: "other", rawFinishReason: " MODEL_CONTEXT_WINDOW_EXCEEDED ", text: "partial" },
  121. ])("returns nonempty $rawFinishReason unchanged for every caller", async (entry) => {
  122. const run = harness(entry.finishReason, entry.rawFinishReason, "direct", entry.text);
  123. const result = await run.read(mode);
  124. expect(result).toMatchObject({ finishReason: entry.finishReason });
  125. if (mode === "generate")
  126. expect(result).toMatchObject({
  127. text: entry.text,
  128. providerMetadata: { fixture: { marker: "preserved" } },
  129. });
  130. if (mode === "stream")
  131. expect(run.events.filter((event) => event.type === "text_delta")).toMatchObject([
  132. { text: entry.text },
  133. ]);
  134. expect(run.status.some((event) => event.type === "model_request_failed")).toBe(false);
  135. expect(run.status.filter((event) => event.type === "model_request_completed")).toHaveLength(1);
  136. expect(run.attempts).toBe(1);
  137. });
  138. it("preserves nonzero reported usage on the failed request", async () => {
  139. const usage = { inputTokens: 80, outputTokens: 5, totalTokens: 85 };
  140. const run = harness("length", "model_context_window_exceeded", "direct", "", { usage });
  141. await expect(run.read(mode)).rejects.toMatchObject({
  142. code: ModelErrorCode.ModelContextExceeded,
  143. usage,
  144. });
  145. expect(run.status.filter((event) => event.type === "model_request_failed")).toMatchObject([
  146. { usage },
  147. ]);
  148. expect(run.status.some((event) => event.type === "model_request_completed")).toBe(false);
  149. expect(run.events.some((event) => event.type === "finish")).toBe(false);
  150. expect(run.attempts).toBe(1);
  151. });
  152. describe.each([
  153. { finishReason: "length", rawFinishReason: "model_context_window_exceeded" },
  154. { finishReason: "other", rawFinishReason: "prompt_too_long" },
  155. ])("partial $finishReason / $rawFinishReason", (completion) => {
  156. it.each(["text", "whitespace", "reasoning", "opaque-reasoning", "tool-call"])(
  157. "preserves partial %s output",
  158. async (kind) => {
  159. const opaque = { test: { signature: "retained" } };
  160. const toolCall = {
  161. type: "tool-call",
  162. toolCallId: "call",
  163. toolName: "Read",
  164. input: { path: "example.txt" },
  165. };
  166. const run = harness(
  167. completion.finishReason,
  168. completion.rawFinishReason,
  169. "metadata",
  170. kind === "text" ? "partial" : kind === "whitespace" ? " " : "",
  171. {
  172. ...(kind === "reasoning" || kind === "opaque-reasoning"
  173. ? {
  174. reasoning: [
  175. {
  176. type: "reasoning",
  177. text: kind === "reasoning" ? "thinking" : "",
  178. providerMetadata: opaque,
  179. },
  180. ],
  181. chunks: [
  182. { type: "reasoning-start", id: "reasoning" },
  183. {
  184. type: "reasoning-delta",
  185. id: "reasoning",
  186. text: kind === "reasoning" ? "thinking" : "",
  187. providerMetadata: opaque,
  188. },
  189. { type: "reasoning-end", id: "reasoning" },
  190. ],
  191. }
  192. : {}),
  193. ...(kind === "tool-call" ? { toolCalls: [toolCall], chunks: [toolCall] } : {}),
  194. },
  195. );
  196. expect(await run.read(mode)).toMatchObject({
  197. finishReason: completion.finishReason,
  198. providerMetadata: { rawFinishReason: completion.rawFinishReason },
  199. });
  200. expect(run.status.filter((event) => event.type === "model_request_completed")).toHaveLength(
  201. 1,
  202. );
  203. expect(run.status.some((event) => event.type === "model_request_failed")).toBe(false);
  204. expect(run.attempts).toBe(1);
  205. },
  206. );
  207. });
  208. describe.each(["direct", "metadata"] as const)("raw reason from %s", (rawSource) => {
  209. it.each(
  210. EXCLUDED_FINISHES.filter(
  211. (entry) => rawSource === "direct" || entry.rawFinishReason !== undefined,
  212. ),
  213. )("does not retry excluded finish $finishReason / $rawFinishReason", async (entry) => {
  214. const { rawFinishReason } = entry;
  215. const run = harness(entry.finishReason, rawFinishReason, rawSource);
  216. const contextLimit = !["content-filter", "content_filter", "refusal"].includes(
  217. rawFinishReason ?? entry.finishReason,
  218. );
  219. if (contextLimit) {
  220. await expect(run.read(mode)).rejects.toMatchObject({
  221. code: ModelErrorCode.ModelContextExceeded,
  222. usage: ZERO_USAGE,
  223. context: {
  224. reason: "context_exceeded",
  225. rawFinishReason,
  226. finishReason: entry.finishReason,
  227. },
  228. });
  229. expect(run.events.some((event) => event.type === "finish")).toBe(false);
  230. expect(run.attempts).toBe(1);
  231. expect(run.status.filter((event) => event.type === "model_request_failed")).toMatchObject([
  232. { reason: "context_exceeded", retryable: false, usage: ZERO_USAGE },
  233. ]);
  234. expect(
  235. run.status.some(
  236. (event) =>
  237. event.type === "model_request_completed" || event.type === "model_retry_scheduled",
  238. ),
  239. ).toBe(false);
  240. return;
  241. }
  242. const result = await run.read(mode);
  243. expect(run.attempts).toBe(1);
  244. expect(run.status.filter((event) => event.type === "model_request_started")).toHaveLength(1);
  245. expect(run.status.some((event) => event.type === "model_retry_scheduled")).toBe(false);
  246. expect(run.status.some((event) => event.type === "model_request_failed")).toBe(false);
  247. expect(result).toMatchObject({
  248. finishReason: entry.finishReason,
  249. usage: ZERO_USAGE,
  250. providerMetadata: {
  251. fixture: { marker: "preserved" },
  252. ...(rawFinishReason !== undefined && (mode === "stream" || rawSource === "metadata")
  253. ? { rawFinishReason }
  254. : {}),
  255. },
  256. });
  257. if (mode === "generate" && rawSource === "direct") {
  258. expect(result).toHaveProperty("providerMetadata", { fixture: { marker: "preserved" } });
  259. }
  260. });
  261. it.each(["stop", "tool-calls", "tool_calls"])(
  262. "preserves the existing no-retry behavior for %s",
  263. async (finishReason) => {
  264. const run = harness(finishReason, "unrecognized_provider_marker", rawSource);
  265. const result = await run.read(mode);
  266. expect(run.attempts).toBe(1);
  267. expect(run.status.some((event) => event.type === "model_retry_scheduled")).toBe(false);
  268. expect(result).toHaveProperty("finishReason", finishReason);
  269. },
  270. );
  271. it.each(
  272. [
  273. { finishReason: "other", rawFinishReason: undefined },
  274. { finishReason: "length", rawFinishReason: undefined },
  275. { finishReason: "length", rawFinishReason: "max_tokens" },
  276. { finishReason: "other", rawFinishReason: "max_output_tokens" },
  277. { finishReason: "other", rawFinishReason: "end_turn" },
  278. { finishReason: "unknown", rawFinishReason: "unknown" },
  279. { finishReason: "other", rawFinishReason: "unrecognized_provider_marker" },
  280. ].filter((entry) => rawSource === "direct" || entry.rawFinishReason !== undefined),
  281. )(
  282. "preserves the existing retry for other finish $finishReason / $rawFinishReason",
  283. async (entry) => {
  284. const run = harness(entry.finishReason, entry.rawFinishReason, rawSource);
  285. const result = await run.read(mode);
  286. expect(run.attempts).toBe(2);
  287. expect(run.status.filter((event) => event.type === "model_retry_scheduled")).toHaveLength(
  288. 1,
  289. );
  290. expect(result).toHaveProperty("providerMetadata", {
  291. fixture: { marker: "preserved" },
  292. ...(entry.rawFinishReason !== undefined && (mode === "stream" || rawSource === "metadata")
  293. ? { rawFinishReason: entry.rawFinishReason }
  294. : {}),
  295. });
  296. },
  297. );
  298. });
  299. });