diff --git a/AGENTS.md b/AGENTS.md index 44b87fec..776f605c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,7 @@ later). The reference points: read its docs, never copy its code. This repo is MIT OR Apache-2.0. Never disassemble or copy from proprietary software. 6. **Accounting laws are proved, not just tested.** Arithmetic that money - flows through lives in `kernel.rs` and carries Kani proofs; the laws + flows through lives in `kernel/` and carries Kani proofs; the laws it serves carry Lean proofs. `just prove` stays green. See "Formal methods" below. @@ -104,11 +104,11 @@ So the bar, for every agent, every change: carry a `SOURCE:` line. Never write a spec from what the code happens to do, or from what you remember; find the document, or ask. -1. **Money arithmetic goes in `kernel.rs`, generic over `Amount`.** If +1. **Money arithmetic goes in `kernel/`, generic over `Amount`.** If you write a sum, a sign flip, a split, or a rounding plug anywhere else, move it into the kernel. The engine calls the kernel. It never gets a second copy. -2. **Every kernel function gets a Kani harness** in `src/proofs.rs`, on +2. **Every kernel function gets a Kani harness** in `src/proofs/`, on fixed arrays (no symbolic-length `Vec` growth, no `copy_from_slice`), with a `kani::cover!` showing the interesting case is reached. 3. **Every new law gets a Lean theorem** in `verify/lean`. Laws about @@ -116,7 +116,7 @@ So the bar, for every agent, every change: `Ledger` command is a new `Step` constructor, with its preservation proof. No `sorry`, ever; `Audit.lean` lists every headline theorem. 4. **Every kernel instantiation gets a bridge property** in - `tests/kernel_bridge.rs`, so what Kani proved on `i64` holds on + `tests/kernel_bridge/`, so what Kani proved on `i64` holds on `Decimal`. 5. **A failing proof is a finding, not an obstacle.** Get the counterexample, replay it natively, and decide on evidence: bug in diff --git a/crates/ledger-core/src/kernel/allocate.rs b/crates/ledger-core/src/kernel/allocate.rs new file mode 100644 index 00000000..df525221 --- /dev/null +++ b/crates/ledger-core/src/kernel/allocate.rs @@ -0,0 +1,5 @@ +//! U3: proportional shares, splitting a whole by weights without drift (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`. diff --git a/crates/ledger-core/src/kernel/control.rs b/crates/ledger-core/src/kernel/control.rs new file mode 100644 index 00000000..6e6df45d --- /dev/null +++ b/crates/ledger-core/src/kernel/control.rs @@ -0,0 +1,5 @@ +//! U8: control and aging, what is due or overdue (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`. diff --git a/crates/ledger-core/src/kernel.rs b/crates/ledger-core/src/kernel/entries.rs similarity index 96% rename from crates/ledger-core/src/kernel.rs rename to crates/ledger-core/src/kernel/entries.rs index a6d59174..9048ffb2 100644 --- a/crates/ledger-core/src/kernel.rs +++ b/crates/ledger-core/src/kernel/entries.rs @@ -1,65 +1,6 @@ -//! The accounting kernel: the arithmetic every bookkeeping invariant rests -//! on, in one place. -//! -//! Each function here is small, pure, and generic over [`Amount`]. The -//! engine runs it on [`Decimal`]; the Kani harnesses in `proofs.rs` run the -//! very same code on machine integers and prove it correct for every input -//! within their bounds; and the Lean model in `verify/lean` proves the -//! laws it implements hold for books of any size. See -//! `docs/verification.md` for which proof covers which law. -//! -//! The laws, in the order they appear (each traced to its authority in -//! `docs/spec/rules.md`): -//! -//! * a line's signed amount is `+amount` for a debit, `-amount` for a credit -//! (B-2); -//! * an entry is acceptable when it has two or more lines, every amount is -//! positive and in range, and its debits equal its credits exactly (B-1, -//! B-2, B-21); -//! * an acceptable entry nets to zero, account by account summed (B-1); -//! * a reversal flips every side, so it is acceptable exactly when the -//! original is, and the two together net every account to zero (B-9); -//! * an account's balance is its movement read on its normal side, so the -//! balances satisfy the accounting equation whenever movements net to -//! zero (B-5, B-7); -//! * a trial balance puts each movement in exactly one column, so its -//! columns differ by the net of all movements (B-6); -//! * a closing line zeroes the account it closes (B-11); -//! * a payment to a vendor splits, line by line, into what counts toward -//! its 1099, what a card or payment network paid, and what is unknown, -//! and money moved between the company's own sources nets out (B-19); -//! * an early-payment discount never exceeds its stated percentage of the -//! total, and a document line's amount is exactly its quantity times its -//! unit price, neither rounded (B-39); -//! * an allocation's parts sum to the whole, to the last unit, by largest -//! remainder (B-13); -//! * a cumulative allocation hands out exactly the new amount, and leaves -//! each running total one allocation of everything allocated, so it never -//! drifts a unit from its exact share (B-13); -//! * an entry's cash is applied to the sections of the statement of cash -//! flows moving against it, in a fixed order, each up to its own -//! movement: the parts sum to the entry's cash, what no cash settled sums -//! to zero, and a reversal's parts are the original's negated (B-14); -//! * what a member or lender paid or received for the company, with no -//! cash account moving, is split among the kinds it settled, netting to -//! zero, and mirrored by a reversal (B-14 rule 11); -//! * a party's part of an entry is signed as a line on the party's own -//! account would be, a reversal's is its original's negated, and what of -//! it counts as money or as property never exceeds it (B-35); -//! * a span prorated by days (depreciation, B-15; daily schedules, B-16) -//! splits into parts that sum to its total, each but the last its days -//! times the monthly rate within one unit, the last the remainder; -//! * a catch-up run brings the books to the schedule without ever carrying -//! more than it says at a month end already posted (B-15), and a -//! disposal trues what the books carry up or down to the schedule; -//! * an asset's basis figures follow from its basis rule and facts: the -//! §723 basis is the contributor's adjusted basis, the depreciable basis -//! the cost, that basis, or the lesser of it and fair market value, and -//! the §704(c) built-in gain is fair market value less the §723 basis -//! (B-25); -//! * a tax category's deductible amount adds its accounts' exact shares and -//! rounds once to the cent, half away from zero, never share by share -//! (B-32, B-21). +//! The entry arithmetic: signing, validating, netting, reversing and +//! grouping the lines of an entry or a book, unchanged in U0. The laws it +//! serves are listed at the module root, [`super`]. use crate::assets::BasisRule; use crate::{AccountType, Side}; diff --git a/crates/ledger-core/src/kernel/fx.rs b/crates/ledger-core/src/kernel/fx.rs new file mode 100644 index 00000000..11680873 --- /dev/null +++ b/crates/ledger-core/src/kernel/fx.rs @@ -0,0 +1,5 @@ +//! U1: foreign-currency conversion, the booking of a foreign amount at the transaction-date rate (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`. diff --git a/crates/ledger-core/src/kernel/mod.rs b/crates/ledger-core/src/kernel/mod.rs new file mode 100644 index 00000000..89632270 --- /dev/null +++ b/crates/ledger-core/src/kernel/mod.rs @@ -0,0 +1,98 @@ +//! The accounting kernel: the arithmetic every bookkeeping invariant rests +//! on, in one place. +//! +//! Each function here is small, pure, and generic over [`Amount`]. The +//! engine runs it on [`rust_decimal::Decimal`]; the Kani harnesses in `proofs/` run the +//! very same code on machine integers and prove it correct for every input +//! within their bounds; and the Lean model in `verify/lean` proves the +//! laws it implements hold for books of any size. See +//! `docs/verification.md` for which proof covers which law. +//! +//! The laws, in the order they appear (each traced to its authority in +//! `docs/spec/rules.md`): +//! +//! * a line's signed amount is `+amount` for a debit, `-amount` for a credit +//! (B-2); +//! * an entry is acceptable when it has two or more lines, every amount is +//! positive and in range, and its debits equal its credits exactly (B-1, +//! B-2, B-21); +//! * an acceptable entry nets to zero, account by account summed (B-1); +//! * a reversal flips every side, so it is acceptable exactly when the +//! original is, and the two together net every account to zero (B-9); +//! * an account's balance is its movement read on its normal side, so the +//! balances satisfy the accounting equation whenever movements net to +//! zero (B-5, B-7); +//! * a trial balance puts each movement in exactly one column, so its +//! columns differ by the net of all movements (B-6); +//! * a closing line zeroes the account it closes (B-11); +//! * a payment to a vendor splits, line by line, into what counts toward +//! its 1099, what a card or payment network paid, and what is unknown, +//! and money moved between the company's own sources nets out (B-19); +//! * an early-payment discount never exceeds its stated percentage of the +//! total, and a document line's amount is exactly its quantity times its +//! unit price, neither rounded (B-39); +//! * an allocation's parts sum to the whole, to the last unit, by largest +//! remainder (B-13); +//! * a cumulative allocation hands out exactly the new amount, and leaves +//! each running total one allocation of everything allocated, so it never +//! drifts a unit from its exact share (B-13); +//! * an entry's cash is applied to the sections of the statement of cash +//! flows moving against it, in a fixed order, each up to its own +//! movement: the parts sum to the entry's cash, what no cash settled sums +//! to zero, and a reversal's parts are the original's negated (B-14); +//! * what a member or lender paid or received for the company, with no +//! cash account moving, is split among the kinds it settled, netting to +//! zero, and mirrored by a reversal (B-14 rule 11); +//! * a party's part of an entry is signed as a line on the party's own +//! account would be, a reversal's is its original's negated, and what of +//! it counts as money or as property never exceeds it (B-35); +//! * a span prorated by days (depreciation, B-15; daily schedules, B-16) +//! splits into parts that sum to its total, each but the last its days +//! times the monthly rate within one unit, the last the remainder; +//! * a catch-up run brings the books to the schedule without ever carrying +//! more than it says at a month end already posted (B-15), and a +//! disposal trues what the books carry up or down to the schedule; +//! * an asset's basis figures follow from its basis rule and facts: the +//! §723 basis is the contributor's adjusted basis, the depreciable basis +//! the cost, that basis, or the lesser of it and fair market value, and +//! the §704(c) built-in gain is fair market value less the §723 basis +//! (B-25); +//! * a tax category's deductible amount adds its accounts' exact shares and +//! rounds once to the cent, half away from zero, never share by share +//! (B-32, B-21). +//! +//! The kernel is a module directory so each kernel-sweep unit adds its +//! arithmetic in a file of its own (`fx`, `round`, `allocate`, `total`, +//! `schedule`, `ratio`, `payroll`, `control`) and the entries above stay +//! in `entries`. Only this file declares the modules; the units never edit +//! it, and every path still resolves as `crate::kernel::foo`. + +mod allocate; +mod control; +mod entries; +mod fx; +mod payroll; +mod ratio; +mod round; +mod schedule; +mod total; + +// The unit modules are empty until their sweep unit lands; re-exporting +// them now is what keeps every `crate::kernel::foo` path in place. +#[allow(unused_imports)] +pub use allocate::*; +#[allow(unused_imports)] +pub use control::*; +pub use entries::*; +#[allow(unused_imports)] +pub use fx::*; +#[allow(unused_imports)] +pub use payroll::*; +#[allow(unused_imports)] +pub use ratio::*; +#[allow(unused_imports)] +pub use round::*; +#[allow(unused_imports)] +pub use schedule::*; +#[allow(unused_imports)] +pub use total::*; diff --git a/crates/ledger-core/src/kernel/payroll.rs b/crates/ledger-core/src/kernel/payroll.rs new file mode 100644 index 00000000..476f2933 --- /dev/null +++ b/crates/ledger-core/src/kernel/payroll.rs @@ -0,0 +1,5 @@ +//! U7: payroll arithmetic, withholding and employer taxes (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`. diff --git a/crates/ledger-core/src/kernel/ratio.rs b/crates/ledger-core/src/kernel/ratio.rs new file mode 100644 index 00000000..67943669 --- /dev/null +++ b/crates/ledger-core/src/kernel/ratio.rs @@ -0,0 +1,5 @@ +//! U6: ratios, percentages and averages that reports show (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`. diff --git a/crates/ledger-core/src/kernel/round.rs b/crates/ledger-core/src/kernel/round.rs new file mode 100644 index 00000000..e412a684 --- /dev/null +++ b/crates/ledger-core/src/kernel/round.rs @@ -0,0 +1,5 @@ +//! U2: one rounding primitive, the single place money is rounded to a step (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`. diff --git a/crates/ledger-core/src/kernel/schedule.rs b/crates/ledger-core/src/kernel/schedule.rs new file mode 100644 index 00000000..10af9855 --- /dev/null +++ b/crates/ledger-core/src/kernel/schedule.rs @@ -0,0 +1,5 @@ +//! 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`. diff --git a/crates/ledger-core/src/kernel/total.rs b/crates/ledger-core/src/kernel/total.rs new file mode 100644 index 00000000..cc3f0d4e --- /dev/null +++ b/crates/ledger-core/src/kernel/total.rs @@ -0,0 +1,5 @@ +//! U4: totals, exact checked sums for books and reports (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`. diff --git a/crates/ledger-core/src/proofs/allocate.rs b/crates/ledger-core/src/proofs/allocate.rs new file mode 100644 index 00000000..83afb7bb --- /dev/null +++ b/crates/ledger-core/src/proofs/allocate.rs @@ -0,0 +1,5 @@ +//! U3 proof harnesses: proportional shares (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. diff --git a/crates/ledger-core/src/proofs/control.rs b/crates/ledger-core/src/proofs/control.rs new file mode 100644 index 00000000..d67021f4 --- /dev/null +++ b/crates/ledger-core/src/proofs/control.rs @@ -0,0 +1,5 @@ +//! U8 proof harnesses: control and aging (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. diff --git a/crates/ledger-core/src/proofs/fx.rs b/crates/ledger-core/src/proofs/fx.rs new file mode 100644 index 00000000..366c235f --- /dev/null +++ b/crates/ledger-core/src/proofs/fx.rs @@ -0,0 +1,5 @@ +//! U1 proof harnesses: foreign-currency conversion (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. diff --git a/crates/ledger-core/src/proofs.rs b/crates/ledger-core/src/proofs/mod.rs similarity index 99% rename from crates/ledger-core/src/proofs.rs rename to crates/ledger-core/src/proofs/mod.rs index 0a92050f..f0bd759d 100644 --- a/crates/ledger-core/src/proofs.rs +++ b/crates/ledger-core/src/proofs/mod.rs @@ -19,6 +19,18 @@ //! for any number of parts and any sizes (docs/verification.md says //! which, and how it ties to the kernel's formula). +// One file per kernel-sweep unit; the harnesses above stay here. `just +// prove` scans every file in this directory, so a new harness only needs +// its own file and no edit to this one. +mod allocate; +mod control; +mod fx; +mod payroll; +mod ratio; +mod round; +mod schedule; +mod total; + use crate::kernel::{self, Amount, LineError, MONTH_L, MonthPart}; use crate::{AccountType, Side}; diff --git a/crates/ledger-core/src/proofs/payroll.rs b/crates/ledger-core/src/proofs/payroll.rs new file mode 100644 index 00000000..d5a1da2c --- /dev/null +++ b/crates/ledger-core/src/proofs/payroll.rs @@ -0,0 +1,5 @@ +//! U7 proof harnesses: payroll arithmetic (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. diff --git a/crates/ledger-core/src/proofs/ratio.rs b/crates/ledger-core/src/proofs/ratio.rs new file mode 100644 index 00000000..0708f480 --- /dev/null +++ b/crates/ledger-core/src/proofs/ratio.rs @@ -0,0 +1,5 @@ +//! U6 proof harnesses: ratios (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. diff --git a/crates/ledger-core/src/proofs/round.rs b/crates/ledger-core/src/proofs/round.rs new file mode 100644 index 00000000..777b9b1c --- /dev/null +++ b/crates/ledger-core/src/proofs/round.rs @@ -0,0 +1,5 @@ +//! U2 proof harnesses: the rounding primitive (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. diff --git a/crates/ledger-core/src/proofs/schedule.rs b/crates/ledger-core/src/proofs/schedule.rs new file mode 100644 index 00000000..93a5549e --- /dev/null +++ b/crates/ledger-core/src/proofs/schedule.rs @@ -0,0 +1,5 @@ +//! U5 proof harnesses: schedule plans (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. diff --git a/crates/ledger-core/src/proofs/total.rs b/crates/ledger-core/src/proofs/total.rs new file mode 100644 index 00000000..d72b3854 --- /dev/null +++ b/crates/ledger-core/src/proofs/total.rs @@ -0,0 +1,5 @@ +//! U4 proof harnesses: exact totals (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. diff --git a/crates/ledger-core/tests/kernel_bridge/allocate.rs b/crates/ledger-core/tests/kernel_bridge/allocate.rs new file mode 100644 index 00000000..5921b8ce --- /dev/null +++ b/crates/ledger-core/tests/kernel_bridge/allocate.rs @@ -0,0 +1,4 @@ +//! U3 bridge properties: proportional shares (kernel sweep). +//! +//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, +//! beside `main.rs` and the other units. diff --git a/crates/ledger-core/tests/kernel_bridge/control.rs b/crates/ledger-core/tests/kernel_bridge/control.rs new file mode 100644 index 00000000..537679dc --- /dev/null +++ b/crates/ledger-core/tests/kernel_bridge/control.rs @@ -0,0 +1,4 @@ +//! U8 bridge properties: control and aging (kernel sweep). +//! +//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, +//! beside `main.rs` and the other units. diff --git a/crates/ledger-core/tests/kernel_bridge/fx.rs b/crates/ledger-core/tests/kernel_bridge/fx.rs new file mode 100644 index 00000000..5c426108 --- /dev/null +++ b/crates/ledger-core/tests/kernel_bridge/fx.rs @@ -0,0 +1,4 @@ +//! U1 bridge properties: foreign-currency conversion (kernel sweep). +//! +//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, +//! beside `main.rs` and the other units. diff --git a/crates/ledger-core/tests/kernel_bridge.rs b/crates/ledger-core/tests/kernel_bridge/main.rs similarity index 99% rename from crates/ledger-core/tests/kernel_bridge.rs rename to crates/ledger-core/tests/kernel_bridge/main.rs index 35ac6c3f..203c814a 100644 --- a/crates/ledger-core/tests/kernel_bridge.rs +++ b/crates/ledger-core/tests/kernel_bridge/main.rs @@ -1,11 +1,21 @@ //! The bridge between the proofs and the engine. //! -//! The Kani harnesses (`src/proofs.rs`) prove the accounting kernel on +//! The Kani harnesses (`src/proofs/`) prove the accounting kernel on //! `i64` money in the smallest unit; the engine runs the same kernel on //! `Decimal`. These properties check the two instantiations agree, value //! for value, on cents: whatever Kani proved of the `i64` kernel holds of //! the `Decimal` one for the same amounts. +// One file per kernel-sweep unit; the properties above stay here. +mod allocate; +mod control; +mod fx; +mod payroll; +mod ratio; +mod round; +mod schedule; +mod total; + use ledger_core::kernel::{self, Amount, LineError}; use ledger_core::{AccountType, Side}; use proptest::prelude::*; diff --git a/crates/ledger-core/tests/kernel_bridge/payroll.rs b/crates/ledger-core/tests/kernel_bridge/payroll.rs new file mode 100644 index 00000000..1b22afdc --- /dev/null +++ b/crates/ledger-core/tests/kernel_bridge/payroll.rs @@ -0,0 +1,4 @@ +//! U7 bridge properties: payroll arithmetic (kernel sweep). +//! +//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, +//! beside `main.rs` and the other units. diff --git a/crates/ledger-core/tests/kernel_bridge/ratio.rs b/crates/ledger-core/tests/kernel_bridge/ratio.rs new file mode 100644 index 00000000..852b5784 --- /dev/null +++ b/crates/ledger-core/tests/kernel_bridge/ratio.rs @@ -0,0 +1,4 @@ +//! U6 bridge properties: ratios (kernel sweep). +//! +//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, +//! beside `main.rs` and the other units. diff --git a/crates/ledger-core/tests/kernel_bridge/round.rs b/crates/ledger-core/tests/kernel_bridge/round.rs new file mode 100644 index 00000000..210bdff5 --- /dev/null +++ b/crates/ledger-core/tests/kernel_bridge/round.rs @@ -0,0 +1,4 @@ +//! U2 bridge properties: the rounding primitive (kernel sweep). +//! +//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, +//! beside `main.rs` and the other units. diff --git a/crates/ledger-core/tests/kernel_bridge/schedule.rs b/crates/ledger-core/tests/kernel_bridge/schedule.rs new file mode 100644 index 00000000..ba25ea35 --- /dev/null +++ b/crates/ledger-core/tests/kernel_bridge/schedule.rs @@ -0,0 +1,4 @@ +//! U5 bridge properties: schedule plans (kernel sweep). +//! +//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, +//! beside `main.rs` and the other units. diff --git a/crates/ledger-core/tests/kernel_bridge/total.rs b/crates/ledger-core/tests/kernel_bridge/total.rs new file mode 100644 index 00000000..19ddb333 --- /dev/null +++ b/crates/ledger-core/tests/kernel_bridge/total.rs @@ -0,0 +1,4 @@ +//! U4 bridge properties: exact totals (kernel sweep). +//! +//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, +//! beside `main.rs` and the other units. diff --git a/docs/architecture.md b/docs/architecture.md index d7aaeebc..8d393f51 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -79,7 +79,7 @@ harnesses), `reports`, `cashflow`, `analysis`, `periods`, `assets`, `schedules`, `recurring`, `payouts`, `payroll`, `form1099`, `tax`, `classes`, `parties`, `arap`, `settings`, `conventions`, `calendar`, `shares`, `tax_capital`, `rules`, `audit` (the audit programme's pure checks, P8), `error`; its tests in `tests/` -(`invariants.rs`, `properties.rs`, `spec_*.rs`, `kernel_bridge.rs`, +(`invariants.rs`, `properties.rs`, `spec_*.rs`, `kernel_bridge/`, `model.rs`, `bookspec/`, `golden/`). ## Dependency rules diff --git a/docs/oracle.md b/docs/oracle.md index 6e412b9d..2ce82529 100644 --- a/docs/oracle.md +++ b/docs/oracle.md @@ -80,7 +80,7 @@ canonical form's fixed point, and the reader now refuses floats promoted to a named regression test. **Layer 4½ — Formal proofs (live now).** The accounting arithmetic lives -in one generic kernel (`kernel.rs`). Kani model-checks it exhaustively +in one generic kernel (`kernel/`). Kani model-checks it exhaustively within bounds, Lean 4 proves the laws for books of any size (trial balance, accounting equation, reversals, posted-is-forever, frozen closed periods, closing to net income), and a property test bridges the two. diff --git a/docs/proofs/README.md b/docs/proofs/README.md new file mode 100644 index 00000000..43f4700c --- /dev/null +++ b/docs/proofs/README.md @@ -0,0 +1,32 @@ +# Proof notes for the kernel sweep + +`docs/verification.md` is the one place the proofs are described: the law +table, the bounds, the times, and what is and isn't proved. The kernel +sweep (`plan/kernel-sweep-audit.md`) runs several units in parallel, so +editing that file from every branch would collide on every hunk. The rule +instead: + +- **Each unit that adds proofs writes `docs/proofs/.md`**, where + `` is the lowercase name of its code files (`fx`, `round`, + `allocate`, `total`, `schedule`, `ratio`, `payroll`, `control`; `U9` + display adds no proofs). The note lists, for that unit: + - every Kani harness it added, with the law each proves; + - the bounds Kani explores (lines, accounts, amounts, scales), and why + they are enough; + - the measured time, alone or in a `just prove` run, with the machine + and date; + - every bridge property in `tests/kernel_bridge/.rs`, and every + Lean theorem it added; + - anything the solver could not do, and what carries it instead (Lean + at any size, a bridge property, an exhaustive unit test). +- **Workers do not edit `docs/verification.md` or `verify/lean/Audit.lean`.** + The integrator folds the unit notes into `verification.md`'s tables and + prose, and adds the `#print axioms` lines to `Audit.lean` in one place, + in one edit per batch, after the batch's merges. +- A unit's note lands in the same commit as its harnesses, so the proof + and its description are never apart in history. + +`just prove` finds the harnesses by scanning `crates/ledger-core/src/proofs/` +(`mod.rs` plus every `.rs`), not one file; `just prove-list` prints +each harness, its module path, and whether it runs in `prove` or +`prove-slow`. diff --git a/docs/spec/claims/arap.md b/docs/spec/claims/arap.md index a91eebb6..66bf3d40 100644 --- a/docs/spec/claims/arap.md +++ b/docs/spec/claims/arap.md @@ -481,7 +481,7 @@ check_discount}`, `arap::{Application, Fee, SettleParams, SettlementRow}`, `discount_on_an_asset_bill_is_refused_with_the_remedy`, `a_fee_posts_gross_to_receivables_and_net_to_the_bank`, `a_settlement_names_its_lines_and_refuses_a_document_twice`), -`tests/kernel_bridge.rs::settle_agrees`; Kani `settle_is_exact`; +`tests/kernel_bridge/main.rs::settle_agrees`; Kani `settle_is_exact`; `ledger-store` `tests/arap_standing.rs` (`a_settlement_names_its_lines_and_replays`, `settlement_waits_for_documents_v2`, `legacy_payment_events_keep_the_positional_rule`), `tests/arap_props.rs`; diff --git a/docs/spec/claims/asset.md b/docs/spec/claims/asset.md index 8fada115..a604b884 100644 --- a/docs/spec/claims/asset.md +++ b/docs/spec/claims/asset.md @@ -309,7 +309,7 @@ non-negative, in cents, at most one quadrillion) and its replay pairs `asset_basis`); `ledger-mcp` `books.set_asset_tax_basis` and `books.register_asset` (a contribution's fair market value is required, never assumed). **Checked:** `ledger-core` `tests/spec_asset_basis.rs`, -`tests/kernel_bridge.rs` (`basis_figures_agree`), `tests/properties.rs` +`tests/kernel_bridge/` (`basis_figures_agree`), `tests/properties.rs` (`prop_basis_figures_laws`); `ledger-store` `tests/asset_tags.rs`; `ledger-cli` `tests/spec_assets.rs`. diff --git a/docs/testing.md b/docs/testing.md index d6f64e51..7929c93c 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -15,15 +15,15 @@ promise. | Spec-derived examples | written specs with sources (1) | `tests/spec_*.rs`, `invariants.rs`, `statements.rs`, `assets.rs`, ...; the store's `tests/spec_store.rs` (written blind, from its specs only) | `just check` | seconds | every change | | Regressions | the bug, named (1) | beside the code they cover, `*_regression`/named for the defect | `just check` | seconds | every change | | Compatibility contracts | journals written under older rules must open, and replay to the figures their version computed (1) | `ledger-store/tests/store.rs` (`books_written_under_older_rules_still_open`; `books_an_earlier_version_wrote_open_to_its_figures` over `tests/fixtures/old-books`: books main 188c90ea wrote, with main's own figures in `expected.json`, in the writer and the viewer; `every_figure_over_old_books_is_computed_or_refused`); `ledger-cli/tests/hostile_args.rs` `old_books_answer_every_tool`; `ledger-gui/tests/old_books.rs` | `just check` | ~30s | every change | -| Properties | laws over all inputs (2) | `properties.rs`, `spec_*.rs`, `kernel_bridge.rs` | `just check` | seconds | every change | +| Properties | laws over all inputs (2) | `properties.rs`, `spec_*.rs`, `kernel_bridge/` | `just check` | seconds | every change | | Metamorphic | scaling, reversal, ordering invariance (2) | `spec_reports.rs` | `just check` | seconds | every change | | Refusal law (store) | a refused command never reaches the journal, an accepted one always does; the live ledger equals its journal's replay in every part, and the books reopen to it (2, 3) | `store.rs` `refused_commands_never_reach_the_journal` | `just check` (`STORE_CASES=5000` deeper) | ~20s | every change | | Fault injection (store) | a full disk or a cut-off append leaves whole, openable books (1) | `ledger-store/tests/faults.rs`, `store.rs` (`power_loss_at_any_byte_of_the_last_append_is_recovered`) | `just check` | ~5s | every change | | Concurrency (store) | a viewer reading while the books are written sees only whole books, never a false "differs" (2) | `ledger-store/tests/concurrency.rs` | `just check` | <1s | every change | | Model-based stateful | the Lean state machine, transcribed (3) | `tests/model.rs` | `just check` | ~3s | every change | -| Differential: Decimal vs i64 | the kernel at two types (3) | `kernel_bridge.rs` | `just check` | <1s | every change | +| Differential: Decimal vs i64 | the kernel at two types (3) | `kernel_bridge/` | `just check` | <1s | every change | | Differential: GnuCash | another implementation, adjudicated (3) | `tests/oracle_gnucash.rs`, `oracle/gnucash/` | `just oracle` | ~2 min | weekly | -| Formal proofs | Kani (bounded) and Lean (unbounded) | `src/proofs.rs`, `verify/lean/` | `just prove` (51 harnesses and Lean), `just prove-slow` (the 9 in the justfile's `kani_slow`, each under its own 30-minute cap); 60 harnesses in all with the checker canary (2026-10-28) | prove ~5 min and prove-slow ~8 min at four jobs on a quiet laptop (each ~25 min under heavy load; docs/verification.md, "Running it") | weekly (CI runs both) | +| Formal proofs | Kani (bounded) and Lean (unbounded) | `src/proofs/`, `verify/lean/` | `just prove` (51 harnesses and Lean), `just prove-slow` (the 9 in the justfile's `kani_slow`, each under its own 30-minute cap); 60 harnesses in all with the checker canary (2026-10-28) | prove ~5 min and prove-slow ~8 min at four jobs on a quiet laptop (each ~25 min under heavy load; docs/verification.md, "Running it") | weekly (CI runs both) | | Fuzzing | crash, hang, broken books (4); for `fuzz_store_replay` (validly chained journals with fuzz-chosen events): books that open must verify, and the viewer must accept exactly what the writer does | `fuzz/fuzz_targets/`, corpora in `fuzz/corpus/` | `just fuzz ` | 10 min each | weekly | | Miri | undefined behavior in our use of dependencies (4) | the core's unit, bridge, invariant tests (the exhaustive calendar walk aside) | `just miri` | ~4 min | on demand | | Golden | `tests/golden/fixture_company.json` (5) | `invariants.rs` | `just check` | <1s | every change | @@ -676,10 +676,10 @@ posts nothing changes no capital, R-3), `a_run_of_closes_never_piles_up_rounding`, and February in `a_partnership_closes_into_members_capital` (Bob 683.33 → 683.34: his share of February's unclosed income is what its close will give, D-38). Unit -tests in `kernel.rs` (`apportion_cumulative_refuses_mismatched_or_out_of_range_inputs`, +tests in `kernel/` (`apportion_cumulative_refuses_mismatched_or_out_of_range_inputs`, `apportion_cumulative_trues_up_a_legacy_split`) and `periods.rs` (`allocate_cumulative_*`: whole yen, a dinar, a loss, a 28-place share -refused, R-5). Bridges (`tests/kernel_bridge.rs`): +refused, R-5). Bridges (`tests/kernel_bridge/`): `apportion_cumulative_agrees`, `allocate_cumulative_agrees_with_the_integer_model`. @@ -1028,7 +1028,7 @@ the end. `Reachable.cashflow_foots`, `Reachable.cashflow_is_change_in_cash` (docs/verification.md, law 10). - **Sensitivity (P3 review, by hand, no mutation run):** 18 deliberate - breaks to `cashflow.rs` and `kernel.rs` (a dropped reversal + breaks to `cashflow.rs` and `kernel/` (a dropped reversal flip, no netting, financing read as operating, no rule 4, no exchange disclosure, no interest class, no warnings, the bill's payments ignored, the label's depth parity, repeated codes allowed, depreciation @@ -1077,7 +1077,7 @@ the end. **For P12** (D-33): `cargo mutants` on `ledger-core`'s `cashflow.rs` (`cash_flow`, `analyse`, `pairs`, `label`, `class_of`, `reconcile`, `warnings`, `bill_splits`, `role_problems`, `foot`, `on_behalf`) and -`kernel.rs`'s `take`, `apply_cash`, `entry_flows`, `constructive`, +`kernel/`'s `take`, `apply_cash`, `entry_flows`, `constructive`, `exchanged`; `ledger-import`'s `report::cash_flow`; `ledger-mcp`'s `cash_flow_out`, `cash_flow_csv`, `export_cash_flow` and `settings_problems`; zero unexplained survivors @@ -1294,8 +1294,8 @@ no mutation run here; what P12 must cover is at the end. | Read from journaled facts: an archived member, a one-member company | `a_members_entry_keeps_its_reading_after_they_leave` | review R2 | | A close is neither; a basis is cash or all; creditor_of's checks; tin_last4's five scenarios; the kernel's cases | `a_close_tagged_with_its_members_is_neither`, `a_basis_is_cash_or_all`, `a_creditor_is_named_only_on_a_liability_with_one_owner`, `defect11_a_partys_tin_last4_is_its_tin_facts_else_its_w9s`, `party_target_cases_by_hand` | specs | | Properties: a reversal's target, parts and flow are the original's negated; parts sum to the target, each with its sign; a sole party's money part is the flow as before P3; tin_last4 is every source present | `a_reversal_is_the_exact_opposite`, `a_sole_partys_money_part_is_the_flow_as_before`, `tin_last4_is_every_source_present` (`PROPTEST_CASES`, default 256; 5,000 run clean) | B-35, B-9 | -| Decimal and i64 agree on party_target and reverse_target | `kernel_bridge.rs` `party_target_agrees` | the bridge | -| Kani: the direction is the sign, the target is odd, reverse_target an involution | `proofs.rs` `party_target_direction_is_its_sign`, `party_target_is_odd`, `reverse_target_is_an_involution` | the kernel spec | +| Decimal and i64 agree on party_target and reverse_target | `kernel_bridge/` `party_target_agrees` | the bridge | +| Kani: the direction is the sign, the target is odd, reverse_target an involution | `proofs/` `party_target_direction_is_its_sign`, `party_target_is_odd`, `reverse_target_is_an_involution` | the kernel spec | | The journal: party.creditor_set one line each, under the feature the books declared when created; in books an older version wrote, refused (FormatUpgradePending, nothing journaled) until the format upgrade; refusals journal nothing; books without creditors never change, in either format; corrupt lines refused | `ledger-store/tests/party_creditors.rs` | the format gate | | Over the MCP: get_entry's direction, cash, in_kind; party totals by basis, echoed, others refused; basis all equals members' equity; creditor_of round trips and a card fee isn't a payment; the post_entry preview's parts are what it posts | `ledger-cli/tests/spec_party_totals.rs` | the tool docs | | Defect 11 over the MCP: a member's TIN last four in the directory, a W-9's, none, after a purge | `ledger-cli/tests/spec_vault.rs` `defect11_the_directory_shows_a_members_tin_last4` | B-26 | @@ -1367,7 +1367,7 @@ filter, the not-reportable and undetermined routing, the R6 test (which methods' accounts are financing, which a card's), `split_share` (the floor corrections, the sign), `vendor_part`, the unresolved fallback, `decisions_during`, `untagged_payments` (`> 0`, each skip, each debit kind), `decision_changes`); -`kernel.rs` (`payment_bucket`, `split_payment`, `net_buckets`); +`kernel/` (`payment_bucket`, `split_payment`, `net_buckets`); `instruments.rs` and `Ledger::check_add_instrument` (each refusal), `set_entry_instrument` (the chain), the reversal step's copy, `set_vendor_w9_flag`; `ledger-store` `form1099.rs` (each decode check, @@ -1451,11 +1451,11 @@ a bookspec example (`bookspec/examples/`, P13, D-34). | Depreciation still due when the disposal's month has a run is charged in the disposal entry, never as a second run of the month (P3 review round 2; no store test held it) | store `a_disposal_whose_month_has_run_charges_what_is_still_due_in_its_entry` | | A command that needs a journal feature asks for it before its first journaled line: in books waiting for the format upgrade it is refused and journals nothing, and after the upgrade it is taken | store `format.rs` `a_write_waiting_for_the_upgrade_journals_nothing` | | What a viewer's one pass says a run of each month posts is run_amount's for that month | property `prop_run_amounts_are_each_months_run_amount` (500 cases); Kani `catch_ups_is_every_suffixs_catch_up` | -| The kernel on i64 and i32 (Kani's) is the kernel on i128 and Decimal (the engine's) | `kernel_bridge.rs` `prorate_agrees_at_i64_and_i128`, `prorated_through_agrees_at_i32_and_i128`, `catch_up_and_true_up_agree` | -| The charge never falls and is continuous at month ends, over every 1-to-3-month span from every day of a common and a leap year | `kernel.rs` unit `the_charge_never_falls_and_is_continuous_over_real_calendars` (exhaustive) | +| The kernel on i64 and i32 (Kani's) is the kernel on i128 and Decimal (the engine's) | `kernel_bridge/` `prorate_agrees_at_i64_and_i128`, `prorated_through_agrees_at_i32_and_i128`, `catch_up_and_true_up_agree` | +| The charge never falls and is continuous at month ends, over every 1-to-3-month span from every day of a common and a leap year | `kernel/` unit `the_charge_never_falls_and_is_continuous_over_real_calendars` (exhaustive) | | Proofs | Kani `prorate_parts_sum_to_total`, `prorate_last_part_absorbs_the_remainder`, `a_months_charge_is_within_half_a_cent`, `a_months_charge_in_tenths_is_within_half_a_cent`, `the_last_months_charge_is_within_half_a_cent`, `the_last_months_charge_in_tenths_is_within_half_a_cent`, `prorated_through_refuses_malformed_input`, `catch_up_never_overtakes_the_schedule`, `catch_ups_is_every_suffixs_catch_up`, `true_up_reaches_the_target`; Lean `Prorate.lean` (`cum_mono`, `cum_le`, `cum_full`, `parts_telescope`, `prorate_total`, `prorate_nonneg`, `part_within_a_unit`, `roundUnit_near`, `roundUnit_scale`, `cum_near`, `part_near`, `chargeMid_eq_cum`, `chargeLast_eq_cum`, `chargeLast_start`, `chargeLast_mono`, `kernel_parts_total`, `kernel_parts_nonneg`; `docs/verification.md`) | -**Mutation targets for P12** (none run in P3, D-33): `kernel.rs` +**Mutation targets for P12** (none run in P3, D-33): `kernel/` `prorated_through` (the last/not-last branch, the rounding comparison `r >= step - r` against `>`, the `k == days && last` shortcut, the cap at the total, every refusal), `round_to_unit`, `prorate_by_days`, @@ -1660,8 +1660,8 @@ basis. Mutation runs wait for P12 (D-33); none was run. up, a loss mirroring a gain at a running whole of zero, a split taken back out); `spec_asset_basis.rs` `a_duplicated_run_line_is_carried_once`; `properties.rs` - `prop_basis_figures_laws` (5,000 cases); `kernel_bridge.rs` - `basis_figures_agree`; Kani `basis_figures_laws` (`src/proofs.rs`, 83 + `prop_basis_figures_laws` (5,000 cases); `kernel_bridge/` + `basis_figures_agree`; Kani `basis_figures_laws` (`src/proofs/`, 83 checks, its cover satisfied); `spec_asset_tags.rs` (the register's posted and scheduled figures, runs recorded as a store records them). - **ledger-store:** `asset_tags.rs` (`asset.basis_set` journaled under the @@ -1786,7 +1786,7 @@ books; the privacy sweep below. | Every tool the server has is documented in `docs/mcp-interface.md`, and every tool the doc documents exists (115; `books.access_log` had no entry) | `ledger-mcp` `server.rs` `every_tool_is_documented_and_every_documented_tool_exists` (with a check of its own reader) | the doc, read tool by tool against the code | | The reversal's cash flow mirror at three lines, in two halves: a reversal's movements are its original's negated, and `kernel::flows_of` is odd; end to end at two lines | Kani `entry_movements_of_a_reversal_mirror`, `flows_of_mirrors`, `entry_flows_of_a_reversal_mirror` (`kernel::entry_flows` split into `entry_movements` and `flows_of`, behavior unchanged: every cash flow test, bridge and property passes) | docs/verification.md law 10; Lean `flows_reversal` | | A closed-list value in a bookspec example (a 1099 form, a payment method's kind, a reason kind, a party totals basis) is spelled exactly as the README spells it; a K-1 query needs `cash_accounts` | `ledger-core` `tests/bookspec/` `a_form_in_another_case_is_refused`, `a_payment_method_kind_in_another_case_is_refused`, `a_reason_kind_in_another_case_is_refused`; `check_k1` | bookspec/README.md | -| Every Kani harness in `src/proofs.rs` runs in exactly one of `just prove` and `just prove-slow`, each run's count is checked, and a slow-list name that isn't a harness fails | `justfile` `_kani` | docs/verification.md, "Running it" | +| Every Kani harness in `src/proofs/` runs in exactly one of `just prove` and `just prove-slow`, each run's count is checked, and a slow-list name that isn't a harness fails | `justfile` `_kani` | docs/verification.md, "Running it" | **Docs corrected** (each against the code): `docs/mcp-interface.md`, about 60 fixes (parameter names: `search_entries`' `account_id`, `link_receipt`'s @@ -1864,7 +1864,7 @@ P12 (D-33); none was run. `prop_project_entries_sum_to_the_net_to_date` (project_entries' own signs: the posted entries' project amounts are the net to date, with refunds, reimbursements, tagged cash lines and drafts beside them); - Kani `unrecovered_cost_laws` (`src/proofs.rs`, docs/verification.md law + Kani `unrecovered_cost_laws` (`src/proofs/`, docs/verification.md law 32, run by `just prove`: never above max(expenses, 0) when revenue isn't negative; the earlier "never above expenses" fails it, checked). @@ -3291,7 +3291,7 @@ tie-out, and the aging exports. lines in application order; one document twice refused). `spec_cash_flow.rs::equipment_bill_payment_is_investing_cash` keeps D-35 through a settlement. -- **Kernel:** `kernel_bridge.rs::settle_agrees`; Kani +- **Kernel:** `kernel_bridge/main.rs::settle_agrees`; Kani `settle_is_exact` (a nonzero discount and a nonzero fee covered). - **Store (`crates/ledger-store/tests/arap_standing.rs`):** `a_settlement_names_its_lines_and_replays` (one entry, two invoices, a @@ -4311,7 +4311,7 @@ count. Accept counts for `ledger-core` and `ledger-import` are R-6. - [P3 cash flow] `cashflow.rs` (`cash_flow`, `analyse`, `pairs`, `label`, `class_of`, `reconcile`, `warnings`, `bill_splits`, `role_problems`, `foot`, - `on_behalf`); `kernel.rs`'s `take`, `apply_cash`, `entry_flows`, + `on_behalf`); `kernel/`'s `take`, `apply_cash`, `entry_flows`, `constructive`, `exchanged`. Likely equivalent, to adjudicate: `min` against `max` in `take` where both bounds coincide; the kind order's tie-breaks. - [P3 rename and defaults] `calendar::{fiscal_year_start_unclamped, @@ -4348,7 +4348,7 @@ count. account type), `Roles::new` (which methods' accounts are financing, which a card's), `split_share` (the floor corrections, the sign), `vendor_part`, the unresolved fallback, `decisions_during`, `untagged_payments` (`> 0`, each - skip, each debit kind), `decision_changes`); `kernel.rs` (`payment_bucket`, + skip, each debit kind), `decision_changes`); `kernel/` (`payment_bucket`, `split_payment`, `net_buckets`); `instruments.rs`, `Ledger::check_add_instrument` (each refusal), `set_entry_instrument` (the chain), the reversal step's copy, `set_vendor_w9_flag`. diff --git a/docs/verification.md b/docs/verification.md index 35d9eb74..edee0580 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -18,7 +18,9 @@ Every invariant rests on a little arithmetic: signing a line, summing sides, grouping by account, flipping for a reversal, reading a balance on its normal side, splitting a movement into trial-balance columns, closing an account, plugging the last share of an allocation. That arithmetic -lives in one place, `crates/ledger-core/src/kernel.rs`. Its functions +lives in one place, `crates/ledger-core/src/kernel/` (the module root +re-exports the entry arithmetic in `entries.rs` and one file per +kernel-sweep unit). Its functions are small, pure, and generic over an `Amount` trait with *checked* operations. The engine calls them on `Decimal`: `JournalEntry::validate`, `movements`, `reverse_entry`, `account_balance`, `account_movement`, @@ -36,10 +38,23 @@ checker explores in reasonable time.) The Lean model in both of `prorated_through`'s branches) and proves the laws with no bounds at all. +### Kernel sweep + +The kernel and its proofs are directories so the kernel-sweep units +(U1 FX, U2 rounding, U3 shares, U4 totals, U5 schedules, U6 ratios, U7 +payroll, U8 control, U9 display) each get files of their own: +`kernel/mod.rs` re-exports `entries` and `fx`, `round`, `allocate`, +`total`, `schedule`, `ratio`, `payroll`, `control`; `proofs/mod.rs` holds +the original harnesses and each unit adds `proofs/.rs`. A unit +writes its proof note in `docs/proofs/.md`; the integrator folds the +notes into this file and the `#print axioms` lines into +`verify/lean/Audit.lean` in one edit per batch. Workers do not edit this +file (see `docs/proofs/README.md`). + ## The laws Each law, and what proves it. Kani harnesses are in -`crates/ledger-core/src/proofs.rs`; Lean theorems are in +`crates/ledger-core/src/proofs/`; Lean theorems are in `verify/lean/Wanderbooks/`. ### Entries @@ -880,8 +895,10 @@ anything beyond Lean's standard axioms (`propext`, `Quot.sound`, runs the slow harnesses, `$(nproc)` at a time, each under its own 30-minute timeout. Both fail if a harness they ask for isn't verified (the count is checked), if any cover is unsatisfiable (a vacuous proof), or if -`kani_slow` names a harness `src/proofs.rs` doesn't have; a new harness -runs in `prove` until it is listed as slow. CI's weekly run does both, on +`kani_slow` names a harness `src/proofs/` doesn't have; a new harness +runs in `prove` until it is listed as slow. `just prove-list` prints every +harness with its module path and the set it runs in, resolving the slow +list without spending a verification. CI's weekly run does both, on two runners (`.github/workflows/scheduled.yml`). Kani downloads its pinned nightly and CBMC into `~/.kani` on first use. diff --git a/justfile b/justfile index 41351041..ea58440b 100644 --- a/justfile +++ b/justfile @@ -63,8 +63,9 @@ sweep-test-tmp: # The Kani harnesses `prove` leaves to `prove-slow`: each takes four to # twenty minutes alone on a busy machine, and with them the suite (about # 100 minutes of CPU, 2026-10-21) can't finish inside the 30-minute cap at -# four jobs, a CI runner's. Every other harness in src/proofs.rs runs in `prove`, a new one -# included; a name here that isn't a harness fails both (docs/verification.md). +# four jobs, a CI runner's. Every other harness in src/proofs/ runs in `prove`, a new one +# included; a name here that isn't a harness, or is shared by two, fails +# both (docs/verification.md). kani_slow := "accounting_equation cumulative_close_never_drifts_a_unit_at_near_thirds cumulative_closing_entry_balances deductible_amount_rounds_once discount_max_is_bounded entry_flows_pure_are_movements entry_flows_sum_to_cash prorate_parts_sum_to_total sums_are_exact the_last_months_charge_is_within_half_a_cent" # Formal proofs: Kani on the accounting kernel (all but kani_slow), Lean for books of any size (docs/verification.md) @@ -86,19 +87,55 @@ prove-slow: (_kani "slow") # Every proof: prove, then prove-slow prove-all: prove prove-slow +# Every Kani harness, its module path, and the set (fast/slow) it runs in: +# no verification, so the slow list is shown resolved without `prove-slow`. +prove-list: (_kani "list") + # Kani on one set of the harnesses: "fast" (all but kani_slow, the whole -# run under the cap) or "slow" (each harness under the cap) +# run under the cap) or "slow" (each harness under the cap); "list" prints +# the harnesses and the set each runs in, without running Kani (prove-list). _kani set: #!/usr/bin/env bash set -euo pipefail - # Every harness: the fn after each #[kani::proof] in src/proofs.rs. - all=$(awk '/#\[kani::proof\]/ { p = 1; next } p && match($0, /^fn [a-z_0-9]+/) { print substr($0, 4, RLENGTH - 3); p = 0 }' crates/ledger-core/src/proofs.rs | sort) + dir=crates/ledger-core/src/proofs + # Every harness, fully qualified: proofs/mod.rs is module `proofs`, + # proofs/.rs is `proofs::`. Kani's --exact matches only a + # fully qualified name, so a harness resolves wherever its file lives. + files=("$dir/mod.rs") + for f in "$dir"/*.rs; do [ "$f" = "$dir/mod.rs" ] || files+=("$f"); done + all=$( + for f in "${files[@]}"; do + mod=proofs + [ "$f" = "$dir/mod.rs" ] || mod="proofs::$(basename "$f" .rs)" + awk -v mod="$mod" '/#\[kani::proof\]/ { p = 1; next } p && match($0, /^fn [a-z_0-9]+/) { print mod "::" substr($0, 4, RLENGTH - 3); p = 0 }' "$f" + done | sort + ) + bare=$(sed 's/.*:://' <<<"$all") slow=$(tr ' ' '\n' <<<"{{kani_slow}}" | sort) - if missing=$(comm -13 <(echo "$all") <(echo "$slow")) && [ -n "$missing" ]; then + # Two harnesses with one name would make kani_slow (a list of bare + # names) ambiguous. + if dup=$(uniq -d <<<"$bare") && [ -n "$dup" ]; then + echo "two harnesses share a name: $dup" >&2 + exit 1 + fi + # A slow name that no harness has is a typo or a moved proof: fail + # rather than silently verify one harness less than the list says. + if missing=$(comm -13 <(echo "$bare") <(echo "$slow")) && [ -n "$missing" ]; then echo "kani_slow names no harness: $missing" >&2 exit 1 fi - if [ "{{set}}" = slow ]; then names=$slow; else names=$(comm -23 <(echo "$all") <(echo "$slow")); fi + # The qualified name whose bare name is in `want` (a slow/fast file). + picked() { # want-file + awk 'NR==FNR { want[$1] = 1; next } { n = $0; sub(/.*::/, "", n); if (n in want) print }' "$1" <(printf '%s\n' "$all") + } + if [ "{{set}}" = list ]; then + for h in $all; do + n=${h##*::} + if grep -qxF "$n" <<<"$slow"; then echo "slow $h"; else echo "fast $h"; fi + done + exit 0 + fi + if [ "{{set}}" = slow ]; then names=$(picked <(echo "$slow")); else names=$(picked <(comm -23 <(echo "$bare") <(echo "$slow"))); fi logs=$(mktemp -d) # What each run must show: every harness asked for verified, and no # cover unsatisfiable (a vacuous proof). @@ -119,19 +156,20 @@ _kani set: ulimit -v 12000000 if [ "{{set}}" = fast ]; then args=() - for h in $names; do args+=(--harness "proofs::$h"); done + for h in $names; do args+=(--harness "$h"); done timeout 1800 cargo kani -j "$(nproc)" --output-format terse --exact "${args[@]}" | tee "$logs/fast.log" checked "$logs/fast.log" "$(wc -l <<<"$names")" else cargo kani --only-codegen --output-format terse failed=0 for h in $names; do + log=${h##*::} while [ "$(jobs -rp | wc -l)" -ge "$(nproc)" ]; do wait -n || failed=1; done ( start=$(date +%s) - timeout 1800 cargo kani --output-format terse --exact --harness "proofs::$h" > "$logs/$h.log" 2>&1 && - checked "$logs/$h.log" 1 && - echo "Kani: $h verified in $(( $(date +%s) - start )) s" || - { echo "Kani: $h failed or ran past 1800 s ($logs/$h.log)" >&2; exit 1; } ) & + timeout 1800 cargo kani --output-format terse --exact --harness "$h" > "$logs/$log.log" 2>&1 && + checked "$logs/$log.log" 1 && + echo "Kani: $log verified in $(( $(date +%s) - start )) s" || + { echo "Kani: $log failed or ran past 1800 s ($logs/$log.log)" >&2; exit 1; } ) & done while [ "$(jobs -rp | wc -l)" -gt 0 ]; do wait -n || failed=1; done wait || failed=1 @@ -184,7 +222,7 @@ mutants shard="0/1": sweep-test-tmp # Core and store tests (the store's replay tests reach Ledger::replay_*); # the whole workspace would rebuild the viewer for every mutant. mkdir -p {{mutants_tmp}} - PROPTEST_MAX_SHRINK_ITERS=0 TMPDIR={{mutants_tmp}} cargo mutants -p ledger-core --exclude crates/ledger-core/src/proofs.rs --test-package ledger-core --test-package ledger-store -j 4 --timeout-multiplier 3 --minimum-test-timeout 120 --shard {{shard}} {{mutants_iterate}} + PROPTEST_MAX_SHRINK_ITERS=0 TMPDIR={{mutants_tmp}} cargo mutants -p ledger-core --exclude 'crates/ledger-core/src/proofs/**' --test-package ledger-core --test-package ledger-store -j 4 --timeout-multiplier 3 --minimum-test-timeout 120 --shard {{shard}} {{mutants_iterate}} @just sweep-test-tmp # Mutation testing of the store. Fewer random cases per mutant (each needs