causality.test.ts 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. import { readdirSync, readFileSync } from "node:fs";
  2. import { dirname, join } from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. import { describe, expect, it } from "vitest";
  5. import { analyzeWorkflowScript, type CausalityGraph, type OrderEdge } from "../src/index.js";
  6. import { reduceOrdering, type OrderKind } from "../src/analysis/causality-reduce.js";
  7. import { serializeCausalityGraph } from "../src/analysis/serialize.js";
  8. import { corpusDiagnostics } from "./helpers/analysis-corpus.js";
  9. /**
  10. * Behavioural tests for the causality graph. The fixture snapshots in graphs.test.ts
  11. * pin the whole corpus; these pin the CLAIMS the design rests on, so a silent change in
  12. * the reduction or the ordering rules fails with a readable message rather than a
  13. * 179-file snapshot diff. Each block cites the worked example in
  14. * docs/analysis.md it is derived from.
  15. */
  16. const graphsDir = join(dirname(fileURLToPath(import.meta.url)), "graphs");
  17. function causalityOf(fixture: string): CausalityGraph {
  18. const source = readFileSync(join(graphsDir, `${fixture}.ts`), "utf8");
  19. const result = analyzeWorkflowScript(source);
  20. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  21. const causality = result.causality;
  22. if (causality === undefined) throw new Error(`no causality graph for ${fixture}`);
  23. return causality;
  24. }
  25. const arrows = (graph: CausalityGraph): string[] =>
  26. graph.edges.map((edge) => `${edge.from} -${edge.kind}-> ${edge.to}`);
  27. describe("worked example 1: the full vocabulary (planner-reviewer)", () => {
  28. const graph = causalityOf("planner-reviewer");
  29. it("draws exactly the arrows the spec derives", () => {
  30. // Five step-to-step arrows plus two into the returned artifact — the seven of
  31. // worked example 1, and nothing else.
  32. expect(arrows(graph)).toEqual([
  33. "ask#1 -seq-> ask#2", // scan → plan: ordering only, no dependency
  34. "ask#1 -data-> ask#4", // scan → judge: survives BECAUSE reduction is typed
  35. "ask#2 -data-> ask#3", // plan → review
  36. "ask#3 -carry-> ask#2", // review → plan: the loop's back edge
  37. "ask#3 -seq-> ask#4", // review → judge: the loop must finish first
  38. ]);
  39. expect(graph.sink?.fedBy).toEqual(["ask#2", "ask#4"]);
  40. });
  41. it("drops the incidental chords a uniform reduction would keep", () => {
  42. // scan → review is implied by scan → plan → review; plan → judge by plan → review
  43. // → judge. Both are `seq`, so any longer path removes them.
  44. expect(arrows(graph)).not.toContain("ask#1 -seq-> ask#3");
  45. expect(arrows(graph)).not.toContain("ask#2 -seq-> ask#4");
  46. });
  47. it("drops the phantom producer→sink edge the actor projection emitted", () => {
  48. // `scanner → sink` disappears because `scanner →data judge →data sink` carries it.
  49. expect(graph.sink?.fedBy).not.toContain("ask#1");
  50. });
  51. it("keeps the loop body `always` because the literal bound is positive", () => {
  52. // Finding (a): a blanket "inside a loop ⇒ maybe" would mislabel this.
  53. const plan = graph.steps.find((step) => step.id === "ask#2");
  54. expect(plan?.certainty).toBe("always");
  55. expect(graph.regions.find((region) => region.kind === "loop")?.bound).toBe(5);
  56. });
  57. it("makes actors lanes, never nodes, and marks the fan-out lane a family", () => {
  58. expect(graph.lanes.map((lane) => lane.id)).toEqual(["actor#1", "actor#2", "actor#3", "actor#4"]);
  59. expect(graph.lanes.find((lane) => lane.id === "actor#4")?.families).toEqual(["fanout#1"]);
  60. });
  61. });
  62. describe("worked example 3: sequence inside one lane", () => {
  63. const graph = causalityOf("emission-graph-same-actor-self-edge");
  64. it("chains three asks on one lane, with no transitive chord", () => {
  65. // Finding (b): `data` outranks the co-existing fifo/seq claims on assess → refine,
  66. // and `fifo` outranks `seq` on refine → wrap up, so neither reads as missed
  67. // parallelism. The assess → wrap up chord is reduced away.
  68. expect(arrows(graph)).toEqual(["ask#1 -data-> ask#2", "ask#2 -fifo-> ask#3"]);
  69. });
  70. });
  71. describe("worked example 4: the motivating pair", () => {
  72. const concurrent = causalityOf("order-map-concurrent");
  73. const sequential = causalityOf("order-forof-sequential");
  74. it("splits on concurrency, not cardinality (finding (f))", () => {
  75. const stacked = concurrent.steps.find((step) => step.kind === "ask");
  76. const serial = sequential.steps.find((step) => step.kind === "ask");
  77. expect(stacked?.repeat).toBe("stack");
  78. expect(serial?.repeat).toBe("serial");
  79. });
  80. it("gives the sequential form a self-arrow and the concurrent form none", () => {
  81. expect(arrows(sequential)).toContain("ask#1 -carry-> ask#1");
  82. expect(arrows(concurrent).filter((arrow) => arrow.includes("ask#1 -carry-> ask#1"))).toEqual([]);
  83. });
  84. it("agrees on everything else — same lanes, same data edge", () => {
  85. expect(concurrent.lanes.map((lane) => lane.id)).toEqual(sequential.lanes.map((lane) => lane.id));
  86. expect(arrows(concurrent)).toContain("world-read#1 -data-> ask#1");
  87. expect(arrows(sequential)).toContain("world-read#1 -data-> ask#1");
  88. });
  89. });
  90. describe("worked example 5: a Promise.all that does not parallelize", () => {
  91. it("orders two un-awaited asks on ONE actor (the mailbox serializes them)", () => {
  92. expect(arrows(causalityOf("order-unawaited-one-actor"))).toEqual(["ask#1 -fifo-> ask#2"]);
  93. });
  94. it("leaves two un-awaited asks on DIFFERENT actors incomparable", () => {
  95. // Concurrency is incomparability in the partial order: arrow versus no arrow is the
  96. // carrier, which is why collapsing to one arrow style costs nothing here.
  97. expect(arrows(causalityOf("order-unawaited-two-actors"))).toEqual([]);
  98. });
  99. });
  100. describe("worked example 6: missed parallelism through helpers", () => {
  101. it("reads as a straight line, with the data edges surviving reduction", () => {
  102. expect(arrows(causalityOf("helper-flow-through"))).toEqual([
  103. "ask#1 -seq-> ask#2", // pure serialization: could have run concurrently
  104. "ask#1 -data-> ask#3", // survives even though ask#1 → ask#2 → ask#3 implies it
  105. "ask#2 -seq-> ask#3",
  106. "ask#2 -data-> ask#4",
  107. "ask#3 -seq-> ask#4",
  108. ]);
  109. });
  110. });
  111. describe("worked example 7: recursion", () => {
  112. const graph = causalityOf("helper-recursive");
  113. it("turns the call-graph SCC into a loop region, never unrolling it", () => {
  114. const loop = graph.regions.find((region) => region.kind === "loop");
  115. expect(loop?.label).toBe("dig");
  116. expect(arrows(graph)).toContain("ask#1 -carry-> ask#1");
  117. });
  118. it("records the base case as `maybe` without drawing anything for it", () => {
  119. expect(graph.steps.find((step) => step.id === "ask#1")?.certainty).toBe("maybe");
  120. });
  121. });
  122. describe("worked example 8: nested fan-outs multiply", () => {
  123. it("gives the lane a LIST of families, since a single id cannot express a product", () => {
  124. // Finding (e). Lexical `within` misses this entirely — the ask sits in a helper.
  125. const graph = causalityOf("nested-fanout-reach");
  126. expect(graph.lanes.find((lane) => lane.id === "actor#1")?.families).toEqual([
  127. "fanout#1",
  128. "fanout#2",
  129. ]);
  130. expect(graph.steps.find((step) => step.id === "ask#1")?.repeat).toBe("stack");
  131. });
  132. });
  133. describe("worked example 9: the workspace is a lane", () => {
  134. it("gives every world read its own step, positioned in time", () => {
  135. const graph = causalityOf("actor-agent-to-workspace");
  136. expect(arrows(graph)).toEqual([
  137. "ask#1 -data-> world-read#1",
  138. "world-read#1 -data-> ask#2",
  139. ]);
  140. expect(graph.steps.map((step) => step.lane)).toEqual(["actor#1", "workspace", "actor#2"]);
  141. });
  142. });
  143. describe("worked example 10: a dynamically-selected actor", () => {
  144. const graph = causalityOf("actor-or-aggregation-and-context-dissolve");
  145. it("expands the may-set into one copy per candidate lane", () => {
  146. // The spanning-card drawing is superseded by may-set lane expansion: what finding (d)
  147. // rejected was the ACTOR graph's cross-product of messages, and a duplicated step
  148. // carrying `maybe` claims strictly less than that.
  149. const copies = graph.steps.filter((step) => step.source === "ask#2");
  150. expect(copies.map((step) => step.id)).toEqual(["ask#2~actor#1", "ask#2~actor#2"]);
  151. expect(copies.map((step) => step.lane)).toEqual(["actor#1", "actor#2"]);
  152. expect(copies.every((step) => step.lanes?.join() === "actor#1,actor#2")).toBe(true);
  153. expect(graph.steps.find((step) => step.id === "ask#2")).toBeUndefined();
  154. });
  155. it("attaches the `maybe` FIFO edge to the same-lane copy alone", () => {
  156. // The copy on beta has no mailbox relation to `a`, so the cross-lane pair is dropped
  157. // rather than duplicated — the shape is crisper than the single card's `fifo maybe`.
  158. const fifo = graph.edges.filter((edge) => edge.kind === "fifo");
  159. expect(fifo).toEqual([
  160. { certainty: "maybe", from: "ask#2~actor#1", kind: "fifo", to: "ask#3" },
  161. ]);
  162. });
  163. });
  164. describe("await resolution and widening", () => {
  165. it("resolves a stored promise's settle exactly through the taint oracle", () => {
  166. // Phase 1 widened here (`await held` issues nothing), so ask#1 -> ask#3 was `maybe`.
  167. // Phase 2's oracle reads a SINGLE exact witness off the awaited operand, which is the
  168. // settle-certainty rule's `always` case.
  169. const graph = causalityOf("order-stored-promise-late-await");
  170. expect(graph.edges).toEqual([
  171. { certainty: "always", from: "ask#1", kind: "seq", to: "ask#3" },
  172. { certainty: "always", from: "ask#2", kind: "seq", to: "ask#3" },
  173. ]);
  174. });
  175. it("resolves a promise awaited inside a helper, through the parameter placeholder", () => {
  176. const graph = causalityOf("order-promise-into-helper");
  177. expect(graph.edges).toEqual([
  178. { certainty: "always", from: "ask#1", kind: "seq", to: "ask#3" },
  179. { certainty: "always", from: "ask#2", kind: "seq", to: "ask#3" },
  180. ]);
  181. });
  182. it("keeps `maybe` when the awaited promise has more than one witness", () => {
  183. // A dynamically-selected promise resolves to BOTH candidates and only one of them
  184. // settles at runtime, so the multi-witness half of the settle-certainty rule applies —
  185. // the same two `maybe` edges phase 1's full-barrier widening produced.
  186. const graph = causalityOf("order-dynamic-promise-await");
  187. expect(graph.edges.every((edge) => edge.certainty === "maybe")).toBe(true);
  188. expect(graph.edges).toHaveLength(2);
  189. });
  190. it("settles a stored promise joined with a fresh one (phase 1 invented concurrency)", () => {
  191. // The awaited expression issues the fresh ask, so phase 1 never widened AND never
  192. // settled `held` — leaving ask#1 incomparable with ask#3, which is concurrency the
  193. // script does not have. The join oracle settles it as a may-claim (`Promise.race`
  194. // shares the join machinery, so settle-all would be unsound).
  195. const graph = causalityOf("order-mixed-join-stored-promise");
  196. expect(graph.edges).toEqual([
  197. { certainty: "maybe", from: "ask#1", kind: "seq", to: "ask#3" },
  198. { certainty: "always", from: "ask#2", kind: "seq", to: "ask#3" },
  199. ]);
  200. });
  201. it("never settles a step before it is issued (the temporal invariant)", () => {
  202. // `first.steps.push(extra)` merges ask#2's label into the slot `plan` denotes, so the
  203. // flow-insensitive oracle offers ask#2 as a witness at the EARLIER `await plan`. That
  204. // settle is temporally impossible; admitting it cost the await its singleton-exact
  205. // certainty and demoted a true `data always` edge through the min-certainty dedup.
  206. const graph = causalityOf("async-promise-double-await-mutate");
  207. expect(arrows(graph)).toEqual([
  208. "ask#1 -seq-> ask#2",
  209. "ask#1 -data-> ask#3",
  210. "ask#2 -data-> ask#3",
  211. ]);
  212. const certainty = (from: string, to: string) =>
  213. graph.edges.find((edge) => edge.from === from && edge.to === to)?.certainty;
  214. expect(certainty("ask#1", "ask#2")).toBe("always");
  215. expect(certainty("ask#2", "ask#3")).toBe("always");
  216. expect(certainty("ask#1", "ask#3")).toBe("always");
  217. });
  218. it("still settles across iterations, where repetition realizes it", () => {
  219. // The carve-out to the invariant. `await acc` awaits the PREVIOUS round's ask, which is
  220. // not yet issued in this linear walk but is realizable by repetition (both ends share
  221. // the fan-out region). A bare already-issued test drops it and the step's cue reverts
  222. // to `stack` — N concurrent instances for a chain the script serializes.
  223. const graph = causalityOf("reduce-accumulator");
  224. expect(graph.steps.find((step) => step.id === "ask#1")?.repeat).toBe("serial");
  225. });
  226. it("never claims CERTAINTY for a settle only repetition realizes", () => {
  227. // A loop whose head awaits the promise its tail issued. The claim fails at both ends:
  228. // iteration 1 awaits the initial value and settles nothing, and the last iteration's
  229. // issue escapes the loop unawaited, so that instance is still pending when ask#2
  230. // issues. `always` here would assert a post-loop ordering the final instance violates.
  231. const graph = causalityOf("order-loop-head-await-tail-issue");
  232. const post = graph.edges.find((edge) => edge.from === "ask#1" && edge.to === "ask#2");
  233. expect(post).toMatchObject({ certainty: "maybe", kind: "seq" });
  234. // The demotion must not cost the multiplicity cue: settledInside records the step
  235. // whatever the settle event's certainty.
  236. expect(graph.steps.find((step) => step.id === "ask#1")?.repeat).toBe("serial");
  237. });
  238. });
  239. describe("control dependence", () => {
  240. it("emits a control edge into a guarded ask and drops its certainty", () => {
  241. const graph = causalityOf("order-control-guarded-ask");
  242. expect(arrows(graph)).toEqual(["ask#1 -control-> ask#2"]);
  243. expect(graph.steps.find((step) => step.id === "ask#2")?.certainty).toBe("maybe");
  244. expect(graph.regions.map((region) => region.kind)).toEqual(["seq", "branch"]);
  245. });
  246. it("finds a controller the syntactic symbol map cannot see (the taint oracle)", () => {
  247. // `const ok = t.escalate` issues nothing, so phase 1 associated no step with `ok` and
  248. // drew a bare `seq` arrow. The oracle carries ask#1's label through the field read.
  249. const graph = causalityOf("order-derived-guard-control");
  250. expect(arrows(graph)).toEqual(["ask#1 -control-> ask#2"]);
  251. expect(graph.steps.find((step) => step.id === "ask#2")?.certainty).toBe("maybe");
  252. });
  253. it("keeps the syntactic controller the oracle cannot see (implicit flow)", () => {
  254. // `flag` is 1 or 2 — a ternary condition does not join the data contract, so the
  255. // oracle has nothing on this guard. The union is what preserves the edge; replacing
  256. // the syntactic scan would regress it.
  257. const graph = causalityOf("order-implicit-flow-guard");
  258. expect(arrows(graph)).toEqual(["ask#1 -control-> ask#2"]);
  259. expect(graph.steps.find((step) => step.id === "ask#2")?.certainty).toBe("maybe");
  260. });
  261. });
  262. describe("loop repetition", () => {
  263. it("closes a two-step loop between the steps, with no self-arrow", () => {
  264. const graph = causalityOf("order-loop-two-steps-carry");
  265. expect(arrows(graph)).toEqual(["ask#1 -data-> ask#2", "ask#2 -carry-> ask#1"]);
  266. expect(graph.steps.every((step) => step.repeat === "serial")).toBe(true);
  267. });
  268. it("keeps the self-arrow when the loop carries no data at all", () => {
  269. // The ordering between consecutive iterations produces it, not the data.
  270. expect(arrows(causalityOf("order-loop-carries-nothing"))).toEqual(["ask#1 -carry-> ask#1"]);
  271. });
  272. it("serializes an un-awaited loop on a fixed actor, but stacks a fresh one", () => {
  273. const fixed = causalityOf("order-loop-unawaited-fixed-actor");
  274. const fresh = causalityOf("order-loop-unawaited-fresh-actor");
  275. expect(fixed.steps.find((step) => step.kind === "ask")?.repeat).toBe("serial");
  276. expect(arrows(fixed)).toContain("ask#1 -carry-> ask#1");
  277. expect(fresh.steps.find((step) => step.kind === "ask")?.repeat).toBe("stack");
  278. expect(arrows(fresh)).not.toContain("ask#1 -carry-> ask#1");
  279. });
  280. });
  281. describe("impossible back edges", () => {
  282. const graph = causalityOf("game-planner-reviewer");
  283. it("drops a backwards data fact whose target cannot run again", () => {
  284. // The site graph's data edges are variable-level, so the reassigned `let plan`
  285. // yields the full writers × readers cross product: the in-loop revision (ask#3)
  286. // gets a data fact into the PRE-LOOP review (ask#2), which reads `plan`. ask#2 runs
  287. // once, before the loop, so no execution realizes it. Because the fact points
  288. // backwards it used to be retyped `carry` — the one class reduction never touches.
  289. expect(arrows(graph)).not.toContain("ask#3 -carry-> ask#2");
  290. });
  291. it("keeps the carry that closes the refinement cycle, and only that one", () => {
  292. expect(arrows(graph)).toContain("ask#4 -carry-> ask#3"); // the refinement cycle
  293. // ask#3 also reads its own last plan, but that self-carry asserts nothing on top
  294. // of ask#3 -data-> ask#4 -carry-> ask#3: carry minimization drops it
  295. // (docs/analysis.md, "Typed transitive reduction" step 3).
  296. expect(arrows(graph)).not.toContain("ask#3 -carry-> ask#3");
  297. });
  298. it("leaves a two-agent refinement loop reading as one chain plus its cycle", () => {
  299. // Four arrows for four steps, down from ten: every surviving arrow asserts an
  300. // order nothing else in the picture asserts — the carries included.
  301. expect(arrows(graph)).toEqual([
  302. "ask#1 -data-> ask#2", // initial plan → initial review
  303. "ask#2 -control-> ask#3", // the verdict decides whether revision happens
  304. "ask#3 -data-> ask#4", // revised plan → re-review
  305. "ask#4 -carry-> ask#3", // …whose verdict feeds the next revision
  306. ]);
  307. });
  308. });
  309. describe("phase-1 scope", () => {
  310. it("ships one step per site, even for a helper called twice", () => {
  311. // Phase 3's site specialization turns this into `ask#1/1` + `ask#1/2`.
  312. const graph = causalityOf("order-helper-ask-two-call-sites");
  313. expect(graph.steps.map((step) => step.id)).toEqual(["ask#1"]);
  314. });
  315. it("is deterministic: the same script serializes identically every time", () => {
  316. const source = readFileSync(join(graphsDir, "planner-reviewer.ts"), "utf8");
  317. const first = analyzeWorkflowScript(source).causality as CausalityGraph;
  318. const second = analyzeWorkflowScript(source).causality as CausalityGraph;
  319. expect(serializeCausalityGraph(first)).toBe(serializeCausalityGraph(second));
  320. });
  321. it("emits no `parallel` or `shared` regions (parallel stays derived)", () => {
  322. const graph = causalityOf("planner-reviewer");
  323. expect(graph.regions.every((region) => region.kind !== "parallel" && region.kind !== "shared"))
  324. .toBe(true);
  325. });
  326. });
  327. describe("may-set lane expansion", () => {
  328. it("draws an alternating receiver as the carry cycle between its two copies", () => {
  329. // The motivating script: the ONLY ask site is `(turn ? black : white).ask(…)`, so
  330. // under the one-step rule one candidate lane had zero homed steps and the emitter
  331. // culled it — a two-player game read as a one-player game. Both lanes are now homed.
  332. const graph = causalityOf("may-set-loop-alternating-receiver");
  333. expect(graph.steps.map((step) => step.id)).toEqual(["ask#1~actor#1", "ask#1~actor#2"]);
  334. expect(graph.steps.map((step) => step.lane)).toEqual(["actor#1", "actor#2"]);
  335. // The self-carry becomes the full k×k product: the alternation cycle, plus a
  336. // self-loop per copy because the same candidate may be selected twice in a row.
  337. expect(arrows(graph)).toEqual([
  338. "ask#1~actor#1 -carry-> ask#1~actor#1",
  339. "ask#1~actor#1 -carry-> ask#1~actor#2",
  340. "ask#1~actor#2 -carry-> ask#1~actor#1",
  341. "ask#1~actor#2 -carry-> ask#1~actor#2",
  342. ]);
  343. expect(graph.sink?.fedBy).toEqual(["ask#1~actor#1", "ask#1~actor#2"]);
  344. });
  345. it("inherits `repeat` and `region`, and keeps the full may-set on every copy", () => {
  346. const graph = causalityOf("may-set-loop-alternating-receiver");
  347. for (const step of graph.steps) {
  348. expect(step).toMatchObject({
  349. certainty: "maybe",
  350. kind: "ask",
  351. label: "ask",
  352. lanes: ["actor#1", "actor#2"],
  353. region: "loop#1",
  354. repeat: "serial",
  355. source: "ask#1",
  356. });
  357. // One textual ask, so one `loc` — this is what tells the reader they are copies.
  358. expect(step.loc).toEqual({ column: 40, line: 12 });
  359. }
  360. });
  361. it("forces `maybe` on copies of an `always` step", () => {
  362. // The ask always runs; each COPY may not. Certainty is per-node and the node changed
  363. // meaning, so this is the one field expansion overrides rather than inherits.
  364. const graph = causalityOf("may-set-oneshot-ternary");
  365. expect(graph.steps.find((step) => step.id === "ask#1")?.certainty).toBe("always");
  366. const copies = graph.steps.filter((step) => step.source === "ask#2");
  367. expect(copies.map((step) => step.certainty)).toEqual(["maybe", "maybe"]);
  368. // No enclosing iteration region, so nothing carries: a plain data fan-out.
  369. expect(arrows(graph)).toEqual([
  370. "ask#1 -data-> ask#2~actor#1",
  371. "ask#1 -data-> ask#2~actor#2",
  372. ]);
  373. expect(copies.every((step) => step.repeat === undefined)).toBe(true);
  374. });
  375. it("expands a `fifo` edge lane-matched, dropping the cross-lane pair", () => {
  376. // A cross-lane fifo copy would claim a mailbox relation that cannot exist, while
  377. // `data` cannot tell which candidate produced the value and so fans out fully.
  378. const graph = causalityOf("may-set-fifo-against-fixed-lane");
  379. expect(arrows(graph)).toEqual([
  380. "ask#1 -data-> ask#2~actor#1",
  381. "ask#1 -data-> ask#2~actor#2",
  382. "ask#1 -data-> ask#3",
  383. "ask#2~actor#1 -fifo-> ask#3",
  384. ]);
  385. expect(graph.steps.find((step) => step.id === "ask#3")?.lanes).toBeUndefined();
  386. expect(graph.sink?.fedBy).toEqual(["ask#2~actor#1", "ask#2~actor#2", "ask#3"]);
  387. });
  388. it("falls back to one card past the cap, rather than truncating the may-set", () => {
  389. // Five candidates: `lanes` is kept in full and the step keeps today's single card in
  390. // `lanes[0]`, with no `source` — dropping candidates would be a claim the analysis
  391. // cannot make, and five copies multiply steps and edges past what a reader can follow.
  392. const graph = causalityOf("may-set-over-cap");
  393. const step = graph.steps.find((s) => s.label === "picked");
  394. expect(step?.id).toBe("ask#2");
  395. expect(step?.source).toBeUndefined();
  396. expect(step?.lane).toBe("actor#1");
  397. expect(step?.lanes).toHaveLength(5);
  398. expect(arrows(graph)).toEqual(["ask#1 -data-> ask#2"]);
  399. });
  400. it("re-applies endpoint inheritance, so no edge touching a copy stays `always`", () => {
  401. // Expansion forces a copy to `maybe`, and an edge inherits the weaker certainty of its
  402. // endpoints — so re-deriving after the rewrite is what keeps the two rules consistent.
  403. // Stated as the invariant over every may-set fixture rather than per-fixture, because
  404. // it is the rule that matters, not the individual demotions.
  405. for (const fixture of [
  406. "may-set-oneshot-ternary",
  407. "may-set-loop-alternating-receiver",
  408. "may-set-fifo-against-fixed-lane",
  409. "actor-or-aggregation-and-context-dissolve",
  410. "actor-nonsingleton-lane-computed",
  411. "actor-may-pick-inside-fanout",
  412. "agent-array-indexed-selection",
  413. "conditional-receiver-may-set",
  414. "emission-graph-may-receiver-overlap-context",
  415. ]) {
  416. const graph = causalityOf(fixture);
  417. const copies = new Set(
  418. graph.steps.filter((step) => step.source !== undefined).map((step) => step.id),
  419. );
  420. const incident = graph.edges.filter(
  421. (edge) => copies.has(edge.from) || copies.has(edge.to),
  422. );
  423. expect(incident.length).toBeGreaterThan(0);
  424. expect(incident.filter((edge) => edge.certainty !== "maybe")).toEqual([]);
  425. }
  426. });
  427. it("agrees with the branch form on certainty (refactoring invariance)", () => {
  428. // `(cond ? a : b).ask(p)` and `cond ? a.ask(p) : b.ask(p)` are the same program, which
  429. // is the whole premise of expansion — so they must draw the same certainty. This is the
  430. // argument that fixes the edge rule to endpoint inheritance re-applied: preserving an
  431. // `always` edge into a copy would make two identical programs disagree.
  432. //
  433. // Edge KIND and region legitimately differ and are NOT part of the claim: the branch
  434. // form's guard yields `control` edges and its own `branch` regions, where the receiver
  435. // -selection form yields `data` out of the taint oracle inside one `seq` region.
  436. const expanded = causalityOf("may-set-oneshot-ternary");
  437. const branch = causalityOf("may-set-branch-form-parity");
  438. const receivers = (graph: CausalityGraph): string[] =>
  439. graph.steps
  440. .filter((step) => step.lane !== "actor#3")
  441. .map((step) => `${step.lane} ${step.certainty}`)
  442. .sort();
  443. expect(receivers(expanded)).toEqual(["actor#1 maybe", "actor#2 maybe"]);
  444. expect(receivers(branch)).toEqual(receivers(expanded));
  445. for (const graph of [expanded, branch]) {
  446. const fromSeed = graph.edges.filter((edge) => edge.from === "ask#1");
  447. expect(fromSeed).toHaveLength(2);
  448. expect(fromSeed.filter((edge) => edge.certainty !== "maybe")).toEqual([]);
  449. expect(graph.sink?.fedBy).toHaveLength(2);
  450. }
  451. });
  452. it("emits `source` only on copies, so untouched fixtures are unperturbed", () => {
  453. // The field is what a downstream consumer joins runtime instances on, so a step that
  454. // did not expand must not carry it — `source` would then duplicate `id` exactly.
  455. for (const fixture of ["planner-reviewer", "may-set-over-cap", "order-loop-two-steps-carry"]) {
  456. expect(causalityOf(fixture).steps.every((step) => step.source === undefined)).toBe(true);
  457. }
  458. });
  459. it("expands within the lane list the pre-expansion pass already computed", () => {
  460. // Expansion is a rewrite of the FINISHED graph: it homes steps in lanes that were
  461. // always in the list (every candidate contributes one), so it adds no lane and
  462. // removes none, and the region tree is untouched.
  463. const graph = causalityOf("may-set-loop-alternating-receiver");
  464. expect(graph.lanes.map((lane) => lane.id)).toEqual(["actor#1", "actor#2"]);
  465. expect(graph.regions.map((region) => region.id)).toEqual(["seq#1", "loop#1"]);
  466. });
  467. });
  468. describe("interpolated actor names", () => {
  469. // docs/analysis.md, "Labels and names". The five outcomes are pinned
  470. // by name here rather than only by the fixture snapshot, because each one encodes a
  471. // separate judgement and a snapshot diff cannot say which of them regressed.
  472. const graph = causalityOf("interpolated-actor-name");
  473. const laneNamed = (id: string) => graph.lanes.find((lane) => lane.id === id);
  474. it("takes the literal run before the first hole", () => {
  475. expect(laneNamed("actor#1")?.namePattern).toEqual({ head: "研究员" });
  476. });
  477. it("takes the literal run after the last hole", () => {
  478. expect(laneNamed("actor#2")?.namePattern).toEqual({ tail: "-worker" });
  479. });
  480. it("takes both affixes when the template has literal text on each side", () => {
  481. expect(laneNamed("actor#3")?.namePattern).toEqual({ head: "a", tail: "b" });
  482. });
  483. it("drops literal middles rather than rendering the expression", () => {
  484. // `pre${x}mid${y}post` is a name on a row, not a rendering of the template that
  485. // produced it — `mid` would only be readable as `pre…mid…post`.
  486. expect(laneNamed("actor#4")?.namePattern).toEqual({ head: "pre", tail: "post" });
  487. });
  488. it("leaves a lane anonymous when the affixes carry nothing to read", () => {
  489. // Whitespace-only trims to empty; `-` has no letter or digit, and `…-` is strictly
  490. // worse than the localized anonymous fallback.
  491. expect(laneNamed("actor#5")?.namePattern).toBeUndefined();
  492. expect(laneNamed("actor#6")?.namePattern).toBeUndefined();
  493. });
  494. it("never displaces a real name with a pattern", () => {
  495. // A literal argument and a `const` binding name are both names; the pattern is the
  496. // last resort, so no lane may carry both.
  497. for (const lane of graph.lanes) {
  498. if (lane.namePattern !== undefined) expect(lane.name).toBeUndefined();
  499. }
  500. });
  501. it("gives the inline receiver's step the same pattern", () => {
  502. // `askLabel` answers the bare "ask" for an inline `agent(...)` receiver, so the card
  503. // is exactly as uninformative as the lane head was.
  504. const first = graph.steps.find((step) => step.id === "ask#1");
  505. expect(first?.label).toBe("ask");
  506. expect(first?.labelPattern).toEqual({ head: "研究员" });
  507. });
  508. it("leaves an identifier receiver's label alone", () => {
  509. // `chiefEditor.ask(...)` already produced a real label; there is nothing to rebuild,
  510. // and a pattern there would be a second name competing with the first.
  511. const named = causalityOf("emission-graph-same-actor-self-edge");
  512. for (const step of named.steps) expect(step.labelPattern).toBeUndefined();
  513. });
  514. });
  515. describe("typed transitive reduction", () => {
  516. const edge = (
  517. from: string,
  518. to: string,
  519. kind: OrderKind,
  520. carryOf?: Exclude<OrderKind, "carry">,
  521. ) => ({ from, kind, to, ...(carryOf === undefined ? {} : { carryOf }) });
  522. const shown = (edges: ReturnType<typeof edge>[]) =>
  523. reduceOrdering(edges).map((e) => `${e.from}-${e.kind}->${e.to}`);
  524. it("keeps a data edge a mixed-kind path implies", () => {
  525. // The planner-reviewer case in miniature: a → d is real, a → b → c → d is not.
  526. expect(
  527. shown([
  528. edge("a", "b", "seq"),
  529. edge("b", "c", "data"),
  530. edge("c", "d", "seq"),
  531. edge("a", "d", "data"),
  532. ]),
  533. ).toContain("a-data->d");
  534. });
  535. it("drops a data edge a pure data path implies", () => {
  536. expect(
  537. shown([edge("a", "b", "data"), edge("b", "c", "data"), edge("a", "c", "data")]),
  538. ).toEqual(["a-data->b", "b-data->c"]);
  539. });
  540. it("drops a seq edge any longer path implies", () => {
  541. expect(shown([edge("a", "b", "fifo"), edge("b", "c", "fifo"), edge("a", "c", "seq")])).toEqual([
  542. "a-fifo->b",
  543. "b-fifo->c",
  544. ]);
  545. });
  546. it("keeps a carry edge no carry composition implies", () => {
  547. // A back-edge asserts a cross-iteration order; only a forward-leg → one-carry-hop
  548. // → forward-leg composition implies that, and there is no second carry here.
  549. // (Whether a carry is REALIZABLE at all is decided upstream — see the
  550. // "impossible back edges" block below.)
  551. expect(
  552. shown([edge("a", "b", "data"), edge("b", "c", "data"), edge("c", "a", "carry")]),
  553. ).toEqual(["a-data->b", "b-data->c", "c-carry->a"]);
  554. });
  555. it("drops a hard edge that a path of hard edges implies", () => {
  556. // `data` and `control` are both non-removable, so either justifies either. This is
  557. // what keeps a refinement loop from growing a second arrow for every data fact a
  558. // guard already ordered: `initial plan → revision` says nothing on top of
  559. // `initial plan → initial review → (guards) → revision`.
  560. expect(
  561. shown([edge("a", "b", "data"), edge("b", "c", "control"), edge("a", "c", "data")]),
  562. ).toEqual(["a-data->b", "b-control->c"]);
  563. expect(
  564. shown([edge("a", "b", "control"), edge("b", "c", "data"), edge("a", "c", "control")]),
  565. ).toEqual(["a-control->b", "b-data->c"]);
  566. });
  567. it("keeps a hard edge whose only path runs through serialization", () => {
  568. // The reader is meant to be able to delete `seq`/`fifo` mentally (that is what
  569. // "missed parallelism" means); the real constraint has to survive that deletion.
  570. expect(
  571. shown([edge("a", "b", "seq"), edge("b", "c", "fifo"), edge("a", "c", "data")]),
  572. ).toContain("a-data->c");
  573. });
  574. it("lifts carry edges out so a cyclic input still reduces, and minimizes them", () => {
  575. // review → plan is a carry; without lifting it the relation has a cycle. The
  576. // self-carry p → p then says nothing on top of p -data-> r -carry-> p (one carry
  577. // hop), so carry minimization drops it — the loop still closes through r.
  578. expect(
  579. shown([edge("p", "r", "data"), edge("r", "p", "carry"), edge("p", "p", "carry")]),
  580. ).toEqual(["p-data->r", "r-carry->p"]);
  581. });
  582. it("keeps connectivity when justifying paths overlap, without a restore pass", () => {
  583. // a→c is implied by a→b→c, and a→d by the chain through c. Deciding every edge
  584. // against the SURVIVING set keeps the chain and drops both chords directly; the
  585. // old pass decided against the ORIGINAL set and needed a restore loop here.
  586. const kept = shown([
  587. edge("a", "b", "seq"),
  588. edge("b", "c", "seq"),
  589. edge("c", "d", "seq"),
  590. edge("a", "c", "seq"),
  591. edge("a", "d", "seq"),
  592. ]);
  593. expect(kept).toEqual(["a-seq->b", "b-seq->c", "c-seq->d"]);
  594. });
  595. it("stays irredundant on a residual cycle (the over-restoration bug)", () => {
  596. // Regression (2026-08-27): the old algorithm batch-removed against the ORIGINAL
  597. // relation, then monotonically restored edges whose witness path was itself
  598. // removed. On this input it removed all four chords in one batch, every witness
  599. // was gone by restore time, and ALL FOUR came back — 7 edges, 4 redundant. The
  600. // real-world shape is a shared helper making the forward relation cyclic
  601. // (fixture order-shared-helper-residual-cycle; jsonl-db rendered 66 forward
  602. // edges, 55 implied by the rest). Greedy decisions against the surviving set
  603. // leave an irredundant set: no kept edge has a length-≥2 witness among the
  604. // others. (Irredundant, not minimum — visit order decides which chord survives.)
  605. const kept = shown([
  606. edge("a", "b", "seq"),
  607. edge("b", "c", "seq"),
  608. edge("c", "d", "seq"),
  609. edge("a", "c", "seq"),
  610. edge("a", "d", "seq"),
  611. edge("b", "d", "seq"),
  612. edge("d", "a", "seq"), // the residual cycle-closer
  613. ]);
  614. expect(kept).toEqual(["a-seq->b", "c-seq->d", "a-seq->c", "b-seq->d", "d-seq->a"]);
  615. });
  616. it("drops a soft carry a one-carry composition implies", () => {
  617. // q@k → p@k+1 is already told by q -seq-> r (inside round k), then r -carry-> p
  618. // (into round k+1). A seq-underlying carry yields to any composition, exactly as
  619. // a forward seq edge yields to any path.
  620. expect(
  621. shown([
  622. edge("q", "r", "seq"),
  623. edge("r", "p", "carry", "seq"),
  624. edge("q", "p", "carry", "seq"),
  625. ]),
  626. ).toEqual(["q-seq->r", "r-carry->p"]);
  627. });
  628. it("keeps a hard carry whose only composition runs through serialization", () => {
  629. // Same shape, but q's answer FEEDS p's next round. The data fact must survive the
  630. // reader mentally deleting the seq hop — the same precedence rule as for forward
  631. // data edges.
  632. expect(
  633. shown([
  634. edge("q", "r", "seq"),
  635. edge("r", "p", "carry", "seq"),
  636. edge("q", "p", "carry", "data"),
  637. ]),
  638. ).toEqual(["q-seq->r", "r-carry->p", "q-carry->p"]);
  639. });
  640. it("drops a hard carry a hard one-carry composition implies", () => {
  641. expect(
  642. shown([
  643. edge("q", "r", "data"),
  644. edge("r", "p", "carry", "data"),
  645. edge("q", "p", "carry", "data"),
  646. ]),
  647. ).toEqual(["q-data->r", "r-carry->p"]);
  648. });
  649. it("lets the forward leg of a composition sit in the next round", () => {
  650. // r@k → s@k+1 via the carry into p@k+1, then p -data-> s inside round k+1.
  651. expect(
  652. shown([
  653. edge("p", "s", "data"),
  654. edge("r", "p", "carry", "data"),
  655. edge("r", "s", "carry", "data"),
  656. ]),
  657. ).toEqual(["p-data->s", "r-carry->p"]);
  658. });
  659. it("never composes two carry hops (that would assert k → k+2)", () => {
  660. expect(
  661. shown([
  662. edge("a", "b", "carry", "data"),
  663. edge("b", "c", "carry", "data"),
  664. edge("a", "c", "carry", "data"),
  665. ]),
  666. ).toEqual(["a-carry->b", "b-carry->c", "a-carry->c"]);
  667. });
  668. it("keeps one of two mutually-justifying carries (the loop still closes)", () => {
  669. // u→v and w→v justify each other through the forward 2-cycle u ⇄ w (the shared
  670. // helper shape again). A batch decision would drop both and lose the back
  671. // ordering entirely; greedy decisions against the surviving set drop exactly one.
  672. expect(
  673. shown([
  674. edge("u", "w", "data"),
  675. edge("w", "u", "data"),
  676. edge("u", "v", "carry", "data"),
  677. edge("w", "v", "carry", "data"),
  678. ]),
  679. ).toEqual(["u-data->w", "w-data->u", "w-carry->v"]);
  680. });
  681. });
  682. /**
  683. * Strands (docs/analysis.md, "Strands and frames"). A strand is one asynchronous activation
  684. * the walk inlines: an `async` body applied at a call, an `async` literal fan-out callback,
  685. * a deferred `.then` continuation. Its `await`s suspend the strand, never the spawner, so
  686. * the walk keeps a settled set per open strand (a FRAME) and the projection reads settles by
  687. * frame visibility. The corpus snapshots pin the resulting graphs; these pin the four claims
  688. * the design rests on — frame visibility, the summary a join replays, the lift rule, and the
  689. * awaited-position scan that decides what a barrier joins at all.
  690. */
  691. describe("strands: frames, summaries and what a barrier joins", () => {
  692. type Core = NonNullable<ReturnType<typeof analyzeWorkflowScript>["core"]>;
  693. function analyzeScript(script: string): { causality: CausalityGraph; core: Core } {
  694. const result = analyzeWorkflowScript(script);
  695. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  696. const causality = result.causality;
  697. const core = result.core;
  698. if (causality === undefined || core === undefined) throw new Error("expected graphs");
  699. return { causality, core };
  700. }
  701. const analyzeFixture = (fixture: string): { causality: CausalityGraph; core: Core } =>
  702. analyzeScript(readFileSync(join(graphsDir, `${fixture}.ts`), "utf8"));
  703. /** The settle events in trace order, in `serializeCore`'s wording minus the `settle` token. */
  704. function settleLines(core: Core): string[] {
  705. const out: string[] = [];
  706. for (const event of core.trace.events) {
  707. if (event.at !== "settle") continue;
  708. const steps = event.steps.length === 0 ? "" : `${event.steps.join(",")} `;
  709. out.push(
  710. `${event.maybe ? "maybe " : ""}${steps}in=${event.regions.join(">")}` +
  711. (event.joins === undefined ? "" : ` joins=${event.joins.join(",")}`),
  712. );
  713. }
  714. return out;
  715. }
  716. /** Forward phase edges only: `carry` is the back edge of a repetition, not an ordering. */
  717. const forwardPhaseEdges = (graph: CausalityGraph): string[] =>
  718. (graph.phaseEdges ?? [])
  719. .filter((edge) => edge.kind !== "carry")
  720. .map((edge) => `${edge.from} -${edge.kind}-> ${edge.to}`);
  721. const HELPER =
  722. 'async function h(): Promise<string> {\n return await agent("h").ask<string>("h");\n}\n';
  723. it("leaves two unawaited fan-outs incomparable, and orders them once each is awaited", () => {
  724. // FRAME VISIBILITY, the defect the refactor exists to fix. The `await` inside A's
  725. // callback used to settle ask#1 in the one global set, so ask#2 (issued after it) read
  726. // as ordered after it and the two fixtures below produced byte-identical output — one
  727. // of them genuinely sequential, the other not.
  728. const concurrent = arrows(causalityOf("strand-fanout-two-phases-join"));
  729. expect(
  730. concurrent.filter((arrow) => arrow.includes("ask#1") && arrow.includes("ask#2")),
  731. ).toEqual([]);
  732. expect(concurrent).toContain("ask#1 -data-> ask#3");
  733. expect(concurrent).toContain("ask#2 -data-> ask#3");
  734. const sequential = arrows(causalityOf("strand-fanout-awaited-per-phase"));
  735. expect(sequential).toContain("ask#1 -seq-> ask#2");
  736. });
  737. it("quotients to A ∥ B → C, and keeps A → B when each phase awaits its own work", () => {
  738. expect(forwardPhaseEdges(causalityOf("strand-fanout-two-phases-join"))).toEqual([
  739. "phase#1 -data-> phase#3",
  740. "phase#2 -data-> phase#3",
  741. ]);
  742. expect(forwardPhaseEdges(causalityOf("strand-fanout-awaited-per-phase"))).toContain(
  743. "phase#1 -seq-> phase#2",
  744. );
  745. });
  746. it("replays an unawaited helper's summary at the await of its promise", () => {
  747. // THE SUMMARY. The helper's own await settles ask#1 in the strand's frame alone, so the
  748. // middle ask is ordered against nothing; `await p` joins the strand — the awaited-position
  749. // scan on a bare identifier — and settles what the strand itself awaited.
  750. const { causality, core } = analyzeFixture("strand-async-helper-unawaited");
  751. expect(settleLines(core)).toEqual([
  752. "ask#1 in=seq#1>call#1",
  753. "ask#2 in=seq#1",
  754. "ask#1 in=seq#1 joins=call#1",
  755. "ask#3 in=seq#1",
  756. ]);
  757. // ask#2 is the middle ask: its only arrow is the data it feeds forward. Nothing from
  758. // the helper reaches it.
  759. expect(arrows(causality).filter((arrow) => arrow.includes("ask#2"))).toEqual([
  760. "ask#2 -data-> ask#3",
  761. ]);
  762. });
  763. it("lifts a strand whose promise reaches the barrier only through a container", () => {
  764. // THE LIFT RULE. The syntactic half cannot fire here: nothing was spawned while
  765. // `const box = [p]` was evaluated, so `box` names no strand, and `p` itself is not in an
  766. // awaited position of the operand. What joins call#1 is the lift — the barrier's claim
  767. // names ask#1, ask#1 was issued inside that strand, so the strand is waited for too.
  768. const lifted = analyzeScript(
  769. HELPER +
  770. "const p = h();\n" +
  771. "const box = [p];\n" +
  772. 'const mid = await agent("m").ask<string>("m");\n' +
  773. "const hv = await Promise.all(box);\n" +
  774. 'return await agent("l").ask<string>(hv.join("") + mid);\n',
  775. );
  776. expect(settleLines(lifted.core)).toContain("ask#1 in=seq#1 joins=call#1");
  777. // The same join reached syntactically, for contrast: each element of an array literal IS
  778. // an awaited position, so `p` is scanned and the strand bound to it joins without a lift.
  779. const syntactic = analyzeScript(
  780. HELPER +
  781. "const p = h();\n" +
  782. 'const mid = await agent("m").ask<string>("m");\n' +
  783. "const hv = await Promise.all([p]);\n" +
  784. 'return await agent("l").ask<string>(hv.join("") + mid);\n',
  785. );
  786. expect(settleLines(syntactic.core)).toContain("ask#1 in=seq#1 joins=call#1");
  787. });
  788. it("joins nothing from an opaque position", () => {
  789. // THE AWAITED-POSITION SCAN, negative half. `work.length` reads the ARRAY, not the
  790. // promises in it, so `await f(work.length)` waits for none of them and the settle carries
  791. // no `joins` at all. This is the accepted residual under-ordering of the plan's soundness
  792. // boundary: the analyzer would rather say nothing than claim an order the runtime lacks.
  793. const { core } = analyzeScript(
  794. "const ids = [1, 2, 3];\n" +
  795. "const work = ids.map(async (i) => {\n" +
  796. " const r = await agent(`a-${i}`).ask<string>(`a ${i}`);\n" +
  797. " return r;\n" +
  798. "});\n" +
  799. 'return await agent("x").ask<string>(String(work.length));\n',
  800. );
  801. expect(settleLines(core)).toEqual(["ask#1 in=seq#1>fanout#1", "ask#2 in=seq#1"]);
  802. });
  803. it("joins a `.then` strand through the variable it was bound to, summary and all", () => {
  804. // The bound-variable half of the scan. `q` is the operand of `await q`, and the strand
  805. // spawned while its declaration was evaluated is bound to it, so the join carries BOTH
  806. // the receiver's step (settled by the strand's prologue) and the step the continuation
  807. // awaited inside itself. The side ask, issued between registration and join, gets
  808. // nothing — the edge the old global may-settle drew here is exactly what disappears.
  809. const { causality, core } = analyzeFixture("strand-then-internal-await");
  810. expect(settleLines(core)).toEqual([
  811. "ask#1 in=seq#1>choice#1>branch#1>call#1",
  812. "ask#2 in=seq#1>choice#1>branch#1>call#1",
  813. "ask#3 in=seq#1",
  814. "ask#1,ask#2 in=seq#1 joins=call#1",
  815. ]);
  816. expect(arrows(causality).filter((arrow) => arrow.includes("ask#3"))).toEqual([]);
  817. });
  818. });
  819. describe("reduction irredundancy (property over the whole corpus)", () => {
  820. // Every surviving forward edge must assert an order no path of at-least-as-strong
  821. // surviving forward edges asserts (docs/analysis.md, "Typed transitive reduction" step 2).
  822. // The old batch-remove-then-restore pass violated this on every
  823. // graph with a residual cycle — the jsonl-db workflow rendered 66 forward edges of
  824. // which 55 were implied by the rest. Checked over the full fixture corpus with an
  825. // independent reimplementation of the justification rule.
  826. const JUSTIFIERS: Record<string, ReadonlySet<string>> = {
  827. control: new Set(["data", "control"]),
  828. data: new Set(["data", "control"]),
  829. fifo: new Set(["data", "control", "fifo"]),
  830. seq: new Set(["data", "control", "fifo", "seq"]),
  831. };
  832. const fixtures = readdirSync(graphsDir)
  833. .filter((name) => name.endsWith(".ts"))
  834. .sort();
  835. it("finds fixtures", () => {
  836. expect(fixtures.length).toBeGreaterThan(0);
  837. });
  838. const impliedByTheOthers = (edges: readonly OrderEdge[]): string[] => {
  839. const forward = edges.filter((edge) => edge.kind !== "carry");
  840. const outgoing = new Map<string, typeof forward>();
  841. for (const edge of forward) {
  842. const list = outgoing.get(edge.from);
  843. if (list === undefined) outgoing.set(edge.from, [edge]);
  844. else list.push(edge);
  845. }
  846. const redundant = forward.filter((edge) => {
  847. if (edge.from === edge.to) return false;
  848. const allowed = JUSTIFIERS[edge.kind] as ReadonlySet<string>;
  849. // BFS for a length-≥2 witness path over allowed kinds, skipping direct hops.
  850. const seen = new Set<string>([edge.from]);
  851. const stack: string[] = [];
  852. for (const hop of outgoing.get(edge.from) ?? []) {
  853. if (hop.to === edge.to || !allowed.has(hop.kind)) continue;
  854. if (!seen.has(hop.to)) {
  855. seen.add(hop.to);
  856. stack.push(hop.to);
  857. }
  858. }
  859. while (stack.length > 0) {
  860. const node = stack.pop() as string;
  861. for (const hop of outgoing.get(node) ?? []) {
  862. if (!allowed.has(hop.kind)) continue;
  863. if (hop.to === edge.to) return true;
  864. if (!seen.has(hop.to)) {
  865. seen.add(hop.to);
  866. stack.push(hop.to);
  867. }
  868. }
  869. }
  870. return false;
  871. });
  872. return redundant.map((edge) => `${edge.from} -${edge.kind}-> ${edge.to}`);
  873. };
  874. for (const fixture of fixtures) {
  875. it(`${fixture}: no forward edge is implied by the others`, () => {
  876. const graph = causalityOf(fixture.replace(/\.ts$/, ""));
  877. expect(impliedByTheOthers(graph.edges)).toEqual([]);
  878. // The quotient projects step edges onto phases and then runs the SAME
  879. // `reduceOrdering`, so the property has to survive projection too: a phase edge
  880. // implied by the surviving others is a reader being told an order twice. Folded
  881. // into this `it` rather than filtered into its own loop so any fixture that grows
  882. // a phase vocabulary is covered without being named here.
  883. if (graph.phaseEdges !== undefined) {
  884. expect(impliedByTheOthers(graph.phaseEdges)).toEqual([]);
  885. }
  886. });
  887. }
  888. });