Skip to content

QPY fails to roundtrip expressions with cancelled-out variables #15355

@jakelishman

Description

@jakelishman

Environment

  • Qiskit version: 2.2.3
  • Python version: 3.13
  • Operating system: macOS

What is happening?

QPY roundtrips can fail on certain ParameterExpressions where a variable is symbolically eliminated without having been bound.

How can we reproduce the issue?

import io
from qiskit import qpy, QuantumCircuit
from qiskit.circuit import Parameter

x = Parameter("x")
# Using either of these triggers the same bug.
bad = [0 * x, x - x]

qc = QuantumCircuit(1)
qc.rz(bad[0], 0)

with io.BytesIO() as fptr:
    qpy.dump(qc, fptr)
    fptr.seek(0)
    qpy.load(fptr)[0]
File ~/code/qiskit/terra/qiskit/qpy/interface.py:430, in load(file_obj, metadata_deserializer, annotation_factories)
    426     if data.qpy_version >= 16:
    427         # Deserialize each program using their byte offsets
    428         file_obj.seek(program_offsets[i])
    429     programs.append(
--> 430         binary_io.read_circuit(
    431             file_obj,
    432             data.qpy_version,
    433             metadata_deserializer=metadata_deserializer,
    434             use_symengine=use_symengine,
    435             annotation_factories=annotation_factories,
    436         )
    437     )
    438 return programs

[... snip ...]

File ~/code/qiskit/terra/qiskit/qpy/binary_io/value.py:611, in _read_parameter_expression_v13(file_obj, vectors, version)
    609     symbol_map[symbol] = value
    610 with io.BytesIO(payload) as buf:
--> 611     return _read_parameter_expr_v13(buf, symbol_map, version, vectors)

File ~/code/qiskit/terra/qiskit/qpy/binary_io/value.py:707, in _read_parameter_expr_v13(buf, symbol_map, version, vectors)
    704         stack.append(getattr(lhs, method_str)())
    705     data = buf.read(formats.PARAM_EXPR_ELEM_V13_SIZE)
--> 707 return stack.pop()

IndexError: pop from empty list

What should happen?

Roundtrip should succeed.

Any suggestions?

I'd assume the bug actually happens in the QPY dump (not writing the relevant variable into the stack) but I haven't looked into it in detail.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingmod: qpyRelated to QPY serialization

    Type

    No type

    Projects

    Status

    Ready

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions