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

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