Skip to main content

verif_arithmetic/
prove.rs

1//! The proofs, discharged by exhaustive enumeration.
2//!
3//! There is no solver here. Each obligation walks **every** input in its domain
4//! and answers [`Verdict::Valid`] only if the property held for all of them, or
5//! [`Verdict::Counterexample`] with the first witness that falsified it. That is
6//! a complete decision procedure for the domain it is given: no size wall, no
7//! `Unknown` because an arena filled, no reliance on a search heuristic.
8//!
9//! It is deliberately *not* symbolic. Enumeration cannot reach a 32-bit
10//! two-variable domain, and it does not pretend to: a domain larger than
11//! [`ENUM_BUDGET`] returns [`Verdict::Unknown`], the same honest refusal the
12//! parent crate's `smt` engine gives at its own wall. The obligations here are
13//! therefore stated at widths the enumeration can *finish*, and the parent's
14//! symbolic engine proves the same statements at the wider ones.
15//!
16//! # The obligations and the runtime primitives sit at different widths
17//!
18//! The runtime operations ([`crate::checked_add`], [`crate::safe_add`], …) are
19//! `u32`-typed, and these obligations are stated at 8 or 16 bits because that is
20//! the largest domain enumeration can exhaust. That gap is deliberate and is not
21//! hidden: an obligation at 8 bits *cannot* call a `u32` primitive and observe an
22//! 8-bit overflow through it, because `u32` addition of two 8-bit values never
23//! overflows. So the obligations model the arithmetic rather than calling it, and
24//! a separate test (`runtime_ops_match_their_proved_statements`) ties each
25//! primitive to the property at the `u32` boundary points where the property is
26//! observable. A regression in a primitive has to survive that test as well as
27//! the verdicts, which is the point of stating it.
28//!
29//! # Why this is a proof and not a test
30//!
31//! A test that samples inputs shows the property holds for the inputs it tried.
32//! An enumeration that visits every input of the domain and stops only when the
33//! domain is exhausted shows it holds for *all* of them — for a domain small
34//! enough to exhaust, that is a proof by cases with no gaps. The distinction is
35//! the domain, not the technique, which is why the budget is explicit and the
36//! answer at the budget is `Unknown` rather than `Valid`.
37
38/// The largest number of cases one obligation will enumerate.
39///
40/// `2^32` is the point past which the method stops being usable in a test suite,
41/// and the figure is measured rather than guessed: such a walk costs about 2.6 s
42/// in the optimised test profile and about 21 s unoptimised, which is why
43/// `[profile.test]` sets `opt-level = 2` (with the debug assertions left on). A
44/// domain above the budget is not attempted; the verdict is [`Verdict::Unknown`].
45///
46/// The budget is a *count of cases*, so it does not bound the wall-clock cost on
47/// its own — an obligation that does more work per case, or one built without
48/// optimisation, is slower for the same count. `ENUM_BUDGET` is the count; the
49/// profile is what keeps the count affordable.
50pub const ENUM_BUDGET: u64 = 1 << 32;
51
52/// The outcome of an obligation.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum Verdict {
55    /// The property held for every input in the domain. A complete proof.
56    Valid,
57    /// The property failed, with a concrete input that falsifies it.
58    Counterexample(Witness),
59    /// The domain exceeds [`ENUM_BUDGET`], or the statement was not one this
60    /// method can decide. We refuse to guess.
61    Unknown,
62}
63
64impl Verdict {
65    /// True only when the property was *proved*. `Unknown` is not a proof.
66    pub const fn is_proved(&self) -> bool {
67        matches!(self, Verdict::Valid)
68    }
69
70    /// True when the query reached a definite answer.
71    pub const fn is_decided(&self) -> bool {
72        !matches!(self, Verdict::Unknown)
73    }
74}
75
76/// A falsifying input. `len` is how many of `a`/`b` the obligation ranged over.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub struct Witness {
79    /// The first input variable.
80    pub a: u64,
81    /// The second input variable, when the obligation has two.
82    pub b: u64,
83    /// How many variables the witness names (1 or 2).
84    pub len: u8,
85}
86
87impl Witness {
88    fn one(a: u64) -> Self {
89        Witness { a, b: 0, len: 1 }
90    }
91    fn two(a: u64, b: u64) -> Self {
92        Witness { a, b, len: 2 }
93    }
94}
95
96// ---------------------------------------------------------------------------
97// The enumeration primitives
98// ---------------------------------------------------------------------------
99
100/// Walk every pair of `w`-bit values, when `2^(2w)` fits the budget. This is the
101/// general entry point for the two-variable obligations at a caller-chosen
102/// width.
103///
104/// `w == 0` is refused rather than enumerated: a zero-bit integer is not a word
105/// width, and `1u64 << 0` is `1`, so the loop below would visit the fabricated
106/// point `(0, 0)` and answer `Valid` for a proposition about a type that does not
107/// exist. `Unknown` is the honest answer for a domain that is not a domain.
108fn forall_pair(w: u8, p: impl Fn(u64, u64) -> bool) -> Verdict {
109    if w == 0 || w > 16 {
110        return Verdict::Unknown;
111    }
112    let domain = 1u64 << w;
113    if domain.checked_mul(domain).is_none_or(|c| c > ENUM_BUDGET) {
114        return Verdict::Unknown;
115    }
116    let mut a = 0u64;
117    while a < domain {
118        let mut b = 0u64;
119        while b < domain {
120            if !p(a, b) {
121                return Verdict::Counterexample(Witness::two(a, b));
122            }
123            b += 1;
124        }
125        a += 1;
126    }
127    Verdict::Valid
128}
129
130/// Walk every pair of `w`-bit values *that satisfy a bound precondition*: the
131/// rectangle `[0, bound] x [0, bound]`, when that fits the budget.
132///
133/// This exists because the guarded form of an obligation — quantify over the
134/// whole `2^(2w)` domain and write `!pre || goal` — makes the points outside the
135/// rectangle trivially true, so visiting them is pure cost. At width 16 with
136/// `bound = 2^14 - 1` that is 4 294 967 296 iterations to check 268 435 456
137/// points, and it was the single slowest thing in the test gate.
138///
139/// Skipping them is sound only if the rectangle is *exactly* the set where `pre`
140/// holds. That is not self-evident, so it is not assumed: the obligation keeps
141/// its `!pre ||` guard (the statement is unchanged), and
142/// [`restricted_domain_matches`] checks that the two predicates select the same
143/// points, over the whole domain, before the shortcut is used.
144fn forall_pair_bounded(w: u8, bound: u64, p: impl Fn(u64, u64) -> bool) -> Verdict {
145    if w == 0 || w > 16 {
146        return Verdict::Unknown;
147    }
148    // A bound at or past the domain would silently enumerate the whole thing, or
149    // worse, claim to restrict a domain it does not. Refuse instead.
150    if bound >= (1u64 << w) {
151        return Verdict::Unknown;
152    }
153    let side = bound + 1;
154    if side.checked_mul(side).is_none_or(|c| c > ENUM_BUDGET) {
155        return Verdict::Unknown;
156    }
157    let mut a = 0u64;
158    while a <= bound {
159        let mut b = 0u64;
160        while b <= bound {
161            if !p(a, b) {
162                return Verdict::Counterexample(Witness::two(a, b));
163            }
164            b += 1;
165        }
166        a += 1;
167    }
168    Verdict::Valid
169}
170
171/// Walk every `w`-bit value. Returns [`Verdict::Unknown`] past `2^ENUM_BUDGET`.
172///
173/// `w == 0` is refused for the same reason as in [`forall_pair`]: the fabricated
174/// point `0` is not an element of a zero-bit domain.
175fn forall_one(w: u8, p: impl Fn(u64) -> bool) -> Verdict {
176    if w == 0 || w > 32 {
177        return Verdict::Unknown;
178    }
179    let domain = 1u64 << w;
180    if domain > ENUM_BUDGET {
181        return Verdict::Unknown;
182    }
183    let mut x = 0u64;
184    while x < domain {
185        if !p(x) {
186            return Verdict::Counterexample(Witness::one(x));
187        }
188        x += 1;
189    }
190    Verdict::Valid
191}
192
193/// Check that the rectangle `forall_pair_bounded` walks is *exactly* the set the
194/// precondition selects, so the restricted enumeration is the same question and
195/// not a smaller one.
196///
197/// This compares the two **domains** and never runs a goal, which is the whole
198/// point. The first version of this check got it wrong in a way worth recording:
199/// it ran both walks on one goal and compared their verdicts, but a walk stops at
200/// its *first* counterexample and two different rectangles can share one. At width
201/// 8, bounds 200 and 199 both fail first at `(1, 198)`, so the verdicts matched and
202/// the check passed — while the 199 rectangle silently omitted every pair
203/// containing 200 that the precondition admits. Coverage is a property of the
204/// domains, so it has to be checked on the domains.
205///
206/// The check is **exact, not sampled**, and that is possible because the
207/// precondition is a square: `pre` holds at `(a, b)` iff `a <= pre_bound` *and*
208/// `b <= pre_bound`, and the walk visits `(a, b)` iff `a <= rect_bound` *and*
209/// `b <= rect_bound`. Two such sets are equal exactly when the bounds are equal —
210/// neither can be a proper subset of the other while both are squares of that
211/// shape — so comparing the bounds decides the question completely. A brute-force
212/// sweep of the domain would reach the same verdict for every input, at `2^32`
213/// cost; it was tried, it agreed, and it made the gate slower for no more evidence.
214///
215/// If the precondition ever stops being a square, this function stops being exact
216/// and must be replaced — that is the assumption to re-check, not the bounds.
217///
218/// Returns [`Verdict::Counterexample`] naming a pair in exactly one of the sets,
219/// or [`Verdict::Unknown`] if the width or a bound makes the question ill-formed.
220pub fn restricted_domain_matches(w: u8, pre_bound: u64, rect_bound: u64) -> Verdict {
221    if w == 0 || w > 16 {
222        return Verdict::Unknown;
223    }
224    let domain = 1u64 << w;
225    // A bound at or past the domain is not a restriction of it, and the walk
226    // refuses such a bound, so the question is ill-formed rather than answered.
227    if pre_bound >= domain || rect_bound >= domain {
228        return Verdict::Unknown;
229    }
230    if pre_bound == rect_bound {
231        return Verdict::Valid;
232    }
233    // Name a point in exactly one of the sets: the first value of `b` above the
234    // smaller bound is admitted by the larger one and not the smaller one. Both
235    // bounds are below the domain here, so the point is a real input.
236    let witness = if pre_bound > rect_bound {
237        (0, rect_bound + 1)
238    } else {
239        (0, pre_bound + 1)
240    };
241    Verdict::Counterexample(Witness::two(witness.0, witness.1))
242}
243
244/// Check that `forall_pair_bounded` visits *exactly* its rectangle, edges
245/// included — the implementation half of the soundness argument, which
246/// [`restricted_domain_matches`] does not cover (that one is about the bounds, this
247/// one is about the walk).
248///
249/// Two tripwires, both independent of any real obligation:
250///
251/// * a goal false at one chosen point must produce *that* witness, for every corner
252///   and edge midpoint, so an off-by-one on any side is caught;
253/// * a goal false everywhere *outside* the rectangle must come back `Valid`, since
254///   a walk that strayed outside would find a counterexample there.
255pub fn bounded_walk_covers_its_rectangle(w: u8, bound: u64) -> Verdict {
256    if w == 0 || w > 16 {
257        return Verdict::Unknown;
258    }
259    if bound >= (1u64 << w) {
260        return Verdict::Unknown;
261    }
262    let mid = bound / 2;
263    let must_visit = [
264        (0, 0),
265        (bound, 0),
266        (0, bound),
267        (bound, bound),
268        (mid, 0),
269        (mid, bound),
270        (0, mid),
271        (bound, mid),
272    ];
273    // Each tripwire re-walks the rectangle, so this check costs a constant factor
274    // more than the walk it inspects; the budget applies to the total, and the
275    // factor is read off `must_visit` so it cannot drift from the loop below.
276    let side = bound + 1;
277    let walks = must_visit.len() as u64 + 1;
278    if side
279        .checked_mul(side)
280        .and_then(|c| c.checked_mul(walks))
281        .is_none_or(|c| c > ENUM_BUDGET)
282    {
283        return Verdict::Unknown;
284    }
285    for (pa, pb) in must_visit {
286        // False only at `(pa, pb)`, so the walk must return exactly that witness.
287        let tripwire = forall_pair_bounded(w, bound, |a, b| !(a == pa && b == pb));
288        match tripwire {
289            Verdict::Counterexample(wi) if wi.a == pa && wi.b == pb => {}
290            _ => return Verdict::Counterexample(Witness::two(pa, pb)),
291        }
292    }
293    // True exactly on the rectangle, so `Valid` means the walk never left it.
294    let inside = |a: u64, b: u64| a <= bound && b <= bound;
295    match forall_pair_bounded(w, bound, inside) {
296        Verdict::Valid => Verdict::Valid,
297        _ => Verdict::Counterexample(Witness::two(bound, bound)),
298    }
299}
300
301// ---------------------------------------------------------------------------
302// The obligations
303// ---------------------------------------------------------------------------
304
305/// The overflow test is sound: for a wrapping 8-bit sum, "the result is below
306/// `a`" and "the result is below `b`" are *the same event*. That is exactly why
307/// `checked_add` can test either one, and why the wrapped result is a reliable
308/// overflow flag even when the true sum is lost.
309///
310/// Enumerated over all `2^16` pairs of `u8`.
311pub fn checked_add_is_total() -> Verdict {
312    forall_pair(8, |a, b| {
313        let sum = a.wrapping_add(b) & 0xFF;
314        (sum < a) == (sum < b)
315    })
316}
317
318/// The saturating sum never falls below an operand: `sat(a,b) >= a` and
319/// `>= b`, unconditionally, including on overflow.
320///
321/// The property is stated about the *saturating* value, not the wrapping one.
322/// The wrapping sum does not satisfy it, so the `min` is load-bearing; see
323/// `saturation_is_load_bearing` in the tests.
324pub fn saturating_add_bounds() -> Verdict {
325    forall_pair(8, |a, b| {
326        let sum = a.wrapping_add(b) & 0xFF;
327        let overflowed = sum < a;
328        let sat = if overflowed { 0xFF } else { sum };
329        sat >= a && sat >= b
330    })
331}
332
333/// `x - x == 0` at width `w`, the cancellation law for subtraction.
334pub fn sub_self_is_zero(w: u8) -> Verdict {
335    forall_one(w, |x| {
336        let mask = if w == 64 { u64::MAX } else { (1u64 << w) - 1 };
337        let x = x & mask;
338        x.wrapping_sub(x) & mask == 0
339    })
340}
341
342/// The algebraic laws an optimiser, a static analyser or a hand proof relies on.
343/// Returns how many of the `laws x widths` were proved.
344///
345/// Each law is a separate obligation, and the count is returned rather than a
346/// single verdict so a test can assert the exact number.
347///
348/// Two of the laws are identity operations -- `x | 0 == x` and `x ^ x == 0` --
349/// which is the point: they are the trivial identities a peephole optimiser
350/// actually folds, and enumerating them is how this module proves the fold is
351/// sound. `clippy` flags them as such, correctly, so the lint is allowed here
352/// with that reason rather than the laws being written to dodge it.
353#[allow(clippy::identity_op, clippy::eq_op)]
354pub fn algebraic_identities() -> usize {
355    let mut proved = 0;
356    for w in [8u8, 16] {
357        let mask = (1u64 << w) - 1;
358        let laws: [&dyn Fn(u64) -> bool; 10] = [
359            &|x| x.wrapping_add(0) & mask == x,
360            &|x| x.wrapping_mul(1) & mask == x,
361            &|x| x.wrapping_mul(0) & mask == 0,
362            &|x| (x | 0) & mask == x,
363            &|x| (x & mask) & mask == x,
364            &|x| (x ^ x) & mask == 0,
365            &|x| x.wrapping_sub(x) & mask == 0,
366            &|x| (x >> w) & mask == 0,
367            // `x | all_ones == all_ones`. This slot previously held `0 <= x`, which for
368            // an unsigned value is a tautology of the *type*, not a fact about the input
369            // -- it is unchanged by substituting any term for `x`, so it added no
370            // coverage while the comment claimed a law. Or-ing with the mask is a real
371            // identity an optimiser folds, and it is falsifiable: `(x | 0) == mask` is
372            // refuted at every `x < mask`.
373            &|x| (x | mask) & mask == mask,
374            &|x| x <= mask, // x <= 2^w - 1, the range law
375        ];
376        for law in laws {
377            if forall_one(w, |x| law(x & mask)).is_proved() {
378                proved += 1;
379            }
380        }
381    }
382    proved
383}
384
385/// `mul_div` widens to 64 bits precisely because a product of two `w`-bit
386/// values needs `2w` bits. This proves the *shape* of that argument at a width
387/// enumeration reaches: if each factor is below `2^(w/2)`, the product fits.
388///
389/// Enumerated over all `2^8` pairs of 4-bit values.
390pub fn product_of_bounded_fits() -> Verdict {
391    forall_pair(4, |a, b| {
392        let pre = a < 4 && b < 4;
393        let prod = a.wrapping_mul(b) & 0xF;
394        !pre || prod <= 9
395    })
396}
397
398/// The bound [`fixed_add_no_overflow`]'s precondition and rectangle both use.
399///
400/// `pub` so the test that checks the rectangle *is* the precondition's set can
401/// check this value rather than a copy of it that could drift.
402///
403/// It is `2^14 - 1`, not `2^14`: a signed 16-bit value tops out at `2^15 - 1`, and
404/// at the inclusive bound `2^14` the sum `2^14 + 2^14` is exactly `2^15`, which
405/// sets the sign bit and reads as `-32768`.
406pub const FIXED_ADD_BOUND: u64 = (1u64 << 14) - 1;
407
408/// Adding two non-negative Q16.16 values cannot overflow a signed 16-bit sum
409/// when each is bounded by [`FIXED_ADD_BOUND`]. This is the guard a controller
410/// uses before summing terms.
411///
412/// Enumerated over the `2^28` pairs that satisfy the precondition, not the
413/// `2^32` pairs of the whole 16-bit domain. The statement is unchanged — it still
414/// carries the `!pre ||` guard — but `forall_pair_bounded` visits only the
415/// points where the guard can matter. The shortcut is checked by
416/// [`restricted_domain_matches`] rather than trusted.
417pub fn fixed_add_no_overflow() -> Verdict {
418    let bound = FIXED_ADD_BOUND;
419    forall_pair_bounded(16, bound, |a, b| {
420        let pre = a <= bound && b <= bound;
421        let sum = (a + b) & 0xFFFF;
422        !pre || sum < (1u64 << 15)
423    })
424}
425
426/// `to_int(from_int(k)) == k`: the integer round-trip is lossless, for the `k`
427/// the Q16.16 range can hold.
428pub fn fixed_roundtrip() -> Verdict {
429    forall_one(8, |k| {
430        // from_int(k) = k << 16, to_int truncates back. At 8 bits we model the
431        // shift/truncate pair by proving (k << 4) >> 4 == k for k < 16.
432        let small = k < 16;
433        let shifted = (k << 4) & 0xFF;
434        let back = shifted >> 4;
435        !small || back == k
436    })
437}
438
439/// `k * SCALE / SCALE == k`, the fixed-point identity behind unit conversion.
440///
441/// Unlike [`fixed_roundtrip`], this performs a real multiply by the scale factor
442/// and *then* divides by shifting. That distinction is the whole content: the
443/// multiply is what makes the statement be about unit conversion rather than a
444/// renamed round-trip.
445pub fn scale_identity() -> Verdict {
446    forall_one(8, |k| {
447        let small = k < 16;
448        let scaled = (k * 16) & 0xFF;
449        let unscaled = scaled >> 4;
450        !small || unscaled == k
451    })
452}
453
454/// If every term of an accumulator is `<= max`, no intermediate sum wraps.
455///
456/// "No overflow" is exactly "the wrapped sum is not below an operand", which is
457/// width-independent and needs no side condition. The naive goal `sum <= 2*max`
458/// degenerates when `2*max` does not fit the width, and was vacuously proved for
459/// exactly the `max` values whose sums overflow.
460///
461/// Enumerated over `2^24` pairs of 12-bit values.
462pub fn accumulator_no_overflow(w: u8, max: u64) -> Verdict {
463    forall_pair(w, move |a, b| {
464        let pre = a <= max && b <= max;
465        let mask = if w == 64 { u64::MAX } else { (1u64 << w) - 1 };
466        let sum = a.wrapping_add(b) & mask;
467        !pre || sum >= a
468    })
469}
470
471/// The wrapped result is a sound and complete overflow flag: `sum < a` happens
472/// exactly when `sum < b`. So `safe_add` can test either operand, and neither
473/// test can miss an overflow or raise a false alarm.
474pub fn safe_add_is_exact(w: u8) -> Verdict {
475    forall_pair(w, |a, b| {
476        let mask = if w == 64 { u64::MAX } else { (1u64 << w) - 1 };
477        let sum = a.wrapping_add(b) & mask;
478        (sum < a) == (sum < b)
479    })
480}
481
482/// The refinement invariant of `Bounded::sub`: for in-range `a` and `b`, `sub`
483/// returns a value exactly when `b <= a` **and** `a - b >= min`.
484///
485/// All three halves matter. The lower bound is not decoration: at `min == 10`,
486/// `a == 11` and `b == 10` are in range and `a >= b`, yet the difference `1` is
487/// below `min`. The underflow gate is the other half: without it, a wrapping
488/// difference can land back in range and be accepted.
489///
490/// Enumerated over an 8-bit domain, which is the range the guard is stated for.
491pub fn bounded_sub_is_total(min: u64, max: u64) -> Verdict {
492    forall_pair(8, move |a, b| {
493        let in_range = |v: u64| v >= min && v <= max;
494        let pre = in_range(a) && in_range(b);
495        // What `checked_sub` would do, and what `sub` accepts.
496        let no_underflow = b <= a;
497        let diff = a.wrapping_sub(b);
498        let result_ok = no_underflow && in_range(diff);
499        let want = no_underflow && diff >= min;
500        !pre || result_ok == want
501    })
502}
503
504/// Saturating addition is monotone: `a <= b` implies `sat(a, k) <= sat(b, k)`
505/// for a fixed addend. Monotonicity is what lets a control loop reason about
506/// saturation without a case split.
507pub fn saturating_add_monotone(w: u8, k: u64) -> Verdict {
508    forall_pair(w, move |a, b| {
509        let mask = if w == 64 { u64::MAX } else { (1u64 << w) - 1 };
510        let max = mask;
511        let sat = |x: u64| {
512            let sum = x.wrapping_add(k) & mask;
513            if sum < x { max } else { sum }
514        };
515        let pre = a <= b;
516        !pre || sat(a) <= sat(b)
517    })
518}