engine-holes.test.ts 18 KB

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