Skip to content

Report an error in a loop body only with invariants proved on every path - #555

Open
CatarinaGamboa wants to merge 2 commits into
mainfrom
fix/553-unproved-invariants
Open

CatarinaGamboa wants to merge 2 commits into
mainfrom
fix/553-unproved-invariants

Conversation

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator

Fixes #553

Part of the loop invariant inference plan (#542). Independent of #552 (based on main).

What and why

When an error stopped the check of a loop body before a back edge, the candidate invariants assumed at the head were never checked on the paths after it, so they were never dropped, and the reported error showed them as facts (#553: found total@18#1 >= 0 && total@18#1 <= 0 && ...).

The issue suggested dropping the candidates not proved at a back edge reached, or all of them if none was reached. I tried that first, and it is sound, but it moves errors onto lines that are correct: in

for (int i = 0; i < 10; i++) { use(i); small(i); }   // use: _ >= 0, small: _ < 5

the error at small(i) stops every check, so all candidates are dropped, and the error is then reported at use(i) as found i < 10 but expected i >= 0. That is the #537 false alarm again, in any loop that has another error, which is what study participants will write.

So this PR keeps checking the rest of the body instead:

  1. When an error stops a check (checkUntilFixpoint catches it), the top-level statement of the body where it stopped (recorded by a scan override) is skipped in the next checks: the checker forgets what it may change (changedIn, as for the loop itself) and declares the variable it declares, if any.
  2. Houdini goes on with the statement skipped, so the candidates are checked at every back edge, on every path.
  3. Once a check drops nothing, the body is checked once more without skipping (reporting), and that check reports the error, with candidates proved on every path.
  4. If a statement cannot be skipped (it continues a loop outside it, changes an object whose typestates the loop follows, or is a local class), or the error is outside the body statements (condition, update), all candidates are dropped instead, and the error is reported by a check that assumes none. A loop with no candidates rethrows at once, as before.

Soundness argument

  • An error is only reported from a check with no skipped statement, and either no candidates, or candidates that a check dropped none of (a fixpoint).
  • Skipping a statement over-approximates what it does to the facts candidates can talk about (int locals): every variable it may write gets a fresh instance with only its declared refinement. So candidates proved with it skipped hold for the real statement too, in executions where no earlier check failed. The declared refinement is the usual "assume after a failed check".
  • A skipped statement must not hide a back edge: one with a continue to this loop or an outer loop cannot be skipped. A break, return or throw it hides only adds paths to check.
  • Typestates: a statement that changes an object whose typestates the loop follows cannot be skipped, so the head typestates are computed as before.
  • Termination: each stopped check either adds a new skipped statement (finitely many) or drops all candidates; each report check that does not stop either drops a candidate or ends the loop.

Before / after (main → this PR)

Program main this PR
#553 reproducer found total@16#1 >= 0 && total@16#1 <= 0 && total@16#1 <= 100 && ... found total@16#1 < 100 && total == total@16#1 + #read_result
for (i = 0; i < 10; i++) { use(i); small(i); } error at small(i), found i < 10 && i >= 0 && i <= 10 same (the suggested "drop all" moved it to use(i))
for (i...) { small(i); k = k - 1; use(k); } error at use(k), found k@8 >= 0 && k@8 <= 0 && .... small(i) passed only because of the false i <= 0 error at small(i), found i < 10 && i >= 0 && i <= 10
while (i < 10) { if (c()) { bad(i); i = -1; } i++; } found i < 10 && i >= 0 && i <= 0 && i <= 10 found i < 10
int x = bad(i); in a for (declaration skipped) ... i >= 0 && i <= 0 ... found i < 10 && i >= 0 && i <= 10
error before i = i - 5; continue; (cannot be skipped) ... i >= 0 && i <= 0 ... found i < 10

Tests

  • ErrorLoopUnprovedInvariant (new fixture, one method): an accumulator with an error after nonNeg(i).
  • TestCounterexamples.errorInLoopBodyShowsNoUnprovedInvariant: Found has no <= 0. Fails on main (#total_2 >= 0 && #total_2 <= 0 && ...).
  • The fixture's Expect line also fails with the suggested "drop all" fix, which reports nonNeg(i) (line 17).

Full suite passes locally. Study tasks (verify-tasks.py, 55 variants): verdicts and messages identical to verify-cur-redesign.json.

Timing

Correct programs do the same work as before. A loop whose body has an error now costs one more body check per skipped statement, plus the report check. Same machine (shared, load ~5 on 4 cores, so noisy):

main this PR
mvn -q test wall 141 s 144 s / 171 s (two runs)
Loop fixtures, cold SMT cache, median of 5 (ms)
ErrorLoopInvariants 329 469
ErrorLoopCondition 470 606
ErrorLoopStateFixpoint 534 1175
CorrectLoopInvariants 599 603
CorrectLoopStateFixpoint 1115 1096
Study tasks (verify-tasks.py, wall) — 233 s / 283 s

🤖 Generated with Claude Code

An error that stops the check of a loop body leaves the candidate
invariants unchecked on the paths after it, and the error showed them as
facts. The statement where the check stopped is now skipped in the next
checks, as if it changed anything it may change, until the candidates
reach a fixpoint; the body is then checked again to report the error.
A statement that cannot be skipped drops all candidates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 1

No soundness or correctness finding. Codex ran five programs against this branch and main. None reported an error from an unproved invariant, accepted a wrong program, hung or crashed:

Program This PR
ErrorLoopUnprovedInvariant (the new fixture) Found total == total@16 + #read_result. Main also showed the unproved total@16 <= 0
Error in a skipped local declaration (int y = ... whose initializer fails) Found x < 100 && y == x - 1. Main showed extra candidates
Two errors in one body the first error, Found n == #read_result - 2
Error before x++; continue; (cannot be skipped) found n == -1 but expected n >= 0, terminates
A valid loop Correct

Code quality

  1. The scan override and rebuilding a skipped declaration from its annotation make the proof path hard to audit. Codex suggests tests for skipped declarations, several errors, and jumps.
  2. The spacing in parent.getParent()instanceof needs cleanup.

What was done

  1. Declined: extra tests. The PM's rule is to add only tests that fail without the change. The new fixture already fails both on main (Found) and with the simpler "drop all" fix (line). Skipped declarations, several errors and jumps were checked by hand (table in the PR body and above), and the full suite covers the error-free paths. The audit concern is answered by the soundness argument in the PR body: an error is only reported from a check that skips nothing.
  2. Declined: spacing. formatter-maven-plugin writes it that way, as everywhere else in the file (e.g. context.getVariableByName(name)instanceof Variable variable).

Nothing to push for this round.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 2

No problem found. Codex wrote 15 programs (in the scratchpad, not in the repo). None of them verified while it broke a refinement, and no reported loop-head fact was false on an iteration that goes on. The skipped statement contained, in turn:

  • break, labelled break, return, throw, a switch, try/finally, a lambda;
  • an inner loop with a labelled continue (it cannot be skipped, so all candidates are dropped);
  • a typestate change, a field write, an array write;
  • an error in an if condition, and two errors in one body.

Codex also tried a for update and a do-while. For example, on ForUpdate.java the branch reports found x < 5 && x >= 0 && x <= 5, while main also shows x <= 0, which is false since x grows.

There are no findings in two rounds, so the Codex loop for this PR ends here.

@CatarinaGamboa

CatarinaGamboa commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

Clean-code review

I audited only this PR's new code (LoopInvariants skip state, and the scan override, canSkip, skip and the catch in checkUntilFixpoint in RefinementTypeChecker) against clean-code-principles.

  • [core-dry] skip rebuilt the declaration of a local variable from its annotation, a copy of the declaration-only path of visitCtLocalVariable. Fixed in 5c838bd: both now use declareWithoutValue, so a skipped declaration also keeps its custom message.
  • [func-command-query] checkAgainAfterError and checkSkippedAgain change state and return whether to check again. Declined: this follows reachedFixpoint in both LoopInvariants and LoopTypestates, and keeps checkUntilFixpoint readable as one loop.
  • [solid-srp] The skip state (skipped, stoppedAt, reporting) lives in LoopInvariants, while the AST work (canSkip, skip, finding the statement) lives in the checker, next to changedIn, forgetChanges and jumpTarget, which it uses. OK.
  • [name-meaningful] The fully qualified java.util.function.Predicate parameter avoids a clash with the RJ Predicate imported in the same file. OK.
  • [doc-why-not-what] The class Javadoc of LoopInvariants says why a stopped check cannot report with its candidates, and canSkip says why each kind of statement cannot be skipped. OK.

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.

Invariant inference: an error in the loop body is reported with candidate invariants that were never proved

1 participant