workflow-concurrency-tool-traffic.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /**
  2. * v3 回归场景(docs/dynamic-workflow/concurrency.md「Where the port is bound」):deep-research 形态——
  3. * 6 个子代理各发 1 个 turn 请求 + 3 个并行工具侧请求,全部经 runtime 层准入(决策 42/43),
  4. * provider 在 8 并发以上 429。钉住三件事:provider 观测到的在飞从不超过治理器 cap;首个 429 立即
  5. * 砍 cap(不再有「治理器看不见工具流量」的一分钟盲区);排队请求发 queued / admitted(决策 44)。
  6. * 真治理器 + 真 adapter runner + 假 provider;每个子代理的准入端口走 driver 的窄包装。
  7. */
  8. import { describe, expect, it } from "vitest";
  9. import {
  10. ModelRetryBudget,
  11. runWithModelInvocationContext,
  12. type ModelNetworkStatusEvent,
  13. type ModelRequestAdmission,
  14. type ModelStatusSink,
  15. } from "@zcode/contracts";
  16. import {
  17. AiSdkModelAdapter,
  18. ProviderBusinessError,
  19. type AiSdkModelRuntime,
  20. } from "@zcode/adapters/model";
  21. import {
  22. ApiKeyAccessConfig,
  23. ModelConfig,
  24. ModelInputFormatConfig,
  25. ModelOptionSpecsConfig,
  26. ModelOutputFormatConfig,
  27. ModelPropertiesConfig,
  28. ProviderApiConfig,
  29. ProviderConfig,
  30. type RegistryModelConfig,
  31. type RegistryProviderConfig,
  32. } from "@zcode/provider";
  33. import { createActorModelActivity } from "../src/app/workflow-driver-concurrency.js";
  34. import {
  35. createWorkflowConcurrencyGovernor,
  36. workflowConcurrencyKey,
  37. } from "../src/app/workflow-concurrency-governor.js";
  38. const DEFAULT_CONCURRENCY = 13;
  39. const PROVIDER_LIMIT = 8;
  40. const ACTORS = 6;
  41. const TOOL_REQUESTS_PER_ACTOR = 3;
  42. /** provider 重构后 adapter 只吃完整的单 Provider/Model Config;这里手工拼一份最小的假 provider。 */
  43. function testProviderConfig(providerId: string): RegistryProviderConfig {
  44. return new ProviderConfig({
  45. access: new ApiKeyAccessConfig({ apiKey: "test-api-key" }),
  46. api: new ProviderApiConfig({ baseUrl: "https://adapter.test/v1", type: "openai-chat-completions" }),
  47. builtinModelIds: [],
  48. enabled: true,
  49. id: providerId,
  50. personalModelIds: [],
  51. name: providerId,
  52. visibility: "visible",
  53. }) as RegistryProviderConfig;
  54. }
  55. function testModelConfig(): RegistryModelConfig {
  56. return new ModelConfig({
  57. enabled: true,
  58. properties: new ModelPropertiesConfig({
  59. requiresMfjsToolSchema: false,
  60. contextWindow: 200_000,
  61. inputFormat: new ModelInputFormatConfig({
  62. supportsText: true,
  63. supportsImage: false,
  64. supportsVideo: false,
  65. supportsAudio: false,
  66. supportsPdf: false,
  67. }),
  68. outputFormat: new ModelOutputFormatConfig({ supportsText: true }),
  69. supportsToolCall: true,
  70. supportsJsonSchemaOutput: true,
  71. supportsNativeWebSearch: false,
  72. supportsMidConversationSystem: true,
  73. }),
  74. optionSpecs: new ModelOptionSpecsConfig({
  75. maxOutputTokens: { max: 1_000_000, map: '{"max_completion_tokens": maxOutputTokens}' },
  76. reasoningLevel: { values: ["disabled"], map: "{}" },
  77. }),
  78. }) as RegistryModelConfig;
  79. }
  80. function usage(n: number) {
  81. return {
  82. inputTokens: n,
  83. outputTokens: n,
  84. totalTokens: 2 * n,
  85. inputTokenDetails: {
  86. noCacheTokens: n,
  87. cacheReadTokens: undefined,
  88. cacheWriteTokens: undefined,
  89. },
  90. outputTokenDetails: { textTokens: n, reasoningTokens: undefined },
  91. };
  92. }
  93. describe("workflow concurrency — 工具侧模型请求也过闸门(v3 决策 42/43/44)", () => {
  94. it("6 子代理 × (1 turn + 3 工具请求):provider 在飞 ≤ cap,首个 429 即砍,排队者发 queued/admitted", async () => {
  95. const governor = createWorkflowConcurrencyGovernor({ defaultConcurrency: DEFAULT_CONCURRENCY });
  96. const key = workflowConcurrencyKey({ providerId: "prov", modelId: "alpha" } as never);
  97. let inFlight = 0;
  98. let maxInFlight = 0;
  99. let rateLimited = 0;
  100. let capAtFirst429: number | undefined;
  101. const capAboveProviderObserved: number[] = [];
  102. const runtime: AiSdkModelRuntime = {
  103. async generateText() {
  104. inFlight += 1;
  105. maxInFlight = Math.max(maxInFlight, inFlight);
  106. const cap = governor.snapshot(key)?.cap ?? DEFAULT_CONCURRENCY;
  107. if (inFlight > cap) capAboveProviderObserved.push(inFlight);
  108. try {
  109. if (inFlight > PROVIDER_LIMIT) {
  110. rateLimited += 1;
  111. capAtFirst429 ??= cap;
  112. throw Object.assign(new Error("rate limited"), { isRetryable: true, statusCode: 429 });
  113. }
  114. await new Promise((resolve) => setTimeout(resolve, 15));
  115. return {
  116. text: "ok",
  117. finishReason: "stop",
  118. usage: usage(1),
  119. totalUsage: usage(1),
  120. } as never;
  121. } finally {
  122. inFlight -= 1;
  123. }
  124. },
  125. streamText() {
  126. throw new Error("not used");
  127. },
  128. };
  129. const adapter = new AiSdkModelAdapter({
  130. retry: { baseDelayMs: 5, jitter: false, maxAttempts: 20, maxDelayMs: 5 },
  131. runtime,
  132. });
  133. const model = adapter.createModel({
  134. providerId: "prov",
  135. modelId: "alpha",
  136. providerConfig: testProviderConfig("prov"),
  137. modelConfig: testModelConfig(),
  138. options: { maxOutputTokens: 32_000, reasoningLevel: "disabled" },
  139. });
  140. const events: ModelNetworkStatusEvent[] = [];
  141. const requests: Promise<unknown>[] = [];
  142. for (let actor = 0; actor < ACTORS; actor += 1) {
  143. const activity = createActorModelActivity({
  144. port: governor,
  145. runId: "run-deep-research",
  146. handlers: { onWaiting: () => {}, onExecuting: () => {} },
  147. });
  148. // 准入端口与状态汇经调用上下文到 runner(adapters/src/model/runner.ts 把上下文整份铺进请求)。
  149. const statusSink: ModelStatusSink = { publish: (event) => void events.push(event) };
  150. const send = (querySource: string, toolCallId?: string) =>
  151. runWithModelInvocationContext(
  152. {
  153. metadata: { querySource, ...(toolCallId === undefined ? {} : { toolCallId }) },
  154. modelRequestAdmission: activity.admission as ModelRequestAdmission,
  155. statusSink,
  156. },
  157. () => model.generateText({ messages: [{ role: "user", content: "Ping" }] }),
  158. );
  159. requests.push(send("workflow_child"));
  160. for (let tool = 0; tool < TOOL_REQUESTS_PER_ACTOR; tool += 1) {
  161. requests.push(send("web_search_tool", `tc-${actor}-${tool}`));
  162. }
  163. }
  164. const results = await Promise.all(requests);
  165. expect(results).toHaveLength(ACTORS * (1 + TOOL_REQUESTS_PER_ACTOR));
  166. // provider 看到的在飞从不超过治理器此刻的 cap(也就从不超过天花板)。
  167. expect(capAboveProviderObserved).toEqual([]);
  168. expect(maxInFlight).toBeLessThanOrEqual(DEFAULT_CONCURRENCY);
  169. // 第一个 429 打在天花板上,之后 cap 立刻降到天花板以下——不再有看不见的流量。
  170. expect(rateLimited).toBeGreaterThan(0);
  171. expect(capAtFirst429).toBe(DEFAULT_CONCURRENCY);
  172. const snapshot = governor.snapshot(key)!;
  173. expect(snapshot.cap).toBeLessThan(DEFAULT_CONCURRENCY);
  174. // 24 个请求挤 13 个槽:至少有人排过队,且排队者都拿到了票。
  175. const queued = events.filter((event) => event.type === "model_request_queued");
  176. const admitted = events.filter((event) => event.type === "model_request_admitted");
  177. expect(queued.length).toBeGreaterThan(0);
  178. expect(admitted.length).toBe(queued.length);
  179. // 工具侧请求确实经过了闸门:它们中也有排过队的。
  180. expect(queued.some((event) => event.querySource === "web_search_tool")).toBe(true);
  181. expect(snapshot.inFlight).toBe(0);
  182. });
  183. });
  184. /**
  185. * 终态设计的回归场景(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md):Start Plan 网关在用户并发上限处
  186. * 回业务码 3008(`user concurrency limit exceeded`),分类器判它 `retryable:false`(主对话的
  187. * 横幅决策)。workflow 流量带无上限预算,runner 改读策略表:3008 = retry——请求不失败、
  188. * 以 retry_scheduled{rate_limited} 喂治理器,cap 收敛到上限以下,24 个请求全部完成。
  189. */
  190. describe("workflow concurrency — Start Plan 3008 在 workflow 内是重试而不是失败", () => {
  191. it("6 子代理 × (1 turn + 3 工具请求):无一失败、cap 收敛、每个 3008 都紧跟一条 retry_scheduled", async () => {
  192. const governor = createWorkflowConcurrencyGovernor({ defaultConcurrency: DEFAULT_CONCURRENCY });
  193. const key = workflowConcurrencyKey({ providerId: "prov", modelId: "alpha" } as never);
  194. let inFlight = 0;
  195. let concurrencyLimited = 0;
  196. const runtime: AiSdkModelRuntime = {
  197. async generateText() {
  198. inFlight += 1;
  199. try {
  200. if (inFlight > PROVIDER_LIMIT) {
  201. concurrencyLimited += 1;
  202. throw new ProviderBusinessError({
  203. providerCode: "3008",
  204. providerId: "prov",
  205. providerKind: "openai-compatible",
  206. providerMessage: "user concurrency limit exceeded",
  207. responseStatus: 429,
  208. statusCode: 429,
  209. });
  210. }
  211. await new Promise((resolve) => setTimeout(resolve, 15));
  212. return {
  213. text: "ok",
  214. finishReason: "stop",
  215. usage: usage(1),
  216. totalUsage: usage(1),
  217. } as never;
  218. } finally {
  219. inFlight -= 1;
  220. }
  221. },
  222. streamText() {
  223. throw new Error("not used");
  224. },
  225. };
  226. const adapter = new AiSdkModelAdapter({
  227. // 有界预算故意给得很小:3008 若仍走分类器的 retryable:false,这里就会立刻失败。
  228. retry: { baseDelayMs: 5, jitter: false, maxAttempts: 2, maxDelayMs: 5 },
  229. runtime,
  230. });
  231. const model = adapter.createModel({
  232. providerId: "prov",
  233. modelId: "alpha",
  234. providerConfig: testProviderConfig("prov"),
  235. modelConfig: testModelConfig(),
  236. options: { maxOutputTokens: 32_000, reasoningLevel: "disabled" },
  237. });
  238. const events: ModelNetworkStatusEvent[] = [];
  239. const requests: Promise<unknown>[] = [];
  240. for (let actor = 0; actor < ACTORS; actor += 1) {
  241. const activity = createActorModelActivity({
  242. port: governor,
  243. runId: "run-start-plan",
  244. handlers: { onWaiting: () => {}, onExecuting: () => {} },
  245. });
  246. const statusSink: ModelStatusSink = { publish: (event) => void events.push(event) };
  247. const send = (querySource: string, toolCallId?: string) =>
  248. runWithModelInvocationContext(
  249. {
  250. metadata: { querySource, ...(toolCallId === undefined ? {} : { toolCallId }) },
  251. modelRequestAdmission: activity.admission as ModelRequestAdmission,
  252. // 预算走调用上下文(core 的 runtime 层按 taskType 绑定;这里直接给 workflow 档位)。
  253. modelRetryBudget: ModelRetryBudget.Unbounded,
  254. statusSink,
  255. },
  256. () => model.generateText({ messages: [{ role: "user", content: "Ping" }] }),
  257. );
  258. requests.push(send("workflow_child"));
  259. for (let tool = 0; tool < TOOL_REQUESTS_PER_ACTOR; tool += 1) {
  260. requests.push(send("web_search_tool", `tc-${actor}-${tool}`));
  261. }
  262. }
  263. const results = await Promise.allSettled(requests);
  264. // 无一失败:3008 在 workflow 内是重试,不是终止。
  265. expect(results.filter((result) => result.status === "rejected")).toEqual([]);
  266. expect(concurrencyLimited).toBeGreaterThan(0);
  267. // 治理器收到了信号:cap 收敛到天花板以下。
  268. const snapshot = governor.snapshot(key)!;
  269. expect(snapshot.cap).toBeLessThan(DEFAULT_CONCURRENCY);
  270. expect(snapshot.inFlight).toBe(0);
  271. // 每个 3008 都作为可重试失败 + 一条 retry_scheduled{rate_limited} 报出;没有终止型 failed。
  272. const failed = events.filter((event) => event.type === "model_request_failed");
  273. expect(failed.length).toBe(concurrencyLimited);
  274. expect(failed.every((event) => event.retryable === true)).toBe(true);
  275. const scheduled = events.filter((event) => event.type === "model_retry_scheduled");
  276. expect(scheduled.length).toBe(concurrencyLimited);
  277. expect(scheduled.every((event) => event.reason === "rate_limited")).toBe(true);
  278. });
  279. });