control-flow-projection.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import { describe, expect, it } from "vitest";
  2. import { analyzeWorkflowScript, phaseFlowToMermaid } from "../src/index.js";
  3. import { createStrandPark } from "../src/analysis/flow-strands.js";
  4. import { corpusDiagnostics } from "./helpers/analysis-corpus.js";
  5. /**
  6. * Scale pins for the control-flow projection (docs/analysis.md, 追记 2026-09-03).
  7. *
  8. * Two recorded scripts — xiangqi engines whose pure rule helpers get inlined a hundred times
  9. * each — made `projectControlFlow` exhaust the call stack after 12 s and 74 s of work. Neither
  10. * failure was deep recursion (33 frames): one was a source multiset doubling at every
  11. * leafless skippable choice until `push(...spread)` overflowed, the other a tree-ordering
  12. * comparator that re-walked whole subtrees per comparison. Both shapes are reproduced here
  13. * synthetically at a size that failed before the fix and completes in milliseconds after it.
  14. */
  15. function analyze(script: string) {
  16. const result = analyzeWorkflowScript(script);
  17. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  18. const flow = result.flow;
  19. const core = result.core;
  20. if (flow === undefined || core === undefined) throw new Error("expected a control-flow graph");
  21. return { core, flow };
  22. }
  23. /** A void helper of `n` skippable choices whose arm holds a nested choice that returns. */
  24. function leaflessChoices(n: number): string {
  25. let body = "";
  26. for (let i = 0; i < n; i += 1) body += ` if (x > ${i}) { if (x < 100) return; }\n`;
  27. return `function bump(x: number): void {\n${body}}
  28. const t = await agent("w").ask<string>("start");
  29. bump(t.length);
  30. return await agent("v").ask<string>(t);
  31. `;
  32. }
  33. /** Helpers h0…hD, each calling the next twice inside choices: ~2^(D+1) inlined call regions. */
  34. function deepInlining(depth: number): string {
  35. let src = "";
  36. for (let k = depth; k >= 0; k -= 1) {
  37. const inner = k === depth ? "if (x < 100) return;" : `h${k + 1}(x); if (x > ${k}) h${k + 1}(x + 1);`;
  38. src += `function h${k}(x: number): void { if (x > ${k}) { ${inner} } }\n`;
  39. }
  40. return `${src}const t = await agent("w").ask<string>("start");
  41. h0(t.length);
  42. return await agent("v").ask<string>(t);
  43. `;
  44. }
  45. describe("control-flow projection at scale", () => {
  46. it("keeps the source list a set through a run of leafless skippable choices", () => {
  47. // 24 such choices in sequence doubled the incoming source 2^24 times before the fix; the
  48. // spread in `exits.push(...armExits)` threw RangeError at a stack depth of 33 frames.
  49. const { flow } = analyze(leaflessChoices(24));
  50. // The helper contributes no node, so the CFG is the two asks in sequence plus the sink,
  51. // however large the helper is. Two kinds survive between the asks — the path that skips
  52. // every choice (`branch`) and the one that returns out of the helper (`next`) — because
  53. // the CFG keeps one edge per kind (render merges them); what must NOT survive is a copy.
  54. expect(flow.nodes.map((node) => node.id)).toEqual(["ask#1@1", "ask#2@1"]);
  55. expect(flow.edges.map((edge) => `${edge.from}>${edge.to}:${edge.kind}`)).toEqual([
  56. "entry>ask#1@1:next",
  57. "ask#1@1>ask#2@1:branch",
  58. "ask#1@1>ask#2@1:next",
  59. "ask#2@1>sink:jump",
  60. ]);
  61. });
  62. it("orders a 20k-region trace of nested inlined helpers in linear time", () => {
  63. // The tree ordering used to call `order(child)` inside the sort comparator, re-sorting
  64. // and re-walking each subtree per comparison — exponential in nesting depth (45 s on a
  65. // 2,500-region trace). Depth 11 here is ~20k regions; the bound is deliberately loose
  66. // (the unfixed comparator does not finish in minutes), so it cannot flake on a slow box.
  67. const started = Date.now();
  68. const { core, flow } = analyze(deepInlining(11));
  69. expect(core.trace.regions.length).toBeGreaterThan(10_000);
  70. expect(flow.nodes.map((node) => node.id)).toEqual(["ask#1@1", "ask#2@1"]);
  71. expect(Date.now() - started).toBeLessThan(10_000);
  72. });
  73. });
  74. /**
  75. * Strands (docs/analysis.md, the concurrent CFG). A `strand` region is one asynchronous
  76. * activation the walk inlined: control forks into it at the spawn, its exits are parked
  77. * (flow-strands.ts) instead of continuing the spawner's line, and they rejoin at the
  78. * barrier whose `joins` names it — or at the sink, when nothing awaits it.
  79. */
  80. const IDS = "const ids = [1, 2, 3];\n";
  81. /** `phase(name)` and a fan-out of `async` callbacks in it: one strand per phase. */
  82. function strandPhase(name: string, binding: string, tag: string): string {
  83. return (
  84. `phase(${JSON.stringify(name)});\n` +
  85. `const ${binding} = ids.map(async (i) => {\n` +
  86. ` const r = await agent(\`${tag}-\${i}\`).ask<string>(${JSON.stringify(tag)});\n` +
  87. " return r;\n" +
  88. "});\n"
  89. );
  90. }
  91. function edgeLines(flow: { edges: readonly { from: string; to: string; kind: string; via?: string }[] }): string[] {
  92. return flow.edges.map((edge) => `${edge.from} -> ${edge.to} ${edge.kind}${edge.via === undefined ? "" : ` via=${edge.via}`}`);
  93. }
  94. describe("strands", () => {
  95. // The reference shape of the whole refactor: two phases fan out `async` work, a single
  96. // barrier joins both, the third phase fans out again and the script returns. A ∥ B → C.
  97. const REFERENCE =
  98. IDS +
  99. strandPhase("A", "aWork", "a") +
  100. strandPhase("B", "bWork", "b") +
  101. "const both = await Promise.all([Promise.all(aWork), Promise.all(bWork)]);\n" +
  102. 'phase("C");\n' +
  103. "const merged = await Promise.all(\n" +
  104. " ids.map(async (i) => {\n" +
  105. ' const r = await agent(`c-${i}`).ask<string>(both.join(",") + String(i));\n' +
  106. " return r;\n" +
  107. " }),\n" +
  108. ");\n" +
  109. "return merged;\n";
  110. it("forks into each phase's strand and joins both at the one barrier", () => {
  111. const { flow } = analyze(REFERENCE);
  112. expect(flow.nodes.map((node) => node.id)).toEqual([
  113. "phase#1@1",
  114. "ask#1@1",
  115. "phase#2@1",
  116. "ask#2@1",
  117. "phase#3@1",
  118. "ask#3@1",
  119. ]);
  120. // A's and B's asks reach C's marker by a `join`, not by the sequential line: the
  121. // spawner walked straight from marker to marker while they ran.
  122. expect(edgeLines(flow)).toEqual([
  123. "entry -> phase#1@1 next",
  124. "phase#1@1 -> ask#1@1 fork",
  125. "phase#1@1 -> phase#2@1 next",
  126. "ask#1@1 -> phase#3@1 join via=return",
  127. "phase#2@1 -> ask#2@1 fork",
  128. "phase#2@1 -> phase#3@1 next",
  129. "ask#2@1 -> phase#3@1 join via=return",
  130. "phase#3@1 -> ask#3@1 fork",
  131. "phase#3@1 -> sink jump via=return",
  132. "ask#3@1 -> sink join via=return",
  133. ]);
  134. });
  135. it("records the phases still running at a marker as `alongside`, on the node and the phase", () => {
  136. const { flow } = analyze(REFERENCE);
  137. const alongside = Object.fromEntries(
  138. flow.nodes.filter((node) => node.kind === "mark").map((node) => [node.id, node.alongside]),
  139. );
  140. // B is entered while A's strand is parked; C is entered after the barrier joined both.
  141. expect(alongside).toEqual({ "phase#1@1": undefined, "phase#2@1": ["phase#1"], "phase#3@1": undefined });
  142. expect(flow.phases?.map((phase) => [phase.id, phase.alongside])).toEqual([
  143. ["phase#1", undefined],
  144. ["phase#2", ["phase#1"]],
  145. ["phase#3", undefined],
  146. ]);
  147. // It is a node fact, never an edge: no `alongside` kind exists in the quotient.
  148. expect(flow.phaseEdges?.every((edge) => edge.kind !== ("alongside" as never))).toBe(true);
  149. });
  150. it("draws each alongside pair as one dashed link, earlier phase first", () => {
  151. const { flow } = analyze(REFERENCE);
  152. const drawn = phaseFlowToMermaid(flow)
  153. .split("\n")
  154. .filter((line) => line.includes("alongside"));
  155. expect(drawn).toEqual([' phase_1 -.->|"alongside"| phase_2']);
  156. });
  157. it("leaves a marker's own phase out of its `alongside`", () => {
  158. // The third marker re-enters A while A's OWN strand is still parked; only B's counts.
  159. const { flow } = analyze(
  160. IDS +
  161. strandPhase("A", "aWork", "a") +
  162. strandPhase("B", "bWork", "b") +
  163. 'phase("A");\n' +
  164. "const tail = await Promise.all([Promise.all(aWork), Promise.all(bWork)]);\n" +
  165. "return tail;\n",
  166. );
  167. const reentry = flow.nodes.find((node) => node.id === "phase#1@2");
  168. expect(reentry?.phase).toBe("phase#1");
  169. expect(reentry?.alongside).toEqual(["phase#2"]);
  170. });
  171. it("leaves a strand the marker sits inside out of its `alongside`", () => {
  172. // Unreachable from a script today — a strand parks only once its body is finished, so
  173. // a marker inside it is always flowed first — but the rule is what makes `alongside`
  174. // mean "running BESIDE me", so it is pinned where it lives.
  175. const park = createStrandPark([
  176. { id: "phase#1", loc: { column: 1, line: 1 }, name: "A" },
  177. { id: "phase#2", loc: { column: 1, line: 2 }, name: "B" },
  178. ]);
  179. park.park("call#1", [{ from: "ask#1@1", kind: "join" }], ["phase#1"]);
  180. park.park("fanout#1", [{ from: "ask#2@1", kind: "join" }], ["phase#2"]);
  181. expect(park.alongside("phase#3", ["seq#1"])).toEqual(["phase#1", "phase#2"]);
  182. expect(park.alongside("phase#3", ["seq#1", "call#1"])).toEqual(["phase#2"]);
  183. expect(park.alongside("phase#2", ["seq#1", "call#1"])).toEqual([]);
  184. });
  185. it("joins a strand nothing awaits at the sink, and counts it alongside every later phase", () => {
  186. // `aWork.length` is an opaque position: the walk joins nothing, so the strand is
  187. // fire-and-forget and the only thing known about it is that the script outlived it.
  188. const { flow } = analyze(
  189. IDS +
  190. strandPhase("A", "aWork", "a") +
  191. 'phase("B");\n' +
  192. "const tail = await agent(\"tail\").ask<string>(`count ${aWork.length}`);\n" +
  193. "return tail;\n",
  194. );
  195. expect(flow.nodes.find((node) => node.id === "phase#2@1")?.alongside).toEqual(["phase#1"]);
  196. expect(edgeLines(flow)).toEqual([
  197. "entry -> phase#1@1 next",
  198. "phase#1@1 -> ask#1@1 fork",
  199. "phase#1@1 -> phase#2@1 next",
  200. "ask#1@1 -> sink join via=return",
  201. "phase#2@1 -> ask#2@1 next",
  202. "ask#2@1 -> sink jump via=return",
  203. ]);
  204. });
  205. it("unparks at a barrier that joins a strand but settles nothing new", () => {
  206. // The second call to one `async` helper: its step was already settled by the FIRST
  207. // call's join, so the walk emits `settle` with no steps and only `joins`. The join is
  208. // still a control-flow fact, and the strand's exit must land on the node after it.
  209. const { core, flow } = analyze(
  210. "async function fetchOne(topic: string): Promise<string> {\n" +
  211. " const r = await agent(\"worker\").ask<string>(`do ${topic}`);\n" +
  212. " return r;\n" +
  213. "}\n" +
  214. 'const alpha = await fetchOne("alpha");\n' +
  215. 'const beta = await fetchOne("beta");\n' +
  216. "const tail = await agent(\"tail\").ask<string>(`${alpha} ${beta}`);\n" +
  217. "return tail;\n",
  218. );
  219. const joinOnly = core.trace.events.filter(
  220. (event) => event.at === "settle" && event.steps.length === 0 && event.joins !== undefined,
  221. );
  222. expect(joinOnly).toHaveLength(1);
  223. // Without the unpark, ask#1@2 would fall through to the sink instead of reaching the
  224. // tail — that edge IS the join-only settle doing its work.
  225. expect(edgeLines(flow)).toContain("ask#1@2 -> ask#2@1 join via=return");
  226. expect(edgeLines(flow)).not.toContain("ask#1@2 -> sink join via=return");
  227. });
  228. it("never parks the spawner's own source, so no entry placeholder escapes", () => {
  229. // Mutual recursion through `async` helpers: the recursion SCC is folded into a `loop`,
  230. // and the strand that carries the base-case ask is spawned as the first thing inside
  231. // that loop body, so its incoming source is the body's entry PLACEHOLDER. Its `return`
  232. // met no node on the way out and still stands on `$entry1`; parking it put an edge out
  233. // of a node that never existed into the finished graph. Note the strand is NOT
  234. // node-free — it holds `ask#1` — which is why `entries.length === 0` cannot catch this.
  235. const { flow } = analyze(
  236. 'const judge = agent("judge");\n' +
  237. "async function even(s: string, n: number): Promise<string> {\n" +
  238. " if (n <= 0) return await judge.ask<string>(`final ${s}`);\n" +
  239. " return odd(s, n - 1);\n" +
  240. "}\n" +
  241. "async function odd(s: string, n: number): Promise<string> {\n" +
  242. " return even(s, n - 1);\n" +
  243. "}\n" +
  244. 'const seed = await agent("s").ask<string>("seed");\n' +
  245. "const out = await even(seed, 4);\n" +
  246. "return out;\n",
  247. );
  248. const known = new Set([...flow.nodes.map((node) => node.id), "entry", "sink", "abort"]);
  249. const dangling = flow.edges.filter((edge) => !known.has(edge.from) || !known.has(edge.to));
  250. expect(dangling).toEqual([]);
  251. expect(edgeLines(flow)).toEqual([
  252. "entry -> ask#2@1 next",
  253. "ask#2@1 -> ask#1@1 fork",
  254. "ask#2@1 -> ask#1@1 loop via=recur",
  255. "ask#2@1 -> sink jump via=return",
  256. "ask#1@1 -> sink join via=return",
  257. ]);
  258. });
  259. it("parks a node-free strand whose barrier joins a strand that is not", () => {
  260. // `p.then(onOk, onErr).finally(...)`: the `.finally` continuation is a strand holding
  261. // no call of its own, so nothing the entry placeholder reached is a node — but its
  262. // barrier joins both `.then` strands, and THEIR exits are the body's exits. Treating
  263. // it as invisible left `ask#2@1` and `ask#3@1` with no outgoing edge at all.
  264. const { flow } = analyze(
  265. 'const draft = agent("writer").ask<string>("draft");\n' +
  266. "const settled = await Promise.resolve(draft)\n" +
  267. " .then(\n" +
  268. " (t) => agent(\"editor\").ask<string>(`edit ${t}`),\n" +
  269. " (e) => agent(\"fixer\").ask<string>(`recover ${String(e)}`),\n" +
  270. " )\n" +
  271. ' .finally(() => log("done"));\n' +
  272. "return settled;\n",
  273. );
  274. expect(edgeLines(flow)).toEqual([
  275. "entry -> ask#1@1 next",
  276. "ask#1@1 -> ask#2@1 branch",
  277. "ask#1@1 -> ask#3@1 branch",
  278. "ask#1@1 -> sink jump via=return",
  279. "ask#2@1 -> sink join",
  280. "ask#3@1 -> sink join",
  281. ]);
  282. });
  283. });