From b31824b2cacdf30e4e577334ab9fb43756081304 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 13:50:54 -0700 Subject: [PATCH] test(core): K-U7 review: None-iff-overflow proof, covers that can fail, a sharper bridge - Kani net_pay_none_iff_a_prefix_overflows proves what the doc claimed: None exactly when some running difference leaves the i64 range, else the exact i128 result. It found that i64's Amount::checked_sub negates first, so a deduction of i64::MIN (no negation) is refused where the difference would fit (-1 - i64::MIN). Conservative, and Decimal's range is symmetric, so the engine is unaffected; the harness assumes it away and asserts the refusal at the fixed case; the kernel doc says so. - payroll_plan_balances: covers that the assumes did not already force (net of one unit, payables holding employer shares alone, federal or state posted); the harness doc says it rebuilds the plan on i64 rather than calling payroll_entry_plan, and what that does and does not prove. - Docs name the Lean theorems that carry any number of employees (payroll_run_net_eq, payroll_run_plan_balances) where they had claimed it. - Bridge: compare to_string as well as value (Decimal equality ignores scale); a strategy near Decimal::MAX/MIN where the reference also returns None, which required the reference to check every running difference as the kernel's fold does, not only the last. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/src/kernel/payroll.rs | 10 +- crates/ledger-core/src/proofs/payroll.rs | 96 +++++++++++++++++-- .../tests/kernel_bridge/payroll.rs | 64 ++++++++++++- docs/proofs/k-u7.md | 85 ++++++++++------ 4 files changed, 210 insertions(+), 45 deletions(-) diff --git a/crates/ledger-core/src/kernel/payroll.rs b/crates/ledger-core/src/kernel/payroll.rs index 2e52f6c9..82cc2116 100644 --- a/crates/ledger-core/src/kernel/payroll.rs +++ b/crates/ledger-core/src/kernel/payroll.rs @@ -36,9 +36,13 @@ use super::Amount; /// payroll line whose net is negative, so a posted run's net pay /// is never below zero. A net below zero is still a value here: /// the refusal is the caller's rule, not arithmetic's. -/// 4. None on overflow; NEVER a rounded or wrapped result, never a -/// panic. The fold is left to right, so [MAX, MAX, -MAX] from a -/// zero gross is None while the same figures summed first would +/// 4. None on overflow (proved: `net_pay_none_iff_a_prefix_overflows` +/// says None exactly when some running difference leaves the +/// range; on `i64` a deduction of `i64::MIN`, which has no +/// negation, is refused too); NEVER a rounded or wrapped +/// result, never a panic. +/// The fold is left to right, so [MAX, MAX, -MAX] from a zero +/// gross is None while the same figures summed first would /// cancel: each step must be exact, as `total`'s fold is. /// SCENARIOS: /// 1. IF gross 5,000.00 and withholdings 750.00, 250.00, 310.00, diff --git a/crates/ledger-core/src/proofs/payroll.rs b/crates/ledger-core/src/proofs/payroll.rs index f509fa37..35fdaac3 100644 --- a/crates/ledger-core/src/proofs/payroll.rs +++ b/crates/ledger-core/src/proofs/payroll.rs @@ -12,7 +12,27 @@ //! lines. Amounts run to a few thousand units: the law is about the //! shape of the subtraction and the balance, not the magnitude, and //! every total stays far inside the `i64` line range (2^40) that -//! `check_lines` requires. Lean proves the same laws at any size. +//! `check_lines` requires. +//! +//! What carries "any number of employees": Kani covers one employee +//! (and `net_pay` for any five deductions). Lean carries the rest, in +//! bookspec's `Payroll.lean`: `foldl_sub_eq` and `payroll_net_eq` (the +//! left-to-right fold is gross less the sum), `payroll_run_net_eq` (the +//! sum of each employee's net is the total gross less every deduction, +//! for a list of any length) and `payroll_run_plan_balances` (the plan +//! built from per-employee sums balances). The edge where a running +//! difference leaves the range is proved here by +//! `net_pay_none_iff_a_prefix_overflows`; the bridge's edge table +//! checks the same on `Decimal`. +//! +//! The plan harness rebuilds the eight totals on `i64` rather than +//! calling `payroll_entry_plan`: that function works in `Decimal` and +//! `Money` and maps the totals to accounts, neither of which is generic +//! over `Amount`. So the harness proves the arithmetic the plan is made +//! of (the kernel totals and `net_pay`, the shape of the eight lines, +//! `check_lines` accepting them); that `payroll_entry_plan` assembles +//! those same totals in that shape is checked by its tests, the goldens +//! and `check_lines`, which every posted entry passes. //! //! ```text //! GOAL: net pay is gross less the withholdings exactly; it is not @@ -24,7 +44,9 @@ //! through check_lines). //! INVARIANTS: //! 1. net_pay(gross, ds) = gross - sum(ds) whenever it is Some, and -//! None exactly when a running difference leaves the range. +//! (net_pay_none_iff_a_prefix_overflows) it is None exactly when +//! some running difference (gross less the first k deductions) +//! leaves the range. //! 2. sum(ds) <= gross (ds non-negative) gives a net that is Some and //! not negative. //! 3. The eight plan lines pass check_lines: two or more lines, every @@ -73,6 +95,57 @@ fn any_employee() -> Employee { } } +/// `net_pay` is `None` exactly when some running difference leaves the +/// `i64` range, and otherwise the exact result: gross and five +/// deductions over the whole `i64` range, checked against an `i128` +/// running difference (which cannot overflow here) at every prefix. +/// +/// The one exception is the `i64` instantiation's own: `Amount`'s +/// `checked_sub` negates the subtrahend first, and `i64::MIN` has no +/// negation, so a deduction of exactly `i64::MIN` is refused even where +/// the difference would fit (`-1 - i64::MIN`). That is conservative (a +/// refusal, never a wrong figure), and `Decimal`'s range is symmetric, +/// so it does not arise in the engine; the harness assumes no deduction +/// is `i64::MIN` and asserts the refusal at the fixed case. +#[kani::proof] +fn net_pay_none_iff_a_prefix_overflows() { + let gross: i64 = kani::any(); + let mut deductions = [0i64; DEDUCTIONS]; + for deduction in &mut deductions { + let d: i64 = kani::any(); + kani::assume(d != i64::MIN); + *deduction = d; + } + assert!( + net_pay(-1i64, &[i64::MIN]).is_none(), + "i64::MIN has no negation: refused, conservatively" + ); + let mut running = i128::from(gross); + let mut overflowed = false; + for deduction in deductions { + running -= i128::from(deduction); + if i64::try_from(running).is_err() { + overflowed = true; + break; + } + } + let net = net_pay(gross, &deductions); + if overflowed { + assert!(net.is_none(), "a prefix left the range: refused"); + } else { + assert_eq!( + i128::from(net.expect("every prefix in range")), + running, + "no prefix left the range: the exact result" + ); + } + kani::cover!(overflowed, "some running difference overflows"); + kani::cover!( + !overflowed && running != i128::from(gross), + "an exact, changed net" + ); +} + /// Net pay is gross less the deductions: the exact difference of the /// gross and the deductions' total, for deductions of either sign. #[kani::proof] @@ -123,9 +196,10 @@ fn net_pay_nonnegative_when() { /// Two employees timed out in CBMC (over 80 minutes, 2026-11-09: /// sixteen symbolic figures into eight totals and `check_lines`); one /// employee reaches every line, both FICA shares on both sides, and -/// the balance, and Lean's `payroll_plan_balances` carries the plan at -/// its totals for any number of employees (a run's totals are sums of -/// the same eight figures). +/// the balance, and Lean's `payroll_run_plan_balances` carries the plan +/// built from per-employee sums for any number of employees. The plan is +/// rebuilt here on `i64` (see the module doc), not taken from +/// `payroll_entry_plan`. #[kani::proof] fn payroll_plan_balances() { let employees = [any_employee()]; @@ -170,6 +244,14 @@ fn payroll_plan_balances() { check_lines(&plan).is_ok(), "the payroll plan is an acceptable entry" ); - kani::cover!(net < gross, "withholdings leave a smaller net"); - kani::cover!(employer > 0, "the employer share is posted"); + // Covers the assumptions do not already force. + kani::cover!(net == 1, "net pay of exactly one unit is posted"); + kani::cover!( + employees[0].deductions[2] == 0 && employees[0].deductions[3] == 0, + "the payables hold the employer shares alone" + ); + kani::cover!( + employees[0].deductions[0] + employees[0].deductions[1] > 0, + "federal and state withholdings are posted" + ); } diff --git a/crates/ledger-core/tests/kernel_bridge/payroll.rs b/crates/ledger-core/tests/kernel_bridge/payroll.rs index c81acb3d..8079e94e 100644 --- a/crates/ledger-core/tests/kernel_bridge/payroll.rs +++ b/crates/ledger-core/tests/kernel_bridge/payroll.rs @@ -1,7 +1,8 @@ //! U7 bridge properties: payroll arithmetic (kernel sweep). //! //! `proofs/payroll.rs` proves `kernel::net_pay` on `i64` (five -//! deductions, a one-employee plan through `check_lines`); the engine +//! deductions, a one-employee plan through `check_lines`, and `None` +//! exactly when a prefix overflows); the engine //! runs the same code on `Decimal`. These properties check that the two //! instantiations agree, that `Decimal` agrees with an independent exact //! `i128` reference (mantissas over a common power of ten, sharing no @@ -17,7 +18,11 @@ fn dec(cents: i64) -> Decimal { } /// The exact net reference: gross less the deductions, from the -/// mantissas over their common power of ten, in `i128` throughout. +/// mantissas over their common power of ten, in `i128` throughout. Like +/// the kernel's fold it requires every running difference to be +/// representable, each at the scale it has so far (the largest scale of +/// the gross and the deductions folded in): a prefix past `Decimal`'s +/// range is `None` even if later deductions would bring it back. fn net_reference(gross: (i128, u32), deductions: &[(i128, u32)]) -> Option { let scale = deductions .iter() @@ -25,9 +30,22 @@ fn net_reference(gross: (i128, u32), deductions: &[(i128, u32)]) -> Option>(), ); prop_assert_eq!(i.map(dec), d); + prop_assert_eq!(i.map(|n| dec(n).to_string()), d.map(|n| n.to_string())); } /// `Decimal`'s net is the exact difference, for a gross and @@ -67,7 +86,41 @@ proptest! { .map(|&(m, s)| Decimal::try_from_i128_with_scale(m, s).unwrap()) .collect(); let want = net_reference((gross_mantissa, gross_scale), &deductions); - prop_assert_eq!(kernel::net_pay(gross, &ds), want); + // `Decimal` equality ignores scale: compare the rendering too, so + // the reference's scale (the common one) is the kernel's. + let got = kernel::net_pay(gross, &ds); + prop_assert_eq!(got.map(|n| n.to_string()), want.map(|n| n.to_string())); + prop_assert_eq!(got, want); + } + + /// Near `Decimal`'s range the reference also overflows, so the + /// property meets `None` (and the in-range answers beside it), not + /// only the edge table: the kernel and the reference agree on which + /// is which. + #[test] + fn decimal_net_pay_near_the_range_agrees_with_the_reference( + gross_offset in 0i128..=3, + gross_negative in any::(), + deductions in prop::collection::vec((0i128..=3, any::()), 0..=5), + ) { + let max = Decimal::MAX.mantissa(); + let with_sign = |offset: i128, negative: bool| { + if negative { -(max - offset) } else { max - offset } + }; + let g = with_sign(gross_offset, gross_negative); + let ds_m: Vec<(i128, u32)> = deductions + .iter() + .map(|&(o, n)| (with_sign(o, n), 0u32)) + .collect(); + let gross = Decimal::try_from_i128_with_scale(g, 0).unwrap(); + let ds: Vec = ds_m + .iter() + .map(|&(m, s)| Decimal::try_from_i128_with_scale(m, s).unwrap()) + .collect(); + let want = net_reference((g, 0), &ds_m); + let got = kernel::net_pay(gross, &ds); + prop_assert_eq!(got.map(|n| n.to_string()), want.map(|n| n.to_string())); + prop_assert_eq!(got, want); } /// When the deductions do not exceed gross, the net is the gross @@ -85,6 +138,7 @@ proptest! { ) .expect("in range"); prop_assert_eq!(net, dec(gross - deducted)); + prop_assert_eq!(net.to_string(), dec(gross - deducted).to_string()); prop_assert!(net >= Decimal::ZERO); } } diff --git a/docs/proofs/k-u7.md b/docs/proofs/k-u7.md index 6d345244..63cf9fc1 100644 --- a/docs/proofs/k-u7.md +++ b/docs/proofs/k-u7.md @@ -26,7 +26,7 @@ outside the kernel: - `payroll_entry_plan`'s per-column totals: seven local checked folds (gross, employer FICA, federal, state, Social Security, Medicare, other) plus the net total over each line's `net_pay`. -- `payroll_remit_plan`'s raw `total += *balance` (see "Left" below). +- `payroll_remit_plan`'s raw `total += *balance` (see "Fixed in review" below). ## The API @@ -49,7 +49,7 @@ payroll use (nothing in a run rounds or splits) and were not called. On `i64`, fixed arrays, each with `kani::cover!`. A payroll line carries five employee deductions, so the deduction arrays are fixed at -five; the plan harness carries one employee and the plan's eight +five; `net_pay`'s `None` half is proved on the whole `i64` range; the plan harness carries one employee and the plan's eight totals in a fixed array of eight `(Side, amount)` lines. Amounts run to a few thousand units (gross 1 to 10,000, withholdings to 1,000 or 2,000): the laws are about the shape of the subtraction and the @@ -63,8 +63,9 @@ positive). | Harness | Law | Verification | |---|---|---| | `net_pay_is_gross_less_deductions` | 45 | net equals gross less the deductions' `total`, for deductions of either sign; withholdings exceeding gross and a negative net are reached, and `i64::MAX`/`MIN` past the range are `None` (2 covers). 19.5 s verification | +| `net_pay_none_iff_a_prefix_overflows` | 45 | gross and five deductions over the whole `i64` range: `None` exactly when some running difference (gross less the first k deductions, in `i128`) leaves the `i64` range, otherwise exactly the `i128` result; both branches reached (2 covers). 4.4 s verification (24.6 s wall). `i64::MIN` as a deduction is assumed away and its refusal asserted at a fixed case: `Amount::checked_sub` negates first and `i64::MIN` has no negation, so it is refused where `-1 - i64::MIN` would fit (conservative; `Decimal` is symmetric) | | `net_pay_nonnegative_when` | 45 | non-negative deductions summing to at most gross give exactly gross less their sum, never negative; a zero net and a partial withholding are reached (2 covers). 21.9 s wall, 7.0 s verification | -| `payroll_plan_balances` | 45 | one employee: the eight totals `payroll_entry_plan` posts pass `check_lines` (two or more lines, every amount positive and in range, debits equal credits); a smaller net and a posted employer share are reached (2 covers). 65.6 s wall, 62.0 s verification. Two employees timed out in CBMC (over 80 minutes, killed): sixteen symbolic figures into eight totals; one employee reaches every line and both FICA shares on both sides, and Lean carries the plan at its totals for any number of employees | +| `payroll_plan_balances` | 45 | one employee: the eight totals `payroll_entry_plan` posts pass `check_lines` (two or more lines, every amount positive and in range, debits equal credits); a net of exactly one unit, payables holding the employer shares alone (a zero employee Social Security and Medicare withholding) and a posted federal or state withholding are reached (3 covers, each able to fail under the assumes). 142 s wall, 135.5 s verification (2026-11-09, machine load average about 18; 62.0 s verification earlier, unloaded). The harness rebuilds the eight totals on `i64` rather than calling `payroll_entry_plan` (that works in `Decimal`/`Money` and maps accounts, neither generic over `Amount`): it proves the arithmetic the plan is made of and `check_lines` accepting that shape, while the assembly is checked by `payroll_entry_plan`'s tests, the goldens and `check_lines` on every posted entry. Two employees timed out in CBMC (over 80 minutes, killed): sixteen symbolic figures into eight totals. Kani covers one employee; Lean's `payroll_run_net_eq` and `payroll_run_plan_balances` carry any number of employees (see Lean below) | Times: `cargo kani -p ledger-core --exact --harness proofs::payroll::`, the shared dev machine under `nice -n 15`, @@ -78,6 +79,7 @@ traceability gate, `crates/ledger-core/tests/bookspec/traceability.rs`): | Harness | Law | |---|---| | `net_pay_is_gross_less_deductions` | 45 | +| `net_pay_none_iff_a_prefix_overflows` | 45 | | `net_pay_nonnegative_when` | 45 | | `payroll_plan_balances` | 45 | @@ -87,9 +89,16 @@ traceability gate, `crates/ledger-core/tests/bookspec/traceability.rs`): engine in dollars give the same net for the same gross and five deductions, of either sign. - `decimal_net_pay_matches_the_exact_reference`: an independent exact - `i128` reference (mantissas over a common power of ten, no kernel - code and no `Decimal` subtraction at the reference) for a gross and + `i128` reference (mantissas over a common power of ten, each running + difference required representable at its own scale, no kernel code and + no `Decimal` subtraction at the reference), compared by `to_string()` + as well as by value (`Decimal` equality ignores scale) for a gross and up to five deductions of every sign and four scales. +- `decimal_net_pay_near_the_range_agrees_with_the_reference`: gross + and up to five deductions within three units of `Decimal::MAX`/`MIN`, + where the reference also returns `None`: the property meets overflow + mid-fold (a prefix past the range is `None` even when a later + deduction would bring it back), not only the edge table does. - `decimal_net_pay_nonnegative_when`: deductions not exceeding gross give exactly gross less their sum, never negative. - `decimal_net_pay_at_the_edges`: no deductions (the gross itself), the @@ -103,22 +112,39 @@ All pass with the rest of `kernel_bridge`. ## Lean (bookspec `lean/Bookspec/Payroll.lean`, law 45) -`payroll_net_eq` (net pay is gross less the deductions' sum), -`payroll_net_nonneg` (not negative when they do not exceed gross) and -`payroll_plan_balances` (the plan's `net` is zero), with -`payroll_plan_debits_eq_credits` stated directly through -`Basic.net_eq_debits_sub_credits`. `netPay` and `payrollPlan` are the -model: accounts 0 to 7 carry Dr gross, Dr employer FICA, Cr the five -payables (Social Security and Medicare with both shares) and Cr cash -for the net. The model is total where the kernel is partial: `Int` -does not overflow, so the kernel's `None` half is carried by the Kani -overflow assertions and the bridge edge table. No `sorry`; `#print -axioms` shows only `propext` and `Quot.sound` (a subset of the standard -trio). +`netPay` is the kernel's fold, `deductions.foldl (. - .) gross`, not a +closed form. The theorems: -BS-entry-3 links `payroll_net_eq`/`payroll_net_nonneg` and BS-entry-1 -links `payroll_plan_balances`/`payroll_plan_debits_eq_credits`, one -theorem per invariant (law 45 in `spec/laws.md`). +- `foldl_sub_eq` and `payroll_net_eq`: the left-to-right fold is gross + less the deductions' sum (induction). +- `payroll_net_nonneg`: not negative when the deductions do not exceed + gross. +- `payroll_plan_balances` (the plan's `net` is zero) and + `payroll_plan_debits_eq_credits` (stated directly through + `Basic.net_eq_debits_sub_credits`), at the plan's scalar totals: + accounts 0 to 7 carry Dr gross, Dr employer FICA, Cr the five + payables (Social Security and Medicare with both shares) and Cr cash + for the net. +- **Any number of employees**: `payroll_run_net_eq` (for a list of + workers, each a gross and any number of deductions, the sum of each + employee's net is the total gross less the total of every deduction) + and `payroll_run_plan_balances` / `payroll_run_plan_debits_eq_credits` + (the plan whose lines are per-employee sums and whose cash line is the + sum of the per-employee nets, `runPlan`, balances for a list of any + length). These carry the step `total_try(net_pay)` = gross less + deductions that Kani does not (it takes one employee). + +The model is total where the kernel is partial: `Int` does not overflow, +so the kernel's `None` half is carried by +`net_pay_none_iff_a_prefix_overflows` and the bridge. No `sorry`; +`#print axioms` shows only `propext`, `Classical.choice` and +`Quot.sound` (the standard trio). + +BS-entry-3 links `payroll_net_eq`, `payroll_net_nonneg` and +`payroll_run_net_eq`, and BS-entry-1 links `payroll_plan_balances`, +`payroll_plan_debits_eq_credits`, `payroll_run_plan_balances` and +`payroll_run_plan_debits_eq_credits`, one theorem per invariant (law 45 +in `spec/laws.md`). ## Sites routed and left @@ -131,17 +157,16 @@ Routed: the net over each line's kernel `net_pay`); the account mapping, the zero-skipping and the refusal are unchanged. The figures are unchanged: every golden and every test passes as it did. +- `payroll_remit_plan` (fixed in review): it did a raw `total += + *balance`, which panics on `Decimal` overflow, behind callers that + pre-checked through `sum_exact_of` (an unenforced precondition on a + `pub fn`). It now returns `Result<_, LedgerError>`, totals through + `kernel::total_of` and refuses `TooLargeToCompute`; `Ledger` and the + store propagate it and keep their own pre-checks. + `remit_plan_past_exact_arithmetic_is_refused` covers it. Left, with why: -- `payroll_remit_plan`'s `total += *balance`: its signature returns a - bare plan, so it cannot refuse. Both callers (`Ledger` and the - store) first total the same payables through `sum_exact_of` and - refuse past exact arithmetic, in the same order the plan then adds - them, so the raw add sums figures already proved representable; - balances are sums of posted, line-capped lines besides. Changing the - signature is a caller decision, not this refactor (K-U4 left it the - same way, for the same reason). - `Ledger::name_payroll_parties`' per-party `checked_add`: a grouped accumulation (each party's net over its lines), not a collection total; the single checked add is the kernel's `Amount` primitive and @@ -153,10 +178,10 @@ Left, with why: ## Gates - `cargo test -p ledger-core`: all tests and every golden unchanged. - (Ledger-store is untouched.) + `cargo test -p ledger-store` (payroll goes through the store). - `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`. -- Kani: the three harnesses above. +- Kani: the four harnesses above. - The traceability gate against the `k-u7` bookspec branch (patched checker/runner), with `Cargo.lock` restored afterwards: 63 kernel functions (48 fully backed), 45 law rows, 133 claims sections, 1962