workflow-driver-concurrency.test.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. /**
  2. * driver 侧的自适应并发半身(docs/dynamic-workflow/concurrency.md「What the driver observes」,
  3. * v3 决策 43/44/46):
  4. * - per-actor `ModelRequestAdmission`:tryAcquire = tryAdmit;未命中由 runner 发 queued 事件、这里排队 admit;
  5. * - actor runtime 的 ModelNetworkStatus 会话事件按请求链聚合 → askExecuting / askWaiting(slot | backoff);
  6. * - 模型侧错误的收容(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md):确定性错误 → stopRun(ProviderStop);
  7. * context_exceeded → ContextLimit;瞬态 → 退避后续跑;非模型错误 → DriverError;
  8. * - run 级 stall 时钟(决策 4):20 分钟无一次成功 → runStalled 恰好一次;
  9. * - 端口缺席即 runtimeFactory 不收 admission。
  10. * 用最小 stub runtime(可控 executeTurn + 可注入会话事件),不跑真模型。
  11. */
  12. import { describe, expect, it, vi } from "vitest";
  13. import {
  14. SessionEventType,
  15. type ModelRequestAdmission,
  16. type ModelRequestAdmissionTicket,
  17. type SessionEvent,
  18. type SessionEventSink,
  19. } from "@zcode/contracts";
  20. import {
  21. InMemoryJournalStore,
  22. type ActorRef,
  23. type AskWaitInfo,
  24. type ConcurrencyChange,
  25. type InstanceRef,
  26. type RunStallInfo,
  27. type WorkflowError,
  28. type WorkflowReportSink,
  29. } from "@zcode/dynamic-workflow";
  30. import { createWorkflowEscalationRegistry } from "../src/app/workflow-escalation-registry.js";
  31. import { createAgentRuntimeWorkflowDriver } from "../src/app/workflow-driver.js";
  32. import {
  33. createRunStallClock,
  34. WORKFLOW_STALL_NOTIFY_AFTER_MS,
  35. } from "../src/app/workflow-driver-concurrency.js";
  36. import type { WorkflowConcurrencyPort } from "../src/app/workflow-concurrency-governor.js";
  37. import { fakeFileSystemPort, unsupportedExecutionPort } from "./workflow-driver.helpers.js";
  38. const RUN = "run-cc";
  39. const ACTOR: ActorRef = { siteId: "actor#1", ordinal: 1 };
  40. const INSTANCE: InstanceRef = { siteId: "ask#1", ordinal: 1 };
  41. const INSTANCE_2: InstanceRef = { siteId: "ask#1", ordinal: 2 };
  42. const MODEL = { providerId: "prov", modelId: "alpha" } as never;
  43. function stubRuntime(executeTurn: () => Promise<unknown>) {
  44. const sinks = new Set<SessionEventSink>();
  45. let sessionIdOfRuntime = "";
  46. const runtime = {
  47. subscribeCalls: 0,
  48. unsubscribeCalls: 0,
  49. executeTurn,
  50. subscribeEvents(sink: SessionEventSink) {
  51. runtime.subscribeCalls++;
  52. sinks.add(sink);
  53. return () => {
  54. runtime.unsubscribeCalls++;
  55. sinks.delete(sink);
  56. };
  57. },
  58. getModelRef: () => MODEL,
  59. closeBrowserSession: async () => {},
  60. /** 执行器在 handler 之前发的 ToolCallStarted(带解析后的副作用能力)。 */
  61. emitToolStarted(flags: Record<string, unknown>, sessionId = sessionIdOfRuntime) {
  62. const event = {
  63. id: "evt-tool",
  64. sessionId,
  65. type: SessionEventType.ToolCallStarted,
  66. timestamp: new Date(),
  67. traceId: "trace",
  68. sequenceNumber: 1,
  69. payload: { toolCallId: "tc", toolName: "Probe", startedAt: new Date(), ...flags },
  70. } as unknown as SessionEvent;
  71. for (const sink of sinks) void sink.onSessionEvent(event);
  72. },
  73. emitStatus(payload: Record<string, unknown>, sessionId = sessionIdOfRuntime) {
  74. const event = {
  75. id: "evt",
  76. sessionId,
  77. type: SessionEventType.ModelNetworkStatus,
  78. timestamp: new Date(),
  79. traceId: "trace",
  80. sequenceNumber: 1,
  81. payload: { model: MODEL, attempt: 1, maxAttempts: 0, ...payload },
  82. } as unknown as SessionEvent;
  83. for (const sink of sinks) void sink.onSessionEvent(event);
  84. },
  85. bind(sessionId: string) {
  86. sessionIdOfRuntime = sessionId;
  87. },
  88. };
  89. return runtime;
  90. }
  91. function recordingSink() {
  92. const calls = {
  93. waiting: [] as Array<{ instance: InstanceRef; info: AskWaitInfo }>,
  94. executing: [] as InstanceRef[],
  95. mutating: [] as InstanceRef[],
  96. failed: [] as Array<{ instance: InstanceRef; error: WorkflowError }>,
  97. concurrency: [] as ConcurrencyChange[],
  98. stopped: [] as WorkflowError[],
  99. stalled: [] as RunStallInfo[],
  100. };
  101. const sink: WorkflowReportSink = {
  102. askSubmitAttempted: () => {},
  103. askTurnEnded: () => {},
  104. askProgress: () => {},
  105. askStats: () => {},
  106. askFailed: (instance, error) => calls.failed.push({ instance, error }),
  107. askWaiting: (instance, info) => calls.waiting.push({ instance, info }),
  108. askExecuting: (instance) => calls.executing.push(instance),
  109. askMutating: (instance) => calls.mutating.push(instance),
  110. concurrencyChanged: (change) => calls.concurrency.push(change),
  111. stopRun: (error) => calls.stopped.push(error),
  112. runStalled: (info) => calls.stalled.push(info),
  113. };
  114. return { sink, calls };
  115. }
  116. /** 假时钟:`now` 可拨,`schedule` 只记录回调,由测试决定何时触发。 */
  117. function fakeClock() {
  118. const state = {
  119. now: 0,
  120. timers: [] as Array<{ callback: () => void; at: number; cancelled: boolean }>,
  121. };
  122. const clock = {
  123. now: () => state.now,
  124. schedule: (callback: () => void, delayMs: number) => {
  125. const timer = { callback, at: state.now + delayMs, cancelled: false };
  126. state.timers.push(timer);
  127. return () => {
  128. timer.cancelled = true;
  129. };
  130. },
  131. };
  132. /** 把时间拨到 `to`,触发到期且未撤的闹钟(按到期顺序)。 */
  133. const advanceTo = (to: number): void => {
  134. state.now = to;
  135. for (const timer of [...state.timers].sort((a, b) => a.at - b.at)) {
  136. if (timer.cancelled || timer.at > to) continue;
  137. timer.cancelled = true;
  138. timer.callback();
  139. }
  140. };
  141. const pending = () => state.timers.filter((timer) => !timer.cancelled);
  142. return { clock, state, advanceTo, pending };
  143. }
  144. function fakeTicket(): ModelRequestAdmissionTicket {
  145. return { publish: () => {}, release: () => {} };
  146. }
  147. /** 可控端口:`fast` 决定 tryAdmit 命中与否;admit 由测试兑现。 */
  148. function fakePort() {
  149. const state = {
  150. fast: true,
  151. tryAdmits: [] as Array<{ runId: string; key: string }>,
  152. admits: [] as Array<{
  153. runId: string;
  154. key: string;
  155. signal: AbortSignal;
  156. resolve: (t: ModelRequestAdmissionTicket) => void;
  157. }>,
  158. subscribes: [] as Array<{ runId: string; listener: (change: ConcurrencyChange) => void }>,
  159. unsubscribe: vi.fn(),
  160. };
  161. const port: WorkflowConcurrencyPort = {
  162. tryAdmit: (runId, key) => {
  163. state.tryAdmits.push({ runId, key });
  164. return state.fast ? fakeTicket() : undefined;
  165. },
  166. admit: (runId, key, signal) =>
  167. new Promise((resolve, reject) => {
  168. state.admits.push({ runId, key, signal, resolve });
  169. if (signal.aborted) reject(signal.reason ?? new Error("aborted"));
  170. else
  171. signal.addEventListener("abort", () => reject(signal.reason ?? new Error("aborted")), {
  172. once: true,
  173. });
  174. }),
  175. subscribe: (runId, listener) => {
  176. state.subscribes.push({ runId, listener });
  177. return state.unsubscribe;
  178. },
  179. // 上界登记是 launch 的事,driver 从不调用。
  180. setRunBound: () => {},
  181. clearRunBound: () => {},
  182. };
  183. return { port, state };
  184. }
  185. function makeDriver(input: {
  186. runtime: ReturnType<typeof stubRuntime>;
  187. concurrency?: WorkflowConcurrencyPort;
  188. clock?: ReturnType<typeof fakeClock>["clock"] & { stallAfterMs?: number; random?: () => number };
  189. }) {
  190. const { sink, calls } = recordingSink();
  191. const journal = new InMemoryJournalStore();
  192. journal.createRun({
  193. runId: RUN,
  194. caps: { maxConcurrency: 16 },
  195. spentTokens: 0,
  196. status: "running",
  197. });
  198. const factoryInputs: Array<{ modelRequestAdmission?: ModelRequestAdmission }> = [];
  199. const driver = createAgentRuntimeWorkflowDriver({
  200. journal,
  201. emit: () => {},
  202. escalationRegistry: createWorkflowEscalationRegistry(),
  203. executionPort: unsupportedExecutionPort(),
  204. fileSystemPort: fakeFileSystemPort({}),
  205. cwd: process.cwd(),
  206. runId: RUN,
  207. ...(input.concurrency === undefined ? {} : { concurrency: input.concurrency }),
  208. ...(input.clock === undefined ? {} : { clock: input.clock }),
  209. runtimeFactory: ({ sessionId, modelRequestAdmission }) => {
  210. factoryInputs.push(modelRequestAdmission === undefined ? {} : { modelRequestAdmission });
  211. input.runtime.bind(sessionId);
  212. return input.runtime as never;
  213. },
  214. })(sink);
  215. return { driver, calls, factoryInputs };
  216. }
  217. const flush = async (rounds = 8) => {
  218. for (let i = 0; i < rounds; i++) await Promise.resolve();
  219. };
  220. describe("workflow driver — waiting / executing 观察(§6,决策 38)", () => {
  221. it("首个 started → askExecuting;同一 ask 内再 started 不重发;completed 不改相位", async () => {
  222. const runtime = stubRuntime(() => new Promise(() => {}));
  223. const { driver, calls } = makeDriver({ runtime });
  224. const session = await driver.createActorSession(ACTOR, {});
  225. // 两个观察面各订阅一次:模型活动(waiting / executing)+ 工具活动(askMutating)。
  226. expect(runtime.subscribeCalls).toBe(2);
  227. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  228. runtime.emitStatus({ type: "model_request_started", attempt: 1 });
  229. expect(calls.executing).toEqual([INSTANCE]);
  230. runtime.emitStatus({ type: "model_request_completed", attempt: 1, durationMs: 10 });
  231. // 工具执行期间的下一个请求:相位仍是 executing,不重发。
  232. runtime.emitStatus({ type: "model_request_started", attempt: 1 });
  233. expect(calls.executing).toEqual([INSTANCE]);
  234. expect(calls.waiting).toEqual([]);
  235. });
  236. it("model_retry_scheduled → askWaiting(backoff);其后的 started → askExecuting(退避后的重试真的发出了)", async () => {
  237. const runtime = stubRuntime(() => new Promise(() => {}));
  238. const { driver, calls } = makeDriver({ runtime });
  239. const session = await driver.createActorSession(ACTOR, {});
  240. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  241. runtime.emitStatus({ type: "model_request_started", attempt: 1 });
  242. runtime.emitStatus({
  243. type: "model_retry_scheduled",
  244. reason: "rate_limited",
  245. delayMs: 20_000,
  246. nextAttempt: 2,
  247. retryAfterMs: 20_000,
  248. message: "429",
  249. });
  250. expect(calls.waiting).toEqual([
  251. {
  252. instance: INSTANCE,
  253. info: {
  254. cause: "backoff",
  255. reason: "rate_limited",
  256. attempt: 2,
  257. delayMs: 20_000,
  258. retryAfterMs: 20_000,
  259. },
  260. },
  261. ]);
  262. runtime.emitStatus({ type: "model_request_started", attempt: 2 });
  263. expect(calls.executing).toEqual([INSTANCE, INSTANCE]);
  264. // 再一次限流 + 重试:每一段等待都恰好一对 waiting / executing。
  265. runtime.emitStatus({
  266. type: "model_retry_scheduled",
  267. reason: "server_error",
  268. delayMs: 3000,
  269. nextAttempt: 3,
  270. message: "500",
  271. });
  272. expect(calls.waiting).toHaveLength(2);
  273. expect(calls.waiting[1]!.info).toEqual({
  274. cause: "backoff",
  275. reason: "server_error",
  276. attempt: 3,
  277. delayMs: 3000,
  278. });
  279. runtime.emitStatus({ type: "model_request_started", attempt: 3 });
  280. expect(calls.executing).toHaveLength(3);
  281. });
  282. it("signature repair / auth_refresh 不报;别的会话的事件忽略", async () => {
  283. const runtime = stubRuntime(() => new Promise(() => {}));
  284. const { driver, calls } = makeDriver({ runtime });
  285. const session = await driver.createActorSession(ACTOR, {});
  286. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  287. runtime.emitStatus({
  288. type: "model_retry_scheduled",
  289. reason: "reasoning_signature_repair",
  290. delayMs: 0,
  291. nextAttempt: 2,
  292. message: "repair",
  293. });
  294. runtime.emitStatus({
  295. type: "model_retry_scheduled",
  296. reason: "auth_refresh",
  297. delayMs: 0,
  298. nextAttempt: 2,
  299. message: "refresh",
  300. });
  301. runtime.emitStatus(
  302. {
  303. type: "model_retry_scheduled",
  304. reason: "server_error",
  305. delayMs: 4000,
  306. nextAttempt: 3,
  307. message: "500",
  308. },
  309. "some-other-session",
  310. );
  311. runtime.emitStatus({ type: "model_request_started" }, "some-other-session");
  312. expect(calls.waiting).toEqual([]);
  313. expect(calls.executing).toEqual([]);
  314. });
  315. it("每个 ask 重置:上一个 ask 的 executing 不带到下一个 ask 的首个请求上", async () => {
  316. const runtime = stubRuntime(() => new Promise(() => {}));
  317. const { driver, calls } = makeDriver({ runtime });
  318. const session = await driver.createActorSession(ACTOR, {});
  319. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  320. runtime.emitStatus({ type: "model_request_started" });
  321. driver.cancelAsk(INSTANCE);
  322. driver.startAsk(session, INSTANCE_2, { instructions: "again", typed: false });
  323. runtime.emitStatus({ type: "model_request_started" });
  324. expect(calls.executing).toEqual([INSTANCE, INSTANCE_2]);
  325. });
  326. it("没有在飞 ask 时不报;dispose 退订", async () => {
  327. const runtime = stubRuntime(() => new Promise(() => {}));
  328. const { driver, calls } = makeDriver({ runtime });
  329. await driver.createActorSession(ACTOR, {});
  330. runtime.emitStatus({ type: "model_request_started" });
  331. runtime.emitStatus({
  332. type: "model_retry_scheduled",
  333. reason: "rate_limited",
  334. delayMs: 2000,
  335. nextAttempt: 2,
  336. message: "429",
  337. });
  338. expect(calls.executing).toEqual([]);
  339. expect(calls.waiting).toEqual([]);
  340. driver.dispose?.();
  341. expect(runtime.unsubscribeCalls).toBe(2);
  342. });
  343. });
  344. describe("workflow driver — per-actor 准入(§4,决策 34/36)", () => {
  345. it("端口在场:runtimeFactory 收到 admission;tryAdmit 命中不发 waiting;订阅 run 级 cap 变化并扇出", async () => {
  346. const runtime = stubRuntime(() => new Promise(() => {}));
  347. const { port, state } = fakePort();
  348. const { driver, calls, factoryInputs } = makeDriver({ runtime, concurrency: port });
  349. expect(state.subscribes).toEqual([expect.objectContaining({ runId: RUN })]);
  350. const session = await driver.createActorSession(ACTOR, {});
  351. const admission = factoryInputs[0]!.modelRequestAdmission;
  352. expect(admission).toBeDefined();
  353. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  354. const ticket = await admission!.acquire({ model: MODEL });
  355. expect(ticket).toBeDefined();
  356. expect(state.tryAdmits).toEqual([{ runId: RUN, key: "prov/alpha" }]);
  357. expect(state.admits).toEqual([]);
  358. expect(calls.waiting).toEqual([]);
  359. const change: ConcurrencyChange = {
  360. key: "prov/alpha",
  361. previous: 8,
  362. next: 4,
  363. reason: "rate_limited",
  364. cooldownMs: 5000,
  365. };
  366. state.subscribes[0]!.listener(change);
  367. expect(calls.concurrency).toEqual([change]);
  368. driver.dispose?.();
  369. expect(state.unsubscribe).toHaveBeenCalledTimes(1);
  370. });
  371. it("tryAcquire = tryAdmit;未命中时 acquire 排队;waiting(slot) 由 runner 的 queued 事件报,不由包装发(决策 44)", async () => {
  372. const runtime = stubRuntime(() => new Promise(() => {}));
  373. const { port, state } = fakePort();
  374. state.fast = false;
  375. const { driver, calls, factoryInputs } = makeDriver({ runtime, concurrency: port });
  376. const session = await driver.createActorSession(ACTOR, {});
  377. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  378. const admission = factoryInputs[0]!.modelRequestAdmission!;
  379. expect(admission.tryAcquire!({ model: MODEL })).toBeUndefined();
  380. expect(state.tryAdmits).toEqual([{ runId: RUN, key: "prov/alpha" }]);
  381. // 包装本身不再报 waiting:那是 runner 看到 tryAcquire 未命中后发 queued 事件的事。
  382. expect(calls.waiting).toEqual([]);
  383. runtime.emitStatus({ type: "model_request_queued", toolCallId: "tc-1" });
  384. expect(calls.waiting).toEqual([{ instance: INSTANCE, info: { cause: "slot" } }]);
  385. const signal = new AbortController().signal;
  386. const pending = admission.acquire({ model: MODEL, signal });
  387. await flush();
  388. expect(state.admits).toHaveLength(1);
  389. expect(state.admits[0]).toMatchObject({ runId: RUN, key: "prov/alpha", signal });
  390. state.admits[0]!.resolve(fakeTicket());
  391. await pending;
  392. // 拿到票:admitted 即 executing(持槽),随后的 started 不重发。
  393. runtime.emitStatus({ type: "model_request_admitted", queuedMs: 5, toolCallId: "tc-1" });
  394. runtime.emitStatus({ type: "model_request_started", toolCallId: "tc-1" });
  395. expect(calls.executing).toEqual([INSTANCE]);
  396. state.fast = true;
  397. expect(admission.tryAcquire!({ model: MODEL })).toBeDefined();
  398. });
  399. it("等槽位中 signal abort → acquire reject", async () => {
  400. const runtime = stubRuntime(() => new Promise(() => {}));
  401. const { port, state } = fakePort();
  402. state.fast = false;
  403. const { driver, factoryInputs } = makeDriver({ runtime, concurrency: port });
  404. await driver.createActorSession(ACTOR, {});
  405. const controller = new AbortController();
  406. const pending = factoryInputs[0]!.modelRequestAdmission!.acquire({
  407. model: MODEL,
  408. signal: controller.signal,
  409. });
  410. await flush();
  411. controller.abort(new Error("cancelled"));
  412. await expect(pending).rejects.toThrow("cancelled");
  413. });
  414. it("端口缺席:runtimeFactory 不收 admission", async () => {
  415. const runtime = stubRuntime(() => new Promise(() => {}));
  416. const { driver, factoryInputs } = makeDriver({ runtime });
  417. await driver.createActorSession(ACTOR, {});
  418. expect(factoryInputs).toEqual([{}]);
  419. });
  420. });
  421. describe("workflow driver — 按请求链聚合的子代理相位(v3 决策 46)", () => {
  422. const turn = (extra: Record<string, unknown> = {}) => ({
  423. queryId: "q-1",
  424. querySource: "workflow_child",
  425. ...extra,
  426. });
  427. const tool = (id: string, extra: Record<string, unknown> = {}) => ({
  428. queryId: "q-1",
  429. querySource: "web_search_tool",
  430. toolCallId: id,
  431. ...extra,
  432. });
  433. it("一条链在执行时另一条链排队不报 waiting;执行链结束、只剩等待者 → 报最新的等待", async () => {
  434. const runtime = stubRuntime(() => new Promise(() => {}));
  435. const { driver, calls } = makeDriver({ runtime });
  436. const session = await driver.createActorSession(ACTOR, {});
  437. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  438. runtime.emitStatus({ type: "model_request_started", ...turn() });
  439. expect(calls.executing).toEqual([INSTANCE]);
  440. runtime.emitStatus({ type: "model_request_queued", ...tool("tc-a") });
  441. expect(calls.waiting).toEqual([]);
  442. // turn 请求完成:集合只剩排队中的工具链,子代理此刻才真的在等。
  443. runtime.emitStatus({ type: "model_request_completed", ...turn({ durationMs: 10 }) });
  444. expect(calls.waiting).toEqual([{ instance: INSTANCE, info: { cause: "slot" } }]);
  445. // 工具链拿到票:executing 重新报一次。
  446. runtime.emitStatus({ type: "model_request_admitted", queuedMs: 40, ...tool("tc-a") });
  447. expect(calls.executing).toEqual([INSTANCE, INSTANCE]);
  448. });
  449. it("重试换 requestId 仍是同一条链:backoff → 下一次尝试 started 不留幽灵等待者", async () => {
  450. const runtime = stubRuntime(() => new Promise(() => {}));
  451. const { driver, calls } = makeDriver({ runtime });
  452. const session = await driver.createActorSession(ACTOR, {});
  453. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  454. runtime.emitStatus({ type: "model_request_started", requestId: "r-1", ...turn() });
  455. runtime.emitStatus({
  456. type: "model_request_failed",
  457. requestId: "r-1",
  458. reason: "rate_limited",
  459. retryable: true,
  460. message: "429",
  461. ...turn(),
  462. });
  463. runtime.emitStatus({
  464. type: "model_retry_scheduled",
  465. requestId: "r-1",
  466. reason: "rate_limited",
  467. delayMs: 2000,
  468. nextAttempt: 2,
  469. message: "429",
  470. ...turn(),
  471. });
  472. expect(calls.waiting).toHaveLength(1);
  473. runtime.emitStatus({ type: "model_request_started", requestId: "r-2", attempt: 2, ...turn() });
  474. expect(calls.executing).toEqual([INSTANCE, INSTANCE]);
  475. runtime.emitStatus({
  476. type: "model_request_completed",
  477. requestId: "r-2",
  478. attempt: 2,
  479. durationMs: 5,
  480. ...turn(),
  481. });
  482. // 集合为空:保持上一相位,不发任何事件。之后一条工具链排队 → 真正在等。
  483. expect(calls.waiting).toHaveLength(1);
  484. runtime.emitStatus({ type: "model_request_queued", ...tool("tc-b") });
  485. expect(calls.waiting).toHaveLength(2);
  486. expect(calls.waiting[1]!.info).toEqual({ cause: "slot" });
  487. });
  488. it("两条工具链并行:一条 executing 另一条 backoff 不报;两条都在等才报,再 started 才 executing", async () => {
  489. const runtime = stubRuntime(() => new Promise(() => {}));
  490. const { driver, calls } = makeDriver({ runtime });
  491. const session = await driver.createActorSession(ACTOR, {});
  492. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  493. runtime.emitStatus({ type: "model_request_started", ...tool("tc-1") });
  494. runtime.emitStatus({ type: "model_request_started", ...tool("tc-2") });
  495. expect(calls.executing).toEqual([INSTANCE]);
  496. runtime.emitStatus({
  497. type: "model_retry_scheduled",
  498. reason: "rate_limited",
  499. delayMs: 1500,
  500. nextAttempt: 2,
  501. message: "429",
  502. ...tool("tc-2"),
  503. });
  504. expect(calls.waiting).toEqual([]);
  505. runtime.emitStatus({
  506. type: "model_retry_scheduled",
  507. reason: "rate_limited",
  508. delayMs: 3000,
  509. nextAttempt: 2,
  510. message: "429",
  511. ...tool("tc-1"),
  512. });
  513. expect(calls.waiting).toEqual([
  514. {
  515. instance: INSTANCE,
  516. info: { cause: "backoff", reason: "rate_limited", attempt: 2, delayMs: 3000 },
  517. },
  518. ]);
  519. runtime.emitStatus({ type: "model_request_started", attempt: 2, ...tool("tc-2") });
  520. expect(calls.executing).toEqual([INSTANCE, INSTANCE]);
  521. // 不可重试的失败结束一条链;另一条仍在执行,不报。
  522. runtime.emitStatus({
  523. type: "model_request_failed",
  524. reason: "auth_failed",
  525. retryable: false,
  526. message: "401",
  527. ...tool("tc-1"),
  528. });
  529. expect(calls.waiting).toHaveLength(1);
  530. });
  531. it("同一段等待里内容相同的等待只报一次(决策 49):四条并行工具链同时排队 → 一条 waiting(slot)", async () => {
  532. const runtime = stubRuntime(() => new Promise(() => {}));
  533. const { driver, calls } = makeDriver({ runtime });
  534. const session = await driver.createActorSession(ACTOR, {});
  535. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  536. for (const id of ["tc-1", "tc-2", "tc-3", "tc-4"]) {
  537. runtime.emitStatus({ type: "model_request_queued", ...tool(id) });
  538. }
  539. expect(calls.waiting).toEqual([{ instance: INSTANCE, info: { cause: "slot" } }]);
  540. // 内容不同的等待(退避)仍照报:相位信息变了。
  541. runtime.emitStatus({
  542. type: "model_retry_scheduled",
  543. reason: "rate_limited",
  544. delayMs: 1500,
  545. nextAttempt: 2,
  546. message: "429",
  547. ...tool("tc-1"),
  548. });
  549. expect(calls.waiting).toHaveLength(2);
  550. // 一条链拿到票 → executing;它完成后只剩等待者 → 同样的 slot 等待再报一次(新的一段等待)。
  551. runtime.emitStatus({ type: "model_request_admitted", queuedMs: 30, ...tool("tc-2") });
  552. expect(calls.executing).toEqual([INSTANCE]);
  553. runtime.emitStatus({ type: "model_request_completed", durationMs: 5, ...tool("tc-2") });
  554. expect(calls.waiting).toHaveLength(3);
  555. expect(calls.waiting[2]!.info).toMatchObject({ cause: "backoff" });
  556. // 最新等待信息从 backoff 变回 slot:报一次;紧随其后的同样 queued 不再重复。
  557. runtime.emitStatus({ type: "model_request_queued", ...tool("tc-5") });
  558. runtime.emitStatus({ type: "model_request_queued", ...tool("tc-6") });
  559. expect(calls.waiting).toHaveLength(4);
  560. expect(calls.waiting[3]!.info).toEqual({ cause: "slot" });
  561. });
  562. });
  563. describe("workflow driver — 模型侧错误的收容(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md)", () => {
  564. const adapterError = (context: Record<string, unknown>, message = "Model request failed") =>
  565. Object.assign(new Error(message), {
  566. name: "AiSdkModelAdapterError",
  567. code: "model_request_failed",
  568. context,
  569. });
  570. it("确定性错误(auth_failed)→ stopRun(ProviderStop) 携结构化明细,不结算节点", async () => {
  571. const runtime = stubRuntime(() =>
  572. Promise.reject(
  573. adapterError(
  574. {
  575. reason: "auth_failed",
  576. providerId: "prov",
  577. modelId: "alpha",
  578. providerCode: "1006",
  579. retryable: false,
  580. },
  581. "[1006] token expired",
  582. ),
  583. ),
  584. );
  585. const { driver, calls } = makeDriver({ runtime });
  586. const session = await driver.createActorSession(ACTOR, { name: "verifier" });
  587. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  588. await flush();
  589. expect(calls.failed).toEqual([]);
  590. expect(calls.stopped).toHaveLength(1);
  591. const error = calls.stopped[0]!;
  592. expect(error.code).toBe("ProviderStop");
  593. expect(error.providerStop).toEqual({
  594. kind: "auth",
  595. reason: "auth_failed",
  596. subagent: "actor#1@1",
  597. subagentName: "verifier",
  598. providerId: "prov",
  599. modelId: "alpha",
  600. providerCode: "1006",
  601. rawMessage: "[1006] token expired",
  602. });
  603. expect(error.message).toContain("verifier");
  604. expect(error.message).toContain("[1006]");
  605. expect(error.toJSON().providerStop?.kind).toBe("auth");
  606. });
  607. it("配额码(1308)→ stop/quota;包了一层 cause 时仍能读到", async () => {
  608. const inner = adapterError(
  609. { reason: "rate_limited", providerCode: "1308", retryable: false },
  610. "[1308] usage cap reached",
  611. );
  612. const runtime = stubRuntime(() => Promise.reject(new Error("turn failed", { cause: inner })));
  613. const { driver, calls } = makeDriver({ runtime });
  614. const session = await driver.createActorSession(ACTOR, {});
  615. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  616. await flush();
  617. expect(calls.stopped[0]?.providerStop).toMatchObject({ kind: "quota", providerCode: "1308" });
  618. // 匿名 actor:没有 subagentName,subagent 仍是结构化 ref。
  619. expect(calls.stopped[0]?.providerStop?.subagent).toBe("actor#1@1");
  620. expect("subagentName" in calls.stopped[0]!.providerStop!).toBe(false);
  621. });
  622. it("context_exceeded → askFailed(ContextLimit)(脚本可 catch,未 catch 则 errored)", async () => {
  623. const runtime = stubRuntime(() =>
  624. Promise.reject(adapterError({ reason: "context_exceeded", retryable: false })),
  625. );
  626. const { driver, calls } = makeDriver({ runtime });
  627. const session = await driver.createActorSession(ACTOR, {});
  628. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  629. await flush();
  630. expect(calls.stopped).toEqual([]);
  631. expect(calls.failed).toHaveLength(1);
  632. expect(calls.failed[0]!.error.code).toBe("ContextLimit");
  633. expect(calls.failed[0]!.error.message).toContain("context window");
  634. });
  635. it("非模型错误 → DriverError(不带任何模型归因字段)", async () => {
  636. const runtime = stubRuntime(() => Promise.reject(new Error("script bug")));
  637. const { driver, calls } = makeDriver({ runtime });
  638. const session = await driver.createActorSession(ACTOR, {});
  639. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  640. await flush();
  641. expect(calls.stopped).toEqual([]);
  642. expect(calls.failed).toHaveLength(1);
  643. expect(calls.failed[0]!.error.code).toBe("DriverError");
  644. expect(calls.failed[0]!.error.message).toBe("Subagent turn failed: script bug");
  645. expect("providerStop" in calls.failed[0]!.error.toJSON()).toBe(false);
  646. });
  647. it("瞬态错误(runner 放过来的残余路径)→ askWaiting(backoff) 后续跑,不结算节点", async () => {
  648. const { clock, pending, advanceTo } = fakeClock();
  649. let turns = 0;
  650. const inputs: string[] = [];
  651. const runtime = stubRuntime(() => {
  652. turns += 1;
  653. return turns === 1
  654. ? Promise.reject(adapterError({ reason: "network_error", retryable: true }, "ECONNRESET"))
  655. : Promise.resolve({ response: "done", events: [], usage: undefined });
  656. });
  657. const originalExecute = runtime.executeTurn;
  658. runtime.executeTurn = ((input: string, ...rest: unknown[]) => {
  659. inputs.push(input);
  660. return (originalExecute as (...args: unknown[]) => Promise<unknown>)(input, ...rest);
  661. }) as never;
  662. const { driver, calls } = makeDriver({ runtime, clock: { ...clock, random: () => 1 } });
  663. const session = await driver.createActorSession(ACTOR, {});
  664. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  665. await flush();
  666. // 不结算、不停止:报一条 backoff 等待(attempt 1,2s 曲线起点,无抖动时恰为 2000)。
  667. expect(calls.failed).toEqual([]);
  668. expect(calls.stopped).toEqual([]);
  669. expect(calls.waiting).toEqual([
  670. {
  671. instance: INSTANCE,
  672. info: { cause: "backoff", reason: "network_error", attempt: 1, delayMs: 2000 },
  673. },
  674. ]);
  675. expect(pending()).toHaveLength(1);
  676. expect(turns).toBe(1);
  677. // 闹钟响:同一持久 runtime 上的一轮续跑 turn。
  678. advanceTo(2000);
  679. await flush();
  680. expect(turns).toBe(2);
  681. expect(inputs[1]).toContain("continue from where you left off");
  682. });
  683. it("瞬态错误带 Retry-After 时等它;等待期间 ask 被取消则不再续跑", async () => {
  684. const { clock, pending, advanceTo } = fakeClock();
  685. let turns = 0;
  686. const runtime = stubRuntime(() => {
  687. turns += 1;
  688. return Promise.reject(
  689. adapterError({ reason: "rate_limited", retryable: true, retryAfterMs: 30_000 }, "429"),
  690. );
  691. });
  692. const { driver, calls } = makeDriver({ runtime, clock });
  693. const session = await driver.createActorSession(ACTOR, {});
  694. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  695. await flush();
  696. expect(calls.waiting[0]!.info).toEqual({
  697. cause: "backoff",
  698. reason: "rate_limited",
  699. attempt: 1,
  700. delayMs: 30_000,
  701. retryAfterMs: 30_000,
  702. });
  703. driver.cancelAsk(INSTANCE);
  704. expect(pending()).toHaveLength(0);
  705. advanceTo(60_000);
  706. await flush();
  707. expect(turns).toBe(1);
  708. });
  709. });
  710. describe("run 级 stall 时钟(决策 4)", () => {
  711. it("20 分钟内没有一次成功、且排定过重试 → onStalled 恰好一次,带占多数的 reason 与 cap", () => {
  712. const { clock, advanceTo } = fakeClock();
  713. const stalled: RunStallInfo[] = [];
  714. const stall = createRunStallClock({ ...clock, onStalled: (info) => stalled.push(info) });
  715. stall.noteCap(4);
  716. advanceTo(60_000);
  717. stall.noteRetryScheduled("rate_limited");
  718. stall.noteRetryScheduled("network_error");
  719. stall.noteRetryScheduled("rate_limited");
  720. advanceTo(WORKFLOW_STALL_NOTIFY_AFTER_MS - 1);
  721. expect(stalled).toEqual([]);
  722. advanceTo(WORKFLOW_STALL_NOTIFY_AFTER_MS);
  723. expect(stalled).toEqual([
  724. { sinceMs: WORKFLOW_STALL_NOTIFY_AFTER_MS, reason: "rate_limited", cap: 4 },
  725. ]);
  726. // 同一段里再多的重试也不再通知。
  727. stall.noteRetryScheduled("rate_limited");
  728. advanceTo(WORKFLOW_STALL_NOTIFY_AFTER_MS * 3);
  729. expect(stalled).toHaveLength(1);
  730. });
  731. it("一次成功归零并重新上膛:时钟量的是「距上次成功」,不是「距首次重试」", () => {
  732. const { clock, advanceTo } = fakeClock();
  733. const stalled: RunStallInfo[] = [];
  734. const stall = createRunStallClock({ ...clock, onStalled: (info) => stalled.push(info) });
  735. stall.noteRetryScheduled("server_error");
  736. advanceTo(10 * 60_000);
  737. stall.noteSuccess();
  738. advanceTo(25 * 60_000);
  739. // 成功之后没有新的重试:不是 stall(哪怕已经 15 分钟没成功)。
  740. expect(stalled).toEqual([]);
  741. // 25 分钟时排定重试:距上次成功(10 分钟)已 15 分钟,再过 5 分钟就满 20 分钟。
  742. stall.noteRetryScheduled("server_error");
  743. advanceTo(30 * 60_000 - 1);
  744. expect(stalled).toEqual([]);
  745. advanceTo(30 * 60_000);
  746. expect(stalled).toEqual([{ sinceMs: WORKFLOW_STALL_NOTIFY_AFTER_MS, reason: "server_error" }]);
  747. });
  748. it("没有重试就没有 stall;dispose 撤闹钟", () => {
  749. const { clock, advanceTo, pending } = fakeClock();
  750. const stalled: RunStallInfo[] = [];
  751. const stall = createRunStallClock({ ...clock, onStalled: (info) => stalled.push(info) });
  752. advanceTo(WORKFLOW_STALL_NOTIFY_AFTER_MS * 2);
  753. expect(stalled).toEqual([]);
  754. stall.noteRetryScheduled("timeout");
  755. expect(pending()).toHaveLength(1);
  756. stall.dispose();
  757. expect(pending()).toHaveLength(0);
  758. advanceTo(WORKFLOW_STALL_NOTIFY_AFTER_MS * 4);
  759. expect(stalled).toEqual([]);
  760. });
  761. it("driver 接线:actor 的 retry_scheduled 上膛、completed 归零,到点经 sink.runStalled 报出", async () => {
  762. const { clock, advanceTo } = fakeClock();
  763. const runtime = stubRuntime(() => new Promise(() => {}));
  764. const { driver, calls } = makeDriver({ runtime, clock: { ...clock, stallAfterMs: 1_000 } });
  765. const session = await driver.createActorSession(ACTOR, {});
  766. driver.startAsk(session, INSTANCE, { instructions: "go", typed: false });
  767. runtime.emitStatus({ type: "model_request_started", attempt: 1 });
  768. runtime.emitStatus({
  769. type: "model_retry_scheduled",
  770. reason: "rate_limited",
  771. delayMs: 500,
  772. nextAttempt: 2,
  773. message: "429",
  774. });
  775. advanceTo(999);
  776. expect(calls.stalled).toEqual([]);
  777. advanceTo(1_000);
  778. expect(calls.stalled).toEqual([{ sinceMs: 1_000, reason: "rate_limited" }]);
  779. // 一次成功归零;之后再重试要重新等满。
  780. runtime.emitStatus({ type: "model_request_completed", attempt: 2, durationMs: 10 });
  781. runtime.emitStatus({
  782. type: "model_retry_scheduled",
  783. reason: "rate_limited",
  784. delayMs: 500,
  785. nextAttempt: 3,
  786. message: "429",
  787. });
  788. advanceTo(1_999);
  789. expect(calls.stalled).toHaveLength(1);
  790. advanceTo(2_000);
  791. expect(calls.stalled).toHaveLength(2);
  792. driver.dispose();
  793. });
  794. });
  795. // ── 工具活动观察(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Amend-resume」)──
  796. describe("workflow driver — askMutating 观察(子代理的第一笔工作区写入)", () => {
  797. it("在飞 ask 的子代理发出会改写工作区的 ToolCallStarted → askMutating 一次;只读工具不算;换 ask 再报一次", async () => {
  798. const runtime = stubRuntime(() => new Promise(() => {}));
  799. const { driver, calls } = makeDriver({ runtime });
  800. const session = await driver.createActorSession(ACTOR, { name: "fixer" });
  801. driver.startAsk(session, INSTANCE, { instructions: "fix", typed: false });
  802. await flush();
  803. runtime.emitToolStarted({ toolName: "Read", readOnly: true, sideEffectScope: "none" });
  804. runtime.emitToolStarted({ toolName: "Bash", readOnly: true, sideEffectScope: "none" });
  805. expect(calls.mutating).toEqual([]);
  806. runtime.emitToolStarted({ toolName: "Write", readOnly: false, sideEffectScope: "workspace" });
  807. runtime.emitToolStarted({ toolName: "Edit", readOnly: false, sideEffectScope: "workspace" });
  808. expect(calls.mutating).toEqual([INSTANCE]);
  809. // 第二个 ask:观察面归零,第一笔写入再报一次,且点的是新实例。
  810. driver.cancelAsk(INSTANCE);
  811. driver.startAsk(session, INSTANCE_2, { instructions: "fix again", typed: false });
  812. await flush();
  813. runtime.emitToolStarted({ toolName: "Bash", readOnly: false, sideEffectScope: "system" });
  814. expect(calls.mutating).toEqual([INSTANCE, INSTANCE_2]);
  815. });
  816. it("没有在飞 ask(已取消 / 尚未开始)时的写入不上报——迟到的观察对结算过的 ask 没有意义", async () => {
  817. const runtime = stubRuntime(() => new Promise(() => {}));
  818. const { driver, calls } = makeDriver({ runtime });
  819. const session = await driver.createActorSession(ACTOR, { name: "fixer" });
  820. runtime.emitToolStarted({ toolName: "Write", readOnly: false, sideEffectScope: "workspace" });
  821. expect(calls.mutating).toEqual([]);
  822. driver.startAsk(session, INSTANCE, { instructions: "fix", typed: false });
  823. await flush();
  824. driver.cancelAsk(INSTANCE);
  825. runtime.emitToolStarted({ toolName: "Write", readOnly: false, sideEffectScope: "workspace" });
  826. expect(calls.mutating).toEqual([]);
  827. });
  828. });