Skip to content

Commit 380b1fb

Browse files
Add reference for loop contracts (#3849)
This PR adds reference of loop contracts: Rendered version: https://github.com/qinheping/kani/blob/docs/loop-contracts/docs/src/reference/experimental/loop-contracts.md By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses. --------- Co-authored-by: Zyad Hassan <88045115+zhassan-aws@users.noreply.github.com>
1 parent b29868a commit 380b1fb

File tree

1 file changed

+154
-0
lines changed

1 file changed

+154
-0
lines changed
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
# Loop Contracts
2+
3+
Loop contract are used to specify invariants for loops for the sake of extending Kani's *bounded proofs* to *unbounded proofs*.
4+
A [loop invariant](https://en.wikipedia.org/wiki/Loop_invariant) is an expression that holds upon entering a loop and after every execution of the loop body.
5+
It captures something that does not change about every step of the loop.
6+
7+
It is worth revisiting the discussion about [bounded proof](../../tutorial-loop-unwinding.md#bounded-proof) and
8+
[loop unwinding](../../tutorial-loop-unwinding.md#loops-unwinding-and-bounds). In short, bounds on the number of times Kani unwinds loops also bound the size of inputs,
9+
and hence result in a bounded proof.
10+
Loop contracts are used to abstract out loops as non-loop blocks to avoid loop unwinding, and hence remove the bounds on the inputs.
11+
12+
Consider the following example:
13+
14+
``` Rust
15+
fn simple_loop() {
16+
let mut x: u64 = kani::any_where(|i| *i >= 1);
17+
18+
while x > 1 {
19+
x = x - 1;
20+
}
21+
22+
assert!(x == 1);
23+
}
24+
```
25+
26+
In this program, the loop repeatedly decrements `x` until it equals `1`. Because we haven't specified an upper bound for `x`, to verify this function,
27+
Kani needs to unwind the loop for `u64::MAX` iterations, which is computationally expensive. Loop contracts allow us to abstract the loop behavior, significantly reducing the verification cost.
28+
29+
With loop contracts, we can specify the loop’s behavior using invariants. For example:
30+
31+
``` Rust
32+
#![feature(stmt_expr_attributes)]
33+
#![feature(proc_macro_hygiene)]
34+
35+
fn simple_loop_with_loop_contracts() {
36+
let mut x: u64 = kani::any_where(|i| *i >= 1);
37+
38+
#[kani::loop_invariant(x >= 1)]
39+
while x > 1 {
40+
x = x - 1;
41+
}
42+
43+
assert!(x == 1);
44+
}
45+
```
46+
47+
Here, the loop invariant `#[kani::loop_invariant(x >= 1)]` specifies that the condition `x >= 1` must hold true at the start of each iteration before the loop guard is
48+
checked. Once Kani verifies that the loop invariant is inductive, it will use the invariant to abstract the loop and avoid unwinding.
49+
50+
Now let's run the proof with loop contracts through kani:
51+
``` bash
52+
kani simple_loop_with_loop_contracts.rs -Z loop-contracts
53+
```
54+
The output reported by Kani on the example will be
55+
```
56+
...
57+
58+
59+
Check 10: simple_loop_with_loop_contracts.loop_invariant_base.1
60+
- Status: SUCCESS
61+
- Description: "Check invariant before entry for loop simple_loop_with_loop_contracts.0"
62+
- Location: simple_while_loop.rs:15:5 in function simple_loop_with_loop_contracts
63+
64+
Check 11: simple_loop_with_loop_contracts.loop_assigns.1
65+
- Status: SUCCESS
66+
- Description: "Check assigns clause inclusion for loop simple_loop_with_loop_contracts.0"
67+
- Location: simple_while_loop.rs:15:5 in function simple_loop_with_loop_contracts
68+
69+
Check 13: simple_loop_with_loop_contracts.assigns.1
70+
- Status: SUCCESS
71+
- Description: "Check that x is assignable"
72+
- Location: simple_while_loop.rs:17:9 in function simple_loop_with_loop_contracts
73+
74+
Check 14: simple_loop_with_loop_contracts.loop_invariant_step.1
75+
- Status: SUCCESS
76+
- Description: "Check invariant after step for loop simple_loop_with_loop_contracts.0"
77+
- Location: simple_while_loop.rs:15:5 in function simple_loop_with_loop_contracts
78+
79+
Check 15: simple_loop_with_loop_contracts.loop_invariant_step.2
80+
- Status: SUCCESS
81+
- Description: "Check invariant after step for loop simple_loop_with_loop_contracts.0"
82+
- Location: simple_while_loop.rs:15:5 in function simple_loop_with_loop_contracts
83+
84+
...
85+
86+
SUMMARY:
87+
** 0 of 99 failed
88+
89+
VERIFICATION:- SUCCESSFUL
90+
Verification Time: 0.3897019s
91+
92+
Complete - 1 successfully verified harnesses, 0 failures, 1 total.
93+
```
94+
95+
96+
## Loop contracts for `while` loops
97+
98+
### Syntax
99+
>
100+
> \#\[kani::loop_invariant\( [_Expression_](https://doc.rust-lang.org/reference/expressions.html) \)\]
101+
>
102+
> `while` [_Expression_](https://doc.rust-lang.org/reference/expressions.html)<sub>_except struct expression_</sub> [_BlockExpression_](https://doc.rust-lang.org/reference/expressions/block-expr.html)
103+
104+
105+
An invariant contract `#[kani::loop_invariant(cond)]` accepts a valid Boolean expression `cond` over the variables visible at the same scope as the loop.
106+
107+
### Semantics
108+
A loop invariant contract expands to several assumptions and assertions:
109+
1. The invariant is asserted just before the first iteration.
110+
2. The invariant is assumed on a non-deterministic state to model a non-deterministic iteration.
111+
3. The invariant is finally asserted again to establish its inductiveness.
112+
113+
Mathematical induction is the working principle here. (1) establishes the base case for induction, and (2) & (3) establish the inductive case.
114+
Therefore, the invariant must hold after the loop execution for any number of iterations. The invariant, together with the negation of the loop guard,
115+
must be sufficient to establish subsequent assertions. If it is not, the abstraction is too imprecise and the user must supply a stronger invariant.
116+
117+
To illustrate the key idea, we show how Kani abstracts the loop in `simple_loop_with_loop_contracts` as a non-loop block:
118+
``` Rust
119+
assert!(x >= 1) // check loop invariant for the base case.
120+
x = kani::any();
121+
kani::assume(x >= 1);
122+
if x > 1 {
123+
// proof path 1:
124+
// both loop guard and loop invariant are satisfied.
125+
x = x - 1;
126+
assert!(x >= 1); // check that loop invariant is inductive.
127+
kani::assume(false) // block this proof path.
128+
}
129+
// proof path 2:
130+
// loop invariant is satisfied and loop guard is violated.
131+
assert!(x == 1);
132+
```
133+
That is, we assume that we are in an arbitrary iteration after checking that the loop invariant holds for the base case. With the inductive hypothesis (`kani::assume(x >= 1);`),
134+
we will either enter the loop (proof path 1) or leave the loop (proof path 2). We prove the two paths separately by killing path 1 with `kani::assume(false);`.
135+
Note that all assertions after `kani::assume(false)` will be ignored as `false => p` can be deduced as `true` for any `p`.
136+
137+
In proof path 1, we prove properties inside the loop and at last check that the loop invariant is inductive.
138+
139+
In proof path 2, we prove properties after leaving the loop. As we leave the loop only when the loop guard is violated, the post condition of the loop can be expressed as
140+
`!guard && inv`, which is `x <= 1 && x >= 1` in the example. The postcondition implies `x == 1`—the property we want to prove at the end of `simple_loop_with_loop_contracts`.
141+
142+
143+
## Limitations
144+
145+
Loop contracts comes with the following limitations.
146+
147+
1. Only `while` loops are supported. The other three kinds of loops are not supported: [`loop` loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html#infinite-loops)
148+
, [`while let` loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-pattern-loops), and [`for` loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html#iterator-loops).
149+
2. Kani infers *loop modifies* with alias analysis. Loop modifies are those variables we assume to be arbitrary in the inductive hypothesis, and should cover all memory locations that are written to during
150+
the execution of the loops. A proof will fail if the inferred loop modifies misses some targets written in the loops.
151+
We observed this happens when some fields of structs are modified by some other functions called in the loops.
152+
3. Kani doesn't check if a loop will always terminate in proofs with loop contracts. So it could be that some properties are proved successfully with Kani but actually are unreachable due to the
153+
non-termination of some loops.
154+
4. We don't check if loop invariants are side-effect free. A loop invariant with a side effect could lead to an unsound proof result. Make sure that the specified loop contracts are side-effect free.

0 commit comments

Comments
 (0)