Skip to content

Add the candidate invariants of the int locals a loop changes - #550

Merged
CatarinaGamboa merged 1 commit into
mainfrom
feat/543-invariant-candidates
Nov 23, 2026
Merged

CatarinaGamboa merged 1 commit into
mainfrom
feat/543-invariant-candidates

Conversation

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator

Stacked on #549; review/merge after it.

Fixes #543

Part of the loop invariant inference plan (#542).

What and why

InvariantCandidates.of(x, x0, condition) builds the candidate invariants of an int local variable x that a loop changes, in the manner of Liquid Types' qualifiers (Rondon, Kawaguchi, Jhala, PLDI 2008):

  • x >= x0 and x <= x0, with x0 the instance of x before the loop (it only grows or only shrinks; works for symbolic starts);
  • the order comparisons (<, <=, >, >=) among the top-level conjuncts of the loop condition that mention x, made non-strict so the iteration that ends the loop can keep them (i < n gives i <= n).

Terms are limited to integer literals, int local variables and parameters, +, -, * and unary minus: fields and calls may change out of sight of the loop (PM decision on #542). Comparisons under || or ! and != give no candidate. Order is deterministic, duplicates are removed, and there are at most 6 candidates per variable (MAX_PER_VARIABLE, to be tuned in #547).

Pure code, not used by the checker yet; the next PR (Houdini check, #544) proves the candidates before using them, so a candidate is only a guess and a wrong one can only cost precision.

Plan change

The plan had this PR based on main and independent of #538. It is stacked on #549 (#538) instead, so the stack is linear (#549 → this → #544 → #545): the Houdini step relies on #549 to stay sound (x++ used to keep the loop condition on the incremented value, which could prove a non-inductive candidate), and the buffer loop from #537 then verifies in the stack itself.

Tests

InvariantCandidatesTest (8 unit tests): bounds from the value before the loop, none without an instance, weakening of each comparison kind, only comparisons that mention the variable, none from ||/!/!=, only supported terms (field, call, cast, division, long literal rejected), the grouping of nested terms (n - (n - 1)), and the cap.

Full suite passes locally; no change in what the verifier accepts.

🤖 Generated with Claude Code

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 1

I found no bug in the current candidate translation. It builds predicate AST nodes directly, preserving nested arithmetic for the Z3 visitor; unsupported operand forms are skipped. The requested Maven command passed: 7 tests, 0 failures, 0 errors. Repository files were not changed.

  1. Test gap — Predicate.toString() omits parentheses. For i < n - (a - b), its text can look like i <= n - a - b even when the AST means the right thing. The tests compare only this text. Fix: assert the predicate AST or its Z3 meaning for nested subtraction, multiplication, and unary minus.

  2. Test gap — The tests cover 10L but not hexadecimal or underscored int literals, char and short operands, or duplicate comparisons. Fix: add cases such as i < 0x10, i < 1_000, and i < 'a', checking which candidates are emitted and that duplicates are removed.

  3. Code quality — of(String variable, ...) cannot verify that a condition read denotes that exact declaration or that a bound name is available in the verifier context. For example, it can emit i <= n whenever Spoon resolves n as an int local, regardless of the context supplied by a future caller. Fix: resolve declarations to verifier names at integration, or pass a name resolver into this API.

  4. Plan — The set is sensible for Invariant inference 1/6: candidate invariants for int locals a loop changes #543: the two pre-loop bounds support ordinary increasing or decreasing counters, and weakened guard comparisons supply possible limits. For i += 2 under i < n, i <= n may fail induction; the planned Houdini checks should drop it. Fix: keep that proof gate mandatory when wiring candidates into the checker.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex round 1: what was done

  1. Fixed: added keepsTheGroupingOfTerms, which checks the predicate tree for i < n - (n - 1) (the printed form has no parentheses).
  2. Declined: hexadecimal and underscored literals reach the code as the same Integer value as decimal ones, and char/short operands are rejected by the same type checks the existing tests exercise (long literal, non-int variables); more cases would test Spoon, not this code.
  3. Declined: Java forbids a local or parameter to shadow another local, so a simple name in the loop condition is that of the context variable; the next PR (Invariant inference 2/6: Houdini check, keep the inductive candidates at the loop head #544) resolves the names through the context (getLastVariableInstance) when it proves candidates.
  4. No change needed: the Houdini PR proves every candidate at loop entry and at every back edge before using it.

The first round found no bug, so the Codex loop for this PR ends here. This round's fix is in the PR's first push.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Clean-code review

Audit of InvariantCandidates and its test (clean-code-principles).

  • [solid-srp] The class has one job: Java loop condition to candidate predicates. OK.
  • [name-searchable] The cap is a named constant (MAX_PER_VARIABLE) with its reason. OK.
  • [func-small] of, comparisons, term are each a few lines with one purpose. OK.
  • [core-dry] The BinaryOperatorKind to RJ operator mapping exists privately in OperationsChecker.getOperatorFromKind. Declined: reusing it needs that private method made shared, for three operators; a small local switch keeps this PR self-contained.
  • [core-yagni] isIntLocal was package-private without a caller outside the class. Fixed: made private.

For each int local variable a loop changes, the facts that may hold at the
loop head on every iteration, as in Liquid Types' qualifiers: that it only
grows or only shrinks from its value before the loop, and the comparisons
of the loop condition that mention it, made non-strict. Terms are limited
to integer literals, int locals and parameters, and +, - and *, with a cap
per variable. Not used by the checker yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CatarinaGamboa
CatarinaGamboa force-pushed the feat/543-invariant-candidates branch from 2bd898a to ddbe7c3 Compare November 23, 2026 17:18
@CatarinaGamboa
CatarinaGamboa merged commit be89891 into main Nov 23, 2026
1 check passed
CatarinaGamboa added a commit that referenced this pull request Nov 23, 2026
Stacked on #550; review/merge after it.

Fixes #544
Fixes #537
Fixes #479

Part of the loop invariant inference plan (#542).

## What and why
A loop havocs every variable it changes: at the loop head a changed
variable keeps only its declared refinement, so `for (int i = 0; i < 10;
i++) use(i)` did not know `i >= 0` (#537). This PR infers invariants for
the `int` local variables (and parameters) a loop changes, with the
Houdini algorithm (Flanagan and Leino, FME 2001) over the candidates of
#550 (Liquid Types qualifiers):

1. **Start check** (`new LoopInvariants`, before the havoc): keep the
candidates that the facts before the loop prove (`x0` is the instance
before the loop).
2. **Assume at the head** (`startIteration`): add the remaining
candidates to the refinements of the loop-head instances (not as a path
condition, which an assignment would rename or drop).
3. **Step check** (`recordNextIteration`): at the point where the next
iteration starts (end of the body for `while`/for-each, after the update
for `for`, after the condition for `do`-`while`, where the condition is
now assumed since the next iteration only starts when it holds) drop
each candidate not proved for the last instances.
4. **Continues:** the end of a body with continues is a join where
`scanBody` havocs the changed variables again. There, the candidates and
"`x` grew / shrank since the head" are kept when proved at every
continue and at the fall-through end of the body (`atJoin`/`joined`), so
a `for` update or a `do`-`while` condition that follows can still be
checked.
5. Repeat until a check drops nothing, inside the existing
`checkUntilFixpoint` loop (which already re-checks the body until
typestates are stable and keeps only the errors of the last check).
After 8 checks that dropped candidates, all are dropped (`MAX_ROUNDS`).

All candidate proofs are silent (`checkStateSMT(..., silent = true)`); a
failed or unknown proof only drops the candidate. Loops whose jumps run
a `finally` or leave a labelled block (`followsJumps` false) infer
nothing, as their typestates are not followed either.

## Soundness argument
A candidate survives only if (a) it is proved from the facts before the
loop, and (b) in the last check, assuming all survivors at the head, it
is proved at every point where the next iteration starts: the end of the
body (if reachable), the update or condition after it, and every
`continue` (through the join facts, each proved on every path into the
join). So the survivors form an inductive invariant and hold at the head
on every iteration; errors are only kept from that last check. An
earlier check assumes more candidates (and fewer typestates) than the
last one, so an error that stops it is also an error of the last one.
Integers are mathematical, as elsewhere in LiquidJava.

Checked with Codex (no false negative found) and these programs that
must still be rejected: decrementing counter with `_ >= 0`, counter
reset in the body, `i = i - 2` on some path, a bound the step breaks (`i
+= 3` under `i < 10` with `_ <= 10`), a continue path that decreases `i`
(in `while`, and in `for` before the update), an inner loop that
decreases the outer counter, labelled continue from an inner loop,
switch and try/finally in the body.

## Before / after
| Program | main | this PR |
|---|---|---|
| #537 `for (int i = 0; i < 10; i++) use(i)` | `found i < 10 but
expected i >= 0` | Correct |
| #537 `while (total < 1024) { use(total); total = total + 1; }` |
`found total < 1024 but expected total >= 0` | Correct |
| #537 buffer loop (`read(buf, total, limit - total)` with `off >= 0`,
`if (n < 0) break; total += n;`) | `found total < limit but expected
total >= 0` | Correct |
| #538 bounded accumulation (`@Refinement("_ >= 0 && _ <= 1024") total`,
guard then `total = total + n`) | Refinement Error | Correct (with #549)
|
| #479 `for (int i = 0; i < l.size(); i++) l.get(i)` | `... i <
#size_result but expected i >= 0 && i < size(l)` | Correct |

#479 needed only `i >= 0`: the list is not havocked (its `size()` and
`get` do not change its state), so the plan's #546 (candidates from what
the body requires) is not needed for it.

## Tests
- `CorrectLoopInvariants` (each method fails without this PR): #537's
counter and accumulator, the buffer loop, a symbolic start (`for (int i
= k; ...)` after `if (k < 0) return;`), nested loops (`j` starts at
`i`), and a continue in `for`, `while` and `do`-`while`.
- `ErrorLoopInvariants` (non-inductive candidates must not be assumed):
decrementing counter, reset in the body, decreased on some path, bound
not kept by the step, decreased before a continue (in `while`, and in
`for` before the update), decreased in an inner loop.
- `classes/loop_list_index_correct`: the #479 reproducer.

## Timing
Full suite, same machine, two runs each (machine shared, so noisy): main
195 s / 170 s wall, TestExamples 127 s / 86 s; this PR 163 s / 142 s
wall, TestExamples 98 s / 91 s. On the same pair of runs, the 16
existing loop fixtures take 1.3 to 2 times as long (e.g.
`CorrectLoopStateFixpoint` 2.3 s to 3.6 s, `CorrectLoopCondition` 0.37 s
to 0.79 s): each check of a loop body now also runs one silent SMT query
per candidate, and a dropped candidate costs one more check of the body.
Tuning (caps, nested loops re-inferred per outer check) is #547.

## Known precision gaps (from the Codex review, left for later)
- A `for` update or `do`-`while` condition that repairs a value set
before a `continue` (`i = -1; continue;` then `i++`) is not followed:
the join keeps only facts proved before the update.
- A `finally` anywhere on a jump path turns inference off for the whole
loop, as for typestates.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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 1/6: candidate invariants for int locals a loop changes

1 participant