callback-invocation.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. });