Repository navigation
Fix k_components losing or truncating k-components - #8734
Conversation
_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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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!
_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.
|
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
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 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 (
|
|
+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 |
|
@rossbar , understood! I hope to find time soon to add unit tests for internal functions on flow, connectivity, and friends. Actually, the bug in Regarding fuzzing: makes sense. Thanks! |
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.
…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.
nx.k_componentscan 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 innetworkx/algorithms/approximation/kcomponents.pyshares no code with these helpers and computes each level independently; it is not affected (verified on both regression graphs).Bug 1:
_generate_partitiondrops cutset nodesWhen 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 + connectorshas 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_componentsreports 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_componentslets fragments replace a componentThe 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_componentsis supposed to clean this up when propagating components down the levels, but its filterskips 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.