Cirq icon indicating copy to clipboard operation
Cirq copied to clipboard

[Bug]: ParallelGate accepts non-integer num_copies, producing an invalid gate

Open NiranjanRSoorej06 opened this issue 2 months ago • 2 comments

Description of the issue

cirq.ParallelGate.__init__ only checks that num_copies > 0. It doesn't check that num_copies is an integer, so a float such as 2.5 is accepted and creates a gate in an invalid state. num_qubits() then returns a non-integer, and later calls fail with confusing errors.

How to reproduce the issue

import cirq

g = cirq.ParallelGate(cirq.X, 2.5)   # no error raised
print(g.num_qubits())                # 2.5

g.on(*cirq.LineQubit.range(3))
# TypeError: can't multiply sequence by non-int of type 'float'

cirq.decompose_once_with_qubits(g, cirq.LineQubit.range(3))
# ValueError: len(qubits)=3 should be 2.5

Expected behavior

The constructor should reject a non-integer num_copies immediately with a clear error. The docstring already says it raises ValueError for invalid input, so this fits that contract. For example:

ValueError: num_copies must be a positive integer.

Suggested fix

In cirq-core/cirq/ops/parallel_gate.py, validate the type alongside the existing check:

if not isinstance(num_copies, int) or num_copies <= 0:
    raise ValueError("num_copies must be a positive integer.")

and add a test case with a float value (e.g. 2.5) to parallel_gate_test.py.

Cirq version 1.8.0.dev0

NiranjanRSoorej06 avatar Oct 01 '26 13:10 NiranjanRSoorej06

Hi! I'd like to work on this. Could you please assign it to me?

My approach:

  • Add an integer check for num_copies in ParallelGate.__init__, raising a ValueError with a clear message (accepting numpy integers too).
  • Update the docstring.
  • Add tests for a float value and a numpy integer.

Thank You!

NiranjanRSoorej06 avatar Oct 01 '26 13:10 NiranjanRSoorej06

@NiranjanRSoorej06 Thank you for this report!

However, this particular problem is not significant enough to be a concern. Technically, yes, ParallelGate.__init__ does not check the type of num_copies at run time. However:

  • The parameter is annotated with the type num_copies: int on both ParallelGate.__init__ and ParallelGate.with_num_copies. Static type checkers (e.g., Mypy) will flag code that uses the wrong type.

  • A ParallelGate with a non-integer num_copies cannot silently corrupt a circuit, unitary matrix, or simulation. Every downstream operation will fail immediately with TypeErrors or ValueErrors if given a float for this parameter.

Other gates in cirq.ops follow the same pattern of relying on type annotations rather than explicit isinstance checks in __init__. Given this, and the low risk in practical terms, I feel it's better to close this as a "wont-fix" situation.

mhucka avatar Oct 02 '26 22:10 mhucka