convergence.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import { describe, expect, it } from "vitest";
  2. import { analyzeWorkflowScript, collectSites, createWorkflowProgram, interpret } from "../src/index.js";
  3. import { corpusDiagnostics } from "./helpers/analysis-corpus.js";
  4. /**
  5. * Fixpoint convergence pins (docs/analysis.md, "Convergence": the canonical-heap rule).
  6. *
  7. * The taint fixpoint is gen-only over a finite lattice, so the only way it fails to settle
  8. * is a transfer that reports a change every pass without the state growing: a persistent
  9. * merge INTO a value that is recreated each pass. Each case here is a shape that once did
  10. * exactly that. The assertion is the analysis completing at all — `analyzeWorkflowScript`
  11. * throws at ITERATION_CAP — plus, where the fix changed what the graph can see, the fact it
  12. * now sees.
  13. */
  14. function analyze(script: string) {
  15. const result = analyzeWorkflowScript(script);
  16. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  17. const causality = result.causality;
  18. if (causality === undefined) throw new Error("expected a causality graph");
  19. return { causality, result };
  20. }
  21. const hasEdge = (edges: ReadonlyArray<{ from: string; to: string }>, from: string, to: string): boolean =>
  22. edges.some((edge) => edge.from === from && edge.to === to);
  23. describe("convergence — container literals are allocation-site places", () => {
  24. it("converges when a callee writes a NEW field through a parameter bound to an inline object literal", () => {
  25. // The minimal shape: nothing here is exotic. Before literals had a persistent place this
  26. // failed on every analyzer generation since 2026-08-17.
  27. analyze(`
  28. function tag(box: { name: string; note?: string }, t: string): void { box.note = t; }
  29. const t = await agent("s").ask<string>("q");
  30. tag({ name: "x" }, t);
  31. return t;
  32. `);
  33. });
  34. it("converges for an inline array literal mutated by the callee", () => {
  35. analyze(`
  36. function fill(xs: string[], t: string): void { xs.push(t); }
  37. const t = await agent("s").ask<string>("q");
  38. fill([], t);
  39. return t;
  40. `);
  41. });
  42. it("converges when the write-back carries no taint at all", () => {
  43. // The re-reported change was the write-back's own doing, not the data it carried.
  44. analyze(`
  45. function tag(box: { name: string; note?: string }, t: string): void { box.note = t; }
  46. tag({ name: "x" }, "plain");
  47. return await agent("s").ask<string>("q");
  48. `);
  49. });
  50. it("converges for a nested literal argument written through two levels", () => {
  51. analyze(`
  52. function deep(p: { inner: { items: string[] } }, t: string): void { p.inner.items.push(t); }
  53. const t = await agent("s").ask<string>("q");
  54. deep({ inner: { items: [] } }, t);
  55. return t;
  56. `);
  57. });
  58. it("makes the field written on the literal visible through the reference the callee returns", () => {
  59. // Persistence is not only about termination: the note now survives to the reader.
  60. const { causality } = analyze(`
  61. function tag(box: { name: string; note?: string }, t: string): { name: string; note?: string } {
  62. box.note = t;
  63. return box;
  64. }
  65. const t = await agent("writer").ask<string>("draft");
  66. const r = tag({ name: "x" }, t);
  67. return agent("reader").ask<string>(\`use \${r.note}\`);
  68. `);
  69. expect(hasEdge(causality.edges, "ask#1", "ask#2")).toBe(true);
  70. });
  71. it("keeps a literal's field that stores a live place aliased to that place", () => {
  72. // `{ box }` stores box's slot itself; the persistent literal place must not turn that alias
  73. // into a copy on later passes (heap-aliasing-param-literal-wrap pins the golden).
  74. const { causality } = analyze(`
  75. const box: { f: string } = { f: "" };
  76. async function poke(p: { box: { f: string } }): Promise<void> {
  77. p.box.f = await agent("writer").ask<string>("secret");
  78. }
  79. await poke({ box });
  80. return agent("reader").ask<string>(\`use \${box.f}\`);
  81. `);
  82. expect(hasEdge(causality.edges, "ask#1", "ask#2")).toBe(true);
  83. });
  84. it("re-evaluates the literal every pass (a site inside it is never short-circuited)", () => {
  85. // The place is reached only through evaluation, never through resolvePlace, so the ask
  86. // nested in the literal keeps its node and its edge.
  87. const { causality } = analyze(`
  88. const seed = await agent("seed").ask<string>("s");
  89. const bundle = { text: await agent("writer").ask<string>(seed), tag: "x" };
  90. return agent("reader").ask<string>(bundle.text);
  91. `);
  92. expect(hasEdge(causality.edges, "ask#1", "ask#2")).toBe(true);
  93. expect(hasEdge(causality.edges, "ask#2", "ask#3")).toBe(true);
  94. });
  95. });
  96. describe("convergence — the keystone-leak family (recorded real scripts, 2026-09-03)", () => {
  97. // Seven recorded workflows stopped converging when a library member call started dispatching
  98. // on tracked functions carried by its receiver: the keystone pot had leaked the callback
  99. // itself into the result of `sort(cmp)` / `JSON.parse(text, reviver)`, so a later
  100. // `top.push({ … })` applied the callback with the literal as its actual and hit the
  101. // write-back above. Two independent tightenings close the path (the pot strips callables,
  102. // library members never dispatch on receiver fns); the literal place removes the cliff.
  103. it("sort comparator, then push of a literal into the sorted result", () => {
  104. analyze(`
  105. interface C { name: string; confidence: number }
  106. const candidates = await agent("s").ask<C[]>("q");
  107. const top = candidates.sort((a, b) => b.confidence - a.confidence);
  108. top.push({ name: "x", confidence: 0.5 });
  109. return top;
  110. `);
  111. });
  112. it("JSON.parse reviver (no registry entry), then push of a literal", () => {
  113. analyze(`
  114. interface C { name: string; confidence: number }
  115. const text = await agent("s").ask<string>("q");
  116. const top = JSON.parse(text, (k, v) => v) as C[];
  117. top.push({ name: "x", confidence: 0.5 });
  118. return top;
  119. `);
  120. });
  121. it("String.replace callback, then a literal pushed into a sibling field", () => {
  122. analyze(`
  123. interface C { name: string; confidence: number }
  124. const text = await agent("s").ask<string>("q");
  125. const holder = { items: [] as C[], text: text.replace(/x/g, (m) => m.toUpperCase()) };
  126. holder.items.push({ name: holder.text, confidence: 0.5 });
  127. return holder;
  128. `);
  129. });
  130. });
  131. describe("convergence — placeholder resolution is linear in the placeholder graph", () => {
  132. // 一个被很多处共用的 callback 包装器(`limited(slots, async () => …)` 这类限流 helper)的
  133. // 摘要是所有 callback 返回值的并集,各调用方的参数占位符原样穿过它,于是每个调用方的实参
  134. // 都含有每个调用方的占位符——占位符图是完全图。发射期曾按「栈上去重、不记忆」逐条枚举
  135. // 简单路径,完全图上是 n! 量级(9 个调用方 19 秒,用户脚本 4GB 堆 OOM)。界限故意放得很松:
  136. // 未修复的实现在 12 个调用方上要跑几个小时,不会因为机器慢而误报。
  137. function sharedLimiter(callers: number): string {
  138. let script = `interface Slots { free: number }
  139. const slots: Slots = { free: 4 };
  140. async function limited<T>(slots: Slots, fn: () => Promise<T>): Promise<T> {
  141. while (slots.free <= 0) await Promise.resolve();
  142. slots.free -= 1;
  143. try { return await fn(); } finally { slots.free += 1; }
  144. }
  145. const results: string[] = [];
  146. `;
  147. for (let i = 0; i < callers; i += 1) {
  148. script += `async function step${i}(x: string): Promise<string> {
  149. return limited(slots, async () => (await agent("a${i}").ask<string>(\`do ${i} \${x}\`)) + x);
  150. }
  151. results.push(await step${i}(results.join(",")));
  152. `;
  153. }
  154. script += `async function nested(x: string): Promise<string> {
  155. return limited(slots, async () => {
  156. let acc = x;
  157. acc = await limited(slots, async () => agent("n0").ask<string>(\`inner \${acc}\`));
  158. acc = await limited(slots, async () => agent("n1").ask<string>(\`inner \${acc}\`));
  159. return acc;
  160. });
  161. }
  162. results.push(await nested(results.join(",")));
  163. return results;
  164. `;
  165. return script;
  166. }
  167. it("resolves a dozen callers of one shared callback helper without enumerating paths", () => {
  168. const callers = 12;
  169. const started = Date.now();
  170. const { result } = analyze(sharedLimiter(callers));
  171. expect(Date.now() - started).toBeLessThan(10_000);
  172. // 提速不改答案:第一个调用方的回答经共用 helper 与 results 流到最后一个调用方的提示,
  173. // 也流到嵌套闭包里内层调用的提示。
  174. const dataEdges = (result.graph?.edges ?? []).filter((edge) => edge.kind === "data");
  175. expect(hasEdge(dataEdges, "ask#1", `ask#${callers}`)).toBe(true);
  176. expect(hasEdge(dataEdges, "ask#1", `ask#${callers + 1}`)).toBe(true);
  177. });
  178. });
  179. describe("analysis cost — shapes that once grew exponentially or as a high power", { timeout: 30_000 }, () => {
  180. // 界限都放得很松(10 秒):修复前这些形状要跑十几秒到几小时,修复后在一秒上下,不会因机器慢而误报。
  181. // vitest 的超时另放宽到 30 秒:分析是同步的,满载跑全套时单个用例会被拖慢,超时只防真正卡死。
  182. const BOUND_MS = 10_000;
  183. const dataEdges = (result: ReturnType<typeof analyzeWorkflowScript>) =>
  184. (result.graph?.edges ?? []).filter((edge) => edge.kind === "data");
  185. function timed(script: string) {
  186. const started = Date.now();
  187. const out = analyze(script);
  188. expect(Date.now() - started).toBeLessThan(BOUND_MS);
  189. return out.result;
  190. }
  191. // 方法链:每一环曾把接收者求值两到三遍,k 环就是 2^k / 3^k(`.trim()` × 20 用了 13 秒)。
  192. it("evaluates each receiver of a long method chain once", () => {
  193. const trim = timed(`const draft = await agent("w").ask<string>("write");
  194. const clean = draft${".trim()".repeat(30)};
  195. return await agent("r").ask<string>(\`review \${clean}\`);
  196. `);
  197. expect(hasEdge(dataEdges(trim), "ask#1", "ask#2")).toBe(true);
  198. const then = timed(`const p = agent("w").ask<string>("write")${'.then((x) => x + "!")'.repeat(20)};
  199. return await agent("r").ask<string>(\`review \${await p}\`);
  200. `);
  201. expect(hasEdge(dataEdges(then), "ask#1", "ask#2")).toBe(true);
  202. const sets = Array.from({ length: 24 }, (_, i) => `.set("k${i}", draft)`).join("");
  203. const mapSet = timed(`const draft = await agent("w").ask<string>("write");
  204. const m = new Map<string, string>();
  205. m${sets};
  206. return await agent("r").ask<string>(\`review \${m.get("k0")}\`);
  207. `);
  208. expect(hasEdge(dataEdges(mapSet), "ask#1", "ask#2")).toBe(true);
  209. // 名为 add 的方法同时走堆变更与普通调用两条路,曾是 3^k。
  210. const builder = timed(`class Pipe {
  211. items: string[] = [];
  212. add(x: string): Pipe { this.items.push(x); return this; }
  213. }
  214. const draft = await agent("w").ask<string>("write");
  215. const pipe = new Pipe()${".add(draft)".repeat(20)};
  216. return await agent("r").ask<string>(\`review \${pipe.items.join(",")}\`);
  217. `);
  218. expect(hasEdge(dataEdges(builder), "ask#1", "ask#2")).toBe(true);
  219. });
  220. // 一个攒着 n 个标签的值被读 n 次:每加一个标签曾扫一遍整个标签集,约 n^3(n=600 用了 5.7 秒,n=800 约 13 秒)。
  221. it("reads a value that carries hundreds of labels hundreds of times", () => {
  222. const n = 800;
  223. let script = `const ps = [${Array.from({ length: n }, (_, i) => `agent("a${i}").ask<string>("q${i}")`).join(", ")}];\n`;
  224. for (let j = 0; j < n; j += 1) script += `const v${j}: string = "s" + ps.length;\n`;
  225. script += "return await Promise.all(ps);\n";
  226. const result = timed(script);
  227. expect(hasEdge(dataEdges(result), "ask#1", "sink")).toBe(true);
  228. expect(hasEdge(dataEdges(result), `ask#${n}`, "sink")).toBe(true);
  229. });
  230. // 被许多阶段共用的 helper:每个 step 按认领它的阶段拷成 k 份,边按拷贝对逐对判时间可行性。
  231. // 每对都调一次 sharesIteration,它曾每次重新过滤站点出现过的全部 region(共用 helper 有
  232. // 上千个),代价是拷贝对数 × region 数(25/25/250 用了 33 秒)。
  233. it("projects phase copies of a helper shared by hundreds of phases", () => {
  234. const fanouts = 25;
  235. const helpers = 25;
  236. const calls = 250;
  237. let script = `const items: string[] = ["a", "b", "c"];
  238. async function helper0(x: string): Promise<string> { return agent(\`h0-\${x}\`).ask<string>(\`do \${x}\`); }
  239. `;
  240. for (let i = 1; i < helpers; i += 1) {
  241. script += `async function helper${i}(x: string): Promise<string> {
  242. const r = await helper${i - 1}(x);
  243. return agent(\`h${i}-\${x}\`).ask<string>(\`step ${i} \${r}\`);
  244. }
  245. `;
  246. }
  247. script += "const out: string[] = [];\n";
  248. for (let f = 0; f < fanouts; f += 1) {
  249. script += `phase("f${f}");\nout.push(...(await Promise.all(items.map(async (x) => helper${helpers - 1}(x + "${f}")))));\n`;
  250. }
  251. for (let m = 0; m < calls; m += 1) script += `phase("m${m}");\nout.push(await helper${m % helpers}("m${m}"));\n`;
  252. script += "return out;\n";
  253. const result = timed(script);
  254. expect(result.causality?.phases?.length).toBe(fanouts + calls);
  255. // helper0 的 ask 在每个阶段都被发出,所以它有一份拷贝对应每个阶段。
  256. const copies = (result.causality?.steps ?? []).filter((step) => step.source === "ask#1");
  257. expect(copies).toHaveLength(fanouts + calls);
  258. });
  259. // 一串互相 await 的 async helper 被很多处调用:每个 await 曾扫一遍目前开过的所有 strand,
  260. // 走查时间是 trace 长度的平方(80/80/800 时走查 16 秒)。只计时不动点加走查(interpret):
  261. // 这个形状的控制流投影另有平方级的边数(顺序 await 的每一步连到之后每一步),那是投影规则的事。
  262. it("walks a long chain of awaiting helpers called from many places", () => {
  263. const fanouts = 80;
  264. const helpers = 80;
  265. const calls = 800;
  266. let script = `const items: string[] = ["a", "b", "c"];
  267. async function helper0(x: string): Promise<string> { return agent(\`h0-\${x}\`).ask<string>(\`do \${x}\`); }
  268. `;
  269. for (let i = 1; i < helpers; i += 1) {
  270. script += `async function helper${i}(x: string): Promise<string> {
  271. const r = await helper${i - 1}(x);
  272. return agent(\`h${i}-\${x}\`).ask<string>(\`step ${i} \${r}\`);
  273. }
  274. `;
  275. }
  276. script += "const out: string[] = [];\n";
  277. for (let f = 0; f < fanouts; f += 1) {
  278. script += `out.push(...(await Promise.all(items.map(async (x) => helper${helpers - 1}(x + "${f}")))));\n`;
  279. }
  280. for (let m = 0; m < calls; m += 1) script += `out.push(await helper${m % helpers}("m${m}"));\n`;
  281. script += "return out;\n";
  282. const workflow = createWorkflowProgram(script);
  283. const started = Date.now();
  284. const core = interpret(workflow, collectSites(workflow));
  285. expect(Date.now() - started).toBeLessThan(BOUND_MS);
  286. expect(core.trace.events.length).toBeGreaterThan(calls);
  287. });
  288. // 一个 helper 被 k 处调用、各传一个回调:`fn()` 曾把每个调用者的回调都内联一遍(k² 份函数体,
  289. // 40 处 4.4 秒、80 处跑不完)。现在按调用点的绑定只内联自己的那一个:call 区域正好 2k 个。
  290. it("inlines one callback per call of a helper shared by hundreds of callers", () => {
  291. const callers = 200;
  292. let script = "async function limited(fn: () => Promise<string>): Promise<string> { return await fn(); }\nconst out: string[] = [];\n";
  293. for (let i = 0; i < callers; i += 1) {
  294. script += `out.push(await limited(async () => agent("c${i}").ask<string>("do ${i}")));\n`;
  295. }
  296. script += "return out;\n";
  297. const workflow = createWorkflowProgram(script);
  298. const started = Date.now();
  299. const core = interpret(workflow, collectSites(workflow));
  300. expect(Date.now() - started).toBeLessThan(BOUND_MS);
  301. expect(core.trace.regions.filter((region) => region.kind === "call")).toHaveLength(2 * callers);
  302. expect(core.trace.regions.filter((region) => region.kind === "choice")).toEqual([]);
  303. });
  304. // L 层包装(每层把自己的参数包成新箭头交给下一层)、n 个调用者:曾是 n^(L+1) 份函数体
  305. // (8 × 3 层 50 秒、2.2 GB)。现在每个调用者的链是 2L 个 call 区域。
  306. it("inlines one chain per caller through nested wrapper layers", () => {
  307. const callers = 8;
  308. const layers = 3;
  309. let script = "async function w1(fn: () => Promise<string>): Promise<string> { return await fn(); }\n";
  310. for (let l = 2; l <= layers; l += 1) {
  311. script += `async function w${l}(fn: () => Promise<string>): Promise<string> { return await w${l - 1}(() => fn()); }\n`;
  312. }
  313. script += "const out: string[] = [];\n";
  314. for (let i = 0; i < callers; i += 1) {
  315. script += `out.push(await w${layers}(async () => agent("c${i}").ask<string>("do ${i}")));\n`;
  316. }
  317. script += "return out;\n";
  318. const workflow = createWorkflowProgram(script);
  319. const started = Date.now();
  320. const core = interpret(workflow, collectSites(workflow));
  321. expect(Date.now() - started).toBeLessThan(BOUND_MS);
  322. expect(core.trace.regions.filter((region) => region.kind === "call")).toHaveLength(2 * layers * callers);
  323. });
  324. });