Skip to content

Native graph engine: replace networkx with a stdlib-only implementation (zero-dependency, exact parity, faster) #3033

Closed

Description

@squid-protocol

Native graph engine: replace networkx with a stdlib-only implementation

Supersedes #3031. Builds on #3027 / PR #3032.

Why

What networkx still does in the engine (the inventory)

gitgalaxy/core/network_risk_sensor.py (build_dependency_graph):

  • nx.betweenness_centrality(G, k=min(V,100) if V>500 else None, weight="weight", seed=42 if sampled else None)
  • nx.closeness_centrality(G), bypassed (None) when V > 1500
  • community.louvain_communities(U, seed=42) (fallback greedy_modularity_communities), then community.modularity(U, communities), skipped when V > 5000. U = G.to_undirected().
  • nx.degree_assortativity_coefficient(G)
  • nx.strongly_connected_components(G), giving cyclic density = nodes in SCCs of size > 1, divided by V
  • nx.average_shortest_path_length(U.subgraph(largest connected component)), skipped when V > 5000
  • nx.articulation_points(U), count

gitgalaxy/security/security_auditor.py (_resolve_dependency_graph):

  • min(len(nx.descendants(G, path)), 500) and min(len(nx.ancestors(G, path)), 500) per file.
  • A pure-Python BFS fallback (get_nth_degree) already exists. It differs from nx in two edge cases:
    • it counts the start node when the start is in a cycle (nx.descendants excludes it)
    • the 500 cap is checked once per popped node, so it can overshoot 500

Measured baseline (language-crucible v1.2.0 import graph: V=2,817, E=1,354, warm timings, best of 3)

operation networkx notes
to_undirected 10.7 ms a copy the native engine avoids
pagerank 4.3 ms (scipy) native _pagerank today: 10.2 ms (dict-of-str). Must beat nx once on integer arrays.
betweenness k=100 seed=42 84.9 ms
closeness (exact, all nodes) 21.4 ms the 1,500-node cutoff is far too conservative for sparse import graphs
louvain + modularity 203.1 ms
assortativity 16.6 ms numpy-backed
SCC 3.1 ms
articulation points 3.9 ms
avg shortest path length (LCC) 1,213.5 ms the dominant cost of the whole graph phase
descendants + ancestors (all nodes) 22.0 ms

Exact networkx conventions a port must reproduce

Read from networkx 3.6.1 source.

  • betweenness:
    • Sample is random.Random(42).sample(list(G.nodes()), k), since py_random_state wraps an int seed in random.Random.
    • Weighted Brandes: _single_source_dijkstra_path_basic pushes (dist, next(count), pred, v) on a heapq. Equal-length paths are counted when vw_dist == seen[w] (exact float equality). sigma starts at 0.0, and 1.0 for the source.
    • Accumulation: _accumulate_basic.
    • Rescale (_rescale, directed, normalized=True, endpoints=False): N = n-1. Unsampled: scale = 1/(K_source*(N-1)). Sampled: per-node scale_source = 1/((K_source-1)*(N-1)) for v in the sample, and scale_nonsource = 1/(K_source*(N-1)) otherwise.
  • closeness (directed): computed on G.reverse(), i.e. incoming distance. Unweighted BFS (single_source_shortest_path_length), totsp = sum(dist). Value is (len(sp)-1)/totsp when totsp>0 and V>1. wf_improved=True multiplies by (len(sp)-1)/(V-1).
  • assortativity: degree_assortativity_coefficient(G, x="out", y="in", weight=None), built from degree_mixing_matrix, then _numeric_ac. A native version must reproduce the Pearson correlation over (out-degree of source, in-degree of target) per edge, in floating-point order close enough to round-equal at the stored 4 dp.
  • louvain: louvain_communities(G, weight="weight", resolution=1, threshold=1e-7, max_level=None, seed=42). It uses a seeded shuffle of nodes per level. U = G.to_undirected(): when both a→b and b→a exist, the undirected edge keeps the attributes of the LAST one added in adjacency iteration order.
  • avg path length: unweighted, largest connected component of U, mean over all ordered pairs.

Engineering approach

Applies to every sub-issue.

  • One shared CSR graph index, built once per scan from _resolve_edges():

    • integer node ids in file order
    • out/in adjacency as flat lists or array('i') with offsets
    • parallel weight arrays, plus an undirected view built without copying attribute dicts

    Every algorithm reads this index. No networkx graph and no to_undirected() copy.

  • Hot-loop technique: integer indices, preallocated lists ([-1]*V), local-variable binding, no per-iteration dict or set allocation, iterative (never recursive) DFS. A 1,501-node chain must not hit the recursion limit.

  • Complexity targets:

metric target notes
PageRank O(iterations × (V+E))
SCC O(V+E) iterative Tarjan or Kosaraju
articulation points O(V+E) iterative Hopcroft–Tarjan
assortativity O(V+E) single pass
reach counts O(V × min(500, V+E)) capped BFS with early exit
closeness, avg path length O(V × (V+E)) all-sources BFS; no exact algorithm does better, so speed comes from constant factors, early exit and parallelism
betweenness O(k × (E + V log V))
Louvain near-linear per level
  • Parallelism, stdlib only: per-source BFS/Dijkstra runs (closeness, avg path length, betweenness sources, reach counts) are independent. Fan them out across a concurrent.futures.ProcessPoolExecutor / the engine's existing worker pool, above a size threshold. Results must be combined in a FIXED source order, so the output is bit-deterministic regardless of worker count.
  • Parity: each native algorithm gets a parity test against networkx on seeded random graphs and on the real crucible graph. Required: equal at the precision the engine stores (6 dp for centralities, 4 dp for macro metrics, exact for counts/ids), plus a benchmark showing it is no slower than networkx.
  • Golden masters: exact parity means the full-precision fixture should not move. The zero-dependency fixture WILL move as metrics that used to be None become real (e.g. the betweenness/closeness bottleneck rankings). Every bless is scoped with an uncapped diff (see CLAUDE.md's "Scoping a bless").

Sub-issues

Tailoring decisions (2026-09-14): these override "exact parity" wherever the two conflict

The goal is no longer to reproduce networkx. It is to compute what GitGalaxy needs, now that networkx's speed-driven limits no longer bind. networkx stays the test-time oracle, but it computes the tailored definition (e.g. exact, unweighted betweenness). So every native algorithm is still proven correct, and every change of definition is a deliberate, measured output change with a scoped golden-master diff.

Evidence: language-crucible v1.2.0 graph (V=2,817, E=1,354) and the self-scan graph (V=395, E=497).

decision evidence
Betweenness exact at every size, with no 100-source sampling Sampled (k=100, seed 42): 11 files with nonzero betweenness. Exact: 78. 14 of the exact top-20 choke points read 0 under sampling (top-20 overlap 6/20). networkx exact takes 1,560 ms (weighted Dijkstra): the native number to beat. Skip sources with no outgoing import (292/395 files on the self-scan have one).
Path metrics use hop count networkx treats weight as distance ("Weights are used to calculate weighted shortest paths, so they are interpreted as distances"), so entity imports (weight 1.5, stronger coupling) became longer paths. That is backwards. It changed 1 file on crucible and 0 on the self-scan. Hop count lets betweenness use BFS instead of Dijkstra. The edge weight remains a PageRank strength only.
Average path length = mean hops over all directed reachable pairs (A transitively depends on B), across every file Today it uses the largest undirected component, which ignores import direction and covered only 22.5% of crucible files and 79.5% of self-scan files. It took 952 ms (crucible) and 211 ms (self-scan). Directed, crucible: 1.36 hops over 1,891 reachable pairs in 6 ms. Directed, self-scan: 1.71 over 1,028 pairs, vs 4.19 undirected.
Closeness at every size (the V>1500 cutoff removed) Exact all-node closeness takes 18 ms on the 2,817-node crucible graph, which the cutoff currently skips.
Reach counts exact (the 500 cap removed) The largest observed on crucible is 185. Use SCC condensation plus Python-int bitset reachability.
Node-count cutoffs become deterministic work budgets Example: V×(V+E) ≤ threshold. Never wall-clock: a timer would compute a metric on a fast runner and skip it on a slow one, and golden masters would flake. A metric past its budget is None, never 0.0 (#3027).

Effect on the sub-issues:

Every definition change updates docs/zero_dependency_mode.md and the metric's user-facing docs in the same PR.

Activity

  1. added
    enhancement
    epic
    metrics
    core-engine
    on Sep 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    core-engineenhancementepicmetrics

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions