From 3cc9965a0412de00292fb5b03083b55ef5edba2a Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 05:44:53 -0700 Subject: [PATCH] refactor(core): the tax summary's deductible share moves into the kernel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A category's deductible amount is the exact sum of its accounts' shares (book × deductible percent ÷ 100), rounded once to the cent, half away from zero (rules.md B-32's CHOICE, owner 2026-11-07, D-67; B-21's "round off only the total"). That rounding was the last money arithmetic outside kernel.rs: tax.rs accumulated Decimal shares and called round_dp_with_strategy itself, so nothing proved the round-once law. `kernel::deductible_amount` now takes the (book, percent) pairs and sums their products exactly, then `Amount::checked_div_round_cent` divides by 100 and rounds once to the cent. The trait method is the explicit step: exact quotient and remainder on a machine integer, cents-then-remainder on Decimal (no double rounding through Decimal's 28-place division), halves away from zero, no negative zero, None on overflow. The amount is the nearest cent of the exact sum, never the sum of per-account roundings, and its sign follows the sum. tax.rs keeps the same output and the same TooLargeToCompute error; it now gathers the shares and asks the kernel for the category total. The 18 tax tests, the golden Form 1065 summary and the two round-once tests pass unchanged. Co-Authored-By: DeepSeek V4.1 Flash --- crates/ledger-core/src/kernel.rs | 126 ++++++++++++++++++++++++++++++- crates/ledger-core/src/tax.rs | 60 +++++++++------ 2 files changed, 160 insertions(+), 26 deletions(-) diff --git a/crates/ledger-core/src/kernel.rs b/crates/ledger-core/src/kernel.rs index 5a99d08f..4456fcc2 100644 --- a/crates/ledger-core/src/kernel.rs +++ b/crates/ledger-core/src/kernel.rs @@ -56,7 +56,10 @@ //! §723 basis is the contributor's adjusted basis, the depreciable basis //! the cost, that basis, or the lesser of it and fair market value, and //! the §704(c) built-in gain is fair market value less the §723 basis -//! (B-25). +//! (B-25); +//! * a tax category's deductible amount adds its accounts' exact shares and +//! rounds once to the cent, half away from zero, never share by share +//! (B-32, B-21). use crate::assets::BasisRule; use crate::{AccountType, Side}; @@ -88,6 +91,15 @@ pub trait Amount: Copy + Ord { /// `self / rhs` exactly, or `None` when `rhs` is zero or the quotient /// is not a whole amount of `Self` (never a rounded share). fn checked_div_exact(self, rhs: Self) -> Option; + /// `self / rhs`, rounded once to the cent (the nearest whole minor + /// unit: a unit for a machine integer, two decimal places for + /// [`Decimal`] dollars), ties away from zero; never a negative zero. + /// `None` when `rhs` is zero or the quotient cannot be represented. + /// + /// The one use is a tax category's deductible amount (rules.md B-32, + /// B-21), whose shares are added exactly and rounded once, never + /// share by share. + fn checked_div_round_cent(self, rhs: Self) -> Option; /// `self - rhs`, or `None` when it cannot be represented exactly. fn checked_sub(self, rhs: Self) -> Option { @@ -126,6 +138,36 @@ impl Amount for Decimal { let q = self.checked_div(rhs)?; (q.checked_mul(rhs) == Some(self)).then_some(q) } + fn checked_div_round_cent(self, rhs: Self) -> Option { + if rhs == Self::ZERO { + return None; + } + // Work in cents so the one rounding is to a whole cent: an amount + // in dollars is already exact to its own scale, and multiplying by + // 100 only shifts it. + let hundred = Decimal::from(100u32); + let scaled = self.checked_mul(hundred)?; + // The truncated quotient and its exact remainder, so the cent's + // half decides the rounding rather than Decimal's own 28-place + // division rounding. + let q = scaled.checked_div(rhs)?.trunc(); + let r = scaled.checked_sub(q.checked_mul(rhs)?)?; + let r_mag = r.abs(); + let d_mag = rhs.abs(); + let rest = d_mag.checked_sub(r_mag)?; + let q = if r_mag >= rest { + if r > Self::ZERO { + q.checked_add(Decimal::ONE)? + } else { + q.checked_sub(Decimal::ONE)? + } + } else { + q + }; + let out = q.checked_div(hundred)?; + // Never a negative zero: money never prints "-0.00". + Some(if out == Self::ZERO { Self::ZERO } else { out }) + } } impl Amount for i32 { @@ -153,6 +195,27 @@ impl Amount for i32 { } self.checked_div(rhs) } + fn checked_div_round_cent(self, rhs: Self) -> Option { + if rhs == 0 { + return None; + } + // A machine integer is already in its smallest money unit, so its + // cent is a whole unit: truncate and round the remainder half + // away from zero. + let q = self.checked_div(rhs)?; + let r = self.checked_rem(rhs)?; + let r_mag = r.unsigned_abs(); + let d_mag = rhs.unsigned_abs(); + let rest = d_mag.checked_sub(r_mag)?; + if r_mag < rest { + return Some(q); + } + if r > 0 { + q.checked_add(1) + } else { + q.checked_sub(1) + } + } } impl Amount for i64 { @@ -181,6 +244,27 @@ impl Amount for i64 { } self.checked_div(rhs) } + fn checked_div_round_cent(self, rhs: Self) -> Option { + if rhs == 0 { + return None; + } + // A machine integer is already in its smallest money unit, so its + // cent is a whole unit: truncate and round the remainder half + // away from zero. + let q = self.checked_div(rhs)?; + let r = self.checked_rem(rhs)?; + let r_mag = r.unsigned_abs(); + let d_mag = rhs.unsigned_abs(); + let rest = d_mag.checked_sub(r_mag)?; + if r_mag < rest { + return Some(q); + } + if r > 0 { + q.checked_add(1) + } else { + q.checked_sub(1) + } + } } /// Why the kernel rejected an entry's lines. @@ -342,6 +426,46 @@ pub fn line_amount(quantity: T, unit_price: T) -> Option { quantity.checked_mul(unit_price) } +/// A tax category's deductible amount from its accounts' `(book, +/// percent)` pairs: every account's exact share `book × percent ÷ 100` +/// added first, then the one rounding to the cent, half away from zero. +/// +/// ```text +/// GOAL: a category's deductible amount is its exact shares added and +/// rounded once, never a sum of rounded shares. +/// SOURCE: docs/spec/rules.md B-32 (CHOICE: owner, 2026-11-07, D-67) and +/// B-21 (Form 1065 instructions: "include cents when adding the +/// amounts and round off only the total"); plan/served.md 10.1. +/// INVARIANTS: +/// 1. On Some(a), a is the exact sum S = Σ(book_i × percent_i ÷ 100) +/// rounded once to the nearest cent, a tie away from zero. +/// 2. |a − S| <= half a cent. a never has S's opposite sign, and is +/// never a negative zero. +/// 3. a is round(S), never Σ round(book_i × percent_i ÷ 100): one +/// rounding for the category, after every share is added. +/// 4. None when a product or the running sum overflows; never a panic. +/// SCENARIOS: +/// 1. IF two accounts of 1.01 at 50% each: +/// - SHOULD be 1.01 (the exact 0.505 + 0.505) +/// - NEVER 1.02 (0.51 + 0.51, rounding each share) +/// BECAUSE the category rounds only its total. +/// 2. IF 1.05 at 50% and 1.05 at 30%: +/// - SHOULD be 0.84 (0.525 + 0.315) +/// - NEVER 0.85 (0.53 + 0.32) +/// 3. IF 333.33 at 50%: +/// - SHOULD be 166.67 (166.665, a tie away from zero) +/// ``` +pub fn deductible_amount(shares: &[(T, T)]) -> Option { + let hundred = T::from_u32(100)?; + let mut numerator = T::ZERO; + for &(book, percent) in shares { + numerator = numerator.checked_add(book.checked_mul(percent)?)?; + } + let rounded = numerator.checked_div_round_cent(hundred)?; + // Never a negative zero: money never prints "-0". + Some(if rounded == T::ZERO { T::ZERO } else { rounded }) +} + /// Check an entry's lines: two or more, every amount positive and within /// line range, debits equal to credits. Accounts and currencies are the /// caller's to check; this is the arithmetic. diff --git a/crates/ledger-core/src/tax.rs b/crates/ledger-core/src/tax.rs index d94bdf7d..a6d6ac91 100644 --- a/crates/ledger-core/src/tax.rs +++ b/crates/ledger-core/src/tax.rs @@ -530,11 +530,19 @@ fn sum(lines: &[TaxSummaryLine], f: fn(&TaxSummaryLine) -> Decimal) -> Decimal { lines.iter().map(f).sum() } +/// A category's line while it is being built, with the exact `(book, +/// percent)` shares the kernel adds before its one rounding. +struct CategoryBuild { + line: TaxSummaryLine, + shares: Vec<(Decimal, Decimal)>, +} + /// Build the tax summary for `[start, end]`, closing entries excluded (like /// the P&L). Each category's deductible amount is the exact sum of its /// accounts' shares (book × deductible percent ÷ 100), rounded once to /// the cent, half away from zero (B-21: "round off only the total"); the -/// book amounts stay exact. +/// book amounts stay exact. The share arithmetic is +/// [`crate::kernel::deductible_amount`], so Kani proves the one rounding. pub fn tax_summary( ledger: &Ledger, start: NaiveDate, @@ -542,7 +550,9 @@ pub fn tax_summary( form: Option, ) -> Result { let pl = crate::reports::profit_and_loss_for_period(ledger, start, end, None)?; - let mut by_cat: BTreeMap<&'static str, TaxSummaryLine> = BTreeMap::new(); + // Each category's line and the exact shares the kernel adds before its + // one rounding. + let mut by_cat: BTreeMap<&'static str, CategoryBuild> = BTreeMap::new(); let mut uncategorized = Vec::new(); for line in pl.revenue.iter().chain(pl.expenses.iter()) { let account = ledger.chart().find_by_code(&line.code).ok_or_else(|| { @@ -567,37 +577,36 @@ pub fn tax_summary( let pct = account .deductible_percent .unwrap_or_else(|| Decimal::from(c.default_deductible_percent)); - // The account's exact share, unrounded: the category rounds once, - // after every account is summed (below). Checked, so a figure too - // large for exact arithmetic is refused, never a panic. let too_large = |what: &str| LedgerError::TooLargeToCompute(format!("the {} category's {what}", c.key)); - let share = book - .checked_mul(pct) - .and_then(|x| x.checked_div(Decimal::from(100))) - .ok_or_else(|| too_large("deductible amount"))?; - let entry = by_cat.entry(c.key).or_insert_with(|| TaxSummaryLine { - category: c.key.to_string(), - label: c.label.to_string(), - accounts: vec![], - book: Decimal::ZERO, - tax: Decimal::ZERO, - }); + let (entry, shares) = { + let build = by_cat.entry(c.key).or_insert_with(|| CategoryBuild { + line: TaxSummaryLine { + category: c.key.to_string(), + label: c.label.to_string(), + accounts: vec![], + book: Decimal::ZERO, + tax: Decimal::ZERO, + }, + shares: Vec::new(), + }); + (&mut build.line, &mut build.shares) + }; entry.accounts.push(name); entry.book = entry .book .checked_add(book) .ok_or_else(|| too_large("book amount"))?; - entry.tax = entry - .tax - .checked_add(share) - .ok_or_else(|| too_large("deductible amount"))?; + shares.push((book, pct)); } // Round each category's deductible amount once, on its exact total. - for line in by_cat.values_mut() { - line.tax = line - .tax - .round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointAwayFromZero); + for build in by_cat.values_mut() { + build.line.tax = crate::kernel::deductible_amount(&build.shares).ok_or_else(|| { + LedgerError::TooLargeToCompute(format!( + "the {} category's deductible amount", + build.line.category + )) + })?; } let mut out = TaxSummary { start, @@ -612,7 +621,8 @@ pub fn tax_summary( }; // Catalog order, so the summary reads like the return. for c in CATEGORIES { - if let Some(line) = by_cat.remove(c.key) { + if let Some(build) = by_cat.remove(c.key) { + let line = build.line; if on_form_4797(c.key) { out.form_4797.push(BookOnlyLine { category: line.category,