merge: the tax summary's deductible share is kernel arithmetic with Kani and bridge proofs (branch t3/move-deductible-share-kernel, 9f5ff9d0; reviewed twice, just prove and the slow harness green)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-11-08 07:00:35 -07:00
commit 5630b9aff8
7 files changed
+501 -34

No files matched your search

+166 -1
View File
@@ -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>;
/// `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>;
/// `self - rhs`, or `None` when it cannot be represented exactly.
fn checked_sub(self, rhs: Self) -> Option<Self> {
@@ -126,6 +138,75 @@ 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<Self> {
if rhs == Self::ZERO {
return None;
}
// Exact integer arithmetic on the mantissas, never `self * 100`:
// that product overflows for a large representable quotient (a
// book of 10^25 - 1 at 100% is the case that found it). With
// self = a * 10^-sa and rhs = b * 10^-sb, the cents to find are
// round(a / b * 10^(sb - sa + 2)), half away from zero. Working
// on the mantissa (an i128) and scale also settles scale 28
// exactly: the digits a Decimal division by 100 would have to
// round away at that scale stay in the integer remainder below,
// so they still decide the half-cent tie.
let a = self.mantissa();
let b = rhs.mantissa();
if a == 0 {
return Some(Self::ZERO);
}
let negative = (a < 0) != (b < 0);
let a_mag = a.unsigned_abs();
let b_mag = b.unsigned_abs();
let exponent = i32::try_from(rhs.scale()).ok()? - i32::try_from(self.scale()).ok()? + 2;
let cents_mag: u128 = if exponent >= 0 {
let pow10 = 10u128.checked_pow(u32::try_from(exponent).ok()?)?;
let main = (a_mag / b_mag).checked_mul(pow10)?;
let mut remainder = a_mag % b_mag;
let mut fraction = 0u128;
for _ in 0..exponent {
remainder = remainder.checked_mul(10)?;
fraction = fraction.checked_mul(10)?.checked_add(remainder / b_mag)?;
remainder %= b_mag;
}
let round_up = remainder.checked_mul(2)? >= b_mag;
main.checked_add(fraction)?
.checked_add(u128::from(round_up))?
} else {
let pow10 = 10u128.checked_pow(u32::try_from(-exponent).ok()?)?;
let quotient = a_mag / b_mag;
let twice = (quotient % pow10).checked_mul(2)?;
// The fraction past the cents is
// (quotient % pow10)/pow10 + remainder/(b_mag * pow10),
// where remainder is a_mag % b_mag, in [0, 1). The second
// term is under 1/pow10, so the fraction reaches a half
// exactly when the first does: twice >= pow10 (a tie at
// equality, the remainder only pushing it further).
let round_up = twice >= pow10;
(quotient / pow10).checked_add(u128::from(round_up))?
};
if cents_mag == 0 {
// Never a negative zero: money never prints "-0.00".
return Some(Self::ZERO);
}
// The result in cents at scale 2; a trailing zero may let a
// quotient past that mantissa fit at scale 1 or 0. Anything else
// past Decimal's mantissa is genuinely unrepresentable.
let max_mag = Decimal::MAX.mantissa().unsigned_abs();
let mut mantissa_mag = cents_mag;
let mut scale = 2u32;
while mantissa_mag > max_mag {
if scale == 0 || !mantissa_mag.is_multiple_of(10) {
return None;
}
mantissa_mag /= 10;
scale -= 1;
}
let signed_mag = i128::try_from(mantissa_mag).ok()?;
let signed = if negative { -signed_mag } else { signed_mag };
Decimal::try_from_i128_with_scale(signed, scale).ok()
}
}
impl Amount for i32 {
@@ -153,6 +234,27 @@ impl Amount for i32 {
}
self.checked_div(rhs)
}
fn checked_div_round_cent(self, rhs: Self) -> Option<Self> {
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 +283,27 @@ impl Amount for i64 {
}
self.checked_div(rhs)
}
fn checked_div_round_cent(self, rhs: Self) -> Option<Self> {
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 +465,48 @@ pub fn line_amount<T: Amount>(quantity: T, unit_price: T) -> Option<T> {
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.
/// A percent is the account's deductible percentage, 0 to 100; an
/// override may carry decimals (33.33 is 33.33%, exactly).
///
/// ```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<T: Amount>(shares: &[(T, T)]) -> Option<T> {
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.
+81
View File
@@ -1983,6 +1983,87 @@ fn line_amount_is_exact() {
);
}
// ---------------------------------------------------------------------------
// Tax categories (B-32)
// ---------------------------------------------------------------------------
/// `n / 100` rounded half away from zero: the reference for the one
/// rounding `kernel::deductible_amount` makes.
fn round_cent(n: i64) -> Option<i64> {
let q = n.checked_div(100)?;
let r = n.checked_rem(100)?;
if r >= 50 {
q.checked_add(1)
} else if r <= -50 {
q.checked_sub(1)
} else {
Some(q)
}
}
/// `kernel::deductible_amount` (rules.md B-32, B-21; CHOICE, owner
/// 2026-11-07, D-67) over up to three accounts in exact range: the exact
/// sum of the shares (`book × percent ÷ 100`) rounded once to the nearest
/// cent, ties away from zero; never the sum of per-account roundings; and
/// never the opposite sign to its sum.
#[kani::proof]
#[kani::unwind(5)]
fn deductible_amount_rounds_once() {
const T: usize = 3;
let n: usize = kani::any();
kani::assume(n <= T);
let shares: [(i64, i64); T] = core::array::from_fn(|_| {
let book: i64 = kani::any();
kani::assume(book.unsigned_abs() <= (1 << 20));
let percent: i64 = kani::any();
kani::assume(percent >= 0 && percent <= 100);
(book, percent)
});
// The exact numerator, and what rounding each account alone would
// have given. Under these bounds three shares cannot leave `i64`.
let mut exact = 0i64;
let mut per_account = 0i64;
for &(book, percent) in &shares[..n] {
let term = book * percent;
exact += term;
per_account += round_cent(term).expect("an i64 quotient by 100 fits");
}
let want = round_cent(exact).expect("an i64 quotient by 100 fits");
let got = kernel::deductible_amount(&shares[..n]);
assert_eq!(got, Some(want));
let err = i128::from(exact) - i128::from(want) * 100;
assert!(err.abs() <= 50, "within half a cent");
if exact >= 0 {
assert!(want >= 0, "the sum's sign, not its opposite");
} else {
assert!(want <= 0, "the sum's sign, not its opposite");
}
kani::cover!(n == T && exact % 100 == 50, "a tie at half a cent");
kani::cover!(exact % 100 == -50, "a negative tie at half a cent");
kani::cover!(exact < 0, "a negative numerator (a refund)");
kani::cover!(
per_account != want,
"rounding the category once differs from rounding each share"
);
}
/// `kernel::deductible_amount` refuses an overflow instead of wrapping: a
/// share too large for `i64`, and a sum of shares too large, both `None`.
#[kani::proof]
fn deductible_amount_refuses_overflow() {
// A product past `i64`: 100 percent of a book above i64::MAX / 100.
let book: i64 = kani::any();
kani::assume(book > i64::MAX / 100);
assert!(kernel::deductible_amount(&[(book, 100i64)]).is_none());
kani::cover!(book == i64::MAX, "the largest share");
// Two shares whose sum overflows, each product in range.
let book: i64 = kani::any();
kani::assume(book > i64::MAX / 2);
assert!(kernel::deductible_amount(&[(book, 1i64), (book, 1i64)]).is_none());
kani::cover!(book == i64::MAX, "a sum of shares too large");
}
// ---------------------------------------------------------------------------
// The checker itself
// ---------------------------------------------------------------------------
+35 -25
View File
@@ -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<TaxForm>,
) -> Result<TaxSummary, LedgerError> {
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,
+147
View File
@@ -554,4 +554,151 @@ proptest! {
let wide = kernel::line_amount(dec(quantity), dec(unit_price));
prop_assert_eq!(narrow.map(|n| Decimal::new(n, 4)), wide);
}
/// The tax summary's one rounding (rules.md B-32, B-21):
/// `kernel::deductible_amount` at i64 cents (what Kani
/// `deductible_amount_rounds_once` proved) and at Decimal dollars
/// agree on the same accounts, and the Decimal result keeps the laws:
/// within half a cent of the exact sum, never the opposite sign, never
/// a negative zero.
#[test]
fn deductible_amount_agrees(
shares in prop::collection::vec((arb_cents(), 0u32..=100), 0..5),
) {
let i: Vec<(i64, i64)> = shares
.iter()
.map(|&(book, percent)| (book, i64::from(percent)))
.collect();
let d: Vec<(Decimal, Decimal)> = shares
.iter()
.map(|&(book, percent)| (dec(book), Decimal::from(percent)))
.collect();
let narrow = kernel::deductible_amount(&i);
let wide = kernel::deductible_amount(&d);
prop_assert_eq!(narrow.map(dec), wide);
let exact_cents: i64 = shares
.iter()
.map(|&(book, percent)| book * i64::from(percent))
.sum();
// The exact share in dollars: book cents x percent, over 10,000.
let exact = Decimal::new(exact_cents, 4);
if let Some(a) = wide {
let half_cent = Decimal::new(5, 3);
prop_assert!((a - exact).abs() <= half_cent);
prop_assert!(!(a > Decimal::ZERO && exact < Decimal::ZERO));
prop_assert!(!(a < Decimal::ZERO && exact > Decimal::ZERO));
prop_assert!(!(a.is_zero() && a.is_sign_negative()));
}
}
/// The Decimal path with decimal percents and sub-cent books, which
/// `deductible_amount_agrees` (2-decimal books, integer percents)
/// never reaches: books at 0 to 6 decimal places (FX precision
/// included), percents in hundredths 0.00 to 100.00 and, half the
/// shares, at 4 decimal places, several shares per category. The
/// reference shares no code with the kernel: each share's product
/// is an exact i128 mantissa over a power of ten, the products are
/// summed over a common power of ten, and the one rounding to
/// cents is integer division, half away from zero.
#[test]
fn deductible_amount_matches_exact_reference_on_decimal_shares(
shares in prop::collection::vec(
(
-2_000_000i64..=2_000_000,
0u32..=6,
0i64..=10_000,
0i64..=1_000_000,
any::<bool>(),
),
0..5,
),
) {
let mut decimals: Vec<(Decimal, Decimal)> = Vec::new();
let mut products: Vec<(i128, u32)> = Vec::new();
for &(book_mant, book_scale, pct_hundredths, pct_four, use_four) in &shares {
let (pct_mant, pct_scale) = if use_four {
(pct_four, 4)
} else {
(pct_hundredths, 2)
};
let book =
Decimal::try_from_i128_with_scale(i128::from(book_mant), book_scale).unwrap();
let percent =
Decimal::try_from_i128_with_scale(i128::from(pct_mant), pct_scale).unwrap();
decimals.push((book, percent));
products.push((
i128::from(book_mant) * i128::from(pct_mant),
book_scale + pct_scale,
));
}
// The exact sum S = total / 10^max_scale / 100, so the cents
// are total / 10^max_scale rounded half away from zero.
let max_scale = products.iter().map(|&(_, s)| s).max().unwrap_or(0);
let mut total: i128 = 0;
for &(mant, scale) in &products {
total += mant * 10i128.pow(max_scale - scale);
}
let denom = 10u128.pow(max_scale);
let mag = total.unsigned_abs();
let mut cents_mag = mag / denom;
if (mag % denom) * 2 >= denom {
cents_mag += 1;
}
let cents = if total < 0 {
-i128::try_from(cents_mag).unwrap()
} else {
i128::try_from(cents_mag).unwrap()
};
let want = if cents_mag == 0 {
Decimal::ZERO
} else {
Decimal::try_from_i128_with_scale(cents, 2).unwrap()
};
let got = kernel::deductible_amount(&decimals);
prop_assert_eq!(got, Some(want));
if let Some(g) = got {
prop_assert!(!(g.is_zero() && g.is_sign_negative()));
}
}
}
fn parse(s: &str) -> Decimal {
s.parse().unwrap()
}
/// The review's table for the Decimal path, one share per category,
/// each expected value figured from the exact share by hand.
#[test]
fn deductible_amount_decimal_table() {
let cases: &[(&str, &str, &str)] = &[
("0.01", "50", "0.01"),
("1.05", "33.33", "0.35"),
("333.33", "50", "166.67"),
("-1.005", "100", "-1.01"),
("1.2345", "33.33", "0.41"),
("0.005", "100", "0.01"),
("-0.004", "100", "0"),
("999.9999", "99.99", "999.90"),
("123456789.1234567890", "33.333333", "41152262.63"),
(
"9999999999999999999999999",
"100",
"9999999999999999999999999.00",
),
];
for &(book, percent, want) in cases {
let got = kernel::deductible_amount(&[(parse(book), parse(percent))]);
assert_eq!(got, Some(parse(want)), "{book} at {percent}%");
}
// A rounded-to-zero result is zero, never a negative zero.
let zero = kernel::deductible_amount(&[(parse("-0.004"), parse("100"))]).unwrap();
assert!(zero.is_zero() && !zero.is_sign_negative(), "{zero}");
}
/// A quotient past what Decimal can hold at any scale from 2 down is
/// refused, never wrapped: twice Decimal::MAX, in cents, fits no
/// mantissa even stripped of its trailing zeros at scale 0.
#[test]
fn deductible_amount_decimal_unrepresentable_is_none() {
assert_eq!(Decimal::MAX.checked_div_round_cent(parse("0.5")), None);
}
+7 -3
View File
@@ -2248,7 +2248,8 @@ included, and an account's header flag never changes).
summary is the exact sum of each of its accounts' shares (book ×
deductible percent ÷ 100), rounded once to the cent, half away from
zero, following B-21's "round off only the total"; the books stay
exact (R-2).
exact (R-2). The arithmetic is `kernel::deductible_amount`, so Kani
proves the one rounding and the bridge carries it to `Decimal`.
- Every account a tool can require has a category that fits it on every
return: the gain or loss account of a disposal (`form_4797_gain_loss`,
Form 4797), tax-exempt income (`tax_exempt_income`, Schedule K), and
@@ -2259,7 +2260,8 @@ included, and an account's header flag never changes).
and in no total, on every return.
**Enforced:** `tax::needs_category`, `account_needs_category`,
`uncategorized_accounts`, `CATEGORIES`; `Ledger::check_tax_category_required`,
`uncategorized_accounts`, `CATEGORIES`; `kernel::deductible_amount`
(`tax::tax_summary`'s one rounding); `Ledger::check_tax_category_required`,
`check_tax_category_kept` (commands only, never `set_account_tax`, which
replay calls); `settings::TaxCategoryPolicy`, `Settings::require_tax_category`;
`Store::add_account_with_tax`, `add_account`, `set_account_tax`
@@ -2268,7 +2270,9 @@ their first `settings.set` naming the key, B-27); `ledger-mcp` `books.add_accoun
`books.import_chart_csv`, `books.digest`; `ledger-gui` Needs attention
(Info under warn, Todo under refuse). **Checked:** `ledger-core`
`tests/tax.rs` (the rounding: `a_category_rounds_its_deductible_amount_once_not_per_account`,
`a_category_rounds_once_across_different_percents`); `ledger-store` `tests/store.rs`
`a_category_rounds_once_across_different_percents`); Kani
`deductible_amount_rounds_once`, `deductible_amount_refuses_overflow`;
bridge `deductible_amount_agrees`; `ledger-store` `tests/store.rs`
(`prop_tax_policy_refuses_exactly`, `a_journaled_clear_replays_under_refuse`);
`ledger-cli` `tests/spec_tax_policy.rs`; `ledger-gui` `tests/view_model.rs`
(`needs_attention_flags_every_uncategorized_pl_account_defect_8`);
+64 -4
View File
@@ -22,8 +22,9 @@ lives in one place, `crates/ledger-core/src/kernel.rs`. Its functions
are small, pure, and generic over an `Amount` trait with *checked*
operations. The engine calls them on `Decimal`: `JournalEntry::validate`,
`movements`, `reverse_entry`, `account_balance`, `account_movement`,
period closing, `periods::allocate`, and the trial balance. There is no
second copy of the arithmetic for proofs to drift from.
period closing, `periods::allocate`, the trial balance, and the tax
summary's deductible amount. There is no second copy of the arithmetic for
proofs to drift from.
Kani compiles the same functions at `i64` (exact integer money in the
smallest unit; the four proration charge harnesses at `i32`) and
@@ -630,6 +631,63 @@ new command, so a new Lean step, and no kernel function.
a period with an open draft can't close, discarded it can, and
every balance and id is as it was).
### A tax category's deductible amount (B-32, D-67)
39. **A category's deductible amount is its accounts' exact shares added
and rounded once**, to the cent, half away from zero: round(Σ bookᵢ ×
percentᵢ ÷ 100), never Σ round(bookᵢ × percentᵢ ÷ 100); within half a
cent of the exact sum, never the opposite sign, and None (never a
panic) when a product or the sum overflows. `tax::tax_summary` calls
it; the book amounts stay exact.
- Kani `deductible_amount_rounds_once` (up to three accounts, books to
2^20 cents, any percent 0 to 100; covers reach a half-cent tie, a
negative half-cent tie, a negative sum and a category where
per-account rounding differs) and
`deductible_amount_refuses_overflow` (a product past `i64`, and a
sum of two shares past it) · bridge `deductible_amount_agrees` (the
i64 cents result and the Decimal dollars result agree, and the
Decimal result is within half a cent of the exact sum) · tests
`a_category_rounds_its_deductible_amount_once_not_per_account`,
`a_category_rounds_once_across_different_percents`, and the golden
`golden_tax_summary_form_1065`.
- The Decimal half of the bridge is what carries the law to the
engine's money, and it now has its own exact reference:
`deductible_amount_matches_exact_reference_on_decimal_shares`
checks `deductible_amount` on `Decimal` against a reference that
shares no code with the kernel (each share's product as an exact
i128 mantissa over a power of ten, summed over a common power of
ten, rounded half away from zero by integer division), over books
at 0 to 6 decimal places and percents in hundredths 0.00 to 100.00
(half the shares at 4 decimal places), up to four shares per
category. That is the part `deductible_amount_agrees` cannot
reach: decimal percents such as 33.33, and books finer than a
cent. The unit table `deductible_amount_decimal_table` pins the
reviewed values (ties, sub-cent books, a 10-decimal book at a
6-decimal percent, and the 10^25 - 1 book at 100% below), and
`deductible_amount_decimal_unrepresentable_is_none` pins a
quotient no Decimal can hold.
- The Decimal `checked_div_round_cent` itself never forms the
`* 100` intermediate the first version did: that product
overflowed, and returned None, for a representable result (the
10^25 - 1 book at 100% above, which the code before the kernel
move returned). It now rounds from the two mantissas and scales
by exact i128 arithmetic, so scale 28 is settled by the integer
remainder rather than by a Decimal division that would have to
round its result to fit, and None is left for a product or sum
overflowing in `deductible_amount`, or a quotient Decimal cannot
hold at any scale from 2 down. Kani still proves the i64 shape of
the same function; the bridge properties above carry it to
Decimal, the exact-reference one over the decimal shapes Kani's
integer model does not have.
- No Lean model: this is arithmetic on a report figure, like
`discount_max` (law 33) and `unrecovered_cost` (law 32), not a
`Ledger` command or a law about posted entries. The model's `Books`
has no tax categories; adding them would model presentation (a
category is a label on an account, and the summary is read from the
P&L), not a change to the books, and the law it would restate is the
kernel function's own definition. Kani proves that function, and the
bridge carries it to `Decimal`.
## What the proofs found
The engine already had 190+ tests, property tests, mutation testing,
@@ -786,8 +844,8 @@ Lean carrying any weights.
```sh
mise install # once: Kani, Lean, and the rest, pinned in mise.toml
just prove # 51 Kani harnesses and Lean
just prove-slow # the other 9: the justfile's kani_slow
just prove # 53 Kani harnesses and Lean
just prove-slow # the other 10: the justfile's kani_slow
just prove-all # both
```
@@ -897,6 +955,8 @@ each harness's whole run, its compile of about 50 s included):
| `bounds_check_matches_definition` | 34 | prove | (not in the 2026-10-22 run; P4b S1, 2026-10-24) |
| `bounds_kept_is_the_definition_on_books_in_bounds` | 34 | prove | (as above) |
| `settle_is_exact` | 36 | prove | 1 |
| `deductible_amount_rounds_once` | 39 | prove-slow | 992 alone; 1,207 in the 2026-11-08 prove-slow |
| `deductible_amount_refuses_overflow` | 39 | prove | 0 |
| `kani_symbolic_copy_canary` | (the checker: "Trusting the checker") | prove | 3 |
+1 -1
View File
@@ -65,7 +65,7 @@ sweep-test-tmp:
# 100 minutes of CPU, 2026-10-21) can't finish inside the 30-minute cap at
# four jobs, a CI runner's. Every other harness in src/proofs.rs runs in `prove`, a new one
# included; a name here that isn't a harness fails both (docs/verification.md).
kani_slow := "accounting_equation cumulative_close_never_drifts_a_unit_at_near_thirds cumulative_closing_entry_balances discount_max_is_bounded entry_flows_pure_are_movements entry_flows_sum_to_cash prorate_parts_sum_to_total sums_are_exact the_last_months_charge_is_within_half_a_cent"
kani_slow := "accounting_equation cumulative_close_never_drifts_a_unit_at_near_thirds cumulative_closing_entry_balances deductible_amount_rounds_once discount_max_is_bounded entry_flows_pure_are_movements entry_flows_sum_to_cash prorate_parts_sum_to_total sums_are_exact the_last_months_charge_is_within_half_a_cent"
# Formal proofs: Kani on the accounting kernel (all but kani_slow), Lean for books of any size (docs/verification.md)
prove: (_kani "fast")