diff --git a/Cargo.lock b/Cargo.lock index b9bec485..25d3aad0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -788,7 +788,7 @@ dependencies = [ [[package]] name = "bookspec-checker" version = "0.1.0" -source = "git+https://git.swaits.com/swaits/bookspec?rev=c597c8f845377d9eb868f0f4486759baf16eb5ea#c597c8f845377d9eb868f0f4486759baf16eb5ea" +source = "git+https://git.swaits.com/swaits/bookspec?rev=2b3b6c904781efc3f9ead71998a61f01efdeeadd#2b3b6c904781efc3f9ead71998a61f01efdeeadd" dependencies = [ "chrono", "include_dir", @@ -801,7 +801,7 @@ dependencies = [ [[package]] name = "bookspec-runner" version = "0.1.0" -source = "git+https://git.swaits.com/swaits/bookspec?rev=c597c8f845377d9eb868f0f4486759baf16eb5ea#c597c8f845377d9eb868f0f4486759baf16eb5ea" +source = "git+https://git.swaits.com/swaits/bookspec?rev=2b3b6c904781efc3f9ead71998a61f01efdeeadd#2b3b6c904781efc3f9ead71998a61f01efdeeadd" dependencies = [ "bookspec-checker", "serde_json", diff --git a/crates/ledger-core/Cargo.toml b/crates/ledger-core/Cargo.toml index 6ca7faa8..0ae1d012 100644 --- a/crates/ledger-core/Cargo.toml +++ b/crates/ledger-core/Cargo.toml @@ -33,8 +33,8 @@ num-rational = "0.4" toml = "1" # The specification lives in its own repository (P13 step 6, D-34, D-65), # pinned to a commit. -bookspec-checker = { git = "https://git.swaits.com/swaits/bookspec", rev = "c597c8f845377d9eb868f0f4486759baf16eb5ea" } -bookspec-runner = { git = "https://git.swaits.com/swaits/bookspec", rev = "c597c8f845377d9eb868f0f4486759baf16eb5ea" } +bookspec-checker = { git = "https://git.swaits.com/swaits/bookspec", rev = "2b3b6c904781efc3f9ead71998a61f01efdeeadd" } +bookspec-runner = { git = "https://git.swaits.com/swaits/bookspec", rev = "2b3b6c904781efc3f9ead71998a61f01efdeeadd" } ledger-package = { path = "../ledger-package" } ledger-import = { path = "../ledger-import" } ledger-store = { path = "../ledger-store" } diff --git a/crates/ledger-core/src/kernel/schedule.rs b/crates/ledger-core/src/kernel/schedule.rs index 10af9855..aab50142 100644 --- a/crates/ledger-core/src/kernel/schedule.rs +++ b/crates/ledger-core/src/kernel/schedule.rs @@ -1,5 +1,81 @@ //! U5: schedule plans, the monthly charge a schedule books (kernel sweep). //! -//! Empty in U0: the unit adds its arithmetic here, in this file alone, so -//! no two sweep units ever edit the same file. The module root re-exports -//! it, keeping every path `crate::kernel::foo`. +//! `even_parts` is the arithmetic of an equal-months (monthly-even) +//! schedule: the total spread over its months, each month but the last +//! the quotient rounded to the currency's step, the last taking what the +//! others leave. `schedules::amortization_plan` calls it; the date half of +//! a plan (which month end each part books on) stays there. + +use super::{Amount, Rounding, plug_last, round_step}; + +/// Fill `parts` (one slot per month) with the equal-months split of +/// `total`: every part but the last is `total / months` rounded to a whole +/// multiple of `step`, half to even; the last is the total less the +/// others, so the parts sum to `total` exactly. `None` for no months, a +/// step that is not positive, or an amount that cannot be held; `parts` +/// is then unspecified, and the caller discards it. +/// +/// ```text +/// GOAL: an equal-months schedule books exactly its total across its +/// months, each month a whole number of the currency's smallest +/// unit: every month but the last the same rounded share, the +/// last what the others leave (INVARIANT 4 bounds how far it is). +/// SOURCE: BS-prepaid-1 (a schedule recognizes exactly its total over its +/// months, each month rounded to the currency's minor unit), BS-prepaid-2 +/// (equal months is one of the two methods an engine picks), +/// BS-prepaid-4 (the unit is the currency's minor unit for a new +/// schedule, the cent for one written before the choice: the +/// caller passes the step, never this function), BS-ledger-1 +/// (whole smallest units), BS-entry-3 (exact totals; round only +/// where a rule says to); owner decision D-72; the `plug_last` +/// rule of BS-partner-1 for the remainder. +/// INVARIANTS: +/// 1. Some(()) means the parts sum to `total` exactly, and there are as +/// many parts as months. +/// 2. Every part but the last is equal: `each = round(total / months)` +/// to `step`, half to even (the schedule rule, frozen by replay), so +/// each is a whole multiple of `step`. +/// A single month has no part but the last: it is the whole total, +/// even one finer than the step (the plug takes it; the cent rule +/// always did). +/// 3. `each` is within half a step of the quotient the type's division +/// gives: for `Decimal` that is the exact quotient wherever the +/// division terminates, otherwise the quotient rounded at 28 +/// significant digits (`Amount::checked_div`: the K-U10 item, +/// checked against an exact reference in the bridge), and for a +/// machine integer it is the truncated quotient, so the bound against +/// the true quotient is one unit wider. Lean proves the exact-rational +/// law at any size (`Bookspec.Schedule.each_near`). +/// 4. The last part is `total - (months - 1) x each`, which is `each` +/// plus the rounding the others left: at most `months x step / 2` +/// from `each` (Lean: `Schedule.last_near`). It is therefore not +/// near the others for a long schedule of a coarse step; it is what +/// makes the sum exact. +/// 5. None for no months (`parts` empty), a step <= 0, or overflow; +/// never a panic. The kernel multiplies nothing: the only rounding +/// is `round_step`, which is exact integer arithmetic, and the +/// division's own. The caller keeps `total` below the size Decimal +/// adds exactly (`schedules::EXACT_LIMIT`). +/// SCENARIOS: +/// 1. IF 1,000.00 over 3 months at the cent: SHOULD be 333.33, 333.33, +/// 333.34 +/// BECAUSE the quotient 333.333... rounds down and the last takes +/// the odd cent. +/// 2. IF 100,000 yen over 3 months at one yen: SHOULD be 33,333, 33,333, +/// 33,334; and 1.000 dinar over 3 at 0.001: 0.333, 0.333, 0.334 +/// BECAUSE each month is a whole number of the currency's smallest +/// unit (the cent rule gave 33,333.33 yen and 0.33 dinar). +/// 3. IF 0.01 over 3 months at the cent: SHOULD be 0.00, 0.00, 0.01 +/// BECAUSE the quotient rounds to nothing and the last takes it all. +/// 4. IF there are no months, or the step is zero or negative: SHOULD be +/// None, never a guess. +/// ``` +pub fn even_parts(total: T, step: T, parts: &mut [T]) -> Option<()> { + let months = u32::try_from(parts.len()).ok().filter(|&m| m > 0)?; + let quotient = total.checked_div(T::from_u32(months)?)?; + let each = round_step(quotient, step, Rounding::HalfToEven)?; + for part in parts.iter_mut() { + *part = each; + } + plug_last(total, parts) +} diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index 027a52b2..6687c61e 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -441,8 +441,22 @@ impl Ledger { /// Register an amortization schedule. Returns its id. pub fn register_schedule(&mut self, new: NewSchedule) -> Result { - schedules::validate_schedule(&new, &self.chart)?; - self.replay_register_schedule(new) + self.register_schedule_under(new, schedules::ScheduleRounding::Cent) + } + + /// [`Self::register_schedule`] for a monthly_even schedule written + /// under `rounding` (D-72, BS-prepaid-4): the store registers new + /// schedules under the currency's minor unit once its books declare + /// the journal feature `schedule_minor_unit`. The plain + /// `register_schedule` is the cent rule, the rule of every schedule + /// before it. + pub fn register_schedule_under( + &mut self, + new: NewSchedule, + rounding: schedules::ScheduleRounding, + ) -> Result { + schedules::validate_schedule_under(&new, rounding, &self.chart)?; + self.replay_register_schedule_under(new, rounding) } /// [`Self::register_schedule`] without the total's range and minor-unit @@ -452,6 +466,17 @@ impl Ledger { pub fn replay_register_schedule( &mut self, new: NewSchedule, + ) -> Result { + self.replay_register_schedule_under(new, schedules::ScheduleRounding::Cent) + } + + /// [`Self::replay_register_schedule`] for a schedule the journal says + /// was written under `rounding` (`schedule.registered`'s `rounding`, + /// absent for every schedule before D-72). + pub fn replay_register_schedule_under( + &mut self, + new: NewSchedule, + rounding: schedules::ScheduleRounding, ) -> Result { schedules::validate_schedule_shape(&new, &self.chart)?; let id = self.next_schedule_id; @@ -469,6 +494,7 @@ impl Ledger { pl_account: new.pl_account, posted: Default::default(), convention: new.convention, + rounding, postings: Default::default(), }, ); diff --git a/crates/ledger-core/src/lib.rs b/crates/ledger-core/src/lib.rs index ec6579bc..74d2a3c4 100644 --- a/crates/ledger-core/src/lib.rs +++ b/crates/ledger-core/src/lib.rs @@ -102,7 +102,7 @@ pub use reports::{ }; pub use schedules::{ AmortizationSchedule, Frequency, NewRecurring, NewSchedule, RecurringEntry, RecurringId, - ScheduleConvention, ScheduleId, ScheduleKind, TemplateLine, + ScheduleConvention, ScheduleId, ScheduleKind, ScheduleRounding, TemplateLine, }; pub use shares::{PartyMember, PartyShare, Share}; pub use tax::{ diff --git a/crates/ledger-core/src/proofs/schedule.rs b/crates/ledger-core/src/proofs/schedule.rs index 93a5549e..ac674441 100644 --- a/crates/ledger-core/src/proofs/schedule.rs +++ b/crates/ledger-core/src/proofs/schedule.rs @@ -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(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::(), total); + assert_eq!(b.iter().sum::(), total); + assert_eq!(c.iter().sum::(), total); + assert_eq!(d.iter().sum::(), 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"); +} diff --git a/crates/ledger-core/src/schedules.rs b/crates/ledger-core/src/schedules.rs index 5d76e0c1..f267e85a 100644 --- a/crates/ledger-core/src/schedules.rs +++ b/crates/ledger-core/src/schedules.rs @@ -90,6 +90,79 @@ impl ScheduleConvention { } } +/// The unit an equal-months (monthly-even) schedule rounds each month to: +/// the rule it was written under (BS-prepaid-4, owner decision D-72). +/// +/// ```text +/// GOAL: a monthly-even schedule's months are whole units of its currency +/// (yen, not 33,333.33 yen), and a schedule written under the old +/// cent rule is never re-planned under a new one. +/// SOURCE: BS-prepaid-4 (new monthly-even schedules round to the +/// currency's minor unit, earlier ones keep the cent rule they +/// were written under), BS-prepaid-1 (months whole to the minor +/// unit), BS-entry-8 (what is journaled never moves); +/// plan/served.md D-72 (owner, 2026-11-08). +/// INVARIANTS: +/// 1. A schedule carries the rule it was written under, journaled on +/// its `schedule.registered` line as `"rounding": "minor_unit"`, +/// and nothing else decides it: not the books' later format, not the +/// currency, not the date. A line with no `rounding` is `Cent`, as +/// every schedule written before D-72 is, and replays exactly as it +/// was posted (the sequence position of the format feature is never +/// consulted: a flag survives a snapshot, a copy and a replay that +/// starts mid-journal; a position survives none of them). +/// 2. `Cent` is two places for every currency, replay-frozen. For a +/// currency with two places, `MinorUnit` gives the same plan +/// (the same call), so a dollar schedule never differs by rule. +/// 3. `MinorUnit` is the currency's ISO 4217 minor unit (`Currency:: +/// minor_units`: USD 0.01, JPY 1, KWD 0.001), and two places for a +/// code ISO gives none (gold, SDRs), as the daily plan does. +/// 4. Only `monthly_even` schedules carry it: a daily schedule always +/// rounds to the minor unit, and is written without the flag. +/// ``` +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ScheduleRounding { + /// Two places, whatever the currency: every schedule written before + /// D-72, and the default of [`crate::Ledger::register_schedule`]. + #[default] + Cent, + /// The currency's minor unit: a monthly-even schedule written after + /// the store's `schedule_minor_unit` feature. + MinorUnit, +} + +impl ScheduleRounding { + /// Its wire name: `cent` or `minor_unit`. + pub fn key(self) -> &'static str { + match self { + ScheduleRounding::Cent => "cent", + ScheduleRounding::MinorUnit => "minor_unit", + } + } + + /// The rule named `key`. + pub fn parse(key: &str) -> Option { + [Self::Cent, Self::MinorUnit] + .into_iter() + .find(|r| r.key() == key) + } + + /// True for [`ScheduleRounding::Cent`] (which the journal and the + /// serialized ledger leave unsaid, as every schedule before D-72 is). + pub fn is_cent(&self) -> bool { + *self == ScheduleRounding::Cent + } + + /// The decimal places each month is rounded to, for `currency`. + pub fn places(self, currency: crate::Currency) -> u32 { + match self { + ScheduleRounding::Cent => 2, + ScheduleRounding::MinorUnit => currency.minor_units().unwrap_or(2), + } + } +} + /// An amortization schedule. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AmortizationSchedule { @@ -119,6 +192,11 @@ pub struct AmortizationSchedule { /// before P3 serialize as they did. #[serde(default, skip_serializing_if = "ScheduleConvention::is_monthly_even")] pub convention: ScheduleConvention, + /// The unit a monthly_even schedule's months round to: the rule it was + /// written under ([`ScheduleRounding`]). Left unsaid when cent, so + /// books from before D-72 serialize as they did. + #[serde(default, skip_serializing_if = "ScheduleRounding::is_cent")] + pub rounding: ScheduleRounding, /// Every entry that ever posted each month, in order: a reversal of /// one un-posts its month, and reversing that reversal posts it again /// (Ledger::reverse_entry). Derived on replay, never serialized. @@ -163,13 +241,17 @@ pub fn month_end(d: NaiveDate) -> NaiveDate { pub const EXACT_LIMIT: Decimal = Decimal::from_parts(0xe400_0000, 0xdcc8_0cd2, 0x0052_b7d2, false, 0); -/// The schedule's monthly postings: (month-end date, amount). Equal -/// amounts to the cent, the last month absorbing rounding, so they sum to -/// the total exactly. +/// The schedule's monthly postings under the cent rule: (month-end date, +/// amount). Equal amounts to the cent, the last month absorbing rounding, +/// so they sum to the total exactly. The rule every schedule written +/// before D-72 replays under ([`ScheduleRounding::Cent`]); a schedule +/// written since rounds to its currency's minor unit +/// ([`amortization_plan_under`]). /// /// ```text /// INVARIANTS: -/// 1. The amounts sum to `total` exactly; all but the last are equal. +/// 1. The amounts sum to `total` exactly; all but the last are equal +/// (kernel::even_parts, at two places). /// 2. NEVER panics: a schedule an earlier version journaled whose months /// run past chrono's last day is refused with DateOutOfRange, and one /// whose amounts exact arithmetic can't hold with TooLargeToCompute @@ -179,6 +261,10 @@ pub const EXACT_LIMIT: Decimal = /// sum of them (none exceeds the total), fits Decimal's 28 significant /// digits, so INVARIANT 1 holds exactly; at it, Decimal's checked /// operations round instead of failing. +/// 4. Unchanged forever: the figures, and the scale they print at, are +/// exactly those every earlier version produced (a posted month's +/// replay compares journaled lines as text). `tests/schedules.rs` +/// checks it against a verbatim copy of the function before K-U5. /// ``` /// /// Replay is unaffected: a posted schedule month passed the line limit @@ -188,40 +274,112 @@ pub fn amortization_plan( total: Decimal, start: NaiveDate, months: u32, +) -> Result, LedgerError> { + plan_in_places(total, 2, start, months) +} + +/// The equal-months plan of `total` under `rounding`: the cent rule +/// ([`amortization_plan`]), or each month a whole number of the currency's +/// minor unit (¥100,000 over 3 months is ¥33,333, ¥33,333, ¥33,334). +/// A currency with two places gives the same plan under both rules. +/// +/// ```text +/// GOAL: an equal-months plan whose months are whole units of its +/// currency. +/// SOURCE: BS-prepaid-1, BS-prepaid-4 (D-72); the arithmetic and its +/// laws are kernel::even_parts (BS-prepaid-1, law 43). +/// INVARIANTS: +/// 1. The amounts sum to `total` exactly; all but the last are equal and +/// a whole multiple of the rule's unit. +/// 2. Under `Cent`, exactly `amortization_plan`; under `MinorUnit` at +/// two places, the same call, so the same figures. +/// 3. Never panics: the refusals are `amortization_plan`'s. +/// ``` +pub fn amortization_plan_under( + rounding: ScheduleRounding, + total: Money, + start: NaiveDate, + months: u32, +) -> Result, LedgerError> { + plan_in_places(total.amount, rounding.places(total.currency), start, months) +} + +/// The equal-months plan to `places` decimal places: the dates, and +/// `kernel::even_parts` for the amounts. +fn plan_in_places( + total: Decimal, + places: u32, + start: NaiveDate, + months: u32, ) -> Result, LedgerError> { let too_large = || LedgerError::TooLargeToCompute(format!("a {months}-month plan of {total}")); if total.abs() >= EXACT_LIMIT { return Err(too_large()); } - // Two places whatever the currency: the monthly-even plan's cent rule is - // replay-frozen, and moving it to the currency's minor unit is K-U5 - // (owner decision D-72), not this behaviour-preserving rounding unit. - let each = kernel::round_places( - total - .checked_div(Decimal::from(months)) - .ok_or_else(too_large)?, - 2, - kernel::Rounding::HalfToEven, - ) - .ok_or_else(too_large)?; let first = start .with_day(1) .ok_or(LedgerError::DateOutOfRange(start))?; - (0..months) + // Every month end first, so a plan running past chrono's last day is + // refused (DateOutOfRange) before a month is allocated. + let ends = (0..months) .map(|i| { - let month = first + first .checked_add_months(Months::new(i)) - .ok_or(LedgerError::DateOutOfRange(start))?; - let amount = if i + 1 == months { - each.checked_mul(Decimal::from(months - 1)) - .and_then(|before| total.checked_sub(before)) - .ok_or_else(too_large)? - } else { - each - }; - Ok((month_end(month), amount)) + .map(month_end) + .ok_or(LedgerError::DateOutOfRange(start)) }) - .collect() + .collect::, _>>()?; + let step = Decimal::try_from_i128_with_scale(1, places).map_err(|_| too_large())?; + let mut parts = vec![Decimal::ZERO; ends.len()]; + kernel::even_parts(total, step, &mut parts).ok_or_else(too_large)?; + present_as_rounded(&mut parts, total, places); + Ok(ends.into_iter().zip(parts).collect()) +} + +/// The scale the plan's figures print at: what `kernel::round_places` and +/// the plan's own subtraction gave every schedule before the kernel +/// computed it. `even_parts` rounds with `round_step`, which returns an +/// amount that is already a whole multiple of the step as it came (so +/// 0.250 stays 0.250) and a zero as a bare 0; the plan has always shown +/// such an amount at `places` places (0.25, 0.00), and a posted month's +/// replay compares its journaled lines as text, so the same figure must +/// print the same. The last month is `total` less the others, whose scale +/// is the wider of the two (or the total's own, when the others are zero). +/// Values never change: every rescale below is +/// to or from trailing zeros, which the debug assertions check. +/// +/// A one-month plan is its total, left as the kernel gives it. A zero +/// total is never registered (validate_schedule_shape), but the plan of +/// one prints as it always did: every month a bare 0 (the kernel's last +/// month is `0 - 0`, which `Decimal` prints as `-0`). +fn present_as_rounded(parts: &mut [Decimal], total: Decimal, places: u32) { + if total.is_zero() { + for part in parts.iter_mut() { + *part = Decimal::ZERO; + } + return; + } + let Some((last, rest)) = parts.split_last_mut() else { + return; + }; + let Some(&first) = rest.first() else { + return; + }; + let mut each = first; + if each.scale() > places || each.is_zero() { + each.rescale(places); + debug_assert_eq!(each, first, "rescaling an amount never changes it"); + } + // Subtracting a zero (a month that rounded to nothing) leaves the + // total as it was, scale included; any other subtrahend widens it. + if !each.is_zero() { + let before = *last; + last.rescale(total.scale().max(each.scale())); + debug_assert_eq!(*last, before, "rescaling an amount never changes it"); + } + for part in rest.iter_mut() { + *part = each; + } } /// The schedule's postings by the day: one per calendar month the span @@ -286,9 +444,22 @@ pub fn plan_for( total: Money, start: NaiveDate, months: u32, +) -> Result, LedgerError> { + plan_under(ScheduleRounding::Cent, convention, total, start, months) +} + +/// [`plan_for`] for a schedule written under `rounding`: the rule decides +/// only a monthly_even plan's months (a daily plan always rounds to the +/// currency's minor unit). +pub fn plan_under( + rounding: ScheduleRounding, + convention: ScheduleConvention, + total: Money, + start: NaiveDate, + months: u32, ) -> Result, LedgerError> { match convention { - ScheduleConvention::MonthlyEven => amortization_plan(total.amount, start, months), + ScheduleConvention::MonthlyEven => amortization_plan_under(rounding, total, start, months), ScheduleConvention::Daily => daily_plan(total, start, months), } } @@ -317,6 +488,18 @@ pub fn plan_for( /// BECAUSE such a month could never post. /// ``` pub fn validate_schedule(new: &NewSchedule, chart: &ChartOfAccounts) -> Result<(), LedgerError> { + validate_schedule_under(new, ScheduleRounding::Cent, chart) +} + +/// [`validate_schedule`] for a schedule that will be written under +/// `rounding` (the store's choice, by the journal feature +/// `schedule_minor_unit`): under `MinorUnit` a yen schedule's months are +/// whole yen, so ¥1,000 over 3 months (¥333, ¥333, ¥334) is accepted. +pub fn validate_schedule_under( + new: &NewSchedule, + rounding: ScheduleRounding, + chart: &ChartOfAccounts, +) -> Result<(), LedgerError> { validate_schedule_shape(new, chart)?; crate::calendar::check(new.start)?; let past_the_calendar = || { @@ -361,7 +544,7 @@ pub fn validate_schedule(new: &NewSchedule, chart: &ChartOfAccounts) -> Result<( } crate::ledger::check_minor_units(new.total)?; let currency = new.total.currency; - if let Some((_, fine)) = plan_for(new.convention, new.total, new.start, new.months)? + if let Some((_, fine)) = plan_under(rounding, new.convention, new.total, new.start, new.months)? .into_iter() .find(|(_, a)| crate::ledger::check_minor_units(Money::new(*a, currency)).is_err()) { @@ -428,7 +611,13 @@ impl AmortizationSchedule { /// [`daily_plan`]); refused, never a panic, for one that can't be /// computed. pub fn plan(&self) -> Result, LedgerError> { - plan_for(self.convention, self.total, self.start, self.months) + plan_under( + self.rounding, + self.convention, + self.total, + self.start, + self.months, + ) } /// The first day it covers: its start (daily), or the 1st of its start's @@ -650,6 +839,24 @@ mod tests { NaiveDate::from_ymd_opt(y, m, day).unwrap() } + /// A zero total's plan prints every month as a bare 0, as the cent + /// rule always has: never `-0` (the K-U5 review's probe found the last + /// month of a zero plan printed `-0`; a replayed month is compared as + /// text). + #[test] + fn a_zero_plan_prints_zero_every_month() { + for months in [1, 2, 3, 12] { + for scale in [0, 2, 5] { + let plan = amortization_plan(Decimal::new(0, scale), d(2026, 1, 1), months) + .expect("a zero total plans"); + assert!( + plan.iter().all(|(_, a)| a.to_string() == "0"), + "{months} months at scale {scale}: {plan:?}" + ); + } + } + } + #[test] fn plans_sum_exactly_and_land_on_month_ends() { let plan = amortization_plan(Decimal::new(100_000, 2), d(2026, 11, 15), 3).unwrap(); @@ -723,6 +930,7 @@ mod tests { pl_account: 2, posted: BTreeSet::new(), convention: ScheduleConvention::MonthlyEven, + rounding: ScheduleRounding::Cent, postings: BTreeMap::new(), }; assert!(s.due(NaiveDate::MAX).is_err()); diff --git a/crates/ledger-core/tests/kernel_bridge/schedule.rs b/crates/ledger-core/tests/kernel_bridge/schedule.rs index ba25ea35..c8ecc08d 100644 --- a/crates/ledger-core/tests/kernel_bridge/schedule.rs +++ b/crates/ledger-core/tests/kernel_bridge/schedule.rs @@ -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> { + 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> { + 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::>(), + 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::(), 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::(), 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::(), max28); +} diff --git a/crates/ledger-core/tests/schedule_minor_unit.rs b/crates/ledger-core/tests/schedule_minor_unit.rs new file mode 100644 index 00000000..3d75d502 --- /dev/null +++ b/crates/ledger-core/tests/schedule_minor_unit.rs @@ -0,0 +1,318 @@ +//! Equal-months schedules round to the currency's minor unit (K-U5, D-72, +//! BS-prepaid-4), and a schedule written before that keeps the cent rule. +//! +//! ```text +//! GOAL: a new monthly-even schedule's months are whole units of its +//! currency, while every schedule written under the cent rule +//! replays to the same figures, printed the same way. +//! SOURCE: BS-prepaid-1, BS-prepaid-4, BS-entry-8; plan/served.md D-72. +//! INVARIANTS: +//! 1. The cent rule (`amortization_plan`) is exactly what every earlier +//! version computed: the same amounts at the same printed scale, +//! checked against a verbatim copy of the function as it was. +//! 2. A currency with two places gets the same plan under both rules. +//! 3. Under the minor-unit rule every month is a whole multiple of the +//! currency's unit and the months sum to the total. +//! SCENARIOS: +//! 1. IF 100,000 yen over 3 months, minor unit: SHOULD be 33,333, +//! 33,333, 33,334 (the cent rule: 33,333.33, 33,333.33, 33,333.34). +//! 2. IF 1.000 dinar over 3 months, minor unit: SHOULD be 0.333, 0.333, +//! 0.334 (the cent rule: 0.33, 0.33, 0.340). +//! ``` + +use chrono::{Datelike, Months, NaiveDate}; +use ledger_core::schedules::{ + ScheduleRounding, amortization_plan, amortization_plan_under, month_end, +}; +use ledger_core::{ + AccountType, Currency, Ledger, LedgerError, Money, NewSchedule, ScheduleConvention, + ScheduleKind, kernel, +}; +use proptest::prelude::*; +use rust_decimal::Decimal; + +fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() +} + +fn dec(s: &str) -> Decimal { + s.parse().unwrap() +} + +fn kwd() -> Currency { + Currency::new("KWD").unwrap() +} + +fn amounts(plan: &[(NaiveDate, Decimal)]) -> Vec { + plan.iter().map(|(_, a)| a.to_string()).collect() +} + +/// `amortization_plan` verbatim as every version before K-U5 had it +/// (`round_places` at two places, the last month the total less +/// `each x (months - 1)`): the oracle for "the cent rule never moves". +fn legacy_plan( + total: Decimal, + start: NaiveDate, + months: u32, +) -> Result, LedgerError> { + let too_large = || LedgerError::TooLargeToCompute(format!("a {months}-month plan of {total}")); + let each = kernel::round_places( + total + .checked_div(Decimal::from(months)) + .ok_or_else(too_large)?, + 2, + kernel::Rounding::HalfToEven, + ) + .ok_or_else(too_large)?; + let first = start + .with_day(1) + .ok_or(LedgerError::DateOutOfRange(start))?; + (0..months) + .map(|i| { + let month = first + .checked_add_months(Months::new(i)) + .ok_or(LedgerError::DateOutOfRange(start))?; + let amount = if i + 1 == months { + each.checked_mul(Decimal::from(months - 1)) + .and_then(|before| total.checked_sub(before)) + .ok_or_else(too_large)? + } else { + each + }; + Ok((month_end(month), amount)) + }) + .collect() +} + +/// Same dates, same values, and the same text for every amount: a posted +/// month's replay compares its journaled lines as text. +fn assert_same_plan( + got: &[(NaiveDate, Decimal)], + want: &[(NaiveDate, Decimal)], + what: impl std::fmt::Display, +) { + assert_eq!(got.len(), want.len(), "{what}: months"); + for (g, w) in got.iter().zip(want) { + assert_eq!(g.0, w.0, "{what}: date"); + assert_eq!(g.1.to_string(), w.1.to_string(), "{what}: amount text"); + } +} + +/// SCENARIOS 1 and 2, recomputed by hand. +/// +/// 100,000 yen over 3: 100,000 / 3 = 33,333.33..., to a whole yen 33,333; +/// the last month takes 100,000 - 2 x 33,333 = 33,334. 1.000 dinar over 3: +/// 0.3333... to a thousandth 0.333; the last 1.000 - 0.666 = 0.334. A tie +/// goes to the even multiple: 5 yen over 2 is 2.5, to 2 (the last takes 3); +/// 7 over 2 is 3.5, to 4 (the last takes 3, less than the others). +#[test] +fn a_jpy_and_a_kwd_plan_are_whole_units() { + let start = d(2027, 1, 1); + let yen = |a: &str| Money::new(dec(a), Currency::JPY); + let dinar = |a: &str| Money::new(dec(a), kwd()); + let minor = ScheduleRounding::MinorUnit; + let plan = amortization_plan_under(minor, yen("100000"), start, 3).unwrap(); + assert_eq!(amounts(&plan), ["33333", "33333", "33334"]); + assert_eq!( + plan.iter().map(|(m, _)| *m).collect::>(), + [d(2027, 1, 31), d(2027, 2, 28), d(2027, 3, 31)] + ); + let plan = amortization_plan_under(minor, dinar("1.000"), start, 3).unwrap(); + assert_eq!(amounts(&plan), ["0.333", "0.333", "0.334"]); + let plan = amortization_plan_under(minor, yen("5"), start, 2).unwrap(); + assert_eq!(amounts(&plan), ["2", "3"]); + let plan = amortization_plan_under(minor, yen("7"), start, 2).unwrap(); + assert_eq!(amounts(&plan), ["4", "3"]); + // The cent rule, which every schedule before D-72 replays under, is + // unchanged: ¥33,333.33 months no yen account can post. + let cent = amortization_plan(dec("100000"), start, 3).unwrap(); + assert_eq!(amounts(¢), ["33333.33", "33333.33", "33333.34"]); + let cent = amortization_plan(dec("1.000"), start, 3).unwrap(); + assert_eq!(amounts(¢), ["0.33", "0.33", "0.340"]); +} + +/// Prints the numbers the change moves (read with --nocapture): the +/// verification protocol's "show the figures". +#[test] +fn print_the_plans_before_and_after() { + let start = d(2027, 1, 1); + for (label, money) in [ + ("JPY 100000", Money::new(dec("100000"), Currency::JPY)), + ("KWD 1.000", Money::new(dec("1.000"), kwd())), + ("USD 1000.00", Money::new(dec("1000.00"), Currency::USD)), + ] { + let before = amortization_plan(money.amount, start, 3).unwrap(); + let after = amortization_plan_under(ScheduleRounding::MinorUnit, money, start, 3).unwrap(); + println!("{label} over 3 months"); + println!(" cent rule (before): {:?}", amounts(&before)); + println!(" minor unit (after): {:?}", amounts(&after)); + } +} + +/// INVARIANT 1 and 2 over a large range: totals of every scale 0 to 5, +/// months 1 to 40. The cent rule equals the legacy copy value for value +/// and text for text, and a two-place currency gets the same plan under +/// the minor-unit rule (the same call, so this is a check of the claim, +/// not its proof). +#[test] +fn the_cent_rule_is_unchanged_and_usd_is_the_same_under_both_rules() { + let start = d(2027, 3, 1); + let mut checked = 0u64; + for scale in 0..=5u32 { + for mantissa in (1..=1_200i64).chain([9_999, 10_000, 99_999, 123_456_789, 4_000_000_007]) { + let total = Decimal::new(mantissa, scale); + for months in (1..=40u32).chain([360, 600]) { + let want = legacy_plan(total, start, months).unwrap(); + let got = amortization_plan(total, start, months).unwrap(); + assert_same_plan(&got, &want, format!("{total} over {months}")); + if scale <= 2 { + let usd = Money::new(total, Currency::USD); + let under = + amortization_plan_under(ScheduleRounding::MinorUnit, usd, start, months) + .unwrap(); + assert_same_plan(&under, &want, format!("USD {total} over {months}")); + } + checked += 1; + } + } + } + assert!(checked > 300_000, "{checked}"); +} + +/// Under the minor-unit rule, for every 0-, 2-, 3- and 4-place currency: +/// the months sum to the total, all but the last are equal, and each is a +/// whole multiple of the unit. +#[test] +fn the_minor_unit_rule_gives_whole_units_that_sum_to_the_total() { + let start = d(2027, 1, 1); + for (currency, places) in [ + (Currency::JPY, 0u32), + (Currency::USD, 2), + (kwd(), 3), + (Currency::new("CLF").unwrap(), 4), + ] { + for units in (1..=2_000i64).chain([99_991, 1_000_003]) { + let total = Decimal::new(units, places); + for months in 1..=24u32 { + let plan = amortization_plan_under( + ScheduleRounding::MinorUnit, + Money::new(total, currency), + start, + months, + ) + .unwrap(); + let sum: Decimal = plan.iter().map(|(_, a)| *a).sum(); + assert_eq!(sum, total, "{currency} {total} over {months}"); + let each = plan[0].1; + for (_, a) in &plan[..plan.len() - 1] { + assert_eq!(*a, each); + } + for (_, a) in &plan { + assert!(a.normalize().scale() <= places, "{currency} {a}"); + assert!(a.scale() <= places, "{currency} {a} prints past its unit"); + } + } + } + } +} + +proptest! { + /// The cent rule is the legacy rule for any total below the exact + /// limit, at any scale up to 8, and any number of months: values and + /// printed text. + #[test] + fn prop_the_cent_rule_is_the_legacy_rule( + mantissa in 1i128..=99_999_999_999_999_999_999_999_999i128, + scale in 0u32..=8, + months in 1u32..=600, + ) { + let total = Decimal::try_from_i128_with_scale(mantissa, scale).unwrap(); + prop_assume!(total < Decimal::from_i128_with_scale(10i128.pow(25), 0)); + let start = d(2027, 1, 1); + let want = legacy_plan(total, start, months).unwrap(); + let got = amortization_plan(total, start, months).unwrap(); + assert_same_plan(&got, &want, format!("{total} over {months}")); + } +} + +fn ledger_in(currency: Currency) -> (Ledger, u64, u64) { + let mut l = Ledger::new(currency); + let prepaid = l + .add_account("1300", "Prepaid", AccountType::Asset, None, false) + .unwrap(); + let insurance = l + .add_account("6300", "Insurance", AccountType::Expense, None, false) + .unwrap(); + (l, prepaid, insurance) +} + +fn monthly_even(total: Money, prepaid: u64, expense: u64) -> NewSchedule { + NewSchedule { + description: "Insurance".into(), + kind: ScheduleKind::PrepaidExpense, + total, + start: d(2027, 1, 1), + months: 3, + balance_account: prepaid, + pl_account: expense, + convention: ScheduleConvention::MonthlyEven, + } +} + +/// The two registrations side by side: the plain one (the cent rule) +/// still refuses ¥1,000 over 3 months, a schedule registered under the +/// minor-unit rule takes it, plans ¥333, ¥333, ¥334 and carries the rule. +#[test] +fn a_schedule_carries_the_rule_it_was_written_under() { + let yen = |a: &str| Money::new(dec(a), Currency::JPY); + let (mut l, prepaid, expense) = ledger_in(Currency::JPY); + match l.register_schedule(monthly_even(yen("1000"), prepaid, expense)) { + Err(LedgerError::InvalidSchedule(m)) => assert!(m.contains("333.33"), "{m}"), + other => panic!("{other:?}"), + } + let id = l + .register_schedule_under( + monthly_even(yen("1000"), prepaid, expense), + ScheduleRounding::MinorUnit, + ) + .unwrap(); + let s = l.get_schedule(id).unwrap(); + assert_eq!(s.rounding, ScheduleRounding::MinorUnit); + assert_eq!(amounts(&s.plan().unwrap()), ["333", "333", "334"]); + for (m, _) in s.due(d(2027, 12, 31)).unwrap() { + l.post_schedule_month(id, m).unwrap(); + } + assert_eq!(l.get_schedule(id).unwrap().remaining().unwrap(), dec("0")); + // A schedule written the old way, in the same books, still plans in + // cents: a dollar-sized yen total that divides evenly. + let old = l + .register_schedule(monthly_even(yen("900"), prepaid, expense)) + .unwrap(); + let s = l.get_schedule(old).unwrap(); + assert_eq!(s.rounding, ScheduleRounding::Cent); + assert_eq!(amounts(&s.plan().unwrap()), ["300", "300", "300"]); +} + +/// The rule is journaled only when it isn't the cent rule: a serialized +/// ledger from before D-72 reads back as the cent rule, and a cent +/// schedule serializes exactly as it did (no `rounding` key). +#[test] +fn the_cent_rule_is_left_unsaid_in_a_serialized_ledger() { + let (mut l, prepaid, expense) = ledger_in(Currency::USD); + let usd = |a: &str| Money::new(dec(a), Currency::USD); + let old = l + .register_schedule(monthly_even(usd("1000.00"), prepaid, expense)) + .unwrap(); + let new = l + .register_schedule_under( + monthly_even(usd("1000.00"), prepaid, expense), + ScheduleRounding::MinorUnit, + ) + .unwrap(); + let old_json = serde_json::to_value(l.get_schedule(old).unwrap()).unwrap(); + let new_json = serde_json::to_value(l.get_schedule(new).unwrap()).unwrap(); + assert!(old_json.get("rounding").is_none(), "{old_json}"); + assert_eq!(new_json["rounding"], "minor_unit"); + let back: ledger_core::AmortizationSchedule = serde_json::from_value(old_json).unwrap(); + assert_eq!(back.rounding, ScheduleRounding::Cent); +} diff --git a/crates/ledger-mcp/handbook/format-upgrade.md b/crates/ledger-mcp/handbook/format-upgrade.md index 54026457..5eeef693 100644 --- a/crates/ledger-mcp/handbook/format-upgrade.md +++ b/crates/ledger-mcp/handbook/format-upgrade.md @@ -8,4 +8,4 @@ - After the upgrade an older version of wanderbooks can't open these books; the backup made first keeps them as they were. Going back is the owner's choice, never yours. - This upgrade is `documents_v2`: invoice numbers, terms and line accounts (S4), sent records (S5), payments that settle several documents with early-payment discounts and a processor's fee (S6), and write-offs (S7). Until it is given, those writes are refused and everything else works as before. -- The journal features an upgrade can add: `members_cumulative`, `account_renamed`, `require_tax_category`, `tax_categories_gain_exempt`, `disposal_before_service`, `depreciation_catch_up`, `party_creditors`, `payment_instruments`, `vendor_1099_decisions`, `schedule_convention`, `month_reposting`, `asset_basis`, `projects`, `document_line_projects`, `document_standing`, `documents_v2`, `attachment_text` (P6: a filed file's extracted text, what a human annotated of it, and the entries a payment settles), `drafts_v2` (P4: a draft's state, awaiting its evidence, and a discarded draft), and `source_revisions` (P5: correcting who decided a convention, a decision or an open item, and when). All are declared at once; a version that doesn't know one stops at the declaration instead of misreading the books. +- The journal features an upgrade can add: `members_cumulative`, `account_renamed`, `require_tax_category`, `tax_categories_gain_exempt`, `disposal_before_service`, `depreciation_catch_up`, `party_creditors`, `payment_instruments`, `vendor_1099_decisions`, `schedule_convention`, `schedule_minor_unit` (K-U5: a new equal-months schedule's months are whole units of its currency, whole yen or thousandths of a dinar, where the cent rule gave two places for every currency; schedules written before keep their rule), `month_reposting`, `asset_basis`, `projects`, `document_line_projects`, `document_standing`, `documents_v2`, `attachment_text` (P6: a filed file's extracted text, what a human annotated of it, and the entries a payment settles), `drafts_v2` (P4: a draft's state, awaiting its evidence, and a discarded draft), and `source_revisions` (P5: correcting who decided a convention, a decision or an open item, and when). All are declared at once; a version that doesn't know one stops at the declaration instead of misreading the books. diff --git a/crates/ledger-package/Cargo.toml b/crates/ledger-package/Cargo.toml index f1b1fde4..a6e5cea5 100644 --- a/crates/ledger-package/Cargo.toml +++ b/crates/ledger-package/Cargo.toml @@ -21,7 +21,7 @@ zip = "9.0.1" workspace = true [dev-dependencies] -bookspec-checker = { git = "https://git.swaits.com/swaits/bookspec", rev = "c597c8f845377d9eb868f0f4486759baf16eb5ea" } +bookspec-checker = { git = "https://git.swaits.com/swaits/bookspec", rev = "2b3b6c904781efc3f9ead71998a61f01efdeeadd" } proptest = "1" tempfile = "3" toml = "1" diff --git a/crates/ledger-store/src/format.rs b/crates/ledger-store/src/format.rs index f6230dc1..a0faf19a 100644 --- a/crates/ledger-store/src/format.rs +++ b/crates/ledger-store/src/format.rs @@ -55,6 +55,7 @@ pub const KNOWN_FEATURES: &[&str] = &[ VENDOR_1099_DECISIONS, MONTH_REPOSTING, SCHEDULE_CONVENTION, + SCHEDULE_MINOR_UNIT, ASSET_BASIS, TAX_CATEGORIES_GAIN_EXEMPT, DISPOSAL_BEFORE_SERVICE, @@ -167,6 +168,18 @@ pub const MONTH_REPOSTING: &str = "month_reposting"; /// months (P3 defect 9, plan/served.md D-11). pub const SCHEDULE_CONVENTION: &str = "schedule_convention"; +/// Feature: `schedule.registered` carries `rounding` (`minor_unit`): a +/// monthly_even schedule written after this feature rounds each month to +/// its currency's minor unit (a yen schedule in whole yen, a dinar one in +/// thousandths); one with no `rounding` is the cent rule, two places for +/// every currency, as every schedule before it is (BS-prepaid-4, D-72). +/// An older version would read the schedule under the cent rule and +/// refuse its first month as a posting that doesn't match its plan, or, +/// replaying a month it can derive, post ¥33,333.33 where the books say +/// ¥33,333. The flag rides on the schedule, never on where the feature +/// was declared: a schedule written before it replays as it was posted. +pub const SCHEDULE_MINOR_UNIT: &str = "schedule_minor_unit"; + /// Feature: `asset.basis_set`, a new event type: an asset's basis facts /// with the value at contribution and the §704(c) method (P3, defect 13). pub const ASSET_BASIS: &str = "asset_basis"; @@ -1088,6 +1101,43 @@ mod tests { assert_eq!(up.adds(), vec!["the journal feature audits"]); } + /// The version before K-U5 (every feature but `schedule_minor_unit`) + /// stops at the declaration as newer, so it never reads a ¥33,333 + /// month under the cent rule (and refuses, or posts ¥33,333.33 where + /// the books say ¥33,333); and a `schedule.registered` naming a + /// rounding this version doesn't know is newer, never corrupt + /// (BS-prepaid-4, D-72, BS-format-1). Books that declared every + /// earlier feature still wait for it. + #[test] + fn schedule_minor_unit_is_its_own_feature() { + assert!(KNOWN_FEATURES.contains(&SCHEDULE_MINOR_UNIT)); + let before: Vec<&str> = KNOWN_FEATURES + .iter() + .copied() + .filter(|f| *f != SCHEDULE_MINOR_UNIT) + .collect(); + let l = line( + FORMAT_SET, + json!({"format": 2, "features": [SCHEDULE_CONVENTION, SCHEDULE_MINOR_UNIT]}), + ); + match declared_knowing(&l, &before) { + Err(StoreError::NewerJournal { need, .. }) => { + assert_eq!(need, "journal features schedule_minor_unit") + } + other => panic!("expected NewerJournal, got {other:?}"), + } + let older = JournalFormat { + format: 2, + features: before.iter().map(|f| f.to_string()).collect(), + }; + assert!(matches!( + older.require_feature(SCHEDULE_MINOR_UNIT), + Err(StoreError::FormatUpgradePending { .. }) + )); + let up = older.upgrade().expect("waits for it"); + assert_eq!(up.adds(), vec!["the journal feature schedule_minor_unit"]); + } + /// This version's format: the newest it reads, every feature it /// knows, each once, sorted (what new books and an upgrade declare). #[test] diff --git a/crates/ledger-store/src/store.rs b/crates/ledger-store/src/store.rs index 2e324fb6..377652fc 100644 --- a/crates/ledger-store/src/store.rs +++ b/crates/ledger-store/src/store.rs @@ -4961,31 +4961,68 @@ impl Store { /// nothing, in books that haven't declared it): an older version reads /// every schedule as equal months, and would refuse a daily one's /// postings as wrong (rather than as newer). + /// + /// A monthly_even schedule's months round to its currency's minor + /// unit in books that declared `schedule_minor_unit` (D-72, + /// BS-prepaid-4), which the journal records as `"rounding": + /// "minor_unit"` on the schedule itself; in books that haven't it is + /// the cent rule, as before, and nothing new is written. + /// + /// ```text + /// GOAL: a new monthly-even schedule's months are whole units of its + /// currency, and what an earlier version journaled never moves. + /// SOURCE: BS-prepaid-4, BS-format-1, BS-entry-8; D-72 (owner, + /// 2026-11-08). + /// INVARIANTS: + /// 1. The rule is a fact of the books when the schedule is written: + /// minor unit exactly when the books declared the feature and the + /// convention is monthly_even, and the flag is journaled with the + /// schedule, so replay never consults the feature's position. + /// 2. A schedule journaling the flag requires the feature + /// (`ensure_feature`): an older version stops at the declaration, + /// never at the schedule. + /// 3. Books without the feature write exactly the line they always + /// did: no `rounding` key. + /// SCENARIOS: + /// 1. IF the books declared the feature and ¥100,000 is spread over + /// 3 equal months: SHOULD plan ¥33,333, ¥33,333, ¥33,334. + /// 2. IF they haven't: SHOULD refuse it as a month finer than a yen + /// (¥33,333.33), as before, until the owner's upgrade. + /// ``` pub fn register_schedule( &mut self, new: ledger_core::NewSchedule, ) -> Result { - self.rehearse(|l| l.register_schedule(new.clone()))?; - ledger_core::schedules::validate_schedule(&new, self.ledger.chart())?; + let rounding = if new.convention == ledger_core::ScheduleConvention::MonthlyEven + && self.format.has_feature(crate::format::SCHEDULE_MINOR_UNIT) + { + ledger_core::ScheduleRounding::MinorUnit + } else { + ledger_core::ScheduleRounding::Cent + }; + self.rehearse(|l| l.register_schedule_under(new.clone(), rounding))?; + ledger_core::schedules::validate_schedule_under(&new, rounding, self.ledger.chart())?; let id = self.ledger.next_schedule_id(); if new.convention == ledger_core::ScheduleConvention::Daily { self.ensure_feature(crate::format::SCHEDULE_CONVENTION)?; } - let line = self.append_journal( - "schedule.registered", - json!({ - "id": id, - "description": new.description, - "kind": serde_json::to_value(new.kind)?, - "total": {"amount": new.total.amount.to_string(), "currency": new.total.currency.code()}, - "start": new.start.to_string(), - "months": new.months, - "balance_account": new.balance_account, - "pl_account": new.pl_account, - "convention": new.convention.key(), - }), - )?; - let got = self.ledger.register_schedule(new)?; + let mut payload = json!({ + "id": id, + "description": new.description, + "kind": serde_json::to_value(new.kind)?, + "total": {"amount": new.total.amount.to_string(), "currency": new.total.currency.code()}, + "start": new.start.to_string(), + "months": new.months, + "balance_account": new.balance_account, + "pl_account": new.pl_account, + "convention": new.convention.key(), + }); + if !rounding.is_cent() { + self.ensure_feature(crate::format::SCHEDULE_MINOR_UNIT)?; + payload["rounding"] = json!(rounding.key()); + } + let line = self.append_journal("schedule.registered", payload)?; + let got = self.ledger.register_schedule_under(new, rounding)?; debug_assert_eq!(got, id); apply_line_to_sqlite(&self.conn, &line)?; Ok(id) @@ -7414,16 +7451,36 @@ fn replay_line( )); } }; - let got = ledger.replay_register_schedule(ledger_core::NewSchedule { - description: get_str(p, "description")?.to_string(), - kind: serde_json::from_value(p["kind"].clone())?, - total: parse_money(p, "total")?, - start: parse_date(get_str(p, "start")?)?, - months: get_u64(p, "months")? as u32, - balance_account: get_u64(p, "balance_account")?, - pl_account: get_u64(p, "pl_account")?, - convention, - })?; + // No rounding (every schedule before D-72): the cent rule, as + // it was posted. The rule is the schedule's own, never the + // books' later format. A rule this version doesn't know is + // newer, never corrupt (BS-format-1). + let rounding = match p.get("rounding") { + None | Some(Value::Null) => ledger_core::ScheduleRounding::Cent, + Some(Value::String(r)) => { + ledger_core::ScheduleRounding::parse(r).ok_or_else(|| { + crate::format::newer_content(line, format!("the schedule rounding {r}")) + })? + } + Some(_) => { + return Err(StoreError::JournalCorrupt( + "schedule.registered rounding".into(), + )); + } + }; + let got = ledger.replay_register_schedule_under( + ledger_core::NewSchedule { + description: get_str(p, "description")?.to_string(), + kind: serde_json::from_value(p["kind"].clone())?, + total: parse_money(p, "total")?, + start: parse_date(get_str(p, "start")?)?, + months: get_u64(p, "months")? as u32, + balance_account: get_u64(p, "balance_account")?, + pl_account: get_u64(p, "pl_account")?, + convention, + }, + rounding, + )?; if got != want { return Err(StoreError::ReplayMismatch(format!( "schedule id: journal says {want}, replay got {got}" diff --git a/crates/ledger-store/tests/schedule_minor_unit.rs b/crates/ledger-store/tests/schedule_minor_unit.rs new file mode 100644 index 00000000..5cd33940 --- /dev/null +++ b/crates/ledger-store/tests/schedule_minor_unit.rs @@ -0,0 +1,288 @@ +//! A new monthly-even schedule rounds to its currency's minor unit; one +//! written before the journal feature `schedule_minor_unit` keeps the +//! cent rule on replay (K-U5, BS-prepaid-4, D-72). +//! +//! ```text +//! GOAL: a yen schedule's months are whole yen, and what an earlier +//! version journaled never moves. +//! SOURCE: BS-prepaid-4, BS-format-1, BS-entry-8; plan/served.md D-72 +//! (owner, 2026-11-08). +//! INVARIANTS: +//! 1. In books that declared the feature, a monthly_even schedule's +//! line carries `"rounding": "minor_unit"` and its months are whole +//! units of its currency. +//! 2. In books that haven't, nothing new is written: the line has no +//! `rounding`, the plan is the cent rule's, and a month finer than +//! the currency's unit is refused as before. +//! 3. A schedule's rule is its own: books upgraded after a cent-rule +//! schedule was written replay it, and post its months, under the +//! cent rule. +//! 4. A reader that doesn't know the feature stops at its declaration +//! as newer books (format.rs's schedule_minor_unit_is_its_own_feature). +//! ``` + +use chrono::NaiveDate; +use ledger_core::{ + AccountType, Currency, Money, NewSchedule, ScheduleConvention, ScheduleKind, ScheduleRounding, +}; +use ledger_store::format::{SCHEDULE_MINOR_UNIT, current}; +use ledger_store::{JOURNAL_FILE, Store, StoreError}; +use rust_decimal::Decimal; +use serde_json::Value; +use std::path::Path; + +fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() +} + +fn kwd() -> Currency { + Currency::new("KWD").unwrap() +} + +fn amount(s: &str, c: Currency) -> Money { + Money::new(s.parse::().unwrap(), c) +} + +fn plan_text(store: &Store, id: u64) -> Vec { + store + .ledger() + .get_schedule(id) + .unwrap() + .plan() + .unwrap() + .iter() + .map(|(_, a)| a.to_string()) + .collect() +} + +/// The journal's `schedule.registered` payloads, in order. +fn registered(dir: &Path) -> Vec { + std::fs::read_to_string(dir.join(JOURNAL_FILE)) + .unwrap() + .lines() + .map(|l| serde_json::from_str::(l).unwrap()) + .filter(|l| l["type"] == "schedule.registered") + .map(|l| l["payload"].clone()) + .collect() +} + +fn books(dir: &Path, currency: Currency, with_feature: bool) -> (Store, u64, u64) { + let mut format = current(); + if !with_feature { + format.features.retain(|f| f != SCHEDULE_MINOR_UNIT); + } + let mut s = Store::create_in_format(dir, currency, &format).unwrap(); + let prepaid = s + .add_account("1300", "Prepaid", AccountType::Asset, None, false) + .unwrap(); + let expense = s + .add_account("6300", "Insurance", AccountType::Expense, None, false) + .unwrap(); + (s, prepaid, expense) +} + +fn schedule(total: Money, prepaid: u64, expense: u64) -> NewSchedule { + NewSchedule { + description: "Insurance".into(), + kind: ScheduleKind::PrepaidExpense, + total, + start: d(2027, 1, 1), + months: 3, + balance_account: prepaid, + pl_account: expense, + convention: ScheduleConvention::MonthlyEven, + } +} + +/// INVARIANT 1, by hand: 100,000 yen over 3 is 33,333.33..., to the yen +/// 33,333, the last month 100,000 - 66,666 = 33,334; 1.000 dinar is 0.333, +/// 0.333, 0.334. The line carries the rule, every month posts whole units, +/// and the books replay on reopening (the replay compares each posted +/// line as text). +#[test] +fn new_books_round_a_yen_and_a_dinar_schedule_to_the_unit() { + for (currency, total, want) in [ + (Currency::JPY, "100000", ["33333", "33333", "33334"]), + (kwd(), "1.000", ["0.333", "0.333", "0.334"]), + ] { + let dir = tempfile::tempdir().unwrap(); + let (mut s, prepaid, expense) = books(dir.path(), currency, true); + let id = s + .register_schedule(schedule(amount(total, currency), prepaid, expense)) + .unwrap(); + assert_eq!(plan_text(&s, id), want); + assert_eq!( + s.ledger().get_schedule(id).unwrap().rounding, + ScheduleRounding::MinorUnit + ); + let line = ®istered(dir.path())[0]; + assert_eq!(line["rounding"], "minor_unit"); + assert_eq!(line["convention"], "monthly_even"); + assert_eq!(s.run_schedules(d(2027, 12, 31)).unwrap().len(), 3); + s.verify().unwrap(); + let ledger_before = s.ledger().clone(); + drop(s); + let reopened = Store::open(dir.path()).unwrap(); + assert_eq!(reopened.ledger(), &ledger_before); + assert_eq!(plan_text(&reopened, id), want); + reopened.verify().unwrap(); + } +} + +/// A daily schedule is written as it always was: no `rounding`. +#[test] +fn a_daily_schedule_carries_no_rounding() { + let dir = tempfile::tempdir().unwrap(); + let (mut s, prepaid, expense) = books(dir.path(), Currency::JPY, true); + s.register_schedule(NewSchedule { + convention: ScheduleConvention::Daily, + ..schedule(amount("100000", Currency::JPY), prepaid, expense) + }) + .unwrap(); + assert!(registered(dir.path())[0].get("rounding").is_none()); +} + +/// INVARIANT 2: books that haven't declared the feature (waiting for the +/// owner's upgrade) keep writing and planning as before: a yen schedule +/// whose months aren't whole yen is refused, a schedule that divides +/// evenly is taken without a `rounding`, and nothing journals the feature +/// uninvited. +#[test] +fn books_without_the_feature_keep_the_cent_rule_and_write_nothing_new() { + let dir = tempfile::tempdir().unwrap(); + let (mut s, prepaid, expense) = books(dir.path(), Currency::JPY, false); + let head = s.head(); + match s.register_schedule(schedule(amount("1000", Currency::JPY), prepaid, expense)) { + Err(StoreError::Ledger(e)) => assert!(e.to_string().contains("333.33"), "{e}"), + other => panic!("expected a refusal, got {other:?}"), + } + assert_eq!(s.head(), head, "a refusal journals nothing"); + let id = s + .register_schedule(schedule(amount("900", Currency::JPY), prepaid, expense)) + .unwrap(); + assert_eq!(plan_text(&s, id), ["300", "300", "300"]); + assert_eq!( + s.ledger().get_schedule(id).unwrap().rounding, + ScheduleRounding::Cent + ); + assert!(registered(dir.path())[0].get("rounding").is_none()); +} + +/// INVARIANT 3 and the replay test: a dinar schedule written before the +/// feature plans 0.33, 0.33, 0.340 (the cent rule; each a valid dinar +/// amount) and posts its first month at that figure. After the owner's +/// upgrade, the same books replay to the same plan and the same posted +/// line; the old schedule still posts its other months at the cent rule's +/// figures, while a schedule written after the upgrade gets 0.333, 0.333, +/// 0.334. +#[test] +fn a_schedule_written_before_the_feature_replays_to_the_same_plan_after_it() { + let dir = tempfile::tempdir().unwrap(); + let (mut s, prepaid, expense) = books(dir.path(), kwd(), false); + let old = s + .register_schedule(schedule(amount("1.000", kwd()), prepaid, expense)) + .unwrap(); + let before = plan_text(&s, old); + assert_eq!(before, ["0.33", "0.33", "0.340"]); + s.post_schedule_month(old, d(2027, 1, 31)).unwrap(); + let first_month = s + .ledger() + .posted_entries() + .last() + .unwrap() + .lines() + .iter() + .map(|l| l.amount.amount.to_string()) + .collect::>(); + assert_eq!(first_month, ["0.33", "0.33"]); + + assert!(s.upgrade_format().unwrap().is_some()); + assert!(s.journal_format().has_feature(SCHEDULE_MINOR_UNIT)); + assert_eq!(plan_text(&s, old), before, "the upgrade moves no plan"); + drop(s); + + // Replay from the journal, as a fresh process does. + let mut s = Store::open(dir.path()).unwrap(); + s.verify().unwrap(); + let schedule_old = s.ledger().get_schedule(old).unwrap(); + assert_eq!(schedule_old.rounding, ScheduleRounding::Cent); + assert_eq!(plan_text(&s, old), before, "replay keeps the cent rule"); + let replayed = s + .ledger() + .posted_entries() + .last() + .unwrap() + .lines() + .iter() + .map(|l| l.amount.amount.to_string()) + .collect::>(); + assert_eq!(replayed, first_month, "the posted line is as it was"); + + // The rest of the old schedule posts at the cent rule's figures, and a + // new one, in the same books, at the dinar's. + s.post_schedule_month(old, d(2027, 2, 28)).unwrap(); + s.post_schedule_month(old, d(2027, 3, 31)).unwrap(); + let new = s + .register_schedule(schedule(amount("1.000", kwd()), prepaid, expense)) + .unwrap(); + assert_eq!(plan_text(&s, new), ["0.333", "0.333", "0.334"]); + assert_eq!( + s.ledger().get_schedule(new).unwrap().rounding, + ScheduleRounding::MinorUnit + ); + let lines = registered(dir.path()); + assert!(lines[0].get("rounding").is_none()); + assert_eq!(lines[1]["rounding"], "minor_unit"); + s.verify().unwrap(); + drop(s); + let again = Store::open(dir.path()).unwrap(); + assert_eq!(plan_text(&again, old), before); + assert_eq!(plan_text(&again, new), ["0.333", "0.333", "0.334"]); + again.verify().unwrap(); +} + +/// A US-dollar schedule is the same under both rules, in every book: +/// written before or after the feature, it plans the same figures. +#[test] +fn a_dollar_schedule_plans_the_same_in_old_and_new_books() { + let plan_in = |with_feature: bool| { + let dir = tempfile::tempdir().unwrap(); + let (mut s, prepaid, expense) = books(dir.path(), Currency::USD, with_feature); + let id = s + .register_schedule(schedule(amount("1000.00", Currency::USD), prepaid, expense)) + .unwrap(); + plan_text(&s, id) + }; + assert_eq!(plan_in(false), ["333.33", "333.33", "333.34"]); + assert_eq!(plan_in(true), plan_in(false)); +} + +/// A `schedule.registered` naming a rounding this version doesn't know is +/// newer books, never corrupt (BS-format-1): the line is whole and +/// chained, and this reader says it is old. +#[test] +fn an_unknown_rounding_is_newer_not_corrupt() { + let dir = tempfile::tempdir().unwrap(); + let (s, prepaid, expense) = books(dir.path(), Currency::USD, true); + drop(s); + { + let mut w = ledger_store::JournalWriter::open(&dir.path().join(JOURNAL_FILE)).unwrap(); + w.append( + "schedule.registered", + serde_json::json!({ + "id": 1, "description": "x", "kind": "prepaid_expense", + "total": {"amount": "1000.00", "currency": "USD"}, + "start": "2027-01-01", "months": 3, + "balance_account": prepaid, "pl_account": expense, + "convention": "monthly_even", "rounding": "to_the_nickel" + }), + ) + .unwrap(); + } + match Store::open(dir.path()) { + Err(StoreError::NewerJournal { need, .. }) => { + assert!(need.contains("to_the_nickel"), "{need}") + } + other => panic!("expected NewerJournal, got {:?}", other.map(|_| ())), + } +} diff --git a/docs/proofs/k-u5.md b/docs/proofs/k-u5.md new file mode 100644 index 00000000..94227599 --- /dev/null +++ b/docs/proofs/k-u5.md @@ -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(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>`. 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::`, +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. diff --git a/docs/spec/claims/prepaid.md b/docs/spec/claims/prepaid.md index b49d108f..23cd9304 100644 --- a/docs/spec/claims/prepaid.md +++ b/docs/spec/claims/prepaid.md @@ -56,14 +56,34 @@ equal months, the last absorbing rounding, forever: a posted month's replay re-derives its plan. Monthly-even schedules journaled before D-72 replay the cent rule (two places for every currency); only new schedules round to the currency's minor unit. Schedules an earlier -version took mid-month under equal months replay as they were. (The -engine change is unit K-U5's; this note records the claim.) +version took mid-month under equal months replay as they were. The rule +is the schedule's own flag, journaled on its `schedule.registered` line +(`"rounding": "minor_unit"`, absent for the cent rule), never the +sequence position of the journal feature `schedule_minor_unit`; the store +writes it only in books that declared the feature, which an older reader +refuses as newer books. -**Claims:** partly (the replay half is implemented; moving new monthly-even -schedules to the currency's minor unit is K-U5, not landed) +**Claims:** yes -**Enforced:** `schedules::amortization_plan` (the cent rule, kept for -replay), `Ledger::replay_register_schedule`, `Ledger::schedule_month_hold`. +**Enforced:** `kernel::even_parts` (the arithmetic, law 43), +`schedules::amortization_plan` (the cent rule, kept for replay), +`schedules::amortization_plan_under`, `ScheduleRounding`, +`AmortizationSchedule`, `Ledger::register_schedule_under`, +`Ledger::replay_register_schedule`, `Ledger::replay_register_schedule_under`, +`Ledger::schedule_month_hold`, `Store::register_schedule`, +`SCHEDULE_MINOR_UNIT`, `KNOWN_FEATURES`. **Checked:** `defect9_legacy_schedules_stay_monthly_even`, `prop_monthly_even_plan_is_unchanged`, -`a_schedule_month_posted_again_waits_for_month_reposting_and_replays`. +`a_schedule_month_posted_again_waits_for_month_reposting_and_replays`, +`a_jpy_and_a_kwd_plan_are_whole_units`, +`the_cent_rule_is_unchanged_and_usd_is_the_same_under_both_rules`, +`prop_the_cent_rule_is_the_legacy_rule`, +`a_schedule_carries_the_rule_it_was_written_under`, +`new_books_round_a_yen_and_a_dinar_schedule_to_the_unit`, +`a_schedule_written_before_the_feature_replays_to_the_same_plan_after_it`, +`books_without_the_feature_keep_the_cent_rule_and_write_nothing_new`, +`an_unknown_rounding_is_newer_not_corrupt`, +`schedule_minor_unit_is_its_own_feature`, `even_parts_sum`, +`even_parts_all_but_last_equal`, `even_parts_last_absorbs`, +`even_parts_within_half_step`, +`even_parts_refuses_no_months_and_a_bad_step`. diff --git a/verify/lean/lake-manifest.json b/verify/lean/lake-manifest.json index 89a6f304..5f4e32b8 100644 --- a/verify/lean/lake-manifest.json +++ b/verify/lean/lake-manifest.json @@ -5,10 +5,10 @@ "type": "git", "subDir": "lean", "scope": "", - "rev": "c597c8f845377d9eb868f0f4486759baf16eb5ea", + "rev": "2b3b6c904781efc3f9ead71998a61f01efdeeadd", "name": "bookspec", "manifestFile": "lake-manifest.json", - "inputRev": "c597c8f845377d9eb868f0f4486759baf16eb5ea", + "inputRev": "2b3b6c904781efc3f9ead71998a61f01efdeeadd", "inherited": false, "configFile": "lakefile.toml"}], "name": "wanderbooks", diff --git a/verify/lean/lakefile.toml b/verify/lean/lakefile.toml index 9bf639fc..aa2efc8c 100644 --- a/verify/lean/lakefile.toml +++ b/verify/lean/lakefile.toml @@ -9,7 +9,7 @@ packagesDir = ".lake/packages" [[require]] name = "bookspec" git = "https://git.swaits.com/swaits/bookspec" -rev = "c597c8f845377d9eb868f0f4486759baf16eb5ea" +rev = "2b3b6c904781efc3f9ead71998a61f01efdeeadd" subDir = "lean" [[lean_lib]]