Skip to content

feat: Shared index resolution in AbstractProgramContext - #420

Merged
speller26 merged 2 commits into
amazon-braket:mainfrom
jheckey:fix/shared-index-resolution
Oct 29, 2026
Merged

speller26 merged 2 commits into
amazon-braket:mainfrom
jheckey:fix/shared-index-resolution

Conversation

@jheckey

@jheckey jheckey commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Issue #, if available:

Follow-up to review feedback on amazon-braket/qiskit-braket-provider#411.

Description of changes:

qiskit-braket-provider#411 fixed if (c[-1]) crashing qiskit-braket-provider's condition resolver. A reviewer there asked for negative-index handling to live in the default simulator's program-context interface, so the simulator and qiskit-braket-provider support the same OpenQASM features. This PR adds that shared helper and uses it in the simulator.

New AbstractProgramContext.resolve_index(name, value) -> int | SymbolLiteral. It resolves one index into name. The caller passes value, the index already evaluated in its own context:

  • Target and size. The size comes from the target's declared type:

    • a bit register: bit[n];
    • a sized int[n] or uint[n], for bit access;
    • an array: its first dimension, from ArrayType or a subroutine's ArrayReferenceType;
    • a qubit register: from the qubit mapping.

    A declared size must be an integer literal or the name of a constant; any other size expression raises a TypeError.

  • Targets that can't be indexed.

    • A scalar bit (declared without a size, so size 0) raises IndexError: 'b' is a scalar bit and cannot be indexed.
    • Following the OpenQASM 3 rule that "an array of size zero cannot be indexed", an array with any zero dimension (for example array[float[32], 0] or array[int[8], 2, 0]) raises IndexError: 'a' has size zero and cannot be indexed. for both non-negative and negative indices. So does a bit[0] or qubit[0] register.
    • A type with no size (float, bool, complex, unsized int, angle) raises TypeError: 'g' of type FloatType is not indexable: it has no declared size.
  • Evaluating the index. Because the caller evaluates the index, a loop variable, an int variable or an arithmetic expression such as c[n - 1] works. It does not have to be a compile-time constant. The helper itself needs no evaluator, so it works for any AbstractProgramContext subclass. That includes the Braket SDK's BraketProgramContext, which has none. A negative index counts back from the end, as OpenQASM 3 specifies.

  • Concrete results. The value must be an IntegerLiteral; anything else, such as a float or bool, raises TypeError: Index into 'c' must evaluate to an integer, got FloatLiteral. An integer outside [-size, size) raises IndexError: Index 3 is out of range for 'c', which has size 3.

  • Symbolic results. If the index evaluates to a symbol, such as an unbound input int n (or n - 1), every free symbol in its sympy expression must be declared int or uint, and every constant in it must be an integer. If so, value comes back as is, so a context that builds circuits instead of running them (qiskit-braket-provider's _QiskitProgramContext) can emit a symbolic condition. Otherwise it raises a TypeError, for example input float f; c[f] gives Index into 'c' must be an integer, but 'f' has type FloatType., and c[n + 0.5] gives Index into 'c' must be an integer, got n + 0.5. A symbolic index that simplifies to a number, such as n - n, is resolved as that integer. To make this check possible, an unbound input is now declared with its own (unevaluated) type instead of a placeholder SymbolLiteral type. Its value is still a symbol.

Other changes.

  • Measurement destinations. The interpreter now resolves negative, computed and symbolic destination indices with resolve_index, passing the value it evaluated, including each element of a discrete set. A negative or symbolic index into an undeclared destination raises NameError: Measurement destination 'c' is not declared, so its index -1 cannot be resolved., since resolving it needs the declared size. This fixes:

    • c[-1] = measure q[0]; and c[n - 1] = measure q[0];, which crashed with AttributeError: 'UnaryExpression' object has no attribute 'value' (or 'BinaryExpression');
    • c[k] = measure q[0]; with int k = -1;, and c[{-1, 0}] = measure q;, which were rejected as out of range.

    A non-negative integer index, or any index into an undeclared destination, still goes to the context's add_measure as before, so each context keeps its own range check. ProgramContext checks those indices with the helper as well. So in the simulator, an out-of-range destination raises the helper's IndexError, b[0] = measure q; on a scalar bit b is now an error, and an unbound input used as a destination index raises a clear TypeError.

  • Indexed bit writes in ProgramContext (c[-1] = 0;) also use the helper.

Not changed: indexed reads in conditions and expressions (if (c[-1]), int x = c[-1];). These already accept negative and computed indices through get_elements, which follows Python indexing and so matches OpenQASM for valid indices. An out-of-range read still raises a plain IndexError: list index out of range. Reads use the same path for MCM-dependent and ordinary expressions, so moving only MCM conditions onto the helper would make the two disagree. Qubit operands (x q[-1];) also keep their existing QubitTable resolution. Routing them through the helper would mean moving resolution out of QubitTable into the context, which is more than a minimal change. The helper does support qubit registers for callers that need it.

Follow-up: strict bounds checking for the Braket SDK's BraketProgramContext. It currently accepts out-of-range destinations, and its test_from_ir_with_measure relies on that.

With this change qiskit-braket-provider can replace its private _resolve_register_index with resolve_index. It also gets the negative-destination fix without any code change, since that path is in the shared interpreter.

Testing done:

  • New unit tests:

    • In test_program_context.py, tests call the helper directly:

      • indexing into a bit register (c[-1], c[-3], positive indices unchanged, an int variable, a negated variable, n - 3), into arrays (array[int[8], 3] a; a[-1] gives 2), into a subroutine array reference, into a qubit register, and into sized int and uint;
      • out of range for each target kind;
      • scalar bit, and size-zero array[float[32], 0], array[int[8], 2, 0], bit[0] and qubit[0], each with [0] and [-1];
      • non-indexable float, bool, unsized int and complex;
      • float and bool indices;
      • symbolic input int m, m - 1 and m + n returned unevaluated;
      • symbolic input float f and m - f raising TypeError, as do non-integer constants: m + 0.5, m / 2, and m + g with a bound float g;
      • symbolic indices that simplify to a number (m - m, m - m - 1) resolved as integers;
      • a declared size that names a constant, a declared size that is neither a literal nor a constant (TypeError), and unbound inputs keeping their declared types.

      They also cover destinations (c[-1], c[-3], c[n - 3], c[{-1, 0}], out of range, a scalar bit) and an out-of-range indexed write.

    • In test_mcm.py, end-to-end runs of the program below and of variants that measure into c[-1] or test c[-1] == 1; every shot measures 11. There are also MCM conditions indexed by a loop variable, -i, an int, a negative int, c[n - 1], c[n - 3] == 1, and an index computed from a measured value on each path, plus negative and computed destinations.

    • In test_interpreter.py, an undeclared destination with a non-negative index (c[1]) still reports the context's error, a negative index into one (c[-1], c[-2]) raises the NameError above, a symbolic input float destination index raises TypeError, and a symbolic input int destination raises a clear TypeError in the simulator.

    OPENQASM 3.0;
    qubit[2] q;
    bit[2] c;
    x q[0];
    c[1] = measure q[0];
    if (c[-1]) {
      x q[1];
    }
    c[0] = measure q[1];
    
  • tox -e clean,unit-tests,coverage-check: 2143 passed, 71 xfailed, 100% coverage.

  • tox -e linters_check: "All checks passed!" ruff format --check . is clean. That needed a one-character fix to trailing whitespace already on main in a program_context.py docstring.

  • Downstream checks against this branch:

    • amazon-braket-sdk-python unit tests: circuits, devices and parametric all pass. The rest of the suite has the same 16 failures and 2 errors under braket/aws as against main, which come from the environment and are unrelated.
    • qiskit-braket-provider unit tests (the fix: Record measurements into named classical registers #411 branch): 678 passed, 4 skipped.

Merge Checklist

Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request.

General

Tests

  • I have added tests that prove my fix is effective or that my feature works (if appropriate)
  • I have checked that my tests are not configured for a specific region or account (if appropriate)

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

Add `AbstractProgramContext.resolve_index(name, value, index=None)`,
which resolves one index into a sized target the same way for the
simulator and for any subclass. The target can be a bit register, a
sized `int` or `uint`, an array (its first dimension), or a qubit
register, and its size comes from the declared type. Scalars, such as
an unsized `bit`, and arrays with any zero dimension cannot be indexed,
so they raise an `IndexError`. Types with no size, such as `float`,
`bool` or an unsized `int`, raise a `TypeError`.

The caller passes the index already evaluated in its own context, so
loop variables, `int` variables and arithmetic expressions work. A
negative index counts back from the end of the target, as in OpenQASM
3. An integer outside the target raises an `IndexError`, and a
non-integer value raises a `TypeError`. A value that is a symbol, such
as an unbound `input int`, is returned as the unevaluated index
expression, so a context that builds circuits rather than running them
can keep it symbolic. It is first checked to reference only `int` or
`uint` variables, so `input float f; c[f]` raises a `TypeError`. To
make that check possible, an unbound `input` is now declared with its
own type instead of a placeholder type, still with a symbol as its
value.

The interpreter now resolves negative, computed and symbolic indexed
measurement destinations with the helper. `c[-1] = measure q[0];` and
destinations such as `c[n - 1]` crashed with `AttributeError:
'UnaryExpression' object has no attribute 'value'` (or
'BinaryExpression'), and `c[k] = measure q[0];` with `int k = -1;` was
rejected as out of range. A non-negative integer index, and any index
into an undeclared destination, is passed to the context's
`add_measure` as before, so each context keeps its own range check.
`ProgramContext` checks those with the helper as well, so a simulated
destination such as `b[0]` on a scalar `bit b` is now an error. It also
uses the helper for indexed bit writes such as `c[-1] = 0;`.
@jheckey
jheckey force-pushed the fix/shared-index-resolution branch from 70fa2f9 to 1da05d5 Compare October 28, 2026 21:14

@speller26 speller26 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.

Looks good, just have some questions.

raise IndexError(f"'{name}' is a scalar bit and cannot be indexed.")
case BitType(size=size) | IntType(size=size) | UintType(size=size) if size:
return self._declared_size(name, size)
case ArrayType(dimensions=dimensions) | ArrayReferenceType(dimensions=list(dimensions)):

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.

interesting, didn't know you could match like

ArrayReferenceType(dimensions=list(dimensions))

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.

Oh, this is treating list as a class pattern

- Drop the unneeded deepcopy before visiting a measurement index; expression
  visitors do not mutate the node.
- A negative or symbolic index into an undeclared measurement destination now
  raises a NameError naming the undeclared destination, since resolving it
  needs the declared size.
- resolve_index takes only the evaluated value. A symbolic index is checked
  with the sympy expression itself: its free symbols must be declared int or
  uint and its constants must be integers, so c[n + 0.5] is rejected. An
  expression that simplifies to a number, such as n - n, is resolved as that
  integer.
@codecov

codecov Bot commented Oct 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (a8eb926) to head (238990e).

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #420   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           50        50           
  Lines         5135      5194   +59     
  Branches       602       620   +18     
=========================================
+ Hits          5135      5194   +59     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@speller26
speller26 merged commit af470f8 into amazon-braket:main Oct 29, 2026
43 of 45 checks passed
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.

2 participants