causality.test.ts 45 KB

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