Guide/How it works
Canonical Graph Semantics Engine (CGSE)
6 min readFrom the README
On this page 8
CGSE is the project's core correctness mechanism. It treats algorithmic tie-breaking as part of the API contract rather than incidental behavior.
The 13 Tie-Break Policies
CGSE's policy registry names, for each of the 12 V1 reference algorithms (table below), which policy governs its choices when multiple equally-correct answers exist. The kernels implement that order directly — they do not take a policy parameter — and the witness records the registered policy:
pub enum TieBreakPolicy {
LexMin, // lex-min node/edge label
LexMax, // lex-max node/edge label
InsertionOrder, // adjacency-list order
ReverseInsertionOrder, // reverse adjacency-list order
WeightThenLex, // weight ↑ then lex-min label
WeightThenInsertionOrder, // weight ↑ then FIFO insertion (Dijkstra)
LexThenWeight, // lex-min label then weight ↑
DeterministicHash { seed: u64 }, // reproducible but order-agnostic
DegreeMinThenLex, // min-degree node, ties lex-min
DegreeMaxThenLex, // max-degree node, ties lex-min
DfsPreorder, // DFS pre-order
BfsLevelLex, // BFS level, within-level lex-min
EdgeKeyLex, // multigraph edge key lex-min
}
Defined in crates/fnx-cgse/src/lib.rs:37. Each policy has a short stable identifier used in ledger entries and serialized artifacts.
The WeightThenInsertionOrder variant is the one NetworkX actually exhibits in its heap-driven shortest-path algorithms (heapq + itertools.count() as a per-push monotonic counter). fnx's Dijkstra uses the same scheme: a DijkstraState { dist, seq, node } struct whose Ord impl tie-breaks equal-distance entries by the insertion-counter seq. The choice of WeightThenInsertionOrder over WeightThenLex for Dijkstra is intentional: matching NetworkX byte-for-byte beats insertion-order-independent reproducibility for the project's drop-in-compatibility contract. The CGSE V1 registry now records this honestly.
Complexity-class reference
The 10 dominant-term strings recognized by fnx_cgse::analytic_upper_bound(term, n, m). Use them to interpret the dominant_term field of a ComplexityWitness:
| Term | Closed form | Typical algorithms |
|---|---|---|
n |
n |
degree_centrality, is_isolate, single-node lookups |
m |
m |
eulerian_circuit, edge-only scans |
n_plus_m |
n + m |
BFS, DFS, connected_components, topological_sort, articulation points |
n_log_n |
n · ⌈log₂ n⌉ |
sorting-based reductions, lex-min element selection |
n_plus_m_log_n |
n + m · max(1, ⌈log₂ n⌉) |
Dijkstra with binary heap |
n_m |
n · m |
Bellman-Ford, Brandes betweenness |
n_squared |
n² |
dense-matrix shortest-paths, dense centrality |
n_m_alpha |
n · m · α(n,m) |
Edmonds' max-weight matching, union-find-amortized algorithms |
m_log_m |
m · ⌈log₂ m⌉ |
Kruskal's MST (edge sort dominates) |
m_log_n |
m · ⌈log₂ n⌉ |
Prim's MST with binary heap |
If you build your own algorithm on top of fnx and want to participate in the witness ledger, pick the term that bounds your worst-case observed-op count, return it in the witness, and the runtime's complexity-bound verifier will catch any regression.
The V1 policy registry
The v1_policy_registry() table pins a canonical tie-break policy and dominant complexity term for each of the 12 reference algorithms, the V1 set whose tie-break behavior is contractually frozen. Source: ReferenceAlgorithm::policy and ::dominant_complexity in crates/fnx-cgse/src/lib.rs.
| Family | Reference algorithm | Tie-break policy | Dominant complexity |
|---|---|---|---|
| shortest_path | dijkstra |
WeightThenInsertionOrder |
n_plus_m_log_n |
| shortest_path | bellman_ford |
InsertionOrder |
n_m |
| traversal | bfs |
InsertionOrder |
n_plus_m |
| traversal | dfs |
InsertionOrder |
n_plus_m |
| matching | max_weight_matching |
WeightThenLex |
n_m_alpha |
| matching | min_weight_matching |
WeightThenLex |
n_m_alpha |
| connectivity | connected_components |
LexMin |
n_plus_m |
| connectivity | strongly_connected_components |
InsertionOrder |
n_plus_m |
| trees | kruskal |
WeightThenLex |
m_log_m |
| trees | prim |
WeightThenLex |
m_log_n |
| euler | eulerian_circuit |
InsertionOrder |
m |
| dag | topological_sort |
InsertionOrder |
n_plus_m |
The choice of InsertionOrder for bfs/dfs/bellman_ford/topological_sort is exactly the NetworkX behavior: those algorithms iterate adjacency in the order the user inserted edges, and IndexMap preserves that. The choice of WeightThenInsertionOrder for Dijkstra matches NetworkX's heapq + itertools.count() pattern (a monotonic per-push counter is the secondary key, so equal-weight frontier entries pop in FIFO order). The registry assigns WeightThenLex to the Kruskal, Prim, and matching reference kernels; this does not describe every public sibling's tie-break behavior.
These are machine-readable assignments for the 12 reference kernels, not automatic policy enforcement across the wider API. Public routes can use different sibling kernels: for example, public Prim uses heap insertion order and NetworkX's set(G).pop() roots, whereas the Rust Prim reference sorts equal-weight endpoints lexically. A registry row alone does not prove a public route's policy or witness coverage.
Complexity Witnesses
Instrumented kernels emit a structured ComplexityWitness only while collect_witnesses is active, capturing n, m, observed operation count, the policy identifier, and a length-prefixed Blake3 hash over the decision path. All 12 reference algorithms in v1_policy_registry() now emit witnesses on their primary public Python routes (br-r37-c1-rc0923-epic-crown-jewels-csmqh.1): connected components, BFS/DFS, Kruskal, Bellman-Ford, DiGraph/MultiDiGraph SCC enumeration and strongly-connected count, topological sort, simple undirected and directed eulerian_circuit, max_weight_matching, min_weight_matching, simple Graph/DiGraph and exact-domain MultiGraph Dijkstra/bidirectional Dijkstra routes, and indexed public Prim on simple graphs. Indexed public Prim reports its actual heap FIFO policy (WeightThenInsertionOrder), whereas the Rust Prim reference kernel uses WeightThenLex. Unit-weight dijkstra_path(weight=None) is instrumented on the four concrete graph classes; callable weights, Python-only weight dictionaries, authoritative private rows, and multigraph Euler retain Python traversal without a native receipt. An empty witness list must not be treated as proof, and the wider API surface outside the 12 reference algorithms does not emit witnesses.
The indexed Prim routes above require a simple undirected Graph.
Strict vs Hardened Modes
Two compatibility doctrines, both available at runtime:
- Strict: maximize observable compatibility for V1 scoped APIs. No behavior-altering repairs. Malformed input fails closed with structured error context.
- Hardened: preserve the API contract while applying bounded defensive recovery for malformed inputs and hostile edge cases. Useful when ingesting graphs from adversarial sources.
The mode is configured via fnx.config, scoped context managers, or per-call reader arguments:
import franken_networkx as fnx
# 1. Process-wide configuration (mirrors nx.config):
fnx.config.compatibility_mode = "hardened" # or fnx.set_compatibility_mode("hardened")
# 2. Scoped context managers (thread-local overrides):
with fnx.config(compatibility_mode="hardened"):
G = fnx.Graph()
assert G.mode == "hardened"
with fnx.compatibility_mode("hardened"):
G = fnx.read_edgelist("adversarial_edges.txt")
# 3. Direct function kwargs on read/parse entry points:
G = fnx.read_graphml("input.graphml", mode="hardened")
assert G.mode == "hardened"
# 4. Audit Evidence Ledger (DecisionRecord):
# Inspect or drain the recovery decisions made during parsing and mutation:
records = G.decision_records() # or fnx.decision_records(G)
drained = G.drain_decision_records() # or fnx.drain_decision_records(G)
The choice is made through CgsePolicyEngine in fnx-runtime, which records every action selection as a DecisionRecord with evidence terms. In Hardened mode, unknown incompatible features still fail closed to maintain security invariants.
Why determinism matters
Most NetworkX algorithms have multiple equally-correct answers. Consider connected_components(G) on a graph with two components. There is no inherent ordering between the components, and NetworkX's actual answer depends on Python's dict iteration order, which depends on insertion order, which depends on whatever sequence of add_edge calls produced the graph. Code that does next(iter(connected_components(G))) is implicitly depending on this chain.
A "faster" library that returns the same set of components but in a different order silently breaks every caller that depended on the original order. The crash, if any, surfaces far from the swap, usually as a downstream comparison or hash that produces a different result.
CGSE addresses this by making the tie-break visible:
import franken_networkx as fnx
from franken_networkx._fnx import cgse # bound Rust submodule
# Inspect the policy registry: which policy governs which algorithm.
# policy_registry() returns: { "<algorithm>": {"family": ..., "policy": ..., "dominant_complexity": ...} }
registry = cgse.policy_registry()
for algorithm, info in registry.items():
print(f"{algorithm:30s} → policy={info['policy']:20s} bound={info['dominant_complexity']}")
# dijkstra → policy=weight_then_insertion_order bound=n_plus_m_log_n
# bellman_ford → policy=insertion_order bound=n_m
# bfs → policy=insertion_order bound=n_plus_m
# connected_components → policy=lex_min bound=n_plus_m
# max_weight_matching → policy=weight_then_lex bound=n_m_alpha
# topological_sort → policy=insertion_order bound=n_plus_m
# ...
# You can also query an algorithm's canonical policy directly:
print(cgse.algorithm_policy("dijkstra")) # → TieBreakPolicy.weight_then_insertion_order
print(cgse.algorithm_policy("unknown_algo")) # → None
print(cgse.reference_algorithms()[:5]) # → ['dijkstra', 'bellman_ford', 'bfs', 'dfs', 'max_weight_matching']
The complexity witness contract
Each reference-algorithm execution emits a ComplexityWitness. The actual Rust struct is:
pub struct ComplexityWitness {
pub n: usize, // node count
pub m: usize, // edge count
pub dominant_term: String, // "n_log_n", "n_plus_m_log_n", "n_m", ...
pub observed_count: u64, // tie-break decisions + main-loop iterations
pub policy: TieBreakPolicy, // which policy governed tie-breaks
pub seed: Option<u64>, // RNG seed for randomized algorithms
pub decision_path_blake3: [u8; 32], // length-prefixed Blake3 over the decision path
}
The 10 supported complexity-class terms in fnx_cgse::analytic_upper_bound are: n, m, n_plus_m, n_log_n, n_plus_m_log_n, n_m, n_squared, n_m_alpha, m_log_m, m_log_n. The analytic upper bound is computed against the term rather than stored in the witness, so the witness stays small and the bound is looked up on demand:
use fnx_cgse::{collect_witnesses, analytic_upper_bound, ComplexityWitness};
let (result, witnesses): (_, Vec<ComplexityWitness>) = collect_witnesses(|| {
// any block of fnx algorithm calls; only the CGSE reference kernels emit
fnx_algorithms::connected_components(&graph)
});
for w in &witnesses {
if let Some(bound) = analytic_upper_bound(&w.dominant_term, w.n, w.m) {
assert!(w.observed_count <= bound, "complexity regression!");
}
}
Or use the verify_complexity_bound(&witness) and assert_complexity_within_bounds(&witness) helpers shipped from fnx_cgse. Two runs on the same graph with the same policy produce identical decision_path_blake3 hashes; any ordering drift manifests as a hash mismatch, making non-determinism a regression-locked property.
This makes complexity regressions a regression-lockable property, not a folklore expectation: crates/fnx-conformance/tests/cgse_complexity_bound_gate.rs (landed 2026-09-03) asserts for all 12 V1 reference algorithms that a witness is emitted, matches the pinned registry policy and dominant term, stays within analytic_upper_bound, and is hash-identical across runs — with a negative case proving an inflated operation count is rejected. It runs with cargo test -p fnx-conformance, which is part of the DSR quality run (see Quality Gates).
Tie-break policies in action
Different policies on the same algorithm give different, but reproducible, answers:
# Conceptually, fnx ships these per-algorithm. Most users never have to think about it;
# the policy that matches NetworkX's behavior is the default. The visibility matters
# when you're auditing for reproducibility.
# Dijkstra under WeightThenInsertionOrder (the default, matching NetworkX):
# equal-weight frontier entries pop in the order they were inserted (FIFO).
import franken_networkx as fnx
G = fnx.Graph()
G.add_weighted_edges_from([
("a", "b", 1.0),
("b", "z", 1.0),
("a", "z", 3.0),
])
fnx.shortest_path(G, "a", "z", weight="w")
# Under a hypothetical WeightThenLex policy, equal-weight alternatives would
# be broken by lex-min node label instead, giving insertion-order-independent
# results but breaking byte-for-byte parity with NetworkX.
You should almost never override the default. The defaults are chosen to match NetworkX. The point is that which tie-break is in effect is now a contract, not an emergent property of Python dict layout.