qiskit-aer icon indicating copy to clipboard operation
qiskit-aer copied to clipboard

Running a custom gate with name collision with a default gate causes segmentation fault

Open rht opened this issue 1 year ago • 1 comments

Environment

  • Qiskit Terra version: 0.21.2
  • Python version: 3.10.6
  • Operating system: Linux

What is happening?

The following minimal code causes segfault

from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.gate import Gate
from qiskit.circuit.library.standard_gates import HGate
from qiskit import transpile
from qiskit_aer import Aer


class Custom(Gate):
    def __init__(self, label=None):
        super().__init__("p", 1, [], label=label)

    def _define(self):
        q = QuantumRegister(1, "q")
        qc = QuantumCircuit(q, name=self.name)
        qc._append(HGate(), [q[0]], [])
        self.definition = qc


qc = QuantumCircuit(1)
qc.append(Custom(), [0])
qc.measure_all()

backend_sim = Aer.get_backend("qasm_simulator")
transpiled = transpile(qc, backend_sim)
result_sim = backend_sim.run(transpiled, shots=10).result()
  • If the name "p" is changed to something else that doesn't collide with standard gates, the code runs fine
  • Alternatively, if it is a statevector simulation with no measurement, the code runs fine
  • Originally observed in this Slack thread https://app.slack.com/client/T7RSPHKK2/C7SS31917/thread/C7SS31917-1664748201.353639

How can we reproduce the issue?

See above.

What should happen?

There should be no segfault.

Any suggestions?

No response

rht avatar Oct 04 '22 02:10 rht

The segfault here is a missing safety check in Aer - it should be a Python-space error - but overall, this failing is expected (and required by our data model). Aer says that it knows about a p gate in its basis set, and Aer expects that to take one parameter. This gate says "I supply the p gate", but it doesn't have any parameters, so when Aer looks for one it errors. Any backend that supports a gate called p with a parameter should throw an error when given this circuit after transpilation.

The simulations probably work if there's no measurement or storage because Aer throws away instructions without simulating them if it detects that they have no observable effect, so it wouldn't ever try to access the missing parameter.

I'll transfer this to Aer because I think we can insert a sanity check on the parameters when we lower this to the C++ parts to ensure the error is in Python space not a segfault, but an error is the correct behaviour.

jakelishman avatar Oct 04 '22 17:10 jakelishman