Repository navigation
Description
Thanks for graphify — I've been using it on a React/Firebase PWA codebase and it's been really useful for surfacing structural patterns I wouldn't have caught manually.
Related: #830 — god-node transit in BFS/DFS. The two issues address the same underlying phenomenon (high-degree hubs degrading downstream analysis), applied here to clustering rather than path-finding.
Context
Running graphify on a ~1500-node React/TypeScript graph, the output flagged Community 0 (86 nodes) with cohesion 0.05. Manual inspection showed the community is not a semantic neighborhood: it bundles six distinct sub-families (UI primitives, page roots, modal family, layout/nav, PWA bootstrap, RBAC) that have been aggregated together by the clustering algorithm rather than by topology that reflects the actual codebase structure.
The aggregation traces to two "super-hub" nodes:
| Node | Degree | Breakdown |
|---|---|---|
src/components/ui/index.tsx |
44 | 14 external imports + 30 contained symbols (barrel re-export module) |
useRBAC() hook |
32 | 13 imports + 18 call sites across consumer modules |
Both hubs are adjacent to nodes from every sub-family at once, which forces Leiden to attract them all into the same basin under uniform edge weights.
Why the existing second-pass mitigation doesn't catch this
I noticed the comment at cluster.py:124-125 showing that you've already addressed a related class of cluster bloating (doc-hub bridging, e.g. CLAUDE.md connected to everything) with the cohesion-based second-pass split. Two reasons it doesn't cover the case described here:
-
The cohesion threshold doesn't trigger. The actual cohesion of Community 0 is
178 / 3655 = 0.0487.cohesion_score()atcluster.py:166returnsround(actual / possible, 2), producing0.05. The threshold check atcluster.py:128(cohesion_score(G, nodes) < _COHESION_SPLIT_THRESHOLD) becomes0.05 < 0.05 → False, so the community falls through unchanged. (See Additional context below — this looks like a small latent bug worth a separate one-line fix.) -
Even if it triggered, the second pass would not separate this case.
_split_community()re-runs_partition()on the same subgraph with the same Leiden invocation (uniform edge weights, no resolution control). The super-hubs are still in the subgraph and would re-attract the same neighbors, producing the same partition. The safety net atcluster.py:151-152(if len(sub_communities) <= 1: return [sorted(nodes)]) would then return the community unchanged.
So the second-pass mitigation is sound for doc-hub bridging but doesn't cover gravitational super-hub attraction. They look similar from the cohesion metric, but the underlying mechanism differs.
Proposed solution
A CLI option (or three) to give users levers when the structural assumptions of plain Leiden don't fit their codebase. Ranked from smallest delta to most ambitious:
-
--exclude-hubs <degree-percentile>(e.g.p99) — exclude nodes whose degree is above the given percentile of the graph's degree distribution from the partitioning pass, then re-attach them post-clustering by majority neighbor community. Direct fix for the super-hub case. Minimal implementation: a thin wrapper around_partition()incluster.py. Percentile is preferred over an absolute degree threshold because hub degree scales with corpus size. -
--algorithm <leiden|louvain>plus--resolution <N>— expose parameters thatgraspologic.partition.leiden()already supports natively (resolution,randomness,use_modularity). Pure wire-up, no algorithmic work. Useful when the graph is genuinely modular but the default Leiden resolution isn't sharp enough. -
--edge-weight-mode <uniform|inverse-degree|inverse-log-degree>— assign edge weights inversely proportional to endpoint degree, so edges incident to super-hubs are down-weighted automatically. The most principled fix; it solves the root cause without requiring the user to pick a threshold.
For the case described here, option 1 alone would be sufficient. Option 3 is the cleanest architecturally if you'd prefer a single configurable knob.
Alternatives considered
- Pre-processing
graph.jsonto delete high-degree nodes before--cluster-only: workable as a user-side workaround, but loses information and isn't reproducible across runs. - Raising
_COHESION_SPLIT_THRESHOLD: would force more splits but risks over-splitting healthy communities. The threshold isn't the right knob — the underlying partitioning is. - Manual annotation in
GRAPH_REPORT.md: not scalable and defeats the point of automated detection.
Additional context — side observation
While tracing the threshold behavior I noticed that cohesion_score() at cluster.py:166 rounds to 2 decimals before returning, and the same function is used both for display and for the threshold comparison at line 128. This makes the threshold effectively unreachable for boundary cases — any community with raw cohesion in [0.045, 0.05) rounds to 0.05 and fails the strict < 0.05 check.
Minimal fix would be returning the unrounded value and rounding only at display sites, or using <= in the threshold comparison. Happy to send a one-line PR for this independently if useful.
Environment
graphifyy0.8.8 (installed via pipx)- Python 3.12, Linux Mint
- Codebase under analysis: React 18 + TypeScript + Vite + Firebase v12 PWA, ~1500-node graph
Happy to provide more details, additional repro data, or contribute a PR for --exclude-hubs if there's interest in this direction.
Activity
fix hooks phantom dir on git < 2.31, save_manifest incremental data l…
safishamsi commentedon May 17, 2026
Fixed in v0.8.10 — three things shipped: (1) cohesion rounding bug fixed so the split threshold actually fires for borderline communities; (2)
--resolution Nadded toextractandcluster-onlyfor both Leiden and Louvain backends; (3)--exclude-hubs Padded — nodes above the Pth degree percentile are excluded from partitioning and reattached to their majority-vote neighbour community, which keeps staging/utility super-hubs from dominating god-node rankings.neo1777 commentedon May 18, 2026
Tested on v0.8.11 against the original codebase across multiple percentile values to characterize how the new knob behaves:
--exclude-hubs 99--exclude-hubs 95--exclude-hubs 90At
--exclude-hubs 99the 6 sub-families I described in the original report emerge as separate communities with much higher cohesion than the old aggregated blob: UI primitives (0.18), audio modals (0.08), DJ/session logic (0.21), audio hooks (0.12), gaming module (0.10), PWA/CI bootstrap (0.07). The super-hubs (useRBAC,src/components/ui/index.tsx) are correctly excluded from partitioning and reattached to their majority-neighbour community — semantically coherent placement in both cases (RBAC ends up alongside CF/firestore.rules/FCM as a backend-infrastructure cluster;ui/index.tsxreattaches to the UI primitives community, its natural home).Higher percentiles (95, 90) over-split healthy groupings — community count balloons to 518/678 and Community 0 itself shifts theme (test mocks at p95, auth core at p90) as the leftover topology re-stratifies. p99 looks like the right sweet spot for super-hub-driven low-cohesion cases; the more aggressive settings are still useful as a debugging knob but I'd be wary of them as defaults.
Small side note for posterity, no action needed: the two new flags don't surface in
graphify <cmd> --helpbecause of the universal help guard introduced for #821 — which is the safe behaviour. Discoverability via release notes is fine for now; just leaving the observation here in case it's useful when documentation gets revisited.One unrelated minor bug surfaced during the testing run — opened separately to keep this thread clean: see #934.
Thanks for the quick turnaround on this.
fix hooks phantom dir on git < 2.31, save_manifest incremental data l…
fix(cluster): keep hub-only neighbours with their hub under --exclude…
neo1777 commentedon Oct 1, 2026
Option 3 (
--edge-weight-mode) measured on two codebases: no consistent gain over--resolutionOn #942 I wrote that I'd look into the third option from this issue,
--edge-weight-mode(down-weighting edges at high-degree nodes), and "open it as a real PR with tests if it holds up". I measured it on 0.9.71, on two codebases. It doesn't hold up as a new flag, so here are the measurements instead of a PR. Along the way, two other things came up: measurements on the open PR #2388 by keith-oak, and a bug in--exclude-hubs, now fixed in 0.9.73 (#3933).Summary
--resolution. Most differences are larger than the seed noise, but their sign changes with the graph and with the granularity. In the regime closest to the Feature request: CLI flags to handle super-hub-driven low-cohesion communities #919 symptom (about 20 communities on the Feature request: CLI flags to handle super-hub-driven low-cohesion communities #919 codebase), weighting gives lower modularity, a larger largest community and lower cohesion.v8today,--resolutionbarely reaches the final output, because the split passes re-partition at the default 1.0. fix(cluster): honor --resolution on the community split passes #2388 fixes that. I measured it and posted the numbers there (fix(cluster): honor --resolution on the community split passes #2388 (comment)), including a side effect on the 25% oversize cap.Setup
graphifyy0.9.71 from PyPI (v8atd6eaa8a). The code paths measured here are the same in 0.9.73: its only change tocluster.py, fix(cluster): keep hub-only neighbours with their hub under --exclude-hubs #3933, runs only with--exclude-hubs. Both partition backends are reported separately: Leiden viagraspologic-native1.3.1, and the networkx 3.7 Louvain fallback that runs without theleidenextra.graphify extract <dir> --code-only, no LLM), loaded ascluster-onlyloads them (build_from_json, self-loops included):0aa0333), 626 nodes and 1,661 edges. The graph behind Feature request: CLI flags to handle super-hub-driven low-cohesion communities #919 was larger: the cluster-only crashes with FileNotFoundError if graphify-out/ doesn't exist before invocation #934 reproducer shows 1,501 nodes, built with graphify 0.8.x.graphify/package atd6eaa8a, 3,182 nodes and 7,784 edges, 109 of them self-loops.uniform= 1 (graphify's AST weights are already 1.0, except 12 INFERRED edges at 0.8 on B);inverse-degree= 1/√(d_u·d_v);inverse-log-degree= 1/(ln(1+d_u)·ln(1+d_v));inverse-max-degree= 1/max(d_u, d_v);structural-triangle= (1 + common neighbours)/(1 + union of neighbours), a triangle-based control (see Why).seed=42; I wrappedgraspologic_native.leidenand networkx'slouvain_communitiesso every partitioner call gets the injected seed. 11 resolutions from 0.25 to 8.cohesion_score, over communities of 3+ nodes);--exclude-hubs, which takes nodes above it), the share of its neighbours that land in its own community, averaged over those hubs. It is descriptive, not a quality score. A hub's private members (e.g. the symbols a filecontains) belong with it, while the Feature request: CLI flags to handle super-hub-driven low-cohesion communities #919 symptom is a hub absorbing neighbours from other subsystems, and this number counts both.Result 1: full
cluster()at resolution 1.0 (uniform vs inverse-degree)(means over 12 seeds; ± shown for Q.
uniformdiffers from graphify's own weights only on B's 12 INFERRED edges, so B's counts here differ slightly from those on #2388.)At resolution 1.0, weighting gives more and smaller communities, lower Q, lower hub pull and higher cohesion. Raising the resolution does all of that too, so the fair comparison is at the same number of communities.
Result 2: at the same number of communities (first-pass partitioner)
The final
cluster()output isn't monotonic in resolution, because the split passes reshape it (see below), and that confounds a matched comparison. So this part calls the first-pass partitionergraphify.cluster._partitiondirectly, on the graphcluster()partitions (isolates removed). There, the community count rises with resolution for every scheme and backend; the one exception is a 0.2-community dip at the low end on A with Louvain, within the seed noise. Each metric is interpolated linearly against the mean community count, between the two resolutions that bracket the target.inverse-degree minus uniform (★ = |Δ| larger than √(SD₁² + SD₂²): a one-SD screen, not a significance test):
The other three weightings also change the sign of ΔQ with the granularity, and give a larger largest community in 23 of their 24 cells, so the smaller largest community on B at 50 is specific to inverse-degree. Over all 32 comparisons (4 weightings × 2 graphs × 2 granularities × 2 backends), size-weighted cohesion is lower in all 32, by 0.002–0.019, and beyond the combined seed SD in 23 of them. Hub pull is higher in 21 and lower in 11, which is descriptive only (see Setup).
How I read it:
A flag whose effect depends this much on the graph and the granularity wouldn't give users a reliable knob, and part of what it does is what
--resolutionalready does.Why (my reading, not a proof)
structural-triangleis not Berry et al.'s scheme, just a cheap check that "use local structure instead of degree" isn't an obvious win on these graphs either. 77–81% of their non-loop edges close at least one triangle, so the weight isn't degenerate. It shows the same kind of trade-offs, with no consistent gain.--resolutionand the split passescluster()passesresolutionto the first partition, but the split passes call_split_community(G, nodes), which re-partitions with_partition(subgraph)at the default 1.0. On graph B,v8gives more communities at 0.25 than at 1.0. With #2388 the count rises with the resolution up to about 4, and 1.0 is unchanged; the numbers, and a side effect on the 25% oversize cap, are on #2388 (#2388 (comment)).What this does not cover
cluster()level.Implications
--edge-weight-modeis worth adding: on these measurements it has no consistent benefit, and part of its effect overlaps with--resolution.--resolutionreach the final output, with the side effect on the oversize cap noted there.Scripts, the two graphs, the patches and the results, with a single
run.shthat regenerates every number above from public sources: https://gist.github.com/neo1777/9b68c8c24b553af37396781fe1f81da4