From fbe7eb712580924a450fa311284d0e98ad68ceb9 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 10:37:16 -0700 Subject: [PATCH] test(core): Kani and bridge for the kernel payroll Three Kani harnesses on i64, fixed arrays (five deductions, a two-employee plan of eight lines): net_pay_is_gross_less_deductions (19.5s verification), net_pay_nonnegative_when (7.0s) and payroll_plan_balances through check_lines (297.6s), each with covers. The bridge checks i64 against Decimal and Decimal against an independent exact i128 reference, with the edges (Decimal::MAX/MIN, mid-fold overflow) giving None, never a panic. All three prove law 45 (bookspec, BS-entry-1/BS-entry-3/BS-entry-4). The traceability gate passes against the k-u7 bookspec branch: 63 kernel functions, 48 fully backed, 45 law rows. docs/proofs/k-u7.md is the unit's record. Co-Authored-By: Muse Wonder 1.0 --- crates/ledger-core/src/proofs/payroll.rs | 173 +++++++++++++++++- .../tests/kernel_bridge/payroll.rs | 140 +++++++++++++- docs/proofs/k-u7.md | 169 +++++++++++++++++ 3 files changed, 477 insertions(+), 5 deletions(-) create mode 100644 docs/proofs/k-u7.md diff --git a/crates/ledger-core/src/proofs/payroll.rs b/crates/ledger-core/src/proofs/payroll.rs index d5a1da2c..2fc32ec8 100644 --- a/crates/ledger-core/src/proofs/payroll.rs +++ b/crates/ledger-core/src/proofs/payroll.rs @@ -1,5 +1,172 @@ //! U7 proof harnesses: payroll arithmetic (kernel sweep). //! -//! Empty in U0: the unit adds its Kani harnesses here; `just prove` scans -//! every file in `proofs/`, so a harness needs no change to the module -//! root or the recipe. +//! `kernel::net_pay` on `i64`: net is gross less the deductions exactly, +//! it is never negative when they do not exceed gross, and a payroll +//! plan built from net pay and totals balances through `check_lines`. +//! +//! A payroll line carries five employee deductions (federal, state, +//! Social Security, Medicare, other), so the deduction arrays are fixed +//! at five. The plan harness carries two employees and the plan's eight +//! totals (gross, employer FICA, the five payables, net), each a kernel +//! total of the two lines, in a fixed array of eight `(Side, amount)` +//! 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. +//! +//! ```text +//! GOAL: net pay is gross less the withholdings exactly; it is not +//! negative when they do not exceed gross; and the payroll plan +//! (Dr gross + employer FICA, Cr the payables + net) balances. +//! SOURCE: BS-entry-3 (exact amounts), BS-entry-4 (every payroll +//! figure and every derived figure computed with checked +//! arithmetic), BS-entry-1 (debits equal credits, the plan +//! 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. +//! 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 +//! amount positive and in range, debits equal to credits. +//! SCENARIOS: +//! 1. IF the withholdings exceed gross: the net is the exact negative +//! difference (the engine refuses the line, not the arithmetic). +//! 2. IF a deduction is past the range: SHOULD be None. +//! ``` + +use crate::Side; +use crate::kernel::{check_lines, net_pay, total}; + +/// The five employee deductions of one payroll line. +const DEDUCTIONS: usize = 5; + +/// One employee's figures for the plan harness: gross, the five +/// withholdings, and the two employer shares. +struct Employee { + gross: i64, + deductions: [i64; DEDUCTIONS], + ss_employer: i64, + medicare_employer: i64, +} + +fn any_employee() -> Employee { + let gross: i64 = kani::any(); + kani::assume((1..=10_000).contains(&gross)); + let mut deductions = [0i64; DEDUCTIONS]; + for deduction in &mut deductions { + let d: i64 = kani::any(); + kani::assume((0..=1_000).contains(&d)); + *deduction = d; + } + // Net pay is at least one unit, so the plan's cash line is posted. + kani::assume(total(deductions.iter().copied()).expect("in range") < gross); + let ss_employer: i64 = kani::any(); + kani::assume((1..=1_000).contains(&ss_employer)); + let medicare_employer: i64 = kani::any(); + kani::assume((1..=1_000).contains(&medicare_employer)); + Employee { + gross, + deductions, + ss_employer, + medicare_employer, + } +} + +/// Net pay is gross less the deductions: the exact difference of the +/// gross and the deductions' total, for deductions of either sign. +#[kani::proof] +fn net_pay_is_gross_less_deductions() { + let gross: i64 = kani::any(); + kani::assume((-10_000..=10_000).contains(&gross)); + let mut deductions = [0i64; DEDUCTIONS]; + for deduction in &mut deductions { + let d: i64 = kani::any(); + kani::assume((-1_000..=1_000).contains(&d)); + *deduction = d; + } + let deducted = total(deductions.iter().copied()).expect("in range"); + let net = net_pay(gross, &deductions).expect("in range"); + assert_eq!(net, gross - deducted, "net is gross less the deductions"); + // Past the range the same call is None, never a panic. + assert!(net_pay(i64::MAX, &[-1]).is_none(), "overflow is refused"); + assert!(net_pay(i64::MIN, &[1]).is_none(), "underflow is refused"); + kani::cover!(deducted > gross, "withholdings exceed gross"); + kani::cover!(net < 0, "a negative net is a value"); +} + +/// When the (non-negative) deductions do not exceed gross, the net is +/// the gross less their sum and is not negative. +#[kani::proof] +fn net_pay_nonnegative_when() { + let gross: i64 = kani::any(); + kani::assume((0..=10_000).contains(&gross)); + let mut deductions = [0i64; DEDUCTIONS]; + for deduction in &mut deductions { + let d: i64 = kani::any(); + kani::assume((0..=2_000).contains(&d)); + *deduction = d; + } + let deducted = total(deductions.iter().copied()).expect("in range"); + kani::assume(deducted <= gross); + let net = net_pay(gross, &deductions).expect("in range"); + assert_eq!(net, gross - deducted, "net is gross less the deductions"); + assert!(net >= 0, "the net is not negative"); + kani::cover!(net == 0, "withholdings can take the whole gross"); + kani::cover!(deducted > 0 && net > 0, "a partial withholding"); +} + +/// The payroll plan balances through `check_lines`: two employees, the +/// eight totals `payroll_entry_plan` posts (Dr gross, Dr employer FICA, +/// Cr federal, state, Social Security, Medicare and other payables, Cr +/// cash net), every total positive, debits equal to credits exactly. +#[kani::proof] +fn payroll_plan_balances() { + let employees = [any_employee(), any_employee()]; + let gross = total(employees.iter().map(|e| e.gross)).expect("in range"); + let employer = total( + employees + .iter() + .map(|e| e.ss_employer + e.medicare_employer), + ) + .expect("in range"); + let federal = total(employees.iter().map(|e| e.deductions[0])).expect("in range"); + let state = total(employees.iter().map(|e| e.deductions[1])).expect("in range"); + let ss = total(employees.iter().map(|e| e.deductions[2] + e.ss_employer)).expect("in range"); + let medicare = total( + employees + .iter() + .map(|e| e.deductions[3] + e.medicare_employer), + ) + .expect("in range"); + let other = total(employees.iter().map(|e| e.deductions[4])).expect("in range"); + let net = total( + employees + .iter() + .map(|e| net_pay(e.gross, &e.deductions).expect("in range")), + ) + .expect("in range"); + // The real plan skips a zero total; this harness takes the case + // where none is zero (gross, employer FICA, both FICA payables and + // net are positive by construction above). + kani::assume(federal > 0 && state > 0 && other > 0); + let plan: [(Side, i64); 8] = [ + (Side::Debit, gross), + (Side::Debit, employer), + (Side::Credit, federal), + (Side::Credit, state), + (Side::Credit, ss), + (Side::Credit, medicare), + (Side::Credit, other), + (Side::Credit, net), + ]; + assert!( + check_lines(&plan).is_ok(), + "the payroll plan is an acceptable entry" + ); + kani::cover!( + employees[0].gross != employees[1].gross, + "two employees differ" + ); + kani::cover!(net > gross, "net over two employees exceeds one gross"); +} diff --git a/crates/ledger-core/tests/kernel_bridge/payroll.rs b/crates/ledger-core/tests/kernel_bridge/payroll.rs index 1b22afdc..f0a94cc8 100644 --- a/crates/ledger-core/tests/kernel_bridge/payroll.rs +++ b/crates/ledger-core/tests/kernel_bridge/payroll.rs @@ -1,4 +1,140 @@ //! U7 bridge properties: payroll arithmetic (kernel sweep). //! -//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, -//! beside `main.rs` and the other units. +//! `proofs/payroll.rs` proves `kernel::net_pay` on `i64` (five +//! deductions, a two-employee plan through `check_lines`); 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 +//! code with the kernel), and the edge table: a gross or a running +//! difference past the type's range is `None`, never a panic. + +use ledger_core::kernel; +use proptest::prelude::*; +use rust_decimal::Decimal; + +fn dec(cents: i64) -> Decimal { + Decimal::new(cents, 2) +} + +/// The exact net reference: gross less the deductions, from the +/// mantissas over their common power of ten, in `i128` throughout. +fn net_reference(gross: (i128, u32), deductions: &[(i128, u32)]) -> Option { + let scale = deductions + .iter() + .map(|&(_, s)| s) + .max() + .unwrap_or(0) + .max(gross.1); + let mut net: i128 = gross.0.checked_mul(10i128.checked_pow(scale - gross.1)?)?; + for &(mantissa, s) in deductions { + net = net.checked_sub(mantissa.checked_mul(10i128.checked_pow(scale - s)?)?)?; + } + Decimal::try_from_i128_with_scale(net, scale).ok() +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(2000))] + + /// The `i64` kernel (cents) and the `Decimal` kernel (dollars) give + /// the same net for the same gross and five deductions. + #[test] + fn i64_and_decimal_net_pay_agree( + gross in -1_000_000_000i64..=1_000_000_000, + deductions in prop::collection::vec(-100_000_000i64..=100_000_000, 5), + ) { + let i = kernel::net_pay(gross, &deductions); + let d = kernel::net_pay( + dec(gross), + &deductions.iter().copied().map(dec).collect::>(), + ); + prop_assert_eq!(i.map(dec), d); + } + + /// `Decimal`'s net is the exact difference, for a gross and + /// deductions of every sign and scale. + #[test] + fn decimal_net_pay_matches_the_exact_reference( + gross_mantissa in -1_000_000_000i128..=1_000_000_000i128, + gross_scale in 0u32..=4, + deductions in prop::collection::vec( + (-1_000_000_000i128..=1_000_000_000i128, 0u32..=4), + 0..=5, + ), + ) { + let gross = Decimal::try_from_i128_with_scale(gross_mantissa, gross_scale).unwrap(); + let ds: Vec = deductions + .iter() + .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); + } + + /// When the deductions do not exceed gross, the net is the gross + /// less their sum and is not negative, at both instantiations. + #[test] + fn decimal_net_pay_nonnegative_when( + gross in 0i64..=1_000_000_000, + deductions in prop::collection::vec(0i64..=100_000_000, 5), + ) { + let deducted: i64 = deductions.iter().sum(); + prop_assume!(deducted <= gross); + let net = kernel::net_pay( + dec(gross), + &deductions.iter().copied().map(dec).collect::>(), + ) + .expect("in range"); + prop_assert_eq!(net, dec(gross - deducted)); + prop_assert!(net >= Decimal::ZERO); + } +} + +/// The edges: empty deductions, a zero net, and figures past the type's +/// range. Each answer is exact or `None`, never a panic. +#[test] +fn decimal_net_pay_at_the_edges() { + // No deductions: the net is the gross itself. + assert_eq!( + kernel::net_pay(Decimal::new(500_000, 2), &[]), + Some(Decimal::new(500_000, 2)) + ); + // The payroll scenario: 5,000.00 less 750, 250, 310, 72.50, 100. + assert_eq!( + kernel::net_pay( + Decimal::new(500_000, 2), + &[ + Decimal::new(75_000, 2), + Decimal::new(25_000, 2), + Decimal::new(31_000, 2), + Decimal::new(7_250, 2), + Decimal::new(10_000, 2), + ], + ), + Some(Decimal::new(351_750, 2)) + ); + // Withholdings taking the whole gross give exactly zero, and more + // than the gross give the exact negative difference. + assert_eq!( + kernel::net_pay(Decimal::ONE, &[Decimal::ONE]), + Some(Decimal::ZERO) + ); + assert_eq!( + kernel::net_pay(Decimal::ONE, &[Decimal::from(2)]), + Some(-Decimal::ONE) + ); + // Past the range, in either direction and mid-fold: None. + assert_eq!(kernel::net_pay(Decimal::MAX, &[-Decimal::ONE]), None); + assert_eq!(kernel::net_pay(Decimal::MIN, &[Decimal::ONE]), None); + assert_eq!( + kernel::net_pay(Decimal::ZERO, &[Decimal::MAX, Decimal::MAX]), + None + ); + // The same edges on the Kani instantiation. + assert_eq!(kernel::net_pay(i64::MAX, &[-1]), None); + assert_eq!(kernel::net_pay(i64::MIN, &[1]), None); + assert_eq!(kernel::net_pay(0i64, &[i64::MAX, i64::MAX]), None); + assert_eq!( + kernel::net_pay(5_000i64, &[750, 250, 310, 72, 100]), + Some(3_518) + ); +} diff --git a/docs/proofs/k-u7.md b/docs/proofs/k-u7.md new file mode 100644 index 00000000..2fe1932a --- /dev/null +++ b/docs/proofs/k-u7.md @@ -0,0 +1,169 @@ +# K-U7: payroll's net pay (`kernel/payroll.rs`) + +_Folded into `docs/verification.md` by the integrator; this note is the +unit's own record._ + +Kernel sweep unit U7 (`plan/kernel-sweep-audit.md` section 3, U7). It +serves a payroll run's net pay and its entry plan: gross wages and the +employer FICA share debited, the withholdings and both FICA shares +credited to the 2110–2150 payables, net pay credited to cash (IRS Pub. +15, `docs/spec/sources/irs-payroll.md`: every withholding number is the +caller's; there is no tax table). The bookspec rules are BS-entry-3 +(exact amounts), BS-entry-4 (every payroll figure, and every derived +figure, computed with checked arithmetic) and BS-entry-1 (debits equal +credits). Law 45 in bookspec's `spec/laws.md`. + +## What remained after K-U4 + +K-U4 already took the collection totals: `payroll_entry_plan`'s sums +were checked folds, `remit_payroll_taxes` and the store's remittance +refuse through `money::sum_exact_of` before they plan, and the MCP +payroll totals go through `checked_sum`/`sum_exact_of`. What was still +outside the kernel: + +- `PayrollLine::net_pay`: gross less the five employee withholdings, a + hand fold of `Decimal::checked_sub` in `payroll.rs`. +- `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). + +## The API + +```rust +pub fn net_pay(gross: T, deductions: &[T]) -> Option +``` + +`net_pay` is gross less every deduction, folded left to right with +`checked_sub`: `Some` is the exact difference, and `None` the moment a +running difference cannot be represented — never a wrapped, rounded or +panicking result. The fold preserves the old `PayrollLine::net_pay` +behaviour exactly, including at the edge: `[MAX, MAX, -MAX]` from a +zero gross is `None`, where summing the deductions first would cancel; +each step must be exact, as `total`'s fold is. A net below zero is a +value, not a refusal: `validate_payroll_lines` refuses it as +`NegativeNetPay`, as before. `round_step` and `plug_last` have no +payroll use (nothing in a run rounds or splits) and were not called. + +## Kani harnesses (`src/proofs/payroll.rs`) + +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 two employees 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 +balance, every total stays far inside the `i64` line range (2^40) that +`check_lines` requires, and Lean proves the same laws at any size. The +plan harness takes the case where no plan total is zero (the real plan +skips a zero total; gross, employer FICA, both FICA payables and net +are positive by construction, and federal, state and other are assumed +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_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 | two employees: the eight totals `payroll_entry_plan` posts pass `check_lines` (two or more lines, every amount positive and in range, debits equal credits); differing employees and a net over one gross are reached (2 covers). 297.6 s verification | + +Times: `cargo kani -p ledger-core --exact --harness +proofs::payroll::`, the shared dev machine under `nice -n 15`, +2026-11-09. `payroll_plan_balances` is the slow harness of the unit: +`check_lines` sums the eight lines through `totals`, and two symbolic +employees make every column total a sum the solver must carry. + +The bookspec law each harness proves (machine-readable for the +traceability gate, `crates/ledger-core/tests/bookspec/traceability.rs`): + +| Harness | Law | +|---|---| +| `net_pay_is_gross_less_deductions` | 45 | +| `net_pay_nonnegative_when` | 45 | +| `payroll_plan_balances` | 45 | + +## Bridge (`tests/kernel_bridge/payroll.rs`) + +- `i64_and_decimal_net_pay_agree`: the Kani model in cents and the + 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 + up to five deductions of every sign and four scales. +- `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 + 5,000.00 scenario (3,517.50), withholdings taking the whole gross + (exactly zero), more than the gross (the exact negative difference), + and past the range in either direction and mid-fold + (`Decimal::MAX`/`MIN`, `[MAX, MAX]` from zero, and the same on + `i64`): each is exact or `None`, never a panic. + +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). + +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`). + +## Sites routed and left + +Routed: + +- `PayrollLine::net_pay` → `kernel::net_pay` over the five employee + withholdings; the `TooLargeToCompute` refusal is unchanged. +- `payroll_entry_plan` → `kernel::total_of` (gross, federal, state, + other), `kernel::total_try` (employer FICA, both FICA payables, and + 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. + +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 + already refuses as `TooLargeToCompute`. No kernel shape fits it + without restructuring the grouping. +- The MCP payroll totals and the store's remittance total: already + kernel arithmetic through `money::sum_exact*` (K-U4). + +## Gates + +- `cargo test -p ledger-core`: all tests and every golden unchanged. + (Ledger-store is untouched.) +- `cargo fmt --all --check`, + `cargo clippy --workspace --all-targets -- -D warnings`. +- Kani: the three 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 + backticked tokens; 15 exceptions, the pinned skipped set unchanged. + Against the still-pinned revision the same gate fails only on law + 45, which is not in it yet, exactly as every K-U law before the + integrator moves the pin. +- bookspec: `lake build`, `lake env lean Audit.lean` (standard axioms + only), `cargo test --workspace`, `render -- --check`, + `scripts/spec-floors.sh main`.