Repository: Qiskit/qiskit

Issue:
Circuit decoding error
### Environment

- **Qiskit Terra version**: `0.45.1`
- **Python version**: `3.10.12`
- **Operating system**: macOS `13.6 (22G120)`

### What is happening?

Serialization decoding of a circuit with `qpy` fails when `qargs` for a `delay` are passed in as a `set` and `len(qargs) > 1`. The error raised here is

```
ValueError: b'\x00' is not a valid Value
```

and when running the circuit on a device, the job will fail with something like:

```
Failed - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 87: invalid start byte
```

### How can we reproduce the issue?

```
from qiskit import QuantumCircuit, qpy

# This case fails when the delay is present
num_qubits = 2
qubits = {0, 1}

# This case always runs
#num_qubits = 1
#qubits = {0}

qc = QuantumCircuit(num_qubits)
qc.delay(duration=160, qarg=qubits)
qc.x(qubits)

with open("test.qpy", "wb") as f:
    qpy.dump(qc, f)

with open("test.qpy", "rb") as f:
    qpy.load(f)
```

### What should happen?

This should run regardless of the cases described.

### Any suggestions?

_No response_


Discussion:
This is a bug with `QuantumCircuit.delay` rather than QPY - it's the same thing as #11208 going on, where the initial `QuantumCircuit` is in a totally invalid state that's somehow not noticed.  It's because of our old "friend" broadcasted arguments.

As an immediate work-around, turn the `set` into a `list` and the circuit will be valid (and roundtrip through QPY, etc).

Resolving patch:
diff --git a/qiskit/circuit/delay.py b/qiskit/circuit/delay.py
--- a/qiskit/circuit/delay.py
+++ b/qiskit/circuit/delay.py
@@ -16,6 +16,7 @@
 import numpy as np
 from qiskit.circuit.exceptions import CircuitError
 from qiskit.circuit.instruction import Instruction
+from qiskit.circuit.gate import Gate
 from qiskit.circuit.parameterexpression import ParameterExpression
 
 
@@ -29,13 +30,12 @@ def __init__(self, duration, unit="dt"):
 
         super().__init__("delay", 1, 0, params=[duration], unit=unit)
 
+    broadcast_arguments = Gate.broadcast_arguments
+
     def inverse(self):
         """Special case. Return self."""
         return self
 
-    def broadcast_arguments(self, qargs, cargs):
-        yield [qarg for sublist in qargs for qarg in sublist], []
-
     def c_if(self, classical, val):
         raise CircuitError("Conditional Delay is not yet implemented.")
 
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py
--- a/qiskit/circuit/quantumcircuit.py
+++ b/qiskit/circuit/quantumcircuit.py
@@ -3206,32 +3206,9 @@ def delay(
         Raises:
             CircuitError: if arguments have bad format.
         """
-        qubits: list[QubitSpecifier] = []
-        if qarg is None:  # -> apply delays to all qubits
-            for q in self.qubits:
-                qubits.append(q)
-        else:
-            if isinstance(qarg, QuantumRegister):
-                qubits.extend([qarg[j] for j in range(qarg.size)])
-            elif isinstance(qarg, list):
-                qubits.extend(qarg)
-            elif isinstance(qarg, (range, tuple)):
-                qubits.extend(list(qarg))
-            elif isinstance(qarg, slice):
-                qubits.extend(self.qubits[qarg])
-            else:
-                qubits.append(qarg)
-
-        instructions = InstructionSet(
-            resource_requester=self._current_scope().resolve_classical_resource
-        )
-        for q in qubits:
-            inst: tuple[
-                Instruction, Sequence[QubitSpecifier] | None, Sequence[ClbitSpecifier] | None
-            ] = (Delay(duration, unit), [q], [])
-            self.append(*inst)
-            instructions.add(*inst)
-        return instructions
+        if qarg is None:
+            qarg = self.qubits
+        return self.append(Delay(duration, unit=unit), [qarg], [])
 
     def h(self, qubit: QubitSpecifier) -> InstructionSet:
         """Apply :class:`~qiskit.circuit.library.HGate`.


Test patch:
diff --git a/test/python/circuit/test_delay.py b/test/python/circuit/test_delay.py
--- a/test/python/circuit/test_delay.py
+++ b/test/python/circuit/test_delay.py
@@ -82,6 +82,17 @@ def test_add_delay_on_multiple_qubits_to_circuit(self):
         expected.delay(300, 2)
         self.assertEqual(qc, expected)
 
+    def test_delay_set(self):
+        """Test that a set argument to `delay` works."""
+        qc = QuantumCircuit(5)
+        qc.delay(8, {0, 1, 3, 4})
+        expected = QuantumCircuit(5)
+        expected.delay(8, 0)
+        expected.delay(8, 1)
+        expected.delay(8, 3)
+        expected.delay(8, 4)
+        self.assertEqual(qc, expected)
+
     def test_to_matrix_return_identity_matrix(self):
         actual = np.array(Delay(100))
         expected = np.array([[1, 0], [0, 1]], dtype=complex)