On this page
Loop invariants, frames, and termination
A loop proof summarizes any iteration allowed by its invariant and control conditions. The solver does not simply simulate the first few executions and extrapolate. State the relationship connecting modified values to progress, then show initialization, preservation and the required exit result. Termination is a separate progress property.
A safe loop that does not yet prove
The loop repair family counts from zero to a bounded input. All three versions require n <= 1000 and promise that the result equals n. The body increments a Natural once per iteration. Its initial value is zero, so actual executions are safe, but the unrepaired proof has no invariant relating that value to the iteration.
veradic prove --no-cache --project docs/manuals/examples/verification/loop/vibe/before/verada.tomlThe proof reports overflow and/or postcondition obligations with the diagnostic qualification that replay runs through rather than failing. The candidate loop state is not necessarily reachable from the operation's initial state. Increasing the budget is not the first repair: the missing inductive relationship is visible directly in the algorithm.
Derive the invariant
At the start of each iteration, the counter equals the number of completed increments. The three sources use different loop index origins:
| Syntax | Loop | Invariant at the top of the body |
|---|---|---|
| Vada | for I in 1 .. N loop |
pragma Loop_Invariant (Count = I - 1); |
| Varc | for I in 1..=N { |
invariant Count == I - 1; |
| Vibe | for i in range(n): |
invariant(count == i) |
These are excerpts from the repaired complete projects. Reason through four questions:
- Initialization: before the first iteration, the counter is zero and the first index is one (Vada/Varc) or zero (Vibe), so the relationship holds.
- Safety/usefulness: the current index and
n <= 1000bound the counter, so adding one fitsNatural. The invariant also carries the relation needed for the result. - Preservation: one increment and one index advance restore the same relationship at the next iteration's invariant point.
- Exit: after the last iteration the counter is
n; whenn = 0the loop is empty and the initial zero already satisfies the result promise.
The actual repaired Vibe function is:
def count_to(n: Natural) -> Natural:
requires(n <= 1000)
ensures(result == n)
count: Natural = 0
for i in range(n):
invariant(count == i)
count += 1
return countThis excerpt requires the imports in its complete module. Prove/run the matching after project. Its client prints count: 10. The invariant is stronger than an arbitrary small bound because it establishes the exact functional result. A bound such as count <= 1000 might help overflow but still fail to prove result equality.
Invariant placement matters
An invariant describes its own program point. An invariant after the body observes an updated accumulator; one before the body observes its prior value. Derive the equation for that position instead of copying a formula from another loop. Invariants must be directly in their supported loop context; frontend-specific helper placement is in the syntax references.
B5103 concerns first establishment, and B5104 concerns preservation. A failed initialization often means the formula assumes one iteration has already happened. A failed preservation often means an update/guard case was omitted or the relation is too strong. A downstream safety/postcondition failure with both invariant obligations proved often means the invariant is too weak for its intended use.
Frames and unchanged regions
A loop can modify one part of an object while preserving other parts. State the frame facts needed outside the loop: unchanged length/bounds, already processed prefix, untouched suffix, and correspondence with an entry model. A partial property such as “every processed element is nonnegative” does not also imply all unprocessed elements retain their values.
Useful patterns include:
| Algorithm | Progress relation | Frame/result relation |
|---|---|---|
| Search | All positions before the cursor were inspected | Earlier values differ from the key; source unchanged |
| Copy/update | Processed prefix equals the desired transformation | Remaining suffix equals the entry model |
| Accumulation | Accumulator describes the processed prefix | Bounds and remaining input values are retained |
| Ownership traversal | Cursor identifies the remaining owned structure | Moved/freed parts do not remain usable aliases |
The linear search and selection sort corpora show these patterns. Start from the desired postcondition and weaken it to describe the processed prefix at an arbitrary iteration. Then add facts making indexes and arithmetic in that formula safe.
Loop_Entry can snapshot a permitted value at loop entry; Old refers to subprogram entry. A nested loop may need a snapshot of the outer iteration's state rather than the entire operation's original state. Use the correct boundary and respect ownership/snapshot limits.
Quantified invariants and nested loops
For array algorithms, a quantified invariant can state a property over the processed range. Empty prefixes are important: at the first iteration, a universal condition over an empty range is true. Guard any index arithmetic used to form that range. Give nested loops separate invariants describing their own progress and the outer facts they must preserve.
Avoid asking the solver to discover a large nonlinear closed form when a small relational invariant suffices. If a lemma or intermediate assertion is needed, prove it separately and call/assert it at a point where its premises are available. This improves both correctness review and proof stability; it is not merely a performance trick.
Termination obligations
Functions, procedures marked with effective Always_Terminates, and applicable implicit finalizers/adjusters must satisfy the termination policy. Ordinary procedures are not universally required to terminate, but a procedure that one of these calls must: Verada then proves its termination where it is declared (its loops' variants, its recursion, its own calls), and the diagnostic's note names the caller that requires it. It need not carry Always_Terminates itself. An imported procedure is trusted to return.
For a supported while/unbounded loop, a variant provides strict progress in a bounded well-founded measure. A decreasing quantity must not decrease indefinitely; an increasing quantity must respect its upper bound. Lexicographic variants allow one component to progress while later components reset under the accepted rules. Arithmetic in the measure must be safe.
The division example maintains Q * D + R = N while decreasing remainder R under D > 0. The algebraic invariant proves the result relation; the variant proves progress. Neither replaces the other.
Finite numeric for loops provide a bounded traversal structure. For iterable containers, termination also depends on the iterator/type contract and its implementation. A library with a saturating cursor at its maximum representable position needs its documented size bound; do not infer every user-defined iterator terminates merely because the source spells for. The bounded-vector sentinel limit is an example.
Recursive operations
Subprogram_Variant provides the supported recursive progress relation. At each recursive call, prove that it progresses relative to the relevant entry measure. In the GCD corpus, the natural second argument decreases through A mod B when recursion continues with nonzero B.
Vibe's decreases(...) and increases(...) are loop variants. A recursive operation that Vibe code calls takes its Subprogram_Variant in a Vada or Varc declaration; in Vibe itself, write the algorithm as a loop with a variant.
Missing evidence is a structural diagnostic (B5108/B5112) before VC solving. A supplied but unproved progress measure has its own B5107/B5109 obligations. Variants are proved, not monitored at run time, and task scheduling and shutdown remain a separate liveness question.