callback-invocation.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import { describe, expect, it } from "vitest";
  2. import { analyzeWorkflowScript, serializeCore } from "../src/index.js";
  3. import type { OrderRegion } from "../src/analysis/causality-order.js";
  4. import { corpusDiagnostics } from "./helpers/analysis-corpus.js";
  5. /**
  6. * Callback invocation (docs/analysis.md): the ordering walk inlines
  7. * exactly the bodies the interpreter applied at each call — the CALL ORACLE — and the callback
  8. * registry says how often a library invokes a callback. These are the behavioural pins the
  9. * corpus goldens cannot state as invariants: each case names the shape, the region the body
  10. * must land in, and the phase its steps must belong to.
  11. */
  12. function trace(script: string) {
  13. const result = analyzeWorkflowScript(script);
  14. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  15. const core = result.core;
  16. const causality = result.causality;
  17. if (core === undefined || causality === undefined) throw new Error("expected a clean analysis");
  18. return { causality, core, regions: core.trace.regions, result };
  19. }
  20. function regionsOf(regions: readonly OrderRegion[], kind: OrderRegion["kind"]): OrderRegion[] {
  21. return regions.filter((region) => region.kind === kind);
  22. }
  23. function phaseOfStep(result: ReturnType<typeof trace>, id: string): string | undefined {
  24. return result.causality.steps.find((step) => step.id === id)?.phase;
  25. }
  26. describe("callback invocation — the call oracle", () => {
  27. it("never leaves a function value that reaches a call to the sweep", () => {
  28. const { regions } = trace(`
  29. const paths = await files.glob("*.md");
  30. const review = (p: string) => agent("reviewer").ask<string>(\`review \${p}\`);
  31. const helper = (fn: () => Node<string>) => fn();
  32. const a = await Promise.all(paths.map(review));
  33. const b = await helper(() => agent("b").ask<string>("b"));
  34. const c = await Promise.resolve(a).then(() => agent("c").ask<string>("c"));
  35. const d = await new Promise<string>((resolve) => { agent("d").ask<string>("d").then(resolve); });
  36. const e = await Array.from(paths, (p) => agent("e").ask<string>(p)).length;
  37. return [a, b, c, d, e];
  38. `);
  39. expect(regions.filter((region) => region.detached === true)).toEqual([]);
  40. });
  41. it("sweeps ONLY a body no call ever applies", () => {
  42. const { regions } = trace(`
  43. const unused = () => agent("ghost").ask<string>("never");
  44. return await agent("w").ask<string>("w");
  45. `);
  46. const detached = regions.filter((region) => region.detached === true);
  47. expect(detached.map((region) => region.label)).toEqual(["unused"]);
  48. });
  49. it("phases a callback body by the phase current at the invoking call", () => {
  50. const result = trace(`
  51. phase("scan");
  52. const paths = await files.glob("*.md");
  53. const review = (p: string) => agent("reviewer").ask<string>(\`review \${p}\`);
  54. const out = await Promise.all(paths.map(review));
  55. phase("report");
  56. return await agent("summarizer").ask<string>(JSON.stringify(out));
  57. `);
  58. expect(phaseOfStep(result, "ask#1")).toBe("phase#1");
  59. expect(phaseOfStep(result, "ask#2")).toBe("phase#2");
  60. // The named callback's ask sits inside the map's fanout, as an inlined call.
  61. const fanout = regionsOf(result.regions, "fanout").find((region) => region.label === "map");
  62. expect(fanout).toBeDefined();
  63. expect(regionsOf(result.regions, "call").some((region) => region.parent === fanout?.id && region.label === "review")).toBe(true);
  64. // And the summarizer runs AFTER the reviewers, never before (the sweep artifact).
  65. expect(result.causality.edges.some((edge) => edge.from === "ask#2" && edge.to === "ask#1")).toBe(false);
  66. });
  67. it("inlines a callback invoked through a helper's parameter", () => {
  68. const result = trace(`
  69. phase("work");
  70. async function withRetry(job: () => Node<string>): Promise<string> { return await job(); }
  71. const a = await withRetry(() => agent("worker").ask<string>("do it"));
  72. phase("check");
  73. return await agent("checker").ask<string>(a);
  74. `);
  75. expect(phaseOfStep(result, "ask#1")).toBe("phase#1");
  76. const calls = regionsOf(result.regions, "call");
  77. const outer = calls.find((region) => region.label === "withRetry");
  78. expect(outer).toBeDefined();
  79. expect(calls.some((region) => region.parent === outer?.id)).toBe(true);
  80. });
  81. it("opens a skippable choice around a deferred continuation and settles its receiver first", () => {
  82. const { core, regions } = trace(`
  83. const draft = agent("writer").ask<string>("draft");
  84. const edited = await draft.then((t) => agent("editor").ask<string>(t));
  85. return edited;
  86. `);
  87. const call = regionsOf(regions, "call").find((region) => region.label === "then");
  88. expect(call).toBeDefined();
  89. const arm = regions.find((region) => region.id === call?.parent);
  90. expect(arm?.kind).toBe("branch");
  91. expect(arm?.entered).toBe(false);
  92. expect(regions.find((region) => region.id === arm?.parent)?.kind).toBe("choice");
  93. // A deferred continuation is a STRAND: the `call` region is its frame, and the
  94. // receiver barrier is its prologue — an ordinary barrier, so a singleton exact
  95. // receiver settles CERTAINLY (the strand model replaced `settleLocally`'s blanket
  96. // may-claim with frame scoping, analyzer-strands-plan.md「The walk」).
  97. expect(call?.strand).toBe(true);
  98. const events = core.trace.events;
  99. const settle = events.findIndex((event) => event.at === "settle" && event.steps.includes("ask#1"));
  100. const issue = events.findIndex((event) => event.at === "issue" && event.step === "ask#2");
  101. expect(settle).toBeGreaterThanOrEqual(0);
  102. expect(settle).toBeLessThan(issue);
  103. expect(events[settle]).toMatchObject({ maybe: false });
  104. // It settled INSIDE the strand, so it says nothing to the main line: the frame is the
  105. // callback's own `call` region, not the root.
  106. expect(events[settle]?.regions).toContain(call?.id);
  107. // The main line's own await settles the editor for real, and joins the strand.
  108. const outer = events.find(
  109. (event) => event.at === "settle" && !event.maybe && event.steps.includes("ask#2"),
  110. );
  111. expect(outer).toBeDefined();
  112. expect(outer?.at === "settle" ? outer.joins : undefined).toContain(call?.id);
  113. });
  114. it("records a join-only settle when the joined strand's summary is already settled", () => {
  115. // A JOIN IS A CONTROL-FLOW FACT whether or not it settles anything: it is where the
  116. // strand's parked exits reconnect. Here the strand awaits a step the MAIN LINE awaits
  117. // first, so by `await p` the whole summary is already visible in the root frame and the
  118. // barrier settles nothing new. Dropping the event would leave the strand parked forever
  119. // in the control-flow projection, so it is recorded with no steps to its name.
  120. const { core, regions } = trace(`
  121. const first = agent("a").ask<string>("x");
  122. async function h(): Promise<void> {
  123. await first;
  124. }
  125. const p = h();
  126. await first;
  127. await p;
  128. return first;
  129. `);
  130. const call = regionsOf(regions, "call").find((region) => region.label === "h");
  131. expect(call).toBeDefined();
  132. expect(call?.strand).toBe(true);
  133. const settles = core.trace.events.filter((event) => event.at === "settle");
  134. expect(settles[settles.length - 1]).toMatchObject({
  135. joins: [call?.id],
  136. maybe: false,
  137. steps: [],
  138. });
  139. // A step-less settle prints without the step token, so the line keeps single spaces.
  140. const text = serializeCore(core);
  141. expect(text).toContain(`settle in=seq#1 joins=${call?.id ?? ""}`);
  142. expect(text).not.toContain("settle in=");
  143. });
  144. it("keeps an ordering edge from receiver steps into a continuation that ignores the value", () => {
  145. const result = trace(`
  146. const a = agent("a").ask<string>("x");
  147. const b = agent("b").ask<string>("y");
  148. const r = await Promise.all([a, b]).catch(() => agent("fallback").ask<string>("recover"));
  149. return r;
  150. `);
  151. const into = result.causality.edges.filter((edge) => edge.to === "ask#3").map((edge) => edge.from).sort();
  152. expect(into).toEqual(["ask#1", "ask#2"]);
  153. });
  154. it("does not smear sibling callbacks into a callback's parameters as callables", () => {
  155. // `Promise.resolve(text)` inside the outer continuation must not re-apply the outer
  156. // continuation to itself (phantom recursion → a `loop` region).
  157. const { regions } = trace(`
  158. const draft = agent("writer").ask<string>("draft");
  159. const out = await draft.then((text) =>
  160. Promise.resolve(text).then((inner) => agent("editor").ask<string>(\`edit \${inner}\`)),
  161. );
  162. return out;
  163. `);
  164. expect(regionsOf(regions, "loop")).toEqual([]);
  165. expect(regionsOf(regions, "call").map((region) => region.label)).toEqual(["then", "then"]);
  166. });
  167. it("never dispatches a library member on the callables its receiver value carries", () => {
  168. // `.finally` on a `.then(a, b)` result: a and b are the receiver's contents, not the callee.
  169. const { regions } = trace(`
  170. const draft = agent("writer").ask<string>("draft");
  171. const settled = await Promise.resolve(draft)
  172. .then((t) => agent("editor").ask<string>(t), (e) => agent("fixer").ask<string>(String(e)))
  173. .finally(() => log("done"));
  174. return settled;
  175. `);
  176. expect(regionsOf(regions, "call").map((region) => region.label)).toEqual(["then", "then", "finally"]);
  177. expect(regionsOf(regions, "choice").filter((region) => region.exhaustive === true)).toEqual([]);
  178. });
  179. it("inlines an indirect dispatch over several targets as one exhaustive choice", () => {
  180. const { regions, causality } = trace(`
  181. const seed = await agent("seed").ask<string>("seed");
  182. const fast = (s: string) => agent("fast").ask<string>(s);
  183. const slow = (s: string) => agent("slow").ask<string>(s);
  184. const pick = seed.length > 3 ? fast : slow;
  185. return await pick(seed);
  186. `);
  187. // The ternary is a choice too; the dispatch is the one whose arms hold inlined calls.
  188. const calls = regionsOf(regions, "call");
  189. const choice = regionsOf(regions, "choice").find(
  190. (region) =>
  191. region.exhaustive === true &&
  192. regions.some((arm) => arm.parent === region.id && calls.some((call) => call.parent === arm.id)),
  193. );
  194. expect(choice).toBeDefined();
  195. const arms = regions.filter((region) => region.parent === choice?.id);
  196. expect(arms.every((arm) => arm.kind === "branch" && arm.entered === false)).toBe(true);
  197. const labels = arms.map((arm) => calls.find((call) => call.parent === arm.id)?.label).sort();
  198. expect(labels).toEqual(["fast", "slow"]);
  199. expect(causality.steps.filter((step) => step.id !== "ask#1").every((step) => step.certainty === "maybe")).toBe(true);
  200. });
  201. it("inlines a script class constructor at `new`, labelled by the class", () => {
  202. const { regions } = trace(`
  203. class Judge {
  204. verdict: Node<string>;
  205. constructor(s: string) { this.verdict = agent("judge").ask<string>(s); }
  206. }
  207. const j = new Judge("case");
  208. return await j.verdict;
  209. `);
  210. expect(regionsOf(regions, "call").map((region) => region.label)).toEqual(["Judge"]);
  211. expect(regions.filter((region) => region.detached === true)).toEqual([]);
  212. });
  213. });
  214. describe("callback invocation — the registry", () => {
  215. it("treats `Array.from(xs, fn)` as a per-element fan-out over its first argument", () => {
  216. const { core, regions } = trace(`
  217. const paths = await files.glob("*.md");
  218. const out = await Promise.all(Array.from(paths, (p) => agent("r").ask<string>(p)));
  219. return out;
  220. `);
  221. expect(regionsOf(regions, "fanout").map((region) => region.label)).toEqual(["from"]);
  222. expect(core.sites.fanouts).toHaveLength(1);
  223. expect(core.sites.asks[0]?.within).toBe("fan-out#1");
  224. // The iterated collection feeds the fan-out relay.
  225. expect(core.facts.fanoutIn.get("fan-out#1")?.map((occ) => occ.site)).toEqual(["world-read#1"]);
  226. });
  227. it("gives an object-length fan-out no cardinality but a `many` family", () => {
  228. const { core, result } = trace(`
  229. const TOTAL = 3;
  230. const items = await Promise.all(Array.from({ length: TOTAL }, (_, i) => agent(\`w-\${i}\`).ask<string>(String(i))));
  231. return items;
  232. `);
  233. expect(core.sites.fanouts[0]?.cardinality).toBeUndefined();
  234. expect(result.handoff?.participants.map((participant) => participant.many)).toEqual([true]);
  235. });
  236. it("binds both comparator parameters of `sort` to the element", () => {
  237. const { core } = trace(`
  238. const paths = await files.glob("*.md");
  239. const sorted = paths.sort((a, b) => a.localeCompare(b));
  240. const picked = [...sorted].sort((a, b) => {
  241. agent("cmp").ask<string>(a + b);
  242. return 0;
  243. });
  244. return picked;
  245. `);
  246. // The second sort's comparator reaches a facade site and promotes; its ask reads the element.
  247. expect(core.sites.fanouts).toHaveLength(1);
  248. expect(core.facts.askData.get("ask#1")?.some((occ) => occ.site === "fan-out#1")).toBe(true);
  249. });
  250. it("leaves a script-declared `.map` / `.then` to the callee path", () => {
  251. const { regions } = trace(`
  252. const pipeline = {
  253. map(fn: (x: string) => Node<string>) { return fn("x"); },
  254. then(fn: (x: string) => Node<string>) { return fn("y"); },
  255. };
  256. const a = await pipeline.map((x) => agent("a").ask<string>(x));
  257. const b = await pipeline.then((y) => agent("b").ask<string>(y));
  258. return [a, b];
  259. `);
  260. expect(regionsOf(regions, "fanout")).toEqual([]);
  261. // Each user method inlines as a call; the callback inlines inside it through the parameter.
  262. expect(regionsOf(regions, "call").map((region) => region.label)).toEqual(["map", undefined, "then", undefined]);
  263. expect(regions.filter((region) => region.detached === true)).toEqual([]);
  264. });
  265. it("runs a Promise executor once, certainly", () => {
  266. const result = trace(`
  267. const gate = await new Promise<string>((resolve) => { agent("g").ask<string>("go").then(resolve); });
  268. return gate;
  269. `);
  270. const call = regionsOf(result.regions, "call").find((region) => region.label === "Promise");
  271. expect(call?.entered).toBe(true);
  272. expect(result.causality.steps[0]?.certainty).toBe("always");
  273. });
  274. });
  275. /**
  276. * Callbacks bound through a parameter (docs/analysis.md "The call oracle", "Inlining"): the
  277. * oracle records WHICH parameter a call applies and WHAT each call site bound to it, and the
  278. * walk resolves the two against the activation it is inlining. These pins state what the
  279. * corpus goldens show for shared-helper-*.ts as invariants on the trace.
  280. */
  281. describe("callbacks bound through a parameter", () => {
  282. const LIMITED = "async function limited(fn: () => Promise<string>): Promise<string> { return await fn(); }\n";
  283. it("inlines only the callback the call being inlined passed", () => {
  284. const { core, regions } = trace(`
  285. ${LIMITED}const xs0 = ["a", "b"];
  286. const xs1 = ["c", "d"];
  287. const out: string[] = [];
  288. out.push(...(await Promise.all(xs0.map(async (x) => limited(async () => agent(\`f0-\${x}\`).ask<string>(\`do \${x}\`))))));
  289. out.push(...(await Promise.all(xs1.map(async (x) => limited(async () => agent(\`f1-\${x}\`).ask<string>(\`do \${x}\`))))));
  290. out.push(await limited(async () => agent("m0").ask<string>("top 0")));
  291. out.push(await limited(async () => {
  292. const inner = await limited(async () => agent("n1").ask<string>("nested"));
  293. return agent("m1").ask<string>(\`after \${inner}\`);
  294. }));
  295. return out;
  296. `);
  297. // Five calls of the helper, each inlining exactly one callback: ten call regions, no
  298. // choice (no "one of every caller's callback"), no loop (the nested use is not recursion).
  299. expect(regionsOf(regions, "call")).toHaveLength(10);
  300. expect(regionsOf(regions, "choice")).toEqual([]);
  301. expect(regionsOf(regions, "loop")).toEqual([]);
  302. // Each step belongs to the fan-out that passed its callback, or to none.
  303. expect(core.sites.asks.map((ask) => [ask.label, ask.within])).toEqual([
  304. ["ask", "fan-out#1"],
  305. ["ask", "fan-out#2"],
  306. ["m0", undefined],
  307. ["n1", undefined],
  308. ["m1", undefined],
  309. ]);
  310. expect(core.sites.actors.map((actor) => actor.within)).toEqual(["fan-out#1", "fan-out#2", undefined, undefined, undefined]);
  311. });
  312. it("resolves a callback through two wrapper layers", () => {
  313. const { regions } = trace(`
  314. ${LIMITED}async function retry(fn: () => Promise<string>): Promise<string> { return await limited(() => fn()); }
  315. const a = await retry(async () => agent("a").ask<string>("a"));
  316. const b = await retry(async () => agent("b").ask<string>("b"));
  317. const c = await retry(async () => agent("c").ask<string>("c"));
  318. return [a, b, c];
  319. `);
  320. // retry → limited → arrow → callback: four call regions per caller, nothing else.
  321. expect(regionsOf(regions, "call")).toHaveLength(12);
  322. expect(regionsOf(regions, "choice")).toEqual([]);
  323. });
  324. it("resolves a parameter handed on to a library call", () => {
  325. const { regions } = trace(`
  326. async function later(fn: () => Promise<string>): Promise<string> { return Promise.resolve("go").then(fn); }
  327. const a = await later(async () => agent("a").ask<string>("a"));
  328. const b = await later(async () => agent("b").ask<string>("b"));
  329. return [a, b];
  330. `);
  331. // later + its own `.then` callback, twice.
  332. expect(regionsOf(regions, "call")).toHaveLength(4);
  333. });
  334. it("resolves a parameter handed to a per-element library call", () => {
  335. const { core, regions } = trace(`
  336. async function each(xs: string[], fn: (x: string) => Promise<string>): Promise<string[]> { return Promise.all(xs.map(fn)); }
  337. const ids = ["1", "2"];
  338. const a = await each(ids, async (x) => agent(\`a-\${x}\`).ask<string>(\`a \${x}\`));
  339. const b = await each(ids, async (x) => agent(\`b-\${x}\`).ask<string>(\`b \${x}\`));
  340. return [...a, ...b];
  341. `);
  342. // each + its own callback inside the one map site, twice; both asks run per element of it.
  343. expect(regionsOf(regions, "call")).toHaveLength(4);
  344. expect(regionsOf(regions, "fanout")).toHaveLength(2);
  345. expect(core.sites.asks.map((ask) => ask.within)).toEqual(["fan-out#1", "fan-out#1"]);
  346. });
  347. it("keeps recursion when the re-entrant call rebinds the same callback", () => {
  348. const { regions } = trace(`
  349. interface Tree { name: string; children: Tree[] }
  350. async function walkTree(node: Tree, visit: (n: Tree) => Promise<string>): Promise<void> {
  351. await visit(node);
  352. for (const child of node.children) await walkTree(child, visit);
  353. }
  354. const root: Tree = { name: "r", children: [] };
  355. await walkTree(root, async (n) => agent(\`v-\${n.name}\`).ask<string>(\`visit \${n.name}\`));
  356. return "done";
  357. `);
  358. expect(regionsOf(regions, "loop").filter((region) => region.recursive === true)).toHaveLength(1);
  359. // walkTree once, visit once; the re-entrant call is a recur jump, not a third call.
  360. expect(regionsOf(regions, "call")).toHaveLength(2);
  361. });
  362. it("falls back to every caller's callback when the parameter reaches the call through an alias", () => {
  363. const { regions } = trace(`
  364. async function viaAlias(fn: () => Promise<string>): Promise<string> { const h = fn; return await h(); }
  365. const a = await viaAlias(async () => agent("a").ask<string>("a"));
  366. const b = await viaAlias(async () => agent("b").ask<string>("b"));
  367. return [a, b];
  368. `);
  369. // Provenance is lost through `h`, so each call inlines both callbacks as an exhaustive choice.
  370. expect(regionsOf(regions, "choice")).toHaveLength(2);
  371. expect(regionsOf(regions, "call")).toHaveLength(6);
  372. });
  373. it("keeps within as a may-fact for a helper called inside and outside a fan-out", () => {
  374. const { core } = trace(`
  375. async function step(x: string): Promise<string> { return agent("w").ask<string>(x); }
  376. const ids = ["1", "2"];
  377. const a = await Promise.all(ids.map((x) => step(x)));
  378. const b = await step("solo");
  379. return [...a, b];
  380. `);
  381. expect(core.sites.asks[0]?.within).toBe("fan-out#1");
  382. });
  383. });