workflow-driver-concurrency.test.ts 36 KB

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