holes.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /**
  2. * 留白在 cell 里、在站点处求值(docs/execution-engine.md「The vm cell」的 Holes 段与「## Holes」)。
  3. * 这些 lowered 体是手写的(与 security.test.ts 同一正当性):被测对象是 `__host.hole` shim、
  4. * 线协议的 `hole` 请求、harness 的路由与控制面的 `fillHole` 绑定,不是编译器。
  5. */
  6. import { describe, expect, it } from "vitest";
  7. import {
  8. InMemoryJournalStore,
  9. type AskSpec,
  10. type FillHoleResult,
  11. type HoleFill,
  12. type RunEvent,
  13. type RunSettlement,
  14. type WorkflowEngine,
  15. } from "@zcode/dynamic-workflow";
  16. import { runWorkflowScript, type RunControlBinding } from "../src/index.js";
  17. import { AutoDriver, type AutoDriverConfig } from "./auto-driver.js";
  18. import { TEST_CWD } from "./helpers.js";
  19. type BoundEngine = Pick<
  20. WorkflowEngine,
  21. "setMaxConcurrency" | "fillHole" | "openHoles" | "filledHoles"
  22. >;
  23. type HoleReached = Extract<RunEvent, { type: "hole-reached" }>;
  24. interface RunLoweredOptions {
  25. asks?: AutoDriverConfig["asks"];
  26. askSpecs?: Map<string, AskSpec>;
  27. signal?: AbortSignal;
  28. /**
  29. * 每条引擎事件都经这里(同步、在 driver.emit 里);`engine()` 取控制面绑下来的这一世的引擎。
  30. * 惰性取:首条 `run-started` 在引擎构造函数里发出,早于 harness 绑控制面。
  31. */
  32. onEvent?: (event: RunEvent, engine: () => BoundEngine) => void;
  33. }
  34. interface RunLoweredResult {
  35. settlement: RunSettlement;
  36. driver: AutoDriver;
  37. journal: InMemoryJournalStore;
  38. }
  39. const untyped = (...ids: string[]): Map<string, AskSpec> =>
  40. new Map(ids.map((id) => [id, { typed: false } as AskSpec]));
  41. let runSeq = 0;
  42. /** 直接投喂手写 lowered 体(自由标识符仅 `__host`),把控制面句柄与事件钩子接给测试。 */
  43. async function runLowered(
  44. lowered: string,
  45. opts: RunLoweredOptions = {},
  46. ): Promise<RunLoweredResult> {
  47. const journal = new InMemoryJournalStore();
  48. const driver = new AutoDriver(journal, { asks: opts.asks });
  49. let engine: BoundEngine | undefined;
  50. const control: RunControlBinding = {
  51. bind(bound) {
  52. engine = bound;
  53. },
  54. };
  55. const requireEngine = (): BoundEngine => {
  56. if (engine === undefined) throw new Error("control was never bound to an engine");
  57. return engine;
  58. };
  59. const emit = driver.emit.bind(driver);
  60. driver.emit = (event: RunEvent): void => {
  61. emit(event);
  62. opts.onEvent?.(event, requireEngine);
  63. };
  64. const settlement = await runWorkflowScript({
  65. cwd: TEST_CWD,
  66. runId: `holes-${++runSeq}`,
  67. lowered,
  68. caps: { maxConcurrency: 4 },
  69. askSpecs: opts.askSpecs ?? new Map(),
  70. validate: () => [],
  71. makeDriver: (sink) => {
  72. driver.attach(sink);
  73. return driver;
  74. },
  75. control,
  76. timeoutMs: 15000,
  77. ...(opts.signal === undefined ? {} : { signal: opts.signal }),
  78. });
  79. return { settlement, driver, journal };
  80. }
  81. /** 一份补全:规格表是原表的超集,新站点都带 `hole#1/` 前缀。 */
  82. function fillFor(code: string, overrides: Partial<HoleFill> = {}): HoleFill {
  83. return {
  84. siteId: "hole#1",
  85. code,
  86. script: { text: "effective", hash: "h1" },
  87. askSpecs: untyped("ask#1", "hole#1/ask#1"),
  88. sitePhases: new Map(),
  89. phaseNames: [],
  90. ...overrides,
  91. };
  92. }
  93. /** 在第一条 hole-reached 上补全(恰好一次),并把补全结果与到达事件留给断言。 */
  94. function fillOnReach(code: string, overrides: Partial<HoleFill> = {}) {
  95. const reached: HoleReached[] = [];
  96. const results: FillHoleResult[] = [];
  97. const onEvent = (event: RunEvent, engine: () => BoundEngine): void => {
  98. if (event.type !== "hole-reached") return;
  99. reached.push(event);
  100. if (reached.length === 1) results.push(engine().fillHole(fillFor(code, overrides)));
  101. };
  102. return { onEvent, reached, results };
  103. }
  104. function artifactOf(settlement: RunSettlement): unknown {
  105. expect(settlement.status).toBe("completed");
  106. return (settlement as { status: "completed"; artifact: unknown }).artifact;
  107. }
  108. describe("holes — evaluated at the site", () => {
  109. it("the fill reads a const declared before the hole, and the request carries name and prompt", async () => {
  110. const hook = fillOnReach("(async () => { return base + 2; })", { filledBy: "main" });
  111. const { settlement, driver } = await runLowered(
  112. [
  113. "const base = 40;",
  114. 'const v = await __host.hole("hole#1", "Verdict", "Decide on base.", (__src) => eval(__src));',
  115. "return v;",
  116. ].join("\n"),
  117. { onEvent: hook.onEvent },
  118. );
  119. expect(artifactOf(settlement)).toBe(42);
  120. expect(hook.results).toEqual([{ ok: true }]);
  121. expect(hook.reached).toEqual([
  122. {
  123. type: "hole-reached",
  124. instance: { siteId: "hole#1", ordinal: 1 },
  125. name: "Verdict",
  126. prompt: "Decide on base.",
  127. },
  128. ]);
  129. expect(driver.eventsOfType("hole-filled")).toEqual([
  130. {
  131. type: "hole-filled",
  132. siteId: "hole#1",
  133. filledAt: expect.any(Number),
  134. filledBy: "main",
  135. phaseNames: [],
  136. },
  137. ]);
  138. });
  139. it("the fill's own lowered sites run through __host (an ask inside the body)", async () => {
  140. const hook = fillOnReach(
  141. [
  142. "(async () => {",
  143. ' const judge = __host.createActor("hole#1/actor#1", "judge");',
  144. ' return await __host.ask("hole#1/ask#1", judge, "judge " + subject);',
  145. "})",
  146. ].join("\n"),
  147. );
  148. const { settlement, driver } = await runLowered(
  149. [
  150. 'const subject = "the patch";',
  151. 'const verdict = await __host.hole("hole#1", "Verdict", undefined, (__src) => eval(__src));',
  152. "return verdict;",
  153. ].join("\n"),
  154. {
  155. onEvent: hook.onEvent,
  156. asks: {
  157. "hole#1/ask#1": ({ message }) => ({
  158. type: "text",
  159. finalText: `verdict on: ${message.instructions}`,
  160. }),
  161. },
  162. },
  163. );
  164. expect(artifactOf(settlement)).toBe("verdict on: judge the patch");
  165. expect(driver.eventsOfType("node-settled").map((e) => e.instance.siteId)).toEqual([
  166. "hole#1/ask#1",
  167. ]);
  168. });
  169. it("a hole in a loop is filled once and its body runs per iteration with that iteration's binding", async () => {
  170. const hook = fillOnReach("(async () => { return i * 10; })");
  171. const { settlement, driver } = await runLowered(
  172. [
  173. "const out = [];",
  174. "for (const i of [1, 2, 3]) {",
  175. ' out.push(await __host.hole("hole#1", "Scale", undefined, (__src) => eval(__src)));',
  176. "}",
  177. "return out;",
  178. ].join("\n"),
  179. { onEvent: hook.onEvent },
  180. );
  181. expect(artifactOf(settlement)).toEqual([10, 20, 30]);
  182. // 一次到达、一次补全:后两轮由 cell 的 fill 表作答,不过线。
  183. expect(hook.reached).toHaveLength(1);
  184. expect(driver.eventsOfType("hole-reached")).toHaveLength(1);
  185. expect(driver.eventsOfType("hole-filled")).toHaveLength(1);
  186. });
  187. it("a thrown fill rejects at the site and the script can catch it", async () => {
  188. const hook = fillOnReach('(async () => { throw new Error("boom"); })');
  189. const { settlement } = await runLowered(
  190. [
  191. "try {",
  192. ' await __host.hole("hole#1", "Verdict", undefined, (__src) => eval(__src));',
  193. ' return "NO-THROW";',
  194. "} catch (e) {",
  195. " return e.message;",
  196. "}",
  197. ].join("\n"),
  198. { onEvent: hook.onEvent },
  199. );
  200. expect(artifactOf(settlement)).toBe("boom");
  201. });
  202. it("a fill that does not parse rejects at the site too, as a SyntaxError", async () => {
  203. const hook = fillOnReach("(async () => { return ; ; )");
  204. const { settlement } = await runLowered(
  205. [
  206. "try {",
  207. ' await __host.hole("hole#1", "Verdict", undefined, (__src) => eval(__src));',
  208. ' return "NO-THROW";',
  209. "} catch (e) {",
  210. " return e.name;",
  211. "}",
  212. ].join("\n"),
  213. { onEvent: hook.onEvent },
  214. );
  215. expect(artifactOf(settlement)).toBe("SyntaxError");
  216. });
  217. it("a filled hole (body present) sends no wire message", async () => {
  218. const seen: string[] = [];
  219. const { settlement, driver } = await runLowered(
  220. [
  221. "const base = 5;",
  222. 'const v = await __host.hole("hole#1", "Verdict", "p", (__src) => eval(__src), async () => { return base + 2; });',
  223. "return v;",
  224. ].join("\n"),
  225. {
  226. onEvent: (event) => {
  227. seen.push(event.type);
  228. },
  229. },
  230. );
  231. expect(artifactOf(settlement)).toBe(7);
  232. expect(seen).not.toContain("hole-reached");
  233. expect(driver.eventsOfType("hole-reached")).toEqual([]);
  234. });
  235. it("a body that throws synchronously rejects at the site rather than escaping the call", async () => {
  236. const { settlement } = await runLowered(
  237. [
  238. "try {",
  239. ' await __host.hole("hole#1", "Verdict", undefined, (__src) => eval(__src), () => { throw new Error("sync"); });',
  240. ' return "NO-THROW";',
  241. "} catch (e) {",
  242. " return e.message;",
  243. "}",
  244. ].join("\n"),
  245. );
  246. expect(artifactOf(settlement)).toBe("sync");
  247. });
  248. });
  249. describe("holes — a parked hole is a request in flight", () => {
  250. it("siblings keep running while the hole waits, and the stall detector stays quiet", async () => {
  251. let reachedCount = 0;
  252. let siblingSettled = false;
  253. let filled = false;
  254. let openWhileSiblingSettled: number | undefined;
  255. const results: FillHoleResult[] = [];
  256. const { settlement } = await runLowered(
  257. [
  258. 'const worker = __host.createActor("actor#1", "w");',
  259. 'const side = __host.future(async () => __host.ask("ask#1", worker, "hi"));',
  260. 'const v = await __host.hole("hole#1", "Verdict", undefined, (__src) => eval(__src));',
  261. "return [await side, v];",
  262. ].join("\n"),
  263. {
  264. askSpecs: untyped("ask#1"),
  265. asks: { "ask#1": () => ({ type: "text", finalText: "sibling done" }) },
  266. onEvent: (event, engine) => {
  267. if (event.type === "hole-reached") reachedCount += 1;
  268. if (event.type === "node-settled" && event.instance.siteId === "ask#1") {
  269. openWhileSiblingSettled = reachedCount;
  270. siblingSettled = true;
  271. }
  272. // 两件事都发生之后才补全,不论谁先到。修复原因:原先在兄弟 ask 结算的那一刻就补全,
  273. // 兄弟若先于留白被到达就结算,补全被拒(hole_not_waiting),run 永远停在留白处,用例
  274. // 5 秒超时——约三次里一次。停滞检测若开过火,run 早就 errored 了,结论不变。
  275. // 先立旗再补全:fillHole 同步发出 hole-filled,会重入这个回调。
  276. if (reachedCount > 0 && siblingSettled && !filled) {
  277. filled = true;
  278. results.push(engine().fillHole(fillFor("(async () => { return 1; })")));
  279. }
  280. },
  281. },
  282. );
  283. expect(artifactOf(settlement)).toEqual(["sibling done", 1]);
  284. // 兄弟可能在留白被到达之前或之后结算;两种次序下留白都只被到达一次、补全一次。
  285. expect([0, 1]).toContain(openWhileSiblingSettled);
  286. expect(reachedCount).toBe(1);
  287. expect(results).toEqual([{ ok: true }]);
  288. });
  289. it("a cancel while parked stops the run and the sandbox goes down with it", async () => {
  290. const controller = new AbortController();
  291. const { settlement, driver } = await runLowered(
  292. 'await __host.hole("hole#1", "Verdict", undefined, (__src) => eval(__src)); return "NO";',
  293. {
  294. signal: controller.signal,
  295. onEvent: (event) => {
  296. if (event.type === "hole-reached") controller.abort("user");
  297. },
  298. },
  299. );
  300. expect(settlement).toEqual({ status: "stopped", reason: "user" });
  301. expect(driver.eventsOfType("hole-filled")).toEqual([]);
  302. });
  303. it("the control binding hands out fillHole, openHoles and filledHoles beside setMaxConcurrency", async () => {
  304. let bound: BoundEngine | undefined;
  305. const journal = new InMemoryJournalStore();
  306. const driver = new AutoDriver(journal);
  307. await runWorkflowScript({
  308. cwd: TEST_CWD,
  309. runId: `holes-${++runSeq}`,
  310. lowered: "return 1;",
  311. caps: { maxConcurrency: 4 },
  312. askSpecs: new Map(),
  313. validate: () => [],
  314. makeDriver: (sink) => {
  315. driver.attach(sink);
  316. return driver;
  317. },
  318. control: {
  319. bind(engine) {
  320. bound = engine;
  321. },
  322. },
  323. timeoutMs: 15000,
  324. });
  325. expect(typeof bound?.fillHole).toBe("function");
  326. // 快照投影的两个只读面也经这条绑定交出去(run 已结算:停驻表空、本世没有补全)。
  327. expect(bound?.openHoles()).toEqual([]);
  328. expect(bound?.filledHoles()).toEqual([]);
  329. // 结算之后是 no-op:`settled`,不写不发。
  330. expect(bound?.fillHole(fillFor("(async () => 1)"))).toEqual({ ok: false, reason: "settled" });
  331. });
  332. });
  333. /** 内层留白的站点 id 带外层前缀(docs/analysis.md「Sites」):外层的体是有效脚本的一部分,体内的站点都是 `hole#1/…`。 */
  334. const INNER = "hole#1/hole#1";
  335. /** 外层补全的体:声明一个 const,再到达一处内层留白,把内层的值原样返回。 */
  336. const OUTER_WITH_INNER = [
  337. "(async () => {",
  338. ' const inside = "I" + (typeof i === "undefined" ? "" : i);',
  339. ` return await __host.hole("${INNER}", "inner", "q", (__src) => eval(__src));`,
  340. "})",
  341. ].join("\n");
  342. describe("holes — recursive: a fill that contains an open hole", () => {
  343. it("the inner request goes out with the nested siteId, parks only that branch, and its fill reads both scopes", async () => {
  344. const reached: HoleReached[] = [];
  345. const results: FillHoleResult[] = [];
  346. let openWhileInnerParked: unknown;
  347. const { settlement, driver } = await runLowered(
  348. [
  349. 'const before = "B";',
  350. 'const worker = __host.createActor("actor#1", "w");',
  351. 'const side = __host.future(async () => __host.ask("ask#1", worker, "hi"));',
  352. 'const v = await __host.hole("hole#1", "outer", "p", (__src) => eval(__src));',
  353. "return [await side, v];",
  354. ].join("\n"),
  355. {
  356. askSpecs: untyped("ask#1"),
  357. asks: { "ask#1": () => ({ type: "text", finalText: "sibling done" }) },
  358. onEvent: (event, engine) => {
  359. if (event.type !== "hole-reached") return;
  360. reached.push(event);
  361. if (event.instance.siteId === "hole#1") {
  362. results.push(engine().fillHole(fillFor(OUTER_WITH_INNER)));
  363. return;
  364. }
  365. // 内层停驻期间只有它自己在飞:拖一段真时间再补全,停滞检测若把停驻的留白当成
  366. // 「无在飞请求」,run 会在这段时间里 errored。
  367. openWhileInnerParked = engine().openHoles();
  368. setTimeout(() => {
  369. results.push(
  370. engine().fillHole(
  371. fillFor("(async () => { return before + inside; })", {
  372. siteId: INNER,
  373. askSpecs: untyped("ask#1", "hole#1/ask#1", `${INNER}/ask#1`),
  374. }),
  375. ),
  376. );
  377. }, 30);
  378. },
  379. },
  380. );
  381. expect(artifactOf(settlement)).toEqual(["sibling done", "BI"]);
  382. expect(results).toEqual([{ ok: true }, { ok: true }]);
  383. expect(reached.map((e) => [e.instance.siteId, e.instance.ordinal, e.name, e.prompt])).toEqual([
  384. ["hole#1", 1, "outer", "p"],
  385. [INNER, 1, "inner", "q"],
  386. ]);
  387. expect(openWhileInnerParked).toEqual([
  388. { siteId: INNER, ordinal: 1, name: "inner", since: expect.any(Number) },
  389. ]);
  390. expect(driver.eventsOfType("hole-filled").map((e) => e.siteId)).toEqual(["hole#1", INNER]);
  391. });
  392. it("reached again in a loop, both are answered from the cell's fill table and the inner sees the iteration's binding", async () => {
  393. const results: FillHoleResult[] = [];
  394. const { settlement, driver } = await runLowered(
  395. [
  396. 'const before = "B";',
  397. "const out = [];",
  398. "for (const i of [1, 2, 3]) {",
  399. ' out.push(await __host.hole("hole#1", "outer", undefined, (__src) => eval(__src)));',
  400. "}",
  401. "return out;",
  402. ].join("\n"),
  403. {
  404. onEvent: (event, engine) => {
  405. if (event.type !== "hole-reached") return;
  406. if (event.instance.siteId === "hole#1") {
  407. results.push(engine().fillHole(fillFor(OUTER_WITH_INNER)));
  408. } else {
  409. results.push(
  410. engine().fillHole(
  411. fillFor("(async () => { return before + inside; })", { siteId: INNER }),
  412. ),
  413. );
  414. }
  415. },
  416. },
  417. );
  418. expect(artifactOf(settlement)).toEqual(["BI1", "BI2", "BI3"]);
  419. // 两个站点各到达一次、各补全一次;后两轮外层与内层都不过线。
  420. expect(driver.eventsOfType("hole-reached").map((e) => e.instance.siteId)).toEqual([
  421. "hole#1",
  422. INNER,
  423. ]);
  424. expect(driver.eventsOfType("hole-filled").map((e) => e.siteId)).toEqual(["hole#1", INNER]);
  425. expect(results).toEqual([{ ok: true }, { ok: true }]);
  426. });
  427. it("an inner fill that throws rejects the inner site; uncaught, it propagates out of the outer body to the outer awaiter", async () => {
  428. const fillBoth = (event: RunEvent, engine: () => BoundEngine): void => {
  429. if (event.type !== "hole-reached") return;
  430. if (event.instance.siteId === "hole#1")
  431. return void engine().fillHole(fillFor(OUTER_WITH_INNER));
  432. engine().fillHole(
  433. fillFor('(async () => { throw new Error("inner boom"); })', { siteId: INNER }),
  434. );
  435. };
  436. const uncaught = await runLowered(
  437. [
  438. "try {",
  439. ' await __host.hole("hole#1", "outer", undefined, (__src) => eval(__src));',
  440. ' return "NO-THROW";',
  441. "} catch (e) {",
  442. ' return "outer caught: " + e.message;',
  443. "}",
  444. ].join("\n"),
  445. { onEvent: fillBoth },
  446. );
  447. expect(artifactOf(uncaught.settlement)).toBe("outer caught: inner boom");
  448. });
  449. it("an inner rejection caught inside the outer body stays inside it", async () => {
  450. const outerCatching = [
  451. "(async () => {",
  452. " try {",
  453. ` return await __host.hole("${INNER}", "inner", undefined, (__src) => eval(__src));`,
  454. " } catch (e) {",
  455. ' return "inner caught: " + e.message;',
  456. " }",
  457. "})",
  458. ].join("\n");
  459. const { settlement } = await runLowered(
  460. 'return await __host.hole("hole#1", "outer", undefined, (__src) => eval(__src));',
  461. {
  462. onEvent: (event, engine) => {
  463. if (event.type !== "hole-reached") return;
  464. if (event.instance.siteId === "hole#1")
  465. return void engine().fillHole(fillFor(outerCatching));
  466. engine().fillHole(
  467. fillFor('(async () => { throw new Error("inner boom"); })', { siteId: INNER }),
  468. );
  469. },
  470. },
  471. );
  472. expect(artifactOf(settlement)).toBe("inner caught: inner boom");
  473. });
  474. });