Guide/How it works
Memory Model and Data Layout
5 min readFrom the README
On this page 7
Understanding the internals helps when you want to reason about cost or attribute semantics.
Adjacency
The actual storage layout for each graph type splits adjacency from attribute storage. This differs from NetworkX's nested-dict layout and is more cache-friendly:
// crates/fnx-classes/src/lib.rs and digraph.rs (abbreviated; revision-keyed caches omitted)
pub struct Graph {
mode: CompatibilityMode, // Strict | Hardened
revision: u64, // bumped on every structural mutation
node_order: FxIndexMap<String, usize>, // name → slot; iteration order = insertion order
slot_names: Vec<Option<String>>, // slot → name (None = tombstoned)
node_attrs: Vec<AttrMap>, // slot → node attrs
free_slots: Vec<usize>, // tombstoned slots awaiting reuse/compaction
adj_indices: Vec<Vec<usize>>, // slot → neighbor slots, insertion-ordered
edges: FxIndexMap<(usize, usize), AttrMap>, // slot-canonical (min, max) → edge attrs
edge_index_endpoints: Vec<(usize, usize)>, // edge slot → string-canonical orientation
runtime_policy: RuntimePolicy,
// plus revision-keyed caches (all-int weights, per-neighbour edge slots)
}
pub struct DiGraph {
// the same slot layout, with succ_indices / pred_indices in place of adj_indices
// plus CSR and all-int-weight caches
}
pub struct MultiGraph {
mode: CompatibilityMode,
revision: u64,
storage: MgSlabStorage, // slab of (u, v, key) → attrs with per-node rows
runtime_policy: RuntimePolicy,
edge_count: usize,
// plus an integer-adjacency cache
}
Three design choices fall out of this layout:
- Insertion order everywhere. The node and edge maps are
IndexMaps and the integer adjacency rows are plainVecs appended in insertion order, so iteration order is the order the user built the graph. This is the structural guarantee that lets fnx match NetworkX's iteration order without sorting. - Adjacency and edge attributes live in separate containers. Adjacency lookups (
G[u],G.neighbors(u)) walk integer rows and never touch attribute payloads. Edge-attribute mutations (G[u][v]["weight"] = 2) are constant-time on the index-canonical(min, max)key and don't disturb the neighbor iteration order. The edge map is keyed by node slot, and a removal frees its slot instead of renumbering, so the map is rekeyed only when the store compacts: at the first insertion after a run of removals, or once freed slots outnumber live nodes. OnGraph/DiGraphthe node order itself tombstones too, so a removal costs O(degree).MultiGraphkeeps reusing freed slots and tombstones a separate insertion-order list, so its removal is O(degree) as well;MultiDiGraph's node table tombstones and its String-keyed row maps are unordered, so its removal is O(degree) too (br-r37-c1-epic-storage-architecture-yr2oc.1). DiGraphkeepssucc_indicesandpred_indicesas separate adjacency rows.in_degree(v)andout_degree(v)are O(1) lookups, not full edge walks.
The revision counter is incremented on every mutation; the cached snapshot views in fnx-views and the Python view classes carry the revision they last saw, so view invalidation is a single integer compare.
Node identity
Python node labels are canonicalized to a Rust String by node_key_to_string in crates/fnx-python/src/lib.rs. The canonicalization:
- Passes through Python strings unchanged.
- Stringifies integers and booleans to mirror Python's
hash(True) == hash(1),hash(False) == hash(0)collisions, so an edge added withkey=0and one added withkey=Falseresolve to the same edge (matching NetworkX's dict-based key semantics). - Collapses floats with integer value into their integer canonical so that
hash(1) == hash(1.0)parity holds for dict-keyed paths (matching NetworkX). - Interns non-primitive custom objects and tuples containing custom objects through a bounded 65,536-entry Python-equality/hash table (
custom_object_canonical_key,br-r37-c1-epic-storage-architecture-yr2oc.5) so user-defined classes with custom__eq__/__hash__and hash collisions preserve NetworkX dict-key identity, while falling back torepr()for pure-primitive tuples and frozensets and preserving distinctness across IEEE-754 special floats (NaN,±Inf,1.5,1e20).
This canonicalization is the entire reason MultiGraph edge keys with key=0, key=0.0, and key=False collide into a single edge (tracked in commit history as br-r37-c1-edgekeyint), and why non-primitive custom objects honor __eq__/__hash__ across all four graph classes (yr2oc.5). The remaining scoped boundary: subclasses of primitive types (str, int, float) that redefine __eq__/__hash__ to make distinct primitive values compare equal still canonicalize by value (br-r37-c1-cow38). See docs/upstream_divergence_ledger.md and docs/planning/FEATURE_PARITY.md for the full set of int/str/float canonicalization caveats.
Attribute storage
In the native store, edge and node attributes live in BTreeMap<String, CgseValue>. CgseValue has five variants: Bool, Int (i64), Float (f64), String, and Map (nested, string-keyed). Anything else a user stores — None, lists, tuples, arbitrary objects — is kept exactly in the Python-side attribute dict the user sees; the native store holds a string form of it, so kernels that need a number check the value rather than trust the variant.
Native readers and writers (fnx-readwrite) map typed format values (bool, long, double) onto these variants and reject malformed type tags in strict mode.
Node order preservation
Node insertion order is preserved across the entire graph lifecycle, with two important caveats:
G.copy()follows the NetworkX contract. Node and adjacency insertion order are preserved; each node/edge gets a fresh attribute dict whose values are shared with the original (not deep-copied).copy.copy(G)does not yet match NetworkX. NetworkX's shallow copy shares the attribute dicts with the original and costs O(1); fnx's copies the structure (O(n)) and shares onlyG.graph(br-r37-c1-epic-storage-architecture-yr2oc.3).
Views
The Python view classes (NodeView, EdgeView, DegreeView, AdjacencyView, SubgraphView) are defined in crates/fnx-python/src/views.rs on top of the borrowed snapshot primitives in fnx-views. Views are live: mutations to the underlying graph are visible through them. They carry a revision counter so they can invalidate themselves cheaply when the graph changes underneath them. SubgraphView is the structure operators (union, intersection, difference, compose) accept transparently; they don't materialize a fresh graph unless asked to.
Edge attribute semantics
Edge attributes are held twice: the Python attribute dict (what G.edges[u, v] returns, holding the original objects) and the native CgseValue form the kernels read:
| Python type | Native CgseValue |
Notes |
|---|---|---|
bool |
Bool |
Python's True == 1 is honoured where NetworkX relies on it (e.g. unit-weight checks) |
int (i64 range) |
Int |
larger ints stay exact in the Python dict |
float (including NaN/±Inf) |
Float |
non-finite weights are routed to NetworkX-exact code paths |
str |
String |
|
dict[str, T] |
Map |
nested |
None, list, tuple, other objects |
String (a string form) |
the Python dict keeps the original object; it is the one users and serializers see |
The contract is NetworkX parity: anywhere NetworkX accepts an arbitrary Python value as an edge attribute, fnx accepts it too and returns the same object. What a format round-trip preserves follows NetworkX's reader/writer for that format; the per-format parity tests compare against it.
The _sync_rust_edge_attrs(G) helper is the wraparound that pushes Python-side attribute mutations like G[u][v]["weight"] = 2.0 down into the Rust adjacency map. This is invoked transparently from algorithm wrappers; you only need to know about it if you're profiling the cost of an attribute-heavy hot loop.
EdgeKey canonicalization
For undirected graphs, the Rust adjacency store indexes edges by slot-canonical (min(slot(u), slot(v)), max(slot(u), slot(v))), while the Python-side edge_py_attrs mirror canonicalizes (u, v) with u <= v lex-order on canonical node keys so G[u][v] and G[v][u] find the same entry. For directed graphs, the source/target order is preserved. For MultiGraph variants, the inner edge key (0, 1, 2, … or user-supplied) is canonicalized through edge_key_lookup_string, collapsing 0, 0.0, and False to a single canonical (mirroring Python's dict-key hash collisions on those values).