Cirq icon indicating copy to clipboard operation
Cirq copied to clipboard

[Bug]: `MappingManager.shortest_path` raises unhandled `KeyError` on unreachable qubits and returns empty list for self-paths

Open SteveSonyJacob opened this issue 2 months ago • 3 comments

Describe the issue

In cirq.transformers.routing.MappingManager.shortest_path:

  1. Unhandled KeyError on unreachable qubits: When shortest_path(lq1, lq2) is called between two logical qubits where no path exists (such as on directed device coupling graphs or disconnected components), nx.reconstruct_path fails with an unhandled, raw KeyError: np.int64(...) leaking from internal NetworkX data structures. This is currently noted as an unresolved # TODO in cirq/transformers/routing/mapping_manager_test.py:

    # path from 2 to 0 does not exist
    # TODO: raise ValueError with informative message
    with pytest.raises(Exception):
        mm.shortest_path(q_int[2], q_int[0])
    

    Instead of leaking an internal KeyError, MappingManager.shortest_path should raise a clean, descriptive ValueError informing the caller that no path exists between the specified logical qubits.

  2. Self-path edge case returns empty list: When lq1 == lq2, shortest_path(lq1, lq1) currently returns an empty list []. Following standard graph theory and NetworkX conventions (nx.shortest_path(G, u, u) == [u]), the shortest path from a node to itself should consist of the node itself [lq1], rather than an empty sequence of length 0.

Explain how to reproduce the bug or problem

import cirq
import networkx as nx

# Directed topology: 0 -> 1 -> 2 (no path exists from 2 to 0)
g = nx.DiGraph([(0, 1), (1, 2)])
q = cirq.LineQubit.range(3)
mapping = {q[i]: i for i in range(3)}
mm = cirq.MappingManager(g, mapping)

# 1. Unhandled internal KeyError when no path exists
try:
    mm.shortest_path(2, 0)
except Exception as e:
    print(f"Raised: {type(e).__name__}: {e}")

# 2. Path to self returns empty list instead of [0]
print("Path from 0 to 0:", mm.shortest_path(0, 0))
Traceback for unreachable qubits
Traceback (most recent call last):
  File "<string>", line 12, in <module>
    mm.shortest_path(2, 0)
  File "cirq/transformers/routing/mapping_manager.py", line 226, in shortest_path
    nx.reconstruct_path(*self.logical_to_physical[[lq1, lq2]], predecessors)
  File "networkx/algorithms/shortest_paths/dense.py", line 391, in reconstruct_path
    prev = predecessors[source]
KeyError: np.int64(2)

Cirq version

1.7.0

SteveSonyJacob avatar Sep 25 '26 06:09 SteveSonyJacob

I would like to submit a PR to fix this if you could assign this to me?

SteveSonyJacob avatar Sep 25 '26 06:09 SteveSonyJacob

@SteveSonyJacob Thank you for the report and your interest in working on it!

mhucka avatar Sep 25 '26 18:09 mhucka

@mhucka Could you please check the PR i have linked?

SteveSonyJacob avatar Oct 13 '26 07:10 SteveSonyJacob