Skip to content

Start nested loop inference from its last invariants; join only for the loop's own continues - #556

Open
CatarinaGamboa wants to merge 3 commits into
fix/553-unproved-invariantsfrom
perf/547-loop-cost
Open

CatarinaGamboa wants to merge 3 commits into
fix/553-unproved-invariantsfrom
perf/547-loop-cost

Conversation

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator

Stacked on #555; review/merge after it. Independent of #552.

Fixes #547

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

Measured first

I instrumented a throwaway build (not in this PR) to log every inference over the 401 test cases and the 8 study tasks:

test suite (248 inferences) study tasks (11 inferences)
candidates of one variable before the cap (MAX_PER_VARIABLE = 6) at most 3 at most 3
checks that dropped candidates (MAX_ROUNDS = 8) at most 2 (178 loops: 1) at most 1
loops that hit MAX_ROUNDS 0 0
body checks per loop 1 to 5 (mostly 2) 1 to 2
nesting depth 32 inner loops (depth 2) 4 inner loops (depth 2)

Loop checking (inference included) takes about 12% of the suite's verification time; a third of that is the candidate proofs (about 4 ms each, without cache).

Caps: unchanged. Neither cap is ever reached, so lowering them would only cost precision on unusual loops, and raising them gains nothing measurable.

What does cost: an inner loop runs its whole inference again on every check of the outer body (each outer check runs 2 inner checks), and the work multiplies with depth.

What and why

  1. A nested loop starts from its last invariants (lastInferred). Each check of a loop body starts from no more facts than the one before: fewer invariants, more typestates, more skipped statements (Report an error in a loop body only with invariants proved on every path #555). So an inner loop cannot have more invariants than at its last visit, and its next visit only tries those. It usually confirms them in one check instead of two. The candidates are matched across visits by their text, with the instance before the loop renamed (i_before), since instance names change on every check.
    • A check that starts from more facts forgets the invariants of the loops nested in it. That is a check that no longer skips a statement (the report check of Report an error in a loop body only with invariants proved on every path #555, or after dropping everything), or a loop starting over (it has no last invariants itself, or its inference stopped at an error). Everything is forgotten when the outermost loop ends.
  2. scanBody joins only for the loop's own continues. The end of the body was a join (forget the changed variables, keep the candidates and grew/shrank) as soon as the body held any continue, also one of an inner loop. Such a continue never reaches the outer end of the body. The join is now only made when a continue targets this loop (jumpTarget(jump) == loop, so a labelled continue from an inner loop still counts). This saves the join's proofs, and it is a strict precision improvement: a for update or do-while condition after an inner loop with a continue keeps the values the body gave.

Soundness argument

  1. Houdini is sound from any starting set. The start check and every step check still run, so a candidate survives only if it is proved before the loop and at every back edge. The warm start only changes which candidates are tried.
    • It gives the same result as a cold start. The largest inductive subset under weaker facts is contained in the one under stronger facts, so it is contained in the last result, and Houdini started from a superset of it finds it. A cold start could only differ by hitting MAX_ROUNDS and dropping everything, which the stats show never happens.
    • Every case where a check may start from more facts than the one before forgets the nested results (listed above), so this precondition holds whenever a result is reused.
  2. Without a continue targeting the loop, the end of the body is reached only by falling through, so the state there is exactly the state after the last statement. Forgetting it was only a loss. Typestates were already joined only for their own continues (LoopTypestates.recordContinue comes from loopLeftBy), so they are unchanged.

Before / after

do { i = 10; for (...) { if (next()) continue; } } while (ten(i) && next()); with ten(@Refinement("_ == 10") int x): before, expected i == 10 but could not prove it; after, Correct.

Tests

  • CorrectLoopInvariants.continueOfInnerLoop (the example above; fails without change 2).
  • No test for change 1: its results are identical by design (all tests pass unchanged, study results identical). A stress fixture would add time but not coverage, since the existing nested loops in CorrectLoopInvariants and ErrorLoopInvariants already run the warm start.

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

Timing (before = #555, after = this PR; same machine, shared, load about 4)

before after
mvn -q test wall, back to back (2 runs each) 143 s, 147 s 142 s, 140 s
TestExamples (sum of test times) 84.6 s, 85.3 s 84.4 s, 84.3 s
Study tasks verify-tasks.py wall 233 s, 283 s 239 s
Nested-loop stress (3 and 4 levels, 5 to 6 changed variables; not committed), cold cache, best of 2 medians of 5 1944 ms 1424 ms
classes/loop_list_index_correct 198 ms 145 ms
CorrectLoopInvariants 714 ms 682 ms
CorrectLoopStateFixpoint 1090 ms 1050 ms
ErrorLoopInvariants 429 ms 428 ms
ErrorLoopStateFixpoint (3 alternating runs) 732 to 765 ms 747 to 802 ms

The suite and the study tasks have few nested loops, so their totals do not move beyond the noise. The saving shows where nesting is deep: 27% on the stress program.

Not done: proving all candidates in one query before proving them one by one. It would save about one 4 ms query per loop in the confirming check, since loops keep 0 to 3 invariants.

🤖 Generated with Claude Code

CatarinaGamboa and others added 2 commits November 23, 2026 19:52
Each check of a loop body starts from no more facts than the one before,
so a loop nested in it cannot have more invariants than at its last
visit: its next visit only tries those. A check that starts from more
facts (one that no longer skips a statement, or a loop starting over)
forgets them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A continue of an inner loop does not reach the end of the outer body,
so the values there need not be forgotten.

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

Copy link
Copy Markdown
Collaborator Author

Codex review, round 1

No correctness issue found. Codex wrote 21 programs and compared this branch with the #555 jar:

  • No incorrect program now verifies.
  • The warm start lost no precision.
  • 19 programs give identical output.

The two differences both come from change 2 (join only for the loop's own continues), and both are more precise:

Program Before This PR
InnerContinueOuterDo: do { i = 10; for (...) { if (...) continue; } } while (ten(i) ...) expected i == 10 but could not prove it Correct
InnerContinueDoBad: the same with i = -1 and a >= 0 check expected i >= 0 but could not prove it found i == -1 but expected i >= 0 (still rejected, with a more specific message)

The programs covered:

  • two and three nested loops, with bounds that depend on outer variables;
  • errors in inner loops;
  • labelled continue and break;
  • for updates;
  • inner loops in branches, lambdas and try/catch;
  • typestate objects.

What was done

Nothing to fix. I start a second round aimed at the interaction with #555's skipping, where nested results are forgotten.

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 read the warm-start code, looking for a check that reuses an inner loop's result after a check with more facts. It found none:

  • the error retry and the report check after skipped statements both forget nested results;
  • a loop visited without a previous result forgets those of its descendants.

The before (#555) and branch jars gave byte-for-byte identical output on three programs (BasicNested, NestedCases with 14 nested-loop cases, SkipAndKeys). They covered:

  • skipped statements around inner loops;
  • inner-loop errors inside lambdas;
  • local classes;
  • a local named x_before, to probe key collisions.

What was done

The x_before probe showed that a key could collide with a real local. A collision only adds candidates to try, so it cannot change a result, but the key now renames the value before the loop to x#before, which no Java variable can be named (227fcfb, from the clean-code audit below).

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

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Clean-code review

I audited only this PR's new code (LoopInvariants constructor previous, inferred and key; lastInferred and forgetInferredNestedIn in RefinementTypeChecker; the continue filter in scanBody) against clean-code-principles.

  • [name-meaningful] key renamed the value before the loop to x_before, which is also a valid Java name. Fixed in 227fcfb: it is now x#before, and key has a Javadoc that says why.
  • [func-small] The constructor walks the variables twice: first to record every before instance, then to build candidates. Declined: key needs all of them, since a candidate from the condition can mention another variable.
  • [core-separation-of-concerns] The cache's lifecycle is split between visitLoop (read, store, clear at the outermost loop) and checkUntilFixpoint (forget on a check with more facts). Declined: each forget sits where the code knows the facts grow, and the rule is stated once, on the lastInferred field.
  • [core-kiss] The continue filter reuses jumpTarget, as loopLeftBy does. OK.
  • [name-searchable] The caps are unchanged and named (MAX_PER_VARIABLE, MAX_ROUNDS). 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.

1 participant