merge: a coverage report and floor; rust_decimal checked against exact rationals (V-D; branch t3/decimal-exact-coverage-floor, e6fe6e29; reviewed, fix applied)

Cargo.toml: both the dev-dependencies for decimal_exact and the bookspec
comment's new path kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-11-08 17:11:27 -07:00
commit 4de03c1eaa
10 files changed
+750 -9

No files matched your search

+10
View File
@@ -28,6 +28,16 @@ jobs:
- uses: actions/checkout@v4
- uses: jdx/mise-action@v2
- run: just oracle
# Line, region and branch coverage of the core and the store, against the
# floor in docs/coverage-floor.md (docs/testing.md). Not a push gate: the
# instrumented suites are slow, so they run weekly, beside the proofs.
coverage:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: jdx/mise-action@v2
- run: just coverage
- run: just coverage-check
fuzz:
runs-on: ubuntu-24.04
strategy:
Generated
+2
View File
@@ -3977,6 +3977,8 @@ dependencies = [
"ledger-import",
"ledger-package",
"ledger-store",
"num-bigint",
"num-rational",
"proptest",
"rust_decimal",
"serde",
+5
View File
@@ -22,6 +22,11 @@ workspace = true
[dev-dependencies]
criterion = "0.8.2"
proptest = "1"
# `tests/decimal_exact.rs`: an independent exact reference (arbitrary
# precision rationals) for `Decimal`, the one numeric type the money paths
# trust. Test-only, like every dev-dependency here.
num-bigint = "0.4"
num-rational = "0.4"
# bookspec examples are TOML (tests/bookspec/), run on the engine's own
# store (a dev-dependency only: the store depends on this crate), each in
# a directory of its own.
+496
View File
@@ -0,0 +1,496 @@
//! `rust_decimal` checked against exact rational arithmetic.
//!
//! The engine's money paths trust `Decimal`: 96-bit integers scaled by a
//! power of ten. `docs/verification.md` ("What is and isn't proved") says
//! so, and Kani cannot explore `Decimal` arithmetic directly (one symbolic
//! add runs for more than ten minutes). This file checks the claim on the
//! operations the books rely on, against an independent exact reference:
//! [`num_rational::BigRational`], where every result is exact by
//! construction.
//!
//! The ranges are the books' own (`kernel::MAX_LINE_AMOUNT` and
//! `kernel::MAX_LINE_SCALE`): a line holds at most one quadrillion units
//! (1e15) with at most ten decimal places, a sum at most 1,000 such lines,
//! and an FX rate at most ten decimal places times such an amount. Every
//! property compares the `Decimal` answer to the rational one *exactly*;
//! the rounding operations compare to the correctly rounded rational.
//!
//! Exact only up to the sums the books reach. Near `Decimal::MAX` the add
//! rounds dust away (`MAX + 0.4` gives `Some(MAX)`, found by unit K-U4 and
//! pinned below; plan unit K-U10 makes the kernel refuse it), and a product
//! whose scale can't fit 28 places is rounded (the reason for decision
//! D-75's ten-place bound on foreign amounts and rates).
//!
//! This is a test of the dependency, not of the engine. When a property
//! fails, the finding is `rust_decimal`'s, and the failing case stays here
//! as a regression named for the defect.
use num_bigint::BigInt;
use num_rational::BigRational;
use proptest::prelude::*;
use rust_decimal::{Decimal, RoundingStrategy};
use std::str::FromStr;
// ------------------------------------------------------------- helpers
/// The repo's usual case count: `PROPTEST_CASES`, default 256.
fn cases() -> u32 {
std::env::var("PROPTEST_CASES")
.ok()
.and_then(|n| n.parse().ok())
.unwrap_or(256)
}
/// 10^n as a `BigInt`.
fn pow10(n: u32) -> BigInt {
BigInt::from(10u8).pow(n)
}
/// `d` as an exact rational: mantissa / 10^scale.
fn rat(d: Decimal) -> BigRational {
BigRational::new(BigInt::from(d.mantissa()), pow10(d.scale()))
}
/// The integer nearest `q` under `strategy`, where `q` may be fractional.
/// `BigInt` division truncates toward zero, so `q` is the truncation and
/// `rem` carries the sign of the dividend.
fn round_int(q: &BigRational, strategy: RoundingStrategy) -> BigInt {
let n = q.numer();
let d = q.denom();
let truncated = n / d;
let rem = n - &truncated * d;
let zero = BigInt::from(0);
let negative = rem < zero;
let magnitude = if negative { -&rem } else { rem.clone() };
let twice = magnitude * 2;
let away = if negative { -1 } else { 1 };
match strategy {
RoundingStrategy::ToZero => truncated,
RoundingStrategy::ToNegativeInfinity => {
if negative {
truncated - 1
} else {
truncated
}
}
RoundingStrategy::ToPositiveInfinity => {
if negative || rem == zero {
truncated
} else {
truncated + 1
}
}
RoundingStrategy::MidpointAwayFromZero => {
if twice >= *d {
truncated + away
} else {
truncated
}
}
RoundingStrategy::MidpointTowardZero => {
if twice > *d {
truncated + away
} else {
truncated
}
}
RoundingStrategy::MidpointNearestEven => {
if twice > *d || (twice == *d && truncated.bit(0)) {
truncated + away
} else {
truncated
}
}
// `Decimal` has no such strategy today; the match stays exhaustive.
_ => unreachable!("unknown round strategy"),
}
}
/// `r` rounded to `scale` decimal places under `strategy`, exactly.
fn round_rat(r: &BigRational, scale: u32, strategy: RoundingStrategy) -> BigRational {
let factor = pow10(scale);
let q = r * BigRational::from_integer(factor.clone());
BigRational::new(round_int(&q, strategy), factor)
}
/// True when `r` can be written as `m / 10^s` with a 96-bit `m` and
/// `s <= 28`: the set of values `Decimal` represents exactly.
fn representable(r: &BigRational) -> bool {
let max = BigInt::from(Decimal::MAX.mantissa());
(0..=Decimal::MAX_SCALE).any(|s| {
let scaled = r * BigRational::from_integer(pow10(s));
let numer = scaled.numer();
let magnitude = if *numer < BigInt::from(0) {
-numer.clone()
} else {
numer.clone()
};
scaled.is_integer() && magnitude <= max
})
}
/// A non-negative amount up to one quadrillion units with up to ten
/// decimal places (the worst case: mantissa to 10^25).
fn line_amount() -> impl Strategy<Value = Decimal> {
(0u32..=10).prop_flat_map(|scale| {
let cap = 10i128.pow(15 + scale);
(0i128..=cap, Just(scale))
.prop_map(move |(mantissa, _)| Decimal::from_i128_with_scale(mantissa, scale))
})
}
/// A signed line amount (the books use negative amounts for reversals and
/// policy limits, and `Decimal` must be exact either side of zero).
fn signed_line_amount() -> impl Strategy<Value = Decimal> {
(line_amount(), any::<bool>())
.prop_map(|(d, negative)| if negative { -d } else { d }.normalize())
}
/// A rate small enough that a full-range line amount times it still has a
/// mantissa below 2^96 - 1: at most 7,900 at ten places.
fn tiny_rate() -> impl Strategy<Value = Decimal> {
(0u32..=10).prop_flat_map(|scale| {
(0i128..=7_900, Just(scale))
.prop_map(move |(mantissa, _)| Decimal::from_i128_with_scale(mantissa, scale))
})
}
/// An FX rate with up to ten decimal places, no larger than 1,000: the
/// realistic band for one unit of a foreign currency in base units.
fn fx_rate() -> impl Strategy<Value = Decimal> {
(0u32..=10).prop_flat_map(|scale| {
let cap = 10i128.pow(3 + scale);
(0i128..=cap, Just(scale))
.prop_map(move |(mantissa, _)| Decimal::from_i128_with_scale(mantissa, scale))
})
}
/// A `Decimal` of at most `digits` significant integer digits at every
/// scale 0..=28 (for the parsing round trips).
fn any_scale_value() -> impl Strategy<Value = Decimal> {
(0u32..=Decimal::MAX_SCALE).prop_flat_map(|scale| {
let cap = 10i128.pow(15);
(0i128..=cap, Just(scale))
.prop_map(move |(mantissa, _)| Decimal::from_i128_with_scale(mantissa, scale))
})
}
// ---------------------------------------------------------- properties
proptest! {
#![proptest_config(ProptestConfig::with_cases(cases()))]
/// Addition is exact over the books' line range.
#[test]
fn prop_checked_add_is_exact(a in signed_line_amount(), b in signed_line_amount()) {
let sum = a.checked_add(b).expect("a line-range sum always fits");
prop_assert_eq!(rat(sum), rat(a) + rat(b));
}
/// Subtraction is exact over the books' line range.
#[test]
fn prop_checked_sub_is_exact(a in signed_line_amount(), b in signed_line_amount()) {
let difference = a.checked_sub(b).expect("a line-range difference always fits");
prop_assert_eq!(rat(difference), rat(a) - rat(b));
}
/// A sum of up to 1,000 line amounts equals the rational sum exactly.
/// The worst case (1,000 × 1e15 at ten places) needs a 29-digit
/// mantissa (10^28), inside `Decimal`'s 96 bits; this checks it.
#[test]
fn prop_sum_of_many_lines_is_exact(
amounts in proptest::collection::vec(line_amount(), 0..=1000)
) {
let mut total = Decimal::ZERO;
let mut expected = BigRational::from_integer(BigInt::from(0));
for a in &amounts {
total = total.checked_add(*a).expect("line-range sums stay exact");
expected += rat(*a);
}
prop_assert!(representable(&expected), "1,000 line-range amounts always fit");
prop_assert_eq!(rat(total), expected);
}
/// Multiplication (a quantity times a unit price, an FX amount times
/// its rate) is exact when the true product fits: here both mantissas
/// multiply to at most 10^28, below `Decimal`'s 2^96 - 1.
#[test]
fn prop_checked_mul_is_exact(
amount in (0i128..=10i128.pow(15)).prop_flat_map(|m| {
(0u32..=10).prop_map(move |s| Decimal::from_i128_with_scale(m, s))
}),
rate in fx_rate(),
) {
let product = amount.checked_mul(rate).expect("mantissas multiply below 2^96");
prop_assert_eq!(rat(product), rat(amount) * rat(rate));
}
/// Multiplication stays exact at the top of the line range: a full
/// quadrillion at ten places (a 26-digit mantissa) times a small rate
/// (at most 7,900 at ten places). The product's mantissa stays below
/// 2^96 - 1, so no rounding may happen.
#[test]
fn prop_checked_mul_at_the_line_range_is_exact(
amount in line_amount(),
rate in tiny_rate(),
) {
let product = amount.checked_mul(rate).expect("mantissas multiply below 2^96");
prop_assert_eq!(rat(product), rat(amount) * rat(rate));
prop_assert!(representable(&(rat(amount) * rat(rate))));
}
/// `round_dp_with_strategy` is the correctly rounded rational for
/// every strategy the engine uses, at every scale 0..=28.
#[test]
fn prop_round_dp_matches_correct_rounding(
amount in signed_line_amount(),
dp in 0u32..=Decimal::MAX_SCALE,
strategy in prop_oneof![
Just(RoundingStrategy::MidpointAwayFromZero),
Just(RoundingStrategy::MidpointNearestEven),
Just(RoundingStrategy::ToZero),
Just(RoundingStrategy::ToNegativeInfinity),
],
) {
let rounded = amount.round_dp_with_strategy(dp, strategy);
prop_assert_eq!(rat(rounded), round_rat(&rat(amount), dp, strategy));
}
/// `rescale` rounds with `MidpointAwayFromZero`, as its documentation
/// says, and never changes the value when scaling up.
#[test]
fn prop_rescale_matches_half_away_rounding(
amount in signed_line_amount(),
scale in 0u32..=Decimal::MAX_SCALE,
) {
let mut rescaled = amount;
rescaled.rescale(scale);
prop_assert_eq!(
rat(rescaled),
round_rat(&rat(amount), scale, RoundingStrategy::MidpointAwayFromZero)
);
}
/// `normalize` strips trailing zeros and changes no value.
#[test]
fn prop_normalize_preserves_value(amount in signed_line_amount()) {
let normalized = amount.normalize();
prop_assert_eq!(rat(normalized), rat(amount));
prop_assert_eq!(normalized.normalize(), normalized, "normalize is idempotent");
if !normalized.is_zero() && normalized.scale() > 0 {
prop_assert_ne!(normalized.mantissa() % 10, 0, "no trailing zero survives");
}
}
/// Ordering and equality across scales agree with the rationals: 1.0
/// equals 1.00, and `cmp` follows value, not representation.
#[test]
fn prop_comparison_matches_rationals(a in signed_line_amount(), b in signed_line_amount()) {
prop_assert_eq!(a.cmp(&b), rat(a).cmp(&rat(b)));
prop_assert_eq!(a == b, rat(a) == rat(b));
prop_assert_eq!(a.partial_cmp(&b), Some(rat(a).cmp(&rat(b))));
}
/// The same value written at any two scales compares equal: 1.0 is
/// 1.00, 1.000 and so on.
#[test]
fn prop_equal_across_scales(
mantissa in 0i128..=10i128.pow(15),
scale in 0u32..=Decimal::MAX_SCALE,
extra in 0u32..=12,
) {
let target = (scale + extra).min(Decimal::MAX_SCALE);
let extra = target - scale;
let a = Decimal::from_i128_with_scale(mantissa, scale);
let b = Decimal::from_i128_with_scale(mantissa * 10i128.pow(extra), target);
prop_assert_eq!(a, b);
prop_assert_eq!(a.cmp(&b), std::cmp::Ordering::Equal);
}
/// `from_str` and `to_string` round-trip at every scale 0..=28,
/// against a string built independently from the mantissa and scale.
#[test]
fn prop_from_str_to_string_round_trips(amount in any_scale_value()) {
let text = amount.to_string();
let parsed = Decimal::from_str(&text).expect("our own rendering parses");
prop_assert_eq!(parsed, amount);
prop_assert_eq!(parsed.scale(), amount.scale());
prop_assert_eq!(parsed.to_string(), text);
// Build the plain decimal rendering from the parts, without
// `to_string`, and parse that too: the same value, same digits.
let mantissa = amount.mantissa();
let scale = amount.scale();
let digits = mantissa.unsigned_abs().to_string();
let body = if scale == 0 {
digits
} else {
let scale = scale as usize;
let padded = if digits.len() <= scale {
format!("{}{}", "0".repeat(scale + 1 - digits.len()), digits)
} else {
digits
};
let split = padded.len() - scale;
format!("{}.{}", &padded[..split], &padded[split..])
};
let body = if mantissa.is_negative() { format!("-{body}") } else { body };
let parsed = Decimal::from_str(&body).expect("a plain decimal parses");
prop_assert_eq!(rat(parsed), rat(amount));
prop_assert_eq!(parsed.scale(), amount.scale());
}
}
// -------------------------------------------------------- edge cases
const MAX_MANTISSA: i128 = 79_228_162_514_264_337_593_543_950_335;
/// `Decimal::MAX`'s mantissa is 28 digits; a line's worst-case sum is 28
/// digits too, so the headroom is stated, not assumed.
#[test]
fn a_thousand_full_lines_fit_below_the_decimal_maximum() {
let line = Decimal::from_i128_with_scale(10i128.pow(25), 10);
assert_eq!(line, Decimal::from(1_000_000_000_000_000i64));
let total = line * Decimal::from(1000u32);
assert_eq!(total, Decimal::from(1_000_000_000_000_000_000i64));
assert!(total < Decimal::MAX);
assert_eq!(Decimal::from_i128_with_scale(MAX_MANTISSA, 0), Decimal::MAX);
}
#[test]
fn the_largest_mantissa_at_scale_zero_round_trips() {
let text = "79228162514264337593543950335";
let d = Decimal::from_str(text).unwrap();
assert_eq!(d, Decimal::MAX);
assert_eq!(d.scale(), 0);
assert_eq!(d.to_string(), text);
}
#[test]
fn scale_28_round_trips_at_both_ends() {
for (mantissa, text) in [
(1i128, "0.0000000000000000000000000001"),
(-1i128, "-0.0000000000000000000000000001"),
(MAX_MANTISSA, "7.9228162514264337593543950335"),
(-MAX_MANTISSA, "-7.9228162514264337593543950335"),
] {
let d = Decimal::from_i128_with_scale(mantissa, 28);
assert_eq!(d.to_string(), text);
let parsed = Decimal::from_str(text).unwrap();
assert_eq!(parsed, d);
assert_eq!(parsed.scale(), 28);
assert_eq!(parsed.to_string(), text);
}
}
#[test]
fn negative_ties_round_away_from_zero() {
for text in ["-0.5", "-1.5", "-2.5", "-0.125", "-0.135"] {
let d = Decimal::from_str(text).unwrap();
let expected = round_rat(&rat(d), 0, RoundingStrategy::MidpointAwayFromZero);
assert_eq!(
rat(d.round_dp_with_strategy(0, RoundingStrategy::MidpointAwayFromZero)),
expected,
"{text}"
);
let expected = round_rat(&rat(d), 2, RoundingStrategy::MidpointAwayFromZero);
assert_eq!(
rat(d.round_dp_with_strategy(2, RoundingStrategy::MidpointAwayFromZero)),
expected,
"{text}"
);
}
// 0.005 is a tie at two places, away from zero on both signs.
assert_eq!(
Decimal::from_str("0.005")
.unwrap()
.round_dp_with_strategy(2, RoundingStrategy::MidpointAwayFromZero),
Decimal::from_str("0.01").unwrap()
);
assert_eq!(
Decimal::from_str("-0.005")
.unwrap()
.round_dp_with_strategy(2, RoundingStrategy::MidpointAwayFromZero),
Decimal::from_str("-0.01").unwrap()
);
}
#[test]
fn one_point_zero_equals_one_point_zero_zero() {
let a = Decimal::from_str("1.0").unwrap();
let b = Decimal::from_str("1.00").unwrap();
assert_eq!(a, b);
assert_eq!(a.cmp(&b), std::cmp::Ordering::Equal);
assert_ne!(a.to_string(), b.to_string(), "the scales still differ");
}
#[test]
fn checked_add_and_sub_return_none_past_the_maximum() {
assert_eq!(Decimal::MAX.checked_add(Decimal::ONE), None);
assert_eq!(Decimal::MIN.checked_sub(Decimal::ONE), None);
assert_eq!(
Decimal::MAX.checked_add(-Decimal::ONE),
Some(Decimal::MAX - Decimal::ONE)
);
}
/// Inexact at the edge: within one unit of `Decimal::MAX`, `checked_add`
/// rounds the fraction away instead of refusing (K-U4's finding). Pinned
/// so the day `rust_decimal` or the kernel (unit K-U10) makes it exact,
/// this test says so.
#[test]
fn checked_add_rounds_dust_away_next_to_the_maximum() {
let dust = Decimal::new(4, 1);
assert_eq!(Decimal::MAX.checked_add(dust), Some(Decimal::MAX));
assert_eq!(Decimal::MAX.checked_add(Decimal::new(5, 1)), None);
}
#[test]
fn checked_mul_returns_none_when_the_integer_part_cannot_fit() {
assert_eq!(Decimal::MAX.checked_mul(Decimal::from(2u32)), None);
assert_eq!(Decimal::MIN.checked_mul(Decimal::from(2u32)), None);
}
/// When the *scale* cannot fit, `checked_mul` does not fail: it rounds the
/// product to 28 decimal places, ties to even (`ops::mul`'s reduction
/// path), and returns `Some`. 5e-28 × 0.5 is 2.5e-28, a tie between 2e-28
/// and 3e-28 at scale 28, and the even one wins.
#[test]
fn checked_mul_rounds_when_only_the_scale_does_not_fit() {
let a = Decimal::from_i128_with_scale(5, 28);
let half = Decimal::from_str("0.5").unwrap();
assert_eq!(
a.checked_mul(half),
Some(Decimal::from_i128_with_scale(2, 28))
);
// 15e-28 × 0.5 = 7.5e-28: a tie, and 8 is even.
let a = Decimal::from_i128_with_scale(15, 28);
assert_eq!(
a.checked_mul(half),
Some(Decimal::from_i128_with_scale(8, 28))
);
}
// ------------------------------------------------- engine reachability
/// The engine's FX path (`Ledger::add_line_fx`) multiplies a foreign
/// amount by a rate, and only bounds the *base* result afterwards. The
/// foreign amount and the rate are any positive `Decimal`, so a product
/// whose scale does not fit is reachable through the public API: that
/// product is rounded (the test above), not refused. Products whose
/// integer part does not fit do return `None`, which the engine maps to
/// `AmountOutOfRange`. This test states the reachability, not a claim
/// that the rounded case is wrong: the base amount is then rounded to the
/// currency's minor unit, far coarser than the lost places.
#[test]
fn the_fx_product_rounding_is_reachable_from_public_decimal_arguments() {
let foreign = Decimal::from_i128_with_scale(15, 28); // 1.5e-27
let rate = Decimal::from_str("0.5").unwrap();
assert_eq!(
foreign.checked_mul(rate),
Some(Decimal::from_i128_with_scale(8, 28)),
"a scale-reduced product, not None"
);
assert_eq!(Decimal::MAX.checked_mul(Decimal::MAX), None);
}
+75
View File
@@ -0,0 +1,75 @@
# Coverage floor
Line, region and branch coverage of the two crates every other crate is
built on, measured from their own test suites. `just coverage` writes the
HTML and a per-file table for each crate under `target/coverage/<crate>/`
(`summary.txt` is the table: regions, functions, lines and branches, with
missed counts and percentages); `just coverage-check` reads that report and
fails when a crate's **total line coverage** is more than 0.5 percentage
points below its recorded floor.
Why a floor, not a target: coverage is a tripwire for silently losing what
a test used to reach. It is not a measure of correctness — the property
tests, the GnuCash oracle, mutation testing and the proofs answer that. A
change that deletes, narrows or replaces a test must not also let the
report drift down unnoticed.
- Tool: `cargo-llvm-cov` 0.9.1, pinned in `mise.toml`. Branch coverage is
nightly-only (`-Zcoverage-options=branch`), so the run uses the pinned
`nightly-2026-10-01` and its `llvm-tools` component, also in
`mise.toml`.
- Measured: `ledger-core` and `ledger-store` library sources, each from
its own suite (`cargo llvm-cov -p <crate>`). Excluded:
`src/proofs.rs` (Kani-only, `cfg(kani)`, never in the test binary),
`tests/`, `benches/` and `examples/`, and the other workspace crates a
dev-dependency compiles instrumented (the core's tests use the store,
the store's use the core).
- The floor is the total line coverage recorded on the measurement date.
Regions and branches are recorded for context but not gated (branch
coverage on a nightly flag is noisier across compiler versions; line
coverage is the stable signal). 0.5 percentage points are tolerated for
measurement movement; more means a test stopped reaching what it used
to.
**Floor: `ledger-core` 90.01% lines, `ledger-store` 91.71% lines** (2026-11-08: the first measurement, from the full `just coverage` run; `ledger-core` 16,839 of 18,708 lines, `ledger-store` 14,255 of 15,543; 256-case properties everywhere, no special shard settings. The store measured 91.98% on an earlier run the same day; properties choose random cases, so a few tenths move between runs, which the 0.5 pp tolerance absorbs. The floor records the lower run.)
| Crate | Lines | Regions | Branches | Lines (covered / total) | Measured |
|---|---|---|---|---|---|
| `ledger-core` | 90.01% | 88.86% | 82.65% | 16,839 / 18,708 | 2026-11-08 |
| `ledger-store` | 91.71% | 85.27% | 80.73% | 14,255 / 15,543 | 2026-11-08 |
## First measurement: the fifteen files with the most uncovered lines
| File | Lines | Regions | Branches | Uncovered lines |
|---|---|---|---|---|
| `crates/ledger-core/src/ledger.rs` | 86.10% | 84.69% | 80.40% | 854 |
| `crates/ledger-store/src/store.rs` | 90.39% | 78.45% | 81.93% | 641 |
| `crates/ledger-store/src/root.rs` | 86.71% | 80.21% | 73.87% | 197 |
| `crates/ledger-core/src/conventions.rs` | 78.29% | 75.95% | 78.21% | 142 |
| `crates/ledger-core/src/evidence.rs` | 33.85% | 30.05% | 8.93% | 129 |
| `crates/ledger-core/src/settings.rs` | 91.05% | 87.70% | 81.25% | 117 |
| `crates/ledger-core/src/cashflow.rs` | 91.63% | 88.55% | 87.64% | 110 |
| `crates/ledger-core/src/audit.rs` | 80.50% | 78.33% | 61.36% | 93 |
| `crates/ledger-store/src/backup.rs` | 95.16% | 94.40% | 82.88% | 83 |
| `crates/ledger-core/src/arap.rs` | 87.97% | 87.67% | 91.46% | 77 |
| `crates/ledger-store/src/reconcilable.rs` | 0.00% | 0.00% | 0.00% | 76 |
| `crates/ledger-core/src/parties.rs` | 88.37% | 86.30% | 81.40% | 67 |
| `crates/ledger-store/src/meta.rs` | 91.32% | 84.56% | 83.33% | 66 |
| `crates/ledger-store/src/describe.rs` | 81.99% | 79.89% | 76.92% | 49 |
| `crates/ledger-core/src/kernel.rs` | 95.95% | 91.34% | 88.56% | 46 |
`reconcilable.rs` is the one whole-module hole: the store exposes it,
but the server and the viewer are its readers, so the store's own suite
never calls it. `ledger.rs`'s uncovered half is mostly the replay steps
of document and payroll commands (`mark_sent_steps`, `settle_steps`,
`run_payroll_steps`, ...), which the store's replay tests exercise; the
core's own suite does not. These are findings, not tasks for this
measurement.
The doors this closes, and the ones it does not: it catches a suite that
loses its reach (a deleted test, an ignored module, a helper no longer
called) and a source file added without tests, at the granularity of total
lines per crate. It does not try to floor each file: a refactor that moves
code between files would then fail for no accounting reason. Per-file
numbers are in `target/coverage/<crate>/summary.txt`; the fifteen files
with the most uncovered lines on the first measurement are the table above.
+3 -1
View File
@@ -28,6 +28,7 @@ promise.
| 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 |
| Benchmarks | a baseline (6) | `ledger-core/benches/books.rs`, `ledger-store/benches/store.rs` | `just bench` | ~2 min | none (no budget, by decision) |
| Coverage | the code lines, regions and branches the suites execute (6) | `ledger-core` and `ledger-store` library sources (`src/proofs.rs` is Kani-only and excluded, as are test and bench files) | `just coverage` (HTML and a per-file table in `target/coverage/`), `just coverage-check` (docs/coverage-floor.md's floor, 0.5 pp tolerance) | ~1–3 h (nightly branch coverage) | weekly (`scheduled.yml`) |
| Mutation | can the tests fail? | `ledger-core` (2026-10-13: 1,011 caught + 13 timeouts of 1,024 viable, 0 missed) | `just mutants` | ~3 h | weekly |
| Mutation (store) | can the tests fail? | `ledger-store` (2026-10-13: 357 caught + 1 timeout of 365 viable, from 82%; three of its seven survivors then killed; four equivalent left: `sort_value`'s two arms, `OpenFlags` `|` vs `^`, the long form of a sweepless close) | `just mutants-store` | ~12 min | weekly |
| Mutation (import) | can the tests fail? | `ledger-import` (2026-10-13: from 91 of 171 (53%) to 208 of 239 viable on the full run; the 31 survivors (XLSX layout, borders, alignment, exact-text grouping, IIF transliteration, tax-summary optional sections, day-equals-month dates) then killed by targeted tests, re-run clean but one: a blank amount cell written unbordered on an unruled row, invisible, so equivalent; 2026-10-19, the first scheduled run in CI: 375 tested, 327 caught, 42 unviable, 6 missed (the tax-basis rule marks, a heading's alignment, the totals row's blank cells, and that blank cell, after all: a ruled row writes it, an unruled one writes none), all six then caught by `rule_marks_match_their_notes`, `asset_register_xlsx_headings_and_totals_rule` and `xlsx_missing_amounts_are_cells_only_on_ruled_rows`, each checked against its mutant by hand) | `just mutants-import` | ~2 h | weekly |
@@ -38,7 +39,8 @@ promise.
CI: `.github/workflows/check.yml` runs `just check` on every push;
`two-user.yml` the self-host deployment's two-account check (P9a);
`scheduled.yml` runs the proofs, the oracle and the fuzz targets weekly. Mutation ran there in shards until 2026-10-29 (`just mutants-mcp 3/16` runs the fourth of sixteen; GitHub stops a job at six hours), and is now local only (D-59). Test timeouts are three times each run's own baseline, never under the recipe's floor, so a slower runner doesn't report false timeouts. The viewer has no mutation job. Development mutation runs are paused until the P12 max-testing pass (D-33, 2026-10-20): each unit records its targets in a **For P12** paragraph instead. Mutation testing is a local run, not a CI job (the owner, 2026-10-29, D-59): the weekly shards were removed from `scheduled.yml`, and the "weekly" in the mutation rows above is history (the 2026-10-26 run: real survivors and timeouts in every crate, the debt P12 clears).
`scheduled.yml` runs the proofs, the oracle, the coverage report and floor,
and the fuzz targets weekly. Mutation ran there in shards until 2026-10-29 (`just mutants-mcp 3/16` runs the fourth of sixteen; GitHub stops a job at six hours), and is now local only (D-59). Test timeouts are three times each run's own baseline, never under the recipe's floor, so a slower runner doesn't report false timeouts. The viewer has no mutation job. Development mutation runs are paused until the P12 max-testing pass (D-33, 2026-10-20): each unit records its targets in a **For P12** paragraph instead. Mutation testing is a local run, not a CI job (the owner, 2026-10-29, D-59): the weekly shards were removed from `scheduled.yml`, and the "weekly" in the mutation rows above is history (the 2026-10-26 run: real survivors and timeouts in every crate, the debt P12 clears).
Seeds and failure databases: proptest's `*.proptest-regressions` files
are checked in and replay on every run. The GnuCash oracle's books come
+25 -6
View File
@@ -804,12 +804,31 @@ Be precise about the claims:
written out and proved equal to the model's charge), and the bridge
property tests tie the `Decimal` (and `i128`) instantiation to the
`i64` (and `i32`) one Kani checked.
- **`Decimal` itself is trusted.** `rust_decimal` is exact for these
sizes: 96-bit integers scaled by a power of ten. With lines capped at
one quadrillion and ten decimal places, every sum is exact while the
total of all amounts stays below 7.9 × 10^18. Kani can't explore
`Decimal` arithmetic directly: a single symbolic add runs for more than
ten minutes.
- **`Decimal` itself is trusted, and now probed against exact
rationals.** `rust_decimal` is exact for these sizes: 96-bit integers
scaled by a power of ten. With lines capped at one quadrillion and ten
decimal places, every sum is exact while the total of all amounts stays
below 7.9 × 10^18. `crates/ledger-core/tests/decimal_exact.rs` checks
the operations the money paths use against `num_rational`/`num_bigint`
(an independent exact reference): `checked_add` and `checked_sub` over
signed line amounts to 1e15 at 0–10 places; 1,000-line sums; `checked_mul`
for ordinary quantities/rates and at the top of the line range while the
true product's mantissa fits 28 digits; `round_dp_with_strategy` for
every strategy the engine uses (`MidpointAwayFromZero`,
`MidpointNearestEven`, `ToZero`, `ToNegativeInfinity`) at every scale
0–28; `rescale`'s half-away rounding; `normalize`; comparison and equality
across scales (1.0 = 1.00); and `from_str`/`to_string` round trips at
every scale, including 28-digit mantissas and negative ties. It also pins
the one inexact edge: when a product's *scale* does not fit,
`checked_mul` rounds to 28 decimal places, ties to even, rather than
failing (`None` comes only when the integer part cannot fit). That case
is reachable through `Ledger::add_line_fx`, whose foreign amount and rate
are unbounded positive `Decimal`s; the base amount is then rounded to the
currency's minor unit. What is still trusted: the 96-bit representation
and `rust_decimal`'s implementation beyond the sampled properties (they
are tests, not a proof, and the edge cases are hand-written); Kani still
cannot explore `Decimal` arithmetic directly (a single symbolic add runs
for more than ten minutes).
- **The state machine is a model of `Ledger`'s checks**, not a proof
about `ledger.rs` line by line. Its correspondence to the code is
checked by review and by the end-to-end property tests in
+73
View File
@@ -215,6 +215,79 @@ fuzz target="fuzz_op_sequence" seconds="300":
miri:
PROPTEST_CASES=4 MIRIFLAGS="-Zmiri-disable-isolation" cargo +nightly-2026-10-01 miri test -p ledger-core --lib --test kernel_bridge --test invariants
# Line, region and branch coverage of the core and the store, from their
# own test suites (nightly's -Zcoverage-options=branch, so every `if` has a
# taken/not-taken record too). HTML and a plain per-file table land in
# target/coverage/<crate>/; docs/coverage-floor.md records the totals and
# `coverage-check` guards them. Not a push gate (it is slow), but the
# weekly scheduled workflow runs it. `src/proofs.rs` is Kani-only (cfg(kani))
# and is excluded, as are test and bench files: this measures the library.
coverage crate="all":
#!/usr/bin/env bash
set -euo pipefail
# The shared sccache wrapper (~/.cargo/config.toml) would hand rustc to
# whatever toolchain it finds, and a `RUSTUP_TOOLCHAIN` in the caller's
# environment (1.99.1 in a session here) would beat `+nightly` for the
# rustc cargo-llvm-cov invokes. Both are overridden explicitly: branch
# coverage needs the pinned nightly. The build is its own target dir
# (`target/llvm-cov-target`), so sccache would not be shared anyway.
export RUSTC_WRAPPER=
export RUSTUP_TOOLCHAIN=nightly-2026-10-01
# Name the compiler itself: the mise shim around cargo-llvm-cov can put
# its pinned stable toolchain back, and a bare `rustc` then loses the
# nightly flag. Call the binary directly, as `fuzz` does with cargo-fuzz.
export RUSTC="$(rustup which --toolchain "$RUSTUP_TOOLCHAIN" rustc)"
llvm_cov=$(mise which cargo-llvm-cov)
mkdir -p target/coverage
# Every workspace member but the crate under measurement: a dev-dependency
# (the core's tests use the store, the store's use the core) is compiled
# instrumented too, and its files must not enter this crate's totals.
others() {
local keep=$1 member
local list=()
for member in ledger-core ledger-store ledger-config ledger-mcp \
ledger-import ledger-reader ledger-cli ledger-gui ledger-vault \
ledger-host ledger-package; do
[ "$member" = "$keep" ] || list+=("${member#ledger-}")
done
local IFS='|'
echo "crates/ledger-(${list[*]})/"
}
run() { # crate
local crate=$1 dir="target/coverage/$1"
local ignore="$(others "$crate")|/(tests|benches|examples)/|/src/proofs\\.rs$"
mkdir -p "$dir"
# One instrumented test run: the HTML comes from it; the JSON and the
# table are regenerated from the same profiles, cheaply.
# `--failure-mode all`: the store's tests start and kill server
# processes, which inherit LLVM_PROFILE_FILE; a SIGKILLed child leaves
# a truncated profraw that llvm-profdata refuses. That file has no
# test coverage in it, so it is tolerated; the test binaries' own
# profiles merge normally.
"$llvm_cov" llvm-cov -p "$crate" --branch --failure-mode all \
--ignore-filename-regex "$ignore" \
--html --output-dir "$dir"
"$llvm_cov" llvm-cov report --failure-mode all \
--ignore-filename-regex "$ignore" \
--json --output-path "$dir/coverage.json"
"$llvm_cov" llvm-cov report --failure-mode all \
--ignore-filename-regex "$ignore" > "$dir/summary.txt"
echo "coverage: $crate written to $dir/html and $dir/summary.txt"
awk -v crate="$crate" '$1 == "TOTAL" { printf "coverage: %s lines %s, regions %s, branches %s\n", crate, $10, $4, $13 }' "$dir/summary.txt"
}
case "{{crate}}" in
all) run ledger-core; run ledger-store ;;
ledger-core | ledger-store) run "{{crate}}" ;;
*) echo "coverage: unknown crate '{{crate}}' (all, ledger-core, ledger-store)" >&2; exit 2 ;;
esac
echo "coverage: floors in docs/coverage-floor.md; check them with \`just coverage-check\`"
# The coverage floor: fails when either crate's total line coverage is more
# than 0.5 percentage points below docs/coverage-floor.md's recorded number
# (reads the last `just coverage` report; it does not rerun the tests).
coverage-check:
@scripts/coverage-floor.sh
# Where cargo-mutants copies and builds the tree for each mutant (several
# GB per job): the user's cache on disk, never /tmp, which is often RAM.
# The tests it runs honor the same TMPDIR (every test's books go in
+6 -2
View File
@@ -5,8 +5,9 @@
# Workspace toolchain (clippy and rustfmt for `just check`).
rust = [
{ version = "1.99", components = "clippy,rustfmt", targets = "x86_64-pc-windows-msvc" },
# Fuzzing (cargo-fuzz) and Miri need nightly; pinned so runs repeat.
{ version = "nightly-2026-10-01", components = "miri,rust-src" },
# Fuzzing (cargo-fuzz), Miri and branch coverage need nightly; pinned so
# runs repeat. `llvm-tools` is what cargo-llvm-cov reads profiles with.
{ version = "nightly-2026-10-01", components = "miri,rust-src,llvm-tools" },
]
just = "1"
# `just oracle` reads the pinned bookspec's path from `cargo metadata`.
@@ -22,6 +23,9 @@ node = "26"
# Mutation testing and fuzzing (docs/oracle.md).
"cargo:cargo-mutants" = "27.1.0"
"cargo:cargo-fuzz" = "0.13.2"
# `just coverage`: line and branch coverage of the core and the store
# (docs/coverage-floor.md).
"cargo:cargo-llvm-cov" = "0.9.1"
# A compile cache shared by every jj workspace's target dir: point
# cargo's build.rustc-wrapper at it (~/.cargo/config.toml).
sccache = "0.18.0"
+55
View File
@@ -0,0 +1,55 @@
#!/bin/bash
# The coverage floor (docs/coverage-floor.md): `just coverage` measures the
# core's and the store's line, region and branch coverage into
# target/coverage/<crate>/; this reads those reports and fails when a
# crate's total line coverage has fallen more than 0.5 percentage points
# below its recorded floor. The report is not regenerated here on purpose:
# `just coverage-check` is the cheap gate over the last `just coverage`
# run, in the same job in CI.
#
# Usage: scripts/coverage-floor.sh
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
doc=docs/coverage-floor.md
if [ ! -f "$doc" ]; then
echo "coverage floor: $doc is missing" >&2
exit 1
fi
status=0
for crate in ledger-core ledger-store; do
summary="target/coverage/$crate/summary.txt"
if [ ! -f "$summary" ]; then
echo "coverage floor: $summary is missing; run \`just coverage\` first" >&2
exit 1
fi
# The `**Floor: ...**` line, e.g. `ledger-core` 87.34% lines.
floor=$(sed -n "s/.*\`$crate\` \([0-9][0-9]*\.[0-9][0-9]*\)% lines.*/\1/p" "$doc" | head -n 1)
if [ -z "$floor" ]; then
echo "coverage floor: $doc has no floor for $crate" >&2
exit 1
fi
# THE report table's TOTAL row: columns are Regions, Missed Regions,
# Cover, Functions, Missed Functions, Executed, Lines, Missed Lines,
# Cover, Branches, Missed Branches, Cover. $10 is line cover, $13
# branch cover, $4 region cover.
total=$(awk '$1 == "TOTAL" { print $10 }' "$summary" | tr -d '%')
if [ -z "$total" ]; then
echo "coverage floor: $summary has no TOTAL row" >&2
exit 1
fi
if awk -v actual="$total" -v floor="$floor" \
'BEGIN { exit !(actual + 0 >= floor - 0.5) }'; then
echo "coverage floor: $crate ${total}% lines (floor ${floor}%, tolerance 0.5 pp)"
else
echo "coverage floor: $crate is at ${total}% lines, more than 0.5 pp below its ${floor}% floor (docs/coverage-floor.md)" >&2
status=1
fi
done
exit "$status"