Skip to content

perf(cluster): use to_undirected(as_view=True) in cluster() to avoid full-graph deepcopy - #5621

Closed
Gaurav-meena95 wants to merge 3 commits into
Graphify-Labs:v8from
Gaurav-meena95:perf/cluster-undirected-view
Closed

Gaurav-meena95 wants to merge 3 commits into
Graphify-Labs:v8from
Gaurav-meena95:perf/cluster-undirected-view

Conversation

@Gaurav-meena95

Copy link
Copy Markdown
Contributor

What does this PR do?

Switches G.to_undirected() in cluster() (graphify/cluster.py) to G.to_undirected(as_view=True) and accepts collections.abc.Mapping edge attribute views (UnionAtlas) in _sorted_native_edges(), eliminating full-graph copy.deepcopy on every DiGraph clustering run.

Problem

Now that cluster() no longer mutates G in place, the only remaining copy.deepcopy in cluster(DiGraph) came from G.to_undirected() (which defaults to as_view=False and deep-copies every node and edge attribute dict). Profiling cluster() on a 28.3k-node / 60.6k-edge DiGraph showed DiGraph.to_undirected spent 1.311s (54.2% of cProfile runtime) across 89,064 copy.deepcopy calls.

Details

Target Previous Updated Rationale
cluster() (graphify/cluster.py) G.to_undirected() G.to_undirected(as_view=True) Avoid deep-copying all node/edge dicts on read-only DiGraph clustering
_sorted_native_edges() (graphify/cluster.py) if type(attrs) is not dict: return None if type(attrs) is not dict and not isinstance(attrs, collections.abc.Mapping): return None Allow undirected UnionAtlas edge attribute views on the _native_leiden fast path
tests/test_cluster.py No guard against deepcopy in cluster(DiGraph) Added test_cluster_digraph_uses_undirected_view_without_deepcopy Pin zero-deepcopy behaviour and identical community output

Type of change

  • Refactor / Performance
  • Tests or CI

How was this tested?

uv run pytest tests/test_cluster.py tests/test_pipeline.py tests/test_report.py -q
uv run ruff check graphify/cluster.py tests/test_cluster.py
PATH="$(pwd)/.venv/bin:$PATH" uv run pre-commit run --all-files
uv run graphify update .

@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @Gaurav-meena95. 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.11 and 3.13, and that the change keeps extraction deterministic.

@github-actions github-actions Bot added the contributor Pull request from a returning community contributor label Nov 29, 2026

@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 review View in Graphify

Review before merging · Merge confidence 4/5

1 bug · 4 possible issues to check · High impact

cluster() now uses an undirected view for directed graphs unless reciprocal edges have conflicting weight or confidence values.

P2  Custom reciprocal weights can make clustering crash · cluster.py:444

4 possible issues we couldn't confirm
  • Directed graphs with hub exclusion may crash because the new undirected view is read-only once clustering removes nodes · graphify/cluster.py:505
  • Directed graphs clustered through a view share edge attribute dicts with the caller, so edge weight changes leak back into the caller's grap · graphify/cluster.py:505
  • Test patches deepcopy on nx.classes.digraph, so it errors instead of checking the no-copy rule when networkx does not expose that name · tests/test_cluster.py:504
  • +1 more in Graphify

They don't change the score.

Code graph · 917 functions depend on this change
  • 1 function became more coupled. cluster() (98 callers).
  • 25 of 652 test files are affected by this change.
  • Gate, test list and every flagged function: in the Graphify check.

Reviewed a2384ca · 4 earlier findings not re-checked

Comment thread graphify/cluster.py
Comment on lines 477 to 478
if G.number_of_nodes() == 0:
return {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug  Reciprocal edges can use the opposite direction’s weight

When a directed graph has both a→b and b→a with different attributes, clustering can use a different edge weight than before.

Preserve the prior copied conversion in cluster().

Evidence · checked against the code
  • Independent source review: Inspected the added test: its directed graph has no reciprocal pair, and it compares cluster(G) with cluster(G.to_undirected()) at the same revision, so it does not test conflicting reciprocal attributes against the previous conversion. The copied-conversion behavior is consistent with the repository's description of reciprocal-edge folding, and no guard on the clustering path preserves the prior attributes.
  • Also reported as: Clustering now reads edge attributes through a live view, so reciprocal directed edges with different weights can be partitioned differently
Prompt to fix with AI
In graphify/cluster.py, cluster (lines 477-478):
Problem: Reciprocal edges can use the opposite direction’s weight
Fix it at the cause, and add a test that fails without the fix.

Graphify · Checked against the code · View in Graphify

Comment thread graphify/cluster.py Resolved
Comment thread graphify/cluster.py
Comment on lines +441 to +444
return any(v in pred[u] for u, nbrs in adj.items() for v in nbrs)
for u, nbrs in adj.items():
pu = pred[u]
for v, data in nbrs.items():

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2  Custom reciprocal weights can make clustering crash

A directed graph with reciprocal edges and a weight whose comparison raises an exception can make cluster() fail before partitioning.

Catch RuntimeError in _has_conflicting_reciprocal_edges in graphify/cluster.py.

Evidence · checked against the code

Expected: Directed-to-undirected conversion should proceed without comparing those custom weights in a way that lets the exception escape.
Actually: The helper's != comparison raises, and its handler does not catch RuntimeError, so cluster() exits before partitioning.

  • Independent source review: The existing test covers a ValueError from array-like edge metadata, but that metadata is not compared by the helper; its exception behavior does not cover a RuntimeError from a reciprocal weight object's __ne__. The standard conflicting-weight test uses ordinary floats and does not refute the custom-object case.
Prompt to fix with AI
In graphify/cluster.py, _has_conflicting_reciprocal_edges (lines 441-444):
Problem: Custom reciprocal weights can make clustering crash
Expected: Directed-to-undirected conversion should proceed without comparing those custom weights in a way that lets the exception escape.
Actually: The helper's `!=` comparison raises, and its handler does not catch `RuntimeError`, so `cluster()` exits before partitioning.
Fix it at the cause, and add a test that fails without the fix.

Graphify · Checked against the code · View in Graphify

safishamsi pushed a commit that referenced this pull request Nov 30, 2026
safishamsi added a commit that referenced this pull request Nov 30, 2026
Extractor accuracy (Swift #5641, Apex #5627, Python #5647, TypeScript
#5604/#5614/#5612, Bash caller-var #5602), GitHub Actions run-step
extraction (#5603), incremental correctness (#5634/#5638/#5636), symlink
and semantic-cache fixes (#5617/#5618), export/report hardening and perf
(#5643/#5644/#5645/#5646/#5619/#5620/#5621), and CLI/docs/skill/install
work (#5629/#5628/#5626/#5624/#5623/#5625/#5642/#5583). AST cache schema
59 to 60; Swift/Apex/Python/Bash/GHA inputs re-extract on first build.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@safishamsi

Copy link
Copy Markdown
Member

Landed in v0.9.124 (just released to PyPI), cherry-picked with your authorship preserved so it shows under your name in the history. Thanks @Gaurav-meena95 for using an undirected view in cluster() to avoid the full-graph deepcopy — verified green in the full suite and, where applicable, smoke-tested against the published package. 🙏

@safishamsi safishamsi closed this Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributor Pull request from a returning community contributor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants