engine-holes.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. HOLE_PROMPT_MAX_CHARS,
  4. InMemoryJournalStore,
  5. WorkflowEngine,
  6. WorkflowError,
  7. refToString,
  8. type AskSpec,
  9. type HoleFill,
  10. } from "../../src/engine/index.js";
  11. import { FakeDriver, flush } from "./fake-driver.js";
  12. /**
  13. * 留白(docs/execution-engine.md「Holes」):`hole` 铸序号、盖出生阶段、记 `hole-reached`、把
  14. * deferred 停在站点下;`fillHole` 在一个同步步骤里换规格表、写脚本、记 `hole-filled`、记住代码、
  15. * 兑现全部停驻。没有 journal 行:留白不是会自己结算的节点。
  16. */
  17. const RUN = "run";
  18. const untyped = (...ids: string[]): Map<string, AskSpec> =>
  19. new Map(ids.map((id) => [id, { typed: false } as AskSpec]));
  20. interface SetupOpts {
  21. journal?: InMemoryJournalStore;
  22. sitePhases?: ReadonlyMap<string, string>;
  23. now?: () => number;
  24. launch?: { inputId: string; phaseNames?: string[]; holes?: number[] };
  25. }
  26. function setup(opts: SetupOpts = {}) {
  27. const journal = opts.journal ?? new InMemoryJournalStore();
  28. const driver = new FakeDriver(journal, {});
  29. const engine = new WorkflowEngine({
  30. runId: RUN,
  31. driver,
  32. caps: { maxConcurrency: 16 },
  33. askSpecs: untyped("ask#1"),
  34. validate: () => [],
  35. scriptText: "original",
  36. scriptHash: "h0",
  37. ...(opts.sitePhases === undefined ? {} : { sitePhases: opts.sitePhases }),
  38. ...(opts.now === undefined ? {} : { now: opts.now }),
  39. ...(opts.launch === undefined ? {} : { launch: opts.launch }),
  40. });
  41. return { journal, driver, engine };
  42. }
  43. /** 一份最小的补全:有效脚本的规格表是原表的超集,新站点都带 `hole#1/` 前缀。 */
  44. function fillFor(overrides: Partial<HoleFill> = {}): HoleFill {
  45. return {
  46. siteId: "hole#1",
  47. code: "(async () => { return 42; })",
  48. script: { text: "effective", hash: "h1" },
  49. askSpecs: untyped("ask#1", "hole#1/ask#1"),
  50. sitePhases: new Map([["hole#1/ask#1", "Verdict"]]),
  51. phaseNames: ["Gather", "Verdict"],
  52. holes: [],
  53. filledBy: "session-main",
  54. ...overrides,
  55. };
  56. }
  57. describe("WorkflowEngine — hole(): reach and park", () => {
  58. it("mints the site's ordinal, records hole-reached and parks the promise without a node row", () => {
  59. const { engine, driver, journal } = setup({ now: () => 1000 });
  60. void engine.hole("hole#1", "Verdict", "Decide.");
  61. const reached = driver.eventsOfType("hole-reached");
  62. expect(reached).toEqual([
  63. {
  64. type: "hole-reached",
  65. instance: { siteId: "hole#1", ordinal: 1 },
  66. name: "Verdict",
  67. prompt: "Decide.",
  68. },
  69. ]);
  70. expect(journal.getNode(RUN, "hole#1", 1)).toBeUndefined();
  71. expect(journal.listNodes(RUN, { kinds: "all", withResult: false })).toEqual([]);
  72. expect(engine.openHoles()).toEqual([
  73. { siteId: "hole#1", ordinal: 1, name: "Verdict", since: 1000 },
  74. ]);
  75. expect(engine.filledHoles()).toEqual([]);
  76. });
  77. it("leaves prompt absent when the site has none", () => {
  78. const { engine, driver } = setup();
  79. void engine.hole("hole#1", "Verdict");
  80. const [reached] = driver.eventsOfType("hole-reached");
  81. expect(reached).not.toHaveProperty("prompt");
  82. });
  83. it("bounds the prompt to 4000 chars with a trailing ellipsis", () => {
  84. const { engine, driver } = setup();
  85. void engine.hole("hole#1", "Verdict", "x".repeat(HOLE_PROMPT_MAX_CHARS + 50));
  86. const [reached] = driver.eventsOfType("hole-reached");
  87. expect(reached?.prompt?.length).toBe(HOLE_PROMPT_MAX_CHARS);
  88. expect(reached?.prompt?.endsWith("…")).toBe(true);
  89. // 恰好到上限的不截。
  90. void engine.hole("hole#2", "Other", "y".repeat(HOLE_PROMPT_MAX_CHARS));
  91. expect(driver.eventsOfType("hole-reached")[1]?.prompt).toBe("y".repeat(HOLE_PROMPT_MAX_CHARS));
  92. });
  93. it("stamps the birth phase lexically first, then from the marker the script last passed", () => {
  94. const { engine, driver } = setup({ sitePhases: new Map([["hole#1", "Gather"]]) });
  95. engine.enterPhase("Verify");
  96. void engine.hole("hole#1", "A");
  97. void engine.hole("hole#2", "B");
  98. expect(driver.eventsOfType("hole-reached").map((e) => e.phaseName)).toEqual([
  99. "Gather",
  100. "Verify",
  101. ]);
  102. });
  103. it("counts ordinals per site: several reaches of one site park side by side", () => {
  104. const { engine, driver } = setup();
  105. void engine.hole("hole#1", "A");
  106. void engine.hole("hole#1", "A");
  107. expect(driver.eventsOfType("hole-reached").map((e) => refToString(e.instance))).toEqual([
  108. "hole#1@1",
  109. "hole#1@2",
  110. ]);
  111. expect(engine.openHoles().map((h) => h.ordinal)).toEqual([1, 2]);
  112. });
  113. it("rejects a reach on a settled run", async () => {
  114. const { engine } = setup();
  115. engine.stop("user");
  116. await expect(engine.hole("hole#1", "A")).rejects.toMatchObject({ code: "Cancelled" });
  117. });
  118. });
  119. describe("WorkflowEngine — fillHole(): one synchronous step", () => {
  120. it("swaps the specs and phases, writes the script, records hole-filled, releases the parked branch", async () => {
  121. const { engine, driver, journal } = setup({ now: () => 2000 });
  122. const promise = engine.hole("hole#1", "Verdict", "Decide.");
  123. const eventsBefore = driver.events.length;
  124. const result = engine.fillHole(fillFor());
  125. expect(result).toEqual({ ok: true });
  126. // 脚本两列同笔改写,其余不动。
  127. const row = journal.getRun(RUN);
  128. expect(row?.scriptText).toBe("effective");
  129. expect(row?.scriptHash).toBe("h1");
  130. expect(row?.status).toBe("running");
  131. // 恰好一条 hole-filled,紧跟在 fill 上。
  132. expect(driver.events.slice(eventsBefore)).toEqual([
  133. {
  134. type: "hole-filled",
  135. siteId: "hole#1",
  136. filledAt: 2000,
  137. filledBy: "session-main",
  138. phaseNames: ["Gather", "Verdict"],
  139. holes: [],
  140. },
  141. ]);
  142. await expect(promise).resolves.toEqual({ code: "(async () => { return 42; })" });
  143. expect(engine.openHoles()).toEqual([]);
  144. expect(engine.filledHoles()).toEqual([
  145. { siteId: "hole#1", filledAt: 2000, filledBy: "session-main" },
  146. ]);
  147. // 规格表已是有效脚本的:体内的 ask 站点不再是 MissingAskSpec,且出生阶段来自新表。
  148. const actor = engine.createActor("hole#1/actor#1", "judge");
  149. void engine.ask("hole#1/ask#1", actor, "judge it");
  150. await flush();
  151. expect(driver.eventsOfType("run-settled")).toEqual([]);
  152. const queued = driver
  153. .eventsOfType("node-queued")
  154. .find((e) => e.instance.siteId === "hole#1/ask#1");
  155. expect(queued?.phaseName).toBe("Verdict");
  156. });
  157. it("leaves filledBy and holes absent when the fill carries none", () => {
  158. const { engine, driver } = setup();
  159. void engine.hole("hole#1", "Verdict");
  160. engine.fillHole(fillFor({ filledBy: undefined, holes: undefined }));
  161. const [filled] = driver.eventsOfType("hole-filled");
  162. expect(filled).toEqual({
  163. type: "hole-filled",
  164. siteId: "hole#1",
  165. filledAt: expect.any(Number),
  166. phaseNames: ["Gather", "Verdict"],
  167. });
  168. });
  169. it("carries the draft a fill minted on hole-filled, and nothing when the fill has none", () => {
  170. const { engine, driver } = setup();
  171. void engine.hole("hole#1", "Verdict");
  172. engine.fillHole(fillFor({ scriptPath: "/repo/.zcode/workflow-drafts/nightly.dwf.ts" }));
  173. const [filled] = driver.eventsOfType("hole-filled");
  174. expect(filled).toMatchObject({ scriptPath: "/repo/.zcode/workflow-drafts/nightly.dwf.ts" });
  175. expect("scriptPath" in (driver.eventsOfType("hole-filled")[0] ?? {})).toBe(true);
  176. const { engine: plain, driver: plainDriver } = setup();
  177. void plain.hole("hole#1", "Verdict");
  178. plain.fillHole(fillFor());
  179. expect("scriptPath" in (plainDriver.eventsOfType("hole-filled")[0] ?? {})).toBe(false);
  180. });
  181. it("resolves every ordinal parked on the site", async () => {
  182. const { engine } = setup();
  183. const first = engine.hole("hole#1", "A");
  184. const second = engine.hole("hole#1", "A");
  185. engine.fillHole(fillFor());
  186. await expect(first).resolves.toEqual({ code: "(async () => { return 42; })" });
  187. await expect(second).resolves.toEqual({ code: "(async () => { return 42; })" });
  188. });
  189. it("answers a later reach of a filled site from memory: no park, no new hole-reached", async () => {
  190. const { engine, driver } = setup();
  191. void engine.hole("hole#1", "A");
  192. engine.fillHole(fillFor());
  193. const eventsBefore = driver.events.length;
  194. await expect(engine.hole("hole#1", "A")).resolves.toEqual({
  195. code: "(async () => { return 42; })",
  196. });
  197. expect(driver.events.length).toBe(eventsBefore);
  198. expect(engine.openHoles()).toEqual([]);
  199. });
  200. it("is not_waiting when nothing is parked and nothing remembered, writing and emitting nothing", () => {
  201. const { engine, driver, journal } = setup();
  202. const eventsBefore = driver.events.length;
  203. expect(engine.fillHole(fillFor())).toEqual({ ok: false, reason: "not_waiting" });
  204. expect(driver.events.length).toBe(eventsBefore);
  205. expect(journal.getRun(RUN)?.scriptText).toBe("original");
  206. // 另一个站点在等也不算:停驻按站点。
  207. void engine.hole("hole#2", "B");
  208. expect(engine.fillHole(fillFor())).toEqual({ ok: false, reason: "not_waiting" });
  209. expect(journal.getRun(RUN)?.scriptText).toBe("original");
  210. });
  211. it("is settled on a settled run, writing and emitting nothing", () => {
  212. const { engine, driver, journal } = setup();
  213. engine.hole("hole#1", "A").catch(() => undefined);
  214. engine.stop("user");
  215. const eventsBefore = driver.events.length;
  216. expect(engine.fillHole(fillFor())).toEqual({ ok: false, reason: "settled" });
  217. expect(driver.events.length).toBe(eventsBefore);
  218. expect(journal.getRun(RUN)?.scriptText).toBe("original");
  219. });
  220. });
  221. describe("WorkflowEngine — settlement rejects parked holes", () => {
  222. it("stop rejects with Cancelled and empties the parked set", async () => {
  223. const { engine } = setup();
  224. const promise = engine.hole("hole#1", "A");
  225. engine.stop("user");
  226. await expect(promise).rejects.toMatchObject({ code: "Cancelled" });
  227. expect(engine.openHoles()).toEqual([]);
  228. });
  229. it("complete rejects the parked branch (a hole nobody awaited)", async () => {
  230. const { engine } = setup();
  231. const promise = engine.hole("hole#1", "A");
  232. engine.complete("done");
  233. await expect(promise).rejects.toMatchObject({ code: "Cancelled" });
  234. });
  235. it("fail rejects with the run's failure", async () => {
  236. const { engine } = setup();
  237. const promise = engine.hole("hole#1", "A");
  238. engine.fail(new WorkflowError("DriverError", "script threw"));
  239. await expect(promise).rejects.toMatchObject({ code: "DriverError", message: "script threw" });
  240. });
  241. it("keeps the fill memory out of settlement: filledHoles still lists the fill", () => {
  242. const { engine } = setup();
  243. void engine.hole("hole#1", "A");
  244. engine.fillHole(fillFor());
  245. engine.stop("user");
  246. expect(engine.filledHoles().map((h) => h.siteId)).toEqual(["hole#1"]);
  247. });
  248. });
  249. describe("WorkflowEngine — holes across lives", () => {
  250. it("run-launched carries the open-hole index table beside phaseNames", () => {
  251. const { driver } = setup({
  252. launch: { inputId: "in-1", phaseNames: ["Gather", "Verdict"], holes: [1] },
  253. });
  254. expect(driver.eventsOfType("run-launched")[0]).toMatchObject({
  255. phaseNames: ["Gather", "Verdict"],
  256. holes: [1],
  257. });
  258. });
  259. it("a run stopped while waiting resumes with nothing parked and re-reaches with a fresh hole-reached", () => {
  260. const journal = new InMemoryJournalStore();
  261. const first = setup({ journal });
  262. first.engine.hole("hole#1", "A", "Decide.").catch(() => undefined);
  263. first.engine.stop("user");
  264. const driver = new FakeDriver(journal, {});
  265. const engine = new WorkflowEngine({
  266. runId: RUN,
  267. driver,
  268. caps: { maxConcurrency: 16 },
  269. askSpecs: untyped("ask#1"),
  270. validate: () => [],
  271. scriptText: "original",
  272. scriptHash: "h0",
  273. });
  274. expect(engine.openHoles()).toEqual([]);
  275. expect(engine.filledHoles()).toEqual([]);
  276. void engine.hole("hole#1", "A", "Decide.");
  277. expect(driver.eventsOfType("hole-reached")).toHaveLength(1);
  278. // 整段日志里现在有两条 hole-reached:上一世一条、这一世一条,序号都从 1 起(没有行可撞)。
  279. const all = journal.listEvents(RUN, { types: ["hole-reached"], reportItems: "all" });
  280. expect(
  281. all.map((e) => (e.event.type === "hole-reached" ? refToString(e.event.instance) : "")),
  282. ).toEqual(["hole#1@1", "hole#1@1"]);
  283. });
  284. it("resume of a filled run replays against the effective script's hash", () => {
  285. const journal = new InMemoryJournalStore();
  286. const first = setup({ journal });
  287. void first.engine.hole("hole#1", "A");
  288. first.engine.fillHole(fillFor());
  289. first.engine.stop("user");
  290. // 旧哈希:拒绝;新哈希:接受(两列同笔写,所以校验成立)。
  291. const driver = new FakeDriver(journal, {});
  292. const config = {
  293. runId: RUN,
  294. driver,
  295. caps: { maxConcurrency: 16 },
  296. askSpecs: untyped("ask#1"),
  297. validate: () => [],
  298. };
  299. expect(
  300. () => new WorkflowEngine({ ...config, scriptText: "original", scriptHash: "h0" }),
  301. ).toThrow(/script changed/);
  302. expect(
  303. () => new WorkflowEngine({ ...config, scriptText: "effective", scriptHash: "h1" }),
  304. ).not.toThrow();
  305. });
  306. });
  307. describe("WorkflowEngine — recursive holes (a fill that contains an open hole)", () => {
  308. const INNER = "hole#1/hole#1";
  309. it("fills the inner site while the outer's fill is remembered: nested ids, superset tables, hole-filled by nested siteId", async () => {
  310. const { engine, driver, journal } = setup({ now: () => 3000 });
  311. void engine.hole("hole#1", "outer", "p");
  312. // 外层的有效脚本:内层留白的站点带外层前缀,词法上出生在外层的阶段。
  313. expect(
  314. engine.fillHole(
  315. fillFor({
  316. askSpecs: untyped("ask#1", "hole#1/ask#1"),
  317. sitePhases: new Map([
  318. ["hole#1/ask#1", "Verdict"],
  319. [INNER, "Verdict"],
  320. ]),
  321. phaseNames: ["Gather", "Verdict", "inner"],
  322. holes: [2],
  323. script: { text: "effective-1", hash: "h1" },
  324. }),
  325. ),
  326. ).toEqual({ ok: true });
  327. const inner = engine.hole(INNER, "inner", "q");
  328. expect(driver.eventsOfType("hole-reached").at(-1)).toEqual({
  329. type: "hole-reached",
  330. instance: { siteId: INNER, ordinal: 1 },
  331. name: "inner",
  332. prompt: "q",
  333. phaseName: "Verdict",
  334. });
  335. expect(engine.openHoles()).toEqual([{ siteId: INNER, ordinal: 1, name: "inner", since: 3000 }]);
  336. // 外层已记住,内层在等:对外层再补全不是 not_waiting(记忆在),对一个无人问津的站点才是。
  337. expect(engine.fillHole(fillFor({ siteId: "hole#2" }))).toEqual({
  338. ok: false,
  339. reason: "not_waiting",
  340. });
  341. const eventsBefore = driver.events.length;
  342. expect(
  343. engine.fillHole(
  344. fillFor({
  345. siteId: INNER,
  346. code: "(async () => { return before + inside; })",
  347. askSpecs: untyped("ask#1", "hole#1/ask#1", `${INNER}/ask#1`),
  348. sitePhases: new Map([
  349. ["hole#1/ask#1", "Verdict"],
  350. [INNER, "Verdict"],
  351. [`${INNER}/ask#1`, "Verdict"],
  352. ]),
  353. phaseNames: ["Gather", "Verdict"],
  354. holes: undefined,
  355. filledBy: "session-main",
  356. script: { text: "effective-2", hash: "h2" },
  357. }),
  358. ),
  359. ).toEqual({ ok: true });
  360. expect(driver.events.slice(eventsBefore)).toEqual([
  361. {
  362. type: "hole-filled",
  363. siteId: INNER,
  364. filledAt: 3000,
  365. filledBy: "session-main",
  366. phaseNames: ["Gather", "Verdict"],
  367. },
  368. ]);
  369. await expect(inner).resolves.toEqual({ code: "(async () => { return before + inside; })" });
  370. expect(engine.openHoles()).toEqual([]);
  371. expect(engine.filledHoles().map((h) => h.siteId)).toEqual(["hole#1", INNER]);
  372. expect(journal.getRun(RUN)).toMatchObject({ scriptText: "effective-2", scriptHash: "h2" });
  373. // 第二份有效脚本的规格表已生效:内层体内的 ask 站点有 spec,出生阶段来自新表。
  374. const actor = engine.createActor(`${INNER}/actor#1`, "judge");
  375. void engine.ask(`${INNER}/ask#1`, actor, "judge");
  376. await flush();
  377. expect(driver.eventsOfType("run-settled")).toEqual([]);
  378. expect(
  379. driver.eventsOfType("node-queued").find((e) => e.instance.siteId === `${INNER}/ask#1`)
  380. ?.phaseName,
  381. ).toBe("Verdict");
  382. // 两个站点都记住了:再到达任一个都立刻作答、不停驻、不记事件。
  383. const after = driver.events.length;
  384. await expect(engine.hole("hole#1", "outer")).resolves.toEqual({
  385. code: "(async () => { return 42; })",
  386. });
  387. await expect(engine.hole(INNER, "inner")).resolves.toEqual({
  388. code: "(async () => { return before + inside; })",
  389. });
  390. expect(driver.events.length).toBe(after);
  391. });
  392. it("stop while the inner is parked rejects it and keeps both fills in memory", async () => {
  393. const { engine } = setup();
  394. void engine.hole("hole#1", "outer");
  395. engine.fillHole(fillFor());
  396. const inner = engine.hole(INNER, "inner");
  397. engine.stop("user");
  398. await expect(inner).rejects.toMatchObject({ code: "Cancelled" });
  399. expect(engine.openHoles()).toEqual([]);
  400. expect(engine.filledHoles().map((h) => h.siteId)).toEqual(["hole#1"]);
  401. });
  402. });