Repository navigation
Description
Native graph engine: replace networkx with a stdlib-only implementation
Supersedes #3031. Builds on #3027 / PR #3032.
Why
- Zero-dependency mode: networkx metrics that were never computed read as 0.0 outside the DB (false 'Containment' insight, 0.0 macro table, HITL never fires) #3027 / PR Uncomputed graph metrics are None, and zero-dependency mode computes PageRank (#3027) #3032: made PageRank native (
_pagerank()ingitgalaxy/core/network_risk_sensor.py) and runs it in BOTH modes, so there is no mode drift and no networkx-version drift. Every metric still not computed isNone, never0.0. - networkx declares no dependencies of its own, but
nx.pagerank(3.x dispatches to_pagerank_scipy) andnx.degree_assortativity_coefficientimport numpy/scipy. Verified by blocking those imports: pagerank and assortativity fail; betweenness, closeness, Louvain, modularity, SCC, avg path length, articulation points and descendants still work. Sopip install networkxalone gives a scan that believes it is full precision but silently loses metrics. - Once networkx leaves the runtime, graph metrics are identical on every install. Zero-dependency mode then loses nothing on the graph side; only tiktoken, ML (xgboost/pandas/numpy) and pyyaml remain optional (see
docs/zero_dependency_mode.md).
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 > 1500community.louvain_communities(U, seed=42)(fallbackgreedy_modularity_communities), thencommunity.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 Vnx.average_shortest_path_length(U.subgraph(largest connected component)), skipped when V > 5000nx.articulation_points(U), count
gitgalaxy/security/security_auditor.py (_resolve_dependency_graph):
min(len(nx.descendants(G, path)), 500)andmin(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.descendantsexcludes it) - the 500 cap is checked once per popped node, so it can overshoot 500
- it counts the start node when the start is in a cycle (
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), sincepy_random_statewraps an int seed inrandom.Random. - Weighted Brandes:
_single_source_dijkstra_path_basicpushes(dist, next(count), pred, v)on a heapq. Equal-length paths are counted whenvw_dist == seen[w](exact float equality).sigmastarts 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-nodescale_source = 1/((K_source-1)*(N-1))for v in the sample, andscale_nonsource = 1/(K_source*(N-1))otherwise.
- Sample is
- 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)/totspwhentotsp>0andV>1.wf_improved=Truemultiplies by(len(sp)-1)/(V-1). - assortativity:
degree_assortativity_coefficient(G, x="out", y="in", weight=None), built fromdegree_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 botha→bandb→aexist, 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
Nonebecome 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
- Native graph engine: shared CSR graph index + parity/benchmark harness #3034 Native graph engine: shared CSR graph index + parity/benchmark harness
- Native graph engine: cyclic density (SCC) and articulation points in O(V+E) #3035 Native graph engine: cyclic density (SCC) and articulation points in O(V+E)
- Native graph engine: degree assortativity without numpy #3036 Native graph engine: degree assortativity without numpy
- Native graph engine: closeness at every size + directed average path length #3037 Native graph engine: closeness and average path length (BFS family) with parallel sources and an edge-budget cutoff
- Native graph engine: exact betweenness (hop-count BFS Brandes, every repo size) #3038 Native graph engine: betweenness (weighted Brandes + networkx-compatible seeded sampler)
- Native graph engine: Louvain modularity (faithful port of networkx's seeded Louvain) #3039 Native graph engine: Louvain modularity (faithful port of networkx's seeded Louvain)
- Native graph engine: exact security_auditor reach counts (no 500 cap) #3040 Native graph engine: security_auditor reach counts via capped BFS
- Native graph engine: remove networkx from the runtime #3041 Native graph engine: remove networkx from the runtime
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:
- Native graph engine: shared CSR graph index + parity/benchmark harness #3034: the parity harness supports "oracle = networkx computing the tailored definition".
- Native graph engine: closeness at every size + directed average path length #3037: closeness has no cutoff; average path length is redefined as above.
- Native graph engine: exact betweenness (hop-count BFS Brandes, every repo size) #3038: exact, hop-count BFS Brandes. Reproducing networkx's seeded sampler and weighted Dijkstra is dropped.
- Native graph engine: exact security_auditor reach counts (no 500 cap) #3040: reach counts are exact, with no 500 cap.
- Native graph engine: cyclic density (SCC) and articulation points in O(V+E) #3035, Native graph engine: degree assortativity without numpy #3036, Native graph engine: Louvain modularity (faithful port of networkx's seeded Louvain) #3039: unchanged (strict parity).
Every definition change updates docs/zero_dependency_mode.md and the metric's user-facing docs in the same PR.
Activity
Native graph engine: shared CSR graph index + parity/benchmark harness (
Native graph engine: cyclic density (SCC) + articulation points in O(…
Native graph engine: exact hop-count betweenness at every size (#3038)
Native graph engine: exact hop-count betweenness at every size (#3038) (