Pure graph query combinators for Nix. Queries take accessor functions as arguments — not node maps. The graph structure is supplied by the caller; gen-graph only answers questions about it.
gen-graph is nixpkgs-lib-free (Class B): it depends only on gen-prelude, the pure utility base — no nixpkgs.lib, no module system.
- Overview
- Gen Ecosystem
- Quick Start
- Design Principles
- API Reference
- Usage Example
- Performance
- Performance Optimizations
- Testing
- Theoretical Foundations
gen-graph works with an accessor record: an attrset of functions that the caller provides to describe graph structure. Queries destructure only the accessors they need, and the record is open: fields a query does not read are carried, not refused, so a gen-product pgraph (parent, nodeData, product beside nodes and edges) is ordered by topoOrder whole.
# Define accessors over your data
g = {
edges = id: myData.${id}.deps or []; # id → [id]
parent = id: myData.${id}.parent or null; # id → id | null
nodes = builtins.attrNames myData; # [id]
nodeData = id: myData.${id}; # id → attrset
};
# Query
graph.reachableFrom g "web" # → [ "api" "cache" "database" ]
graph.dependents { } g "database" # → [ "api" "web" ]
graph.roots g # → [ "web" ]
graph.cycles g # → []The four accessor fields:
| Field | Type | Used by |
|---|---|---|
edges |
id → [id] |
traversal, global analysis, fixpoint |
parent |
id → id | null |
ancestorsOf, materializeParents |
nodes |
[id] |
global analysis, enumeration, materialization |
nodeData |
id → attrset |
select |
Functions that only need traversal destructure { edges, ... }. Functions that need global analysis also take nodes. Functions that need parent walks take parent. No function requires all four.
Every caller-supplied function is checked where the library applies it. A value that is not callable, a result of a type the surface does not read, and a curried function whose first application does not return a function are each a refusal by name (gen-graph.<surface>: …) that tryEval catches, never an interpreter abort or a plausible wrong answer. The check is lazy: a function a call never applies is never refused. Callable is what Nix can apply (gen-prelude isApplicable, the fuelled __functor walk): a functor whose __functor returns a non-function is refused by name, one whose walk exhausts 32 __functor steps is refused naming that bound, and a curried function's first result is applied through the head it reaches. One shape is recorded rather than refused: a pattern-formal function ({ x }: …) aborts in the caller's own destructuring.
| Library | Role |
|---|---|
| gen-prelude | Pure nixpkgs-lib-free utility base (builtins re-exports + vendored lib utils) |
| gen-algebra | Pure primitives (record, either, intensional identity) |
| gen-types | Clean-room MIT structural type checker (leaf/poly checkers; verify: v → null|err) |
| gen-merge | Byte-mode module merge engine (evalModuleTree, byte-identical to nixpkgs lib.evalModules over the priority subset) |
| gen-schema | Typed registries (kinds, instances, collections, refs); re-hosted on gen-merge |
| gen-aspects | Aspect type system (traits, classification, dispatch); re-hosted on gen-merge |
| gen-scope | HOAG scope-graph evaluator (demand-driven, _eval memoization, circular attributes) |
| gen-graph | This lib — Accessor-based graph query combinators (traversal, condensation, topoOrder/phaseOrder) |
| gen-select | Selector algebra (pattern matching over graph positions) |
| gen-bind | Module binding (inject external args into NixOS modules) |
| gen-dispatch | Relational rule dispatch STEP (stratified phases, conflict resolution) |
| gen-memo | The incremental plane — decides reuse, never evaluates (change propagation, AFFECTED set) |
| gen-vars | Pure-Nix vars/secrets (den-agnostic) |
{
inputs.gen-graph.url = "github:sini/gen-graph";
# gen-graph pulls in gen-prelude transitively — no nixpkgs input required.
outputs = { gen-graph, ... }:
let
graph = gen-graph.lib;
in { /* use graph.reachableFrom, graph.roots, graph.phaseOrder, etc. */ };
}The standalone entry derives its only dependency (gen-prelude) from the pinned
flake.lock, so it needs no <nixpkgs> and takes no arguments:
let
graph = import ./path/to/gen-graph { }; # prelude auto-derived from flake.lock
in
graph.reachableFrom { edges = id: deps.${id} or []; } "start"Pass prelude explicitly to override it: import ./path/to/gen-graph { prelude = gen-prelude.lib; }.
- Queries take accessor functions, not node maps. The caller owns the data; gen-graph never stores it.
- Traversal is lazy.
reachableFrom,ancestorsOf, andpathsBetweenonly visit nodes reachable from the start — they never enumeratenodes. - Global operations materialize internally.
cycles,dependents,transpose,transitiveClosure, andtransitiveReductioncallmaterializeonce, then work on the resulting edge map. - Edge maps are always deduplicated.
materializecallslib.uniqueon each target list.unionEdgescallslib.uniqueon merged lists. - Set operations use attrset membership. Intersection and difference build a target attrset for O(1) per-edge lookups.
- A name carrying string context is accepted. A node, scope or label named after a package (
baseNameOf pkgs.hello) cannot be an attribute name, so every attrset this library builds is keyed by the name's TEXT, the same partition==draws, while the name itself is returned with its context. The exception is an answer read off an edge map's keys (transpose's edges,dependents,fbWork's representative), which comes back as text;directDependents,dependentsOfandfbNodekeep the context. - A non-string where an attrset is keyed is refused by name. An edge target, node or label that is not a string, reaching a surface that keys an attrset by it, is a catchable
thrownaming the door (gen-graph.directDependents: got int, expected a node identifier (a string)), where Nix's own type error escapestryEval. A shared primitive reached through another door refuses under that door's name and says where:dependentson an int target refuses asgen-graph.dependents: got int, expected a node identifier (a string) (in compose). ThegenericClosuretraversals (reachableFrom,reachableWhere,canReach,selfReachable,coScc,fromRegistryDownand the hoistedreachableVia/selfReachableVia) refuse any non-string target by name (gen-graph.reachableFrom: got set, expected a node identifier (a string)) — a node id is a string; an int, bool or float target is refused the same way a set, list, function or null one already was.
These functions visit only the nodes they reach. They do not require nodes.
reachableFrom : { edges, ... } → id → [id]
reachableWhere : { edges, ... } → id → (id → bool) → [id]
canReach : { edges, ... } → id → id → bool
selfReachable : { edges, ... } → id → bool
ancestorsOf : { parent, ... } → id → [id]
pathsBetween : { maxDepth ? 2000 } → { edges, ... } → id → id → [[id]]
And their amortized dual, for a caller spending many traversals over one accessor. hoistEdges
is eager in the node set and lazy in each node's edges: it builds a Θ(n) spine over nodes up
front, and a node's edges call happens on first lookup, so a traversal still never reads the edges
of a node it does not visit:
hoistEdges : { edges, nodes, ... } → (id → succ)
reachableVia : (id → succ) → id → [id]
selfReachableVia : (id → succ) → id → bool
reachableFrom g startId — all nodes transitively reachable from startId via edges, excluding startId itself. C-level BFS via builtins.genericClosure.
graph.reachableFrom g "web"
# → [ "api" "cache" "database" ]reachableWhere g startId pred — reachableFrom filtered by pred id.
graph.reachableWhere g "web" (id: lib.hasPrefix "cache" id)
# → [ "cache" ]canReach g fromId toId — point query: can fromId transitively reach toId? The traversal stops expanding at the target, so it costs Θ(Σ_{u ∈ visited} (1 + outdeg u)) over reach fromId less the nodes toId dominates — O(reachable) only where out-degree is bounded, Θ(n²) on a complete DAG. ★ The win is scoped to targets that dominate a sub-closure: on a chain walked from the tail a one-hop query is Θ(1) where the full walk was Θ(n), while on a complete digraph every node sits one hop from the source and the query stays Θ(n²) — ci/bench/canreach-exit.nix reads both regimes as a pair. The target still enters the closure whenever it is reachable, so the answer is unchanged; builtins.any short-circuits its scan of the finished list, not the traversal that built it.
graph.canReach g "web" "database" # → true
graph.canReach g "database" "web" # → falseselfReachable g id — is id reachable from itself (i.e., in a cycle)? C-level BFS. Used internally by cycles.
graph.selfReachable cyclicGraph "a" # → true
graph.selfReachable dagGraph "a" # → falseancestorsOf g startId — walks parent links upward. Returns the chain from immediate parent to root. Cycle-safe: stops if a visited id is seen again. A genericClosure over the parent chain, so it has no depth ceiling (the ceiling row below) and takes no depth option. A bound on path depth is pathsBetween { maxDepth = …; }.
graph.ancestorsOf g "grandchild"
# → [ "child1" "root" ]hoistEdges g / reachableVia succ startId / selfReachableVia succ id — the same two traversals with the per-visit work lifted out. The operators above re-read edges at every visit and wrap each successor into genericClosure's item shape there, so a visit costs O(1 + outdeg); hoistEdges does that wrapping once over nodes and returns the successor function, and the two *Via operators read it. Semantics are identical — same reachable set, same order, same exclusion of the start — and a target outside nodes still expands through the accessor, so hoisting cannot truncate a walk.
This is amortization, so it is a trade and not an improvement. k traversals over one accessor go from Θ(k · Σ (1 + outdeg)) attrsets to Θ(n + E) + Θ(k · |reach|): a whole class removed where k is large, and a straight loss where k is 1, because the wrap's Θ(n) spine is built over every node while one traversal reads only the ones it reaches. Reach for it only when the same accessor is walked many times.
let succ = graph.hoistEdges g; # read the accessor once
in map (graph.reachableVia succ) g.nodes # …spend it n timesInside this library cycles and fbNode bind it and dependentsOf and fbWork deliberately do not — see their cost rows for the measurement each decision rests on.
pathsBetween { maxDepth ? 2000; } g startId endId — all acyclic paths from startId to endId. Each path is a list of ids including both endpoints. The maxDepth option caps the path depth it will extend to (given on the accessor record it is refused as misplaced); see the ceiling row below.
graph.pathsBetween { } g "a" "d"
# → [ [ "a" "b" "d" ] [ "a" "c" "d" ] ] # diamondreachableFrom is C-level but BFS, single-keyed and payload-blind — it returns a set, in
no guaranteed order, with no way to expose the traversed edge or carry a projection. These
combinators are the missing DFS pre-order, payload-carrying, edge-exposing dual:
a frame is folded before its children, siblings in list order, each frame visited once (first
occurrence wins) via a threaded visited set. They visit only what they reach, and a
frame's successors may be demand-generated (forced only when the frame is reached).
foldPreorder : { visited?; surface ? "foldPreorder" } → { roots; key; expand; acc; } → { acc; visited }
expandPreorder : { resolve?; emit?; seen0?; nodes0? } → { roots; key; edges; } → { nodes; seen }
foldReach : { visited0?; seen0?; nodes0? } → { roots; edges; target; project; itemKey; } → { nodes; seen; visited }
foldPreorder — the primitive. A pre-order DFS fold with a caller-owned accumulator and a
first-occurrence visited set. key frame is the cycle-guard/dedup key (a null key is never
guarded); expand acc frame → { acc; children? } folds this frame in and yields its child
frames; visited seeds the guard set (a pre-seeded key prunes that frame's subtree without
forcing it). expandPreorder and foldReach are thin specializations of it.
No depth or fan-out ceiling. The fold is a builtins.genericClosure loop over an explicit
DFS stack, with every carried field forced each step, and its visited set is Bentley &
Saxe's logarithmic method over native attrsets, so it copies Θ(n log(n/32)) values rather than
Θ(n²) (lib/preorder.nix's header has the construction and the measured cost, and
./ci/bench/walks-cost.sh is its oracle). The walks (ancestorsOf too) take no depth option;
a bounded walk over paths is pathsBetween { maxDepth; }. surface is the name every
caller-function refusal carries — a specialization written outside this library names itself
the same way.
Contract — strictness. acc is forced to WHNF at every frame, whether or not you read it
(and for foldReach, so are project and itemKey, which build its accumulator). visited is
therefore no longer independent of acc: an acc that throws refuses the whole call, including a
caller who reads .visited alone, and with two bad inputs the refusal reported is the one at the
earlier frame. The seed acc is forced even when roots = [ ]. An acc whose own field is a
lazily chained list ({ xs = a.xs ++ [ f ]; }) keeps that chain's ceiling where you read it: it
is the caller's, not the library's.
Price — an infinite graph diverges. An unbounded stream of distinct keys, or null-keyed
frames that generate forever, is not refused: the walk runs until the evaluator is killed
(measured on the prototype: still running at 20.6 GB after 134 s, deaf to SIGTERM, where the old
depth cap refused in 0.12 s). No finite prefix distinguishes an infinite demand-generated graph
from a large one, so any guard would refuse some finite graph past a bound — a cap that only
bounds cost, and the library states no such cap. The precondition is stated instead: the reachable key set is finite, and
null-keyed frames terminate by finite authored structure. reachableFrom carries the same
precondition.
# classify a nested include tree into two buckets, cycle-guarded by .key
graph.foldPreorder { } {
roots = [ rootNode ];
key = v: v.key or null;
acc = { recs = [ ]; bares = [ ]; };
expand = acc: v: {
acc = { recs = acc.recs ++ policyIncludes v; bares = acc.bares ++ bareIncludes v; };
children = subRecords v;
};
}expandPreorder — payload-carrying DFS-preorder closure. Folds emit frame (resolve frame)
in first-occurrence pre-order into an ordered witness list. resolve is the (possibly
parametric) node force; edges reads the resolved payload's successors, so a node's
children can be demand-generated (they exist only after resolve invokes it). One key set —
key frame both cycle-guards and dedups. seen0/nodes0 seed the guard set and the witness
list.
graph.expandPreorder {
resolve = a: if a.__isWrappedFn or false then a ctx else a; # parametric invoke
emit = a: concrete: { inherit (a) key; content = concrete; };
seen0 = droppedKeys;
} {
roots = aspectList;
key = a: a.key;
edges = concrete: concrete.includes or [ ]; # demand-generated
}
# → { nodes = [ … witness, pre-order … ]; seen = { … }; }foldReach — labeled, suppression-aware, transitive reach fold. Folds over labeled
edges, each carrying a target vertex and a projection label; project edge → [item] is
the per-edge content projection with the whole edge exposed (so it can slice the target's
content by the edge's label — one edge → many items). Negative-edge suppression is expressed
by the edges accessor itself (return a vertex's edges minus the suppressed ones), so the fold
is suppression-aware by construction. Two key sets, because one vertex projects many items:
target edge cycle-guards the vertex DFS (visited0), itemKey item first-occurrence-dedups
the witness across vertices (seen0; a null item key is kept, never deduped).
graph.foldReach {
visited0 = { ${startId} = true; };
seen0 = structuralKeys; # structural component already emitted
nodes0 = structuralNodes;
} {
roots = edgesAt startId; # edgesAt bakes in suppression
edges = edgesAt;
target = e: e.target;
project = e: builtins.filter (classFilter e) (contentAt e.target); # per-edge label projection
itemKey = n: n.key;
}
# → { nodes = [ … ordered witness … ]; seen = { … }; visited = { … }; }These functions enumerate all nodes. They require both edges and nodes.
cycles : { edges, nodes, ... } → [id]
cyclePaths : { edges, nodes, ... } → [[id]]
dependents : { maxIter? } → { edges, nodes, ... } → id → [id]
dependentsOf : { edges, nodes, ... } → id → [id]
dependentsFrontier : { edges, nodes, ... } → id → (id → bool) → [id]
impactOf : { edges, nodes, ... } → id → [id] # alias for dependentsOf
transpose : { edges, nodes, ... } → { edges, nodes }
coScc : { edges, ... } → id → id → bool
condensation : { edges, nodes, ... } → { reps, bottomUp, members, sccs, sccOf, condEdges, depth }
fbNode : { edges, nodes, ... } → <the same record> # partition arm, by name
fbWork : { edges, nodes, ... } → <the same record> # partition arm, by name
lowlink : { root? } → { edges, nodes, ... } → <the same record> (+ cyclic, order with root) # partition arm, by name; the door's default
condensationClosure: { maxIter? } → { edges, nodes, ... } → <the same record> # partition arm, by name
condensationOf : { edges, nodes, ... } → tagOf → <the same record> # the finisher every arm calls
directDependents : { edges, nodes, ... } → { id → [id] }
directDependentsOf : { edges, nodes, ... } → id → [id]
coneRank is an ordering surface and is documented under Ordering below.
cycles g — nodes that appear in any cycle (self-reachable). Read off the SCC partition: a node lies on a cycle iff its component has two or more members or it has an edge to itself (Tarjan 1972, Lemma 9). It binds the lowlink arm by name, so it costs Θ((n + m) · log₈ n) and takes a closed accessor only (Which accessors the partition takes). Returns a sorted list.
graph.cycles g # → [] for a DAG, → [ "a" "b" "c" ] for a → b → c → acyclePaths g — one representative simple cycle per cyclic component, as an ordered node list rotated to begin at the component's smallest key. [] for a DAG. Where cycles answers which nodes lie on a cycle (a key-sorted membership set), cyclePaths answers what the loop is: every consecutive pair in a returned list is a real edge, so a caller may join it with -> and state something true. Reach for it whenever the cycle is going to be shown to a human.
One per component, not all: the SCC is the canonical object, the cycle through it is existential. Enumerating every simple cycle is Johnson 1975 and is deliberately not provided.
The walk for a component C with smallest member u is the one a depth-first search finds: take u's first successor v inside C, then search from v for u, successors in edges order, never visiting a node twice, restricted to C. That is the first simple path from v to u in that order — the one pathsBetween enumerates first, which this surface used to read off it — because a node the search has finished without reaching u reaches u only through the search's current stack. The search is iterated like lowlink (one genericClosure loop over a persistent trie), so the whole surface is Θ((n + m) · log₈ n) on every graph, cyclic or not, and has no depth cap: it no longer inherits pathsBetween's. It takes a closed accessor only.
# b → d → c → b, keys sorting b < c < d
graph.cycles g # → [ "b" "c" "d" ] membership, key-sorted
graph.cyclePaths g # → [ [ "b" "d" "c" ] ] the traversal — b→d, d→c, c→bdependents { maxIter ? 1000; } g targetId — all nodes that transitively reach targetId (reverse reachability). Uses full transitive closure + transpose — closure-class cost (super-quadratic, see Performance), O(1) lookup thereafter. Best for multi-target queries (amortized).
graph.dependents { } g "database" # → [ "api" "web" "worker" ]dependentsOf g targetId — same result as dependents, but uses reverse traversal: builds the reverse edge index over every edge (Θ(n + E)) once per application to g, so a held dependentsOf g answers any number of targets over one index, then runs the same C-level BFS from the target over that index, costing Θ(Σ_{u ∈ reach⁻ target} (1 + indeg u)) — the operator re-reads the index at every visit, and in the reversed graph a node's out-degree is its forward in-degree. O(reachable) only where in-degree is bounded; Θ(n²) on a complete DAG. Preferred for single-target queries on large graphs, and for several targets when the partial application is held (map (graph.dependentsOf g) targets); re-applying it per target (map (t: graph.dependentsOf g t) targets) builds one index per target. The held index lives as long as the partial application does. impactOf, dependentsFrontier g and directDependentsOf g bind their index the same way.
graph.dependentsOf g "database" # → [ "api" "cache" "web" "worker" ]dependentsFrontier g targetId prune — dependentsOf with an early cutoff. Walks the reverse-reachability cone level by level, but descends into a node's own dependents only when prune node is true. A pruned node is still included in the result (it was reached) but is not expanded, so nothing beyond it is walked. Cycle-safe: the traversal is the same C-level genericClosure dependentsOf uses, with prune consulted inside the operator, so the done set is the guard. Reduces exactly to dependentsOf when prune = _: true.
# Everything that depends on db, but stop walking past api:
graph.dependentsFrontier g "db" (id: id != "api")
# → [ "api" "worker" ] # api included, but web (which only reaches db via api) is cutimpactOf — alias for dependentsOf. "What breaks if this node changes?"
transpose g — returns a new accessor record { edges, nodes } with all edges reversed.
rev = graph.transpose g;
graph.reachableFrom rev "database" # → nodes that depend on databasecoScc g u v — are u and v in the same strongly connected component? canReach-backed point query: true iff u == v, or each reaches the other. Each probe stops expanding at its own target, so it materializes its start's closure less the sub-closure that target dominates — and where the target dominates nothing, the whole of it. What is avoided is the whole-graph transitive closure and the dominated remainder, not the rest of the per-probe one.
★ Export-only, and so is the probe underneath it. Nothing in lib/ calls coScc — the condensationClosure arm decides co-SCC from its own materialized closure, not through this name — and coScc is in turn the only caller of canReach in lib/. So the two-probe cost is yours to price, against your own call pattern: the library states the shape (below) but owes no figure on a surface it never calls, and no bench arm measures one. Probing many pairs re-materializes both closures every pair; hold transitiveClosure or a condensation record once instead.
graph.coScc cyclicGraph "a" "c" # → true (a → b → c → a)
graph.coScc dagGraph "a" "b" # → falsecondensation g — collapses each SCC to a super-node and returns the condensation (quotient) graph. This is the one published front door for SCC partitioning; it carries the default, and the arms behind it are published under their own names (see The partition routing contract below). Tarjan's single DFS is one of those arms, lowlink. SCC detection here is constrained to be non-recursive, since the evaluator's call-depth ceiling ends a self-applying step with an uncatchable max-call-depth exceeded, so the DFS is not written as a recursion: its call stack is data, stepped one edge or one pop at a time by a single genericClosure loop over a persistent 8-ary trie. That costs Θ((n + m) · log₈ n), the log being the persistent map's — not Tarjan's O(V + E). The two forward–backward arms iterate over a worklist. Returns a record:
| Field | Type | Meaning |
|---|---|---|
reps |
[tag] |
SCC tags in bottom-up order (== bottomUp) |
bottomUp |
[tag] |
SCCs in reverse-topological order: each appears after every SCC it points to |
members |
{ tag → [id] } |
the member ids of each SCC, sorted |
sccs |
[[id]] |
member lists, in bottomUp order |
sccOf |
{ id → tag } |
the SCC tag (smallest member id) of each node |
condEdges |
{ tag → [tag] } |
the SCCs that each SCC points to |
depth |
int |
the longest path over the condensation DAG, in edges |
c = graph.condensation g;
c.sccs # → [ [ "d" ] [ "c" ] [ "b" ] [ "a" ] ] for chain a → b → c → d
c.sccOf."a" # → "a"
c.condEdges.${c.sccOf."a"} # → SCCs that a's component depends on
c.depth # → 3The three lookups are MAPS, not functions, and that is a contract rather than a style: the door is read across library boundaries, where a foreign evaluation receives only strings, lists, integers and attrsets of those. A function's identity is minted by the build that made it and does not survive the crossing — builtins.toJSON of a record carrying one aborts, uncatchably. A caller that wants a lookup builds one from the map on its own side (id: c.sccOf.${id} or id restores the older spelling exactly). ★ The maps are defined on nodes and on the tags respectively, so an id that is not in nodes is a missing attribute rather than a value: the older function form answered sccOf "nope" with "nope", and the map does not.
depth is the longest path and nothing else. Three different quantities travel under the word — the longest path over the condensation DAG, the closure cardinality of a class, and the summed per-node reach Σ|reach(v)| over atoms — and they separate by the full width of the graph. On a hub depending on 19 leaves the cardinality is 19 and the longest path is 1. Only the longest path is published, because the partition determines every one of the others: a consumer computes whichever its own cost model is fitted over, from { sccs, sccOf, condEdges }, and names its own domain where it derives it. Publishing one of them here would decide that for every consumer; publishing all of them would be this library doing the consumer's work.
Which arm answers by default. condensation is the front door and delegates to lowlink, Tarjan's single DFS iterated — the arm that is Θ((n + m) · log₈ n) on every shape. It used to delegate to fbNode, which is quadratic in the size of one large component; the one shape where lowlink costs more is fleet (many small components), by a constant (×2.19 nrFunctionCalls at n = 1,000). A consumer that derived a figure from the door's cost re-derives it against the new arm: gen-scope's verifiedDepth (2049) is still true and now understated, and gen-scope and gen-program, which reads it, owe that re-derivation on their relock; it is not re-derived here. The delegation is an identity, not a wrapper, so the door cannot drift from the arm it names. Every consumer inside this library binds an arm by name rather than the door — topoOrderKahn's cycle report, cycles, cyclePaths and cyclicEdgesWhere all bind lowlink — because the door's own result is finished with an ordering pass, and an ordering surface reading the door would be ordering through a surface that orders through it.
How the other arms are reached. By name: fbNode, fbWork, lowlink and condensationClosure. There is no mode flag on the door, and that is deliberate: a routing decision is a property of the program, computed once, and a caller-selected mode is a second place the default lives — one a caller can use to select the arm that cannot express their graph. A named arm has no default to disagree with.
What the result carries. The partition itself (sccs, sccOf, condEdges, plus reps/bottomUp/members) and one measure, depth. All plain data. Every arm returns the identical record on every graph (every closed accessor; the rest are refused, Which accessors the partition takes), and that is a property of the CONSTRUCTION rather than of the cells that check it: each arm computes a tag map and nothing else, then calls the one exported finisher, condensationOf. An arm that finished its own record would agree with its siblings only for as long as someone kept three copies in step. condensationOf takes an accessor and a tag map; its precondition is that the tag map is an SCC partition's, total on nodes, since any other map can induce a cyclic quotient — which the ordering pass refuses by name rather than answering.
Which accessors the partition takes. Every surface built on the partition — the three arms, the door, condensationClosure, cycles, cyclePaths and cyclicEdgesWhere — takes a closed accessor only: every target edges returns is in nodes. An edge to a node outside nodes means (nodes, edges) is not a graph (Tarjan 1972 §2: E is a set of pairs of V), so it has no SCC partition to return. The domain is checked once, in the finisher every arm shares (condensationOf), and, for a rooted lowlink's order and cyclic fields, which never force the finisher, by the run itself; so every surface refuses it by name and catchably, the way the ordering surfaces refuse a dangling target: gen-graph.<arm>: edges "<id>" names a target outside nodes``. The name is the arm's — fbNode, fbWork or lowlink; lowlink for the door and for cycles, cyclePaths and cyclicEdgesWhere, which bind it; condensationOf for condensationClosure, which reaches the finisher by that name. The refusal holds including where the off-node target lies on no cycle, and it is attached to the whole record, so reading any one field (sccOf included) refuses. A nodes entry that is not a string is refused by name before any target is read (gen-graph.<arm>: got int, expected a node identifier (a string)). The line is node-set-total versus seeded, not partition versus not: a surface that returns a structure over nodes needs a graph on nodes, while a seeded walk (reachableFrom, canReach, pathsBetween) names no domain to close. cycles sits on that line — it enumerates nodes, and its answer is a per-node reachability predicate — and it is on the closed side because it is read off the partition, and because answering where cyclePaths (the same question plus a witness) refuses would state two domains for one family. The traversals keep the open convention stated under Traversal (lazy) (a target outside nodes still expands through the accessor).
The rooted run, lowlink { root = r; } g. lowlink takes a closed options set first and the open graph record second, the shape topoOrder has. lowlink { } g is the partition record above. With root (a member of nodes, or null for key order alone) the record gains two fields read off the same run, with no second traversal:
cyclicequalscycles g, from one derivation;orderlists every node once, each strongly connected component's members together, and each component after every component it reaches. On a DAG it is the depth-first finishing order of a search that starts atroot, restarts at each unvisited node in key order, and expands successors inedgeslist order. On a cyclic graph the component blocks come in the order their roots finish; the order of members inside a component is not promised. The order does not depend on the permutation ofnodes.
The fields are lazy: order and cyclic force the run alone, never the finisher's closed-accessor scan, while the partition fields force the finisher. Every field still refuses a malformed graph by name; with two faults each field names the first one it meets, so order on a nonmember root over a dangling edge names the root, and sccOf names the edge. A root outside nodes is refused (root "zz" is not a member of `nodes`), a non-string root names its type, and a root left on the graph record is refused as a misplaced option. root is read by lowlink alone: condensation, cycles and cyclePaths ignore one.
★ Migration hazard. A caller still written in the one-record form lowlink { nodes; edges; } now hands its record to the OPTIONS set and is refused by name, catchably (gen-graph.lowlink: 'edges' is not an option of this door; the options are closed (accepted: 'root')). Write lowlink { } g. There is no compatibility arm: a door that read a graph in the options position would admit an options set with unknown fields. A caller that calls the door many times binds lowlink { } once; written inline, lowlink { } g pays the options step on every call (measured +5 thunks per call bound once against +8 inline, over the unary form the door replaced).
When each arm wins — measured, with no budget attached. The arms are complementary, not ranked: all three take the same input, a closed accessor, and none is uniformly cheaper. Growth exponents by doubling pair, ci/bench/cost-classes.nix, arms fbNode / fbWork / lowlink:
| shape | pairing | fbNode list / sets / nrLookups |
fbWork list / sets / nrLookups |
lowlink list / sets / nrLookups |
|---|---|---|---|---|
cycle (ONE component) |
500→1000 | 2.00 / 1.99 / 1.99 | 1.00 / 0.96 / 0.99 | 1.37 / 0.99 / 1.21 |
cycle |
1000→2000 | 2.00 / 2.00 / 2.00 | 1.00 / 0.98 / 1.00 | 1.00 / 0.99 / 1.00 |
fleet (n components) |
500→1000 | 1.04 / 1.00 / 1.04 | 1.05 / 1.35 / 1.04 | 1.27 / 1.00 / 1.16 |
fleet |
1000→2000 | 1.04 / 1.01 / 1.04 | 1.05 / 1.53 / 1.04 | 1.02 / 1.01 / 1.02 |
chain |
500→1000 | 1.97 / 1.96 / 1.96 | 1.94 / 1.85 / 1.95 | 1.27 / 0.99 / 1.15 |
chain |
1000→2000 | 1.99 / 1.98 / 1.98 | 1.97 / 1.92 / 1.97 | 1.02 / 1.00 / 1.00 |
deepwide |
8000→16000 | 0.02 / 0.04 / 0.06 | 0.04 / 1.02 / 0.07 | 1.01 / 1.22 / 1.09 |
deepwide |
16000→32000 | 0.04 / 0.09 / 0.12 | 0.08 / 1.56 / 0.14 | 1.01 / 1.14 / 1.08 |
Read the two extremes together, because either alone is misleading. On one large component fbNode is quadratic and fbWork is linear — it spends a pivot per node where the worklist spends one per component, and at n = 2000 on cycle that is 36,048,017 list elements against 62,018. On many small components the ranking reverses on the allocation axis: fbWork's accumulator acc.tags // … copies the whole growing tag map once per component, so it is quadratic in copies whatever the node order — nrOpUpdateValuesCopied 1,565,126 → 25,010,126 on fleet at n = 5000 → 20000 (exponent 2.00) while its calls read 1.03 — and its sets term grows with it (1.35 → 1.53 on fleet, 1.88 over 5000 → 20000, and 1.02 → 1.56 on deepwide), while fbNode, which carries no accumulator at all, stays flat at 1.00–1.01. On one large component fbWork is linear on every axis: cycle 5000 → 20000 reads calls 1.00 and copied flat at 127. chain is quadratic for both and for the same reason — every pivot's reach set is Θ(n) whichever arm picks it — and there fbWork is quadratic in calls and copies (1.99 / 2.00 over 2000 → 4000). lowlink is neither extreme: one DFS whatever the component structure, so every row reads 1.00–1.02 on list inside one trie depth, and 1.27–1.37 on the doubling that adds a level (500 → 1000 crosses 8³ = 512), which is the log₈ n term and not a quadratic. Its nrOpUpdateValuesCopied is flat at 127 on every shape it is read on here, because it performs no //. Where every reach is small the forward–backward arms win by a constant: on fleet at n = 2000 fbNode reads 524,466 calls against lowlink's 1,171,109. No figure here is a budget and none is offered as one; they are filed with their derivation so the choice between arms is made against measurement rather than against intuition, and they are to be re-derived whenever either construction changes.
Ceilings, one row per surface the partition and its consumers reach. A surface with a real ceiling refuses by name at it; a surface with no measured ceiling states that and refuses nothing; no ceiling is invented to bound a cost. A "none found to N" row is a bounded claim, not a guarantee, and each row carries its N.
| surface | ceiling | disposition |
|---|---|---|
fbNode |
none found to 64,000 atoms on fleet, 4,000 on chain, 4,000 on cycle (one 4,000-member component) |
states no ceiling; refuses nothing |
fbWork |
none found to 64,000 atoms on fleet, 4,000 on chain, 4,000 on cycle |
states no ceiling; refuses nothing |
lowlink |
none found to 100,000 on chain, cycle, star and rand (ci/bench/partition-ceiling.sh). The code contains no recursion, but its evaluation depth is not constant: it is set within a step by the trie's nesting, so it grows at most as Θ(log₈ n). Lowest passing max-call-depth on cycle under that instrument: 41 at 1,000 and 10,000, 43 at 100,000 |
states no ceiling; refuses a target outside nodes, and a nodes entry that is not a string, by name |
condensationClosure |
real — the closure is a capped fixpoint, so it returns iff the cap (1,000 as shipped) is at least the graph's diameter, and throws otherwise | refuses by name: the message names this surface and the diameter the closure could not reach, not the fixpoint's iteration count. The message, and why only these four surfaces may name a cause, are under Fixpoint |
dependentsOf |
none found to 256,000 on chain (depth 255,999); depth-1 control at 64,000 |
states no ceiling |
reachableFrom |
none found to 256,000 on chain; depth-1 control at 64,000 |
states no ceiling |
directDependents |
none found to 64,000 | states no ceiling |
canReach |
none found to 64,000 | states no ceiling |
selfReachable |
none found to 64,000 | states no ceiling |
cycles |
none found to 100,000 on cycle, chain and rand (ci/bench/cost-classes.nix, arm cycles); it inherits lowlink's Θ(log₈ n) evaluation depth and adds no recursion of its own |
states no ceiling and the bound of the claim |
cyclePaths |
none found to 100,000 on cycle, chain and rand (arm cyclePaths). The witness search is iterated like lowlink, so it has no depth cap; it no longer inherits pathsBetween's, under which it refused a 4,000-member ring |
states no ceiling and the bound of the claim |
topoOrder / topoOrderKahn |
none found to 64,000 | states no ceiling |
phaseOrder |
none found to 16,000 | states no ceiling and its bound |
coneRank |
none found to 32,000 on chain and deepwide |
states no ceiling |
pathsBetween |
real — ≈2,498 on chain as an UPPER BOUND in a bare expression: uncatchable, depth-driven, and strictly lower under any open call stack (three measuring expressions give 2,498 / 2,499 / 2,500 on one fixture, and eight extra evaluator frames above the call move it below 2,497; re-derived at 374b0ad, 2,497 returns / 2,498 aborts bare and 2,447 / 2,448 under 200 added caller frames) |
refuses by name past a STATED cap (maxDepth, 2,000 as shipped), which is what makes the refusal catchable at all: the evaluator's own abort is not. The cap is a parameter because the boundary belongs to the whole evaluation — a consumer nested deep lowers it |
foldPreorder / expandPreorder / foldReach |
none found to 200,000 on chain and star and to 402,000 on deepwide (a 2,000-node spine with 200 leaves per node). The walk contains no recursion: one genericClosure step per DFS action over an explicit stack, every carried field forced per step. The self-recursive core it replaced aborted at 4,994 on chain and, because its accumulator was never forced, with CSTACK on a 34,000 star |
states no ceiling. An infinite demand-generated graph DIVERGES rather than refusing, a recorded price (the pre-order section) |
ancestorsOf |
none found to 200,000 on a parent-chain. A genericClosure over the chain, with no recursion; the recursive walk it replaced aborted at 9,989 |
states no ceiling. An infinite parent chain of distinct ids diverges |
Two axes are excluded from every "none found" row above and are named once rather than per row. Shape: the readings are on chain, fleet, cycle, star, bush and deepwide; dense and complete shapes are not measured for ceilings. Evaluation context: a surface that spends an evaluator frame per link has a boundary belonging to the whole evaluation rather than to the surface, so a consumer's real ceiling is strictly lower than a bare-expression reading. One surface above is frame-per-link, pathsBetween, so that axis qualifies its row and leaves the others untouched. It is also why its cap is a parameter rather than a constant: a stated cap that a consumer cannot lower is a bare-expression figure sold as a consumer's ceiling.
Provenance, so no row is hand-carried. The three arm rows and the plain-data property are re-derived in this repository: ./ci/bench/partition-ceiling.sh (verdict CEILING-FREE, with a fixed-depth abort control firing at every cell and the unforced-accumulator construction as a live negative control) and ./ci/bench/partition-plaindata.sh (verdict CROSSES, with the pre-map record shape and a bare function as armed controls that must fail). The coneRank row is ./ci/bench/cone-ceiling.sh. The remaining rows were measured outside this repository, by the same instrument shape — the exit code of nix-instantiate --eval --strict --json on a separate evaluation, with okControl / catchControl / fixed-depth abortControl in every sweep — and this repository carries no cell that re-derives them. That is stated rather than left to be assumed.
The calibrated successor, named and NOT armed. Routing on a cheap pre-partition upper bound — edge count, out-degree distribution — is the calibrated successor to selecting an arm by name. It is decidable when a synthetic configuration of the intended scale exists, and not before: there is no present artefact whose stratum depth stands in for the intended fleet, so a threshold fitted against what exists today would have a domain that does not match the property it quantifies over, and would be uncalibrated by construction. No bound is proposed here, not even a placeholder — a number in this contract would be read as the thing to tune rather than the thing to derive.
directDependents g — the full direct reverse-adjacency map { id → [direct dependents of id] }: the immediate reverse neighbours of every node, in one Θ(n + E) groupBy — it visits every node to read its out-edges, so a node with none still costs its visit. This is the public face of the internal _reverseIndex. Direct, in contrast to dependentsOf's transitive closure — a producer with no consumer simply has no key.
directDependentsOf g id — the immediate dependents of a single node: (directDependents g).${id} or [ ].
graph.directDependentsOf g "A" # → [ "B" ] (DIRECT — immediate neighbour)
graph.dependentsOf g "A" # → [ "B" "X" ] (TRANSITIVE — full reverse cone)topoOrder is the ordering front door for the gen ecosystem. Behind it are two arms:
Kahn's algorithm (A. B. Kahn 1962; not Gilles Kahn 1974, which preorder.nix cites for
something else) over an accessor, and a certificate-gated comparator arm that answers only
where it can prove its answer is the one Kahn's would have given. entry*/phaseOrder are the home-manager-style authoring layer on top
of it, for consumers that would rather write before/after constraints than build an
accessor.
topoOrder { keyOf ? id; lessThan ? builtins.lessThan } { nodes; edges; ... }
: { ok = true; order = [ node ]; } | { ok = false; cycles = [ [ node ] ]; }
topoOrderKahn <same> : <same> ( the ARM, by name )
coneRank : { edges, ... } → [id] → { order, depth }
entryAnywhere : entry ( {} — no constraints )
entryAfter [ "a" ] : entry ( comes after "a" )
entryBefore [ "b" ] : entry ( comes before "b" )
entryBetween { before = befs; after = afts; } : entry
phaseOrder { name = entry; ... } : [ name ] ( forward topological order )
topoOrderKahn { } accessor is Kahn's algorithm published under its own name, and
topoOrder is the door, which selects. The two are separate because a default is a
separate decision from an algorithm: a caller whose correctness depends on which arm
answers binds the arm, and coneRank below is exactly such a caller. Everything documented
for topoOrder holds verbatim for the arm — same formals, same refusals, same cycle report —
except that each refusal names the door the caller invoked.
Options first, then the graph. The options set { keyOf, lessThan } comes first, so
topoOrder { lessThan = …; } is itself an ordering function; the graph record comes second and
is open, so a record wider than { nodes, edges } is ordered as it stands. The options set
is closed by gen-prelude's shared checkOptions: a misspelt option is refused by name, catchably, when
the options are applied. The graph record is a door too: a graph argument that is not an
attrset, or a record missing nodes or edges, is refused by name, catchably, when it is applied.
★ Migration hazard. A caller still written in the one-record form topoOrder { nodes; edges; }
now hands its record to the OPTIONS set and is refused by name, catchably
(gen-graph.topoOrder: 'edges' is not an option of this door; …) — loudly, and in-roster the suites catch it. The quiet case is a caller that migrates
mechanically to topoOrder { } { nodes; edges; keyOf; }: an option left on the open graph record
is ignored, not refused, so keyOf and lessThan must move into the first argument.
The selection is invisible in the answer, by construction. The second arm sorts the nodes
by (out-degree, key) and then CHECKS two things about that candidate: that every edge points
strictly backwards in it, and that each element is a direct dependency of the next. The first
makes it a topological order — and, over a total position map, proves the graph acyclic. The
second means every topological order must place those pairs that way, so by transitivity there
is exactly one such order and the candidate is it. Where both hold, the door emits what
Kahn's arm would have emitted, necessarily and at every index; where either fails, Kahn's arm
answers. The gate is what makes that true rather than likely: the same candidate emitted
ungated diverges from this door on 1,990 of 2,000 positions on a fleet-shaped graph, and on a
chain whose keys descend with depth it is not a topological order at all.
What it costs, both ways. On the dense total order at n = 2000 the door allocates
8,026,003 list.elements against the arm's 24,082,640 — 2.010 per edge net of the
fixture against 10.042 — and 36,522 sets.elements against 21,960,278, because the
comparator arm builds neither the reverse index nor the emission loop. On a shape the gate
refuses, the door pays the check and nothing else: 2n − 1 list.elements and n
sets.elements, constant in E, measured on every refused shape including the dense ones.
★ A caller supplying a lessThan that is not a strict total order — the one precondition this
door documents and cannot afford to check — can only produce a candidate the gate REJECTS, so
that precondition is guarded here rather than merely stated.
What the door promises. (1) TOPOLOGICALITY — PROMISED: ok = true carries a linear
extension of the dependency relation. (2) PERMUTATION-INDEPENDENCE — PROMISED while lessThan
is a strict total order on distinct keys: the order is a function of the node set, the edges,
keyOf and lessThan, never of the nodes list's permutation. (3) WHICH LINEAR EXTENSION —
DECLARED AND PINNED, NOT NORMATIVE: today the door answers with the Kahn arm's pick, the
smallest ready key under lessThan taken globally; the cells pinning it are named
…-change-detector and are re-baselined deliberately, and the ruled default flip to the rank
recurrence moves it. A consumer whose value depends on the order among incomparable nodes
declares that order itself — as edges — rather than inheriting this one. topoOrderKahn is
outside clause 3: it is the named algorithm, and its global min-key ready discipline is its own
contract, pinned by the cells that bind the arm by name. The basis is the design's premise that
the door owes "a pinned, DECLARED order — not one specific order".
topoOrder { } accessor does not throw on a cycle. It returns a producers-first
ordering, or the cycles that prevented one — as strongly-connected-component member sets,
sorted within each component, all of them, so a caller sees every cycle at once rather
than fixing one and meeting the next. A self-loop is reported as its own singleton
component. Consumers that build their own diagnostic (the retired gen-pipe named the channels
and the operators forming each edge) need the members, not a throw.
keyOfprojects a node to its string identity, which is also its tie-break key. It is what admits nodes that are not themselves strings — the retired gen-edge ordered edge records by a canonical sort key, and gen-view, which inherited that materialization, reaches this library's Kahn arm the same way. Not gen-class'smkClasses { nodes; keyOf; }argument, which shares the name and thenode -> stringshape but plays the opposite role: that key partitions nodes into share-classes, deliberately mapping many nodes to one key, while this one identifies a node and a collision in it is a refusal.lessThanorders those keys. Ordering by a frozen key is what makes the result a function of the node set rather than of the input permutation (clause 2 below); which order incomparable nodes take is clause 3's, declared and not normative, andlessThanis not promised to order an antichain. It must be a strict total order on distinct keys — a documented precondition rather than a refusal, and the only requirement here that is not checked. The ready set is a heap and a heap is not stable, so a comparator that is not a strict total order can separate this ordering from the one a stable whole-array sort would give. Establishing totality means exercising the comparator on every pair, Ω(m²) comparisons, which is worse than the cost the heap exists to remove and would be paid on every call including the overwhelming majority using the default. Keys are distinct by construction — a shared key is already a refusal.- A
keyOfoutput that is not a string, two nodes sharing a key, and an edge naming a node outsidenodesare each a refusal by name — athrowthattryEvalcan catch, not the uncatchable type error those cases would otherwise raise insidegenAttrs.
No node-count ceiling. The Kahn loop is driven by a bounded iteration over the key
list rather than by a step that applies itself, so its evaluator frame cost is constant in
n. There is no graph size at which ordering aborts with
stack overflow; max-call-depth exceeded — an abort tryEval cannot catch — and no size at
which the front door declines to order. Measured: a 20,000-node chain orders under
--option max-call-depth 1000, twenty times the setting, on every public accessor of both
topoOrder and phaseOrder. Cost is the only remaining bound, and it is no longer a
quadratic one: over n = 1000 / 2000 / 4000 the loop's allocation grows by ×2.10–×2.12 per
doubling on list.elements (exponent 1.07–1.08) and ×1.99–×2.18 on sets.elements
(exponent 0.99–1.12), on all four acyclic shapes — read on arm topoOrderKahn, which is the
loop by name. Through the door the routed shapes are cheaper than that and the refused ones
are the loop plus 2n − 1. A large graph gets slower rather than
refused, and it gets slower roughly in proportion to itself.
None of the loop's three carried structures is a quadratic. The emitted sequence is held
as runs whose lengths are the binary representation of the number of nodes emitted, so
appending is the increment of a binary counter and an element is copied once per carry it
survives: Θ(n log n), where appending to one vector copied k elements at step k and cost
Θ(n²). The indegree map is a residue over a base that is not rewritten — only nodes
decremented but not yet at zero are carried, so on a graph whose indegrees are all one the
residue is empty at every step — and the residue is folded back into a rebuilt base once
carrying it has cost about what rebuilding costs, which is what keeps a graph that satisfies
many nodes partially from paying the same quadratic in a smaller font. The ready set is a
leftist heap with O(log m) insert and delete-min, Θ(n log n). Held as a sorted array instead
— rebuilding the unconsumed residue and re-sorting it on every arrival — it was a third,
independent quadratic, and on shapes with out-degree it was the largest single term: 60% of
the loop's list.elements on independent pairs, 21% on a fleet of ten-chains, 43% on a
binary tree, and 0% on a chain, whose ready set never holds two nodes at once.
The heap's price is now the leading set-axis term, as it was predicted to become. It adds
one attrset per node on each merge path, 63 → 89 attrsets per node across n = 1000 → 8000;
with the indegree map's quadratic gone, that Θ(n log n) term is what the wide set axis
mostly is — 427,094 ÷ 4000 = 106.8 sets.elements per node at n = 4000, against the
heap's own ~80. It is stated rather than netted, and it is the reason sets grows a little
faster than list on the shapes with real out-degree.
The set axis is shape-dependent where the list axis is not, because it is the one the
indegree residue is charged to: exponent 0.99 on a chain, 1.02 on a fleet, 1.09 on discrim,
1.12 on wide, and 1.21 off the committed shapes where consumers really do accumulate
waiting on a late common producer. On a driver chain with √n waiters it reads 1.49 — and
there E is itself n^1.5, so 1.49 is E-linear and is the floor, not a defect. What keeps
those numbers off a quadratic is when the residue is folded back into its base; the width
comment in lib/order.nix derives the trigger and prices getting it wrong.
None of this is a claim about dense inputs. On the total order (shape=total, node i
depends on every j > i, E = n(n−1)/2) the loop costs 12.05 list.elements per edge at
n = 2000 against 12.01 before the change: unmoved, because both accumulators are already
small there and what dominates is the reverse index — 4.00 per edge, 36.3% of the total —
which neither remedy touches.
★ That 12.05 is GROSS, and on this shape the distinction is load-bearing. total's fixture
is Θ(n²) by construction, so arm=floor is not a rounding error here the way it is on every
sparse shape — it is 2.01 of the 12.05. Net of the floor the loop costs 10.04 list.elements
per edge, and the per-edge figure falls across the sizes measured — 10.15 / 10.08 / 10.04 at
n = 500 / 1000 / 2000, with sets 11.02 / 10.99 / 10.98 and nrLookups 7.21 / 7.11 / 7.05. A
flat-to-falling cost per edge on all three axes is the statement that this surface is Θ(E),
i.e. linear in the input it is given, and a dense input is simply a large one. Quote whichever
figure you like, but quote which: 12.05 and 10.04 are the same measurement, and a budget compared
against the wrong one is comparing a library to a fixture.
Re-run, and the figures above have two different producers, split by whether they are a
reading or a comparison. The growth rates and the per-node counts are readings of the shipped
library: ci/bench/cost-classes.nix, arm topoOrderKahn — the loop by name, which is what
these figures are about; arm topoOrder is the door and answers a routed shape with the other
arm — at n = 1000 / 2000 / 4000. The
shares and deltas — the ready set's 60% / 21% / 43% / 0%, and the heap's 63 → 89 attrsets
per node — are comparisons between two revisions of this library, and the array ready set
exists at neither the tip nor in any arm of ci/bench/cost-classes.nix, so no command in this
repository produces a share or a delta, and none can. Those come from the committed
two-revision harness: den-architecture,
specs/2026-08-08-gen-graph-ready-set-quadratic.r1-*, whose .r1-data-note.md carries the
procedure, the pinned revisions and the md5 anchors. The 1.21 and 1.49 exponents have a
third producer again: their shapes are in no arm of this bench, and they are recorded with
den-architecture, specs/2026-08-09-gen-graph-accumulator-remedies-spec.md, alongside the
arm-against-arm measurement the residue's fold trigger is derived from. Post-change cells
— what the shipped topoOrder costs on any shape, as it stands — come from
ci/bench/cost-classes.nix, arm topoOrderKahn, shapes wide / fleet / discrim / total /
deepwide. ★ Before quoting a
sets.elements figure from that bench, read ci/bench/sentinel.sh: sets figures are
comparable only within one revision of the bench file, and the sentinel is what says which
revision you are on.
coneRank g cone — producers-first topological rank of a node set, computed
cone-locally. Returns { order; depth; } where depth id = 0 if id has no producer
inside cone, else 1 + max(depth of its in-cone producers), and order is cone sorted
ascending by depth with an id tie-break (so every producer precedes its consumers).
Memoized via lib.fix over the cone, so it runs in O(|cone| + edges-in-cone) — it does
not materialize the whole-graph condensation. This is longest-incoming-path
topological rank restricted to a dependent cone (cf. Tarjan 1983 — unheld, cite unverified).
graph.coneRank g [ "A" "B" "X" ] # for B→A, X→B
# → { order = [ "A" "B" "X" ]; depth = { A = 0; B = 1; X = 2; }; }No ceiling, and a cyclic cone is a named refusal. Both used to be otherwise, and both
came from the same place. The memo map is forced along a topological order of the cone,
taken from topoOrderKahn — the arm by name, so that a future default cannot make the rank
recurrence call itself. Forcing in that order flattens what was a descent: reading the
deepest node first used to walk the cone one evaluator frame per link and abort with
stack overflow; max-call-depth exceeded, uncatchably, at a 3,998-node chain and at every
size of a graph with a 4,000-deep leg. No ceiling found to 32,000 on either shape, so
this surface states that and refuses nothing at a size — re-run
./ci/bench/cone-ceiling.sh, which runs the pre-remediation construction beside the
current one at every cell and reports INVALID if that control does not abort.
The cone no longer has to be acyclic. The ordering call that supplies the warming order is
the same call that reports a cycle, and its verdict is read before the memo map is
entered, so a cyclic cone is a throw naming the cycle instead of an uncatchable
infinite recursion encountered. The order of those two steps is the requirement, not
merely that the driver exists: ./ci/bench/cone-consultation.sh is one construction with a
single switch on consultation order, and the late arm dies on a cyclic cone while returning
the same order as the early one on an acyclic cone.
The price is one ordering pass, filed rather than accepted silently:
ci/bench/cost-classes.nix, arms coneRank and coneRankShipped.
phaseOrder entries is the throwing convenience layer over topoOrder: it returns
a valid topological order, and throws on a cycle or a self-loop, preserving the
contract gen-dispatch's dag.nix had.
Behaviour change — an unknown phase name is now a refusal, and used to be ignored. An
after or before naming a phase that is not a key of entries previously composed
fine, with the constraint silently dropped: phaseOrder { a = entryAfter [ "ghost" ]; b = entryAnywhere; } returned an order treating a and b as independent. It now throws a
named refusal. A constraint that cannot be honoured is a caller error, and dropping it
returns a confidently wrong order rather than no order.
For genuinely independent nodes the tie-break is today
ascending name, declared and not normative (topoOrder's clause 3), so treat the result as
a valid order rather than a specific permutation —
a consumer that applies a phase's effect only after the phase (so later phases see
earlier results, never the reverse) is output-invariant across any valid order.
Edge direction, stated once. edges u ∋ v means "u depends on v" (consumer →
producer), so an ordering is producers-first. Every ordering surface in this library reads
an accessor this way — topoOrder, coneRank, condensation.bottomUp, dependentsOf,
reachableFrom — and so does phaseOrder's internal construction: after = [ d ] on n
builds the edge n → d.
graph.phaseOrder {
validate = graph.entryAnywhere;
resolve = graph.entryAfter [ "validate" ];
emit = graph.entryAfter [ "resolve" ];
} # → [ "validate" "resolve" "emit" ]These functions scan all nodes. They require nodes.
roots : { edges, nodes, ... } → [id]
leaves : { edges, nodes, ... } → [id]
select : { nodes, nodeData, ... } → (attrset → bool) → [id]
roots g — nodes with no incoming edges (not a target of any edge). Sorted.
leaves g — nodes with no outgoing edges (edges id == []). Sorted.
select g pred — ids where pred (nodeData id) is true.
graph.select g (d: d.type == "backend") # → [ "api" "worker" ]materialize : { edges, nodes, ... } → { id → [id] }
materializeParents : { parent, nodes, ... } → { id → id }
materialize g — builds an edge map { nodeId = [targetId ...]; } for all nodes. Deduplicates each target list via lib.unique.
materializeParents g — builds { nodeId = parentId; } for nodes where parent id != null. A parent result that is a set, a list or a function is refused by name; a scalar is carried as given.
fixpoint : { maxIter?, refusal? } → step → seed → edgeMap
seededFixpoint : { maxIter? } → { seed, frontier, step } → edgeMap
compose : { first, second } → edgeMap
closureClass : [ surfaceName ]
closureOf : surfaceName → { maxIter? } → { edges, nodes, ... } → edgeMap
transitiveClosure : { maxIter? } → { edges, nodes, ... } → edgeMap
transitiveReduction : { maxIter? } → { edges, nodes, ... } → edgeMap
fixpoint { maxIter?, refusal? } step seed — iterates step on seed until the result stabilizes (next == current). Throws if the step is not ascending — if it withdraws an edge the accumulator already held — naming the withdrawn edges, or if it exceeds maxIter (default 1000). The test is containment of edge content (differenceEdges { minuend = current; subtrahend = next; } == { }), not edge count: a step removing one edge and adding another keeps the count and is still refused. ★ Edge targets must be strings, because the membership set the test builds is keyed by them; a non-string target gets Nix's own type error rather than a gen-graph refusal.
The cap's refusal names no cause, and that is deliberate. Reaching maxIter, this binding has observed two things — the cap was reached, and no step ever withdrew an edge, since the guard would have refused that where it happened — and step is yours, so it cannot know which of two unrelated constructions it is holding: a step whose ascent (monotone, or merely inflationary) is longer than the cap, or a step stationary in edge content that is never literally equal, which permuting a target list is enough to produce — the containment test passes in both directions and next == current never holds. The message therefore reports the observation and stops; saying the step ascended would be false of the permutation, which reaches the cap having ascended nowhere. refusal is how a caller whose step is fixed supplies its own reading: it receives the cap that was exhausted and returns the message to throw.
closureClass / closureOf surfaceName { maxIter? } g — transitiveClosure, dependents, condensationClosure and transitiveReduction each make one closure call, so they share one cost curve (see The closure class under Performance), one ceiling, and one refusal. closureOf is that shared construction, named by the surface calling it; closureClass is the enumeration it accepts, and a surface off that list is refused rather than allowed to emit a refusal naming a surface the library does not have. Every member takes maxIter as its OPTION and forwards it to the fixpoint (transitiveClosure { maxIter = 64; } g), so a caller who knows their graph's depth can state the budget the refusal will quote back; a maxIter given on the accessor record is refused as misplaced.
Because the closure's step is unionEdges current (compose { first = current; second = mat; }), it only ever grows — it is monotone on the subset order, not merely on cardinality — so the withdrawing cause cannot arise there, and since fixpoint's own guard now tests that same order it cannot arise past the guard anywhere; the stationary-but-unequal cause cannot arise here either, because this step converges. Reaching the cap can only mean an ascending chain that has not converged. For reachability that chain's height is the graph's diameter, so these four refuse with it by name:
gen-graph: dependents: the graph's reachability diameter exceeds 1000, the closure
fixpoint's iteration cap. The closure step is monotone on the subset order by
construction, so an unconverged closure at the cap is depth and nothing else.
closure = graph.fixpoint { } (current: graph.unionEdges current (graph.compose {
first = current;
second = (graph.materialize g);
})) (graph.materialize g);seededFixpoint { maxIter? } { seed, frontier, step } — semi-naive variant of fixpoint. Here step takes two arguments, step frontier accumulator, and is shown only the current delta frontier rather than the whole accumulator — so each iteration does work proportional to what changed, not to the full result. Newly produced facts join the accumulator and become the next frontier; it converges when the frontier empties. Throws past maxIter (default 1000).
★ step must be monotone in BOTH arguments. The binding does not check THAT — it checks ONE-STEP SUPPORT, which a monotone step cannot fail. This line used to say no monotonicity guard was needed "since union-accumulation never shrinks" — true of the accumulator and silent about the content. Union cannot shrink, but neither can it RETRACT: a rule concluding from a fact's ABSENCE keeps its conclusion after that fact arrives, so the run converges, well-formed, on an accumulation the converged graph does not support. At convergence every conclusion must therefore be an axiom (seed ∪ frontier) or be re-derived by step from the converged accumulator; one that is not is refused by name, the message enumerating the withdrawn conclusions.
★★ THE ABSENCE OF A REFUSAL IS NOT EVIDENCE THAT YOUR step IS MONOTONE, and the gap is the same defect class. Support is strictly weaker than foundedness: a conclusion drawn on an absence that later acquires a circular re-derivation is supported, and is returned. p :- not r. p :- p. r :- a has a non-monotone step (measured: step {a} yields p, step {a,r} does not), is not refused, and returns p — which the well-founded model makes FALSE. Closing that needs a well-founded engine, which is a later phase's work here — but nothing need wait on it: gen-scope ships one today (wellFoundedModel), so a caller needing foundedness runs it one layer up. It is unreachable from gen-graph by layering rather than by absence: gen-scope takes gen-graph as a flake input, so consuming it here would invert the dependency. The ceiling is instrumented, not just described: test-seeded-circular-rederivation-is-supported-and-RETURNED.
Measured price: one extra full step, and the axis is ROUND COUNT, not size. On the canonical closure instance over a 400-node chain (~399 rounds) it is +0.73% (45,307,630 → 45,637,203 thunks), cpuTime ranges overlapping either side — but on a diameter-2 graph, which converges in 2 rounds, it is +30% to +37%, stable at 402 and at 1,602 nodes. Shallow dependency graphs pay the high end.
# Semi-naive transitive closure: dR = dF ∘ R each round.
mat = graph.materialize g;
closure = graph.seededFixpoint { } {
seed = mat;
frontier = mat;
step = dF: _acc: graph.compose {
first = dF;
second = mat;
};
};compose { first; second; } — relational composition of two edge maps. For each a → b in first and b → c in second, emits a → c. Composition is not commutative, so the two maps are one record whose field names carry the order.
transitiveClosure { maxIter ? 1000; } g — full transitive closure as an edge map. Materializes g, then iterates compose to fixpoint.
transitiveReduction { maxIter ? 1000; } g — minimal edge map preserving reachability. Removes edge a → c when a → b → c exists for some b. Standard DAG transitive reduction (gen-graph's own implementation); assumes a DAG — the reduction is unique only on acyclic graphs.
These operate on materialized edge maps { id → [id] }, not on accessor records.
unionEdges : edgeMap → edgeMap → edgeMap
intersectEdges : edgeMap → edgeMap → edgeMap
differenceEdges : { minuend, subtrahend } → edgeMap
selectEdges : (id → id → bool) → edgeMap → edgeMap
unionEdges a b — merged edge map; target lists are deduplicated.
intersectEdges a b — only edges present in both maps. Empty target lists are dropped.
differenceEdges { minuend; subtrahend; } — edges in minuend not in subtrahend. Empty target lists are dropped.
Top-level helpers for building accessor records, exported flat (no mock namespace).
mkGraph : { edges?, parents?, nodeData? } → accessorRecord
fromRegistry : { parent? } → edges → registry → accessorRecord
fromScan : { nodeData?, parents? } → { items, scan, project } → accessorRecord + { derivedEdges }
field : name → id → entry → [id]
fields : [name] → id → entry → [id]
fixtures : { diamond, chain, cyclic, tree, attributed, disconnected }
labeledFixtures : { world, cyclic, poisoned } # { labeledEdges; nodes; } for labeled queries
mkGraph — takes declarative { from; to; } edge lists and returns a valid accessor record with all four fields populated.
g = graph.mkGraph {
edges = [
{ from = "a"; to = "b"; }
{ from = "b"; to = "c"; }
];
nodeData = {
a = { label = "start"; };
c = { label = "end"; };
};
};
graph.reachableFrom g "a" # → [ "b" "c" ]
graph.select g (d: d ? label) # → [ "a" "c" ]fromScan — the graph a reference scan derives. Where mkGraph takes an edge list you already have, fromScan takes the values and constructs one: items are { id; value; } pairs, scan reads the references out of a value, and project maps a reference to the id it names. The dependency structure is then a function of the values alone, knowable before any of them is used — Mokhov, Mitchell & Peyton Jones, Build Systems à la Carte (ICFP 2018) §3, applicative task dependencies.
g = graph.fromScan {
nodeData = { "theme:font" = { field = "font"; }; };
} {
items = [
{ id = "theme:font"; value = { size = mkRef "terminal:size"; }; }
{ id = "terminal:size"; value = { }; }
];
scan = v: builtins.filter isRef (builtins.attrValues v);
project = r: r.target;
};
g.edges "theme:font" # → [ "terminal:size" ]
graph.cyclePaths g # → [ ]
g.derivedEdges # → [ { from; to; item; ref; } ]Nothing here knows what a reference is: scan and project arrive as arguments, so the scanned domain's vocabulary never enters gen-graph, and ids stay opaque strings — the compound "<identity>:<field>" addresses above are never split. Two contract points. nodeData's keys seed nodes and items do not, so an item the scan finds nothing in, and that nothing references, is absent unless you name it. And derivedEdges comes back beside the accessor carrying the item and the ref behind each edge — that is where a caller reads a reference's own payload, instead of running the scan a second time.
fromRegistry — wraps an arbitrary registry attrset. edges/parent are id → entry → … projections applied per node; field/fields build common projections.
g = graph.fromRegistry { } (graph.field "deps") myNodes;Malformed caller data is refused by name, catchably. Each read of caller data is guarded where it already was, never pre-scanned, so a construction refuses exactly what the unguarded read died on or misread, and a read that never meets the defect answers as before. Shape is checked at every read (a list is a list, an element is a record, a field is present); an endpoint's stringness only where the constructor keys it (from, a keyed to, a scanned item's id). An endpoint passed through unkeyed — edges id returning a to, parent id, derivedEdges[i].from — is not checked for type. A message names the door you invoked, the field and the element's position, and the type, never the value:
gen-graph.mkGraph: edges element 0: 'from' is a int, not a node identifier (a string)
gen-graph.mkGraph: parents element 0 has no 'to'
gen-graph.mkGraph: nodeData is a list, not an attrset from a node identifier to its data
gen-graph.fromScan: items element 1 has no 'id'
gen-graph.fromScan: scan on the item at position 0 returned a int, not a list of references
gen-graph.fromRegistry: registry is a list, not an attrset from a node identifier to its entry
gen-graph.fields: names element 0 is a int, not an attribute name (a string)
fromScan refuses a malformed parents or nodeData under its own name. An unknown or missing argument (mkGraph { edgs = …; }, fromScan without items) still aborts in Nix's own words, naming the door.
fixtures — pre-built accessor records for common graph shapes:
| Name | Shape |
|---|---|
diamond |
a → b,c → d |
chain |
a → b → c → d |
cyclic |
a → b → c → a |
tree |
parent chain: grandchild → child1 → root |
attributed |
two sources, reconvergent sinks; typed nodeData |
disconnected |
a → b plus isolated island node |
An evaluating substrate hands out its structural attributes as id → { name → value } — an
attribute-name-indexed record, which is not even the arity of an edge set. mkEndpointProjection
is the projection that reads it as one, id → [id], so an accessor-shaped edges can be built from
a substrate that never had one.
structuralEdges = graph.mkEndpointProjection (name: name == "children" || name == "derived-children") (t: builtins.elem t ev.allNodeIds) ev.structuralAttributes;
structuralEdges "a" # => [ "b" "a-spawned" "c" ]| Export | Signature |
|---|---|
mkEndpointProjection |
{ childBearing, isNode } -> (id -> structuralRecord) -> id -> [id] |
mkProjectionFindings |
{ childBearing, isNode } -> (id -> structuralRecord) -> id -> [string] |
The two parameters are injected, not derived. childBearing decides which attributes hold an
attrset keyed by child node id (endpoints = its keys) rather than a list of node references
(endpoints = itself); isNode is the membership authority. Both are facts about an evaluated
substrate, and this library has no evaluator — its only input is gen-prelude. A constructor taking
them as parameters mints its answer inside the caller's own evaluation, which is what keeps the
dependency edge pointing at this library rather than away from it. A private copy of the
child-bearing names here would be correct only for as long as someone kept the two copies in step,
and the failure when they stop agreeing is silent.
The result is a SET. A relational projection is set-valued, so prelude.unique is part of the
definition rather than a tidy-up: the same target reached under two labels, or a child that is also
an imports target, contributes one element. That is the set-of-targets contract forgetLabels and
mkGraph already state.
The codomain contract is checked here, and only on the non-child-bearing family. A construct's codomain contract belongs at its construction site; a consumer-site check guards a path, not a construct. Child-bearing attributes are contracted by the substrate that built them, so a check there asks a question already answered. Every other structural attribute is the consumer's own equation: it must evaluate to a list of ids, each a member of the evaluated node set, and is refused by name otherwise.
The refusal is staged, and the order is load-bearing. The whole value is tested with isList
before anything is mapped, each element with isString before it is interpolated, and only then is
membership asked. Naming a non-string offender in a message interpolates it, and interpolating a
non-string is a coercion error rather than a throw — uncatchable, so a check written the other
way round converts a silent defect into an abort no oracle can observe. Each stage therefore names
only what it can legitimately name: shape refusals name the reading node, the attribute, and
type-and-position; only the membership refusal names an id.
mkProjectionFindings runs the same three tests and returns their messages as a list, [ ]
when the node's governed attributes are clean. Nothing on the production path forces it. Assert on
this returned message rather than on a caught throw — a caught throw proves only that something
refused, never that it refused for the reason under test.
Membership is a claim about the whole graph, so reading the projection forces the node set, and one broken structural equation anywhere refuses every projection read. That is the intended direction of failure: a projection that answered while its authority was unavailable would assert a membership it could not verify.
Where fromScan derives an edge set from values, some consumers declare theirs: they hand
the substrate a dependency relation they wrote by hand. Three things about such a value are facts
about the whole evaluation and cannot be recovered later — what it is (a relation, never a function
of one), what its endpoints are (references the substrate minted, never strings a caller assembled),
and when it is fixed (before the evaluation it orders exists). mkDeclaredEdges is where all three
are settled, at construction, because a construct's contract belongs at its construction site.
ref = graph.mkNodeRef (id: builtins.elem id declaredNodeOrder);
declared = graph.mkDeclaredEdges {
child = [ (ref "parent") (ref "sibling") ];
};
declared.dependencies "child" # => [ "parent" "sibling" ]
builtins.attrNames declared.index # => [ "child" ]
graph.isDeclaredEdges declared # => true| Export | Signature |
|---|---|
mkNodeRef |
{ isRegistered } -> id -> <nodeRef> |
mkSpawnedNodeRef |
id -> <nodeRef> |
isNodeRef |
a -> bool |
refName |
<nodeRef> -> string |
nodeRefFindings |
{ isRegistered } -> id -> [string] |
mkDeclaredEdges |
relation -> <declaredEdges> |
declaredEdgesFindings |
relation -> [string] |
isDeclaredEdges |
a -> bool |
An endpoint is a tagged reference, and that is a convention rather than a capability. A node
reference is { _type = "gen-graph/node-ref"; id = <identifier>; }, built only by the two
constructors above; isNodeRef asks whether a value carries the tag. That refuses by name every
accidental construction — a raw string endpoint, a typo, an id computed from something, a value
carried in from another graph — which is the whole of the defect class that occurs in practice. It
does not refuse deliberate circumvention: an author who writes the tagged record out by hand
defeats it, and that is out of threat model rather than overlooked, since nothing here needs
cryptographic integrity, only distinctness. This is the mkOverride-class convention, and the
refusal names the constructor — "was not built by mkNodeRef" — rather than the shape.
id is an identifier, not necessarily an identity, so nothing in this vocabulary depends on a
mint. refName is the only route from a reference to a string; every attrset key, membership
comparison and message fragment goes through it.
Two construction routes, disjoint and jointly total. mkNodeRef is the author-written route
and validates at construction against the registration set — the declared vertex order, which is
fixed before any equation runs — so a reference it admits is a node the evaluator will have.
mkSpawnedNodeRef is the substrate-minted route, for a node created after the registration set
was fixed; no author writes it, so no membership check is owed or possible. Its stringness check is
not a weakened membership check: it is what keeps refName's codomain a string.
The entry is an accept-list, not a deny-list — one conjunct per declared form. A list
relation must have every element { from = <nodeRef>; to = <nodeRef>; }; an attrset relation
must have every value a list and every element of it a <nodeRef>; anything else is refused naming
the conjunct that failed. Nothing is refused by enumerating what it is. That matters concretely: a
__functor attrset is the edge set being a function while builtins.isFunction reads false
for it, so a deny-list asking "is this a function?" admits it and awards every node the maximal
claim silently. Fields beyond the pair are admitted and ignored — fromScan builds its own edge
records with four fields, so an extended record is the normal case here.
The force is builtins.deepSeq and the depth is part of the contract. It is applied to the
relation, and to nothing else, before anything downstream exists. Under it a relation that reaches
back into the evaluation it orders cannot be produced: the force demands the value and every
sub-value transitively, the value demands the evaluation, the evaluation demands the force. That
failure is infinite recursion encountered — a divergence tryEval does not contain — so what is
assertable is the depth rather than the knot. A WHNF force satisfies every other word of this
paragraph and leaves the knot writable; so does the interposed per-value force a reader cannot
distinguish by reading the input type alone. The cost is an eager O(|E|) traversal of the declared
relation at construction, paid once, unconditionally.
The normalization is part of the definition. A list relation becomes the attrset index the
published relation reads: groupBy on the source's name, each group mapped to its targets'
names. Duplicate sources accumulate — a listToAttrs-based derivation keeps the first
binding for a repeated key and drops the rest with no signal, which is under-declaration by another
route. Repeated identical edges are not deduplicated; that is left to the consumer, which is the
opposite of the choice mkGraph makes for its own index.
isDeclaredEdges is nominal, not structural, and that is the point. A contract enforced only
inside the fold that reads the relation is bypassed by any caller who hand-assembles the context,
and callers do exactly that. So the contract lives at a constructor and the type is what an entry
point accepts in place of a bare attrset: a hand-assembled value carrying an index and a
dependencies has the right shape, no tag, and is precisely the bypass. A consumer states its own
refusal, naming its own entry point.
declaredEdgesFindings and nodeRefFindings run the same checks and return their messages as a
list, [ ] when clean — the same dual-surface convention mkProjectionFindings follows next door.
Assert on the returned message rather than on a caught throw.
The label-blind surface above (edges : id → [id]) is untouched. A graph whose edges carry a
kind is written as a labeled record, { labeledEdges; nodes; }, by hand, as data:
labeledEdges : id → [ { label; target; } ]
nodes : [ id ]
g = {
nodes = [ "root" "h1" "u1" "g1" ];
labeledEdges = id:
map (target: { label = "contains"; inherit target; }) (containsEdges id)
++ map (target: { label = "member"; inherit target; }) (memberEdges id);
};This library does not resolve over it. Resolution — reachability under a label expression,
witness paths, visibility under a label order, boundary marks — is gen-scope's one calculus,
resolve, over an evaluated scope: one calculus, owned by the library that evaluates. query, regex, labeledFrom and
boundedBy are tombstones that refuse by name and say what replaced them; series, layers,
fixpoint, queryFold, queryArrivals and the rank helpers had no caller and are gone. What
stays here is classical, and each surface is node-set-total, which is why nodes is part of
the record: an accessor's domain is not enumerable, so a node set cannot be recovered from
labeledEdges afterwards.
forgetLabels g is the one published bridge, labeledGraph → { edges; nodes; }. Every
global surface composes with a labeled record through it and only through it. Parallel edges
differing only in label collapse, because the plain accessor is a set of targets — the same
contract mkGraph states.
graph.condensation (graph.forgetLabels g) # SCC partition of a labeled recordlabeledTranspose g reverses every edge and carries its label.
(graph.labeledTranspose g).labeledEdges "u1"
# → [ { label = "contains"; target = "h1"; } ] who points at u1, and by which kindMokhov 2017 §5.2's law is that transpose flips the arguments of connect and leaves
overlay unchanged: direction is reversed, not erased. Going through forgetLabels to
reach the plain transpose erases the labels, which is why this is not sugar for that
composition. It is Θ(n + E) — one accessor pass, one groupBy, shared by every lookup and not
forced at all if the transposed record is never read — and it is expressible only because
nodes is part of the record: reversal asks who points at a node, which an accessor's
non-enumerable domain cannot answer alone.
cyclicEdgesWhere p g — the edges whose label satisfies p and which lie on a
cycle, as [ { from; label; to; } ] sorted by (from, label, to). Empty means no cycle of
this graph carries such an edge. It completes the family cycles (which nodes) and
cyclePaths (which walk) with which edges satisfying p.
graph.cyclicEdgesWhere (l: l == "neg") g
# → [ ] , or e.g. [ { from = "c"; label = "neg"; to = "a"; } ]The construction is the composition the total record exists for: forget the labels, partition the projection into strongly connected components, then join back onto the retained labelled edges — two endpoints in one component are mutually reachable, so the edge between them closes a cycle, and a self-loop is one already. That decomposition is ABW 1988's own proof method for Lemma 1's converse, not a construction that agrees with it. The predicate is the caller's: this library is label-agnostic and does not know which labels are special, so it answers about the graph and leaves the meaning of an empty answer to whoever supplied the predicate.
The accessor's result is checked where it is read. A surface that applies labeledEdges
refuses, by its own name and catchably, a result that is not a list, an element that is not an
edge, and a label or target that is not a string — at the read, never before: a surface that
reads no target (cyclicEdgesWhere under a p that is never true) does not refuse a datum
target a caller lawfully hangs on a node.
key is the module every door in this library forms attribute names and refusals with, published
unapplied so another library binds the same module under its own name: key "gen-scope"
renders every refusal as gen-scope.<door>: …, and gen-graph's own doors apply it as
key "gen-graph". It is one module bound twice, not a second key former.
k = graph.key "my-lib";
k.attrKey "lookup" "web" # → "web"
k.attrKey "lookup" 1 # refuses: my-lib.lookup: got int, expected a node identifier (a string)
k.keyedAttrs "index" [ "a" "b" ] (n: n + "!") # → { a = "a!"; b = "b!"; }A key is a FORMER, not an identity. attrKey who k is the identifier's text with its store
context discarded — the partition == already induces, so two names key alike exactly when they
compare equal. Nothing is hashed and nothing new is named: a binding keyed here carries the
caller's original value, context included, and the key only indexes it. This is gen-prelude
unique's keying, for the same reason: Nix refuses a string with context as an attribute name,
uncatchably, while == and genericClosure keys ignore context, so keying the raw name would
abort on a name the rest of the library accepts. A non-string is refused by the door's name
rather than coerced (unsafeDiscardStringContext would turn an outPath set into its string).
The bindings, each taking the calling door's name who first:
| binding | what it is |
|---|---|
attrKey who k |
the key of a node identifier (a string), context discarded; a non-string is refused |
keyedAttrs who names f |
genAttrs keyed by text; f receives the original name |
identifier who v |
v if it is a string, else the named refusal (a door that keys its id) |
nodeKey who v |
v if it is a scalar, else refused (a door whose closure keys on toJSON, not the raw id) |
notAnIdentifier who v |
the refusal text for a non-string id: names the type, never the value |
renderId id |
an id for a message: JSON for a string, <a type> otherwise, so a refusal cannot abort while rendering |
say who text, within door prim |
render <prefix>.<door>: text; through within, a shared primitive reached from another door refuses as <prefix>.<door>: … (in <prim>) |
callable v, callableAt surface name want f |
what Nix can apply (gen-prelude isApplicable); the door that returns it or refuses it by name, throwing notA surface name "a function returning ${want}" f |
kindOf v |
a refused value's kind (gen-prelude applicableKindOf, naming the bound where the walk exhausted it) |
badResult, notA, notEdgeList |
refusal texts for a caller function's result, a caller field, and an edges result of the wrong type |
edgesAccessor who f |
the edges accessor, or its refusal |
{ gen-graph }:
let
graph = gen-graph.lib;
# Your data
services = {
web = { deps = [ "api" ]; type = "frontend"; };
api = { deps = [ "db" "cache" ]; type = "backend"; };
worker = { deps = [ "db" "queue" ]; type = "backend"; };
db = { deps = []; type = "datastore"; };
cache = { deps = []; type = "datastore"; };
queue = { deps = []; type = "datastore"; };
};
# Accessor record
g = {
edges = id: services.${id}.deps or [];
parent = _: null;
nodes = builtins.attrNames services;
nodeData = id: services.${id};
};
in {
entryPoints = graph.roots g; # [ "web" "worker" ]
datastores = graph.leaves g; # [ "cache" "db" "queue" ]
webDeps = graph.reachableFrom g "web"; # [ "api" "cache" "db" ]
dbImpact = graph.dependents { } g "db"; # [ "api" "web" "worker" ]
backendNodes = graph.select g (d: d.type == "backend"); # [ "api" "worker" ]
hasCycles = graph.cycles g != []; # false
}| Operation | Complexity | Notes |
|---|---|---|
reachableFrom |
Θ(Σ_{u ∈ reach s} (1 + outdeg u)) — i.e. O(reachable) only where out-degree is bounded; Θ(n²) on a complete DAG |
C-level BFS via builtins.genericClosure. The per-visit cost is O(1 + outdeg), not O(1), because the genericClosure operator re-reads edges at every visit |
reachableWhere |
exactly the reachableFrom cost above — O(reachable) only at bounded out-degree, Θ(n²) on a complete DAG |
same C-level BFS, filter applied after |
canReach |
Θ(Σ_{u ∈ visited} (1 + outdeg u)) from the source s, where visited is reach s less the nodes the target dominates — same operator, same per-visit cost, over fewer visits. O(reachable) only at bounded out-degree and Θ(n²) on a complete DAG |
C-level BFS that stops expanding at the target; the target still enters the closure, so the answer is unchanged. ★ Scoped: Θ(n) → Θ(1) on a one-hop chain query, unchanged on a complete digraph where the target dominates nothing. Measured as a pair against the full walk in ci/bench/canreach-exit.nix; the exit costs one key comparison per visit, which is what the far/miss cells price |
selfReachable |
Θ(Σ_{u ∈ reach v} (1 + outdeg u)) from the node v — same operator, same per-visit cost, so O(reachable) only at bounded out-degree and Θ(n²) on a complete DAG |
C-level BFS checking self-reappearance |
hoistEdges |
Θ(n) spine, paid once and eagerly; then Θ(1 + outdeg u) per node on first lookup, so Θ(n + E) only if every node is looked up |
builds a builtins.listToAttrs spine over nodes whose values are unforced thunks — a node's edges call and its wrapping happen when the traversal first reaches it, never for a node it does not. This is the whole out-degree factor of the three rows above, lifted out of the per-visit path and charged per node instead |
reachableVia / selfReachableVia |
Θ(|reach s|) attrsets per traversal, on top of the one hoistEdges charge — so k traversals over one accessor cost Θ(n + E) + Θ(k · |reach|) where the unhoisted pair cost Θ(k · Σ (1 + outdeg)) |
the same two closures with the wrapping hoisted. ★ Worth it only for large k: at k = 1 the caller still pays the whole Θ(n) spine while the traversal reads only the nodes it reaches, so a single-traversal caller is strictly worse off — measured on dependentsOf's row below, where the penalty is 2–3 allocations per node, flat in n on every shape, and is not the unread edges |
ancestorsOf |
Θ(depth): one closure element per ancestor, no per-step copy | |
foldPreorder / expandPreorder / foldReach |
Θ(n + m) steps plus the caller's expand work; Θ(n log(n/32)) values copied into the visited set; peak memory grows with the values copied (lib/preorder.nix's header; oracle ./ci/bench/walks-cost.sh) |
|
pathsBetween |
O(paths × depth) | exponential in path count; use on small subgraphs |
materialize |
O(nodes × avg degree) | one-time scan |
transitiveClosure |
closure class (see below) | fixpoint over materialized map |
transitiveReduction |
closure class unless every node has out-degree ≤ 1 (see below) | needs full closure; O(1) membership via attrsets |
cycles |
Θ((n + m) · log₈ n) through the lowlink arm, plus one accessor read per node for the self-loop test. nrFunctionCalls on cycle n = 1000 → 20000: 427,092 → 10,180,104 (span exponent 1.06), flat as calls / (n · ⌈log₈ n⌉) in 101.8–106.8; nrOpUpdateValuesCopied flat at 125. The per-node self-reachability it replaced was Θ(Σ_v |reach⁺ v|): 3,021,018 → 12,042,018 → 48,084,018 at 1000 → 2000 → 4000 (×3.99 per doubling) |
read off the SCC partition (Tarjan 1972, Lemma 9): a node is cyclic iff its class has two or more members or it has a self-loop. Binds lowlink by name. Arm cycles; arm cyclesUnhoisted is the pre-hoist per-node construction |
cyclePaths |
Θ((n + m) · log₈ n) on every graph, cyclic or not: the cycles term above plus one iterated search per cyclic component, Θ((|C| + m_C) · log₈ |C|). nrFunctionCalls n = 1000 → 20000: cycle 612,962 → 14,679,943 (calls / (n · ⌈log₈ n⌉) in 146.8–153.2), rand 555,390 → 11,910,930 (119.1–151.8); nrOpUpdateValuesCopied flat at 125. The pathsBetween reconstruction it replaced copied Θ(L²), refused a 4,000-member ring at its depth cap, and was exponential on rand (47,958 calls at n = 25, 148,006,257 at n = 50) |
the witness is the first simple path in edges order, found by a depth-first search with a global visited set restricted to the component — the path pathsBetween enumerates first. Arm cyclePaths; arm cyclePathsUnhoisted is the pre-hoist construction, pathsBetween included |
cyclicEdgesWhere |
Θ((n + m) · log₈ n) through the lowlink partition arm, plus one pass over the labelled edges. nrFunctionCalls with p accepting every edge, n = 1000 → 20000: cycle 451,095 → 10,660,107, chain 446,045 → 10,560,053, rand 550,845 → 12,863,196 — span exponents 1.06 / 1.06 / 1.05, ×2.00 per doubling inside one trie depth and ×2.36 on the doubling that adds a level; nrOpUpdateValuesCopied flat at 127. Bound to fbNode the cycle cells read 10,096,051 → 40,192,051 → 160,384,051 at n = 1000 / 2000 / 4000. p on one edge of a 5000-node cycle: 2,605,120 against fbNode's 420,104; p never true: 50,021 on both (arms cyclicEdgesWhere / …One / …None) |
the p test short-circuits, so no p-edge forces no tag; the first tag read forces the whole partition. That trade — a constant factor on a sparse p for a class bound on every p — is the choice: fbNode's per-endpoint cost depends on reach, so no threshold on the number of p-edges bounds it, and routing on that count inside the binder would be a second default beside the door's. A target outside nodes is refused by name |
dependents |
closure class (see below) | full transitive closure + transpose |
dependentsOf |
Θ(n + E) for the reverse index, then Θ(Σ_{u ∈ reach⁻ t} (1 + indeg u)) for the walk — i.e. O(reachable) only where in-degree is bounded; Θ(n²) on a complete DAG |
reverse index + C-level BFS. The walk is the reachableFrom operator run over the reversed index, so its per-visit factor is the forward in-degree. ★ It does not hoist the accessor: one closure has no second traversal to spread the wrap's Θ(n) spine over, and that spine is built whether or not the walk reaches the node. Measured worse hoisted on every shape — 1.003× on complete, 1.32× on cycle, 1.35× on chain, 1.41× on fleet. The margin is 3n + 1 on chain/fleet, 3n on cycle and 2n + 2 on complete — exact at every n measured: 2–3 allocations per node, flat in n on every shape and independent of E, which is what says it is the spine and not the unread edges — on complete nothing is unreached at all and the margin is still 2n + 2. Arms dependentsOf / dependentsOfHoisted |
dependentsFrontier |
the row above restricted to what prune admits, and nothing else: Θ(n + E) for the reverse index, then Θ(Σ_{u ∈ expanded} (1 + indeg u)) for the walk — a pruned node is reached without paying its in-degree. One term, no accumulator term, so at prune = _: true it is dependentsOf's law and not merely bounded by it |
reverse index + C-level BFS with the prune moved into the operator. ★ Inclusion and expansion are two separate moments in genericClosure — a node enters the closure when its PARENT emits it and the operator runs on it only afterwards — so an operator returning [ ] includes a pruned node without expanding it, and the early cutoff needs neither a level walk nor a visited attrset; the C-level done set is the cycle guard. Measured on chain (in-degree exactly 1, so nothing here is an in-degree effect), n = 100 → 800: sets exponent 1.80 → 0.89 net of the fixture floor and nrOpUpdateValuesCopied 40,508 → flat 110, landing on the dependentsOf control within one attrset at every n with list bit-identical to it. Arms dependentsFrontier / dependentsFrontierPruned, paired with dependentsOf on the same shape and n |
coScc |
the canReach cost paid from each of u and v, each probe over its own start's reachable set less what its own target dominates — O(reachable) only at bounded out-degree, Θ(n²) on a complete DAG. ★ This is the CALLER's figure, not the library's: it is derived from canReach's operator law above, and no bench arm measures it |
two canReach probes, each stopping at its own target — two closures, so what is avoided is the whole-graph transitive closure and each probe's dominated remainder, not the rest of the per-probe one. ★ Export-only — nothing in lib/ pays this. The condensationClosure arm decides co-SCC from its own closure rather than through this name, and coScc is in turn canReach's only caller in lib/, so the two probes sit off every internal cost path. What a caller pays scales with its own pair count, since each pair re-materializes both closures |
fbNode |
quadratic in the members of ONE component and linear in components: list/sets/nrLookups exponents 2.00 on cycle, 1.00–1.04 on fleet, ~1.98 on chain (n = 500 → 2000) — all three re-derived and unmoved by the accessor hoist, which changes the DENSE reading those shapes cannot see: on complete (n = 200 → 400) sets runs 2.98 → 2.00, 62.2× fewer attrsets at n = 400. ★ list there now drops the same full exponent, 2.97 → 2.00, where it once stayed cubic at 2.86 under the hoist. The residue that kept it there was the foldl'-with-elem dedup edge-maps.materialize called per node, and it left with the gen-prelude dedup bump; it was not prelude.concatMap's ++ inside the shared finisher, which an earlier reading of this row named and which is builtins.concatMap |
two genericClosure calls per node, no accumulator, no recursion. 2n closures over two accessors, so it binds hoistEdges on each and the operator no longer re-reads edges per visit. No closure call and no fixpoint, so no iteration cap to inherit. Arms fbNode / fbNodeUnhoisted. Ceilings and the arm comparison: The partition routing contract above |
fbWork |
linear on one large component on every axis — calls 1.00 and nrOpUpdateValuesCopied flat at 127 on cycle, n = 5000 → 20000. Quadratic in copies on many components, whatever the node order: its accumulator copies the whole tag map once per component, so copied reads 2.00 on fleet over the same n while calls read 1.03, and sets runs 1.35 → 1.53 on fleet (500 → 2000). Quadratic in calls as well where the backward walk re-covers the unassigned tail every round — chain, 1.99 on calls and 2.00 on copied over 2000 → 4000 |
one forward–backward pass per COMPONENT over a foldl' accumulator. Complementary to fbNode, not ranked. ★ It does NOT hoist its accessor, though it makes many closures: hoisting builds a whole-graph Θ(n) memo up front, and this arm's closures partition the graph rather than re-covering it — each round walks a subgraph the earlier rounds have shrunk — so there is no second traversal over the same edges to spread that build cost over. Same mechanism as dependentsOf's negative cell below. Measured 4.12× better on one deep chain (the one shape whose backward walk re-covers the whole unassigned tail every round) and 1.003–1.25× worse on complete, fleet, wide, total and cycle, the decisive losses being cycle (1.243×) and complete's nrLookups (1.397×). ★ Restriction ordering is not the lever, measured: an arm memoizing plain adjacency and restricting before wrapping recovers none of it — worst of three on fleet, and within 4 sets of the full hoist on cycle while both memoizing arms sit ~2,400 above the shipped one. Arms fbWork / fbWorkHoisted |
condensation / lowlink |
Θ((n + m) · log₈ n) on every shape, the log being its persistent trie's. nrFunctionCalls n = 1000 → 20000: cycle 433,180 → 10,300,192, chain 548,039 → 12,600,049, rand 508,180 → 12,320,786 — span exponents 1.06 / 1.05 / 1.06, and flat as calls / (n · ⌈log₈ n⌉): 108 at n = 1000–4000 and 103 at 8000–20000 on cycle. The finisher's domain check is in these figures, about 7n calls. list.elements span exponents 1.07 / 1.07 / 1.08. nrOpUpdateValuesCopied flat at 125 on cycle and chain; on rand it rises with the component count (125 → 2,175), and that is the shared finisher's term, not the arm's: fbNode reads the identical 1,053 and 2,139 at n = 2000 and 4000 |
one genericClosure loop, one step per push, edge, finished frame or popped member; every record the loop carries is built by a constructor that forces each field |
condensationClosure |
closure class (see below) | one transitive closure. The second closure over the quotient is gone — every arm now takes its bottomUp and depth from one coneRank pass over the condensation instead, which is topoOrderKahn-warmed and reaches no fixpoint |
coneRank |
O(|cone| + edges-in-cone) for the recurrence, plus one ordering pass — list exponent 1.07 on chain and fleet, sets 1.00–1.02, nrLookups 1.00–1.06 (n = 1000 → 8000) |
lib.fix memoized depth, cone-local (no condensation), warmed along topoOrderKahn's order. No ceiling found to 32,000 on chain or deepwide; a cyclic cone is a named refusal. The construction it replaced is linear on all three axes and aborts past ~4,000 on chain — ci/bench/cost-classes.nix, arms coneRank / coneRankShipped |
topoOrder / phaseOrder |
O(n + E) decrements through the Kahn arm, and near-linear in allocation — exponent 1.07–1.08 on list.elements and 0.99–1.12 on sets.elements, all four acyclic shapes, read on arm topoOrderKahn. ★ Through the DOOR a shape the certificate admits is cheaper by a class of construction rather than a constant — 18n on a chain against the loop's 1.07 exponent, 2.010 list/edge against 10.042 on the dense total order — and a shape it refuses is the loop plus 2n − 1. The ok = false cycle report runs the lowlink arm twice (once through cycles, once for sccOf), Θ((n + m) · log₈ n): on cycle 889,195 → 21,060,219 nrFunctionCalls at n = 1000 → 20000, calls / (n · ⌈log₈ n⌉) in 210.6–222.3; the per-node guard it replaced read 3,476,115 → 12,952,115 → 49,904,115 at 1000 → 2000 → 4000 |
nothing the loop carries is quadratic: the emitted sequence is a binary-counter run list (Θ(n log n)), the indegree map is a residue over a rebuilt base, and the ready set is a leftist heap (Θ(n log n)), where a re-sorted array was a third quadratic worth 60% of the wide list allocation. The heap's sets.elements price, 63 → 89 attrsets per node over n = 1000 → 8000, is now the leading set-axis term. No frame ceiling — the loop is a bounded iteration, so no node count aborts or is refused |
directDependents / directDependentsOf |
Θ(n + E) |
one groupBy reverse-adjacency map — this is _reverseIndex, whose concatMap visits every node, so a node with no out-edges still costs its visit |
seededFixpoint |
O(work per delta), plus one full step at convergence | semi-naive: each iteration touches only the frontier. The support check re-derives once from the converged accumulator, and what dilutes it is ROUND COUNT, not size — the loop's per-round unions and differences dominate only when there are many rounds. Deep instance, 400-node chain at ~399 rounds: 45,307,630 → 45,637,203 thunks, +0.73%; cpuTime 25.3–29.2s against 28.2–30.2s over three runs a side, which OVERLAPS, so the thunk count resolves it and the wall clock does not. Shallow instance, diameter-2 at 2 rounds: +30% to +37%, and the ratio holds across a 4× size change (402 and 1,602 nodes), which is what identifies the axis. A caller on a shallow dependency graph pays the high end |
roots / leaves |
O(nodes × avg degree) | single scan of all edges |
select |
O(nodes) | one pass over node list |
unionEdges / intersectEdges / differenceEdges |
Θ(keys + entries) over both maps for intersectEdges and differenceEdges; unionEdges adds a per-key Θ(m log m) in that key's combined target count m — Θ(m) on the list axis, the log m being comparisons |
both maps are walked by attrNames, so a key with an empty target list still costs its visit. intersect/difference test membership in an attrset, O(1) per edge; unionEdges instead calls prelude.unique per key, which on a string target domain dedups by sorting first-occurrence indices. ★ The quadratic this row used to name is not gone, it is domain-scoped: prelude.unique keeps the foldl'-with-elem fold as its non-string fallback, so a caller whose targets are not strings still pays Θ(m²). Edge targets are node ids, so the shipped path is the linear one. Measured on one key with m distinct string targets in both maps, m = 250 / 500 / 1,000: 3,007 / 6,007 / 12,007 list elements, exactly 12m + 7, exponent 1.00 — against 126,756 / 503,506 / 2,007,006 and exponent 2.00 before the gen-prelude dedup landed, a factor of 167× at m = 1,000 that doubles with every doubling of m. The set axis takes the other side of that trade: flat at 313 before, 6m + 313 now |
The closure class. transitiveClosure, dependents, condensationClosure and transitiveReduction each cost one fp.closureOf call, and on list.elements they measure as one curve, not four costs. ★ That axis is where the class reads cleanest; it is no longer where the bill is. Before the gen-prelude dedup bump the list term at n = 200 exceeded the other two counters combined by 417× on the complete digraph and 124× on the cycle, and the class was stated on list for that reason. The bump traded the dedup's list allocation for attrsets, and at the same n those ratios are now 0.68× on the complete digraph and 0.69× on the cycle — sets is the larger term on both. The class still reads as one curve on list, and it now reads as one curve on sets as well. On a complete digraph the growth exponent is ~2.95 for all four and the exponents agree to 0.50% (2.947–2.962); the raw figures agree an order closer only for the first three (0.730% apart at n = 200), while transitiveReduction sits 1.09% above transitiveClosure — the 0.50% is a statement about exponents, not about allocation counts. transitiveClosure alone is 99.6% of dependents. On a simple cycle the first three are ~2.93, and their spread narrows with n — 1.651% at n = 50, 0.891% at n = 100, 0.464% at n = 200 — so the class claim strengthens as the graph grows rather than holding at one fixed bound. Spread here is max ÷ min − 1 over the members compared, stated because the figure is meaningless without it. It is super-quadratic on both shapes — not the O(nodes²) once documented here. This is practical scaling guidance, not an identity on every axis — though the axis that used to break the identity no longer does: on sets.elements the complete-digraph exponents once separated, transitiveClosure at 0.74 against 1.93–1.99 for its siblings, and under the dedup bump and the squared schedule all four sit together at 2.972–2.989. What makes it a class is structural rather than measured — all four are fp.closureOf under their own name, from one enumeration (closureClass). The rows above therefore name the class instead of repeating a figure, so the four cannot drift apart into an apparent distinction that does not exist. They share a refusal for the same reason they share a curve: one capped fixpoint, so all four throw the diameter-and-surface message of Fixpoint above at the same ceiling, and a fix applied to one of them would have left three refusing the old way. Re-run: ci/bench/cost-classes.nix, arms transitiveClosure / dependents / condensationClosure / transitiveReduction.
★ These figures were re-derived after condensation LEFT this class, and they are the re-derived ones. condensation is the partition front door and is an unconditional alias for fbNode, the forward–backward arm, which makes no closure call at all; the construction the class describes is published as condensationClosure, which used to make TWO closure calls (the graph, and a second over the quotient) and now makes one. The membership claim never depended on the figures — it is structural, condensationClosure is fp.closureOf "condensationClosure", the one construction its three siblings bind under their own names — but the percentages did, so all four arms were re-run together on one revision of the bench and the paragraph above states that run.
What that re-run moved was confined to the complete digraph, and every cycle figure came through it unmoved. The deltas it was recorded with are not restated here: both of their baselines predate the gen-prelude dedup bump, so neither side is reproducible from any command at this revision, and a figure binds to a command at a rev rather than to a sentence that once carried it. The paragraph above is the reading that replaced them.
The asymmetry that re-run exposed survives the bump, but its mechanism does not. The reason then was an exponent gap between the shapes — the cycle's closure ran at 3.9 and swamped everything downstream of it, where the complete digraph's ran at 3.0 and let the same downstream work show. The bump takes the cycle to ~2.98 against the complete digraph's ~2.96, so there is no exponent gap left to explain anything, and what remains is a much smaller difference in sensitivity: condensationClosure sits 0.314% above transitiveClosure on the cycle against 0.730% on the complete digraph, a ratio of 2.3× between the two shapes where the cycle's own margin used to be 0.014%. A class figure quoted from the cycle is still the more stable number and the less informative one, but it is no longer nearly blind to work after the closure, and a change to that work is now worth looking for on both shapes. Re-run: ci/bench/cost-classes.nix, arms transitiveClosure / condensationClosure, shapes cycle and complete, n = 200.
transitiveReduction is the one partial member, and its carve-out is a property of the whole graph, not of a node. Its closure is a single binding shared by every node, and the only thing that forces it is the closureSets.${mid} lookup sitting behind the mid != to && guard. When every node has out-degree ≤ 1 that guard is false everywhere, the shared binding is never forced, and the call measures linear — 1,803 allocations at n = 200 on the cycle (exponent 1.00 over n = 50 / 100 / 200), against 25,968,807 for the closure on the same graph. But one node with out-degree ≥ 2 anywhere in the graph forces that shared binding, and then the entire call pays closure class: on cyclechord — the same 200-node ring plus a single chord from n00000 to n00100, so exactly one node has out-degree 2 — it reads 29,413,537, a factor of 16,314, landing within 0.0048% of transitiveClosure on that same chorded fixture (29,412,127). ★ The chord is named because "add one edge" does not identify a graph and the choice is worth 13.3%: the closure itself goes from 25,968,807 on the ring to 29,412,127 with the chord in, so a figure quoted for an unnamed edge cannot be reproduced or compared. Re-run: ci/bench/cost-classes.nix, arm transitiveReduction, shapes cycle and cyclechord.
There is no middle reading — an average or typical out-degree of 1 buys nothing, so on any realistic dependency graph or host fleet treat transitiveReduction as closure class. The carve-out covers exactly those graphs in which every node has at most one successor. In-degree is irrelevant to it, so it holds on in-trees and in-stars as well as on disjoint unions of paths and cycles, and fails on anything denser. Re-run: ci/bench/cost-classes.nix, arm transitiveReduction, shape cycle.
★ These are Nix-heap allocation counters and therefore a lower bound, not the bill: genericClosure keeps its done-set in C++, so its key comparisons appear on none of the three axes. Read the figures as a floor.
Lazy traversal (reachableFrom, canReach, ancestorsOf, pathsBetween) visits only what is reachable. Global operations (cycles, dependents, transpose, transitiveClosure, transitiveReduction) scan all nodes.
gen-graph is designed to support large infrastructure graphs (1000+ nodes) without forcing performance regressions onto the underlying evaluator.
All reachability queries use Nix's native builtins.genericClosure — a C-level builtin with built-in dedup. This is ~4-5x faster than equivalent Nix-level BFS on 5000-node graphs:
- No Nix-level queue management (list concatenation is O(n²) for BFS queues)
- Native hash-based dedup (not attrset
//per visited node) - Constant-factor advantage of compiled C vs interpreted Nix
When gen-graph's accessor functions are wired to gen-scope's result.get id "imports":
- Each
edges idcall hits gen-scope's memoized_eval→ O(1) after first evaluation - Traversal operations only trigger attribute evaluation for VISITED nodes
- Global operations trigger evaluation for ALL nodes, but each evaluates exactly once
This means gen-graph never causes redundant evaluation in gen-scope. The accessor pattern is the zero-cost bridge:
# gen-scope evaluates each node's imports ONCE; gen-graph reads the cached result
genGraph.reachableFrom { edges = id: result.get id "imports"; } "host:igloo"| Need | Use | Don't use |
|---|---|---|
| "Can A reach B?" | canReach (stops expanding at the target; O(reachable) at bounded out-degree, Θ(n²) on a dense graph — see Performance) |
dependents (closure class) |
| "What depends on X?" (one target) | dependentsOf (reverse index, then O(reachable) at bounded in-degree, Θ(n²) on a dense graph — see Performance) |
dependents (closure class) |
| "What depends on X, Y, Z?" (multi-target) | map (dependentsOf g) [ X Y Z ] (one reverse index for every target, then the walks) |
map (t: dependentsOf g t) … (rebuilds the index per target); dependents (closure class) |
| "Is there a cycle?" | cycles (C-level; O(n × reachable) at bounded out-degree, Θ(n²) on a dense graph — see Performance) |
transitiveClosure (closure class) |
| "Which loop, in order, for a message?" | cyclePaths (Θ((n + m) · log₈ n)) |
hand-rolled DFS per node (enumerates every simple path even when acyclic) |
| "All paths between A and B" | pathsBetween (DFS) |
Only for small subgraphs |
| "Full closure for analysis" | transitiveClosure |
— (use when you genuinely need it) |
| "Minimal graph for diagrams" | transitiveReduction |
— (closure class unless every node has out-degree ≤ 1) |
For 10,000+ node fleets, partition the graph by environment/datacenter before running global operations:
# Instead of:
graph.cycles { edges; nodes = ALL_10K_NODES; } # O(10K × reachable) at bounded out-degree; Θ(n²) dense
# Partition first:
lib.concatMap (partition:
graph.cycles { inherit edges; nodes = partition; }
) (partitionByEnvironment allNodes) # 20 × O(500 × reachable) — and 20 × Θ((n/20)³) denseCross-partition edges are rare in practice. The speed-up is shape-dependent: splitting into k partitions divides the cycles term by k where out-degree is bounded and by k² on a complete DAG, so k = 20 predicts roughly 20× at the bounded end and 400× at the dense end. Those follow from the cost model above rather than from a benchmark — measure your own shape instead of assuming the top of the range.
Two test outputs, and both need running.
nix develop ./ci --command ci # cells asserting a VALUE, guarded
nix develop ./ci --command ci --tests-error # cells asserting an ERROR, guarded
nix-unit --flake ./ci#tests # cells asserting a VALUE; unguarded
nix-unit --flake ./ci#testsError # cells asserting an ERROR (nix-unit `expectedError`); unguarded
nix flake check ./ci # the batch gate, which covers ./ci#tests; unguardedci refuses when anything under a declared read root is unknown to git — any extension or name,
_-prefixed included — and the remedy is git add or a move. The unguarded forms read a
git-filtered copy of the tree, so an untracked cell is silently absent and the run stays green.
655 tests across 38 suites in ./ci#tests
(nix-unit --flake ./ci#tests ⇒ 655/655 successful) (arms, caller-functions,
caller-results, closure-targets, construction, context-node-names,
declared-edges, doors, edge-maps, edges-results, endpoints, entry, enumerate,
fixpoint-tests, gen-ci-examples, global, hoist, identifier-doors, integration,
key-former, labeled-door,
labeled-global, labeled-transpose, order, order-contract-fence, order-front-door,
p2-doors, partition,
prelude-domain, preorder, purity, registry, repl, scan,
surface, topo, traverse, walks),
plus 390 in ./ci#testsError (nix-unit --flake ./ci#testsError ⇒ 390/390 successful)
— run under nix-unit via
the gen CI harness (gen.lib.mkCi). The purity suite asserts the library source stays
nixpkgs-lib-free (gen-prelude only). gen-ci-examples is gen-harness's examples guard
(declared in ci/tests/examples.nix, gen.ci.examples): it holds that examples/
directory names equal the declared names, and that every declared example forces under
deepSeq.
Why two outputs. checks.default is a batch asserter that evaluates expr == expected
unconditionally over flake.tests and nothing else, so a cell with no expected and a
throwing expr crashes that gate rather than failing a case. Cells whose subject IS the
error therefore live on flake.testsError (ci/tests-error.nix, outside the ./ci/tests
tree by construction) — out of the asserter's quantifier and still under nix-unit, which
does read expectedError. Both outputs carry a pre-commit hook: ci and ci-error.
The algorithms and design principles draw from the entries below. The resolution calculus's sources — Brzozowski 1964, Owens, Reppy & Turon 2009, Néron et al. 2015's label order and van Antwerpen et al. 2018 — left with it for gen-scope.
- Mokhov (2017) — Algebraic Graphs with Class. Informed by. Algebraic graph construction primitives (overlay, connect, vertex, empty) and the compositional approach to graph representation inform gen-graph's edge map operations and structural combinators. Edge map set operations (
unionEdges,intersectEdges,differenceEdges) are gen-graph's own contribution built on this algebraic foundation. Mokhov 2017 §4.5 supplies only the equivalence-class notion of reduction;transitiveReductionis a standard DAG transitive-reduction algorithm (gen-graph's own implementation) and assumes a DAG, since reduction is not unique under cycles. Transpose follows Mokhov 2017 §5.2 Graph Transpose directly: the law is that transpose flips the arguments ofconnectand leavesoverlayunchanged, so direction is reversed rather than erased.condensation's quotient-graph idiom is §4.6 Preorders and Equivalence Relations — a condensation is the quotient by the co-SCC equivalence. - Arntzenius & Krishnaswami (2016) — Datafun: A Functional Datalog. Implements — Lemma 4, and that is the whole of the claim. Lemma 4 (Fixed points in finite-height pointed posets): any monotone map
f : P → Pon a poset of finite height with a least elementεhas a least fixed point of the formfⁿ(ε); the proof is that the iterates ascend and a chain in a finite-height poset cannot be infinite. gen-graph's ascent qualifies because the edge set over a finite node set is finite. Thefixpointoperator's ascent check (the step must not withdraw an edge the accumulator already held — containment of edge content, which is the orderunionEdgesjoins on and therefore the poset Lemma 4 takes its chain over, rather than edge count) matches Datafun's requirement that fixpoint computations operate over monotone functions on semilattices — but it is a step check, not a convergence guarantee, and the paper is explicit that monotonicity "is not sufficient by itself to guarantee termination" (pp. 11–12). Finiteness is what terminates it. ★ Withdrawn as unsupported at the primary: reverse reachability independents/dependentsOfdoes not follow a "Datafun reverse-query pattern" — reverse occurs 0 times in the paper — andseededFixpointis not Datafun's semi-naive evaluation either (seeAGENTS.mdfor the measurements and their controls). Both are gen-graph's own; the reverse operators are described on their own terms inlib/global.nix.directDependents/directDependentsOfexpose the underlying reverse-adjacency index directly: the immediate reverse neighbours (one edge), in contrast todependentsOf's transitive reverse closure — the distinction matters when a consumer must enumerate only its direct producers' dependents without re-materializing the whole reverse cone. - Tarjan (1983) — Data Structures and Network Algorithms (RTD). Cited unverified — the text is UNHELD (paywalled), so nothing below is claimed from it; the reference is kept because the trail matters. The mechanism on its own terms: longest-incoming-path topological rank over a cone —
coneRankassigns each nodedepth = 1 + max(depth of producers), the standard topological-rank recurrence — but restricted to a cone: only producers inside the supplied node set count, so the rank is computed in O(|cone| + edges-in-cone) vialib.fixmemoization rather than over the whole graph. Ordering by ascending depth yields a producers-first (reverse-topological) enumeration without buildingcondensation. The recurrence is memoized, which makes it linear and also made it a descent: forcing the memo map in an unfavourable order walked the cone one evaluator frame per link. The map is therefore forced along a topological order of the cone taken fromtopoOrderKahn, which flattens that descent — the rank recurrence is unchanged, only the order in which its cells are demanded. - Neron et al. (2015) — A Theory of Name Resolution. Implements. Parent-chain traversal (
ancestorsOf) follows scope graph P-edge resolution: walking theparentpartial function upward through scopes corresponds to following P-edges in the resolution calculus (Neron 2015 §2.3). Silent cycle termination chosen over throwing for composability, matching the well-foundedness requirement on the parent relation. - Kahn, A. B. (1962) — Topological sorting of large networks, CACM 5(11). Implemented.
topoOrderKahnis Kahn's algorithm andtopoOrderis the door that selects it (see Ordering): an indegree count over the dependency relation, a ready set of indegree-zero nodes, decrement-on-emit restricted to the pick's successors, and the residual-emptiness check that detects a cycle. Incomparable nodes are emitted in ascending key order, which is what makes the result a function of the node set rather than of the input permutation. This is A. B. Kahn 1962 and not Gilles Kahn 1974 below — a different author and a different result, a conflation this codebase has made before. Min-extraction over the ready set is the one place the algorithm is not linear, and the ready set is a leftist heap (see Crane 1972 / Okasaki 1998 below) — O(log m) insert and delete-min, so the loop attains the Ω(m log m) comparison bound that emitting in min-key order under a caller-supplied comparator inherits. ★ This entry previously recorded that a priority queue was out of reach because pure Nix has no mutable heap. That is false: persistent priority queues need no mutation. The same claim was for a time also whatcondensationClosuregave for not being Tarjan's algorithm, and a later reading replaced mutability with RECURSION as the obstruction. Neither was a bound: Tarjan's DFS is thelowlinkarm, its stack and index map persistent and its recursion stepped by onegenericClosureloop (see Tarjan 1972 below). The cycle report is deliberately not read off the Kahn residual, which knows only that nodes went unemitted and not which cycles they form; it comes fromcyclesand a partition arm (lowlink, bound by name), so the failure path pays both — and neither may be quoted as the cost alone, since which of the two is larger flips with the graph's shape and with the allocation axis measured — while the success path pays neither. - Crane (1972) — Linear Lists and Priority Queues as Balanced Binary Trees; Knuth, TAOCP vol. 3 §5.2.3. Implements.
topoOrder's ready set is a leftist heap:null | { k; l; r; rank; },rankthe right-spine length, with the leftist invariantrank l >= rank rat every node. Merge walks and rebuilds the two right spines, which the invariant keeps at O(log m), and insert and delete-min are both defined as a merge. Immutability is paid in path copying rather than in asymptotics — no node is overwritten, so a merge allocates one attrset per node on the spine it rebuilds, giving Θ(n log n) attrsets over the loop. That is an achieved upper bound, not a proven optimum: the comparison-sorting bound rules out a Θ(n) comparison-based ordering, but it does not prove Θ(n log n) allocations necessary. - Okasaki (1998) — Purely Functional Data Structures, §3.1. Informed by. The book's subject is exactly this substrate restriction: priority queues with O(log n) worst-case merge and delete-min and no mutable store. Leftist heaps are §3.1; skew heaps (Sleator & Tarjan 1986) and pairing heaps (Fredman, Sedgewick, Sleator & Tarjan 1986) are alternatives with the same property. Cited here because "pure Nix cannot express a priority queue" was written into this library as a justification for a quadratic, and it is a false impossibility claim.
- Kahn (1974) — The Semantics of a Simple Language for Parallel Programming. Informed by. Continuous functions over streams with deterministic dataflow semantics. gen-graph's lazy accessor pattern — traversal only forces nodes it visits — aligns conceptually with Kahn's model where computing stations produce output incrementally as input arrives, and monotonicity ensures that receiving more input can only provoke more output (Kahn 1974 §2.2.4). The pre-order combinators (
preorder.nix) make this demand property load-bearing:expandPreorder'sedgesread the resolved payload, so a node's successors are demand-generated, and aseen0-pruned frame is never forced. - Tarjan (1972) — Depth-First Search and Linear Graph Algorithms. Implements. The pre-order traversal combinators (
foldPreorder,expandPreorder,foldReach) fold in DFS pre-order — a frame before its children, siblings in list order, each frame visited once via a first-occurrence visited set. First-occurrence is Tarjan's pre-order discovery numbering;genericClosure(BFS, single-keyed, payload-blind) structurally cannot express the order, payload or edge exposure these carry. Separately, Lemma 9 (p.155) is the definition anchor the SCC-partition sites cite — the strongly connected components as equivalence classes of mutual reachability; the paper does not supply the condensation/quotient construction, which is anchored at Mokhov (2017) §4.6.lowlinkimplements STRONGCONNECT, the SCC procedure of Theorem 13: DFS numbering, the stack of points, and the LOWLINK root test of Lemma 12. It is iterated rather than recursed — onegenericClosurestep per push, edge examined, frame finished or member popped, over a persistent 8-ary trie index — so its cost is Θ((n + m) · log₈ n), not the paper's O(V + E). It departs from the paper in one stated respect: a component is tagged by its smallest member, the library's contract, not by its root. - Bentley & Saxe (1980) — Decomposable Searching Problems I: Static-to-Dynamic Transformation. Implements. The pre-order walks' visited set: membership is a decomposable searching problem, so the static structure (a native attrset) is made dynamic by the logarithmic method — a flat buffer of 32 keys carried into levels of 32·2ⁱ keys as a binary counter — and each key is copied O(log(n/32)) times rather than once per later insert (
lib/preorder.nix,levels). - Meijer, Fokkinga & Paterson (1991) — Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire. Informed by.
foldPreorderhas the shape of a hylomorphism: the visited-set coalgebra unfolds the (possibly cyclic) graph into its finite DFS spanning forest, whichexpandfolds (catamorphism) into the accumulator.expandPreorderandfoldReachspecialize that accumulator to an ordered witness list — an ordered, payload-carrying fold rather than a set-returning closure. - Apt, Blair & Walker (1988) — Towards a Theory of Declarative Knowledge, Lemma 1. Implements — the graph half only. The lemma is a biconditional between a program property and a graph property: no cycle of the dependency graph contains a negative edge.
cyclicEdgesWherecomputes that graph property for a caller-supplied notion of "negative", and the construction is the paper's own proof method for the converse — decompose the dependency graph into strongly connected components (which iscondensation), then read the retained labelled edges against that partition. gen-graph has no programs, no relation symbols and no clauses, and does not know which labels are negative, so it computes the graph side and names it accordingly; the program-level word belongs to a caller that has programs. The archived text carries an OCR hazard inside the converse half of that proof (a flattened inequality), so its prose is cited and no inequality from it is lifted into code, comment or oracle — the stratum-index arithmetic plays no part here, only the decomposition.