From a7b6ed03049cc11b64d5c17f338e200888a923f8 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 23:27:24 -0700 Subject: [PATCH] build(check): no Decimal arithmetic outside the kernel, held by the lint part (K-U11a) AGENTS.md's bar says money arithmetic lives in the kernel and nowhere else, because the proofs are about the kernel only and because a raw operator panics where rust_decimal's own methods round silently. Nothing checked it, and 210 places in ledger-core broke it. `just kernel-only` runs scripts/raw-decimal-arith.sh over the crates named in kernel_only_crates and fails on the first place found; the lint part of `just check` runs it. The list is ledger-core, now at zero, and the four outer crates that never had a place (ledger-cli, ledger-host, ledger-reader, ledger-vault). The other six join as K-U12 brings each to zero. docs/proofs/k-u11.md is the unit's account: what was measured, what each group of sites became, what exact arithmetic refused and why, and what the detector does not show (that a site calls the right kernel function; the tests and a reading of every long figure carry that). Co-Authored-By: Claude --- docs/proofs/k-u11.md | 153 +++++++++++++++++++++++++++++++++++++++++++ docs/testing.md | 1 + docs/verification.md | 24 +++++-- justfile | 18 +++++ 4 files changed, 191 insertions(+), 5 deletions(-) create mode 100644 docs/proofs/k-u11.md diff --git a/docs/proofs/k-u11.md b/docs/proofs/k-u11.md new file mode 100644 index 00000000..c976086c --- /dev/null +++ b/docs/proofs/k-u11.md @@ -0,0 +1,153 @@ +# K-U11: no Decimal arithmetic outside the kernel (ledger-core) + +Bar item 1 of `AGENTS.md` says money arithmetic lives in `kernel/` and +nowhere else. Until this unit nothing checked it, and it was not true. + +## What was measured + +`scripts/raw-decimal-arith.sh ` asks the compiler. It runs clippy +twice over the package's own source (tests and proof harnesses are not +compiled; `src/kernel/` is where arithmetic belongs), once flagging every +arithmetic operator and once with `Decimal` allowed, and prints the places +that drop out: those are the `Decimal` ones. It also prints every call to +one of rust_decimal's own arithmetic or rounding methods (`checked_add`, +`checked_mul`, `round_dp`, `rescale`, ...) and every `Iterator::sum` or +`product`. A call such as `a.checked_add(b)` on a `Decimal` is +rust_decimal's method even with the kernel's `Amount` in scope, since an +inherent method wins over a trait's; reading the source does not show +which one runs, and the compiler does. + +At 8ad55e82a it listed **210 places in ledger-core**. Two kinds of fault +sat behind them: + +- a raw operator (`+`, `-`, `*`, unary `-`) panics when the result does + not fit; +- rust_decimal's operators and its `checked_*` methods both return a + rounded answer when the exact one needs more than 96 bits, and say + nothing (K-U10, `docs/proofs/k-u10.md`). + +## What was done + +| Sites | Now | +|---|---| +| 199 | the kernel's `Amount` methods by their full path, `kernel::total` and `total_of` for hand-rolled sums, `kernel::normal_balance`, and `money.rs`'s helpers over the kernel: `neg`, `signed_amount`, `on_side` (a line's sign, said once), `add_in_range` and `sub_in_range` (sums of posted lines, exact by BS-entry-3 and BS-entry-4), `add_exact` and `sub_exact` (anything a caller can make too large: a `TooLargeToCompute`) | +| 2 | `Money::checked_add` and `checked_sub`: exact or `TooLargeToCompute` (K-U10a) | +| 3 | the frozen close rules (`periods::try_allocate`, `try_allocate_last_absorbs`) and `Ledger::member_close_split`: `Amount::checked_mul_rounded`, the product they have always computed, by name. Posted closes replay with the first two, so not a digit of them may move | +| 2 | the audit's check of a close (`audit::check_split`): the bound and the drift through `Amount`. A bound or a drift exact arithmetic cannot hold is raised as a finding, never passed | +| 4 | `kernel::rescale_exact`, new: see below | + +Two sites among the 199 were then moved again, on evidence (see "What +exact arithmetic refused"): the K-1 worksheet's running total adds and +subtracts through `Amount::checked_add_rounded` and `checked_sub_rounded`. + +The first 199 were rewritten by a script from the compiler's own line and +column for each site, so no site was copied by hand. The ones that needed +a decision are in that commit's message (a balance sheet that cannot add +liabilities and equity is not balanced; a template's shares, a party's +percents and a reconciliation's balances refuse where they panicked). + +No figure moves: every site computes what it computed. What changes is +the edge: a result past exact arithmetic is refused where it panicked or +was rounded. + +## What exact arithmetic refused + +The script ran before K-U10 landed, when `Amount::checked_add` on a +`Decimal` was rust_decimal's rounding sum. K-U10 made it exact or `None`, +and after the merge one test failed: +`tax_capital::tests::thirds_summed_are_the_cents_they_are`, with +`TooLargeToCompute("a member's tax-basis capital")`. + +The cause is not a wrong figure. A member's "exact" running total in the +K-1 worksheet (`tax_capital::RunningSplit`) is a sum of shares, each +`whole x weight / sum`, a quotient of 28 significant digits. Two thirds of +28 digits each do not add to a number 96 bits hold, so the exact sum +refuses every split by thirds. rust_decimal's sum rounded it at the last +digit, and INVARIANT 4 of that type was written for exactly that: the +total is snapped to ten places before a cent is taken from it. + +A sum of rounded quotients is a rounded figure by construction, as a +share's product is (K-U10, `checked_mul_rounded`). So the kernel names +that sum too: `Amount::checked_add_rounded` and `checked_sub_rounded`, +rust_decimal's own for `Decimal` and the plain operation for a machine +integer, called by `RunningSplit::split` and `unsplit` and by nothing +else. The bridge property +`the_rounding_sum_is_the_exact_one_wherever_that_exists` +(`tests/kernel_bridge/decimal_exact.rs`) checks, over `Decimal`'s whole +range: it is rust_decimal's figure to the digit and the scale, it is the +exact figure wherever exact arithmetic gives one, and where it rounds it +is within half a unit of the last place it keeps. + +Every other place that makes a figure of more than ten places outside the +kernel was then read for the same fault, since a test only catches the +ones it reaches: + +| Place | What happens to the long figure next | +|---|---| +| `form1099::vendor_part` (`share_of`) | rounded to the cent on the next line | +| `form1099::split_share` (`share_floor_with`) | floors and remainders stay inside the kernel (`apportion`) | +| `settings::parse_share` (a percent over 100) | summed by `kernel::total_of`; shares that sum to one never pass 10^28 at 28 places, so a valid set is never refused, and one that does not sum to one was refused before | +| `reports::contribution_margin_pct` (`percent_of`) | already rounded to one place by the kernel | +| `Ledger::member_close_split` (`checked_mul_rounded`) | read only by the audit, whose difference is raised as a finding when exact arithmetic cannot hold it | +| `tax_capital::RunningSplit` (`share_of`) | the case above | + +## `kernel::rescale_exact` + +Four places changed how many decimal places a figure is written with: +a contribution margin always prints one place ("100.0"), a schedule's +months print at the currency's places (the kernel returns 0.250 as it +came, the plan has always shown 0.25, and a posted month is compared as +text on replay), and `Money`'s step count prints the minor places. Each +called `Decimal::rescale`, which rounds half away from zero when asked for +fewer places than the value has. None of the four ever asked for that, +and a debug assertion said so; nothing stopped the next one. + +`rescale_exact(amount, places)` adds or drops trailing zeros and returns +`None` for anything else. It is the only place outside the kernel's own +rounding that writes a scale. + +It has no Kani harness and no Lean theorem, and is the sixteenth entry in +the traceability gate's exception list, for this reason: whole-number +money has no places, so there is nothing for an `i64` harness or a law +over the rationals to state. What carries it instead: + +| Bridge property (`tests/kernel_bridge/round.rs`) | Checks | +|---|---| +| `rescale_exact_never_changes_the_value` | over Decimal's whole range (96-bit mantissas, every scale and every target from 0 to 28), against whole-number arithmetic that shares no code with it: `None` exactly when the amount is no whole multiple of 10^-places; a result is the same number with the same sign, at `places` places or, where 96 bits cannot hold it that wide, as many as they can | +| `rescale_exact_at_the_edges` | the figures the four call sites print, a negative zero (it keeps its sign and takes the places), the refusals, and the largest mantissa | + +## The gate + +`just kernel-only` runs the detector over the crates named in the +justfile's `kernel_only_crates`, and the lint part of `just check` runs +it, so a new raw operator or rust_decimal method on a `Decimal` outside +the kernel fails the build. The list is ledger-core and the four outer +crates that were already at zero (ledger-cli, ledger-host, ledger-reader, +ledger-vault); the other six join it as K-U12 brings each to zero, and a +crate never leaves it. A waiver is an +`#[allow(clippy::arithmetic_side_effects)]` or +`#[allow(clippy::disallowed_methods)]` with a `reason`, and the detector +counts them on its last line so one cannot slip in unseen. There are none +in ledger-core. + +## What this does not show + +- That each site calls the *right* kernel function. The detector shows + that arithmetic goes through the kernel, not that a sum or product which + should round was not made exact (a refusal where there was a figure) or + the reverse. The engine's tests and the properties check the figures, + and they found one (above). Every multiplication and division outside + the kernel was read for this unit (eleven, listed by + `grep -n "Amount::checked_mul\|Amount::checked_div"`), and every place + a long figure is made (the table above). A sum of figures a caller + supplies with more than ten places each (settings, a template's shares) + is refused where exact arithmetic cannot hold it; that is K-U10's rule, + not a regression, and no such sum is rounded later. +- The K-1 worksheet's running split is still a prelude outside the kernel + (`plan/2026-11-09_TRIAGE.md`, P2.7): its rounding sum has a bridge + property, and the split built on it has no Kani harness or Lean theorem + yet. +- `Decimal::abs`, `normalize` and comparisons are not arithmetic and are + not flagged: none can round or overflow. +- Integer arithmetic on counts, indexes and step counts (`i128` steps in + `Steps`, day counts) is outside this detector. diff --git a/docs/testing.md b/docs/testing.md index 75db0e0e..277d16f9 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -28,6 +28,7 @@ promise. | Fuzzing | crash, hang, broken books (4); for `fuzz_store_replay` (validly chained journals with fuzz-chosen events): books that open must verify, and the viewer must accept exactly what the writer does | `fuzz/fuzz_targets/`, corpora in `fuzz/corpus/` | `just fuzz ` | 10 min each | weekly | | Miri | undefined behavior in our use of dependencies (4) | the core's unit, bridge, invariant tests (the exhaustive calendar walk aside) | `just miri` | ~4 min | on demand | | Golden | `tests/golden/fixture_company.json` (5) | `invariants.rs` | `just check` | <1s | every change | +| Kernel only | no `Decimal` arithmetic outside `src/kernel/`: no raw operator, none of rust_decimal's own arithmetic or rounding methods, no `Iterator::sum` (AGENTS.md, bar item 1; the proofs are about the kernel only) | `scripts/raw-decimal-arith.sh`, which asks clippy twice and compares; the crates held at zero are the justfile's `kernel_only_crates` (ledger-core, ledger-cli, ledger-host, ledger-reader, ledger-vault; the other six join as K-U12 brings each to zero) | `just kernel-only` (in `just check`, the lint part) | ~1 min warm, a few minutes cold (two clippy runs of the crate) | every change. A waiver is an `#[allow]` with a `reason`; the last line counts them, and ledger-core has none | | Dependencies | no crate in the lock file with a known vulnerability (RustSec) or yanked; none under a licence that does not fit MIT OR Apache-2.0; none from a source `deny.toml` does not name; none of our own unmaintained (4) | `deny.toml`, each exception with its reason and date | `just deny` (in `just check`, the lint part) | seconds, needs the network | every change, and weekly (`scheduled.yml`), since an advisory is published when it is, not when we push. First run, 2026-11-09: 23 advisories; closed by upgrades (quick-xml, rusqlite, rust_xlsxwriter, rmcp, rustls, tokio, zstd, pulldown-cmark) but two, lived with in `deny.toml` | | Notices | every crate the program links and every font it embeds, with the licence text each asks to travel with (1, the licence itself) | `THIRD-PARTY-NOTICES.txt`, written by cargo-about from `ledger-cli`'s manifest, by `scripts/notices-packaged.py` (the crates' own licence files, where cargo-about could only give a licence's standard text with a placeholder for the copyright line) and from the licence files beside the fonts | `just notices`; `just notices-check` (in `just check`, the lint part) | ~2 min (12 CPU-minutes: it reads every crate's files for licence text) | every change that touches a dependency or a font. `just notices` writes the file; `just notices-check` fails when a dependency changed and the file was not regenerated, and the fix is `just notices` and committing the result | | Benchmarks | a baseline (6) | `ledger-core/benches/books.rs`, `ledger-store/benches/store.rs` | `just bench` | ~2 min | none (no budget, by decision) | diff --git a/docs/verification.md b/docs/verification.md index 3c8feb66..2caf1fe5 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -1065,6 +1065,17 @@ kernel. What the proofs and their reviews found, beyond the tidying: never refused; they now prove both, from the rational alone. One refusal remains by design: a product that is not exact, rounded to a step of 27 or 28 places. `docs/proofs/k-u10.md` has the account. +- **No `Decimal` arithmetic outside the kernel, checked by the compiler + (K-U11).** Bar item 1 was a rule nothing enforced: 210 places in + ledger-core added, negated, multiplied or summed a `Decimal` outside + `kernel/`, by raw operators (which panic) or by rust_decimal's own + `checked_*` methods (which round silently). All go through the kernel + now and `just kernel-only`, in the lint part of `just check`, fails on + a new one. It found one more rounding figure to name: a running total + of 28-digit shares (`checked_add_rounded`), which exact addition + refused for every split by thirds. `kernel::rescale_exact` is the one + place a figure's written places change, and it refuses to round. + `docs/proofs/k-u11.md` has the account. - **The sweep changed no posted figure.** Every golden and existing test passed unchanged. `round_places` reproduces `round_dp_with_strategy` to the character except a negative-zero input (which no call site can @@ -1124,13 +1135,16 @@ Be precise about the claims: `checked_sub` and `checked_mul` for `Decimal` are exact or `None` (`tests/kernel_bridge/decimal_exact.rs`: `Some` exactly when the exact result is a `Decimal`), and a foreign amount at a rate is rounded once - from the exact product. Two operations round, each by name: + from the exact product. Three operations round, each by name: `checked_div` at 28 significant digits (K-U3's `finding_the_quotients_rounding_can_cross_a_step`, K-U5's `the_edges` - at `Decimal::MAX / 2`) and a share's `checked_mul_rounded`. Neither - edge is reachable by a posted line (the line cap is 10^15, and - schedules refuse totals of `EXACT_LIMIT` or more), so the laws hold at - the engine's inputs. Not proved by Kani: the 256-bit helpers, which + at `Decimal::MAX / 2`), a share's `checked_mul_rounded`, and a running + total of such shares, `checked_add_rounded` and `checked_sub_rounded` + (K-U11: the K-1 worksheet's running split, whose thirds of 28 digits + are no exact sum; `docs/proofs/k-u11.md`). Neither edge of the first + two is reachable by a posted line (the line cap is 10^15, and schedules + refuse totals of `EXACT_LIMIT` or more), so the laws hold at the + engine's inputs. Not proved by Kani: the 256-bit helpers, which rest on the bridge properties and unit tests against `num_bigint`. - **The FX overflow harness proves two concrete cases, not every overflow.** `fx_booked_refuses_overflow` proves `i64::MAX × 2` and diff --git a/justfile b/justfile index fafaf61d..3b01c422 100644 --- a/justfile +++ b/justfile @@ -37,6 +37,7 @@ check-shard shard: cargo clippy --workspace --all-targets -- -D warnings RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --quiet just server-only + just kernel-only just check-shards-agree just deny just notices-check @@ -58,6 +59,23 @@ check-shard shard: ;; esac +# The crates with no Decimal arithmetic outside the kernel. A crate joins +# this list when its count reaches zero (K-U12) and never leaves it. +kernel_only_crates := "ledger-core ledger-cli ledger-host ledger-reader ledger-vault" + +# Money arithmetic lives in the kernel and nowhere else (AGENTS.md, bar +# item 1). The compiler is asked (scripts/raw-decimal-arith.sh): a raw +# operator on a Decimal, one of rust_decimal's own arithmetic or rounding +# methods, or an Iterator::sum outside `src/kernel/` fails. Those panic or +# round where the kernel's operations are exact or refuse (K-U10), and the +# proofs are about the kernel only. +kernel-only: + #!/usr/bin/env bash + set -euo pipefail + for crate in {{kernel_only_crates}}; do + scripts/raw-decimal-arith.sh "$crate" + done + # What every dependency must be (deny.toml): free of known vulnerabilities # (the RustSec database, fetched now), not yanked, under a licence that # fits MIT OR Apache-2.0, and from crates.io or the bookspec repository.