Skip to content

Feature request: CLI flags to handle super-hub-driven low-cohesion communities #919

Closed

Description

@neo1777

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:

  1. The cohesion threshold doesn't trigger. The actual cohesion of Community 0 is 178 / 3655 = 0.0487. cohesion_score() at cluster.py:166 returns round(actual / possible, 2), producing 0.05. The threshold check at cluster.py:128 (cohesion_score(G, nodes) < _COHESION_SPLIT_THRESHOLD) becomes 0.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.)

  2. 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 at cluster.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:

  1. --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() in cluster.py. Percentile is preferred over an absolute degree threshold because hub degree scales with corpus size.

  2. --algorithm <leiden|louvain> plus --resolution <N> — expose parameters that graspologic.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.

  3. --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.json to 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

  • graphifyy 0.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

  1. safishamsi commented on May 17, 2026

    @safishamsi
    Member

    Fixed in v0.8.10 — three things shipped: (1) cohesion rounding bug fixed so the split threshold actually fires for borderline communities; (2) --resolution N added to extract and cluster-only for both Leiden and Louvain backends; (3) --exclude-hubs P added — 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.

  2. neo1777 commented on May 18, 2026

    @neo1777
    ContributorAuthor

    Tested on v0.8.11 against the original codebase across multiple percentile values to characterize how the new knob behaves:

    Run Hubs excluded Community 0 size Community 0 cohesion Total communities
    pre-fix v0.8.5 (no flag, rounding bug) 0 86 0.0487 ~12–20
    v0.8.11 --exclude-hubs 99 ~15 (top 1%) 39 0.06 261
    v0.8.11 --exclude-hubs 95 ~75 (top 5%) 31 0.10 518
    v0.8.11 --exclude-hubs 90 ~150 (top 10%) 20 0.11 678

    At --exclude-hubs 99 the 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.tsx reattaches 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> --help because 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.

  3. neo1777 commented on Oct 1, 2026

    @neo1777
    ContributorAuthor

    Option 3 (--edge-weight-mode) measured on two codebases: no consistent gain over --resolution

    On #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

    Setup

    Result 1: full cluster() at resolution 1.0 (uniform vs inverse-degree)

    graph backend scheme communities largest Q hub pull cohesion
    A Leiden uniform 21.3 76.9 0.620 ± 0.005 0.438 0.113
    A Leiden inverse-degree 27.5 64.2 0.605 ± 0.004 0.398 0.144
    A Louvain uniform 21.2 79.4 0.617 ± 0.008 0.445 0.113
    A Louvain inverse-degree 27.0 69.0 0.609 ± 0.004 0.413 0.141
    B Leiden uniform 151.3 104.7 0.617 ± 0.009 0.316 0.135
    B Leiden inverse-degree 318.3 76.7 0.547 ± 0.003 0.155 0.209
    B Louvain uniform 148.4 136.0 0.625 ± 0.010 0.353 0.131
    B Louvain inverse-degree 311.6 78.0 0.550 ± 0.001 0.155 0.205

    (means over 12 seeds; ± shown for Q. uniform differs 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 partitioner graphify.cluster._partition directly, on the graph cluster() 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):

    graph communities backend ΔQ Δ largest Δ hub pull
    A 20 Leiden −0.031 ★ +68.3 ★ +0.092 ★
    A 20 Louvain −0.030 ★ +60.5 ★ +0.093 ★
    A 40 Leiden +0.010 ★ +6.3 ★ +0.062 ★
    A 40 Louvain +0.010 ★ +6.5 ★ +0.043 ★
    B 50 Leiden −0.009 ★ −24.8 ★ −0.054 ★
    B 50 Louvain −0.011 ★ −35.1 ★ −0.072 ★
    B 100 Leiden +0.009 ★ +0.2 +0.001
    B 100 Louvain +0.007 ★ −1.5 −0.001

    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 --resolution already does.

    Why (my reading, not a proof)

    • Fortunato & Barthélemy (PNAS 104(1):36–41, 2007) show that modularity optimisation may fail to resolve modules below a scale that depends on the total number of links and on how interconnected the modules are. Berry et al. (Phys. Rev. E 83, 056119, 2011; arXiv:0903.1072) extend this to weighted graphs, where communities with less than √(Wε/2) total edge weight may go unresolved (W = total edge weight, ε = the heaviest inter-community edge). They show that weights derived to keep ε low let small communities be resolved; their title calls it tolerating the limit.
    • Degree-based weighting doesn't target ε: it lightens every edge at a hub, inside the hub's community as much as across it, which fits the mixed result above.
    • structural-triangle is 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.

    --resolution and the split passes

    cluster() passes resolution to 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, v8 gives 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

    • Two AST-only code graphs, without semantic or LLM edges, measured on 0.9.71 only.
    • My own simple weight formulas, not Berry et al.'s scheme.
    • Two granularities per graph for Result 2; hub pull is a descriptive proxy I defined.
    • Result 2 is at the partitioner level; Result 1 is at the full cluster() level.

    Implications

    Scripts, the two graphs, the patches and the results, with a single run.sh that regenerates every number above from public sources: https://gist.github.com/neo1777/9b68c8c24b553af37396781fe1f81da4

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions