fake-provider-server.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /**
  2. * 假 provider 服务器的自测(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Verification」):用**真**
  3. * `AiSdkModelAdapter` 直连,不起 run。钉住的是矩阵赖以成立的几条事实——两种 wire 的成功帧
  4. * 被真 adapter 解析成同一个工具调用;各种判决经真实 fetch 包装 → 业务码 → 分类器之后落到
  5. * 预期的 reason / providerCode;`retry-after-ms` 真的被 runner 采用。
  6. */
  7. import { afterEach, describe, expect, it } from "vitest";
  8. import {
  9. ModelRetryBudget,
  10. runWithModelInvocationContext,
  11. SUBMIT_RESULT_TOOL_NAME,
  12. type Model,
  13. type ModelEvent,
  14. type ModelInputMessage,
  15. type ModelNetworkStatusEvent,
  16. type ModelRequest,
  17. type ModelToolContract,
  18. } from "@zcode/contracts";
  19. import { AiSdkModelAdapterError } from "@zcode/adapters/model";
  20. import {
  21. startFakeProviderServer,
  22. type FakeProviderServer,
  23. type FaultProgram,
  24. type WireFormat,
  25. } from "./helpers/fake-provider-server.js";
  26. import { always, AUTH_401, BUSY_3008, failFirst, healthy } from "./helpers/fault-programs.js";
  27. import {
  28. createFaultModelFactory,
  29. FAULT_MODEL_SELECTION,
  30. type FaultProviderModelOptions,
  31. } from "./helpers/fault-provider-model.js";
  32. const FORMATS: readonly WireFormat[] = ["anthropic-messages", "openai-chat-completions"];
  33. const TOOLS: ModelToolContract[] = [
  34. {
  35. name: "Glob",
  36. description: "find files",
  37. inputSchema: { type: "object", properties: { pattern: { type: "string" } }, required: ["pattern"] },
  38. },
  39. {
  40. name: SUBMIT_RESULT_TOOL_NAME,
  41. description: "submit",
  42. inputSchema: {
  43. type: "object",
  44. properties: { result: { type: "object", properties: { note: { type: "string" } } } },
  45. required: ["result"],
  46. },
  47. },
  48. ];
  49. const FIRST_TURN: ModelInputMessage[] = [{ role: "user", content: "Do the work." }];
  50. /** 已经跑过一轮 Glob 的对话:assistant 工具调用 + tool 结果。 */
  51. const AFTER_ONE_TOOL_RESULT: ModelInputMessage[] = [
  52. ...FIRST_TURN,
  53. {
  54. role: "assistant",
  55. content: "",
  56. toolCalls: [{ id: "call-glob-1", name: "Glob", input: { pattern: "**/*.md" } }],
  57. },
  58. { role: "tool", content: "[]", toolCallId: "call-glob-1", toolName: "Glob" },
  59. ];
  60. interface Rig {
  61. server: FakeProviderServer;
  62. model: Model;
  63. statusEvents: ModelNetworkStatusEvent[];
  64. dispose(): Promise<void>;
  65. }
  66. const rigs: Rig[] = [];
  67. afterEach(async () => {
  68. await Promise.all(rigs.splice(0).map((rig) => rig.dispose()));
  69. });
  70. async function rig(
  71. apiFormat: WireFormat,
  72. program: FaultProgram,
  73. options: Partial<FaultProviderModelOptions> & { turns?: number } = {},
  74. ): Promise<Rig> {
  75. const server = await startFakeProviderServer({
  76. program,
  77. ...(options.turns === undefined ? {} : { canned: { turns: options.turns } }),
  78. });
  79. const statusEvents: ModelNetworkStatusEvent[] = [];
  80. const factory = createFaultModelFactory({
  81. apiFormat,
  82. baseURL: server.baseURL,
  83. statusSink: { publish: (event) => void statusEvents.push(event) },
  84. ...(options.retry === undefined ? {} : { retry: options.retry }),
  85. ...(options.streamIdleTimeoutMs === undefined ? {} : { streamIdleTimeoutMs: options.streamIdleTimeoutMs }),
  86. });
  87. const model = factory.modelFactory({ selection: FAULT_MODEL_SELECTION });
  88. const built: Rig = {
  89. server,
  90. model,
  91. statusEvents,
  92. dispose: async () => {
  93. factory.dispose();
  94. await server.close();
  95. },
  96. };
  97. rigs.push(built);
  98. return built;
  99. }
  100. function request(messages: ModelInputMessage[]): ModelRequest {
  101. return { messages, tools: TOOLS, options: { maxOutputTokens: 1024 } };
  102. }
  103. async function collectStream(
  104. model: Model,
  105. messages: ModelInputMessage[],
  106. budget: ModelRetryBudget | undefined,
  107. ): Promise<ModelEvent[]> {
  108. const events: ModelEvent[] = [];
  109. const iterable = runWithModelInvocationContext(
  110. budget === undefined ? {} : { modelRetryBudget: budget },
  111. () => model.streamText(request(messages)),
  112. );
  113. for await (const event of iterable) events.push(event);
  114. return events;
  115. }
  116. async function rejectionOf(work: () => Promise<unknown>): Promise<AiSdkModelAdapterError> {
  117. const rejection = await work().then(
  118. () => undefined,
  119. (error: unknown) => error,
  120. );
  121. expect(rejection).toBeInstanceOf(AiSdkModelAdapterError);
  122. return rejection as AiSdkModelAdapterError;
  123. }
  124. function toolCallsOf(events: ModelEvent[]): { name: string; input: unknown }[] {
  125. return events
  126. .filter((event): event is Extract<ModelEvent, { type: "tool_call" }> => event.type === "tool_call")
  127. .map((event) => ({ name: event.toolCall.name, input: event.toolCall.input }));
  128. }
  129. /** 一次性 fail-fast 的重试选项:只钉 reason,不在本文件里等退避。 */
  130. const NO_RETRY = { baseDelayMs: 1, jitter: false, maxAttempts: 1, maxDelayMs: 1 };
  131. describe.each(FORMATS)("fake provider server — %s", (apiFormat) => {
  132. it("serve: the real adapter parses the streamed canned turn into a Glob call, then submit_result", async () => {
  133. const { model, server } = await rig(apiFormat, healthy(), { turns: 1 });
  134. const first = await collectStream(model, FIRST_TURN, ModelRetryBudget.Unbounded);
  135. expect(toolCallsOf(first)).toEqual([{ name: "Glob", input: { pattern: "**/*.md" } }]);
  136. const second = await collectStream(model, AFTER_ONE_TOOL_RESULT, ModelRetryBudget.Unbounded);
  137. expect(toolCallsOf(second)).toEqual([
  138. { name: SUBMIT_RESULT_TOOL_NAME, input: { result: { note: "done" } } },
  139. ]);
  140. expect(server.requests.map((entry) => [entry.route, entry.stream, entry.toolResultCount])).toEqual([
  141. [apiFormat, true, 0],
  142. [apiFormat, true, 1],
  143. ]);
  144. expect(server.requests.every((entry) => entry.servedStatus === 200 && !entry.closedByClient)).toBe(true);
  145. });
  146. it("serve: the non-stream path yields the same tool calls", async () => {
  147. const { model, server } = await rig(apiFormat, healthy(), { turns: 1 });
  148. const result = await runWithModelInvocationContext({}, () => model.generateText(request(AFTER_ONE_TOOL_RESULT)));
  149. expect(result.finishReason).toBe("tool-calls");
  150. expect(result.toolCalls?.map((call) => [call.name, call.input])).toEqual([
  151. [SUBMIT_RESULT_TOOL_NAME, { result: { note: "done" } }],
  152. ]);
  153. expect(server.requests[0]?.stream).toBe(false);
  154. });
  155. it("status 429 + error.code 3008: providerCode 3008, reason rate_limited (bounded budget fails fast)", async () => {
  156. const { model } = await rig(apiFormat, always(BUSY_3008), { retry: NO_RETRY });
  157. const error = await rejectionOf(() => collectStream(model, FIRST_TURN, undefined));
  158. expect(error.context).toMatchObject({ providerCode: "3008", reason: "rate_limited", statusCode: 429 });
  159. });
  160. it("status 429 with a top-level {code,msg} body and text/plain content-type still yields providerCode 3008", async () => {
  161. const { model } = await rig(
  162. apiFormat,
  163. always({ ...BUSY_3008, bodyShape: "top-level", headers: { "content-type": "text/plain" } }),
  164. { retry: NO_RETRY },
  165. );
  166. const error = await rejectionOf(() => collectStream(model, FIRST_TURN, undefined));
  167. expect(error.context).toMatchObject({ providerCode: "3008", reason: "rate_limited" });
  168. });
  169. it("status 401 + error.code 1006: reason auth_failed even under the unbounded workflow budget", async () => {
  170. const { model } = await rig(apiFormat, always(AUTH_401));
  171. const error = await rejectionOf(() => collectStream(model, FIRST_TURN, ModelRetryBudget.Unbounded));
  172. expect(error.context).toMatchObject({ providerCode: "1006", reason: "auth_failed", retryable: false });
  173. });
  174. it("stream_error frame: an in-stream business error carries providerCode 3008", async () => {
  175. const { model } = await rig(
  176. apiFormat,
  177. always({ kind: "stream_error", code: "3008", message: "user concurrency limit exceeded" }),
  178. { retry: NO_RETRY },
  179. );
  180. const error = await rejectionOf(() => collectStream(model, FIRST_TURN, undefined));
  181. expect(error.context).toMatchObject({ providerCode: "3008", reason: "rate_limited" });
  182. });
  183. it("cut after visible output: the runner does not replay and reports streamOutputCommitted", async () => {
  184. const { model, statusEvents } = await rig(apiFormat, always({ kind: "cut", after: "visible" }));
  185. await rejectionOf(() => collectStream(model, FIRST_TURN, ModelRetryBudget.Unbounded));
  186. const failed = statusEvents.filter((event) => event.type === "model_request_failed");
  187. expect(failed).toHaveLength(1);
  188. expect(failed[0]).toMatchObject({ streamOutputCommitted: true });
  189. expect(statusEvents.filter((event) => event.type === "model_retry_scheduled")).toHaveLength(0);
  190. });
  191. it("cut before visible output: the runner retries and the next attempt completes", async () => {
  192. const { model, server } = await rig(apiFormat, failFirstCut(1), { turns: 1 });
  193. const events = await collectStream(model, FIRST_TURN, ModelRetryBudget.Unbounded);
  194. expect(toolCallsOf(events)).toEqual([{ name: "Glob", input: { pattern: "**/*.md" } }]);
  195. expect(server.requests.map((entry) => entry.verdict.kind)).toEqual(["cut", "serve"]);
  196. });
  197. it("reset: the connection drop classifies as a network error", async () => {
  198. const { model } = await rig(apiFormat, always({ kind: "reset" }), { retry: NO_RETRY });
  199. const error = await rejectionOf(() => collectStream(model, FIRST_TURN, undefined));
  200. expect(error.context).toMatchObject({ reason: "network_error" });
  201. });
  202. it("hang: the stream idle timeout fires and classifies as stream_idle_timeout", async () => {
  203. const { model } = await rig(apiFormat, always({ kind: "hang" }), {
  204. retry: NO_RETRY,
  205. streamIdleTimeoutMs: 200,
  206. });
  207. const error = await rejectionOf(() => collectStream(model, FIRST_TURN, undefined));
  208. expect(error.context).toMatchObject({ reason: "stream_idle_timeout" });
  209. });
  210. it("retry-after-ms 20 on a plain 429 is adopted as the retry delay under the unbounded budget", async () => {
  211. const { model, statusEvents, server } = await rig(apiFormat, failFirst(1, 429), { turns: 1 });
  212. const events = await collectStream(model, FIRST_TURN, ModelRetryBudget.Unbounded);
  213. expect(toolCallsOf(events)).toHaveLength(1);
  214. const scheduled = statusEvents.filter(
  215. (event): event is Extract<ModelNetworkStatusEvent, { type: "model_retry_scheduled" }> =>
  216. event.type === "model_retry_scheduled",
  217. );
  218. expect(scheduled).toHaveLength(1);
  219. expect(scheduled[0]?.delayMs).toBe(20);
  220. expect(scheduled[0]?.reason).toBe("rate_limited");
  221. expect(server.requests.map((entry) => entry.servedStatus)).toEqual([429, 200]);
  222. });
  223. });
  224. /** 第一个请求在 message_start 之后切断,其余放行。 */
  225. function failFirstCut(n: number): FaultProgram {
  226. return (request) => (request.ordinal <= n ? { kind: "cut", after: "message_start" } : { kind: "serve" });
  227. }