Skip to content

Fix Graphs.hasCycle missing cycles in undirected graphs - #8796

Closed
b84330808 wants to merge 1 commit into
google:masterfrom
b84330808:fix-undirected-hascycle
Closed

b84330808 wants to merge 1 commit into
google:masterfrom
b84330808:fix-undirected-hascycle

Conversation

@b84330808

Copy link
Copy Markdown
Contributor

Graphs.hasCycle returns false for some undirected graphs that do have a cycle:

MutableGraph<String> graph = GraphBuilder.undirected().build();
graph.putEdge("a", "b");
graph.putEdge("b", "c");
graph.putEdge("c", "a");
graph.addNode("x");
graph.addNode("y");
Graphs.hasCycle(graph); // false; 32.1.3 returns true

This came in with 63734b9 (iteration instead of recursion, to avoid StackOverflowError), so 33.3.0 through 33.6.0 are affected.

In subgraphHasCycle, when the next successor is the node we just came from (the undirected A->B->A case that canTraverseWithoutReusingEdge rejects), the loop falls through to stack.removeLast() and marks the node COMPLETE, so the rest of its successors are never visited. The recursive version only skipped that one successor. Connected graphs with a cycle still hit the numEdges >= nodes().size() shortcut, which is probably why the existing tests didn't catch it; it shows up once there are more nodes than edges.

The fix moves the continue out of the if, so only the rejected successor is skipped.

The new GraphPropertiesTest.hasCycle_threeCyclicEdgesAndIsolatedNode fails before the change and passes after, and the rest of com.google.common.graph passes. A randomized comparison against a plain recursive DFS on 20,000 small graphs (directed/undirected, with and without self-loops) found 456 wrong answers before the change and none after. I left android/ alone per CONTRIBUTING.

Unrelated, but nearby: hasCycle_deepPathGraph adds the 100,000-edge path to graphsToTest and then asserts on directedNetwork/undirectedNetwork, which are empty, so it doesn't actually check the deep-path graph case. Happy to fix that here or in a separate PR.

I used Claude Code to write this change.

Since the switch from recursion to iteration in 63734b9, `subgraphHasCycle`
pops a node and marks it `COMPLETE` as soon as it dequeues the node it was
reached from (the A->B->A case that `canTraverseWithoutReusingEdge` rejects),
so the node's remaining successors are never visited. In an undirected graph
whose successor order puts the parent first, cycles reachable only through
those successors are missed.

Connected undirected graphs with a cycle are caught by the
`numEdges >= nodes().size()` shortcut, so this shows up when the graph has
more nodes than edges, e.g. a triangle plus an isolated node.

Skip only the rejected successor and keep iterating, as the recursive
version did.
copybara-service Bot pushed a commit that referenced this pull request Oct 28, 2026
…rected graphs.

This will be fixed by cl/1009013320.

(progress toward fixing #8796)

RELNOTES=n/a
PiperOrigin-RevId: 1009103711
@cpovirk cpovirk self-assigned this Oct 28, 2026
@cpovirk cpovirk added type=defect Bug, not working as expected package=graph P2 labels Oct 28, 2026
copybara-service Bot pushed a commit that referenced this pull request Oct 28, 2026
…rected graphs.

This will be fixed by cl/1009013320.

(progress toward fixing #8796)

RELNOTES=n/a
PiperOrigin-RevId: 1009160348
copybara-service Bot pushed a commit that referenced this pull request Oct 29, 2026
… in light of the recently detected bug.

### `Graphs`

- We have been copying a `Set` to an `ArrayDeque` for no particular reason. We might as well use its `Iterator` to reduce how much we store.

### `GraphPropertiesTest`

- `hasCycle_deepPathGraph` was populating `graphsToTest` but then asserting on `directedNetwork` and `undirectedNetwork`, which are empty! (This seems like a sign that the tests should really be restructed more significantly....) This is my fault from 63734b9.
- Because of the recently detected bug (fix: cl/1009013320), our tests weren't actually traversing deeply into the graph, so they weren't actually proving that the switch from recursion to iteration was effective. Shame on me for not verifying that the tests failed before my change!
- Until cl/1009013320, all tests that checked for `hasCycle(undirectedGraph) == true` triggered [a shortcut](https://github.com/google/guava/blob/ff4f4e8dee0cad772ffa0256a93cae5b4aae695f/guava/src/com/google/common/graph/Graphs.java#L65), so we were not testing the part of the logic that lives in `subgraphHasCycle`. This has probably been broken forever.

Amazingly, all the new and fixed tests do pass without prod changes.

(noticed during investigation of #8796)

RELNOTES=n/a
PiperOrigin-RevId: 1009644539
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 package=graph type=defect Bug, not working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants