FrankenNetworkX

Guide/How it works

Internals Walkthrough

3 min readFrom the README

On this page 6
Step 1: Python wrapper entryStep 2: PyO3 binding (crates/fnx-python/src/algorithms.rs)Step 3: Native algorithm (crates/fnx-algorithms/src/lib.rs)Step 4: Result marshalingStep 5: Witness ledger drain (optional)Anatomy of PyGraph

A guided tour of the moving parts in a single algorithm execution. Useful for new contributors and for anyone debugging an edge case.

Step 1: Python wrapper entry

Every public algorithm name in franken_networkx.* resolves through the package's __getattr__ or its 3 MB, 70,000-line __init__.py. A typical wrapper does these things in order:

  1. Argument validation. Check that the graph is a supported type, that node arguments exist, that weight strings are hashable. Errors raised here use the same class and message as nx.
  2. Boundary coercion. If the user passed an nx.Graph, convert it via _networkx_graph_for_parity (which uses _topo_emit_edges_by_adj to preserve adjacency order).
  3. Argument-shape dispatch. For ~125 functions, check whether the call shape is one the native fast path handles. If not, route through _call_networkx_for_parity or _call_networkx_submodule_for_parity and return nx's answer.
  4. GIL-releasing call into the Rust kernel via franken_networkx._fnx.<bound_name>.
  5. Post-processing, if the function is one of the 24 wrapper-patched ones.

Step 2: PyO3 binding (crates/fnx-python/src/algorithms.rs)

The cdylib re-exports algorithm functions as #[pyfunction]s. The pagerank binding, which the public wrapper does not currently use because it prefers the scipy route (simplified; the real signature also takes personalization, nstart and dangling, and raises NetworkXNotImplemented if any of them is given):

#[pyfunction]
#[pyo3(signature = (g, alpha=0.85, max_iter=100, tol=1.0e-6, weight="weight"))]
pub fn pagerank(
    py: Python<'_>,
    g: &Bound<'_, PyAny>,            // accepts a fnx graph or an nx graph
    alpha: f64,
    max_iter: isize,
    tol: f64,
    weight: Option<&str>,
) -> PyResult<Py<PyDict>> {
    let graph: PyRef<'_, PyGraph> = g.downcast::<PyGraph>()?.borrow();
    let result: HashMap<String, f64> = py.allow_threads(|| {     // ← GIL released
        fnx_algorithms::pagerank(&graph.inner, alpha, max_iter as usize, tol, weight)
    });
    let dict = PyDict::new(py);                                  // ← GIL reacquired
    for (node, score) in result {
        dict.set_item(node, score)?;
    }
    Ok(dict.into())
}

GIL release is critical: without it, concurrent Python threads calling fnx algorithms would serialize on the interpreter lock. With it, each call holds only its own Rust adjacency borrow for the duration.

Step 3: Native algorithm (crates/fnx-algorithms/src/lib.rs)

A Rust kernel builds dense node-index working data from the IndexMap-keyed adjacency, runs the algorithm body on indices, and returns the natural result type (HashMap<String, f64> for pagerank). The CGSE reference kernels (Dijkstra, Bellman-Ford, BFS/DFS, components, Kruskal, ...) additionally:

  1. call cgse_begin(CgseReferenceAlgorithm::<Name>) to open a witness sink (a no-op unless witness collection is active);
  2. call cgse_record_decision(...) at tie-break points;
  3. call cgse_publish(...) at the end to finalise the witness into the thread-local WitnessLedger.

PageRank is not one of them and emits no witness.

Step 4: Result marshaling

PyO3 walks the returned Rust collection and constructs the corresponding Python container. For a HashMap<String, f64> returning a PyDict, this is N hash insertions; for a Vec<HashSet<String>> returning a list of PySet, this is one nested walk.

Step 5: Witness ledger drain (optional)

If Python, the conformance harness or a Rust integration test wraps an instrumented call in collect_witnesses(...), the WitnessLedger is drained at scope exit and the per-call ComplexityWitnesses are returned to the caller. Outside a collection scope, no sink is opened and no witness is recorded.

Anatomy of PyGraph

The Python-visible franken_networkx.Graph is implemented as a PyO3 #[pyclass] named PyGraph whose state has two tiers (simplified below: the real struct has 19 pub(crate) fields, the rest being caches, generation counters and index lookasides):

#[pyclass(module = "franken_networkx", name = "Graph", dict, weakref, subclass)]
pub(crate) struct PyGraph {
    pub(crate) inner: Graph,                                  // the Rust adjacency map
    pub(crate) node_key_map: HashMap<String, PyObject>,        // canonical key → original Py object
    pub(crate) node_py_attrs: HashMap<String, Py<PyDict>>,     // per-node Python attr dict
    pub(crate) edge_py_attrs: HashMap<(String, String), Py<PyDict>>,  // per-edge Python attr dict
    pub(crate) graph_attrs: Py<PyDict>,                        // graph-level attr dict
}

The two-tier design is deliberate:

  • inner: Graph: the canonical adjacency the Rust algorithm kernels iterate. Attribute values inside inner use CgseValue (serde-typed), which is the form algorithms want and which serializers can round-trip without information loss.
  • node_py_attrs / edge_py_attrs / graph_attrs: real Python PyDicts that the Python-visible G.nodes[u], G.edges[u, v], and G.graph views point to. Mutations like G[u][v]["weight"] = 2.0 land here first because the user expects standard dict semantics (live views, identity, subclass support). These mirrors are materialised lazily: a graph built natively (generators, batch constructors) keeps its attributes only in inner until something reads them through a Python view, so code that asks "does any edge carry this attribute?" must consult inner too.
  • node_key_map: preserves the original Python object that became the canonical string key, so iteration returns the same Python object the user passed in (G.add_node(("a", "b")) then list(G.nodes())[0] returns the same tuple instance, not a re-constructed one).

The _sync_rust_edge_attrs(G) helper bridges the two: when an algorithm needs current edge attributes, it copies the Python-side dict into inner in CgseValue form first. This is why a G[u][v]["weight"] = 2.0 mutation is immediately visible to downstream weighted algorithms, at the cost of a sync pass scoped to the algorithm call.