Skip to content

fix: emit distinct x gates with fresh operands in negctrl expansion - #357

Open
ryanhill1 wants to merge 3 commits into
mainfrom
fix-negctrl-aliasing
Open

fix: emit distinct x gates with fresh operands in negctrl expansion#357
ryanhill1 wants to merge 3 commits into
mainfrom
fix-negctrl-aliasing

Conversation

@ryanhill1

@ryanhill1 ryanhill1 commented Aug 7, 2026

Copy link
Copy Markdown
Member

Fixes #350

The negctrl @ expansion placed the same QuantumGate object at both the leading and trailing position of the emitted statement list. In-place transformations therefore reached the same operand nodes twice: reverse_qubit_order() raised KeyError on any unrolled negctrl gate, and remove_idle_qubits() survived only via the visited_node_ids guard.

The two x gates are now built as distinct statements whose operands go through fresh_qubits(), matching the fix #335 made for decomposition-emitted statements.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed negative-control gate expansion to generate correct leading and trailing x operations.
    • Resolved failures when reversing qubit order after unrolling negative-control gates.
  • Tests

    • Added coverage for single- and multi-control negative-control operations.
    • Added regression testing for expected gate sequences and qubit remapping.
  • Documentation

    • Added a changelog entry describing the fix.

The negctrl modifier expansion placed the same QuantumGate object at both
the leading and trailing position of the emitted statement list, so
in-place transformations reached the same operand nodes twice and
reverse_qubit_order() raised KeyError on any unrolled negctrl gate.

Fixes #350
@ryanhill1
ryanhill1 requested a review from TheGupta2012 as a code owner August 7, 2026 13:04
@argus-eye

argus-eye Bot commented Aug 7, 2026

Copy link
Copy Markdown

Argus review

Auto-review is off for this repo. Tick the box below to run a review on this PR.

  • Trigger Argus review

Estimated cost

  • Files changed: 3
  • Diff lines (±): 43
  • Historical avg: ~318.9k tokens · ~$1.35 · across last 6 review(s)

Tip: you can also comment @argus-eye review at any time.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review Change Stack

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 4dacf0b8-0ac6-4dce-b586-ab29bf256749

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The negative-control expansion now creates separate leading and trailing X-gate statements with fresh operand nodes. Tests cover single- and multi-qubit controls and verify successful qubit-order reversal.

Changes

Negative-control expansion

Layer / File(s) Summary
Fresh negative-control expansion operands
src/pyqasm/visitor.py
Negative-control conversion uses fresh_qubits and creates distinct operand nodes for the generated X gates.
Transformation regression coverage
tests/qasm3/test_transformations.py, CHANGELOG.md
Tests cover negative-control unrolling and qubit-order reversal. The changelog records the fix.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: thegupta2012

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the primary fix: emitting distinct X gates with fresh operands during negctrl expansion.
Linked Issues check ✅ Passed The PR satisfies #350 by creating distinct statements and fresh operands, with regression coverage for unrolling and qubit-order reversal; #335 is supporting context.
Out of Scope Changes check ✅ Passed The visitor fix, changelog entry, and regression tests directly support the negctrl aliasing fix and linked issue objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-negctrl-aliasing

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@ryanhill1

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/pyqasm/visitor.py`:
- Around line 1614-1618: Update the nested _neg_x_gates function with a concise
docstring describing that it creates X gates for the negative-control qubits and
returns the resulting list of qasm3_ast.QuantumGate objects; note that it takes
no parameters.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 30436573-a75a-409f-8e45-04afa54dfe69

📥 Commits

Reviewing files that changed from the base of the PR and between 7e05f4c and 4e60a7c.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • src/pyqasm/visitor.py
  • tests/qasm3/test_transformations.py

Comment thread src/pyqasm/visitor.py
Comment on lines +1614 to +1618
def _neg_x_gates() -> list[qasm3_ast.QuantumGate]:
return [
qasm3_ast.QuantumGate([], qasm3_ast.Identifier("x"), [], fresh_qubits(ctrl))
for ctrl in negctrls
]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add a docstring to _neg_x_gates.

The new nested function has no docstring. Add a concise description of its purpose and return value.

As per coding guidelines, every Python function must have a docstring explaining its purpose, parameters, and return values.

Proposed fix
         def _neg_x_gates() -> list[qasm3_ast.QuantumGate]:
+            """Create X gates for the negative controls.
+
+            Returns:
+                list[qasm3_ast.QuantumGate]: The generated X gates.
+            """
             return [
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _neg_x_gates() -> list[qasm3_ast.QuantumGate]:
return [
qasm3_ast.QuantumGate([], qasm3_ast.Identifier("x"), [], fresh_qubits(ctrl))
for ctrl in negctrls
]
def _neg_x_gates() -> list[qasm3_ast.QuantumGate]:
"""Create X gates for the negative controls.
Returns:
list[qasm3_ast.QuantumGate]: The generated X gates.
"""
return [
qasm3_ast.QuantumGate([], qasm3_ast.Identifier("x"), [], fresh_qubits(ctrl))
for ctrl in negctrls
]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/pyqasm/visitor.py` around lines 1614 - 1618, Update the nested
_neg_x_gates function with a concise docstring describing that it creates X
gates for the negative-control qubits and returns the resulting list of
qasm3_ast.QuantumGate objects; note that it takes no parameters.

Source: Coding guidelines

@TheGupta2012 TheGupta2012 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: approve with minor comments

The fix is correct, minimal, and consistent with the precedent #335 set for decomposition-emitted statements. It resolves issue #350 and, as a side effect, a second crash the description does not mention. Nothing here blocks merge. Four comments below: two Medium about documentation and coverage of that second crash, one Low about test breadth.

No security findings. The change adds no input handling, no I/O and no dependency, and fresh_qubits() was already public within pyqasm.maps.gates. No public API or shared contract moves, so the blast radius stays inside this repository.

Findings

  • Medium — the fix also repairs unroll(consolidate_qubits=True) crashing with KeyError: '__PYQASM_QUBITS__' on any negctrl @ gate, which the CHANGELOG entry does not mention.
  • Medium — regression coverage exercises reverse_qubit_order() only. remove_idle_qubits() is named in #350 and consolidate_qubits=True crashed outright on main; neither is asserted.
  • Low — the test_unroll_emits_fresh_operand_nodes matrix gains two plain negctrl rows, while six other operand shapes the aliasing reached stay uncovered.

How it was tested

Two worktrees were compared: PR head 624ec7c4 and origin/main at 7c31308. Every claim below comes from running code.

Issue #350 reproduces on main and is fixed here. For one, two and three negative controls, reverse_qubit_order() after unroll() raises KeyError: -5 on main and returns correct output on this branch.

Object identity. Every statement, operand node and index node in the unrolled AST was compared by id(). On main, the leading and trailing x are one object with one shared operand node and one shared index node per negative control. On this branch, zero shared objects across every case tried: one, two and three negative controls, ctrl @ negctrl @, negctrl @ ctrl @, pow(2) and pow(3) outer modifiers, a user-defined gate, physical qubits ($0), a broadcast register control (negctrl @ x q, r;), a discrete-set control (q[{0,1}]), negctrl inside a gate body invoked twice, inside a for body, inside an if body, and inside a box body.

Semantics are unchanged. The unrolled text this branch emits is byte-identical to main on all 14 cases main can unroll, so the x … x sandwich keeps its order. Independently, qiskit.quantum_info.Operator was compared for negctrl @ <gate> against its pyqasm expansion across 15 programs (qiskit 2.1.2, qiskit-qasm3-import 0.6.0). All 15 match exactly, not merely up to global phase. That set includes the reverse_qubit_order() output, checked against a hand-reversed reference program, and the inv @ negctrl @ and negctrl @ inv @ combinations on rzs cannot serve here, since controlled sdg is unsupported on both worktrees for unrelated reasons.

Suite and lint. pytest tests on this branch: 717 passed, 2 failed, 4 skipped. On main: 714 passed, 2 failed, 4 skipped. The two failures are the same pre-existing tests/cli/test_cli_commands.py cases on both sides, so this PR adds no failure and adds 3 tests. black --check and isort --check-only are clean. pylint on src/pyqasm/visitor.py and on tests/qasm3/test_transformations.py produces no message this branch does not already produce on main; the changed region is clean. mypy src reports no error in visitor.py, and the # type: ignore on line 1621 was checked by removal and is still required. All 26 checks on gh pr checks 357 pass. The headers lint target was not run, though the PR adds no file.

Next steps

  1. Extend the CHANGELOG entry to name the consolidate_qubits=True crash — a suggestion block is inline.
  2. Add the two missing pass assertions to the new regression test.
  3. Optionally widen the test_unroll_emits_fresh_operand_nodes matrix.

Comment thread CHANGELOG.md
### Removed

### Fixed
- Fixed the `negctrl @` expansion emitting the same `x` `QuantumGate` object at both the leading and trailing position, so in-place transformations mutated its operands twice — crashing `reverse_qubit_order()` (`KeyError`) on any unrolled `negctrl` gate. The two `x` gates are now distinct statements with fresh operand nodes. ([#350](https://github.com/qBraid/pyqasm/issues/350))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Type: Maintenance
Severity: Medium

Rationale: This entry credits the fix with repairing reverse_qubit_order() only, but the same aliasing broke a second user-visible path that this PR also fixes. On origin/main, unroll(consolidate_qubits=True) raises KeyError: '__PYQASM_QUBITS__' for any negctrl @ gate:

qubit[3] q;
negctrl @ x q[0], q[1];

# origin/main:  KeyError: '__PYQASM_QUBITS__'
#               (transformer.py:480, _get_pyqasm_device_qubit_index)
# 624ec7c4:     x __PYQASM_QUBITS__[0];
#               cx __PYQASM_QUBITS__[0], __PYQASM_QUBITS__[1];
#               x __PYQASM_QUBITS__[0];

Same root cause: consolidate_qubit_registers rewrote the shared x operand once, then met the already-renamed node a second time and looked __PYQASM_QUBITS__ up in global_qreg_size_map. A reader scanning the changelog to see whether their crash is fixed will not find it under the current wording, so the release notes understate the change.

Change Requested: Name the second crash in the entry.

Suggested change
- Fixed the `negctrl @` expansion emitting the same `x` `QuantumGate` object at both the leading and trailing position, so in-place transformations mutated its operands twice — crashing `reverse_qubit_order()` (`KeyError`) on any unrolled `negctrl` gate. The two `x` gates are now distinct statements with fresh operand nodes. ([#350](https://github.com/qBraid/pyqasm/issues/350))
- Fixed the `negctrl @` expansion emitting the same `x` `QuantumGate` object at both the leading and trailing position, so in-place transformations mutated its operands twice — crashing `reverse_qubit_order()` (`KeyError`) and `unroll(consolidate_qubits=True)` (`KeyError: '__PYQASM_QUBITS__'`) on any unrolled `negctrl` gate. The two `x` gates are now distinct statements with fresh operand nodes. ([#350](https://github.com/qBraid/pyqasm/issues/350))

_assert_no_shared_operand_nodes(module)


def test_reverse_qubit_order_negctrl():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Type: Implementation
Severity: Medium

Rationale: This test covers one of the three consumers the aliasing broke. Issue #350 names remove_idle_qubits() explicitly, noting it survives only because of the visited_node_ids guard in Modules._remap_qubits — an incidental guard rather than a deliberate contract, so nothing stops a later refactor from dropping it and silently reintroducing the crash. And unroll(consolidate_qubits=True) did not merely survive on main; it raised KeyError: '__PYQASM_QUBITS__' outright. Both paths are fixed by this change and neither is asserted, which leaves the fix resting on a single pass.

Change Requested: Add two short cases alongside this one, so all three passes the aliasing reached are pinned:

  • remove_idle_qubits() on the unrolled negctrl @ x q[0], q[1]; — expect qubit[2] q; x q[0]; cx q[0], q[1]; x q[0];
  • unroll(consolidate_qubits=True) on the same program — expect qubit[3] __PYQASM_QUBITS__; x __PYQASM_QUBITS__[0]; cx __PYQASM_QUBITS__[0], __PYQASM_QUBITS__[1]; x __PYQASM_QUBITS__[0];

Both expected outputs were confirmed against this commit.

"ecr q[0], q[1];",
"inv @ crz(0.5) q[1], q[2];",
"negctrl @ x q[0], q[1];",
"negctrl(2) @ x q[0], q[1], q[2];",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Type: Maintenance
Severity: Low

Rationale: These two rows cover the plain negctrl shape only. Testing on origin/main shows the aliasing also reached six further operand shapes that this change fixes but that no test pins: a broadcast register control (negctrl @ x q, r;), a discrete-set control (negctrl @ x q[{0,1}], q[2];), negctrl inside a gate body invoked twice, negctrl inside a for body, pow(n) @ negctrl @, and ctrl @ negctrl @. Each takes a different _copy_qubit branch or repeats the expansion, so each is a distinct way for the pattern to regress. This is the fourth fix for one bug class (#331, #333, #335, #350), which argues for making this matrix the durable guard rather than adding a bespoke test per incident.

Change Requested: Optional. Consider adding two or three of the above as parametrize rows — one line each, no new helper needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

negctrl expansion emits the same QuantumGate object twice, aliasing operand nodes

3 participants