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

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