Skip to content

Fix Bellman-Ford false cycle detection for neighbor-only vertices - #2786

Open
Miladkhoshdel wants to merge 2 commits into
keon:mainfrom
Miladkhoshdel:fix/bellman-ford-vertex-count
Open

Miladkhoshdel wants to merge 2 commits into
keon:mainfrom
Miladkhoshdel:fix/bellman-ford-vertex-count

Conversation

@Miladkhoshdel

@Miladkhoshdel Miladkhoshdel commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2785

Bug

Both bellman_ford and bellman_ford_paths incorrectly report a negative cycle when a destination vertex appears only as a neighbor.

For example:

graph = {"a": {"b": 1}}

bellman_ford(graph, "a")
# Actual: False
# Expected: True

bellman_ford_paths(graph, "a")
# Actual: (None, None, True)
# Expected: ({"a": 0, "b": 1}, {"a": None, "b": "a"}, False)

This graph contains two vertices and one positive edge, with no cycle.

Initialization correctly discovers both vertices. However, both functions use len(graph) to calculate the vertex count, counting only top-level dictionary keys.

Here, that count is 1, so the V - 1 relaxation loop performs zero passes. The distance to b remains infinity, and the subsequent negative-cycle check incorrectly interprets the unprocessed edge as evidence of a negative cycle.

For longer paths, insufficient relaxation passes can also make results depend on dictionary insertion order.

Fix

Use len(distance) to count vertices in both functions. The initialized distance dictionary includes neighbor-only vertices, providing the correct number of relaxation passes before checking for negative cycles.

Regression tests

Added coverage for both functions:

  • A single positive edge to a neighbor-only vertex.
  • A chain ending at a neighbor-only sink, with different insertion orders.
  • A negative edge without a cycle.
  • A reachable negative cycle with a neighbor-only sink.

Validation

  • Full test suite: 604 passed.
  • git diff --check: passed.

Summary by CodeRabbit

  • Bug Fixes
    • Bellman-Ford now correctly handles vertices that appear only as neighbors, including when calculating shortest paths and detecting reachable negative cycles.
  • Tests
    • Added coverage for positive and negative edges, multi-edge paths with different vertex orders, and negative-cycle detection.

@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: aefde835-dfca-42c7-9247-0142815954d0

📥 Commits

Reviewing files that changed from the base of the PR and between bd1d152 and 6e48195.


📒 Files selected for processing (2)
  • algorithms/graph/bellman_ford.py
  • tests/test_graph.py

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.



📝 Walkthrough

Walkthrough

Both Bellman-Ford functions now count initialized distance entries when setting the relaxation-pass count. New tests cover neighbor-only destinations, paths in different insertion orders, and negative-cycle detection.

Changes

Bellman-Ford vertex counting

Layer / File(s) Summary
Relaxation count and regression coverage
algorithms/graph/bellman_ford.py, tests/test_graph.py
Both functions use the initialized distance map to set the relaxation-pass count. Tests cover single edges, two-edge paths in different insertion orders, and a reachable negative cycle. The tests check distances and predecessors from bellman_ford_paths.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: keon


Merge Risk: ⚪ Minimal · up to 6e481

No actionable merge-blocking risk is identified; the change is mergeable after normal checks.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: fixing false negative-cycle detection for neighbor-only vertices in Bellman-Ford.
Linked Issues check Passed Issue #2785 requires both bellman_ford and bellman_ford_paths to count neighbor-only vertices during relaxation. The PR changes both functions to use the initialized distance dictionary for the …
Out of Scope Changes check Passed The changes are limited to algorithms/graph/bellman_ford.py and regression tests in tests/test_graph.py. The implementation change and tests directly support Issue #2785. No unrelated change is id…

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

This branch has not been deployed

No deployments
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.

Bellman-Ford reports false negative cycles for neighbor-only vertices

1 participant