test(core): Kani and bridge for even_parts

Five Kani harnesses on i64 (fixed arrays, fixed months and steps, covers
reached): the parts sum to the total, all but the last are the half-even
rounded quotient and a whole multiple of the step, the last takes what the
others leave, the first part is within half a step of the quotient (a unit
a month wider against the true one, because i64 truncates), and no months
or a bad step is None. Law 43, bookspec's even-parts law.

The bridge checks i64 against Decimal where the quotient is exact, and
Decimal against an independent exact i128 reference at the USD, JPY, KWD
and CLF steps for any month count, with an edge table: Decimal::MAX and
scale 28 never panic and still sum exactly, though the 28-digit division
leaves MAX / 2 half a unit off its exact quotient (the K-U10 item, pinned).

docs/proofs/k-u5.md records the API, how a schedule knows its rule, the
times and the bounds.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-09 03:33:15 -07:00
1 parent 09308d5528
commit 317c53fa00
3 files changed
+659 -7

No files matched your search

+193 -4
View File
@@ -1,5 +1,194 @@
//! U5 proof harnesses: schedule plans (kernel sweep).
//! U5 proof harnesses: equal monthly parts (kernel sweep).
//!
//! Empty in U0: the unit adds its Kani harnesses here; `just prove` scans
//! every file in `proofs/`, so a harness needs no change to the module
//! root or the recipe.
//! `kernel::even_parts` on `i64`: the total a symbolic whole number of the
//! smallest unit, the months and the step fixed constants. A symbolic
//! month count or step was not used: `even_parts` divides by the months
//! and `round_step` by the step, and CBMC's bit-blasted division by a
//! symbolic `i64` did not finish in K-U2 (`docs/proofs/k-u2.md`). The
//! month counts below are one (nothing but the plug), two (the smallest
//! split, and an exact tie at an even total), three (the schedule the
//! tests are written on, a quotient that never ends) and seven (a count
//! that divides few totals); the steps are one, an even step (a tie
//! exists), an odd one, and two decimal steps. The bridge carries the
//! same laws to every `Decimal` total, month count and step, and
//! bookspec's Lean (`Bookspec.Schedule`, law 43) proves them of the
//! exact-rational model for any number of months.
//!
//! ```text
//! GOAL: an equal-months schedule books exactly its total across its
//! months, each month but the last a whole multiple of the unit and
//! within half a unit of the quotient, the last taking the rest.
//! SOURCE: BS-prepaid-1 (a schedule recognizes exactly its total over its
//! months), BS-prepaid-2 (equal months), BS-prepaid-4 (the
//! currency's minor unit is the step), BS-ledger-1 (whole smallest
//! units).
//! INVARIANTS:
//! 1. The parts sum to the total exactly, whatever the rounding.
//! 2. Every part but the last equals `round_half_even(total / months)`
//! to the step, so each is a whole multiple of it.
//! 3. The last part is the total less the others, which is the first
//! part plus what the others left (`total - months x each`).
//! 4. The first part is within half a step of the quotient the integer
//! division gives, and `months x each` within half a step per month
//! (plus the truncation, under one unit a month) of the total. The
//! `Decimal` quotient keeps its fraction, so the bridge checks the
//! strict half-step bound against the exact total / months.
//! 5. No months, or a step that is not positive, is None.
//! SCENARIOS:
//! 1. IF 1,000 over 3 months at one: SHOULD be 333, 333, 334.
//! 2. IF 5 over 2 months at one: SHOULD be 2, 3, the half to the even
//! multiple.
//! 3. IF no months: SHOULD be None.
//! ```
//!
//! Bounds: totals -1,000 to 1,000, months {1, 2, 3, 7}, steps {1, 2, 5,
//! 10, 100}. The laws are about the shape of the split, not the
//! magnitude.
use crate::kernel::{self, Rounding};
use kani::cover;
/// The fixed steps: one, an even step (a tie exists), an odd step, a
/// decimal step, and a step well above the totals' quotients.
const STEPS: [i64; 5] = [1, 2, 5, 10, 100];
/// A total the harnesses explore: -1,000 to 1,000 units.
fn any_total() -> i64 {
let total: i64 = kani::any();
kani::assume((-1_000..=1_000).contains(&total));
total
}
/// The split of `total` into `M` months at `step`.
fn split<const M: usize>(total: i64, step: i64) -> [i64; M] {
let mut parts = [0i64; M];
kernel::even_parts(total, step, &mut parts).expect("no overflow under these bounds");
parts
}
/// The parts sum to the total, whatever the rounding left.
#[kani::proof]
#[kani::unwind(10)]
fn even_parts_sum() {
let total = any_total();
for step in STEPS {
let a = split::<1>(total, step);
let b = split::<2>(total, step);
let c = split::<3>(total, step);
let d = split::<7>(total, step);
assert_eq!(a.iter().sum::<i64>(), total);
assert_eq!(b.iter().sum::<i64>(), total);
assert_eq!(c.iter().sum::<i64>(), total);
assert_eq!(d.iter().sum::<i64>(), total);
}
cover!(
split::<3>(total, 1)[2] != split::<3>(total, 1)[0],
"the last part takes a unit the others left"
);
cover!(
split::<3>(total, 10)[2] != split::<3>(total, 10)[0],
"the last part takes what a coarse step left"
);
cover!(total < 0, "a negative total");
}
/// Every part but the last is the same whole multiple of the step: the
/// quotient rounded half to even.
#[kani::proof]
#[kani::unwind(10)]
fn even_parts_all_but_last_equal() {
let total = any_total();
for step in STEPS {
let each = kernel::round_step(total / 3, step, Rounding::HalfToEven)
.expect("no overflow under these bounds");
let c = split::<3>(total, step);
assert_eq!(c[0], each, "each is the rounded quotient");
assert_eq!(c[1], c[0], "all but the last are equal");
assert_eq!(c[0] % step, 0, "a whole multiple of the step");
let d = split::<7>(total, step);
for i in 1..6 {
assert_eq!(d[i], d[0]);
}
assert_eq!(d[0] % step, 0);
}
cover!(
total / 3 % 10 == 5 && total > 0,
"a quotient exactly on a tie at step 10 (rounds to the even multiple)"
);
cover!(total % 3 != 0, "a quotient that does not terminate");
}
/// The last part is the total less the others: the first part plus the
/// rounding the others left.
#[kani::proof]
#[kani::unwind(10)]
fn even_parts_last_absorbs() {
let total = any_total();
for step in STEPS {
let c = split::<3>(total, step);
assert_eq!(
c[2],
total - 2 * c[0],
"the last is the total less the others"
);
assert_eq!(
c[2] - c[0],
total - 3 * c[0],
"it is each plus what was left"
);
let d = split::<7>(total, step);
assert_eq!(d[6], total - 6 * d[0]);
let one = split::<1>(total, step);
assert_eq!(one[0], total, "a single month is the whole total");
}
cover!(
split::<3>(total, 100)[2] - split::<3>(total, 100)[0] > 50,
"a last part far from the others under a coarse step"
);
}
/// The first part is within half a step of the quotient, and the parts
/// are within half a step a month of the total (plus truncation).
#[kani::proof]
#[kani::unwind(10)]
fn even_parts_within_half_step() {
let total = any_total();
for step in STEPS {
let c = split::<3>(total, step);
let quotient = total / 3;
assert!(
2 * (c[0] - quotient).abs() <= step,
"within half a step of the quotient"
);
// Against the exact total / 3: the quotient truncated, under one
// unit a month.
assert!(
2 * (3 * c[0] - total).abs() <= 3 * step + 2 * 2,
"months x each within half a step a month, plus truncation"
);
let d = split::<7>(total, step);
assert!(2 * (d[0] - total / 7).abs() <= step);
assert!(2 * (7 * d[0] - total).abs() <= 7 * step + 2 * 6);
}
cover!(
2 * (split::<3>(total, 10)[0] - total / 3).abs() == 10,
"an exact tie at step 10, taken at exactly half a step"
);
cover!(
split::<3>(total, 2)[0] != total / 3,
"a quotient moved to the step"
);
}
/// No months and a step that is not positive are None, never a guess.
#[kani::proof]
#[kani::unwind(4)]
fn even_parts_refuses_no_months_and_a_bad_step() {
let total = any_total();
let mut none: [i64; 0] = [];
assert_eq!(kernel::even_parts(total, 1, &mut none), None);
let mut parts = [0i64; 3];
assert_eq!(kernel::even_parts(total, 0, &mut parts), None);
assert_eq!(kernel::even_parts(total, -5, &mut parts), None);
cover!(total != 0, "a total no step can place");
}
@@ -1,4 +1,281 @@
//! U5 bridge properties: schedule plans (kernel sweep).
//! U5 bridge properties: equal monthly parts (kernel sweep).
//!
//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here,
//! beside `main.rs` and the other units.
//! `proofs/schedule.rs` proves `even_parts` on `i64` (whole units, fixed
//! months and steps); the engine runs the same code on `Decimal`. These
//! properties check that the two instantiations agree where the integer
//! quotient is exact, that `Decimal` agrees with an independent exact
//! rational reference (an `i128` numerator over an `i128` denominator,
//! rounded half to even, sharing no code with the kernel and no `Decimal`
//! division) at the steps of USD (0.01), JPY (1) and KWD (0.001), that the
//! laws of the proofs hold for any month count (the Kani harnesses fix
//! it), and the edge table: `Decimal::MAX`, scale 28, and no months, which
//! must be `None`, never a panic.
//!
//! What rounds, stated plainly (the K-U10 item): `even_parts` divides with
//! `Decimal`'s own division, exact where the quotient terminates and
//! otherwise rounded at 28 significant digits, and then rounds that
//! quotient to the step in exact integer arithmetic. For a total whose
//! quotient fits the 28 digits to well below the step (every total up to
//! about 10^15, which the properties use), that is the exact rational
//! rounded once, and the reference agrees. For a total near `Decimal::MAX`
//! the quotient itself carries a half-unit of error, so the part is not
//! within half a step of the exact quotient: the parts still sum to the
//! total (the plug is exact), and `the_edges` pins what happens.
use ledger_core::kernel;
use proptest::prelude::*;
use rust_decimal::Decimal;
/// The exact rational reference: `tm x 10^-ts` over `months`, each part
/// the quotient rounded half to even to `places` places, the last the
/// total less the others. Plain `i128` integers: the count is
/// `round_half_even(tm x 10^(places - ts) / months)`, found by integer
/// division and its remainder. `None` when a number leaves `i128` or the
/// answer leaves `Decimal`'s 96 bits.
fn reference(tm: i128, ts: u32, months: u32, places: u32) -> Option<(Decimal, Decimal)> {
let m = i128::from(months);
let (num, den) = if places >= ts {
(tm.checked_mul(10i128.checked_pow(places - ts)?)?, m)
} else {
(tm, m.checked_mul(10i128.checked_pow(ts - places)?)?)
};
let negative = num < 0;
let magnitude = num.unsigned_abs();
let den = den.unsigned_abs();
let floor = magnitude / den;
let twice = (magnitude % den).checked_mul(2)?;
let up = twice > den || (twice == den && floor % 2 == 1);
let count = i128::try_from(if up { floor + 1 } else { floor }).ok()?;
let count = if negative { -count } else { count };
// Both at the wider of the two scales.
let scale = ts.max(places);
let total = tm.checked_mul(10i128.checked_pow(scale - ts)?)?;
let each = count.checked_mul(10i128.checked_pow(scale - places)?)?;
let last = total.checked_sub(each.checked_mul(m - 1)?)?;
Some((
Decimal::try_from_i128_with_scale(each, scale).ok()?,
Decimal::try_from_i128_with_scale(last, scale).ok()?,
))
}
/// `even_parts` on `Decimal`: the parts, or None.
fn decimal_parts(total: Decimal, step: Decimal, months: usize) -> Option<Vec<Decimal>> {
let mut parts = vec![Decimal::ZERO; months];
kernel::even_parts(total, step, &mut parts)?;
Some(parts)
}
/// `even_parts` on `i64`: the parts, or None.
fn integer_parts(total: i64, step: i64, months: usize) -> Option<Vec<i64>> {
let mut parts = vec![0i64; months];
kernel::even_parts(total, step, &mut parts)?;
Some(parts)
}
fn step_of(places: u32) -> Decimal {
Decimal::try_from_i128_with_scale(1, places).unwrap()
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(3000))]
/// The Kani model (whole cents, an integer step in cents) and the
/// engine (dollars) agree on the same plan wherever the integer
/// quotient is exact, so truncation moves nothing: the shared case.
#[test]
fn i64_and_decimal_agree_where_the_quotient_is_exact(
each_cents in -(1i64 << 30)..=(1i64 << 30),
months in 1usize..=600,
step_cents in prop_oneof![Just(1i64), Just(5), Just(10), Just(100)],
) {
let total_cents = each_cents * months as i64;
let ours = integer_parts(total_cents, step_cents, months).unwrap();
let theirs = decimal_parts(
Decimal::new(total_cents, 2),
Decimal::new(step_cents, 2),
months,
)
.unwrap();
prop_assert_eq!(
ours.iter().map(|&c| Decimal::new(c, 2)).collect::<Vec<_>>(),
theirs
);
}
/// A single month is the whole total, even finer than the step (the
/// plug takes everything): on both types.
#[test]
fn one_month_is_the_whole_total(
total in -(1i64 << 40)..=(1i64 << 40),
step in prop_oneof![Just(1i64), Just(2), Just(10), Just(100)],
ts in 0u32..=6,
) {
let mut one = [0i64];
prop_assert_eq!(kernel::even_parts(total, step, &mut one), Some(()));
prop_assert_eq!(one, [total]);
let exact = Decimal::new(total, ts);
let mut one = [Decimal::ZERO];
prop_assert_eq!(kernel::even_parts(exact, step_of(2), &mut one), Some(()));
prop_assert_eq!(one, [exact]);
}
/// The proofs' laws for any month count (two or more) on `i64`: the parts sum to the
/// total, all but the last are one whole multiple of the step within
/// half a step of the (truncated) quotient, and the last is the total
/// less the others.
#[test]
fn the_i64_laws_hold_for_any_month_count(
total in -(1i64 << 40)..=(1i64 << 40),
months in 2usize..=600,
step in prop_oneof![Just(1i64), Just(2), Just(5), Just(10), Just(100), Just(1000)],
) {
let parts = integer_parts(total, step, months).unwrap();
prop_assert_eq!(parts.iter().sum::<i64>(), total);
let each = parts[0];
prop_assert!(parts[..months - 1].iter().all(|&p| p == each));
prop_assert_eq!(each % step, 0);
prop_assert!(2 * (each - total / months as i64).abs() <= step);
prop_assert_eq!(parts[months - 1], total - each * (months as i64 - 1));
}
/// The exact reference, for totals of every scale 0 to 6 and up to 15
/// digits (so the quotient fits `Decimal`'s 28 digits to well below
/// the step), 1 to 600 months, and the steps of JPY, USD and KWD
/// (and a four-place unit): `Decimal`'s parts are the reference's,
/// value for value, for either sign.
#[test]
fn decimal_matches_the_exact_reference(
tm in -(1_000_000_000_000_000i128)..=1_000_000_000_000_000i128,
ts in 0u32..=6,
months in 2u32..=600,
places in prop_oneof![Just(0u32), Just(2u32), Just(3u32), Just(4u32)],
) {
let total = Decimal::try_from_i128_with_scale(tm, ts).unwrap();
let want = reference(tm, ts, months, places).expect("fits");
let parts = decimal_parts(total, step_of(places), months as usize).unwrap();
prop_assert_eq!(parts[0], want.0);
prop_assert!(parts[..months as usize - 1].iter().all(|&p| p == want.0));
prop_assert_eq!(*parts.last().unwrap(), want.1);
}
/// The laws on `Decimal` for any month count: the parts sum to the
/// total exactly, all but the last are equal and whole multiples of
/// the step, and `months x each` is within half a step a month of the
/// total (so `each` is within half a step of the exact quotient,
/// strictly: no truncation here).
#[test]
fn the_decimal_laws_hold_for_any_month_count(
tm in 0i128..=1_000_000_000_000_000i128,
ts in 0u32..=6,
months in 2usize..=600,
places in prop_oneof![Just(0u32), Just(2u32), Just(3u32)],
) {
let total = Decimal::try_from_i128_with_scale(tm, ts).unwrap();
let step = step_of(places);
let parts = decimal_parts(total, step, months).unwrap();
prop_assert_eq!(parts.iter().copied().sum::<Decimal>(), total);
let each = parts[0];
prop_assert!(parts[..months - 1].iter().all(|&p| p == each));
prop_assert_eq!((each / step).fract(), Decimal::ZERO);
let off = (each * Decimal::from(months as u32) - total).abs();
prop_assert!(off * Decimal::TWO <= Decimal::from(months as u32) * step);
// The last is `each` plus what the others left.
let last = *parts.last().unwrap();
prop_assert_eq!(last, total - each * Decimal::from(months as u32 - 1));
}
}
/// The edge table, each row checked by hand.
#[test]
fn the_edges() {
let parse = |s: &str| -> Decimal { s.parse().unwrap() };
let cent = parse("0.01");
// No months, and a step that is no step: None, never a guess.
assert_eq!(decimal_parts(parse("100"), cent, 0), None);
assert_eq!(decimal_parts(parse("100"), Decimal::ZERO, 3), None);
assert_eq!(decimal_parts(parse("100"), parse("-0.01"), 3), None);
assert_eq!(integer_parts(100, 0, 3), None);
assert_eq!(integer_parts(100, 1, 0), None);
// The three currencies of the plans, by hand: 100,000 yen over 3 is
// 33,333.33..., to the yen 33,333, the last 100,000 - 66,666 = 33,334;
// 1,000.00 dollars is 333.33, 333.33, 333.34; 1.000 dinar is 0.333,
// 0.333, 0.334.
let plan = |t: &str, step: &str| decimal_parts(parse(t), parse(step), 3).unwrap();
assert_eq!(
plan("100000", "1"),
[parse("33333"), parse("33333"), parse("33334")]
);
assert_eq!(
plan("1000.00", "0.01"),
[parse("333.33"), parse("333.33"), parse("333.34")]
);
assert_eq!(
plan("1.000", "0.001"),
[parse("0.333"), parse("0.333"), parse("0.334")]
);
// A tie goes to the even multiple (5 / 2 = 2.5 to 2; 7 / 2 = 3.5 to
// 4), the last taking the rest, which may be the smaller.
assert_eq!(
decimal_parts(parse("5"), parse("1"), 2).unwrap(),
[parse("2"), parse("3")]
);
assert_eq!(
decimal_parts(parse("7"), parse("1"), 2).unwrap(),
[parse("4"), parse("3")]
);
assert_eq!(
decimal_parts(parse("-7"), parse("1"), 2).unwrap(),
[parse("-4"), parse("-3")]
);
// A total smaller than its months: every other month rounds to
// nothing and the last takes it all (0.01 over 3 at the cent).
assert_eq!(
decimal_parts(parse("0.01"), cent, 3).unwrap(),
[Decimal::ZERO, Decimal::ZERO, parse("0.01")]
);
// Scale 28, the finest Decimal holds: 1e-28 over 2 rounds to nothing
// at any step, and the last takes the whole.
let tiny = Decimal::try_from_i128_with_scale(1, 28).unwrap();
assert_eq!(decimal_parts(tiny, cent, 2).unwrap(), [Decimal::ZERO, tiny]);
let widest = Decimal::MAX;
// Decimal::MAX: no panic, and the parts still sum to the total. The
// answer is not None, because the plug is exact; but the quotient
// MAX / 2 = ...167.5 has 29 digits, so Decimal's division rounds it to
// ...168 first, and the part is half a unit from the exact quotient,
// a hundred steps at the cent: the K-U10 item, which is why the
// callers refuse totals of 10^26 or more (EXACT_LIMIT).
for months in [1usize, 2, 3, 7, 600] {
for step in ["1", "0.01", "0.001"] {
let parts = decimal_parts(widest, parse(step), months)
.expect("MAX fits: the quotient is smaller, the last is the remainder");
assert_eq!(
parts
.iter()
.try_fold(Decimal::ZERO, |a, &b| a.checked_add(b)),
Some(widest),
"{months} months at {step}"
);
}
}
let halves = decimal_parts(widest, cent, 2).unwrap();
assert_eq!(halves[0], parse("39614081257132168796771975168"));
assert_eq!(halves[1], parse("39614081257132168796771975167"));
// A step as large as the total: MAX / 2 rounds up at 28 digits to a
// hair over half the step, so the part is the whole step (the same
// K-U10 half unit) and the last takes nothing.
assert_eq!(
decimal_parts(widest, widest, 2),
Some(vec![widest, Decimal::ZERO])
);
assert_eq!(
decimal_parts(Decimal::MIN, cent, 1),
Some(vec![Decimal::MIN])
);
// The maximum scale the engine accepts for a total, 28 places, over
// 7 months at the cent: 7.9228162514264337593543950335 / 7 = 1.13...
let max28 =
Decimal::try_from_i128_with_scale(79_228_162_514_264_337_593_543_950_335, 28).unwrap();
let parts = decimal_parts(max28, cent, 7).unwrap();
assert_eq!(parts[0], parse("1.13"));
assert_eq!(parts.iter().copied().sum::<Decimal>(), max28);
}
+186
View File
@@ -0,0 +1,186 @@
# K-U5: equal monthly parts (`kernel/schedule.rs`) and the versioned rounding rule
Kernel sweep unit U5 (`plan/kernel-sweep-audit.md` section 3), with the
owner's decision D-72 (2026-11-08, "Version the rule"): **new monthly-even
schedules round to the currency's minor unit (it was two places for every
currency, wrong for the yen and the dinar); schedules written before the
format feature replay the cent rule, so nothing journaled moves.** The
authorities are bookspec `BS-prepaid-1` (a schedule recognizes exactly its
total over its months), `BS-prepaid-2` (equal months), `BS-prepaid-4` (the
choice D-72 picked), `BS-ledger-1` (whole smallest units) and `BS-entry-8`
(what is journaled never moves).
## The function
```rust
pub fn even_parts<T: Amount>(total: T, step: T, parts: &mut [T]) -> Option<()>
```
Fills `parts` (one slot per month) with `months = parts.len()` amounts that
sum to `total` exactly: every part but the last is `total / months`
rounded half to even to `step` (`round_step`), the last is `total` less the
others (`plug_last`). `None` for no months, a step that is not positive, or
an amount the type cannot hold; never a panic. Nothing is multiplied; the
only rounding is `round_step`'s exact integer arithmetic and the type's
own division.
The audit sketched `(total, months, step) -> Option<Vec<T>>`. The slice
form keeps `months` implicit, allocates nothing in the kernel (so there is
no allocating wrapper to except from the gate, as `movements` and
`reversal` needed), and lets the Kani harnesses use fixed arrays. The
caller (`schedules::plan_in_places`) allocates after it has checked the
month ends, so a plan that runs past chrono's last day is refused before a
part is made.
### What rounds, stated plainly
`even_parts` divides with `Amount::checked_div`: for `Decimal`, exact where
the quotient terminates and otherwise rounded at 28 significant digits;
for `i64`, truncating. It then rounds that quotient to the step exactly.
So for a total whose quotient fits 28 digits to well below the step (every
schedule: totals under `EXACT_LIMIT`, 10^26, and in practice a line limit
of 10^15), the part is the exact rational rounded once, half to even, and
the bridge's independent `i128` reference agrees. Near `Decimal::MAX` the
quotient carries a half-unit of its own: `MAX / 2 = ...167.5` has 29
digits, `Decimal` rounds it to `...168` first, and the part is not within
half a step of the exact quotient (`the_edges` pins it). The parts still
sum to the total, because the plug is exact. This is the K-U10 item (the
division's rounding); the engine's callers refuse totals of `EXACT_LIMIT`
or more, so no schedule reaches it. A single month is the whole total even
when finer than the step (the plug takes it, as the cent rule always did).
## How a schedule knows its rule (the D-72 decision)
**A flag journaled on the schedule, never the feature's sequence
position.** `AmortizationSchedule.rounding` is a `ScheduleRounding`
(`Cent` or `MinorUnit`); a monthly-even schedule written under
`MinorUnit` journals `"rounding": "minor_unit"` on its
`schedule.registered` line. A line with no `rounding` is the cent rule, as
every schedule before D-72 is, and replays exactly as it was posted.
Why not the position: a position (the schedule's `seq` against the
`journal.format_set` that declared the feature) is not in the core's
`Ledger`, would have to be threaded through every replay, snapshot and
adoption copy, and breaks the moment a replay starts mid-journal or a
schedule is carried to another set of books. A flag is the schedule's own
fact and survives all of those. The cost is one optional key, left unsaid
for the cent rule so a serialized ledger from before D-72 reads back, and
a cent schedule serializes, byte for byte as before.
The store chooses the rule when a schedule is registered (`Store::
register_schedule`): minor unit exactly when the books declared
`schedule_minor_unit` and the schedule is monthly-even; otherwise the cent
rule, so books waiting for the owner's format upgrade keep working as they
do and refuse a yen month finer than a yen as before. `ensure_feature`
guards the journaling of the flag. The core's plain
`Ledger::register_schedule` stays the cent rule (the core cannot know the
format, and its existing tests rest on the cent rule); the store calls the
new `register_schedule_under`.
**Older binaries refuse, never misread (BS-format-1).** The feature
`schedule_minor_unit` is in `KNOWN_FEATURES`, declared with every other
feature by new books and by an upgrade, before any `schedule.registered`
can carry the flag. A version that doesn't know it stops at the
`journal.format_set` as newer books
(`format::tests::schedule_minor_unit_is_its_own_feature`); a
`schedule.registered` naming a rounding this version doesn't know is
`NewerJournal` too, never corrupt
(`an_unknown_rounding_is_newer_not_corrupt`).
**A USD schedule gives the same plan under both rules: by construction,
and tested.** `ScheduleRounding::places` is two for `Cent` and the
currency's ISO 4217 minor unit for `MinorUnit` (two for USD); both rules
call the same `plan_in_places(total, places, ..)`, so for any currency with
two places the call is literally the same. The test
`the_cent_rule_is_unchanged_and_usd_is_the_same_under_both_rules` also
checks it over 300,000 plans, values and printed text.
### Replay fidelity: the printed scale
A posted month's replay compares its journaled lines as text, so the cent
rule must give the same figures at the same printed scale as before, not
only equal values. `round_places` (the old call) returns `0.250` as
`0.25` and a zero as `0.00`; `round_step` (the kernel's) returns an amount
already a whole multiple of the step as it came, and a zero as `0`. The
exhaustive test found it (`1 over 360` printed `1.00` against `1`): the
plan applies `present_as_rounded`, which restores the old scale (and the
last month's: `total` less the others at the wider scale, or the total's
own when the others are zero). Values never change; every rescale is to
or from trailing zeros, checked by debug assertions. The oracle is a
verbatim copy of the pre-K-U5 function in `tests/schedule_minor_unit.rs`,
compared over 300,000+ (total, scale, months) plans and a proptest up to
10^25, value and text.
## Kani harnesses (`src/proofs/schedule.rs`)
On `i64`, fixed arrays, each with `kani::cover!`. Totals -1,000 to 1,000;
months fixed to {1, 2, 3, 7} and steps to {1, 2, 5, 10, 100}. Symbolic
months or step were not used: `even_parts` divides by the months and
`round_step` by the step, and CBMC's bit-blasted division by a symbolic
`i64` did not finish in K-U2. Months {2, 3, 7} cover a tie, a quotient that
never ends and a divisor that divides few totals; the bridge carries every
month count, step and `Decimal` total, and Lean any number of months.
| Harness | Law | Verification |
|---|---|---|
| `even_parts_sum` | 43 | the parts sum to the total for every month count and step; the last takes a unit the others left (3 covers). 47.1 s |
| `even_parts_all_but_last_equal` | 43 | all but the last are equal, are the half-even rounded quotient, and a whole multiple of the step; a tie at step 10 is reached (2 covers). 23.9 s |
| `even_parts_last_absorbs` | 43 | the last is the total less the others, the first part plus what the others left; a single month is the whole total (1 cover). 31.4 s |
| `even_parts_within_half_step` | 43 | the first part is within half a step of the integer quotient, and `months x each` within half a step a month of the total plus the truncation, under a unit a month; an exact tie at half a step is reached (2 covers). 42.7 s |
| `even_parts_refuses_no_months_and_a_bad_step` | 43 | no months, a zero step and a negative step are `None` (1 cover). 0.27 s |
Times: `cargo kani -p ledger-core --exact --harness proofs::schedule::<name>`,
the verifier's own "Verification Time", the shared dev machine under
`nice -n 15` and `ulimit -v 12000000`, 2026-11-09. The `i64` quotient
truncates, so the bound against the true quotient is one unit a month
wider than half a step (`3 * step + 4` for three months); the `Decimal`
quotient keeps its fraction, and the bridge checks the strict bound.
## Bridge (`tests/kernel_bridge/schedule.rs`)
- `i64_and_decimal_agree_where_the_quotient_is_exact`: the Kani model in
cents and the engine in dollars agree, value for value, at every step
where the integer quotient is exact (1 to 600 months).
- `the_i64_laws_hold_for_any_month_count`: sum, all-but-last equal, whole
multiple, within half a step of the quotient, last absorbs, for 2 to 600
months and six steps. `one_month_is_the_whole_total`: one month, both
types.
- `decimal_matches_the_exact_reference`: `Decimal`'s parts equal an
independent exact reference (an `i128` numerator over an `i128`
denominator, half to even, no kernel code and no `Decimal` division) for
totals of up to 15 digits at every scale 0 to 6, either sign, 2 to 600
months, steps 1, 0.01, 0.001, 0.0001 (JPY, USD, KWD, CLF).
- `the_decimal_laws_hold_for_any_month_count`: sum, equal, whole multiple,
`2 |months x each - total| <= months x step`, and the last, on `Decimal`.
- `the_edges`: no months and a bad step are `None`; the three plans by hand
(¥33,333 x 2 and ¥33,334; 333.33, 333.33, 333.34; 0.333, 0.333, 0.334);
ties of both signs (5 over 2 is 2, 3; 7 over 2 is 4, 3; -7 over 2 is
-4, -3); 0.01 over 3 at the cent (0, 0, 0.01); scale 28 (1e-28 over 2);
`Decimal::MAX` and `MIN` at every step and month count (**not `None`: the
parts exist and sum exactly, because the plug is exact; they never panic,
and the half-unit the quotient carries is pinned, see above**).
Engine tests (`tests/schedule_minor_unit.rs` in ledger-core and ledger-store):
the hand-computed JPY and KWD plans, the cent-rule oracle, the USD
equivalence, the replay of a pre-feature schedule after the upgrade, an
unknown rounding is newer, a daily schedule carries no flag.
## Lean (bookspec `lean/Bookspec/Schedule.lean`, law 43)
`evenParts_sum` (reusing `plugLast_total`), `evenParts_length`,
`evenParts_all_but_last_equal`, `evenParts_last_absorbs` (the closed
form), `each_multiple`, `each_near` (reusing `Round.near_halfEven`),
`last_near`, with `n_mul_each` and `plugLast_replicate` as lemmas. The
model counts in whole steps and rounds the exact quotient once
(`roundStep .halfEven (n * step) whole / n`), so it does not model
`Decimal`'s 28-digit division; the bridge's reference carries that half.
## What is not covered
- The engine's two-place rule for a currency ISO 4217 gives no minor unit
(gold, SDRs) is the daily plan's, not a law of this function.
- `Decimal`'s division at the 28-digit edge (K-U10).
- The pin: wanderbooks still pins the bookspec revision before this law;
the integrator moves the pin (`verify/lean/lakefile.toml`,
`lake-manifest.json`, the crates' `Cargo.toml`) after bookspec's
`k-u5` branch is merged.