How to Prove a Rust Function Correct With Verus: Write a Spec, Read the Prover’s Errors, and Find the Bugs Tests Miss
Install Verus on Windows, prove a Rust function and a binary search correct for every input, read the prover’s error messages, and plant nine bugs to see which ones tests catch and which only the...
A test shows that a function gives the right answer for the inputs you tried. A proof shows that it gives the right answer for every input the function accepts. This tutorial teaches you to write such proofs for Rust code with Verus, an open-source (MIT-licensed) verifier that checks your code against a written contract before the program ever runs. You will install it on Windows, verify a first function, break it on purpose and read the error messages, prove a loop correct, and finish with a binary search that Verus proves correct for vectors of any length. Then you will find out how much that proof is worth by planting nine bugs in the binary search and seeing which ones tests catch and which ones only the prover catches.
Table Of Content
- The words used in this tutorial
- Prerequisites
- Step 1: Install Verus and check that it runs
- 1.1 Download the release and check its hash
- 1.2 Unzip it and put it on your PATH
- 1.3 Install the Rust compiler that Verus asks for
- 1.4 Check that Verus runs
- Common mistakes in Step 1
- Step 2: Verify your first function
- 2.1 Write the function and its contract
- 2.2 Run the prover
- 2.3 Break it on purpose and read the error
- Step 3: Preconditions and the overflow check
- 3.1 Let Verus find an overflow
- 3.2 State what callers must promise
- 3.3 See the promise enforced at the call site
- 3.4 The midpoint bug in miniature
- Step 4: Prove a loop with an invariant
- 4.1 Find the largest number in a vector
- 4.2 What the errors look like when the invariant is missing or wrong
- Step 5: Prove a binary search
- 5.1 The specification
- 5.2 The code and its invariant
- 5.3 The midpoint bug that fooled a whole industry
- Step 6: A green result is only as strong as the specification
- 6.1 A promise that anything can keep
- 6.2 A precondition nobody can meet
- 6.3 Holes you can open on purpose
- Step 7: Plant bugs and see who catches them
- 7.1 The test program
- 7.2 The mutation script
- 7.3 Run it and read the table
- Step 8: Make the check part of your build
- Reading Verus’s messages: a cheat sheet
- Step 9: Run everything once
- Where to go next
- What to remember
- Sources and further reading
Two recent posts on this site leaned on proof tools without teaching them: our audit of Microsoft’s PDD Kit, which ran Verus on a contract printed in a Microsoft Research post, and our reading of DeepMind’s Signal proofs, which are written in a different tool called Lean. This tutorial starts from zero. Its mirror image is our tutorial on property-based testing in Rust with proptest: that one hunts for bugs by trying many inputs, and this one tries to rule bugs out for all of them.
By the end you will be able to:
- explain what a specification is, and write one with
requires(what a caller must promise) andensures(what the function promises back); - install Verus on Windows and run it on a file;
- read the eight messages this tutorial walks through and say what each one means;
- write a loop invariant and a
decreasesclause, and say why a loop needs both; - prove a binary search correct, including its “not found” answer;
- recognize three ways a green result can mislead you: a promise that anything satisfies, a precondition nobody can meet, and an
assume; - measure what a proof adds to your tests, using nine planted bugs and four judges.
Everything below was run on Windows 11 on November 22, 2026, with Verus 0.2026.11.02.8bf68ee, the Rust 1.99.1 compiler that this Verus release asks for, and the Z3 4.16.0 solver that comes in the Verus download. Python 3.13.14 ran the two helper scripts in Steps 7 and 9. Every output block is copied from those runs, and each Verus run takes about a second, so you can type each step as you read. The Verus project describes its point releases as weekly, so a newer version may word a message differently from the ones shown here.
The words used in this tutorial
- Specification (or contract). A precise written statement of what a function needs and what it promises. Verus checks the code against it.
- Precondition (
requires). A condition that must hold when the function is called. It is the caller’s duty. - Postcondition (
ensures). A condition that holds when the function returns. It is the function’s promise. - Loop invariant. A statement that is true before the loop starts, true again after every pass through the loop, and therefore true when the loop ends.
decreases. A whole number that gets smaller on every pass of a loop and cannot go below zero. It shows that the loop has to end.- SMT solver. A program that checks whether a logical formula can be true. Verus hands its questions to one; by default that is Z3, which is inside the download.
- Spec function. A function that exists only to be used in specifications, such as
sortedin Step 5. It is never run. - Ghost code. Code and proof steps that exist only for the prover and disappear when the program is compiled.
- Planted bug (mutation). A small deliberate mistake that you put into correct code to see whether your checks notice it.
- Exhaustive small-scope test. A test that tries every input up to a small size instead of a few hand-picked ones.
The Verus guide describes the whole approach in one sentence: “Verification is static: Verus adds no run-time checks, but instead uses computer-aided theorem proving to statically verify that executable Rust code will always satisfy some user-provided specifications for all possible executions of the code.” Keep that sentence in mind. A Verus proof says nothing about speed, and it says nothing about code you did not ask it to look at, and we will meet both limits below.
Prerequisites
- A computer. Windows 11, 64-bit, for the commands as written. The Verus install notes give “first-tier support to relatively recent OS distributions (MacOS, Windows and Ubuntu)”, so the same steps work elsewhere with the zip file for your platform.
- PowerShell. The one that comes with Windows is enough.
- rustup, the Rust toolchain manager, from rustup.rs. Verus is built against one exact compiler version, and you install that version with rustup in Step 1.
- Python 3, only for the two scripts in Steps 7 and 9.
- Some Rust. You should be able to read a function, a
Vec, awhileloop and anOption. You do not need any logic beyond “for every” and “there is some”. - About 100 MB of disk space for Verus itself, plus whatever the Rust toolchain needs.
- A folder to work in. This tutorial uses
C:\verus-lab, and every file below goes there.
Step 1: Install Verus and check that it runs
Verus is a command-line program. You download a zip file, unzip it, and run verus.exe on a Rust file. The only subtle part is the Rust compiler version, which we handle in 1.3.
1.1 Download the release and check its hash
Verus is published as a zip file on its GitHub releases page. The install notes recommend the weekly point releases, and the file for 64-bit Windows is named verus-VERSION-x86-win.zip. Open PowerShell and run:
mkdir C:\verus-lab
cd C:\verus-lab
$ver = "0.2026.11.02.8bf68ee"
$url = "https://github.com/verus-lang/verus/releases/download/release/$ver/verus-$ver-x86-win.zip"
Invoke-WebRequest -Uri $url -OutFile verus.zip
(Get-FileHash .\verus.zip -Algorithm SHA256).Hash.ToLower()
Invoke-WebRequest downloads the file, which is about 26 MB. Get-FileHash computes its SHA-256 fingerprint. GitHub shows the expected fingerprint next to each release file, and comparing the two tells you that the download is complete and is the file the project published. For this release the command prints:
221f471d5925c4b55362cbd20a1bb15333338962902c2283b3f2b4d4c8930456
If your fingerprint differs, delete verus.zip and download it again.
1.2 Unzip it and put it on your PATH
Expand-Archive .\verus.zip -DestinationPath .\verus
$env:Path = "$PWD\verus\verus-x86-win;$env:Path"
The zip holds one folder, verus-x86-win, with ten files: verus.exe (the tool you run), z3.exe (the solver), rust_verify.exe and two macro libraries (the machinery behind verus.exe), the standard library vstd as libvstd.rlib and vstd.vir, libverus_builtin.rlib, cargo-verus.exe and version.json. They add up to about 104 MB. The second line adds that folder to the Path variable of this PowerShell window, so that typing verus finds it.
1.3 Install the Rust compiler that Verus asks for
Verus is built against one specific version of the Rust compiler, and this release wants 1.99.1. If the right toolchain is missing, the install notes say Verus prints the exact rustup command you need, so you can also let Verus tell you. Here it is up front:
rustup toolchain install 1.99.1-x86_64-pc-windows-msvc --profile minimal
The --profile minimal flag installs just the compiler and the standard library. On the lab machine the toolchain was already there, so rustup printed:
info: syncing channel updates for 1.99.1-x86_64-pc-windows-msvc
1.99.1-x86_64-pc-windows-msvc unchanged - rustc 1.99.1 (58cf8f9c3 2026-10-13)
info: checking for self-update (current version: 1.29.3)
On a machine without that toolchain, rustup downloads it first. Windows PowerShell 5.1 may wrap rustup’s info: lines in a red banner that ends in NativeCommandError. That is only how PowerShell 5.1 displays text that a program writes to its error stream; it is not a failure.
1.4 Check that Verus runs
verus --version
Verus
Version: 0.2026.11.02.8bf68ee
Profile: release
Platform: windows_x86_64
Toolchain: 1.99.1-x86_64-pc-windows-msvc (overridden by environment variable RUSTUP_TOOLCHAIN)
The version is the release you downloaded, and the toolchain is the compiler Verus will use. Your default Rust toolchain does not have to match: on the lab machine the default is the stable channel, which is Rust 1.97.1, and Verus still reports 1.99.1. The words in brackets at the end of the last line are Verus’s own note about how it picked that toolchain; I never set the RUSTUP_TOOLCHAIN variable in my shell. The project’s rust-toolchain.toml for this release pins channel = "1.99.1".
Common mistakes in Step 1
- PowerShell says it does not recognize the term
verus. The$env:Pathline only lasts for the PowerShell window it was typed in. Run it again in each new window, or type the full path toverus.exe. - A message about rustup or a toolchain. Verus printed what it needs. Run the command it shows, then run
verus --versionagain. - A different hash. Download the file again before you run anything from it.
Step 2: Verify your first function
A function has a body, which says what it does, and a contract, which says what it promises. A test runs the body on a few inputs and compares the results with what you expect. Verus does something different: it reads the body and the contract together and tries to prove that no allowed input can break a promise.
2.1 Write the function and its contract
Create s01_max.rs in C:\verus-lab with this content:
// s01_max.rs
use vstd::prelude::*;
verus! {
fn max_u64(a: u64, b: u64) -> (r: u64)
ensures
r >= a,
r >= b,
r == a || r == b,
{
if a >= b { a } else { b }
}
} // verus!
Here is what each part does.
use vstd::prelude::*;brings invstd, Verus’s standard library of specification tools.verus! { ... }is a macro that marks the code Verus must check. The guide is explicit about it: “Verus only examines Rust code that the developer explicitly indicates should be verified”. Anything outside the macro is ordinary Rust that Verus does not look at.-> (r: u64)gives the return value the namer, so that the contract can talk about it.- The three
ensuresclauses are the promise: the result is at leasta, at leastb, and equal to one of them. Together they say “the larger of the two” without saying how to compute it. - The body is plain Rust: return
aifa >= b, otherwiseb.
2.2 Run the prover
verus --crate-type=lib s01_max.rs
The flag --crate-type=lib tells Verus the file is a library, so it does not need a main function. Output:
verification results:: 1 verified, 0 errors
One item verified and no errors. Verus took the body and the three clauses, turned them into logical questions, and asked Z3 whether any input could break a clause. The solver ruled that out. Because the question covers every pair of u64 values, this is a stronger statement than any list of examples could be.
2.3 Break it on purpose and read the error
Save a copy as s02_max_bug.rs and change only the last line of the body, so that it returns the smaller number:
// s02_max_bug.rs
use vstd::prelude::*;
verus! {
fn max_u64(a: u64, b: u64) -> (r: u64)
ensures
r >= a,
r >= b,
r == a || r == b,
{
if a <= b { a } else { b }
}
} // verus!
verus --crate-type=lib s02_max_bug.rs
verification results:: 0 verified, 1 errors
note: function body check: not all errors may have been reported; rerun with a higher value for --multiple-errors to find other potential errors in this function
--> s02_max_bug.rs:6:1
|
6 | fn max_u64(a: u64, b: u64) -> (r: u64)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: postcondition not satisfied
--> s02_max_bug.rs:8:9
|
8 | r >= a,
| ^^^^^^ failed this postcondition
...
12 | if a <= b { a } else { b }
| -------------------------- at the end of the function body
error: postcondition not satisfied
--> s02_max_bug.rs:9:9
|
9 | r >= b,
| ^^^^^^ failed this postcondition
...
12 | if a <= b { a } else { b }
| -------------------------- at the end of the function body
error: aborting due to 2 previous errors
Verus does not tell you how to fix the problem, but it shows exactly where to look:
error: postcondition not satisfiednames the kind of failure: a promise in anensuresclause can be broken.- The arrow line,
s02_max_bug.rs:8:9, is the file, line and column of the clause that failed. The labelfailed this postconditionunderlines it. - The second label,
at the end of the function body, points at the returning expression, where the broken promise would be seen by a caller. - There are two errors because each clause can fail on some path. When
a < bthe function returnsa, which is smaller thanb, sor >= bfails. Whena > bit returnsb, which is smaller thana, sor >= afails. - The
notewarns that not every error in the function may have been reported, and suggests a higher--multiple-errorsvalue if you want to see more.
Checkpoint. You now know the whole working loop of verification: write a contract, run Verus, and read which clause failed and where. Everything else in this tutorial is a new kind of clause or a new kind of message.
Step 3: Preconditions and the overflow check
Many functions only work for some inputs. A precondition, written with requires, says which inputs. Rust integers have a second reason to need preconditions: they have limits. The guide states the rule for ordinary code: “In executable code, we frequently have to reason about integer overflow, and in fact, Verus requires us to prove the absence of overflow.”
3.1 Let Verus find an overflow
Create s03_add_bad.rs, a function that adds one to a u32:
// s03_add_bad.rs
use vstd::prelude::*;
verus! {
fn add_one(x: u32) -> (r: u32)
ensures
r == x + 1,
{
x + 1
}
} // verus!
verus --crate-type=lib s03_add_bad.rs
verification results:: 0 verified, 1 errors
error: possible arithmetic underflow/overflow
--> s03_add_bad.rs:10:5
|
10 | x + 1
| ^^^^^
error: aborting due to 1 previous error
The contract says r == x + 1, and Verus accepts that clause. Inside a contract, + is ordinary mathematical addition on numbers that never run out of room. The guide says the common arithmetic operations in this ghost code “never overflow or wrap”. The failure is in the body, where x + 1 is real u32 arithmetic: when x is u32::MAX, the sum does not fit. Verus reported that overflow is possible without waiting for such an input to turn up at run time.
3.2 State what callers must promise
The fix is to say what the function needs. Create s04_add_requires.rs:
// s04_add_requires.rs
use vstd::prelude::*;
verus! {
fn add_one(x: u32) -> (r: u32)
requires
x < u32::MAX,
ensures
r == x + 1,
{
x + 1
}
fn caller_ok() {
let y = add_one(41);
assert(y == 42);
}
} // verus!
verus --crate-type=lib s04_add_requires.rs
verification results:: 2 verified, 0 errors
Two items verified: add_one and caller_ok. The requires clause turns the contract into a handshake. Inside add_one, Verus may assume that x < u32::MAX, which is why the addition is now safe. In caller_ok, Verus must prove that the argument 41 meets that condition, and it can. After the call it knows from the ensures clause that y == 41 + 1, so assert(y == 42) holds. An assert inside verus! is a proof step that Verus checks while verifying; it costs nothing when the program runs.
3.3 See the promise enforced at the call site
A precondition binds every caller. Create s05_add_caller_bad.rs, where a caller passes along an argument it knows nothing about:
// s05_add_caller_bad.rs
use vstd::prelude::*;
verus! {
fn add_one(x: u32) -> (r: u32)
requires
x < u32::MAX,
ensures
r == x + 1,
{
x + 1
}
fn caller_bad(x: u32) -> (r: u32) {
add_one(x)
}
} // verus!
verus --crate-type=lib s05_add_caller_bad.rs
verification results:: 1 verified, 1 errors
error: precondition not satisfied
--> s05_add_caller_bad.rs:16:5
|
8 | x < u32::MAX,
| ------------ failed precondition
...
16 | add_one(x)
| ^^^^^^^^^^
error: aborting due to 1 previous error
The first label, failed precondition, underlines the clause x < u32::MAX in add_one. The second underlines the call that might break it. The count says 1 verified, 1 errors, because add_one itself is fine and the problem is in its caller. You would fix this by adding requires x < u32::MAX to caller_bad, or by handling the maximum value in a separate branch.
3.4 The midpoint bug in miniature
One more overflow, because you will meet it again in Step 5. A midpoint function takes two bytes with lo <= hi and returns a number between them. The obvious body is (lo + hi) / 2. With lo at 100 and hi at 200, the sum is 300, which does not fit in a u8. Create s06_mid_bad.rs:
// s06_mid_bad.rs
use vstd::prelude::*;
verus! {
fn midpoint(lo: u8, hi: u8) -> (r: u8)
requires
lo <= hi,
ensures
lo <= r <= hi,
{
(lo + hi) / 2
}
} // verus!
verus --crate-type=lib s06_mid_bad.rs
verification results:: 0 verified, 1 errors
error: possible arithmetic underflow/overflow
--> s06_mid_bad.rs:12:5
|
12 | (lo + hi) / 2
| ^^^^^^^^^
error: aborting due to 1 previous error
Now rewrite the body as lo + (hi - lo) / 2 in s07_mid_good.rs:
// s07_mid_good.rs
use vstd::prelude::*;
verus! {
fn midpoint(lo: u8, hi: u8) -> (r: u8)
requires
lo <= hi,
ensures
lo <= r <= hi,
{
lo + (hi - lo) / 2
}
} // verus!
verus --crate-type=lib s07_mid_good.rs
verification results:: 1 verified, 0 errors
The new form never adds two large numbers. hi - lo cannot go below zero because the precondition says lo <= hi, and lo plus half of hi - lo cannot pass hi. Verus also proved the postcondition lo <= r <= hi, so the same run checked the arithmetic and the meaning.
Checkpoint. You can now read three message kinds: postcondition not satisfied, possible arithmetic underflow/overflow and precondition not satisfied. A precondition is the caller’s duty and a postcondition is the function’s promise.
Step 4: Prove a loop with an invariant
A loop is hard for a prover, because it does not know how many times the loop will run and so cannot simply follow the code step by step. Instead you describe what stays true on every pass. That description is the loop invariant, and it has three jobs:
- It must be true when the loop starts.
- If it is true at the start of a pass, it must still be true at the end of that pass.
- When the loop ends, the invariant plus the fact that the loop condition is now false must be enough to prove the promise the function makes.
A loop also needs a reason to end. That is the decreases clause: a quantity that shrinks on every pass and cannot go below zero.
4.1 Find the largest number in a vector
Create s08_max_of.rs:
// s08_max_of.rs
use vstd::prelude::*;
verus! {
fn max_of(v: &Vec<u64>) -> (m: u64)
requires
v.len() > 0,
ensures
forall|i: int| 0 <= i < v.len() ==> v[i] <= m,
exists|i: int| 0 <= i < v.len() && v[i] == m,
{
let mut m = v[0];
let mut k: usize = 1;
while k < v.len()
invariant
1 <= k <= v.len(),
forall|i: int| 0 <= i < k ==> v[i] <= m,
exists|i: int| 0 <= i < k && v[i] == m,
decreases v.len() - k,
{
if v[k] > m {
m = v[k];
}
k += 1;
}
m
}
} // verus!
Take it in pieces.
v: &Vec<u64>is a borrowed vector. In the contract,v[i]withi: intmeans “the element at positioni”, whereintis the unbounded mathematical integer that exists only in specifications.requires v.len() > 0excludes the empty vector, which has no largest element.- The first
ensuressays every element is at mostm. The second saysmreally is one of the elements. You need both: a function that returnedu64::MAXevery time would satisfy the first alone. - The invariant repeats the promise for the part of the vector the loop has seen so far, the first
kelements:mis at least each of them and equals one of them. The line1 <= k <= v.len()keepskin range. decreases v.len() - kis the shrinking number: how many elements are left.
verus --crate-type=lib s08_max_of.rs
verification results:: 2 verified, 0 errors
Two items verified. Verus counts each function body and each loop separately, so one function with one loop gives two. (A throwaway file with one function and two loops reported three.) When the loop ends, k equals v.len(), so “the first k elements” is the whole vector, and the invariant turns into the postcondition.
4.2 What the errors look like when the invariant is missing or wrong
Make three broken copies of the file and read what Verus says about each. First, s09_max_of_no_invariant.rs, where the loop keeps only the bounds on k:
// s09_max_of_no_invariant.rs
use vstd::prelude::*;
verus! {
fn max_of(v: &Vec<u64>) -> (m: u64)
requires
v.len() > 0,
ensures
forall|i: int| 0 <= i < v.len() ==> v[i] <= m,
exists|i: int| 0 <= i < v.len() && v[i] == m,
{
let mut m = v[0];
let mut k: usize = 1;
while k < v.len()
invariant
1 <= k <= v.len(),
decreases v.len() - k,
{
if v[k] > m {
m = v[k];
}
k += 1;
}
m
}
} // verus!
verus --crate-type=lib s09_max_of_no_invariant.rs
verification results:: 1 verified, 1 errors
note: function body check: not all errors may have been reported; rerun with a higher value for --multiple-errors to find other potential errors in this function
--> s09_max_of_no_invariant.rs:6:1
|
6 | fn max_of(v: &Vec<u64>) -> (m: u64)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: postcondition not satisfied
--> s09_max_of_no_invariant.rs:10:9
|
10 | forall|i: int| 0 <= i < v.len() ==> v[i] <= m,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ failed this postcondition
...
25 | m
| - at the end of the function body
error: postcondition not satisfied
--> s09_max_of_no_invariant.rs:11:9
|
11 | exists|i: int| 0 <= i < v.len() && v[i] == m,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ failed this postcondition
...
25 | m
| - at the end of the function body
error: aborting due to 2 previous errors
The loop itself verifies, because the weak invariant is true. The function fails at the end: once the loop is over, Verus remembers only what the invariant says about the variables the loop changed, and the invariant says nothing about m. Both postconditions fail. This is the most common error when you first write loops, and the cure is always the same: put into the invariant what you need to know afterwards.
Second, s10_max_of_bad_invariant.rs, where the bound is a little too strict (k < v.len() instead of k <= v.len()):
// s10_max_of_bad_invariant.rs
use vstd::prelude::*;
verus! {
fn max_of(v: &Vec<u64>) -> (m: u64)
requires
v.len() > 0,
ensures
forall|i: int| 0 <= i < v.len() ==> v[i] <= m,
exists|i: int| 0 <= i < v.len() && v[i] == m,
{
let mut m = v[0];
let mut k: usize = 1;
while k < v.len()
invariant
1 <= k < v.len(),
forall|i: int| 0 <= i < k ==> v[i] <= m,
exists|i: int| 0 <= i < k && v[i] == m,
decreases v.len() - k,
{
if v[k] > m {
m = v[k];
}
k += 1;
}
m
}
} // verus!
verus --crate-type=lib s10_max_of_bad_invariant.rs
verification results:: 0 verified, 2 errors
error: invariant not satisfied at end of loop body
--> s10_max_of_bad_invariant.rs:17:13
|
17 | 1 <= k < v.len(),
| ^^^^^^^^^^^^^^^^
error: invariant not satisfied before loop
--> s10_max_of_bad_invariant.rs:17:13
|
17 | 1 <= k < v.len(),
| ^^^^^^^^^^^^^^^^
error: aborting due to 2 previous errors
These are the first two jobs of an invariant failing. invariant not satisfied before loop says it is not true on entry: k starts at 1, and a vector with exactly one element has v.len() equal to 1. invariant not satisfied at end of loop body says one pass can break it: after the last increment k equals v.len(). An invariant has to hold at the end of every pass, including the last.
Third, s11_max_of_no_decreases.rs, with the decreases line removed:
// s11_max_of_no_decreases.rs
use vstd::prelude::*;
verus! {
fn max_of(v: &Vec<u64>) -> (m: u64)
requires
v.len() > 0,
ensures
forall|i: int| 0 <= i < v.len() ==> v[i] <= m,
exists|i: int| 0 <= i < v.len() && v[i] == m,
{
let mut m = v[0];
let mut k: usize = 1;
while k < v.len()
invariant
1 <= k <= v.len(),
forall|i: int| 0 <= i < k ==> v[i] <= m,
exists|i: int| 0 <= i < k && v[i] == m,
{
if v[k] > m {
m = v[k];
}
k += 1;
}
m
}
} // verus!
verus --crate-type=lib s11_max_of_no_decreases.rs
error: loop must have a `decreases` clause
--> s11_max_of_no_decreases.rs:15:5
|
15 | while k < v.len()
| ^^^^^^^^^^^^^^^^^
|
= help: to disable this check, use `#[verifier::exec_allows_no_decreases_clause]` on the function
error: aborting due to 1 previous error
This one is not a failed proof but a missing piece, and Verus stops before it proves anything. A word of caution from the guide: checking decreases clauses in ordinary code “should be treated as a lint, not a complete guarantee of termination.” It catches the common slip of a counter that never moves, which is what you want from it, but it is not a proof that the whole program stops.
Checkpoint. You can now read invariant not satisfied before loop, invariant not satisfied at end of loop body and loop must have a `decreases` clause, and you know that a loop forgets everything about the variables it changes except what the invariant keeps.
Step 5: Prove a binary search
Binary search finds a value in a sorted vector by looking at the middle and discarding the half that cannot hold it. It looks like the simplest algorithm there is, and it has a famous history of bugs, one of which you will reproduce below. The Verus guide has its own binary search example, which assumes that the key is somewhere in the vector. The version here also proves the other answer: when the function says “not found”, it is right.
5.1 The specification
Two pieces of language are new here. v@ is the vector’s contents viewed as a mathematical sequence, which is what a specification talks about. spec fn sorted defines a reusable fact about such a sequence: for every two positions i < j, the element at i is at most the element at j. Spec functions are never run; they only name an idea.
The promise has two branches, because the function returns an Option:
- If it returns
Some(i), theniis a valid position andv[i]equals the target. - If it returns
None, then no element of the vector equals the target.
5.2 The code and its invariant
Create s12_bsearch.rs:
// s12_bsearch.rs
use vstd::prelude::*;
verus! {
spec fn sorted(s: Seq<u64>) -> bool {
forall|i: int, j: int| 0 <= i < j < s.len() ==> s[i] <= s[j]
}
fn binary_search(v: &Vec<u64>, target: u64) -> (r: Option<usize>)
requires
sorted(v@),
ensures
match r {
Some(i) => i < v.len() && v[i as int] == target,
None => forall|i: int| 0 <= i < v.len() ==> v[i] != target,
},
{
let mut lo: usize = 0;
let mut hi: usize = v.len();
while lo < hi
invariant
lo <= hi <= v.len(),
sorted(v@),
forall|i: int| 0 <= i < lo ==> v[i] < target,
forall|i: int| hi <= i < v.len() ==> v[i] > target,
decreases hi - lo,
{
let mid = lo + (hi - lo) / 2;
if v[mid] == target {
return Some(mid);
} else if v[mid] < target {
lo = mid + 1;
} else {
hi = mid;
}
}
None
}
} // verus!
The search keeps a window of positions from lo up to but not including hi. The loop invariant has two halves that say what has been ruled out: every element before lo is smaller than the target, and every element from hi onward is larger. The other two lines keep the window inside the vector and remember that the vector is sorted.
Each pass looks at mid. If v[mid] is the target, the function returns. If it is smaller, then because the vector is sorted everything up to and including mid is smaller than the target as well, so lo moves to mid + 1. If it is larger, everything from mid onward is larger than the target, so hi moves to mid. Either way the window shrinks, and decreases hi - lo says so. When the loop ends, lo == hi, so the two ruled-out halves cover the whole vector, and the target is absent. That is exactly the None promise.
verus --crate-type=lib s12_bsearch.rs
verification results:: 2 verified, 0 errors
It verifies with no hints from you. Verus also proved things you never wrote down: that mid is a valid position whenever v[mid] is read, and that no arithmetic overflows. The guide’s list of what a successful run promises includes “The code is panic free, modulo resource exhaustion”, and the index check is part of that. With --time, one run on the lab machine reported 514 ms in total, of which the solver itself ran for 8 ms.
5.3 The midpoint bug that fooled a whole industry
Now change one line, from lo + (hi - lo) / 2 to the form most people write first, (lo + hi) / 2. Save the result as s13_bsearch_mid.rs:
// s13_bsearch_mid.rs
use vstd::prelude::*;
verus! {
spec fn sorted(s: Seq<u64>) -> bool {
forall|i: int, j: int| 0 <= i < j < s.len() ==> s[i] <= s[j]
}
fn binary_search(v: &Vec<u64>, target: u64) -> (r: Option<usize>)
requires
sorted(v@),
ensures
match r {
Some(i) => i < v.len() && v[i as int] == target,
None => forall|i: int| 0 <= i < v.len() ==> v[i] != target,
},
{
let mut lo: usize = 0;
let mut hi: usize = v.len();
while lo < hi
invariant
lo <= hi <= v.len(),
sorted(v@),
forall|i: int| 0 <= i < lo ==> v[i] < target,
forall|i: int| hi <= i < v.len() ==> v[i] > target,
decreases hi - lo,
{
let mid = (lo + hi) / 2;
if v[mid] == target {
return Some(mid);
} else if v[mid] < target {
lo = mid + 1;
} else {
hi = mid;
}
}
None
}
} // verus!
verus --crate-type=lib s13_bsearch_mid.rs
verification results:: 1 verified, 1 errors
error: possible arithmetic underflow/overflow
--> s13_bsearch_mid.rs:29:19
|
29 | let mid = (lo + hi) / 2;
| ^^^^^^^^^
error: aborting due to 1 previous error
Joshua Bloch’s 2006 post about the discovery that nearly all binary searches and mergesorts were broken told the story of this exact line in Java’s standard library. His closing advice fits this tutorial: “It is not sufficient merely to prove a program correct; you have to test it too.” He added that “to be really certain that a program is correct, you have to test it for all possible input values, but this is seldom feasible.” Verus is a way to cover the inputs that testing cannot reach.
Be careful about how far to take the verdict, though. On a real Vec<u64> this addition cannot overflow. Rust’s documentation says a vector panics if its capacity would exceed isize::MAX bytes, so a vector of u64 values holds at most an eighth of that many elements, and the sum of two such positions fits easily. Verus does not know that. In the vstd specification of Vec that Verus reads, a source comment on the length axiom says that “the axiom also shows that [email protected]() is in-bounds for usize”, and a bound of usize is not enough to rule out the sum overflowing. The rule is different for vectors of zero-sized types, where the Rust documentation says “the capacity will always be usize::MAX”. So the prover is not wrong; it is strict. It asks for a form that works for every length, and that form costs nothing.
Checkpoint. You have a proof, written for a function you can run, that a binary search is correct for every sorted vector. The next two steps are about how far to trust that proof.
Step 6: A green result is only as strong as the specification
Verus checks the code against the contract you wrote. If the contract is weak, the check is weak, and Verus will not warn you. The guide says it plainly: “Note that the last guarantee is only as strong as the specification itself.” It gives a pointed example. For a function that returns an Option, a specification that only says something about the Some case allows an implementation that always returns None. That implementation satisfies the spec, in the guide’s words, “but likely not satisfying the caller.” Three traps follow, each with a lab file.
6.1 A promise that anything can keep
Suppose you want a function that puts two numbers in order and you write only the obvious promise. Create s14_pair_weak.rs:
// s14_pair_weak.rs
use vstd::prelude::*;
verus! {
fn order_pair(a: u64, b: u64) -> (r: (u64, u64))
ensures
r.0 <= r.1,
{
(0, 0)
}
} // verus!
verus --crate-type=lib s14_pair_weak.rs
verification results:: 1 verified, 0 errors
It verifies, and the body returns (0, 0) whatever you pass in. The pair is ordered, which is all the contract asked for. The missing promise is that the result is made of the inputs. Create s15_pair_strong.rs with that clause added:
// s15_pair_strong.rs
use vstd::prelude::*;
verus! {
fn order_pair(a: u64, b: u64) -> (r: (u64, u64))
ensures
r.0 <= r.1,
(r.0 == a && r.1 == b) || (r.0 == b && r.1 == a),
{
if a <= b { (a, b) } else { (b, a) }
}
} // verus!
verus --crate-type=lib s15_pair_strong.rs
verification results:: 1 verified, 0 errors
The new clause says the result is either (a, b) or (b, a). The honest body passes. I also put the (0, 0) body back under this contract, and Verus reported the new clause as the one that fails. When you read a contract, ask what a lazy implementation could return, and write the clause that rules it out.
6.2 A precondition nobody can meet
If the requires clauses contradict each other, no caller can satisfy them, so the function can never be called, and anything you promise about it is true. Create s16_vacuous.rs:
// s16_vacuous.rs
use vstd::prelude::*;
verus! {
fn impossible(x: u32) -> (r: u32)
requires
x > 5,
x < 3,
ensures
r == 12345,
r == 54321,
{
0
}
} // verus!
verus --crate-type=lib s16_vacuous.rs
verification results:: 1 verified, 0 errors
The function promises that r equals both 12345 and 54321, and Verus accepts it, because no x is both above 5 and below 3. The cheap defense is a smoke test: write one caller that uses the function the way a real caller would. Create s17_vacuous_smoke.rs:
// s17_vacuous_smoke.rs
use vstd::prelude::*;
verus! {
fn impossible(x: u32) -> (r: u32)
requires
x > 5,
x < 3,
ensures
r == 12345,
r == 54321,
{
0
}
fn smoke_test() {
let r = impossible(7);
}
} // verus!
verus --crate-type=lib s17_vacuous_smoke.rs
verification results:: 1 verified, 1 errors
error: precondition not satisfied
--> s17_vacuous_smoke.rs:18:13
|
9 | x < 3,
| ----- failed precondition
...
18 | let r = impossible(7);
| ^^^^^^^^^^^^^
error: aborting due to 1 previous error
Verus must now prove the preconditions at the call, and it cannot, so the contradiction shows up as precondition not satisfied. This is the same message as in Step 3, now used as a detector. The caller_ok function in s04_add_requires.rs was a smoke test too.
6.3 Holes you can open on purpose
Verus lets you state a fact without proving it. That is useful in big projects, and it is also the easiest way to make a proof meaningless. Create s18_assume.rs:
// s18_assume.rs
use vstd::prelude::*;
verus! {
fn double(x: u32) -> (r: u32)
ensures
r == 2 * x,
{
assume(false);
7
}
} // verus!
verus --crate-type=lib s18_assume.rs
verification results:: 1 verified, 0 errors
The function claims r == 2 * x and returns 7. It verifies, because assume(false) tells Verus to take a false statement as true, and from a false statement everything follows. Now run the same file with the flag that forbids such holes:
verus --crate-type=lib --no-cheating s18_assume.rs
error: `assume`/`admit` not allowed with `--no-cheating`
--> s18_assume.rs:10:5
|
10 | assume(false);
| ^^^^^^
error: aborting due to 1 previous error
The guide lists the other ways to introduce an assumption: an assume statement, a function marked #[verifier::external_body] or declared as an axiom fn, a specification attached with #[verifier::external_fn_specification] or assume_specification, and code marked #[verifier::external]. Each is sometimes necessary, and each means that part of the result rests on your word. The guide says the --no-cheating flag “confines them to explicitly trusted code”.
The same caution applies to flags that skip checks. The guide says: “Verification results should only be trusted when flags like these are not included in the invocation of Verus.” It names --verify-function and --no-verify. Step 7 uses --no-verify once, to build a program for the tests, and never to decide whether something is verified.
Step 7: Plant bugs and see who catches them
How do you know whether your specification is strong enough, and whether the proof adds anything to your tests? Break the code in small realistic ways and see which checks notice. This is called mutation testing, and it works on specifications too: a bug that survives is either a hole in the tests or a hole in the contract.
7.1 The test program
Create bs_full.rs. It holds the same binary search as s12_bsearch.rs inside verus!, followed by ordinary Rust test code outside the macro. Verus compiles that code and does not verify it, so it can call the verified function like any other Rust function:
// bs_full.rs
use vstd::prelude::*;
verus! {
spec fn sorted(s: Seq<u64>) -> bool {
forall|i: int, j: int| 0 <= i < j < s.len() ==> s[i] <= s[j]
}
fn binary_search(v: &Vec<u64>, target: u64) -> (r: Option<usize>)
requires
sorted(v@),
ensures
match r {
Some(i) => i < v.len() && v[i as int] == target,
None => forall|i: int| 0 <= i < v.len() ==> v[i] != target,
},
{
let mut lo: usize = 0;
let mut hi: usize = v.len();
while lo < hi
invariant
lo <= hi <= v.len(),
sorted(v@),
forall|i: int| 0 <= i < lo ==> v[i] < target,
forall|i: int| hi <= i < v.len() ==> v[i] > target,
decreases hi - lo,
{
let mid = lo + (hi - lo) / 2;
if v[mid] == target {
return Some(mid);
} else if v[mid] < target {
lo = mid + 1;
} else {
hi = mid;
}
}
None
}
} // verus!
// Plain Rust below: Verus treats everything outside verus! as external code.
use std::env;
fn valid(v: &Vec<u64>, t: u64) -> bool {
match binary_search(v, t) {
Some(i) => i < v.len() && v[i] == t,
None => !v.contains(&t),
}
}
fn examples() -> Result<(), String> {
let cases: Vec<(Vec<u64>, u64)> = vec![
(vec![1, 3, 5, 7, 9], 7),
(vec![1, 3, 5, 7, 9], 4),
(vec![], 3),
(vec![2, 4, 6, 8], 8),
(vec![2, 4, 6, 8], 10),
(vec![5], 5),
];
for (v, t) in cases {
if !valid(&v, t) {
return Err(format!("wrong answer for {:?} target {}", v, t));
}
}
Ok(())
}
fn fill(cur: &mut Vec<u64>, len: usize, min: u64, top: u64, count: &mut u64) -> Result<(), String> {
if cur.len() == len {
for t in 0..=top + 1 {
*count += 1;
if !valid(cur, t) {
return Err(format!("wrong answer for {:?} target {}", cur, t));
}
}
return Ok(());
}
for x in min..=top {
cur.push(x);
let r = fill(cur, len, x, top, count);
cur.pop();
r?;
}
Ok(())
}
fn exhaustive() -> Result<(), String> {
let mut count = 0u64;
for len in 0..=7 {
fill(&mut Vec::new(), len, 0, 6, &mut count)?;
}
println!("checked {} (array, target) pairs", count);
Ok(())
}
fn main() {
let mode = env::args().nth(1).unwrap_or_default();
let r = match mode.as_str() {
"examples" => examples(),
"exhaustive" => exhaustive(),
_ => Err("usage: bs <examples|exhaustive>".to_string()),
};
match r {
Ok(()) => println!("PASS {}", mode),
Err(m) => {
println!("FAIL {}: {}", mode, m);
std::process::exit(1);
}
}
}
The function valid checks an answer against the same contract, using plain code. There are two test modes:
examplesis the suite a careful developer might write in five minutes: six hand-picked cases, including an empty vector, a one-element vector and targets above and between the elements.exhaustivetries every sorted vector of up to seven numbers drawn from 0 to 6, with every target from 0 to 7. That is 27,456 cases, and it prints the count when it passes.
7.2 The mutation script
The script below makes nine copies of bs_full.rs, each with one planted bug, plus an unchanged copy as a control, and a second version of every copy that carries the weak contract. It asks four judges about them:
- the five-minute example tests;
- the exhaustive small-scope test;
- Verus with the full contract from Step 5;
- Verus with a weak contract that says only “if the answer is
Some(i)theniis a valid position, and if it isNone, nothing”.
The tests run in a separate executable. The script builds it with verus --no-verify --compile, and gives each test run ten seconds before it records a hang. Set the VERUS environment variable to the full path of verus.exe if it is not on your PATH.
# mutants.py
"""Plant one-line bugs in bs_full.rs and ask four judges: examples, exhaustive tests, Verus (full spec), Verus (weak spec)."""
import os, subprocess, sys
VERUS = os.environ.get("VERUS", "verus")
HONEST = open("bs_full.rs", encoding="utf-8", newline="").read().replace("\r\n", "\n")
FULL_POST = """ match r {
Some(i) => i < v.len() && v[i as int] == target,
None => forall|i: int| 0 <= i < v.len() ==> v[i] != target,
},"""
WEAK_POST = """ match r {
Some(i) => i < v.len(),
None => true,
},"""
MUTANTS = [
("M1", "lo moves to mid, not mid + 1", "lo = mid + 1;", "lo = mid;"),
("M2", "hi moves to mid - 1", "hi = mid;", "hi = mid - 1;"),
("M3", "loop runs while lo <= hi", "while lo < hi\n", "while lo <= hi\n"),
("M4", "comparison reversed", "} else if v[mid] < target {", "} else if v[mid] > target {"),
("M5", "miss returns Some(lo)", " None\n}\n\n} // verus!", " Some(lo)\n}\n\n} // verus!"),
("M6", "search starts at index 1", "let mut lo: usize = 0;", "let mut lo: usize = 1;"),
("M7", "one-element shortcut", " while lo < hi\n", " if v.len() == 1 {\n return Some(0);\n }\n while lo < hi\n"),
("M8", "midpoint (lo + hi) / 2", "let mid = lo + (hi - lo) / 2;", "let mid = (lo + hi) / 2;"),
("M9", "a found key returns None", "return Some(mid);", "return None;"),
]
def sh(args, timeout=60):
try:
p = subprocess.run(args, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout)
return p.returncode, (p.stdout + p.stderr).replace("\r\n", "\n")
except subprocess.TimeoutExpired:
return None, "TIMEOUT"
def verus_verdict(path):
rc, out = sh([VERUS, "--crate-type=lib", path])
if rc == 0:
return "verified"
errs = [l[len("error: "):] for l in out.splitlines() if l.startswith("error: ") and "aborting" not in l]
return errs[0] if errs else "error (no message)"
def run_tests(exe, mode):
rc, out = sh([exe, mode], timeout=10)
if rc is None:
return "HANG (10 s timeout)"
if rc == 0:
return "pass"
if "FAIL" in out:
return "FAIL"
if "panicked" in out:
return "PANIC"
return f"exit {rc}"
def make(tag, old, new, weak=False):
src = HONEST
if weak:
assert src.count(FULL_POST) == 1
src = src.replace(FULL_POST, WEAK_POST)
if old is not None:
assert src.count(old) == 1, (tag, old, src.count(old))
src = src.replace(old, new)
path = f"mut/{tag}{'_weak' if weak else ''}.rs"
open(path, "w", encoding="utf-8", newline="\n").write(src)
return path
SHORT = {
"decreases not satisfied at end of loop": "decreases",
"invariant not satisfied at end of loop body": "invariant (end of body)",
"invariant not satisfied before loop": "invariant (entry)",
"postcondition not satisfied": "postcondition",
"possible arithmetic underflow/overflow": "overflow",
}
def short(verdict):
return "verified" if verdict == "verified" else "REJECT " + SHORT.get(verdict, verdict)
os.makedirs("mut", exist_ok=True)
os.makedirs("out", exist_ok=True)
lines = [f"{'id':3} {'examples':9} {'exhaustive':10} {'verus, full spec':32} {'verus, weak spec':32} planted bug"]
print(lines[0], flush=True)
for tag, desc, old, new in [("H0", "honest code", None, None)] + MUTANTS:
full = make(tag, old, new)
weak = make(tag, old, new, weak=True)
exe = os.path.abspath(f"mut/{tag}.exe")
sh([VERUS, "--no-verify", "--compile", "--crate-type=bin", full, "-o", exe])
ex, exh = run_tests(exe, "examples"), run_tests(exe, "exhaustive")
ex = "HANG" if ex.startswith("HANG") else ex
exh = "HANG" if exh.startswith("HANG") else exh
lines.append(f"{tag:3} {ex:9} {exh:10} {short(verus_verdict(full)):32} {short(verus_verdict(weak)):32} {desc}")
print(lines[-1], flush=True)
with open("out/matrix.txt", "w", encoding="utf-8", newline="\n") as f:
f.write("\n".join(lines) + "\n")
7.3 Run it and read the table
python mutants.py
It took 53 seconds on the lab machine, most of it waiting out the three runs that never finish, each of which costs the ten-second limit:
id examples exhaustive verus, full spec verus, weak spec planted bug
H0 pass pass verified verified honest code
M1 HANG HANG REJECT decreases REJECT decreases lo moves to mid, not mid + 1
M2 FAIL PANIC REJECT invariant (end of body) REJECT invariant (end of body) hi moves to mid - 1
M3 HANG PANIC REJECT decreases REJECT decreases loop runs while lo <= hi
M4 FAIL FAIL REJECT invariant (end of body) REJECT invariant (end of body) comparison reversed
M5 FAIL FAIL REJECT postcondition REJECT postcondition miss returns Some(lo)
M6 FAIL FAIL REJECT invariant (entry) REJECT invariant (entry) search starts at index 1
M7 pass FAIL REJECT postcondition verified one-element shortcut
M8 pass pass REJECT overflow REJECT overflow midpoint (lo + hi) / 2
M9 FAIL FAIL REJECT postcondition verified a found key returns None
In the test columns, FAIL means a wrong answer, PANIC means the program crashed, and HANG means the ten-second limit was hit, which a test run without a timeout would never finish. In the Verus columns, REJECT names the kind of message Verus gave. The tally:
| Judge | Planted bugs caught | Missed |
|---|---|---|
| Five-minute example tests | 7 of 9 | M7, M8 |
| Exhaustive small-scope test | 8 of 9 | M8 |
| Verus, full contract | 9 of 9 | none |
| Verus, weak contract | 7 of 9 | M7, M9 |
Read the rows one lesson at a time.
- M1 and M3 loop forever or crash. M1 hangs under both test suites. M3 hangs under the examples and, under the exhaustive test, crashes with an index out of bounds on the empty vector. Verus rejects both with
decreasesmessages under either contract, because termination does not depend on what the function promises. - M7, the one-element shortcut, slips past the five-minute tests. It returns
Some(0)for any one-element vector, and the examples happen to include[5]with target 5. The exhaustive test finds the answerSome(0)for the vector[0]with target 1. A small-scope test is the best friend of a bug hunt. - M8, the midpoint, slips past both test suites. No test here builds a vector big enough for the sum to overflow, which is the point of Step 5.3. Verus rejects it with
overflow, under either contract. - M7 and M9 pass the weak contract. M9 returns
Noneeven when it finds the key, which is the guide’s own example of a weak specification, and the weak contract allows it. The full contract rejects M9 withpostcondition, because it saysNonemeans no element equals the target.
Treat the table as a demonstration, not a statistic. It is one function and nine bugs that I chose, and a different example suite would score differently. What it shows is how the judges differ. Tests find most bugs quickly and cheaply, and an exhaustive small-scope test finds nearly all of them. Only the proof covers vectors of every size, and only a strong contract makes the proof worth having.
Step 8: Make the check part of your build
Verus’s exit code is the whole interface for a build script. It exits with 0 when everything verified and with 1 when anything failed. In PowerShell, $LASTEXITCODE holds the code of the last program:
verus --crate-type=lib --no-cheating s12_bsearch.rs
"exit code: $LASTEXITCODE"
verification results:: 2 verified, 0 errors
exit code: 0
On s18_assume.rs the same two lines print the --no-cheating message from Step 6.3 and then exit code: 1. In a CI job, fail the build on a nonzero exit code, keep --no-cheating on, and never add --no-verify or --verify-function to the command that decides the verdict. Pin the Verus version and the Rust toolchain in your build (the Version and Toolchain lines of verus --version show both), so that a new weekly release does not change your results without notice.
Reading Verus’s messages: a cheat sheet
These are the eight messages from this tutorial, with what each one means and what to try first.
| Message | What it means | What to try first |
|---|---|---|
postcondition not satisfied |
Some path through the body can end with a promise broken. | Read which clause is underlined. After a loop, check that the invariant keeps what the clause needs. |
precondition not satisfied |
A call may pass arguments that break the callee’s requires. |
Add the condition to the caller’s requires, or branch before the call. |
possible arithmetic underflow/overflow |
Machine-integer arithmetic could leave the type’s range for some allowed input. | Add a requires, or rewrite the expression so no large intermediate value appears, as in lo + (hi - lo) / 2. |
invariant not satisfied before loop |
The invariant is false when the loop starts. | Check the starting values against each invariant line. |
invariant not satisfied at end of loop body |
One pass through the body can break the invariant. | Include the last pass: after the final update, does it still hold? |
decreases not satisfied at end of loop |
The measure after a pass may not be smaller than before. | Check that every branch moves the counters toward the end, as lo = mid + 1 does. |
loop must have a `decreases` clause |
The loop has no termination measure. | Add decreases with a number that shrinks. |
`assume`/`admit` not allowed with `--no-cheating` |
The file contains an unproved assumption. | Prove the fact, or move it into code you have marked as trusted. |
Step 9: Run everything once
This script runs all the steps in order and prints the exit code and the first line of Verus’s answer for each. Create run_all.py:
# run_all.py
import os, subprocess, sys, time
VERUS = os.environ.get("VERUS", "verus")
STEPS = [
("s01_max.rs", []), ("s02_max_bug.rs", []), ("s03_add_bad.rs", []), ("s04_add_requires.rs", []),
("s05_add_caller_bad.rs", []), ("s06_mid_bad.rs", []), ("s07_mid_good.rs", []),
("s08_max_of.rs", []), ("s09_max_of_no_invariant.rs", []), ("s10_max_of_bad_invariant.rs", []),
("s11_max_of_no_decreases.rs", []), ("s12_bsearch.rs", []), ("s13_bsearch_mid.rs", []),
("s14_pair_weak.rs", []), ("s15_pair_strong.rs", []), ("s16_vacuous.rs", []),
("s17_vacuous_smoke.rs", []), ("s18_assume.rs", []), ("s18_assume.rs", ["--no-cheating"]),
]
os.makedirs("out", exist_ok=True)
for name, extra in STEPS:
p = subprocess.run([VERUS, "--crate-type=lib", name] + extra, capture_output=True, text=True,
encoding="utf-8", errors="replace")
text = (p.stdout + p.stderr).replace("\r\n", "\n")
stem = name[:-3] + ("_nocheat" if extra else "")
with open(f"out/{stem}.txt", "w", encoding="utf-8", newline="\n") as f:
f.write(text)
print(f"{stem:32} exit {p.returncode} {text.splitlines()[0] if text.strip() else ''}")
python run_all.py
s01_max exit 0 verification results:: 1 verified, 0 errors
s02_max_bug exit 1 verification results:: 0 verified, 1 errors
s03_add_bad exit 1 verification results:: 0 verified, 1 errors
s04_add_requires exit 0 verification results:: 2 verified, 0 errors
s05_add_caller_bad exit 1 verification results:: 1 verified, 1 errors
s06_mid_bad exit 1 verification results:: 0 verified, 1 errors
s07_mid_good exit 0 verification results:: 1 verified, 0 errors
s08_max_of exit 0 verification results:: 2 verified, 0 errors
s09_max_of_no_invariant exit 1 verification results:: 1 verified, 1 errors
s10_max_of_bad_invariant exit 1 verification results:: 0 verified, 2 errors
s11_max_of_no_decreases exit 1 error: loop must have a `decreases` clause
s12_bsearch exit 0 verification results:: 2 verified, 0 errors
s13_bsearch_mid exit 1 verification results:: 1 verified, 1 errors
s14_pair_weak exit 0 verification results:: 1 verified, 0 errors
s15_pair_strong exit 0 verification results:: 1 verified, 0 errors
s16_vacuous exit 0 verification results:: 1 verified, 0 errors
s17_vacuous_smoke exit 1 verification results:: 1 verified, 1 errors
s18_assume exit 0 verification results:: 1 verified, 0 errors
s18_assume_nocheat exit 1 error: `assume`/`admit` not allowed with `--no-cheating`
Nine files exit with 0 and ten runs exit with 1, and the exit codes tell the story of the tutorial: the working proofs are s01, s04, s07, s08, s12, s14, s15, s16 and s18, and every other run is a failure you caused on purpose. Three of the zeros are the cases of Step 6 that deserve suspicion: s14 (a promise anything satisfies), s16 (an impossible precondition) and s18 (an assume). A green run is where the thinking starts, not where it ends.
If your outputs match the blocks above, and python mutants.py prints the same table, you have reproduced the whole tutorial.
Where to go next
- Read the guide chapters this tutorial skipped. The Verus guide covers proof functions, recursion, quantifiers and the “triggers” that decide whether the solver notices a fact, structs and enums, and how to find out why a proof is slow. Its chapter on loops and invariants goes further than Step 4. If you only want to try things first, the guide says you can “run Verus through the Verus playground in your browser”.
- Prove a sort. Try specifying a function that sorts a vector. The obvious first contract, “the result is sorted”, has the same hole as the pair in Step 6: a function that returns an empty vector satisfies it. The strong version has to say the result has the same elements as the input, which needs multisets from
vstd. - Verify code that an assistant wrote. The guide has a chapter on using language models to write Verus proofs. Its advice includes “Use a cheat checker to catch invalid proof shortcuts”, and its sample prompt says “Do NOT use
assume(...)oradmit(...).” Step 6 shows why that matters:assume(false)turns any claim green. Our PDD Kit audit shows how a plausible contract can still verify a login that fails every time. - Compare with another kind of proof. Our post on Microsoft’s SymCrypt proofs covers machine-checked proofs for Rust implementations of SHA-3 and ML-KEM, and our Signal proofs post shows what a Lean proof does and does not cover.
What to remember
- A test checks the inputs you chose. A Verus proof checks every input the contract allows, for code inside
verus!only. requiresis the caller’s duty andensuresis the function’s promise. Verus checks the body against the promise and every call against the duty.- Machine arithmetic must be proved not to overflow. In a contract,
+is exact mathematics; in a body, it is the real operation. - A loop needs an invariant that keeps what you need afterwards, and a
decreasesmeasure that shrinks. The loop forgets everything else about the variables it changes. lo + (hi - lo) / 2is the safe midpoint, and Verus will ask for it.- A green result is only as strong as the contract. Ask what a lazy implementation could return, call every function once with the arguments a real caller would pass, and run with
--no-cheating. - Plant bugs. A proof, a contract and a test suite are each checked best by the others.
Sources and further reading
- Verus project, source repository, release 0.2026.11.02.8bf68ee and its install notes.
- Verus project, Verus Tutorial and Reference: the overview, the chapters on integer arithmetic, loops and invariants, the binary search example, and the cheat checker.
- Verus project, the
vstdspecification ofVec, source of the comment aboutusizebounds. - Rust project, the
Vecdocumentation, on capacity limits and zero-sized types. - Joshua Bloch, a post on the binary search and mergesort midpoint bug, Google Research blog (June 2006).
- Z3, the SMT solver that Verus uses by default.
- More from this site: property-based testing in Rust with proptest, Microsoft’s PDD Kit and a login that answers every attempt with a 500, Microsoft’s SymCrypt proofs, and DeepMind’s Signal proofs.








No Comment! Be the first one.