engine-resume-reads.test.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. /**
  2. * resume 的 journal 读形状(docs/execution-engine.md「Reading the journal」):
  3. *
  4. * - 报告行只数不读:一个 run 可以有 65,536 条 report,resume 恢复它们的计数与重放它们的去重,
  5. * 都不需要把任何一条 item 读进内存;
  6. * - 节点表只读一次:每个 actor 的已记录 ask 数从 resume 已读好的 ask 行建表,而不是每注册一个
  7. * actor 就整表读一遍(修复前是 O(actor × 行) 次解码);
  8. * - 事件只读结算次序与导入关门判定要的那几种类型。
  9. */
  10. import { describe, expect, it } from "vitest";
  11. import {
  12. InMemoryJournalStore,
  13. WorkflowEngine,
  14. type AskSpec,
  15. type GetNodeOptions,
  16. type InstanceRef,
  17. type JournalStorePort,
  18. type ListEventsOptions,
  19. type ListNodesOptions,
  20. type NodeKind,
  21. } from "../../src/engine/index.js";
  22. import { FakeDriver, flush } from "./fake-driver.js";
  23. const RUN = "run";
  24. const ACTORS = 5;
  25. const REPORTS = 40;
  26. function inst(siteId: string, ordinal = 1): InstanceRef {
  27. return { siteId, ordinal };
  28. }
  29. const specs = new Map<string, AskSpec>([["ask#1", { typed: false } as AskSpec]]);
  30. /** 转发到真 store、并记下每一次读的形状的 journal。 */
  31. class RecordingJournal extends InMemoryJournalStore {
  32. readonly nodeReads: ListNodesOptions[] = [];
  33. readonly eventReads: ListEventsOptions[] = [];
  34. readonly pointReads: Array<{ siteId: string; opts: GetNodeOptions | undefined }> = [];
  35. readonly counts: NodeKind[] = [];
  36. readonly byteSums: NodeKind[] = [];
  37. recording = false;
  38. override listNodes(runId: string, opts: ListNodesOptions) {
  39. if (this.recording) this.nodeReads.push(opts);
  40. return super.listNodes(runId, opts);
  41. }
  42. override listEvents(runId: string, opts: ListEventsOptions) {
  43. if (this.recording) this.eventReads.push(opts);
  44. return super.listEvents(runId, opts);
  45. }
  46. override getNode(runId: string, siteId: string, ordinal: number, opts?: GetNodeOptions) {
  47. if (this.recording) this.pointReads.push({ siteId, opts });
  48. return super.getNode(runId, siteId, ordinal, opts);
  49. }
  50. override countNodes(runId: string, kind: NodeKind) {
  51. if (this.recording) this.counts.push(kind);
  52. return super.countNodes(runId, kind);
  53. }
  54. override sumResultBytes(runId: string, kind: NodeKind) {
  55. if (this.recording) this.byteSums.push(kind);
  56. return super.sumResultBytes(runId, kind);
  57. }
  58. }
  59. function engineOn(journal: JournalStorePort) {
  60. const driver = new FakeDriver(journal);
  61. const engine = new WorkflowEngine({
  62. runId: RUN,
  63. driver,
  64. caps: { maxConcurrency: 16 },
  65. askSpecs: specs,
  66. validate: () => [],
  67. });
  68. return { driver, engine };
  69. }
  70. /** 同一段「脚本」:ACTORS 个 actor 各问一次,然后报 REPORTS 条。第一世逐个作答,第二世全部命中。 */
  71. async function runScript(
  72. engine: WorkflowEngine,
  73. answer: (i: number) => void,
  74. ): Promise<Array<Promise<unknown>>> {
  75. const asks: Array<Promise<unknown>> = [];
  76. for (let i = 0; i < ACTORS; i += 1) {
  77. const actor = engine.createActor("actor#1");
  78. asks.push(engine.ask("ask#1", actor, `task ${i}`));
  79. }
  80. await flush();
  81. for (let i = 0; i < ACTORS; i += 1) answer(i);
  82. await Promise.all(asks);
  83. for (let i = 0; i < REPORTS; i += 1)
  84. engine.report("report#1", { finding: i, pad: "x".repeat(64) });
  85. return asks;
  86. }
  87. describe("resume reads only what it uses", () => {
  88. it("never loads a report item, and reads the node table once however many actors register", async () => {
  89. const journal = new RecordingJournal();
  90. const first = engineOn(journal);
  91. await runScript(first.engine, (i) =>
  92. first.engine.askTurnEnded(inst("ask#1", i + 1), `answer ${i}`),
  93. );
  94. first.engine.stop("user");
  95. await first.engine.settled;
  96. journal.recording = true;
  97. const resumed = engineOn(journal);
  98. await runScript(resumed.engine, () => {});
  99. journal.recording = false;
  100. // 节点表:恰好两次读(工作行不带结果 + 产物行),与 actor 个数无关;没有一次读报告行。
  101. expect(journal.nodeReads).toEqual([
  102. { kinds: ["ask", "world-read", "world-run"], withResult: false },
  103. { kinds: ["artifact"], withResult: true },
  104. ]);
  105. // 报告的条数与字节数都是聚合:count(*) 与 sum(octet_length(result_json))。
  106. expect(journal.counts).toEqual(["report"]);
  107. expect(journal.byteSums).toEqual(["report"]);
  108. // 事件:只读结算次序要的类型,且 report item 一条不读。
  109. expect(journal.eventReads.length).toBeGreaterThan(0);
  110. for (const read of journal.eventReads) {
  111. expect(read.types).not.toBe("all");
  112. expect(read.reportItems).toEqual({ limit: 0 });
  113. }
  114. // 报告的重放去重只比对哈希。
  115. const reportPoints = journal.pointReads.filter((read) => read.siteId === "report#1");
  116. expect(reportPoints).toHaveLength(REPORTS);
  117. for (const read of reportPoints) expect(read.opts).toEqual({ withResult: false });
  118. // 行为不变:全部命中、一条 report 都不重发、没有派发新的 ask。
  119. expect(resumed.driver.eventsOfType("report")).toEqual([]);
  120. expect(resumed.driver.startAskCount()).toBe(0);
  121. });
  122. it("still holds a live ask behind the actor's recorded asks after a resume", async () => {
  123. // recordedCount 从 resume 读好的 ask 行建表:一个 actor 在第一世答完两问,第二世多问一句——
  124. // 第三问必须排在两条命中之后才派发(hold 规则),而且只派发它自己。
  125. const journal = new InMemoryJournalStore();
  126. const first = engineOn(journal);
  127. const actor = first.engine.createActor("actor#1");
  128. const a = first.engine.ask("ask#1", actor, "one");
  129. await flush();
  130. first.engine.askTurnEnded(inst("ask#1", 1), "r1");
  131. await a;
  132. const b = first.engine.ask("ask#1", actor, "two");
  133. await flush();
  134. first.engine.askTurnEnded(inst("ask#1", 2), "r2");
  135. await b;
  136. first.engine.stop("user");
  137. await first.engine.settled;
  138. const resumed = engineOn(journal);
  139. const again = resumed.engine.createActor("actor#1");
  140. const hits = [
  141. resumed.engine.ask("ask#1", again, "one"),
  142. resumed.engine.ask("ask#1", again, "two"),
  143. ];
  144. const live = resumed.engine.ask("ask#1", again, "three");
  145. await expect(Promise.all(hits)).resolves.toEqual(["r1", "r2"]);
  146. await flush();
  147. expect(resumed.driver.startAskCount()).toBe(1);
  148. expect(resumed.driver.startAsks[0]?.instance).toEqual(inst("ask#1", 3));
  149. resumed.engine.askTurnEnded(inst("ask#1", 3), "r3");
  150. await expect(live).resolves.toBe("r3");
  151. });
  152. });