Skip to content

Swapping measurement keys with with_measurement_key_mapping collapses a SympyCondition (a > b becomes a > a or b > b) #8529

Open

Description

@haonanren888

SympyCondition.replace_key substitutes one key at a time (self.expr.subs({str(current): sympy.Symbol(str(replacement))})), so a mapping that swaps two keys is applied sequentially and merges them.

import cirq, sympy
q0, q1, q2 = cirq.LineQubit.range(3)
a, b = sympy.symbols('a b')
c = cirq.Circuit(cirq.X(q0), cirq.measure(q0, key='a'), cirq.measure(q1, key='b'),
                 cirq.X(q2).with_classical_controls(cirq.SympyCondition(a > b)),
                 cirq.measure(q2, key='out'))
s = cirq.with_measurement_key_mapping(c, {'a': 'b', 'b': 'a'})
print(s)                                          # condition is now a > a or b > b (varies between runs)
print(cirq.Simulator().run(c).records['out'])     # [[[1]]]
print(cirq.Simulator().run(s).records['out'])     # [[[0]]], expected [[[1]]] (b=1 > a=0)

The measurements themselves are swapped correctly; only the condition is wrong, so the result changes silently. Which of a > a / b > b you get depends on the iteration order of the condition's keys, which can differ between interpreter runs (string hash randomization). Substituting all keys at once (subs(..., simultaneous=True) or a single xreplace of the full mapping) would avoid this.

Seen on 1.8.0.dev0; line unchanged on current main (cirq-core/cirq/value/condition.py). Different cause from #8525 and #8528, same family (condition objects under key rewriting).

Disclosure: found with AI-assisted differential testing that I direct; the snippet above was run before posting.

Saved-version clarification: a separate saved run on November 12, 2026 also reproduced this result with Cirq 1.8.0.dev20261111222613: the mapped condition was a > a, and the original/mapped outputs were [[[1]]] / [[[0]]]. That saved run is separate from the original 1.8.0.dev0 evidence.

Activity

  1. locked and limited conversation to collaborators on Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    triage/discussNeeds decision / discussion, bring these up during Cirq Cynque

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions