Skip to content

Only rewrite the jumps that leave a prev loop's body - #4937

Merged
feliperodri merged 3 commits into
model-checking:mainfrom
tautschnig:loop-contract-prev-nested-break
Oct 2, 2026
Merged

feliperodri merged 3 commits into
model-checking:mainfrom
tautschnig:loop-contract-prev-nested-break

Conversation

@tautschnig

Copy link
Copy Markdown
Member

Fix a loop-contract unsoundness: with prev(..) in a loop invariant, a break of a loop nested in the body ended the outer loop, so Kani reported SUCCESS on assertions that fail.

The bug. For a loop whose #[kani::loop_invariant] uses prev, the macro runs the first iteration as a closure and turns the body's break/continue into returns from it (BreakContinueReplacer in loop_contracts/mod.rs). It rewrote every break and continue in the body, including those that belong to a nested loop. On main:

let mut k: u8 = 7;
#[kani::loop_invariant(k <= 7 && k < prev(k))]
while k > 0 {
    k -= 1;
    let mut m: u8 = 0;
    #[kani::loop_invariant(m <= 2)]
    while m < 2 { m += 1; if m == 1 { break; } }
    assert!(k != 5);   // fails natively when k == 5
}

verifies (VERIFICATION:- SUCCESSFUL), while the same program without prev fails as it should. The inner break became "stop the outer loop" after its first iteration, so the iterations where k == 5 were never checked. Two related mistranslations of the same rewriting:

  • break 'outer to a loop enclosing the prev loop was rewritten as if it ended only the prev loop; the code after the prev loop then ran although natively it does not, and an assertion that fails natively verified;
  • a return inside a closure defined in the body was rewritten too, which did not compile.

The fix. Only a break/continue that targets the prev loop itself (unlabeled at its own level, or naming its label) is rewritten. Jumps of nested loops (unlabeled inside them, or naming their labels), and everything inside nested closures, async blocks and items, keep their meaning. A break/continue to an enclosing loop cannot be expressed in the closure, so it is now rejected with an error instead of mistranslated.

Found while reviewing #4930, which touches the same file; the two merge cleanly, and the loop-contract tests (62) pass on the combination.

Testing. New tests in tests/expected/loop-contract/: loop_with_prev_nested_break (the reproducer above, now fails as it should), loop_with_prev_nested_jumps (unlabeled and labeled jumps of nested loops and a return in a closure keep their meaning; all succeed), and loop_with_prev_enclosing_break (rejected). All three fail with the previous macro. The expected loop-contract (59 passed) and contract (183 passed) tests, the kani Quantifiers tests (incl. gcd_invariant) and script-based-pre/cargo_autoharness_contracts pass, as do fmt and both clippy invocations.

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

For a loop whose `#[kani::loop_invariant]` uses `prev`, the first
iteration runs as a closure, and `BreakContinueReplacer` turns the body's
`break`/`continue` into returns from it. It rewrote every `break` and
`continue` in the body, including those of a nested loop. An unlabeled
`break` of an inner loop therefore ended the outer loop after its first
iteration, and anything later in the outer loop went unchecked:

    #[kani::loop_invariant(k <= 7 && k < prev(k))]
    while k > 0 {
        k -= 1;
        let mut m: u8 = 0;
        #[kani::loop_invariant(m <= 2)]
        while m < 2 { m += 1; if m == 1 { break; } }
        assert!(k != 5);   // fails natively when k == 5
    }

verified (the same program without `prev` fails as it should). A labeled
`break 'outer` to a loop enclosing the `prev` loop was rewritten as if it
ended the `prev` loop, so the code after it ran although natively it does
not, and an assertion that fails natively verified. A `return` inside a
closure in the body was rewritten too, which did not compile.

Now only a `break`/`continue` that targets the `prev` loop itself
(unlabeled at its level, or naming its label) is rewritten. Jumps of
nested loops, and everything inside nested closures, `async` blocks and
items, keep their meaning. A `break`/`continue` to an enclosing loop
cannot be expressed in the closure, so it is reported as unsupported
rather than mistranslated.

New tests: `loop_with_prev_nested_break` (the reproducer; fails as it
should), `loop_with_prev_nested_jumps` (nested unlabeled/labeled jumps and
a closure `return` keep their meaning), `loop_with_prev_enclosing_break`
(rejected). All three fail with the previous rewriting.

Co-authored-by: Kiro <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 1, 2026 12:01
@tautschnig
tautschnig requested review from a team as code owners October 1, 2026 12:01
@github-actions github-actions Bot added Z-EndToEndBenchCI Tag a PR to run benchmark CI Z-CompilerBenchCI Tag a PR to run benchmark CI labels Oct 1, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Labeled block breaks remain misclassified and can preserve unsound behavior.

Review effort: Balanced
Findings: 1 High severity · 1 Low severity

Open (2)
What changed in this PR

Fixes unsound jump rewriting in loop contracts using prev.

Changes:

  • Restricts rewriting to jumps targeting the transformed loop.
  • Preserves control flow inside nested loops and closures.
  • Adds regression and diagnostic tests.
File Description
library/​kani_macros/​src/​sysroot/​loop_contracts/​mod.rs Adds target-aware jump rewriting.
tests/​expected/​loop-contract/​loop_with_prev_nested_jumps.rs Tests preserved nested control flow.
tests/​expected/​loop-contract/​loop_with_prev_nested_jumps.expected Records successful verification.
tests/​expected/​loop-contract/​loop_with_prev_nested_break.rs Reproduces the original unsoundness.
tests/​expected/​loop-contract/​loop_with_prev_nested_break.expected Expects the previously missed failure.
tests/​expected/​loop-contract/​loop_with_prev_enclosing_break.rs Tests unsupported enclosing jumps.
tests/​expected/​loop-contract/​loop_with_prev_enclosing_break.expected Records the new diagnostic.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@feliperodri feliperodri added [F] Soundness Kani failed to detect an issue Z-Contracts Issue related to code contracts labels Oct 2, 2026
@feliperodri feliperodri added this to the Contracts milestone Oct 2, 2026
`BreakContinueReplacer` tracked only nested loops, so a labeled block in
the body of a `prev` loop was invisible to it:

- `'done: { break 'done; }` was taken for a jump to an enclosing loop and
  rejected with the "not supported" error;
- a block that reuses the loop's own label (`'a: while .. { 'a: { break
  'a; } }`) had its `break` rewritten as an exit from the loop, so the rest
  of the iteration was skipped and an assertion that fails natively
  verified.

Track nested loops and labeled blocks in one stack: an unlabeled jump
still targets the innermost loop only, and a labeled one the innermost
loop or block with that label.

Also test that a `fn` item defined in the body keeps its own `return`s
and loop jumps.

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

Approving. This fixes a real soundness bug: with prev(..) in the invariant, a break of a nested loop became an exit from the outer loop, so the outer loop's later iterations were never checked. Rewriting only the jumps that actually leave the body, and rejecting a jump to an enclosing loop instead of mistranslating it, is the right shape.

I pushed two commits so this is ready to merge:

  • a merge of current main;
  • Treat labeled blocks as jump targets in a prev loop's body. Copilot was right about labeled blocks: 'done: { break 'done; } was rejected as an enclosing jump, and a block reusing the loop's label ('a: while .. { 'a: { break 'a; } .. }) had its break rewritten as a loop exit, which verified an assertion that fails natively. Loops and labeled blocks now share one stack: an unlabeled jump targets the innermost loop, a labeled one the innermost loop or block with that label. New harnesses cover both cases and a fn item in the body (which fails to compile if visit_item_mut is removed).

Beyond the tests, I checked that the rewrite agrees with native behaviour for while let and for loops with prev and an inner break, a nested loop reusing the outer label, and a valued break out of a nested loop: each assertion fails exactly where it does natively. expected (501), kani (620) and script-based-pre (90) pass, as do fmt, workspace clippy, kani_macros clippy with --cfg=kani_sysroot, and the LLBC clippy gate.

@feliperodri
feliperodri added this pull request to the merge queue Oct 2, 2026
Merged via the queue into model-checking:main with commit 402c15c Oct 2, 2026
34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[F] Soundness Kani failed to detect an issue Z-CompilerBenchCI Tag a PR to run benchmark CI Z-Contracts Issue related to code contracts Z-EndToEndBenchCI Tag a PR to run benchmark CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants