replay-settle-order.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /**
  2. * Replay 的结算次序(docs/execution-engine.md「Replaying the settle order」)。
  3. *
  4. * 复现的是生产事故:扇出分支在 await 之后调 `report`,于是那些 report 的 ordinal 按**完成
  5. * 顺序**落库;resume 若按准入顺序释放缓存结算,同一个 ordinal 会落到另一条分支的 item 上,
  6. * run 以 InputHashMismatch 死在自己的防御性校验里,而脚本本身是纯的。
  7. */
  8. import { describe, expect, it } from "vitest";
  9. import {
  10. InMemoryJournalStore,
  11. WorkflowEngine,
  12. refToString,
  13. type AskSpec,
  14. type InstanceRef,
  15. type WorkflowDriver,
  16. } from "../../src/engine/index.js";
  17. import { ReplaySettleOrder, recoverSettleOrder } from "../../src/engine/replay-order.js";
  18. import { FakeDriver, flush } from "./fake-driver.js";
  19. const RUN = "run";
  20. const DIMS = ["alpha", "beta", "gamma"] as const;
  21. function inst(siteId: string, ordinal = 1): InstanceRef {
  22. return { siteId, ordinal };
  23. }
  24. const untypedSpecs = (...siteIds: string[]): Map<string, AskSpec> =>
  25. new Map(siteIds.map((id) => [id, { typed: false } as AskSpec]));
  26. function engineOver(journal: InMemoryJournalStore, driver: WorkflowDriver): WorkflowEngine {
  27. return new WorkflowEngine({
  28. runId: RUN,
  29. driver,
  30. caps: { maxConcurrency: 16 },
  31. askSpecs: untypedSpecs("ask#1", "ask#2"),
  32. validate: () => [],
  33. });
  34. }
  35. /**
  36. * 测试扮演沙箱脚本。一条扇出分支:建 actor、问一次、答案回来后报一条——`report#2` 的
  37. * ordinal 因此由**这条分支什么时候拿到答案**决定,正是事故的形状。
  38. */
  39. async function branch(engine: WorkflowEngine, dim: string): Promise<unknown> {
  40. const actor = engine.createActor("actor#1", `researcher-${dim}`);
  41. engine.report("report#1", { dim, status: "researching" });
  42. const answer = await engine.ask("ask#1", actor, `research ${dim}`);
  43. engine.report("report#2", { dim, status: "done" });
  44. return answer;
  45. }
  46. const fanOut = (engine: WorkflowEngine): Promise<unknown[]> =>
  47. Promise.all(DIMS.map((dim) => branch(engine, dim)));
  48. /** journal 里某个站点的行,按 ordinal 升序取结果。 */
  49. function rowsAt(journal: InMemoryJournalStore, siteId: string): unknown[] {
  50. return journal
  51. .listNodes(RUN, { kinds: "all", withResult: true })
  52. .filter((n) => n.siteId === siteId)
  53. .sort((a, b) => a.ordinal - b.ordinal)
  54. .map((n) => n.result);
  55. }
  56. describe("replay settle order — the fan-out report bug", () => {
  57. it("replays the journaled settle order, so ordinals after a join land where the journal has them", async () => {
  58. const journal = new InMemoryJournalStore();
  59. // ——— 第一世:三条分支并行,答案按 3、1 的顺序回来,第 2 条还在飞时进程被打断。———
  60. const driver1 = new FakeDriver(journal);
  61. const e1 = engineOver(journal, driver1);
  62. void fanOut(e1).catch(() => {}); // stop() 会以 Cancelled 拒绝这一世的扇出
  63. await flush();
  64. expect(driver1.startAskCount()).toBe(3);
  65. e1.askTurnEnded(inst("ask#1", 3), "r3");
  66. await flush();
  67. e1.askTurnEnded(inst("ask#1", 1), "r1");
  68. await flush();
  69. e1.stop("interrupted");
  70. await flush();
  71. // 完成顺序 = 3、1,report#2 的 ordinal 因此不是数组顺序。
  72. expect(rowsAt(journal, "report#2")).toEqual([
  73. { dim: "gamma", status: "done" },
  74. { dim: "alpha", status: "done" },
  75. ]);
  76. // report#1 在 await 之前,恒按数组顺序。
  77. expect(rowsAt(journal, "report#1")).toEqual([
  78. { dim: "alpha", status: "researching" },
  79. { dim: "beta", status: "researching" },
  80. { dim: "gamma", status: "researching" },
  81. ]);
  82. // ——— 第二世:同一份脚本、同一份 journal。———
  83. const driver2 = new FakeDriver(journal);
  84. const e2 = engineOver(journal, driver2);
  85. const replayed = fanOut(e2);
  86. await flush();
  87. // 缓存结算按记录的完成顺序释放,而不是准入顺序。
  88. expect(driver2.cachedSettleOrder()).toEqual(["ask#1@3", "ask#1@1"]);
  89. // 在飞的那一条重新 live 派发,其余零派发。
  90. expect(driver2.startedInstanceKeys()).toEqual(new Set(["ask#1@2"]));
  91. e2.askTurnEnded(inst("ask#1", 2), "r2");
  92. await expect(replayed).resolves.toEqual(["r1", "r2", "r3"]);
  93. // run 没有因为 InputHashMismatch 死掉,journal 里的 report 行一行没动。
  94. expect(journal.getRun(RUN)?.failure).toBeUndefined();
  95. expect(rowsAt(journal, "report#2")).toEqual([
  96. { dim: "gamma", status: "done" },
  97. { dim: "alpha", status: "done" },
  98. { dim: "beta", status: "done" },
  99. ]);
  100. // 重放命中的 report 静默跳过,只有这一世新跑到的那条发事件。
  101. expect(driver2.eventsOfType("report").map((e) => e.item)).toEqual([
  102. { dim: "beta", status: "done" },
  103. ]);
  104. e2.complete("done");
  105. await expect(e2.settled).resolves.toMatchObject({ status: "completed" });
  106. });
  107. it("keeps the same schedule on a third life", async () => {
  108. const journal = new InMemoryJournalStore();
  109. const driver1 = new FakeDriver(journal);
  110. const e1 = engineOver(journal, driver1);
  111. void fanOut(e1).catch(() => {}); // stop() 会以 Cancelled 拒绝这一世的扇出
  112. await flush();
  113. e1.askTurnEnded(inst("ask#1", 2), "r2");
  114. await flush();
  115. e1.askTurnEnded(inst("ask#1", 3), "r3");
  116. await flush();
  117. e1.stop("interrupted");
  118. await flush();
  119. // 第二世:两条命中、一条重跑并结算,再次被打断。
  120. const driver2 = new FakeDriver(journal);
  121. const e2 = engineOver(journal, driver2);
  122. void fanOut(e2).catch(() => {});
  123. await flush();
  124. expect(driver2.cachedSettleOrder()).toEqual(["ask#1@2", "ask#1@3"]);
  125. e2.askTurnEnded(inst("ask#1", 1), "r1");
  126. await flush();
  127. e2.stop("interrupted");
  128. await flush();
  129. // 第三世:三条全命中。首生次序(2、3)仍在前,第二世才跑完的 1 排在其后。
  130. const driver3 = new FakeDriver(journal);
  131. const e3 = engineOver(journal, driver3);
  132. const replayed = fanOut(e3);
  133. await flush();
  134. expect(driver3.cachedSettleOrder()).toEqual(["ask#1@2", "ask#1@3", "ask#1@1"]);
  135. expect(driver3.startAskCount()).toBe(0);
  136. await expect(replayed).resolves.toEqual(["r1", "r2", "r3"]);
  137. expect(journal.getRun(RUN)?.failure).toBeUndefined();
  138. expect(driver3.eventsOfType("report")).toEqual([]);
  139. });
  140. it("never leaves a parked hit hanging when the run settles mid-replay", async () => {
  141. // 闸门的兜底:队首那条还没被认领时 run 就被停了——挂着的命中必须照常兑现(否则脚本那侧
  142. // 的 promise 永不落地),而且它的 cached 事件要排在 `run-settled` **之前**。
  143. const journal = new InMemoryJournalStore();
  144. const driver1 = new FakeDriver(journal);
  145. const e1 = engineOver(journal, driver1);
  146. const one = e1.createActor("actor#1", "one");
  147. const two = e1.createActor("actor#1", "two");
  148. const p1 = e1.ask("ask#1", one, "A");
  149. const p2 = e1.ask("ask#1", two, "B");
  150. await flush();
  151. // 第二条先结算,于是记录的次序是 [ask#1@2, ask#1@1]。
  152. e1.askTurnEnded(inst("ask#1", 2), "rB");
  153. await flush();
  154. e1.askTurnEnded(inst("ask#1", 1), "rA");
  155. await expect(Promise.all([p1, p2])).resolves.toEqual(["rA", "rB"]);
  156. e1.stop("interrupted");
  157. await flush();
  158. // 第二世只跑到第一条就被停:它在等 ask#1@2 让位,谁也不会来认领了。
  159. const driver2 = new FakeDriver(journal);
  160. const e2 = engineOver(journal, driver2);
  161. const actor = e2.createActor("actor#1", "one");
  162. const replayed = e2.ask("ask#1", actor, "A");
  163. await flush();
  164. expect(driver2.cachedSettleOrder()).toEqual([]);
  165. e2.stop("user");
  166. await expect(replayed).resolves.toBe("rA");
  167. const types = driver2.events.map((e) => e.type);
  168. expect(types.indexOf("node-settled")).toBeLessThan(types.indexOf("run-settled"));
  169. });
  170. it("still fails loudly when the script really is nondeterministic", async () => {
  171. const journal = new InMemoryJournalStore();
  172. const driver1 = new FakeDriver(journal);
  173. const e1 = engineOver(journal, driver1);
  174. const actor1 = e1.createActor("actor#1", "one");
  175. const p1 = e1.ask("ask#1", actor1, "first instructions");
  176. await flush();
  177. e1.askTurnEnded(inst("ask#1"), "r1");
  178. await p1;
  179. e1.stop("interrupted");
  180. await flush();
  181. // 同一个站点、同一个 ordinal,指令变了——闸门放行之前的防御性校验照旧大声失败。
  182. const driver2 = new FakeDriver(journal);
  183. const e2 = engineOver(journal, driver2);
  184. const actor2 = e2.createActor("actor#1", "one");
  185. await expect(e2.ask("ask#1", actor2, "other instructions")).rejects.toMatchObject({
  186. code: "InputHashMismatch",
  187. });
  188. await expect(e2.settled).resolves.toMatchObject({ status: "errored" });
  189. });
  190. });
  191. describe("replay settle order — world reads and artifacts", () => {
  192. it("releases cached world reads in the journaled order", async () => {
  193. const journal = new InMemoryJournalStore();
  194. const seen: string[] = [];
  195. const script = async (engine: WorkflowEngine): Promise<void> => {
  196. await Promise.all(
  197. ["a", "b"].map(async (name) => {
  198. const files = await engine.worldRead("world#1", "glob", [name]);
  199. seen.push(String(files));
  200. engine.report("report#1", { name, files });
  201. }),
  202. );
  203. };
  204. const driver1 = new FakeDriver(journal);
  205. const e1 = engineOver(journal, driver1);
  206. void script(e1).catch(() => {});
  207. await flush();
  208. // 第二个 glob 先返回。
  209. driver1.worldReads[1]?.deferred.resolve("files-b");
  210. await flush();
  211. driver1.worldReads[0]?.deferred.resolve("files-a");
  212. await flush();
  213. expect(rowsAt(journal, "report#1")).toEqual([
  214. { name: "b", files: "files-b" },
  215. { name: "a", files: "files-a" },
  216. ]);
  217. e1.stop("interrupted");
  218. seen.length = 0;
  219. const driver2 = new FakeDriver(journal);
  220. const e2 = engineOver(journal, driver2);
  221. await script(e2);
  222. expect(driver2.worldReads).toEqual([]);
  223. expect(seen).toEqual(["files-b", "files-a"]);
  224. expect(journal.getRun(RUN)?.failure).toBeUndefined();
  225. expect(driver2.eventsOfType("report")).toEqual([]);
  226. });
  227. it("gates content artifacts and never waits on a preset declaration", async () => {
  228. const journal = new InMemoryJournalStore();
  229. const script = async (engine: WorkflowEngine): Promise<void> => {
  230. // 预置声明是同步 void:它落 journal 行、发 artifact-published,却永远不会来认领闸门。
  231. engine.declareArtifact("artifact#0", "board", [
  232. "board-1",
  233. { key: "dim", status: "status", columns: ["doing", "done"] },
  234. ]);
  235. await Promise.all(
  236. ["a", "b"].map(async (name) => {
  237. await engine.publishArtifact("artifact#1", "markdown", [`doc-${name}`, `# ${name}`]);
  238. engine.report("report#1", { name });
  239. }),
  240. );
  241. };
  242. const driver1 = new FakeDriver(journal, { deferArtifactPublishes: true });
  243. const e1 = engineOver(journal, driver1);
  244. void script(e1).catch(() => {});
  245. await flush();
  246. const [first, second] = driver1.artifactDeferrals;
  247. // 第二个发布先完成。
  248. second?.resolve(driver1.artifactStore.get("doc-b@1")!);
  249. await flush();
  250. first?.resolve(driver1.artifactStore.get("doc-a@1")!);
  251. await flush();
  252. expect(rowsAt(journal, "report#1")).toEqual([{ name: "b" }, { name: "a" }]);
  253. e1.stop("interrupted");
  254. const driver2 = new FakeDriver(journal, { deferArtifactPublishes: true });
  255. const e2 = engineOver(journal, driver2);
  256. await script(e2);
  257. expect(driver2.artifactPublishes).toEqual([]);
  258. expect(journal.getRun(RUN)?.failure).toBeUndefined();
  259. expect(driver2.eventsOfType("report")).toEqual([]);
  260. });
  261. });
  262. describe("ReplaySettleOrder", () => {
  263. const key = (siteId: string, ordinal: number): string => refToString({ siteId, ordinal });
  264. it("releases parked entries in the recorded order, never inside the call that parked one", async () => {
  265. const gate = new ReplaySettleOrder([key("ask#1", 2), key("ask#1", 1)]);
  266. const released: string[] = [];
  267. gate.hold(inst("ask#1", 1), () => released.push("1"));
  268. expect(released).toEqual([]);
  269. // 轮到了也**不在这次调用里**投递:调用方的 await 还没挂上去(见 enqueue 的说明)。
  270. gate.hold(inst("ask#1", 2), () => released.push("2"));
  271. expect(released).toEqual([]);
  272. await flush();
  273. expect(released).toEqual(["2", "1"]);
  274. });
  275. it("passes through instances it has no entry for", () => {
  276. const gate = new ReplaySettleOrder([key("ask#1", 1)]);
  277. const released: string[] = [];
  278. gate.hold(inst("ask#9", 7), () => released.push("unknown"));
  279. expect(released).toEqual(["unknown"]);
  280. });
  281. it("opens for good on settlement, draining what is parked in recorded order", () => {
  282. const gate = new ReplaySettleOrder([key("ask#1", 1), key("ask#1", 2), key("ask#1", 3)]);
  283. const released: string[] = [];
  284. gate.hold(inst("ask#1", 3), () => released.push("3"));
  285. gate.hold(inst("ask#1", 2), () => released.push("2"));
  286. expect(released).toEqual([]);
  287. gate.open();
  288. expect(released).toEqual(["2", "3"]);
  289. gate.hold(inst("ask#1", 1), () => released.push("1"));
  290. expect(released).toEqual(["2", "3", "1"]);
  291. });
  292. });
  293. describe("recoverSettleOrder", () => {
  294. function seed(): InMemoryJournalStore {
  295. const journal = new InMemoryJournalStore();
  296. journal.createRun({
  297. runId: RUN,
  298. caps: { maxConcurrency: 4 },
  299. spentTokens: 0,
  300. status: "running",
  301. });
  302. return journal;
  303. }
  304. it("takes the first settle of each instance and keeps only terminal, promise-returning rows", () => {
  305. const journal = seed();
  306. const put = (
  307. siteId: string,
  308. ordinal: number,
  309. kind: "ask" | "report",
  310. status: "completed" | "running",
  311. result?: unknown,
  312. ): void => {
  313. journal.putNode({
  314. runId: RUN,
  315. siteId,
  316. ordinal,
  317. kind,
  318. inputHash: "h",
  319. status,
  320. ...(result === undefined ? {} : { result }),
  321. });
  322. };
  323. put("ask#1", 1, "ask", "completed");
  324. put("ask#1", 2, "ask", "completed");
  325. put("ask#1", 3, "ask", "running"); // 被打断,重跑而不是释放
  326. put("report#1", 1, "report", "completed"); // void,不进次序表
  327. journal.appendEvent(RUN, { type: "node-settled", instance: inst("ask#1", 2), outcome: "ok" });
  328. journal.appendEvent(RUN, { type: "report", instance: inst("report#1", 1), item: {} });
  329. journal.appendEvent(RUN, { type: "node-settled", instance: inst("ask#1", 1), outcome: "ok" });
  330. journal.appendEvent(RUN, {
  331. type: "node-settled",
  332. instance: inst("ask#1", 3),
  333. outcome: "cancelled",
  334. });
  335. // 第二世重放同样发事件:首生次序优先,重复不再入表。
  336. journal.appendEvent(RUN, {
  337. type: "node-settled",
  338. instance: inst("ask#1", 1),
  339. outcome: "ok",
  340. cached: true,
  341. });
  342. expect(recoverSettleOrder(journal, RUN).recorded()).toEqual(["ask#1@2", "ask#1@1"]);
  343. });
  344. it("keeps content artifacts and drops preset declarations", () => {
  345. const journal = seed();
  346. journal.putNode({
  347. runId: RUN,
  348. siteId: "artifact#1",
  349. ordinal: 1,
  350. kind: "artifact",
  351. inputHash: "h",
  352. status: "completed",
  353. artifactId: "doc",
  354. result: { id: "doc", kind: "markdown", version: 1 },
  355. });
  356. journal.putNode({
  357. runId: RUN,
  358. siteId: "artifact#0",
  359. ordinal: 1,
  360. kind: "artifact",
  361. inputHash: "h",
  362. status: "completed",
  363. artifactId: "board",
  364. result: { id: "board", kind: "board", version: 1 },
  365. });
  366. journal.appendEvent(RUN, {
  367. type: "artifact-published",
  368. instance: inst("artifact#0", 1),
  369. artifact: { id: "board", kind: "board", version: 1 },
  370. });
  371. journal.appendEvent(RUN, {
  372. type: "artifact-published",
  373. instance: inst("artifact#1", 1),
  374. artifact: { id: "doc", kind: "markdown", version: 1 },
  375. });
  376. expect(recoverSettleOrder(journal, RUN).recorded()).toEqual(["artifact#1@1"]);
  377. });
  378. it("is empty for a journal whose events predate the rule", () => {
  379. const journal = seed();
  380. journal.putNode({
  381. runId: RUN,
  382. siteId: "ask#1",
  383. ordinal: 1,
  384. kind: "ask",
  385. inputHash: "h",
  386. status: "completed",
  387. result: "r",
  388. });
  389. expect(recoverSettleOrder(journal, RUN).recorded()).toEqual([]);
  390. });
  391. });