runner-stream-timing-wire.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. runWithModelInvocationContext,
  4. type ModelNetworkStatusEvent,
  5. type ModelStreamEvent,
  6. } from "@zcode/contracts";
  7. import { calculateOutputTps } from "@zcode/shared";
  8. import { createProviderBusinessErrorFetch } from "../src/model/model-execution.js";
  9. import { TestAiSdkModelAdapter, TestProviderConfigFixture } from "./test-provider-config.js";
  10. type Frame = Record<string, unknown>;
  11. type ScheduledFrame = [number, Frame | Error];
  12. const ORIGIN = 1_800_000_000_000;
  13. const END_MS = 1000;
  14. const OUTPUT_TOKENS = 70;
  15. function installTransport(create: () => Response) {
  16. let count = 0;
  17. const waiters = new Map<number, ReturnType<typeof Promise.withResolvers<void>>>();
  18. vi.stubGlobal(
  19. "fetch",
  20. vi.fn(async () => {
  21. const result = create();
  22. waiters.get(++count)?.resolve();
  23. return result;
  24. }),
  25. );
  26. return (request = 1): Promise<void> => {
  27. if (count >= request) return Promise.resolve();
  28. const waiter = Promise.withResolvers<void>();
  29. waiters.set(request, waiter);
  30. return waiter.promise;
  31. };
  32. }
  33. function response(frames: ScheduledFrame[]): Response {
  34. const encoder = new TextEncoder();
  35. return new Response(
  36. new ReadableStream<Uint8Array>({
  37. start(controller) {
  38. for (const [at, frame] of frames) {
  39. setTimeout(() => {
  40. if (frame instanceof Error) controller.error(frame);
  41. else controller.enqueue(encoder.encode(`data: ${JSON.stringify(frame)}\n\n`));
  42. }, at);
  43. }
  44. if (!frames.some(([, frame]) => frame instanceof Error)) {
  45. setTimeout(() => controller.close(), END_MS);
  46. }
  47. },
  48. }),
  49. { headers: { "content-type": "text/event-stream" } },
  50. );
  51. }
  52. function anthropicFrames(kind: "tool" | "text" | "reasoning", firstMs = 300): ScheduledFrame[] {
  53. const block =
  54. kind === "tool"
  55. ? { type: "tool_use", id: "call_read", name: "Read", input: {} }
  56. : kind === "reasoning"
  57. ? { type: "thinking", thinking: "" }
  58. : { type: "text", text: "" };
  59. const delta =
  60. kind === "tool"
  61. ? { type: "input_json_delta", partial_json: '{"path":"example.txt"}' }
  62. : kind === "reasoning"
  63. ? { type: "thinking_delta", thinking: "think" }
  64. : { type: "text_delta", text: "a" };
  65. return [
  66. [50, { type: "ping" }],
  67. [
  68. 100,
  69. {
  70. type: "message_start",
  71. message: {
  72. id: "message",
  73. type: "message",
  74. role: "assistant",
  75. model: "model",
  76. content: [],
  77. usage: { input_tokens: 10, output_tokens: 0 },
  78. },
  79. },
  80. ],
  81. [200, { type: "content_block_start", index: 0, content_block: block }],
  82. [
  83. 250,
  84. {
  85. type: "content_block_delta",
  86. index: 0,
  87. delta: {
  88. ...delta,
  89. ...(kind === "tool"
  90. ? { partial_json: "" }
  91. : kind === "reasoning"
  92. ? { thinking: "" }
  93. : { text: "" }),
  94. },
  95. },
  96. ],
  97. [firstMs, { type: "content_block_delta", index: 0, delta }],
  98. [900, { type: "content_block_stop", index: 0 }],
  99. [
  100. 950,
  101. {
  102. type: "message_delta",
  103. delta: { stop_reason: kind === "tool" ? "tool_use" : "end_turn", stop_sequence: null },
  104. usage: { output_tokens: OUTPUT_TOKENS },
  105. },
  106. ],
  107. [END_MS, { type: "message_stop" }],
  108. ];
  109. }
  110. function harness(kind: "anthropic" | "openai-compatible" = "anthropic") {
  111. const status: ModelNetworkStatusEvent[] = [];
  112. const visible: Array<{ at: number; event: ModelStreamEvent }> = [];
  113. const adapter = new TestAiSdkModelAdapter({
  114. env: { ZCODE_RUNTIME_ENV: "test" },
  115. registry: new TestProviderConfigFixture({
  116. env: {},
  117. providers: {
  118. test: { kind, baseURL: "https://model.example.test/v1", apiKey: "fixture-key" },
  119. },
  120. }),
  121. retry: { maxAttempts: 2, baseDelayMs: 0, maxDelayMs: 0, jitter: false },
  122. statusSink: {
  123. publish: (event) => {
  124. status.push(event);
  125. },
  126. },
  127. });
  128. const model = adapter.createModel({ providerId: "test", modelId: "model" });
  129. return {
  130. status,
  131. visible,
  132. async run() {
  133. const stream = runWithModelInvocationContext({ metadata: { querySource: "main_turn" } }, () =>
  134. model.streamText({
  135. messages: [{ role: "user", content: "read" }],
  136. tools: [
  137. {
  138. name: "Read",
  139. inputSchema: {
  140. type: "object",
  141. properties: { path: { type: "string" } },
  142. required: ["path"],
  143. },
  144. },
  145. ],
  146. }),
  147. );
  148. for await (const event of stream) visible.push({ at: Date.now() - ORIGIN, event });
  149. },
  150. completed() {
  151. const event = status.findLast((entry) => entry.type === "model_request_completed");
  152. expect(event?.type).toBe("model_request_completed");
  153. if (event?.type !== "model_request_completed") throw new Error("Missing completion");
  154. return event;
  155. },
  156. };
  157. }
  158. describe("provider receive timing before stream buffers", () => {
  159. beforeEach(() => {
  160. vi.useFakeTimers();
  161. vi.setSystemTime(ORIGIN);
  162. });
  163. afterEach(() => {
  164. vi.useRealTimers();
  165. vi.restoreAllMocks();
  166. vi.unstubAllGlobals();
  167. });
  168. it.each(["tool", "text", "reasoning"] as const)(
  169. "times %s at the first non-empty wire delta",
  170. async (kind) => {
  171. const started = installTransport(() => response(anthropicFrames(kind)));
  172. const run = harness();
  173. const done = run.run();
  174. await started();
  175. await vi.advanceTimersByTimeAsync(END_MS + 100);
  176. await done;
  177. const completed = run.completed();
  178. expect(completed.timeToFirstContentMs).toBe(300);
  179. expect(run.status.find((event) => event.type === "model_first_content")).toMatchObject({
  180. elapsedMs: 300,
  181. timestamp: new Date(ORIGIN + 300).toISOString(),
  182. });
  183. expect(completed.durationMs).toBe(END_MS);
  184. expect(
  185. calculateOutputTps(
  186. completed.usage?.outputTokens,
  187. completed.durationMs! - completed.timeToFirstContentMs!,
  188. ),
  189. ).toBe(100);
  190. if (kind === "tool" || kind === "text") {
  191. const first = run.visible.find(
  192. ({ event }) => event.type === (kind === "tool" ? "tool_input_delta" : "text_delta"),
  193. );
  194. expect(first?.at).toBe(900);
  195. }
  196. },
  197. );
  198. it("keeps the retry buffer and starts timing anew after a partial tool attempt fails", async () => {
  199. let attempt = 0;
  200. const started = installTransport(() => {
  201. attempt += 1;
  202. return response(
  203. attempt === 1
  204. ? [
  205. ...anthropicFrames("tool").filter(([at]) => at <= 300),
  206. [400, Object.assign(new Error("connection reset"), { code: "ECONNRESET" })],
  207. ]
  208. : anthropicFrames("tool", 500),
  209. );
  210. });
  211. const run = harness();
  212. const done = run.run();
  213. await started();
  214. await vi.advanceTimersByTimeAsync(3000);
  215. await done;
  216. expect(attempt).toBe(2);
  217. expect(run.completed().timeToFirstContentMs).toBe(500);
  218. expect(run.visible.filter(({ event }) => event.type === "tool_call")).toHaveLength(1);
  219. expect(
  220. new Set(
  221. run.status
  222. .filter((event) => event.type === "model_request_started")
  223. .map((event) => event.requestId),
  224. ).size,
  225. ).toBe(2);
  226. });
  227. it("isolates simultaneous requests with different first-content times", async () => {
  228. let call = 0;
  229. const started = installTransport(() =>
  230. response(anthropicFrames("tool", ++call === 1 ? 300 : 600)),
  231. );
  232. const run = harness();
  233. const done = Promise.all([run.run(), run.run()]);
  234. await started(2);
  235. await vi.advanceTimersByTimeAsync(1200);
  236. await done;
  237. expect(
  238. run.status
  239. .filter((event) => event.type === "model_request_completed")
  240. .map((event) => event.timeToFirstContentMs)
  241. .sort(),
  242. ).toEqual([300, 600]);
  243. });
  244. it("does not invent timing from empty frames or SDK synthetic start", async () => {
  245. const frames = anthropicFrames("text").filter(([at]) => at !== 300);
  246. const started = installTransport(() => response(frames));
  247. const run = harness();
  248. const done = run.run();
  249. await started();
  250. await vi.advanceTimersByTimeAsync(1200);
  251. await done;
  252. expect(run.completed().timeToFirstContentMs).toBeUndefined();
  253. });
  254. it.each(["text", "reasoning", "tool"] as const)(
  255. "times compatible %s output through the real SDK",
  256. async (kind) => {
  257. const chunk = (delta: Frame, finish_reason: string | null = null) => ({
  258. id: "chatcmpl-timing",
  259. object: "chat.completion.chunk",
  260. created: 1,
  261. model: "model",
  262. choices: [{ index: 0, delta, finish_reason }],
  263. });
  264. const delta =
  265. kind === "text"
  266. ? { content: "answer" }
  267. : kind === "reasoning"
  268. ? { reasoning_content: "think" }
  269. : {
  270. tool_calls: [
  271. {
  272. index: 0,
  273. id: "call_read",
  274. type: "function",
  275. function: { name: "Read", arguments: '{"path":"example.txt"}' },
  276. },
  277. ],
  278. };
  279. const started = installTransport(() =>
  280. response([
  281. [100, chunk({ role: "assistant" })],
  282. [200, chunk({ content: "" })],
  283. [300, chunk(delta)],
  284. [900, chunk({}, kind === "tool" ? "tool_calls" : "stop")],
  285. [
  286. END_MS,
  287. {
  288. ...chunk({}),
  289. choices: [],
  290. usage: { prompt_tokens: 10, completion_tokens: OUTPUT_TOKENS, total_tokens: 80 },
  291. },
  292. ],
  293. ]),
  294. );
  295. const run = harness("openai-compatible");
  296. const done = run.run();
  297. await started();
  298. await vi.advanceTimersByTimeAsync(1200);
  299. await done;
  300. expect(run.completed()).toMatchObject({ timeToFirstContentMs: 300, durationMs: END_MS });
  301. },
  302. );
  303. it.each([
  304. "response.output_text.delta",
  305. "response.reasoning_text.delta",
  306. "response.reasoning_summary_text.delta",
  307. "response.function_call_arguments.delta",
  308. ])("observes %s before forwarding its SSE frame", async (type) => {
  309. const timing: { firstContentAt?: number } = {};
  310. const frames: ScheduledFrame[] = [
  311. [100, { type: "response.created" }],
  312. [200, { type, delta: "" }],
  313. [300, { type, delta: "x" }],
  314. [END_MS, { type: "response.completed" }],
  315. ];
  316. const fetch = createProviderBusinessErrorFetch({
  317. env: {},
  318. providerId: "test",
  319. providerKind: "openai",
  320. streamTiming: timing,
  321. fetch: async () => response(frames),
  322. });
  323. const result = await fetch("https://model.example.test/v1/responses");
  324. const body = result.text();
  325. await vi.advanceTimersByTimeAsync(1200);
  326. expect(timing.firstContentAt).toBe(ORIGIN + 300);
  327. expect(await body).toBe(
  328. frames.map(([, frame]) => `data: ${JSON.stringify(frame)}\n\n`).join(""),
  329. );
  330. });
  331. });