Skip to content

fix(cluster): keep hub-only neighbours with their hub under --exclude-hubs - #3933

Closed
neo1777 wants to merge 1 commit into
Graphify-Labs:v8from
neo1777:fix/exclude-hubs-stranded-neighbours
Closed

neo1777 wants to merge 1 commit into
Graphify-Labs:v8from
neo1777:fix/exclude-hubs-stranded-neighbours

Conversation

@neo1777

@neo1777 neo1777 commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Follow-up to #919, where --exclude-hubs came from.

Related: #446 proposes pruning degree-1 leaves attached to a hub before partitioning in the default path and reattaching them afterwards. This PR is narrower. It only fixes the --exclude-hubs path, where nodes whose only neighbours are the excluded hubs are already left out of the partition and currently come back as singletons. I haven't tested how it would interact with that proposal, which has no PR yet. #1800 shows --exclude-hubs in regular use, and community counts there will change with this fix (fewer singletons).

With --exclude-hubs P, cluster() removes the hubs from the subgraph it partitions (cluster.py#L272-L275), then reattaches each hub to its neighbours' majority community (#L289-L305).

A node whose only neighbours are hubs is not an isolate in G, so it skips the isolate handling (#L273). But it has degree 0 in the subgraph that is actually partitioned (#L274-L275), so it comes back from the partition as a singleton community, cut off from the only nodes it connects to. In practice they are mostly nodes tied to a hub by contains, imports or rationale_for edges: local symbols of a hub file with no other edge, dependency entries of a manifest, rationale notes. For example:

Minimal reproducer:

import networkx as nx
from graphify.cluster import cluster

G = nx.Graph()
for group in (["a1", "a2", "a3", "a4"], ["b1", "b2", "b3", "b4"]):
    G.add_edges_from((u, v) for i, u in enumerate(group) for v in group[i + 1:])
G.add_edges_from(("H", n) for n in ["a1", "a2", "a3", "a4", "b1", "l1", "l2", "l3"])  # l1-l3 hang off H only
print(sorted(cluster(G, exclude_hubs_percentile=90).values(), key=len))
# v8 (0.9.71):  [['l1'], ['l2'], ['l3'], ['b1', 'b2', 'b3', 'b4'], ['H', 'a1', 'a2', 'a3', 'a4']]
# this branch: [['b1', 'b2', 'b3', 'b4'], ['H', 'a1', 'a2', 'a3', 'a4', 'l1', 'l2', 'l3']]

Measured on 0.9.71 (d6eaa8a), graphs built with graphify extract <dir> --code-only and loaded the way cluster-only loads them. "Stranded" means singletons whose non-self neighbours are all excluded hubs.

graphify's own graphify/ package (3,182 nodes, 7,784 edges):

--exclude-hubs hubs Leiden: communities Leiden: stranded Louvain: communities Louvain: stranded
— 0 156 → 156 0 → 0 146 → 146 0 → 0
99 32 293 → 247 64 → 0 289 → 237 64 → 0
95 158 616 → 357 279 → 0 609 → 357 279 → 0
90 297 946 → 486 479 → 0 948 → 488 477 → 0

The React/TS codebase from #919, at its current state (neo1777/marzio1777 @ 0aa0333, 626 nodes; #919 used an older, larger graph):

--exclude-hubs hubs Leiden: communities Leiden: stranded Louvain: communities Louvain: stranded
— 0 21 → 21 0 → 0 24 → 24 0 → 0
99 7 47 → 22 25 → 0 49 → 22 25 → 0
95 32 100 → 27 76 → 0 100 → 27 76 → 0
90 62 192 → 41 154 → 0 193 → 41 153 → 0

(before → after. Each cell is a single cluster() run with graphify's fixed seed (42), as a user gets it. Leiden = graspologic-native 1.3.1, Louvain = the networkx fallback. "hubs" = graphify's own rule, degree above the percentile. The one singleton left on graphify's graph is a true isolate, there before and after.)

On graphify's graph the community count drops by less than the number of stranded nodes (Leiden, p99: 293 − 64 = 229, but 247 measured). The hub communities, grown by their former singletons, are split again by the existing passes: with Leiden, 19, 20 and 19 more communities come from split passes than on v8 at p99, p95 and p90 (3 more at p95 and p90 on the #919 codebase). That accounts for most of the gap. The rest comes from the partitioner itself: at p99 one stranded node has a self-loop that on v8 was part of the first-pass input, and removing a single edge is enough to change the first partition slightly, so single-run differences of a community or two are not attributable to the fix.

On #919 I reported 261 / 518 / 678 communities at p99 / 95 / 90 and read the growth as over-splitting. That was a different graph, built with 0.8.11 on an older state of the codebase, and I didn't keep it, so I can't say how much of that growth was stranded nodes.

The change. Nodes whose non-self neighbours are all excluded hubs are held out of the partition. After the hubs are reattached, they are placed with the same majority vote the hubs use, with ties going to the lowest community id, as for hubs. Since all their neighbours are hubs and every hub is placed by then, the vote always has a winner. They are placed in sorted order, so the result stays deterministic. The cluster() docstring now mentions it.

Type of change

  • Bug fix

Verification & Invariants

Invariant: excluding a hub from partitioning must not leave the nodes that connect only to it in communities of their own.

What changes in behaviour, only when --exclude-hubs is set:

  • the stranded nodes join their hub's community instead of staying alone;
  • a hub's placement can change too. On v8 each stranded singleton was a community that could win a hub's majority vote. Now only real communities vote.
  • a hub's community grows by its private members, so it can now cross the oversize or cohesion threshold and be split by the existing passes.

What doesn't change:

  • default output (no --exclude-hubs) is identical;
  • true isolates, and nodes whose only edge is a self-loop, keep their own community.

Not covered: two or more nodes that hang off a hub and link to each other (a pair, a chain). They form their own component in the partitioned subgraph, so they come back as a small community rather than a singleton, and they are left as they are.

  • Read CONTRIBUTING.md.
  • Reproduced the issue and identified the invariant.
  • Smallest fix: two blocks in cluster() plus a docstring line, no signature change.
  • Regression tests in a new tests/test_cluster_exclude_hubs.py, kept separate so it doesn't collide with other open PRs that touch tests/test_cluster.py, e.g. fix(cluster): honor --resolution on the community split passes #2388:
    • test_exclude_hubs_keeps_hub_only_neighbours_with_their_hub fails on v8;
    • ..._hub_only_neighbour_with_self_loop_joins_its_hub fails on v8;
    • three boundary tests pass before and after: true isolates, self-loop-only nodes, and percentile 100 (no hubs, identical to the default).
  • Description kept in sync with the implementation.
  • Limitations documented above.

How was this tested?

uv run pytest tests/test_cluster_exclude_hubs.py tests/test_cluster.py tests/test_god_nodes_exclude_hubs.py -q   # 28 passed, 2 skipped
# same three files with graspologic-native installed (Leiden path)                                           # 28 passed, 2 skipped
uv run pytest tests/ -q                          # 6013 passed, 101 skipped, 23 failed (see below)
uv run ruff check .                              # all checks passed
uv run pyright graphify/cluster.py               # same 3 errors as on v8, none new

The full-suite failures are the Erlang, R, Solidity, VB.NET and ollama tests (openai and the optional grammars aren't installed without --all-extras). They fail identically on a clean v8. I also applied this branch together with #2388 on d6eaa8a: it merges cleanly and the cluster tests pass.

The before/after tables come from a small script that runs cluster() at each percentile and counts the stranded singletons: https://gist.github.com/neo1777/9b68c8c24b553af37396781fe1f81da4 (with a run.sh that regenerates every number in this description from public sources).

The branch is based on v8 at 1cd9a36 (0.9.72); the measurements above ran on 0.9.71 (d6eaa8a), and cluster.py is unchanged between the two.

Environment: Python 3.12.3, uv 0.11.23, Linux Mint 22.3. The "before" columns come from graphifyy 0.9.71 from PyPI, the "after" columns from this branch, on the same graphs.

Graphify-specific checklist

  • Generated skill artifacts: not touched.
  • Deterministic: stranded nodes are placed in sorted order; the new tests pass under PYTHONHASHSEED 0, 1, 2, 42.
  • No unsafe interpolation.
  • No API keys or local-only graph data.
  • AI authorship disclosed in the commit (Co-Authored-By).

…-hubs

With exclude_hubs_percentile set, excluded hubs are removed from the
graph that gets partitioned. A node whose only neighbours are hubs (e.g.
a local symbol of a hub file, or a dependency entry of a manifest) is
then isolated in that subgraph and came back as a singleton community,
while the hub itself was reattached by majority vote. Every such node
ended up cut off from the only node it connects to, and the community
count inflated with singletons.

Such nodes are now held out of the partition and placed after the hubs
are reattached, with the same majority vote the hubs use; since all of
their neighbours are hubs and every hub is placed by then, the vote
always has a winner. A self-loop does not count as a neighbour. True
isolates, and nodes whose only edge is a self-loop, are unchanged.

Follow-up to Graphify-Labs#919, where --exclude-hubs was introduced. The cluster()
docstring now says so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@neo1777
neo1777 requested a review from safishamsi as a code owner September 29, 2026 21:47
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @neo1777. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.10 and 3.13, and that the change keeps extraction deterministic.

@graphify-labs graphify-labs Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify reviewed this change.

Looks safe to merge — no coupling regressions and no blocking issues, checked against the code graph (not a self-assessment).


Graphify review — findings

Fixes cluster under exclude_hubs_percentile so nodes whose only neighbours are excluded hubs no longer come back as singleton communities. They are now held out of the partition and join their hub's community by the same majority vote. Self-loops don't count as neighbours, and true isolates and self-loop-only nodes still get their own communities.

No blocking issues surfaced.

Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 526 functions depend on the 33 functions this change touches.

Health — this change adds coupling hotspots:

  • new: _rebuild_code() — 147 callers, 56 callees
  • new: main() — 98 callers, 3 callees
  • new: dispatch_command() — 2 callers, 126 callees
  • new: _make_graph() — 37 callers, 6 callees
  • new: cluster() — 69 callers, 3 callees
  • new: run_pipeline() — 8 callers, 13 callees
  • new: make_inputs() — 16 callers, 5 callees
  • new: suggest_questions() — 11 callers, 4 callees
  • …and 13 more — each is listed as a finding

Verification — 526 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 315 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

14 of 309 test file(s) selected (5%) via static blast radius.

  • tests/test_analyze.py — impact
  • tests/test_build.py — impact
  • tests/test_cli_export.py — impact
  • tests/test_cluster.py — impact
  • tests/test_cluster_exclude_hubs.py — impact, changed-test
  • tests/test_community_hub_labels.py — impact
  • tests/test_confidence.py — impact
  • tests/test_export.py — impact
  • tests/test_pipeline.py — impact
  • tests/test_reflect.py — impact
  • tests/test_report.py — impact
  • tests/test_serve.py — impact
  • tests/test_serve_http.py — impact
  • tests/test_watch.py — impact

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

· 21 more finding(s) on lines outside this diff (see the check run).

safishamsi added a commit that referenced this pull request Sep 30, 2026
Solidity free functions (#3906), VB.NET qualified calls (#3909), Astro
frontmatter-only AST pass (#3902), surprise bonus/reason alignment (#3934),
exclude-hubs stranded-neighbour (#3933), graph-DB push index (#3957),
label retry keep-named (#3956), stale-hook status (#3951), virtual-workspace
Cargo.toml skip (#3930), and symlinked-instructions install/uninstall
handling (#3950/#3953).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@safishamsi

Copy link
Copy Markdown
Member

Shipped in v0.9.73 (now on PyPI) via an authorship-preserving cherry-pick, so your commit keeps contributor-graph credit. Thanks @neo1777!

Release: https://github.com/Graphify-Labs/graphify/releases/tag/v0.9.73

@safishamsi safishamsi closed this Sep 30, 2026
@neo1777

neo1777 commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for shipping both so quickly, and for keeping the authorship — much appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants