holes.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 { settlement, driver } = await runLowered(
  219. [
  220. "const base = 5;",
  221. 'const v = await __host.hole("hole#1", "Verdict", "p", (__src) => eval(__src), async () => { return base + 2; });',
  222. "return v;",
  223. ].join("\n"),
  224. );
  225. expect(artifactOf(settlement)).toBe(7);
  226. expect(driver.eventsOfType("hole-reached")).toEqual([]);
  227. });
  228. it("a body that throws synchronously rejects at the site rather than escaping the call", async () => {
  229. const { settlement } = await runLowered(
  230. [
  231. "try {",
  232. ' await __host.hole("hole#1", "Verdict", undefined, (__src) => eval(__src), () => { throw new Error("sync"); });',
  233. ' return "NO-THROW";',
  234. "} catch (e) {",
  235. " return e.message;",
  236. "}",
  237. ].join("\n"),
  238. );
  239. expect(artifactOf(settlement)).toBe("sync");
  240. });
  241. });
  242. describe("holes — a parked hole is a request in flight", () => {
  243. it("siblings keep running while the hole waits, and the stall detector stays quiet", async () => {
  244. let reachedCount = 0;
  245. let siblingSettled = false;
  246. let filled = false;
  247. let openWhileSiblingSettled: number | undefined;
  248. const results: FillHoleResult[] = [];
  249. const { settlement } = await runLowered(
  250. [
  251. 'const worker = __host.createActor("actor#1", "w");',
  252. 'const side = __host.future(async () => __host.ask("ask#1", worker, "hi"));',
  253. 'const v = await __host.hole("hole#1", "Verdict", undefined, (__src) => eval(__src));',
  254. "return [await side, v];",
  255. ].join("\n"),
  256. {
  257. askSpecs: untyped("ask#1"),
  258. asks: { "ask#1": () => ({ type: "text", finalText: "sibling done" }) },
  259. onEvent: (event, engine) => {
  260. if (event.type === "hole-reached") reachedCount += 1;
  261. if (event.type === "node-settled" && event.instance.siteId === "ask#1") {
  262. openWhileSiblingSettled = reachedCount;
  263. siblingSettled = true;
  264. }
  265. // 两件事都发生之后才补全,不论谁先到。修复原因:原先在兄弟 ask 结算的那一刻就补全,
  266. // 兄弟若先于留白被到达就结算,补全被拒(hole_not_waiting),run 永远停在留白处,用例
  267. // 5 秒超时——约三次里一次。停滞检测若开过火,run 早就 errored 了,结论不变。
  268. // 先立旗再补全:fillHole 同步发出 hole-filled,会重入这个回调。
  269. if (reachedCount > 0 && siblingSettled && !filled) {
  270. filled = true;
  271. results.push(engine().fillHole(fillFor("(async () => { return 1; })")));
  272. }
  273. },
  274. },
  275. );
  276. expect(artifactOf(settlement)).toEqual(["sibling done", 1]);
  277. // 兄弟可能在留白被到达之前或之后结算;两种次序下留白都只被到达一次、补全一次。
  278. expect([0, 1]).toContain(openWhileSiblingSettled);
  279. expect(reachedCount).toBe(1);
  280. expect(results).toEqual([{ ok: true }]);
  281. });
  282. it("a cancel while parked stops the run and the sandbox goes down with it", async () => {
  283. const controller = new AbortController();
  284. const { settlement, driver } = await runLowered(
  285. 'await __host.hole("hole#1", "Verdict", undefined, (__src) => eval(__src)); return "NO";',
  286. {
  287. signal: controller.signal,
  288. onEvent: (event) => {
  289. if (event.type === "hole-reached") controller.abort("user");
  290. },
  291. },
  292. );
  293. expect(settlement).toEqual({ status: "stopped", reason: "user" });
  294. expect(driver.eventsOfType("hole-filled")).toEqual([]);
  295. });
  296. it("the control binding hands out fillHole, openHoles and filledHoles beside setMaxConcurrency", async () => {
  297. let bound: BoundEngine | undefined;
  298. const journal = new InMemoryJournalStore();
  299. const driver = new AutoDriver(journal);
  300. await runWorkflowScript({
  301. cwd: TEST_CWD,
  302. runId: `holes-${++runSeq}`,
  303. lowered: "return 1;",
  304. caps: { maxConcurrency: 4 },
  305. askSpecs: new Map(),
  306. validate: () => [],
  307. makeDriver: (sink) => {
  308. driver.attach(sink);
  309. return driver;
  310. },
  311. control: {
  312. bind(engine) {
  313. bound = engine;
  314. },
  315. },
  316. timeoutMs: 15000,
  317. });
  318. // 快照投影的两个只读面也经这条绑定交出去(run 已结算:停驻表空、本世没有补全)。
  319. expect(bound?.openHoles()).toEqual([]);
  320. expect(bound?.filledHoles()).toEqual([]);
  321. // 结算之后是 no-op:`settled`,不写不发。
  322. expect(bound?.fillHole(fillFor("(async () => 1)"))).toEqual({ ok: false, reason: "settled" });
  323. });
  324. });
  325. /** 内层留白的站点 id 带外层前缀(docs/analysis.md「Sites」):外层的体是有效脚本的一部分,体内的站点都是 `hole#1/…`。 */
  326. const INNER = "hole#1/hole#1";
  327. /** 外层补全的体:声明一个 const,再到达一处内层留白,把内层的值原样返回。 */
  328. const OUTER_WITH_INNER = [
  329. "(async () => {",
  330. ' const inside = "I" + (typeof i === "undefined" ? "" : i);',
  331. ` return await __host.hole("${INNER}", "inner", "q", (__src) => eval(__src));`,
  332. "})",
  333. ].join("\n");
  334. describe("holes — recursive: a fill that contains an open hole", () => {
  335. it("the inner request goes out with the nested siteId, parks only that branch, and its fill reads both scopes", async () => {
  336. const reached: HoleReached[] = [];
  337. const results: FillHoleResult[] = [];
  338. let openWhileInnerParked: unknown;
  339. const { settlement, driver } = await runLowered(
  340. [
  341. 'const before = "B";',
  342. 'const worker = __host.createActor("actor#1", "w");',
  343. 'const side = __host.future(async () => __host.ask("ask#1", worker, "hi"));',
  344. 'const v = await __host.hole("hole#1", "outer", "p", (__src) => eval(__src));',
  345. "return [await side, v];",
  346. ].join("\n"),
  347. {
  348. askSpecs: untyped("ask#1"),
  349. asks: { "ask#1": () => ({ type: "text", finalText: "sibling done" }) },
  350. onEvent: (event, engine) => {
  351. if (event.type !== "hole-reached") return;
  352. reached.push(event);
  353. if (event.instance.siteId === "hole#1") {
  354. results.push(engine().fillHole(fillFor(OUTER_WITH_INNER)));
  355. return;
  356. }
  357. // 内层停驻期间只有它自己在飞:拖一段真时间再补全,停滞检测若把停驻的留白当成
  358. // 「无在飞请求」,run 会在这段时间里 errored。
  359. openWhileInnerParked = engine().openHoles();
  360. setTimeout(() => {
  361. results.push(
  362. engine().fillHole(
  363. fillFor("(async () => { return before + inside; })", {
  364. siteId: INNER,
  365. askSpecs: untyped("ask#1", "hole#1/ask#1", `${INNER}/ask#1`),
  366. }),
  367. ),
  368. );
  369. }, 30);
  370. },
  371. },
  372. );
  373. expect(artifactOf(settlement)).toEqual(["sibling done", "BI"]);
  374. expect(results).toEqual([{ ok: true }, { ok: true }]);
  375. expect(reached.map((e) => [e.instance.siteId, e.instance.ordinal, e.name, e.prompt])).toEqual([
  376. ["hole#1", 1, "outer", "p"],
  377. [INNER, 1, "inner", "q"],
  378. ]);
  379. expect(openWhileInnerParked).toEqual([
  380. { siteId: INNER, ordinal: 1, name: "inner", since: expect.any(Number) },
  381. ]);
  382. expect(driver.eventsOfType("hole-filled").map((e) => e.siteId)).toEqual(["hole#1", INNER]);
  383. });
  384. it("reached again in a loop, both are answered from the cell's fill table and the inner sees the iteration's binding", async () => {
  385. const results: FillHoleResult[] = [];
  386. const { settlement, driver } = await runLowered(
  387. [
  388. 'const before = "B";',
  389. "const out = [];",
  390. "for (const i of [1, 2, 3]) {",
  391. ' out.push(await __host.hole("hole#1", "outer", undefined, (__src) => eval(__src)));',
  392. "}",
  393. "return out;",
  394. ].join("\n"),
  395. {
  396. onEvent: (event, engine) => {
  397. if (event.type !== "hole-reached") return;
  398. if (event.instance.siteId === "hole#1") {
  399. results.push(engine().fillHole(fillFor(OUTER_WITH_INNER)));
  400. } else {
  401. results.push(
  402. engine().fillHole(
  403. fillFor("(async () => { return before + inside; })", { siteId: INNER }),
  404. ),
  405. );
  406. }
  407. },
  408. },
  409. );
  410. expect(artifactOf(settlement)).toEqual(["BI1", "BI2", "BI3"]);
  411. // 两个站点各到达一次、各补全一次;后两轮外层与内层都不过线。
  412. expect(driver.eventsOfType("hole-reached").map((e) => e.instance.siteId)).toEqual([
  413. "hole#1",
  414. INNER,
  415. ]);
  416. expect(driver.eventsOfType("hole-filled").map((e) => e.siteId)).toEqual(["hole#1", INNER]);
  417. expect(results).toEqual([{ ok: true }, { ok: true }]);
  418. });
  419. it("an inner fill that throws rejects the inner site; uncaught, it propagates out of the outer body to the outer awaiter", async () => {
  420. const fillBoth = (event: RunEvent, engine: () => BoundEngine): void => {
  421. if (event.type !== "hole-reached") return;
  422. if (event.instance.siteId === "hole#1")
  423. return void engine().fillHole(fillFor(OUTER_WITH_INNER));
  424. engine().fillHole(
  425. fillFor('(async () => { throw new Error("inner boom"); })', { siteId: INNER }),
  426. );
  427. };
  428. const uncaught = await runLowered(
  429. [
  430. "try {",
  431. ' await __host.hole("hole#1", "outer", undefined, (__src) => eval(__src));',
  432. ' return "NO-THROW";',
  433. "} catch (e) {",
  434. ' return "outer caught: " + e.message;',
  435. "}",
  436. ].join("\n"),
  437. { onEvent: fillBoth },
  438. );
  439. expect(artifactOf(uncaught.settlement)).toBe("outer caught: inner boom");
  440. });
  441. it("an inner rejection caught inside the outer body stays inside it", async () => {
  442. const outerCatching = [
  443. "(async () => {",
  444. " try {",
  445. ` return await __host.hole("${INNER}", "inner", undefined, (__src) => eval(__src));`,
  446. " } catch (e) {",
  447. ' return "inner caught: " + e.message;',
  448. " }",
  449. "})",
  450. ].join("\n");
  451. const { settlement } = await runLowered(
  452. 'return await __host.hole("hole#1", "outer", undefined, (__src) => eval(__src));',
  453. {
  454. onEvent: (event, engine) => {
  455. if (event.type !== "hole-reached") return;
  456. if (event.instance.siteId === "hole#1")
  457. return void engine().fillHole(fillFor(outerCatching));
  458. engine().fillHole(
  459. fillFor('(async () => { throw new Error("inner boom"); })', { siteId: INNER }),
  460. );
  461. },
  462. },
  463. );
  464. expect(artifactOf(settlement)).toBe("inner caught: inner boom");
  465. });
  466. });