merge: every report and book total goes through the kernel's checked sum (K-U4; branch t3/kernel-checked-totals, bc81b849; reviewed)
periods.rs conflicted with K-U2: the frozen replay rules delegate to K-U4's checked twins, whose rounding now goes through K-U2's round_places (so every rounding stays in the kernel); no figure changes. The K-U4 note gains the review's list of bounded raw sums left, and the caveat that the twin test checks delegation (the review's independent 20,000-case comparison found the twins identical). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
57d86b1920
25 files changed
+1184
-229
No files matched your search
@@ -0,0 +1,104 @@
|
||||
//! Totals past exact arithmetic are refused, never a panic (kernel sweep
|
||||
//! unit K-U4; rules.md B-21, B-28).
|
||||
//!
|
||||
//! A replayed journal line is accepted "of any size", so a restored
|
||||
//! figure can sit at `Decimal::MAX`; every sum the engine makes of such
|
||||
//! figures must return `TooLargeToCompute` (or skip a check), where a raw
|
||||
//! `+` / `.sum()` used to crash the process. Each test names the site it
|
||||
//! guards; before this unit each of them panicked.
|
||||
|
||||
use ledger_core::arap::{DocumentLine, document_total};
|
||||
use ledger_core::audit::check_articulation;
|
||||
use ledger_core::money::{add_exact, sub_exact, sum_exact, sum_exact_of, sum_exact_try};
|
||||
use ledger_core::periods::{
|
||||
allocate, allocate_last_absorbs, try_allocate, try_allocate_last_absorbs,
|
||||
};
|
||||
use ledger_core::{LedgerError, kernel};
|
||||
use rust_decimal::Decimal;
|
||||
|
||||
fn too_large<T: std::fmt::Debug>(r: Result<T, LedgerError>) {
|
||||
assert!(
|
||||
matches!(r, Err(LedgerError::TooLargeToCompute(_))),
|
||||
"expected TooLargeToCompute, got {r:?}"
|
||||
);
|
||||
}
|
||||
|
||||
fn dec(s: &str) -> Decimal {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_engine_sums_refuse_at_the_edge() {
|
||||
let max = Decimal::MAX;
|
||||
too_large(sum_exact([max, Decimal::ONE], "a column"));
|
||||
too_large(sum_exact_of([max, max], |x| x, "a column"));
|
||||
too_large(sum_exact_try([(max, -max)], |_| None, "a column"));
|
||||
too_large(add_exact(max, Decimal::ONE, "a balance"));
|
||||
too_large(sub_exact(-max, Decimal::ONE, "a balance"));
|
||||
// And the ordinary case is exact.
|
||||
assert_eq!(
|
||||
sum_exact([dec("1.10"), dec("2.20"), dec("-3.30")], "a column").unwrap(),
|
||||
Decimal::ZERO
|
||||
);
|
||||
assert_eq!(
|
||||
add_exact(dec("0.10"), dec("0.20"), "x").unwrap(),
|
||||
dec("0.30")
|
||||
);
|
||||
}
|
||||
|
||||
/// arap::document_total (store: create_invoice / create_bill).
|
||||
#[test]
|
||||
fn a_documents_lines_past_exact_arithmetic_are_refused() {
|
||||
let line = |amount| DocumentLine {
|
||||
description: "x".into(),
|
||||
amount,
|
||||
class_id: None,
|
||||
account: None,
|
||||
quantity: None,
|
||||
unit_price: None,
|
||||
};
|
||||
let big = [line(Decimal::MAX), line(Decimal::ONE)];
|
||||
too_large(document_total(&big, "the invoice"));
|
||||
let ok = [line(dec("10.00")), line(dec("5.25"))];
|
||||
assert_eq!(document_total(&ok, "the invoice").unwrap(), dec("15.25"));
|
||||
}
|
||||
|
||||
/// audit::check_articulation (current_earnings + closed was a raw +).
|
||||
#[test]
|
||||
fn the_articulation_check_skips_what_it_cannot_compute() {
|
||||
assert!(check_articulation(Decimal::MAX, Decimal::MAX, Decimal::MAX).is_none());
|
||||
// An ordinary mismatch is still reported, and a match is not.
|
||||
assert!(check_articulation(dec("10"), dec("4"), dec("5")).is_some());
|
||||
assert!(check_articulation(dec("10"), dec("4"), dec("6")).is_none());
|
||||
}
|
||||
|
||||
/// periods::allocate / allocate_last_absorbs (amount * share was raw: a
|
||||
/// replayed close with a huge journaled amount). The frozen rules'
|
||||
/// results do not move; only the overflow is an error.
|
||||
#[test]
|
||||
fn the_frozen_close_splits_refuse_instead_of_panicking() {
|
||||
let two = Decimal::from(2);
|
||||
too_large(try_allocate(Decimal::MAX, &[two]));
|
||||
too_large(try_allocate_last_absorbs(Decimal::MAX, &[two]));
|
||||
too_large(try_allocate(-Decimal::MAX, &[two]));
|
||||
|
||||
// The same split as the infallible rule for ordinary inputs.
|
||||
for amount in ["100.00", "0.07", "-33.33", "0.01", "1234567.89"] {
|
||||
let shares = [dec("0.5"), dec("0.3"), dec("0.2")];
|
||||
let a = dec(amount);
|
||||
assert_eq!(try_allocate(a, &shares).unwrap(), allocate(a, &shares));
|
||||
assert_eq!(
|
||||
try_allocate_last_absorbs(a, &shares).unwrap(),
|
||||
allocate_last_absorbs(a, &shares)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The kernel total over the line cap's edge: ten of the largest allowed
|
||||
/// line sum exactly (no refusal where the cap says it must work).
|
||||
#[test]
|
||||
fn lines_at_the_cap_still_sum_exactly() {
|
||||
let cap = kernel::MAX_LINE_AMOUNT;
|
||||
let ten = kernel::total(std::iter::repeat_n(cap, 10)).unwrap();
|
||||
assert_eq!(ten, cap * Decimal::from(10));
|
||||
}
|
||||
@@ -1,4 +1,143 @@
|
||||
//! U4 bridge properties: exact totals (kernel sweep).
|
||||
//!
|
||||
//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here,
|
||||
//! beside `main.rs` and the other units.
|
||||
//! `kernel::total`, `total_of` and `total_try` on `i64` cents (what Kani
|
||||
//! proved, `src/proofs/total.rs`) against the same on `Decimal` (what the
|
||||
//! engine runs), on random lists, plus a table of the `Decimal` edges.
|
||||
|
||||
use super::{arb_cents, dec};
|
||||
use ledger_core::kernel::{self, Amount};
|
||||
use proptest::prelude::*;
|
||||
use rust_decimal::Decimal;
|
||||
|
||||
fn arb_run() -> impl Strategy<Value = Vec<i64>> {
|
||||
prop::collection::vec(arb_cents(), 0..9)
|
||||
}
|
||||
|
||||
fn to_dec(run: &[i64]) -> Vec<Decimal> {
|
||||
run.iter().map(|&c| dec(c)).collect()
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(2000))]
|
||||
|
||||
/// Both types total a run to the same cents, and to the plain sum.
|
||||
#[test]
|
||||
fn total_agrees(run in arb_run()) {
|
||||
let i = kernel::total(run.iter().copied());
|
||||
let d = kernel::total(to_dec(&run));
|
||||
prop_assert_eq!(i.map(dec), d);
|
||||
prop_assert_eq!(i, Some(run.iter().sum::<i64>()));
|
||||
}
|
||||
|
||||
/// A mapped total agrees: the map is applied before the sum, both types.
|
||||
#[test]
|
||||
fn total_of_agrees(run in arb_run()) {
|
||||
let i = kernel::total_of(run.iter().copied(), |c| c * 3);
|
||||
let d = kernel::total_of(to_dec(&run), |x| x * Decimal::from(3));
|
||||
prop_assert_eq!(i.map(dec), d);
|
||||
// total_of is the total of the mapped run.
|
||||
prop_assert_eq!(
|
||||
kernel::total_of(run.iter().copied(), |c| c * 3),
|
||||
kernel::total(run.iter().map(|&c| c * 3))
|
||||
);
|
||||
}
|
||||
|
||||
/// A fallible mapping agrees too: the difference of each pair.
|
||||
#[test]
|
||||
fn total_try_agrees(pairs in prop::collection::vec((arb_cents(), arb_cents()), 0..7)) {
|
||||
let i = kernel::total_try(pairs.iter().copied(), |(c, d)| c.checked_sub(d));
|
||||
let d = kernel::total_try(
|
||||
pairs.iter().map(|&(c, d)| (dec(c), dec(d))),
|
||||
|(c, d)| Amount::checked_sub(c, d),
|
||||
);
|
||||
prop_assert_eq!(i.map(dec), d);
|
||||
// And a failing mapping fails the whole total at both types.
|
||||
prop_assert_eq!(
|
||||
kernel::total_try(pairs.iter().copied(), |_| None::<i64>).is_none(),
|
||||
!pairs.is_empty()
|
||||
);
|
||||
prop_assert_eq!(
|
||||
kernel::total_try(pairs.iter().map(|&(c, _)| dec(c)), |_| None::<Decimal>).is_none(),
|
||||
!pairs.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
/// Appending runs adds their totals (no overflow at cents), at both types.
|
||||
#[test]
|
||||
fn total_append_agrees(a in arb_run(), b in arb_run()) {
|
||||
let both: Vec<i64> = a.iter().chain(&b).copied().collect();
|
||||
let (ta, tb) = (kernel::total(to_dec(&a)).unwrap(), kernel::total(to_dec(&b)).unwrap());
|
||||
prop_assert_eq!(kernel::total(to_dec(&both)), Amount::checked_add(ta, tb));
|
||||
let (ia, ib) = (kernel::total(a.iter().copied()).unwrap(), kernel::total(b.iter().copied()).unwrap());
|
||||
prop_assert_eq!(kernel::total(both.iter().copied()), ia.checked_add(ib));
|
||||
}
|
||||
}
|
||||
|
||||
/// The `Decimal` edges: what is representable is summed exactly, and what is
|
||||
/// not is `None`, never a panic and never a rounded figure.
|
||||
#[test]
|
||||
fn decimal_edge_table() {
|
||||
let max = Decimal::MAX;
|
||||
let min = Decimal::MIN;
|
||||
let one = Decimal::ONE;
|
||||
|
||||
// The empty total, and a single figure at either edge.
|
||||
assert_eq!(kernel::total(Vec::<Decimal>::new()), Some(Decimal::ZERO));
|
||||
assert_eq!(kernel::total([max]), Some(max));
|
||||
assert_eq!(kernel::total([min]), Some(min));
|
||||
|
||||
// One unit past either edge is refused.
|
||||
assert_eq!(kernel::total([max, one]), None);
|
||||
assert_eq!(kernel::total([min, -one]), None);
|
||||
assert_eq!(kernel::total([max, max]), None);
|
||||
assert_eq!(kernel::total([min, min]), None);
|
||||
|
||||
// Opposite edges cancel exactly.
|
||||
assert_eq!(kernel::total([max, min]), Some(Decimal::ZERO));
|
||||
assert_eq!(kernel::total([max, -max]), Some(Decimal::ZERO));
|
||||
// Mixed signs that cancel exactly, in the middle of the range.
|
||||
let run = [dec(1_00), dec(-1_00), dec(3_33), dec(-3_33), Decimal::ZERO];
|
||||
assert_eq!(kernel::total(run), Some(Decimal::ZERO));
|
||||
|
||||
// Each step must be exact, so the edge is order dependent by design:
|
||||
// the same three figures, one order representable, the other not.
|
||||
assert_eq!(kernel::total([max, -one, one]), Some(max));
|
||||
assert_eq!(kernel::total([max, one, -one]), None);
|
||||
assert_eq!(kernel::total([one, max, -one]), None);
|
||||
|
||||
// total_of and total_try see the same edges.
|
||||
assert_eq!(kernel::total_of([max, one], |x| x), None);
|
||||
assert_eq!(
|
||||
kernel::total_of([1, 2, 3], Decimal::from),
|
||||
Some(Decimal::from(6))
|
||||
);
|
||||
assert_eq!(
|
||||
kernel::total_try([(max, min)], |(a, b)| Amount::checked_sub(a, b)),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
kernel::total_try([(max, max), (min, min)], |(a, b)| Amount::checked_sub(a, b)),
|
||||
Some(Decimal::ZERO)
|
||||
);
|
||||
}
|
||||
|
||||
/// FINDING (K-U4), pinned as a canary: `rust_decimal` rounds sub-unit dust
|
||||
/// away when a sum lands on `Decimal::MAX`, so `Amount::checked_add` for
|
||||
/// `Decimal` is not exact at the very edge (`MAX + 0.4 = MAX`, but `MAX +
|
||||
/// 0.5` is `None`). The kernel's "exact or `None`" contract (and `total`'s
|
||||
/// invariant 2) therefore holds for `Decimal` everywhere except figures
|
||||
/// within one unit of `Decimal::MAX` (~7.9 x 10^28, 10^13 times a journal
|
||||
/// line's cap). The fix belongs in `impl Amount for Decimal`
|
||||
/// (`kernel/entries.rs`), not in `total`; when it lands this test fails
|
||||
/// and is flipped to expect `None`. See docs/proofs/k-u4.md.
|
||||
#[test]
|
||||
fn finding_decimal_add_rounds_dust_at_the_edge() {
|
||||
let max = Decimal::MAX;
|
||||
let dust = Decimal::new(4, 1);
|
||||
assert_eq!(
|
||||
kernel::total([max, dust]),
|
||||
Some(max),
|
||||
"rust_decimal rounds the 0.4 away"
|
||||
);
|
||||
assert_eq!(kernel::total([max, Decimal::new(5, 1)]), None);
|
||||
}
|
||||
Reference in new issue
Block a user