dynamic-workflow-quota-resume.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /**
  2. * 额度停止的 run 到点自动续跑(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md
  3. * 「Resuming after a quota reset」)。
  4. *
  5. * 唯一数据源是 journal 的 run 行;定时器只是唤醒,到点重新读行再决定。这里用假时钟与假 journal
  6. * 钉住:冷启动扫描、本进程结算后排定、到点复核、行变了不续跑、重置时刻不前进不再续跑、dispose,
  7. * 以及 MR !3072 评审补的两条:journal 读失败不逃出回调(CR-01)、瞬态拒绝有界补做(SG-01)。
  8. */
  9. import { describe, expect, it, vi } from "vitest";
  10. import type { DynamicWorkflowRunResumeResult } from "@zcode/contracts";
  11. import type { RunRecord } from "@zcode/dynamic-workflow";
  12. import {
  13. WORKFLOW_QUOTA_RESUME_MARGIN_MS,
  14. WORKFLOW_QUOTA_RESUME_MAX_SPACING_MS,
  15. WORKFLOW_QUOTA_RESUME_MIN_SPACING_MS,
  16. WORKFLOW_QUOTA_RESUME_RETRY_LIMIT,
  17. startWorkflowQuotaAutoResume,
  18. } from "../src/app/dynamic-workflow-quota-resume.js";
  19. const SESSION = "sess-quota";
  20. const HOUR = 60 * 60 * 1000;
  21. /** 从 resetAt 起按余量逐步推进 steps 个余量:补做定时器是在触发中、相对当时的时钟排的。 */
  22. async function stepThrough(
  23. h: { advanceTo(at: number): Promise<void> },
  24. resetAt: number,
  25. steps: number,
  26. ): Promise<void> {
  27. for (let step = 1; step <= steps; step += 1) {
  28. await h.advanceTo(resetAt + step * WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  29. }
  30. }
  31. /** 让 resume 的 promise 链(含 Promise.resolve 包装与 then 回调)走完。 */
  32. async function flush(): Promise<void> {
  33. for (let index = 0; index < 5; index += 1) await Promise.resolve();
  34. }
  35. function quotaStopped(runId: string, resetAt: number | undefined): RunRecord {
  36. return {
  37. runId,
  38. status: "stopped",
  39. stopReason: "provider",
  40. parentSessionId: SESSION,
  41. failure: {
  42. code: "ProviderStop",
  43. message: "quota",
  44. providerStop: {
  45. kind: "quota",
  46. reason: "rate_limited",
  47. providerCode: "1308",
  48. ...(resetAt === undefined ? {} : { resetAt }),
  49. },
  50. },
  51. } as unknown as RunRecord;
  52. }
  53. interface HarnessOptions {
  54. /** 缺省:把行改成 running 并回 ok(与真实 resume 的效果一致)。 */
  55. resume?: (runId: string) => Promise<DynamicWorkflowRunResumeResult>;
  56. }
  57. function harness(initial: RunRecord[] = [], options: HarnessOptions = {}) {
  58. let now = Date.parse("2026-10-19T08:00:00.000Z");
  59. const rows = new Map(initial.map((row) => [row.runId, row]));
  60. /** 置上后 getRun 抛它:模拟 journal 关闭、SQLite 句柄异常。 */
  61. let readError: Error | undefined;
  62. const logger = { warn: vi.fn(), info: vi.fn(), debug: vi.fn(), error: vi.fn() };
  63. const timers: { at: number; callback: () => void; cancelled: boolean }[] = [];
  64. const listeners: ((notice: { runId: string; liveRunCount: number }) => void)[] = [];
  65. const resumed: string[] = [];
  66. const clock = {
  67. now: () => now,
  68. schedule: (callback: () => void, delayMs: number) => {
  69. const timer = { at: now + delayMs, callback, cancelled: false };
  70. timers.push(timer);
  71. return () => {
  72. timer.cancelled = true;
  73. };
  74. },
  75. };
  76. const service = startWorkflowQuotaAutoResume({
  77. journal: {
  78. getRun: (runId: string) => {
  79. if (readError !== undefined) throw readError;
  80. return rows.get(runId);
  81. },
  82. listRunsByParentSession: (sessionId: string) =>
  83. [...rows.values()].filter((row) => row.parentSessionId === sessionId) as never,
  84. },
  85. parentSessionId: SESSION,
  86. subscribeRunSettled: (listener) => {
  87. listeners.push(listener);
  88. return () => {
  89. listeners.splice(listeners.indexOf(listener), 1);
  90. };
  91. },
  92. resume: async (runId) => {
  93. resumed.push(runId);
  94. if (options.resume !== undefined) return options.resume(runId);
  95. const row = rows.get(runId);
  96. if (row) rows.set(runId, { ...row, status: "running", stopReason: undefined } as RunRecord);
  97. return { ok: true, runId, status: "backgrounded" } as never;
  98. },
  99. clock,
  100. logger: logger as never,
  101. });
  102. /** 把时钟拨到 at,依次触发到期的定时器(触发中新排的也算)。 */
  103. const advanceTo = async (at: number) => {
  104. now = at;
  105. for (;;) {
  106. const due = timers.find((timer) => !timer.cancelled && timer.at <= now);
  107. if (due === undefined) break;
  108. due.cancelled = true;
  109. due.callback();
  110. await flush();
  111. }
  112. await flush();
  113. };
  114. const settle = (row: RunRecord) => {
  115. rows.set(row.runId, row);
  116. for (const listener of [...listeners]) listener({ runId: row.runId, liveRunCount: 0 });
  117. };
  118. /** 记下的事件名(info / warn 的第二个参数里的 event)。 */
  119. const events = () =>
  120. [...logger.info.mock.calls, ...logger.warn.mock.calls].map(
  121. (call) => (call[1] as { event?: string } | undefined)?.event,
  122. );
  123. return {
  124. advanceTo,
  125. events,
  126. failReads: (error: Error | undefined) => {
  127. readError = error;
  128. },
  129. listeners,
  130. logger,
  131. now: () => now,
  132. resumed,
  133. rows,
  134. service,
  135. settle,
  136. pendingTimers: () => timers.filter((timer) => !timer.cancelled),
  137. };
  138. }
  139. describe("workflow quota auto-resume", () => {
  140. it("resumes a run stopped by quota a margin after its reset time", async () => {
  141. const h = harness();
  142. const resetAt = h.now() + 2 * HOUR;
  143. h.settle(quotaStopped("run-a", resetAt));
  144. await h.advanceTo(resetAt + WORKFLOW_QUOTA_RESUME_MARGIN_MS - 1);
  145. expect(h.resumed).toEqual([]);
  146. await h.advanceTo(resetAt + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  147. expect(h.resumed).toEqual(["run-a"]);
  148. });
  149. it("on start, resumes the session's quota-stopped runs that are due, and arms the rest", async () => {
  150. const base = Date.parse("2026-10-19T08:00:00.000Z");
  151. const h = harness([
  152. quotaStopped("run-due", base - HOUR),
  153. quotaStopped("run-later", base + HOUR),
  154. { ...quotaStopped("run-other-session", base - HOUR), parentSessionId: "sess-x" },
  155. ]);
  156. await h.advanceTo(base);
  157. expect(h.resumed).toEqual(["run-due"]);
  158. await h.advanceTo(base + HOUR + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  159. expect(h.resumed).toEqual(["run-due", "run-later"]);
  160. });
  161. it("does nothing for a quota stop without a reset time, or a stop for another reason", async () => {
  162. const h = harness();
  163. h.settle(quotaStopped("run-no-reset", undefined));
  164. h.settle({
  165. ...quotaStopped("run-auth", h.now() + HOUR),
  166. failure: {
  167. code: "ProviderStop",
  168. message: "auth",
  169. providerStop: { kind: "auth", reason: "auth_failed", resetAt: h.now() + HOUR },
  170. },
  171. } as unknown as RunRecord);
  172. h.settle({ ...quotaStopped("run-user", h.now() + HOUR), stopReason: "user" } as RunRecord);
  173. await h.advanceTo(h.now() + 10 * HOUR);
  174. expect(h.resumed).toEqual([]);
  175. expect(h.pendingTimers()).toHaveLength(0);
  176. });
  177. it("re-reads the row when the timer fires: a run resumed or amended meanwhile is left alone", async () => {
  178. const h = harness();
  179. const resetAt = h.now() + HOUR;
  180. h.settle(quotaStopped("run-a", resetAt));
  181. h.rows.set("run-a", { ...h.rows.get("run-a")!, stopReason: "superseded" } as RunRecord);
  182. await h.advanceTo(resetAt + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  183. expect(h.resumed).toEqual([]);
  184. });
  185. it("does not resume again when the run stops on the same reset time", async () => {
  186. const h = harness();
  187. const resetAt = h.now() + HOUR;
  188. h.settle(quotaStopped("run-a", resetAt));
  189. await h.advanceTo(resetAt + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  190. expect(h.resumed).toEqual(["run-a"]);
  191. // provider 过了重置时刻仍拒绝、报同一个时刻:不再续跑,否则会一分钟一次地循环。
  192. h.settle(quotaStopped("run-a", resetAt));
  193. await h.advanceTo(h.now() + 10 * HOUR);
  194. expect(h.resumed).toEqual(["run-a"]);
  195. // 下一个窗口(重置时刻前进了)照常续跑。
  196. const nextReset = h.now() + HOUR;
  197. h.settle(quotaStopped("run-a", nextReset));
  198. await h.advanceTo(nextReset + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  199. expect(h.resumed).toEqual(["run-a", "run-a"]);
  200. });
  201. // MR !3072 第 2 轮评审 SG-01 引出的下限:额度停止回了个几秒的 Retry-After,重置时刻每次都「前进」,
  202. // 不循环规则挡不住;间隔逐次翻倍、封顶,避免每分钟续跑一次、撞额度一次。
  203. it("spaces repeated resumes of a run whose reset time keeps moving by seconds", async () => {
  204. const h = harness();
  205. const starts: number[] = [];
  206. let resetAt = h.now() + 5_000;
  207. h.settle(quotaStopped("run-a", resetAt));
  208. for (let round = 0; round < 6; round += 1) {
  209. // 推进到下一次续跑(逐分钟走,最多两小时)。
  210. const before = h.resumed.length;
  211. for (let step = 0; step < 120 && h.resumed.length === before; step += 1) {
  212. await h.advanceTo(h.now() + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  213. }
  214. expect(h.resumed.length).toBe(before + 1);
  215. starts.push(h.now());
  216. // 续跑后马上又撞额度,provider 又报「5 秒后重置」。
  217. resetAt = h.now() + 5_000;
  218. h.settle(quotaStopped("run-a", resetAt));
  219. }
  220. const gaps = starts.slice(1).map((at, index) => at - starts[index]!);
  221. const minute = WORKFLOW_QUOTA_RESUME_MARGIN_MS;
  222. // 第二次起:10、20、40 分钟,之后封顶 60 分钟(逐分钟推进,允许一分钟的粒度)。
  223. expect(WORKFLOW_QUOTA_RESUME_MIN_SPACING_MS).toBe(10 * minute);
  224. expect(WORKFLOW_QUOTA_RESUME_MAX_SPACING_MS).toBe(60 * minute);
  225. const expected = [10, 20, 40, 60, 60].map((minutes) => minutes * minute);
  226. gaps.forEach((gap, index) => {
  227. expect(gap).toBeGreaterThanOrEqual(expected[index]!);
  228. expect(gap).toBeLessThanOrEqual(expected[index]! + minute);
  229. });
  230. expect(h.events()).toContain("dynamic_workflow.quota_resume.scheduled");
  231. });
  232. it("does not delay a real next quota window, hours later", async () => {
  233. const h = harness();
  234. const first = h.now() + HOUR;
  235. h.settle(quotaStopped("run-a", first));
  236. await h.advanceTo(first + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  237. for (const hours of [5, 10]) {
  238. const next = first + hours * HOUR;
  239. h.settle(quotaStopped("run-a", next));
  240. await h.advanceTo(next + WORKFLOW_QUOTA_RESUME_MARGIN_MS - 1);
  241. const before = h.resumed.length;
  242. await h.advanceTo(next + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  243. expect(h.resumed.length).toBe(before + 1);
  244. }
  245. });
  246. it("keeps a reset more than 24 days away correct across the timer ceiling", async () => {
  247. const h = harness();
  248. const resetAt = h.now() + 30 * 24 * HOUR;
  249. h.settle(quotaStopped("run-monthly", resetAt));
  250. await h.advanceTo(h.now() + 25 * 24 * HOUR);
  251. expect(h.resumed).toEqual([]);
  252. await h.advanceTo(resetAt + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  253. expect(h.resumed).toEqual(["run-monthly"]);
  254. });
  255. it("stops listening and cancels its timers on dispose", async () => {
  256. const h = harness();
  257. const resetAt = h.now() + HOUR;
  258. h.settle(quotaStopped("run-a", resetAt));
  259. h.service.dispose();
  260. expect(h.listeners).toHaveLength(0);
  261. await h.advanceTo(resetAt + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  262. expect(h.resumed).toEqual([]);
  263. });
  264. it("logs and survives a refused resume", async () => {
  265. const warn = vi.fn();
  266. const rows = new Map([["run-a", quotaStopped("run-a", 0)]]);
  267. let fire: (() => void) | undefined;
  268. startWorkflowQuotaAutoResume({
  269. journal: { getRun: (runId: string) => rows.get(runId) },
  270. parentSessionId: SESSION,
  271. subscribeRunSettled: (listener) => {
  272. queueMicrotask(() => listener({ runId: "run-a", liveRunCount: 0 }));
  273. return () => {};
  274. },
  275. resume: async () => ({ ok: false, reason: "already_running" }) as never,
  276. clock: {
  277. now: () => WORKFLOW_QUOTA_RESUME_MARGIN_MS,
  278. schedule: (callback) => {
  279. fire = callback;
  280. return () => {};
  281. },
  282. },
  283. logger: { warn, info: vi.fn(), debug: vi.fn(), error: vi.fn() } as never,
  284. });
  285. await Promise.resolve();
  286. fire?.();
  287. await new Promise((resolve) => setTimeout(resolve, 0));
  288. expect(warn).toHaveBeenCalledWith(
  289. "Dynamic workflow quota auto-resume was refused",
  290. expect.objectContaining({ reason: "already_running", runId: "run-a" }),
  291. );
  292. });
  293. // CR-01:定时器回调与结算订阅里的 journal 读取失败,只记日志、本次不续跑,异常不逃出回调。
  294. it("survives a journal read that throws when the timer fires", async () => {
  295. const h = harness();
  296. const resetAt = h.now() + HOUR;
  297. h.settle(quotaStopped("run-a", resetAt));
  298. h.failReads(new Error(`SQLITE_MISUSE: database is closed ${"x".repeat(2_000)}`));
  299. await expect(h.advanceTo(resetAt + WORKFLOW_QUOTA_RESUME_MARGIN_MS)).resolves.toBeUndefined();
  300. expect(h.resumed).toEqual([]);
  301. expect(h.pendingTimers()).toHaveLength(0);
  302. const readFailed = h.logger.warn.mock.calls.find(
  303. (call) =>
  304. (call[1] as { event?: string }).event === "dynamic_workflow.quota_resume.read_failed",
  305. );
  306. expect(readFailed?.[1]).toMatchObject({ runId: "run-a" });
  307. // 日志里的错误文本截断过:存储异常可能带很长的上下文。
  308. const message = (readFailed?.[1] as { errorMessage: string }).errorMessage;
  309. expect(message.startsWith("SQLITE_MISUSE")).toBe(true);
  310. expect(message.length).toBeLessThanOrEqual(501);
  311. });
  312. it("survives a journal read that throws on run-settled", () => {
  313. const h = harness();
  314. h.failReads(new Error("database is closed"));
  315. expect(() => h.settle(quotaStopped("run-a", h.now() + HOUR))).not.toThrow();
  316. expect(h.pendingTimers()).toHaveLength(0);
  317. expect(h.events()).toContain("dynamic_workflow.quota_resume.read_failed");
  318. });
  319. // SG-01:瞬态拒绝(already_running)或 resume 抛错时有界补做;其余拒绝不补做。
  320. it("retries after a transient refusal and resumes", async () => {
  321. let calls = 0;
  322. const h = harness([], {
  323. resume: async (runId) => {
  324. calls += 1;
  325. if (calls === 1) return { ok: false, reason: "already_running" };
  326. return { ok: true, runId };
  327. },
  328. });
  329. const resetAt = h.now() + HOUR;
  330. h.settle(quotaStopped("run-a", resetAt));
  331. await h.advanceTo(resetAt + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  332. expect(h.resumed).toEqual(["run-a"]);
  333. expect(h.events()).toContain("dynamic_workflow.quota_resume.retry_scheduled");
  334. await h.advanceTo(resetAt + 2 * WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  335. expect(h.resumed).toEqual(["run-a", "run-a"]);
  336. expect(h.pendingTimers()).toHaveLength(0);
  337. });
  338. it("retries a resume that throws a bounded number of times, then gives up", async () => {
  339. const h = harness([], {
  340. resume: async () => {
  341. throw new Error("execution boundary failed");
  342. },
  343. });
  344. const resetAt = h.now() + HOUR;
  345. h.settle(quotaStopped("run-a", resetAt));
  346. await stepThrough(h, resetAt, 10);
  347. expect(h.resumed).toHaveLength(1 + WORKFLOW_QUOTA_RESUME_RETRY_LIMIT);
  348. expect(h.events()).toContain("dynamic_workflow.quota_resume.gave_up");
  349. expect(h.pendingTimers()).toHaveLength(0);
  350. });
  351. it("does not retry a refusal that says the run cannot be resumed", async () => {
  352. const h = harness([], {
  353. resume: async () => ({ ok: false, reason: "not_resumable" }),
  354. });
  355. const resetAt = h.now() + HOUR;
  356. h.settle(quotaStopped("run-a", resetAt));
  357. await stepThrough(h, resetAt, 10);
  358. expect(h.resumed).toEqual(["run-a"]);
  359. expect(h.pendingTimers()).toHaveLength(0);
  360. });
  361. it("re-reads the row on a retry: a run that started meanwhile is left alone", async () => {
  362. const rows: { current?: Map<string, RunRecord> } = {};
  363. const h = harness([], {
  364. resume: async (runId) => {
  365. // 用户同一时刻点了恢复:run 已在飞,自动续跑被拒为 already_running。
  366. const row = rows.current!.get(runId)!;
  367. rows.current!.set(runId, { ...row, status: "running", stopReason: undefined } as RunRecord);
  368. return { ok: false, reason: "already_running" };
  369. },
  370. });
  371. rows.current = h.rows;
  372. const resetAt = h.now() + HOUR;
  373. h.settle(quotaStopped("run-a", resetAt));
  374. await stepThrough(h, resetAt, 10);
  375. expect(h.resumed).toEqual(["run-a"]);
  376. expect(h.pendingTimers()).toHaveLength(0);
  377. });
  378. it("drops a pending retry when the run stops again on the same reset time", async () => {
  379. const rows: { current?: Map<string, RunRecord> } = {};
  380. const h = harness([], {
  381. resume: async (runId) => {
  382. // resume 报错,但 run 其实已经跑起来了(例如重臂追踪那一步失败)。
  383. const row = rows.current!.get(runId)!;
  384. rows.current!.set(runId, { ...row, status: "running", stopReason: undefined } as RunRecord);
  385. throw new Error("track failed");
  386. },
  387. });
  388. rows.current = h.rows;
  389. const resetAt = h.now() + HOUR;
  390. h.settle(quotaStopped("run-a", resetAt));
  391. await h.advanceTo(resetAt + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  392. expect(h.pendingTimers()).toHaveLength(1);
  393. // 补做到点前,run 又停在同一窗口:不前进,补做一并撤掉,不再撞一次额度。
  394. h.settle(quotaStopped("run-a", resetAt));
  395. expect(h.pendingTimers()).toHaveLength(0);
  396. await stepThrough(h, resetAt, 10);
  397. expect(h.resumed).toEqual(["run-a"]);
  398. });
  399. it("does not schedule a retry when disposed while a resume is in flight", async () => {
  400. let refuse: ((result: DynamicWorkflowRunResumeResult) => void) | undefined;
  401. const h = harness([], {
  402. resume: () =>
  403. new Promise((resolve) => {
  404. refuse = resolve;
  405. }),
  406. });
  407. const resetAt = h.now() + HOUR;
  408. h.settle(quotaStopped("run-a", resetAt));
  409. await h.advanceTo(resetAt + WORKFLOW_QUOTA_RESUME_MARGIN_MS);
  410. expect(h.resumed).toEqual(["run-a"]);
  411. h.service.dispose();
  412. refuse?.({ ok: false, reason: "already_running" });
  413. await flush();
  414. expect(h.pendingTimers()).toHaveLength(0);
  415. });
  416. });