Skip to content

Fix k_components losing or truncating k-components - #8734

Merged
rossbar merged 1 commit into
networkx:mainfrom
jtorrents:fix-generate-partition
Jul 7, 2026
Merged

rossbar merged 1 commit into
networkx:mainfrom
jtorrents:fix-generate-partition

Conversation

@jtorrents

Copy link
Copy Markdown
Member

nx.k_components can return wrong results: it can miss a k-component entirely, report a strict subset of one, or replace a genuine k-component by lower-connectivity fragments. Differential fuzzing against the fixed implementation hits a divergence in roughly 1 in 60 random G(n, p) graphs (n = 12-20, p = 0.2-0.6), so this is not a corner case. Two independent root causes, both fixed here. The approximation in networkx/algorithms/approximation/kcomponents.py shares no code with these helpers and computes each level independently; it is not affected (verified on both regression graphs).

Bug 1: _generate_partition drops cutset nodes

When partitioning a graph by its minimum node cutsets, the helper removed the union of all cutsets in a single pass and re-attached each cutset node only to the resulting components it has a direct neighbor in. A cutset node whose neighbors all belong to other cutsets is attached to nothing and silently vanishes, so the recursion never examines the intact subgraph and the k-component containing that node is lost or truncated.

Reproducer (first regression test): two icosahedra A and B (5-connected, so each is a 5-component) joined through three connector nodes, plus one node that makes the whole graph 4-connected. In the recursion, the subproblem A + connectors has minimum 3-cutsets {0, 1, 2}, {3, 4, 5} and {6, 7, 8} (the connector neighborhoods). Removing all nine nodes at once leaves cutset nodes 1 and 6 with no surviving neighbors: the "partition" is a single 10-node part and A is never seen intact. Result: k_components reports only one of the two 5-components.

The fix applies cutsets one at a time, which is what Moody and White describe (appendix A, step 3): removing a single cutset splits the current part into connected components; each component plus its adjacent cutset nodes becomes a new part; remaining cutsets are applied recursively inside each part (iteratively, with an explicit stack). This is correct by Menger's theorem: a j-component with j > k cannot be disconnected by removing k < j nodes, so it survives intact inside one part at every step.

Bug 2: _reconstruct_k_components lets fragments replace a component

The recursive-cut loop records candidate components whenever connectivity rises above the parent level, which admits non-maximal fragments of a higher-k component. _reconstruct_k_components is supposed to clean this up when propagating components down the levels, but its filter

nodes_at_k = set.union(*k_comps[k])
to_add = [c for c in result[k + 1] if any(n not in nodes_at_k for n in c)]

skips a component from level k+1 whenever the union of the level-k candidates covers its nodes, even when no single candidate contains it.

Reproducer (second regression test): a 7-connected G(16, 0.6) graph whose whole node set is the unique k-component for every k <= 7. The recursion records 5-connected fragments whose union covers all 16 nodes, and the whole-graph component silently disappears from level 5 downward, replaced by its fragments. The fix tests containment in a single component: not any(c <= comp for comp in k_comps[k]).

On current main this second bug is masked by the first one: the dropped nodes keep fragment unions from covering everything, which is why both fixes land together.

Tests

Two regression tests are added to the connectivity test suite, one per root cause. The same two graphs are also added as tests to the approximation test suite (networkx/algorithms/approximation/tests/test_kcomponents.py): the approximation shares no code with the fixed helpers and is not affected by either bug, and it recovers the exact results on both graphs -- these tests pin that behavior down.

Performance note

Correctness costs some speed on mid-size inputs, because the old code's dropped nodes and degree-filtered parts made subproblems artificially small: powerlaw_cluster_graph(500, 5, 0.3) goes from 15.6s to 28.1s and n=1000 from 74s to 171s on the same machine. The test-suite fixtures show no slowdown. Reintroducing degree-based part shrinking with a connectivity-safe re-attachment is possible follow-up work.

AI disclaimer: Once I detected the problem, Claude helped a lot by writing and running the fuzzing that pin pointed the exact cause of the problem. Also it designed the two icosahedra example in the tests and provided a draft of the implementation. I reviewed carefully, did some corrections, and validated all the examples, code and tests.

_generate_partition removed the union of all minimum cutsets in a
single pass, dropping cutset nodes whose neighbors all belong to other
cutsets; apply cutsets one at a time as in Moody and White (2003),
appendix A. _reconstruct_k_components skipped propagating a component
down a level whenever the union of lower-level candidates covered its
nodes, letting non-maximal fragments replace a genuine k-component;
test containment in a single component instead.

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for this @jtorrents !!
It's pretty hairy, with one fix uncovering another bug elsewhere. Nice work!

I've verified that the the 1st new test fails on main and the 2nd passes. And once
the 1st fix is in the 1st test passes and the 2nd fails. The PR green check shows that both tests pass with both fixes.

I am going to approve these changes based on reading through the comments and code and it seems reasonable. I have not checked for corner cases where this might go wrong.

As for speed, we should profile it to see what to improve, but I suspect the large number of subset operations like c <= comp are taking a lot of time. If that turns out to be the bottleneck, it might be tricky to speed things up. Your suggestion of follow-up using degree based part shrinking with safe reattachment seems reasonable. And rightly put off for another PR.

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Indeed, thanks @jtorrents - I spent some time looking at this yesterday and generally LGTM, though I can't claim to have any special familiarity with this class of problems. One thing that immediately jumps out how highly inter-dependent the connectivity code is - i.e. the number internal "private" functions and the dependence on other high-order functionality in networkx (e.g. flow) which makes regression testing difficult and leads to the potential for "deep" bugs like these. One worthwhile activity would be trying to build up the unit testing around some of the internal functionality to clearly define expected behaviors. Anyways - that's not relevant here, thanks for the fix!

@rossbar
rossbar merged commit d808179 into networkx:main Jul 7, 2026
43 checks passed
@dschult dschult added this to the 3.7 milestone Jul 7, 2026
sumedhabhattacharya0711-spec pushed a commit to sumedhabhattacharya0711-spec/networkx that referenced this pull request Jul 7, 2026
_generate_partition removed the union of all minimum cutsets in a
single pass, dropping cutset nodes whose neighbors all belong to other
cutsets; apply cutsets one at a time as in Moody and White (2003),
appendix A. _reconstruct_k_components skipped propagating a component
down a level whenever the union of lower-level candidates covered its
nodes, letting non-maximal fragments replace a genuine k-component;
test containment in a single component instead.
@jtorrents

Copy link
Copy Markdown
Member Author

Thanks @dschult and @rossbar for the careful reviews, and for verifying the tests against each fix independently!

@dschult , on performance: I profiled the merged code on powerlaw_cluster_graph(500, 5, 0.3) (the graph from the PR's performance note, ~28s plain). The subset operations turn out to be negligible: neither the c <= comp checks nor _consolidate show up anywhere near the top of the profile. Where the time actually goes:

  • ~52% is max-flow: 16,845 edmonds_karp calls, driven by all_node_cuts and node_connectivity.
  • ~30% is _generate_partition, and almost all of that is the repeated connected_components BFS over candidate parts (~54,000 calls), not set arithmetic.

So the lever is not making the set operations faster but making the graphs that reach the flow machinery smaller and fewer. This is the same principle behind the approximation in networkx/algorithms/approximation/kcomponents.py (Torrents & Ferraro 2015): by Whitney's theorem every k-component is nested inside a k-core and a bicomponent, so cheap k-core and bicomponent computations can drastically narrow down where the expensive connectivity work happens. Sinkovits, Moody, Oztan & White (2016, J. Comput. Sci. 17, 62-72) push the same kind of reduction further (clique condensation, k-cores, bicomponents, applied iteratively) while keeping the result exact. That's the follow-up I'm drafting, rather than re-introducing degree-based shrinking piecemeal. On this same benchmark graph the draft is currently ~8x faster than the fixed code (3.4s vs 28s) while returning identical decompositions. I'll open a PR once it settles.

Incidentally, this PR itself adds a small data point in that direction: the two regression graphs were also added to the approximation's test suite, where it recovers the exact decompositions: the reduction-first design shares none of the recursive-partition machinery where both bugs lived.

@rossbar , fully agree. Both bugs lived in private helpers (_generate_partition, _reconstruct_k_components) whose contracts were only implicit, and neither could be caught by testing k_components end-to-end on the small classic graphs alone. Two things that would have caught them, which I'd like to add in a follow-up:

  1. Unit tests for the internal helpers with their contracts stated (e.g. "_generate_partition never loses a node"; "every part is a strict subset of the input part").
  2. Differential fuzzing, which is how I pin pointed these bugs in the first place: comparing k_components against an independent brute-force implementation on small random graphs (divergence showed up in roughly 1 in 60 G(n, p) samples). Maybe a seeded, bounded version of that could run in the regular test suite?

@rossbar

rossbar commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

+1 for unit tests of "private"/internal functions - that is an obvious improvement and it fits perfectly within the existing test framework.

Re: fuzzing - this is a larger question that has been come up in the past and is related to other testing ideas, e.g. property based testing, integration tests, tests for boundedness etc. All of these things are valuable, but exactly how they should be implemented/where they should live is less clear. The only mechanism we have for managing tradeoffs in test time/complexity within the networkx test suite itself is the pytest.mark.slow mechanism - which is an important feature but test runtime is not the only consideration.

@jtorrents

Copy link
Copy Markdown
Member Author

@rossbar , understood! I hope to find time soon to add unit tests for internal functions on flow, connectivity, and friends. Actually, the bug in all_node_cuts was also related to the mis-use of the internal build_auxiliary_node_connectivity function.

Regarding fuzzing: makes sense. Thanks!

jtorrents added a commit to jtorrents/networkx that referenced this pull request Jul 15, 2026
Replace the parametrized contract test for _generate_partition with a
single explicit example, as suggested in review. The Davis Southern
Women graph is biconnected, so no bicomponent loop or conditionals are
needed, and every expected value is stated explicitly: the node
connectivity, the two minimum cutsets, and the exact four parts. The
pre-networkxgh-8734 code silently dropped the three women that attended only
cutset events. Also drop a redundant comment block above the
private-helper unit tests.
dschult pushed a commit that referenced this pull request Jul 24, 2026
…s the private helpers (#8753)

* Drop nested components in reconstruction, add doctest

A single _consolidate pass merges on pairwise overlaps of its input
sets, so a level can still end up containing a component that is a
strict subset of a merged one: a propagated (k+1)-level component
sharing fewer than k nodes with each of two level-k candidates is not
merged with their union. Drop such nested sets at each level; every
emitted set is k-connected, so a nested one is never maximal. This
completes the more permissive propagation introduced by #8734 (which
is preserved verbatim) and turns the never-observed redundant-subset
scenario into a structural impossibility. No known construction
reaches it; validated with the full suite plus differential and
brute-force fuzzing.

Also turn the k_components docstring example into a real doctest.

* Add unit tests for private k-components helpers

Follow-up to the #8734 review discussion: both bugs fixed there lived
in private helpers whose contracts were only implicit, and neither was
reachable by end-to-end tests on the small classic graphs alone. State
the contracts explicitly and test the helpers directly:

- _reconstruct_k_components propagates a (k+1)-level component that
  spans several k-level candidates (the #8734 fix), drops a component
  nested inside a consolidated merge (the fix in this branch; the test
  synthesizes the input that graph-level fuzzing never produced and
  fails without the fix), and never emits a component that is a strict
  subset of another at the same level.
- _generate_partition never loses a node, yields only strict subsets of
  the input, and every part induces a connected subgraph.

* Remove slow markers from k_components tests

The three pytest.mark.slow markers predate the all_node_cuts fix
(#8586), which is what made these tests slow. The whole file now runs
in under 2 seconds with --runslow and the slowest single test
(test_random_gnp[50-0.2]) takes under a second, so run the complete
k_components suite by default.

* Use the Davis Southern Women graph in the partition test

Replace the parametrized contract test for _generate_partition with a
single explicit example, as suggested in review. The Davis Southern
Women graph is biconnected, so no bicomponent loop or conditionals are
needed, and every expected value is stated explicitly: the node
connectivity, the two minimum cutsets, and the exact four parts. The
pre-gh-8734 code silently dropped the three women that attended only
cutset events. Also drop a redundant comment block above the
private-helper unit tests.

* Restore the slow markers on the k_components tests

This reverts commit ae5d6af, as agreed
in review: keep the slow marks for now, and revisit removing them in a
separate PR once the k_components work has been merged, so that the
effect on CI test balance can be evaluated.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

3 participants