What is Program Verification?
Program verification uses formal methods to prove that code satisfies specifications. Instead of testing with specific inputs, we prove correctness for all possible inputs (or find counterexamples). Key concepts:- Pre-conditions: What must be true before the program runs
- Post-conditions: What must be true after the program runs
- Invariants: Properties that remain true throughout execution
- Counterexample: An input that violates the specification
Example: Verifying Bubble Sort
Let’s verify that bubble sort correctly sorts arrays.1
Model the array
Use Z3’s Z3 arrays are functions from indices to values.
Array type to represent the array before and after sorting:2
Define the sorting property
What does it mean for an array to be sorted?
Select(arr, i) reads the value at index i.3
Model one bubble sort pass
One pass compares adjacent elements and swaps if needed:
Store(arr, idx, val) creates a new array with arr[idx] = val.4
Verify correctness
Try to find a counterexample where the algorithm fails:
Complete Verification Example
Here’s a complete example that verifies bubble sort:Z3 proves bubble sort is correct by showing no counterexample exists!
Finding Bugs: Broken Sort
Let’s intentionally introduce a bug and see Z3 find it:Verifying Mathematical Properties
You can verify mathematical properties hold:Loop Invariants
Verify loop invariants hold:Verification Best Practices
Start small
Start small
Verify simple properties first, then build up to complex invariants. Start with small bounds (e.g., arrays of size 3).
Use bounded model checking
Use bounded model checking
For loops, unroll a fixed number of iterations. This finds bugs in early iterations efficiently.
Clear specifications
Clear specifications
Write precise pre-conditions and post-conditions. Ambiguous specs lead to meaningless verification.
Expect counterexamples
Expect counterexamples
When Z3 finds
sat, examine the model carefully - it shows exactly how the property fails.Bounded Model Checking Pattern
A general pattern for verification:Limitations
For full verification of unbounded programs, you need inductive proofs and loop invariants.Next Steps
Basic Solving
Review fundamental constraint solving concepts
Optimization
Learn to find optimal solutions with Z3 Optimize
