merge: payroll's net pay in the kernel (K-U7; reviewed, fixes applied)

Net pay is gross less the withholdings and deductions, now one kernel
fold (net_pay) with the plan's totals through the kernel's checked
totals; payroll_remit_plan refuses a total past exact arithmetic instead
of panicking. Proved: Kani (net pay equals gross less the deductions,
None exactly when a running difference overflows, the plan balances for
an employee), bridge properties against an exact integer reference at
every prefix, and law 45 in bookspec's Lean for any number of employees.
No figure moves; every golden unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-11-09 13:52:02 -07:00
commit a37612d07c
8 files changed
+767 -39

No files matched your search

+60 -3
View File
@@ -1,5 +1,62 @@
//! U7: payroll arithmetic, withholding and employer taxes (kernel sweep).
//!
//! Empty in U0: the unit adds its arithmetic here, in this file alone, so
//! no two sweep units ever edit the same file. The module root re-exports
//! it, keeping every path `crate::kernel::foo`.
//! Net pay is gross less every employee withholding and deduction, exact
//! to the last unit. `payroll::payroll_entry_plan` keeps its account
//! mapping in `payroll.rs` and builds its totals from [`net_pay`] and
//! [`super::total`]/[`super::total_try`]; the plan it builds is checked
//! by [`super::check_lines`] before it posts, as every entry is. There
//! is no tax law here: every withholding number is supplied by the
//! caller, and this file only subtracts what it is given.
use super::Amount;
/// Gross pay less every deduction, in the order given (`gross` less
/// `d1`, less `d2`, and so on), each subtraction exact. `None` the
/// moment a running difference cannot be represented, never a wrapped,
/// rounded or panicking one.
///
/// ```text
/// GOAL: one definition of net pay: gross less the employee's
/// withholdings and deductions, exactly, or refused.
/// SOURCE: BS-entry-3 (amounts are exact; a sum of amounts is their
/// exact sum, so a difference of amounts is their exact
/// difference), BS-entry-4 (every payroll figure a command
/// takes, and every figure an engine derives, is computed with
/// checked arithmetic and refused past exact arithmetic),
/// BS-entry-1 (the payroll plan this feeds balances: debits
/// equal credits); IRS Pub. 15 (docs/spec/sources/irs-payroll.md:
/// the withholdings are the caller's numbers, never a table here).
/// INVARIANTS:
/// 1. Some(n) is the exact mathematical `gross` less the sum of the
/// deductions (every running difference was representable, so no
/// step lost anything). No rounding, ever.
/// 2. net_pay(gross, []) = Some(gross).
/// 3. When the deductions sum to at most `gross`, the net is the
/// gross less that sum and is not negative; the engine refuses a
/// 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 (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,
/// 72.50 and 100.00: SHOULD be 3,517.50.
/// 2. IF the withholdings together exceed gross: SHOULD be the exact
/// negative difference, for the caller to refuse as negative net
/// pay, never a clamped zero.
/// 3. IF a running difference is past the amount's range: SHOULD be
/// None, never a panic.
/// ```
pub fn net_pay<T: Amount>(gross: T, deductions: &[T]) -> Option<T> {
let mut net = gross;
for &deduction in deductions {
net = net.checked_sub(deduction)?;
}
Some(net)
}
+1 -1
View File
@@ -8533,7 +8533,7 @@ impl Ledger {
}
let entry = self.try_create_entry(date, &format!("Payroll tax remittance {date}"))?;
for (account, side, amount) in
payroll_remit_plan(&payables, cash_account, self.base_currency)
payroll_remit_plan(&payables, cash_account, self.base_currency)?
{
self.add_line(entry, account, side, amount)?;
}
+38 -27
View File
@@ -52,15 +52,16 @@ impl PayrollLine {
/// (TooLargeToCompute), never a panic, past exact arithmetic: a run is
/// restored as journaled (BS-entry-4).
pub fn net_pay(&self) -> Result<Decimal, LedgerError> {
[
self.federal_withholding,
self.state_withholding,
self.ss_employee,
self.medicare_employee,
self.other_deductions,
]
.into_iter()
.try_fold(self.gross_pay, Decimal::checked_sub)
crate::kernel::net_pay(
self.gross_pay,
&[
self.federal_withholding,
self.state_withholding,
self.ss_employee,
self.medicare_employee,
self.other_deductions,
],
)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{}'s net pay", self.employee_name)))
}
}
@@ -172,20 +173,26 @@ pub fn payroll_entry_plan(
base: Currency,
) -> Result<Vec<(AccountId, Side, Money)>, LedgerError> {
let too_large = || LedgerError::TooLargeToCompute("the payroll run's totals".into());
let sum = |f: &dyn Fn(&PayrollLine) -> Option<Decimal>| {
lines
.iter()
.try_fold(Decimal::ZERO, |t, l| t.checked_add(f(l)?))
.ok_or_else(too_large)
};
let gross = sum(&|l| Some(l.gross_pay))?;
let employer = sum(&|l| l.ss_employer.checked_add(l.medicare_employer))?;
let federal = sum(&|l| Some(l.federal_withholding))?;
let state = sum(&|l| Some(l.state_withholding))?;
let ss = sum(&|l| l.ss_employee.checked_add(l.ss_employer))?;
let medicare = sum(&|l| l.medicare_employee.checked_add(l.medicare_employer))?;
let other = sum(&|l| Some(l.other_deductions))?;
let net = sum(&|l| l.net_pay().ok())?;
// Every total is a kernel total (net pay itself is kernel::net_pay):
// exact, or refused here as TooLargeToCompute, never a panic.
let gross = crate::kernel::total_of(lines.iter(), |l| l.gross_pay).ok_or_else(too_large)?;
let employer = crate::kernel::total_try(lines.iter(), |l| {
l.ss_employer.checked_add(l.medicare_employer)
})
.ok_or_else(too_large)?;
let federal =
crate::kernel::total_of(lines.iter(), |l| l.federal_withholding).ok_or_else(too_large)?;
let state =
crate::kernel::total_of(lines.iter(), |l| l.state_withholding).ok_or_else(too_large)?;
let ss = crate::kernel::total_try(lines.iter(), |l| l.ss_employee.checked_add(l.ss_employer))
.ok_or_else(too_large)?;
let medicare = crate::kernel::total_try(lines.iter(), |l| {
l.medicare_employee.checked_add(l.medicare_employer)
})
.ok_or_else(too_large)?;
let other =
crate::kernel::total_of(lines.iter(), |l| l.other_deductions).ok_or_else(too_large)?;
let net = crate::kernel::total_try(lines.iter(), |l| l.net_pay().ok()).ok_or_else(too_large)?;
let mut plan = Vec::new();
let mut push = |account: AccountId, side: Side, amount: Decimal| {
if !amount.is_zero() {
@@ -206,24 +213,28 @@ pub fn payroll_entry_plan(
/// The remittance entry's lines: Dr each payable with a non-zero balance,
/// Cr cash for the total. Balances are normal-side (positive = owed), so
/// the plan balances by construction.
///
/// Refused (TooLargeToCompute) when the payables' total is past exact
/// arithmetic, never a panic: the total is the kernel's checked fold, so
/// this function does not depend on its callers having refused first.
pub fn payroll_remit_plan(
payables: &[(AccountId, Decimal)],
cash_account: AccountId,
base: Currency,
) -> Vec<(AccountId, Side, Money)> {
) -> Result<Vec<(AccountId, Side, Money)>, LedgerError> {
let total = crate::kernel::total_of(payables.iter(), |(_, b)| *b)
.ok_or_else(|| LedgerError::TooLargeToCompute("the payroll taxes payable".into()))?;
let mut plan = Vec::new();
let mut total = Decimal::ZERO;
for (account, balance) in payables {
if balance.is_zero() {
continue;
}
plan.push((*account, Side::Debit, Money::new(*balance, base)));
total += *balance;
}
if !total.is_zero() {
plan.push((cash_account, Side::Credit, Money::new(total, base)));
}
plan
Ok(plan)
}
#[cfg(test)]
+255 -3
View File
@@ -1,5 +1,257 @@
//! 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 one employee 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.
//!
//! 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
//! 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
//! (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
//! 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 `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]
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`: one employee, 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.
/// 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_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()];
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"
);
// 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"
);
}
@@ -1,4 +1,194 @@
//! 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 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
//! 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. 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<Decimal> {
let scale = deductions
.iter()
.map(|&(_, s)| s)
.max()
.unwrap_or(0)
.max(gross.1);
let at_common = |(m, s): (i128, u32)| m.checked_mul(10i128.checked_pow(scale - s)?);
let mut net: i128 = at_common(gross)?;
let mut so_far = gross.1;
let representable = |net: i128, so_far: u32| {
let own = net / 10i128.pow(scale - so_far);
Decimal::try_from_i128_with_scale(own, so_far).is_ok()
};
if !representable(net, so_far) {
return None;
}
for &(mantissa, s) in deductions {
net = net.checked_sub(at_common((mantissa, s))?)?;
so_far = so_far.max(s);
if !representable(net, so_far) {
return None;
}
}
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::<Vec<_>>(),
);
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
/// 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<Decimal> = deductions
.iter()
.map(|&(m, s)| Decimal::try_from_i128_with_scale(m, s).unwrap())
.collect();
let want = net_reference((gross_mantissa, gross_scale), &deductions);
// `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::<bool>(),
deductions in prop::collection::vec((0i128..=3, any::<bool>()), 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<Decimal> = 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
/// 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::<Vec<_>>(),
)
.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);
}
}
/// 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)
);
}
@@ -1029,7 +1029,8 @@ fn remit_plan_hand_worked() {
&[(3, d("600.00")), (4, d("0")), (6, d("145.00"))],
PLAN_CASH,
Currency::USD,
);
)
.unwrap();
let got: Vec<(AccountId, Side, Decimal)> =
plan.iter().map(|(a, s, m)| (*a, *s, m.amount)).collect();
assert_eq!(
@@ -1042,6 +1043,29 @@ fn remit_plan_hand_worked() {
);
}
/// Oracle: BS-entry-4 (every derived figure computed with checked
/// arithmetic): payables whose total is past exact arithmetic are refused
/// as TooLargeToCompute, never a panic, even when a caller did not
/// pre-check.
#[test]
fn remit_plan_past_exact_arithmetic_is_refused() {
let err = payroll_remit_plan(
&[(3, Decimal::MAX), (6, Decimal::ONE)],
PLAN_CASH,
Currency::USD,
)
.unwrap_err();
assert!(matches!(err, LedgerError::TooLargeToCompute(_)), "{err:?}");
// Past the range downward, too.
let err = payroll_remit_plan(
&[(3, Decimal::MIN), (6, -Decimal::ONE)],
PLAN_CASH,
Currency::USD,
)
.unwrap_err();
assert!(matches!(err, LedgerError::TooLargeToCompute(_)), "{err:?}");
}
/// Oracle: run_payroll INVARIANTS 1–2 and doc (auto-create 6100/6110/
/// 2110–2150), hand-worked Alice entry; balances after: cash 10000 − 3567.50
/// = 6432.50; payables as in the plan.
@@ -1478,7 +1502,7 @@ proptest! {
.enumerate()
.map(|(i, c)| (i as AccountId + 1, Decimal::new(*c, 2)))
.collect();
let plan = payroll_remit_plan(&payables, PLAN_CASH, Currency::USD);
let plan = payroll_remit_plan(&payables, PLAN_CASH, Currency::USD).unwrap();
let total: Decimal = payables.iter().map(|(_, b)| *b).sum();
let (dr, cr) = plan_totals(&plan);
prop_assert_eq!(dr, cr);
+1 -1
View File
@@ -4437,7 +4437,7 @@ impl Store {
}
let entry_id = self.ledger.next_entry_id();
let base = self.base_currency;
let plan = payroll_remit_plan(&payables, cash_account, base);
let plan = payroll_remit_plan(&payables, cash_account, base)?;
let description = format!("Payroll tax remittance {date}");
let mut journaled = Vec::with_capacity(plan.len() + 2);
journaled.push(self.append_journal(
+194
View File
@@ -0,0 +1,194 @@
# 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 "Fixed in review" below).
## The API
```rust
pub fn net_pay<T: Amount>(gross: T, deductions: &[T]) -> Option<T>
```
`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; `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
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_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 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::<name>`, 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_none_iff_a_prefix_overflows` | 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, 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
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)
`netPay` is the kernel's fold, `deductions.foldl (. - .) gross`, not a
closed form. The theorems:
- `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
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.
- `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:
- `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.
`cargo test -p ledger-store` (payroll goes through the store).
- `cargo fmt --all --check`,
`cargo clippy --workspace --all-targets -- -D warnings`.
- 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
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`.