Skip to content

Native graph engine: Louvain modularity, a faithful port of networkx's seeded Louvain (#3039) - #3049

Merged
squid-protocol merged 2 commits into
mainfrom
fix/3039-native-louvain
Sep 15, 2026
Merged

squid-protocol merged 2 commits into
mainfrom
fix/3039-native-louvain

Conversation

@squid-protocol

Copy link
Copy Markdown
Owner

Closes #3039. Part of #3033 (the native graph engine). Stacked: #3047 (#3036) → #3048 (#3038) → this PR. The branch carries their commits until they merge. Only the last commit, plus its re-bless, is this PR's own.

What changed

A faithful port of networkx's seeded Louvain is in gitgalaxy/core/graph_engine.py: louvain_communities, louvain_modularity, and private helpers mirroring louvain_partitions / _one_level / _gen_graph / modularity. Parity was the acceptance bar, and it goes beyond equal modularity to identical communities, in the same order. To get that, the port reproduces every order that decides a Louvain move:

  • G.to_undirected(): edges are added source-major in out-run order. A mutually importing pair becomes one undirected edge that keeps the later-added direction's weight, while each neighbour keeps the position of its first edge (a dict key keeps its position when reassigned).
  • louvain_partitions rebuild: edges are re-added in G.edges() order, meaning node order with each edge once, per the seen-set rule. That rebuilt adjacency order drives _one_level.
  • The seeded shuffle: random.Random(42), which is what networkx's py_random_state makes of an int seed. One RNG is shared across levels, as in networkx.
  • Gain ties: reading a node's own community from the defaultdict inserts it last when no neighbour shares it, exactly as networkx does. That fixes the order in which equal gains are compared.
  • _gen_graph / weighted degree: community edge weights are summed in edge order, and a self-loop counts twice in the degree.

NetworkRiskSensor._topology_metrics() now also returns modularity, in both modes. This removes:

  • the G.to_undirected() copy
  • community.louvain_communities and its greedy_modularity_communities fallback
  • community.modularity
  • the V>5000 cutoff, now replaced by the deterministic WorkBudget (PATH_METRICS_WORK_BUDGET; each Louvain sweep charges the neighbour entries it reads)

Modularity is None when no file imports another. networkx divides by zero there, which the sensor already recorded as None.

After this PR, networkx computes nothing. The DiGraph builder still exists only for its degree counts and as the full-precision code path; #3040 (reach counts in security_auditor) and #3041 (removal) remain.

Parity and speed

result
seeded random graphs identical communities 300/300 (prototype) plus 25 in pytest (== on the ordered list of sets); modularity equal at 4 dp 300/300
language-crucible (V=2,817, E=1,354) identical 1,989 communities; modularity bit-identical (0.8150048644056641)
crucible timing (graph_parity.py, warm) 69.6 ms native vs 158.0 ms for networkx (to_undirected + Louvain + modularity; #3033 recorded 203 ms)

One caveat: networkx's own modularity sums each community's edges in set order. At level 0 the members are string paths, so the float summation order varies with PYTHONHASHSEED. Parity at the stored 4 dp is therefore the meaningful bar for modularity. The communities themselves never depend on hash order.

Golden masters

I diffed fresh scans of each mode against the committed fixtures with an uncapped golden_diff.deep_compare. The scans used GITGALAXY_DISABLE_GIT_HISTORY=1 and the same flags as test_golden_crucible.py.

  • Full precision: 0 differences. crucible_check.py --update also reported "No drift detected". On the real corpus the port reproduces networkx's modularity (0.8131).
  • Zero dependency: 1 difference, intended. network_macro/modularity went from None to 0.8131, the value full precision reports.

The zero-dependency fixture is re-blessed in the second commit.

Verification

  • pytest passes on the 10 affected suites (509 passed), run as plain pytest from outside the repo.
  • New tests:
    • identical communities vs networkx
    • edgeless → None
    • the budget raises
    • the sensor never calls louvain_communities, modularity or to_undirected, and both modes agree
    • zero-dependency modularity is computed
  • Removed tests:
    • test_modularity_falls_back_to_greedy_when_louvain_unavailable: the fallback is gone
    • test_macro_math_outer_failure_returns_all_none: the outer macro block is gone. The new test_macro_metrics_never_call_networkx covers the same ground.
  • audit_check.py: all clear. The seeded RNG carries noqa: S311, since it reproduces networkx's shuffle and has nothing to do with security.
  • Docs updated: zero_dependency_mode.md (the networkx section now says it provides nothing; modularity row; older snapshots), the 02-16 wiki, README (networkx is no longer listed as needed for anything), CLAUDE.md, the console banner and the zero-dependency warning.

🤖 Generated with Claude Code

@squid-protocol squid-protocol added enhancement New feature, sensor, or structural signature metrics Heuristics, risk exposures, and topological math updates core-engine Modifications to the central physics and parsing engine labels Sep 14, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🐦‍⬛ Muninn Security Scan

✅ No security issues found.

🐦‍⬛ Powered by Muninn · Skald Lab

Comment thread tests/tools/graph_parity.py Fixed
squid-protocol and others added 2 commits September 14, 2026 20:19
…s seeded Louvain (#3039)

- graph_engine: louvain_communities / louvain_modularity, mirroring
  louvain_partitions, _one_level, _gen_graph and modularity order for order:
  - to_undirected's neighbour order, with the later-added reverse weight
    winning
  - the rebuilt G.edges() order
  - random.Random(42) shuffles shared across levels
  - the defaultdict own-community insert-last that orders gain ties
- The result is the same communities as networkx, not just the same
  modularity: 300/300 seeded graphs, plus the crucible's 1,989 communities
  with a bit-identical 0.8150048644056641. 69.6 ms vs 158 ms.
- NetworkRiskSensor._topology_metrics adds modularity in BOTH modes. It
  drops the to_undirected copy, nx Louvain and its greedy fallback, and
  nx.community.modularity. The V>5000 cutoff becomes PATH_METRICS_WORK_BUDGET.
  None when no file imports another, as before.
- networkx now computes nothing; #3040 and #3041 remain.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…w native)

Uncapped golden_diff scope: full precision 0 differences (crucible_check
--update: no drift -- the Louvain port reproduces networkx's modularity on
the real corpus); zero dependency exactly 1 -- network_macro/modularity
None -> 0.8131, the value full precision reports.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@squid-protocol
squid-protocol merged commit 0c8c9ab into main Sep 15, 2026
29 checks passed
@squid-protocol
squid-protocol deleted the fix/3039-native-louvain branch September 15, 2026 00:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core-engine Modifications to the central physics and parsing engine enhancement New feature, sensor, or structural signature metrics Heuristics, risk exposures, and topological math updates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Native graph engine: Louvain modularity (faithful port of networkx's seeded Louvain)

2 participants