merge: main into k-u11a (K-U10's exact operations)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude committed 2026-11-09 22:41:45 -07:00
commit 3918151794
94 files changed
+19771 -635

No files matched your search

+15 -2
View File
@@ -1,5 +1,10 @@
# Every change: format, clippy and rustdoc with zero warnings, every test.
# Tools come from mise.toml, the same as on a laptop.
#
# `just check` is cut into parts (the justfile's check_shards), one runner
# each, side by side: on one runner the job took 72 minutes on 2026-11-09,
# and a red test was an hour away. The list below must be the justfile's
# (the lint part checks that), so no part can be left out here unseen.
name: check
on:
push:
@@ -15,7 +20,14 @@ concurrency:
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
check:
name: check (${{ matrix.shard }})
runs-on: ubuntu-24.04
timeout-minutes: 75
strategy:
# One red part does not stop the others: the run lists every failure.
fail-fast: false
matrix:
shard: [lint, gui-unit, gui-tests, cli, rest]
# The runner's disk is small (the first run after P6 landed died in
# the linker: "No space left on device", ld killed by SIGBUS). A fresh
# runner gains nothing from incremental caches, and line tables keep
@@ -31,7 +43,7 @@ jobs:
with:
fetch-depth: 2
- name: The base branch, for the parity floor
if: github.event_name == 'pull_request'
if: matrix.shard == 'lint' && github.event_name == 'pull_request'
run: |
git fetch --no-tags --depth=1 origin \
"+refs/heads/${{ github.base_ref }}:refs/remotes/origin/${{ github.base_ref }}"
@@ -50,6 +62,7 @@ jobs:
# new tip's parent: a push of several commits could otherwise lower
# the floor in an earlier one unseen.
- name: The parity floor holds
if: matrix.shard == 'lint'
env:
BEFORE: ${{ github.event.before }}
run: |
@@ -61,7 +74,7 @@ jobs:
else
scripts/parity-floor.sh HEAD^1
fi
- run: just check
- run: just check-shard ${{ matrix.shard }}
- name: What the build used
if: always()
run: df -h / | tail -1
+8
View File
@@ -22,6 +22,14 @@ jobs:
- uses: actions/checkout@v4
- uses: jdx/mise-action@v2
- run: just prove-slow
# A dependency's advisory is published when it is, not when we push:
# the same check as in `just check`, so a week is the longest one waits.
deny:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: jdx/mise-action@v2
- run: just deny
lean-model:
runs-on: ubuntu-24.04
steps:
+1
View File
@@ -224,6 +224,7 @@ clone, with status. Rules:
| `docs/spec/claims/` | Wanderbooks' claims on each bookspec rule: the CHOICE picked, where the engine enforces it, which tests check it, and product rules `WB-<area>-<n>` |
| https://git.swaits.com/swaits/bookspec | Where the rules live (D-68): `rules/` records, `spec/rules/` reading pages, `spec/rules-index.md`; every rule is `BS-<area>-<n>` |
| `docs/verification.md` | The formal proofs: every accounting law, its Kani harness and Lean theorem, what they found |
| `docs/command-steps.md` | Which step of bookspec's Lean model each `Ledger` command is, and which commands the proofs do not cover |
| `docs/parity.md` | Feature catalog and the non-regression floor |
| `docs/capability-parity.md` | Parity vs the GSheet+GDrive system + the cutover rule |
| `docs/mcp-interface.md` | The MCP tool surface: the primary interface spec |
Generated
+64 -92
View File
@@ -292,15 +292,6 @@ dependencies = [
"object",
]
[[package]]
name = "arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
dependencies = [
"derive_arbitrary",
]
[[package]]
name = "arboard"
version = "3.6.1"
@@ -386,9 +377,9 @@ dependencies = [
[[package]]
name = "async-executor"
version = "1.14.0"
version = "1.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
dependencies = [
"async-task",
"concurrent-queue",
@@ -1148,9 +1139,9 @@ checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
[[package]]
name = "clipboard-win"
version = "5.4.1"
version = "5.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"
checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a"
dependencies = [
"error-code",
]
@@ -1496,9 +1487,9 @@ checksum = "8fd9f3db6f2cfef61c10613071955154ffdc9e515daebff26de4b54e35038fdd"
[[package]]
name = "ctutils"
version = "0.4.3"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574"
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
dependencies = [
"cmov",
]
@@ -1598,17 +1589,6 @@ version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
[[package]]
name = "derive_arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.7",
]
[[package]]
name = "deunicode"
version = "1.6.0"
@@ -2076,7 +2056,6 @@ dependencies = [
"bytemuck",
"ecolor",
"emath",
"epaint_default_fonts",
"font-types 0.12.6",
"harfrust",
"log",
@@ -2092,12 +2071,6 @@ dependencies = [
"vello_cpu 0.1.0",
]
[[package]]
name = "epaint_default_fonts"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773fa9c96dd0dbef887e39d0ed6177f141cce4d68e6041df77570aa3702dfa13"
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -2794,15 +2767,6 @@ dependencies = [
"smallvec",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
@@ -2827,11 +2791,11 @@ dependencies = [
[[package]]
name = "hashlink"
version = "0.9.1"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb"
dependencies = [
"hashbrown 0.14.5",
"hashbrown 0.17.1",
]
[[package]]
@@ -3949,7 +3913,7 @@ dependencies = [
"sha2 0.10.9",
"tempfile",
"tokio",
"zip 9.0.2",
"zip",
]
[[package]]
@@ -4016,7 +3980,7 @@ dependencies = [
"serde_json",
"tempfile",
"zeroize",
"zip 9.0.2",
"zip",
]
[[package]]
@@ -4061,7 +4025,7 @@ dependencies = [
"typst-as-lib",
"typst-layout",
"typst-pdf",
"zip 9.0.2",
"zip",
]
[[package]]
@@ -4111,7 +4075,7 @@ dependencies = [
"serde_json",
"tempfile",
"toml 1.1.8+spec-1.1.0",
"zip 9.0.2",
"zip",
]
[[package]]
@@ -4121,9 +4085,9 @@ dependencies = [
"hayro 0.8.0",
"hayro-interpret 0.8.0",
"kurbo",
"quick-xml 0.38.4",
"quick-xml 0.42.0",
"thiserror 2.0.21",
"zip 9.0.2",
"zip",
]
[[package]]
@@ -4208,9 +4172,9 @@ dependencies = [
[[package]]
name = "libsqlite3-sys"
version = "0.30.1"
version = "0.39.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3"
dependencies = [
"cc",
"pkg-config",
@@ -5574,9 +5538,9 @@ dependencies = [
[[package]]
name = "pulldown-cmark"
version = "0.13.5"
version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "278e9268c93b9e498a2da46c34d90ba93a3255eb99009646398f34bc73ab36eb"
checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b"
dependencies = [
"bitflags 2.13.2",
"memchr",
@@ -6077,9 +6041,9 @@ dependencies = [
[[package]]
name = "rmcp"
version = "3.5.1"
version = "3.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab5023804cbe0304cbe06197ac16e645a0a0d0ffa2953bf735c15c2fa0213350"
checksum = "d24a7e92f4bcaa36b97fa93c4fa7ca8f3e669eced949345b3462dba333c7f909"
dependencies = [
"async-trait",
"base64 0.23.1",
@@ -6090,6 +6054,7 @@ dependencies = [
"http-body",
"http-body-util",
"indexmap",
"libc",
"pastey",
"pin-project-lite",
"rand 0.10.3",
@@ -6098,6 +6063,7 @@ dependencies = [
"schemars",
"serde",
"serde_json",
"sha2 0.11.0",
"sse-stream",
"thiserror 2.0.21",
"tokio",
@@ -6110,9 +6076,9 @@ dependencies = [
[[package]]
name = "rmcp-macros"
version = "3.5.1"
version = "3.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1da498700030856ba63114bceefa30ba21f5e278cb975e5b9de3529fe842b40"
checksum = "b3140f24a766f80f9ec1607bde85680959a69b83d46fa9ce87dadab7e67ab029"
dependencies = [
"darling",
"proc-macro2",
@@ -6177,6 +6143,15 @@ dependencies = [
"lru",
]
[[package]]
name = "rsqlite-vfs"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "rtoolbox"
version = "0.0.6"
@@ -6189,9 +6164,9 @@ dependencies = [
[[package]]
name = "rusqlite"
version = "0.32.1"
version = "0.41.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594"
dependencies = [
"bitflags 2.13.2",
"fallible-iterator",
@@ -6199,6 +6174,7 @@ dependencies = [
"hashlink",
"libsqlite3-sys",
"smallvec",
"sqlite-wasm-rs",
]
[[package]]
@@ -6220,11 +6196,11 @@ dependencies = [
[[package]]
name = "rust_xlsxwriter"
version = "0.90.2"
version = "0.102.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2be778223b36bb449b2ef2df4856ced2d311680818a7310db5c5dc370170f935"
checksum = "6ca3d0e879a578c1313c2800ab0c6c029d38eed18098675e50341a30d32372ed"
dependencies = [
"zip 4.6.1",
"zip",
]
[[package]]
@@ -6287,9 +6263,9 @@ dependencies = [
[[package]]
name = "rustls"
version = "0.23.45"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"aws-lc-rs",
"once_cell",
@@ -6350,9 +6326,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
[[package]]
name = "rustls-webpki"
version = "0.103.15"
version = "0.103.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
dependencies = [
"aws-lc-rs",
"ring",
@@ -6879,6 +6855,16 @@ dependencies = [
"bitflags 2.13.2",
]
[[package]]
name = "sqlite-wasm-rs"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36bd8e29bf08189a005b2df1df99823aa0861cabe9044e5f31ed54ca292ee618"
dependencies = [
"cc",
"rsqlite-vfs",
]
[[package]]
name = "sse-stream"
version = "0.2.6"
@@ -7254,9 +7240,9 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "tokio"
version = "1.53.2"
version = "1.54.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044"
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
dependencies = [
"bytes",
"libc",
@@ -8565,9 +8551,9 @@ dependencies = [
[[package]]
name = "webpki-root-certs"
version = "1.0.9"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a"
dependencies = [
"rustls-pki-types",
]
@@ -9478,20 +9464,6 @@ dependencies = [
"syn 3.0.7",
]
[[package]]
name = "zip"
version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
dependencies = [
"arbitrary",
"crc32fast",
"flate2",
"indexmap",
"memchr",
"zopfli",
]
[[package]]
name = "zip"
version = "9.0.2"
@@ -9546,27 +9518,27 @@ dependencies = [
[[package]]
name = "zstd"
version = "0.14.2"
version = "0.14.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "057cfd910cfac363a0ada849592624b4c9ff2e10bef504c3433810d78ed96f93"
checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "8.1.0"
version = "8.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdd44c6a7284e91f3717755b24315a302edd9153a01f753c3cba3d765e8eafac"
checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.1.1+zstd.1.5.7"
version = "2.1.2+zstd.1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aeec9eaf2dffbbd09201e23bd0ffcbaa33bb8e9266a10734fd7ed90a85eca078"
checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3"
dependencies = [
"cc",
"pkg-config",
+10
View File
@@ -6,6 +6,10 @@ members = ["crates/ledger-core", "crates/ledger-store", "crates/ledger-config",
edition = "2024"
license = "MIT OR Apache-2.0"
repository = "https://git.swaits.com/swaits/wanderbooks"
# The crates are parts of one program, built from this tree and shipped as
# its packages. None is a library for crates.io, and saying so lets
# `cargo deny` accept their path dependencies on each other.
publish = false
[workspace.lints.rust]
missing_docs = "warn"
@@ -35,3 +39,9 @@ opt-level = 3
# AppImage, .deb and .rpm are not carrying debug tables.
[profile.release]
strip = "symbols"
# The shipped program refuses the way the tested one does. Without this an
# integer that overflows wraps silently in a release build and panics in
# a test build, so the tests would be checking a program nobody runs.
# Money is Decimal and goes through the kernel's checked arithmetic; this
# covers the integers around it (counts, sequence numbers, minor units).
overflow-checks = true
File diff suppressed because it is too large. Load diff
+43
View File
@@ -0,0 +1,43 @@
# What cargo-about may report when it writes THIRD-PARTY-NOTICES.txt
# (`just notices`). The accepted list is deny.toml's `allow` list, word for
# word: the gate and the notices describe the same set of licences. A
# licence that is not here is not in the program either; if cargo-about
# meets one, fix the dependency, never this list.
accepted = [
"MIT",
"MIT-0",
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"BSD-2-Clause",
"BSD-3-Clause",
"ISC",
"Zlib",
"0BSD",
"BSL-1.0",
"CC0-1.0",
"Unlicense",
"Unicode-3.0",
"bzip2-1.0.6",
"MPL-2.0",
"CDLA-Permissive-2.0",
]
# Every platform the program ships on. The list is fixed rather than the
# build machine's, so the notices name the same dependencies everywhere.
targets = [
"x86_64-unknown-linux-gnu",
"aarch64-unknown-linux-gnu",
"x86_64-apple-darwin",
"aarch64-apple-darwin",
"x86_64-pc-windows-msvc",
]
# Only what the binary links: a build script's dependencies and the tests'
# are not shipped, so their licences have no notice to travel with.
ignore-build-dependencies = true
ignore-dev-dependencies = true
# The workspace's own crates are `publish = false`: they are the program,
# not third parties, and the program's own licence is stated at the top of
# the notices.
private = { ignore = true }
+3 -1
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
description = "wanderbooks: the one executable (viewer, books server, host, agents' bridge, owner's commands)."
[[bin]]
@@ -32,7 +33,7 @@ jsonschema = { version = "0.58", default-features = false }
libc = "0.2"
proptest = "1"
reqwest = "0.13"
rusqlite = { version = "0.32", features = ["bundled"] }
rusqlite = { version = "0.41", features = ["bundled", "fallible_uint"] }
rust_decimal = "1"
rmcp = { version = "3", features = ["client", "transport-streamable-http-client-reqwest"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
@@ -61,4 +62,5 @@ assets = [
{ source = "target/release/wanderbooks", dest = "/usr/bin/wanderbooks", mode = "0755" },
{ source = "deploy/packaging/install-method-rpm", dest = "/usr/share/wanderbooks/install-method", mode = "0644" },
{ source = "deploy/packaging/wanderbooks-static.desktop", dest = "/usr/share/applications/wanderbooks.desktop", mode = "0644" },
{ source = "THIRD-PARTY-NOTICES.txt", dest = "/usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt", mode = "0644" },
]
+51 -10
View File
@@ -11,8 +11,14 @@
//! agent).
use std::env;
use std::io::Write;
use std::path::PathBuf;
/// Every third-party licence the program must travel with, built into it
/// by the build (`just notices`; scripts/notices.sh). `wanderbooks
/// licenses` prints it.
const NOTICES: &str = include_str!("../../../THIRD-PARTY-NOTICES.txt");
fn print_usage() {
eprintln!("usage: wanderbooks setup [--root PATH] [--home DIR]");
eprintln!(" wanderbooks gui [BOOK | --root PATH --book ID]");
@@ -29,6 +35,7 @@ fn print_usage() {
eprintln!(" wanderbooks download --book ID [--token NAME] ATTACHMENT --to FOLDER");
eprintln!(" wanderbooks serve | close | doctor");
eprintln!(" wanderbooks update [--check] | rollback");
eprintln!(" wanderbooks licenses");
eprintln!();
eprintln!(" setup make the books' private folder (only your account can open it)");
eprintln!(" gui open the live, read-only view of the books (a book of the data root)");
@@ -45,6 +52,7 @@ fn print_usage() {
eprintln!(" close close the books now: everything holding them lets go");
eprintln!(" doctor whether the books are open, what holds them, what went wrong");
eprintln!(" update bring this program to the newest release (`rollback` goes back)");
eprintln!(" licenses the licences of the libraries and fonts this program includes");
}
/// The viewer's arguments for `wanderbooks gui ARGS` (plan 3.6): a lone
@@ -381,6 +389,25 @@ fn run_server(args: Vec<String>) -> i32 {
}
}
/// `wanderbooks licenses`: the third-party notices compiled into the
/// program. It opens no books and reads no file: what it prints is part of
/// this binary. A pipe that closes early (`| head`) is how the reader
/// finished, not an error, so a write error is ignored.
fn run_licenses(args: Vec<String>) -> i32 {
if !args.is_empty() {
eprintln!("usage: wanderbooks licenses");
return 2;
}
let mut out = std::io::stdout().lock();
let header = format!(
"wanderbooks {} is licensed under MIT OR Apache-2.0.\n\n",
env!("CARGO_PKG_VERSION")
);
let _ = out.write_all(header.as_bytes());
let _ = out.write_all(NOTICES.as_bytes());
0
}
/// The modes that open and hold the books (plan 3.9): the host, the
/// agents' bridge, and the owner's commands.
fn run_local(mode: &str, args: Vec<String>) -> i32 {
@@ -478,6 +505,7 @@ fn main() {
Some("gui") => std::process::exit(run_gui(all.collect())),
Some("setup") => std::process::exit(run_setup(all.collect())),
Some("server") => std::process::exit(run_server(all.collect())),
Some("licenses") => std::process::exit(run_licenses(all.collect())),
Some(
mode @ ("host" | "mcp" | "serve" | "close" | "books" | "doctor" | "token" | "connect"
| "passphrase" | "update" | "rollback"),
@@ -499,16 +527,29 @@ fn main() {
std::process::exit(2);
}
// A mode named after a flag: it must come first.
match words
.iter()
.map(String::as_str)
.find(|w| !w.starts_with('-'))
{
Some(
mode @ ("gui" | "setup" | "server" | "host" | "mcp" | "serve" | "connect" | "close"
| "books" | "doctor" | "token" | "passphrase" | "update" | "rollback"
| "upload" | "download"),
) => {
match words.iter().map(String::as_str).find(|w| {
matches!(
*w,
"gui"
| "setup"
| "server"
| "host"
| "mcp"
| "serve"
| "connect"
| "close"
| "books"
| "doctor"
| "token"
| "passphrase"
| "update"
| "rollback"
| "upload"
| "download"
| "licenses"
)
}) {
Some(mode) => {
eprintln!("`{mode}` must come first: wanderbooks {mode} [its own flags]");
std::process::exit(2);
}
+80
View File
@@ -0,0 +1,80 @@
//! `wanderbooks licenses`: the third-party notices are part of the binary
//! and print as plain text, and the mode behaves like every other one.
use std::process::Command;
fn wanderbooks() -> Command {
Command::new(env!("CARGO_BIN_EXE_wanderbooks"))
}
#[test]
fn licenses_prints_the_notices_and_nothing_on_stderr() {
let out = wanderbooks().arg("licenses").output().unwrap();
assert_eq!(out.status.code(), Some(0), "{out:?}");
assert!(
out.stderr.is_empty(),
"{:?}",
String::from_utf8_lossy(&out.stderr)
);
let text = String::from_utf8(out.stdout).unwrap();
assert!(
text.starts_with("wanderbooks "),
"the version line comes first: {:?}",
&text[..text.len().min(80)]
);
for needle in [
"MIT OR Apache-2.0",
"Apache License",
"SIL OPEN FONT LICENSE",
"rust_decimal",
"egui",
"rusqlite",
"Inter Project Authors",
"Bitstream",
// A crate whose own licence file cargo-about cannot match (two
// licences in one file) still travels with its copyright line.
"LICENCE FILES AS PACKAGED",
"Kang Seonghoon",
"Packaged with no licence file",
] {
assert!(text.contains(needle), "{needle:?} is not in the notices");
}
}
#[test]
fn the_printed_notices_are_the_file_at_the_repository_root() {
let notices = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../THIRD-PARTY-NOTICES.txt"
));
let out = wanderbooks().arg("licenses").output().unwrap();
let done = out
.stdout
.windows(2)
.position(|w| w == b"\n\n")
.expect("the header line and an empty line");
assert_eq!(&out.stdout[done + 2..], notices);
}
#[test]
fn licenses_takes_no_arguments() {
let out = wanderbooks().args(["licenses", "extra"]).output().unwrap();
assert_eq!(out.status.code(), Some(2), "{out:?}");
assert!(
String::from_utf8_lossy(&out.stderr).contains("usage: wanderbooks licenses"),
"{out:?}"
);
}
#[test]
fn licenses_comes_first_like_every_mode() {
let out = wanderbooks()
.args(["--root", "x", "licenses"])
.output()
.unwrap();
assert_eq!(out.status.code(), Some(2), "{out:?}");
assert!(
String::from_utf8_lossy(&out.stderr).contains("must come first"),
"{out:?}"
);
}
+1
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
description = "Company settings for wanderbooks: an older books dir's wanderbooks.toml, read at adoption."
[dependencies]
+1
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
description = "Canonical double-entry bookkeeping semantics: the engine everything else is built on."
[dependencies]
+46 -5
View File
@@ -189,7 +189,7 @@ pub const CODES: &[CodeRow] = &[
CodeRow {
code: "close_split_drifts",
severity: Severity::Failure,
predicate: "a member's running share of the closes is more than a minor unit from its exact share",
predicate: "a member's running share of the closes drifts past the bound its regime allows from its exact share",
},
CodeRow {
code: "schedule_behind",
@@ -474,7 +474,12 @@ pub fn check_control(checks: &[crate::arap::ControlCheck]) -> Vec<Finding> {
}
fn closes(ledger: &Ledger, through: NaiveDate) -> Vec<Finding> {
let unit = Decimal::new(1, ledger.base_currency().minor_units().unwrap_or(2));
// The unit the allocation itself splits to, from the one helper both
// sides use (`Currency::allocation_unit`, on `allocation_places`):
// for a currency with no minor unit the split is far finer than a
// cent, and the audit must not check it at a cent (BS-partner-1
// statement 4).
let unit = ledger.base_currency().allocation_unit();
let mut out = Vec::new();
for p in ledger.list_periods() {
if p.status != PeriodStatus::Closed || p.end > through {
@@ -496,8 +501,33 @@ fn closes(ledger: &Ledger, through: NaiveDate) -> Vec<Finding> {
/// that posted an entry ([`crate::Ledger::member_close_trued_up`]). Until
/// then the count may still carry the rounding of closes made under the
/// older rules, which the first such close trues up (BS-partner-1
/// statement 6; WB-partner-1), so only a drift beyond a unit is raised.
/// Once trued up, a drift of a unit or more is raised: the bound is strict.
/// statement 6; WB-partner-1).
///
/// ```text
/// SOURCE: BS-partner-1 statement 5 (after a close that posts, a member's
/// total MUST be under one smallest unit from their exact share);
/// BS-partner-1 statement 6 (the rounding left by an earlier rule
/// is trued up by the first close that posts: a last-absorbs close
/// rounded each member but the last to within half a unit, and
/// the last absorbed up to half a unit for each of the others --
/// a unit with three members, more with four or more); WB-ledger-16
/// invariant 8.
/// DERIVED: the rule states those per-member facts; it does not state an
/// audit bound. The pre-true-up bound below is derived from them:
/// with n members and unit u under last-absorbs, member i (not last)
/// carries rounding e_i with |e_i| <= u/2, and the last member's part
/// is the remainder, so e_last = -(e_1 + ... + e_{n-1}) and
/// |e_last| <= (n-1) * u/2. The largest drift any member of one such
/// close may legitimately carry is therefore (n-1)*u/2: u with three
/// members, 3u/2 with four, 2u with five. Statement 6 also allows
/// under u per member for each break in an earlier run and for each
/// per-close close, so the allowance is floored at u:
/// B(n) = max(u, (n-1)*u/2). A drift past B(n) is raised; a drift of
/// exactly B(n) is legitimate (every non-last tie rounding the same
/// way reaches it), so the pre-true-up test is strict (> B(n)).
/// Once trued up, statement 5's bound is strict the other way: a
/// drift of a unit or more is raised (>= u).
/// ```
pub fn check_split(
period: u64,
name: &str,
@@ -505,11 +535,22 @@ pub fn check_split(
unit: Decimal,
trued_up: bool,
) -> Vec<Finding> {
// B(n) as derived above: (n-1)*u/2, floored at u. `unit` is a power
// of ten and n is small, so the product and the halving are exact.
let legacy_bound = {
let others = Decimal::new(split.len().saturating_sub(1) as i64, 0);
let last = others * unit / Decimal::new(2, 0);
if last > unit { last } else { unit }
};
split
.iter()
.filter(|m| {
let drift = (m.running - m.exact).abs();
if trued_up { drift >= unit } else { drift > unit }
if trued_up {
drift >= unit
} else {
drift > legacy_bound
}
})
.map(|m| {
Finding::new(
+2 -3
View File
@@ -34,9 +34,8 @@
//! it) is shared among the members credited in proportion to their
//! credits, to the base currency's minor unit (cents, whole yen),
//! leftover units by largest remainder
//! (kernel::apportion, a tie in the rounded remainders to the
//! earlier member; an exact tie follows the quotient's 28th digit,
//! K-U10): each takes at
//! (kernel::apportion over the exact remainders, a tie to the
//! earlier member, K-U10): each takes at
//! most its own credit, and the split depends on the order the
//! members are given only for a tied leftover cent (never on line
//! order). Joint property is joint (BS-partner-1's
+54 -23
View File
@@ -9,7 +9,10 @@
//! division, so a `Decimal` quotient is rounded at 28 significant digits
//! (and a machine integer's is truncated), never an exact rational.
//! Multiplication is not exact either at `Decimal`'s 96-bit mantissa:
//! `checked_mul` rounds the product there. Every invariant below is
//! `checked_mul_rounded` rounds the product there, and this module uses
//! it by name wherever a rounded product is the figure meant (the
//! kernel's `checked_mul` is exact or refused, K-U10, and would refuse a
//! share by a percent of 27 places). Every invariant below is
//! stated of that computation, and of the parts after the named leftover
//! policy, which do sum to the whole exactly. See `docs/proofs/k-u3.md`
//! for the edges where a product's or a quotient's rounding can change a
@@ -21,11 +24,10 @@ use super::{Amount, apportion, plug_last};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Leftover {
/// Each part is rounded down; the units left over go one each to the
/// largest remainders. The remainders are the rounded quotients'
/// differences, not exact rationals, so ranking follows the quotient:
/// an exact tie can go where the quotient's 28th digit sends it, and
/// only a tie in the rounded remainders goes to the earlier part. K-U10
/// decides the exact ranking. [`apportion`].
/// largest remainders. The remainders are exact: `whole x weight -
/// part x total`, an integer comparison, never the rounded quotient's
/// difference, so an exact tie goes to the earlier part (the Lean
/// model's rank, bookspec's `Apportion`). [`apportion`].
LargestRemainder,
/// The last part becomes the whole less the others. [`plug_last`].
LastAbsorbs,
@@ -47,10 +49,13 @@ pub enum Leftover {
/// government's part of a payment), BS-arap-3 (a document line's
/// exact amount).
/// INVARIANTS:
/// 1. Some(s) is the amount type's `checked_mul` of whole and weight,
/// then its checked division by total. For Decimal the product and
/// quotient are exact while they fit 96 bits and scale 28, and are
/// rounded at that edge (rust_decimal's checked operations, K-U10);
/// 1. Some(s) is the amount type's `checked_mul_rounded` of whole and
/// weight, then its checked division by total. For Decimal the
/// product and quotient are exact while they fit 96 bits and scale
/// 28, and are rounded at that edge (rust_decimal's checked
/// operations: a share by a percent of 27 places is a rounded figure
/// by construction, and is computed so, to the digit; K-U10 left
/// this one product rounding, because the quotient rounds anyway);
/// for a machine integer the division truncates toward zero. This is
/// the computation the six call sites made before U3, to the digit.
/// 2. None when total is zero, or when the product or quotient is not
@@ -68,7 +73,7 @@ pub enum Leftover {
/// be None.
/// ```
pub fn share_of<T: Amount>(whole: T, weight: T, total: T) -> Option<T> {
whole.checked_mul(weight)?.checked_div(total)
whole.checked_mul_rounded(weight)?.checked_div(total)
}
/// The largest whole multiple of `step` not above `whole × weight ÷ total`,
@@ -120,7 +125,7 @@ pub fn share_floor_with<T: Amount>(
if total <= T::ZERO || step <= T::ZERO {
return None;
}
let num = whole.checked_mul(weight)?;
let num = whole.checked_mul_rounded(weight)?;
let quotient = num.checked_div(total)?;
let mut part = round(quotient)?;
// The quotient may have rounded across the exact floor: take whole
@@ -130,7 +135,7 @@ pub fn share_floor_with<T: Amount>(
// K-U10, pinned in the bridge). Both directions are bounded so a
// quotient rounded far across the floor refuses instead of hanging.
let mut steps = 0;
while part.checked_mul(total)? > num {
while part.checked_mul_rounded(total)? > num {
if steps == MAX_CORRECTION_STEPS {
return None;
}
@@ -143,13 +148,13 @@ pub fn share_floor_with<T: Amount>(
return None;
}
let next = part.checked_add(step)?;
if next.checked_mul(total)? > num {
if next.checked_mul_rounded(total)? > num {
break;
}
part = next;
steps += 1;
}
let remainder = num.checked_sub(part.checked_mul(total)?)?;
let remainder = num.checked_sub(part.checked_mul_rounded(total)?)?;
Some((part, remainder))
}
@@ -195,11 +200,13 @@ const MAX_CORRECTION_STEPS: usize = 4096;
/// a part more than one step from the exact rational (K-U10, pinned
/// in the bridge). Under the first/last-absorbs policies only the
/// absorbing part may be further, by the rounding of all the others.
/// The largest-remainder ranking compares the rounded quotients'
/// remainders, not exact rationals: an exact tie can go where
/// `Decimal`'s 28th digit sends it, and only a tie in the rounded
/// remainders goes to the earlier part (K-U10 decides the exact
/// rule; the bridge pins today's answer).
/// The largest-remainder ranking compares the exact remainders
/// `whole x weight - part x total` (the quantity `share_floor_with`
/// returns, scaled by total; the sign flipped for a negative total),
/// never the rounded quotients' differences. An exact tie goes to the
/// earlier part, whatever `Decimal`'s 28th digit would have said
/// (K-U10, the owner's decision; exact while the products are, as
/// above).
/// 3. With total not zero, no part exceeds the whole when every weight
/// is in [0, total] and the whole is not negative; no part is
/// negative when the weights and the whole are not.
@@ -213,13 +220,19 @@ const MAX_CORRECTION_STEPS: usize = 4096;
/// promised.
/// SCENARIOS:
/// 1. IF 100 by 1/1/1 to the cent by largest remainder: SHOULD be
/// 33.34, 33.33, 33.33 (the rounded remainders tie, so the cent goes
/// 33.34, 33.33, 33.33 (the exact remainders tie, so the cent goes
/// to the earlier part).
/// 2. IF 0.01 by 1/1 to the cent by largest remainder: SHOULD be
/// 0.01, 0.00.
/// 3. IF 10 by weights 2/3/5 by first-absorbs: SHOULD be the rounded
/// shares with the first taking the whole less the others.
/// 4. IF the total is zero, or every weight is zero: SHOULD be zeros (a
/// 4. IF 20.00 by 4/1/1 over 6 to the cent by largest remainder: SHOULD
/// be 13.34, 3.33, 3.33. The exact remainders (0.02, 0.02, 0.02 over
/// 6, as 80 - 79.98, 20 - 19.98) tie, so the cent goes to the first.
/// The rounded quotients (13.33...3 keeps one fewer fractional digit
/// than 3.33...3 at 28 significant digits) would have put the
/// second's remainder above the first's.
/// 5. IF the total is zero, or every weight is zero: SHOULD be zeros (a
/// zero total) or the largest-remainder handout of the whole (a
/// positive total with zero weights, as the conventions' template
/// split has always done).
@@ -257,8 +270,26 @@ pub fn split_by_weights_into<T: Amount>(
if unit <= T::ZERO {
return None;
}
// Rank by the exact remainder, never the rounded quotient's
// difference: `whole x weight - part x total`, the exact
// rational's fraction scaled by `total`, the same quantity
// `share_floor_with` returns. A negative total flips the
// scale's sign, so the order is the share's own. The two
// products are the rounding ones: each is exact while it fits
// Decimal's mantissa (every split of posted amounts by whole
// weights or basis points), and where a weight of 27 places
// makes a product round, the split is still made, ranked by
// the nearest figures Decimal holds, not refused. Their
// difference is exact: the subtraction refuses otherwise.
for i in 0..weights.len() {
remainders[i] = remainders[i].checked_sub(parts[i])?;
let exact = whole
.checked_mul_rounded(weights[i])?
.checked_sub(parts[i].checked_mul_rounded(total)?)?;
remainders[i] = if total < T::ZERO {
T::ZERO.checked_sub(exact)?
} else {
exact
};
}
apportion(whole, parts, remainders, unit)
}
@@ -0,0 +1,309 @@
//! The exactness check behind `impl Amount for Decimal` (K-U10): a sum or
//! a product `rust_decimal` returns is the exact one, or the kernel
//! refuses it.
//!
//! `rust_decimal`'s `checked_add` and `checked_mul` return `None` only
//! when the integer part overflows. When the exact result merely needs
//! more than 96 bits of mantissa, or a scale past 28, they *round* it and
//! return `Some` (found by K-U1, K-U4, K-U8: `MAX + 0.4` is `Some(MAX)`;
//! `0.01 + 792281625142643375935439503.35` is `…503.4`;
//! `1050000010.0000000001 x 9.9999999999` is `10500000099.895`). The
//! kernel's contract is "exact or `None`" (BS-ledger-1: a product the
//! arithmetic cannot hold MUST be refused), so each operation here runs
//! `rust_decimal`'s and then checks, in integers wide enough that nothing
//! can overflow, that the figure it returned equals the exact result as a
//! rational. It never builds a rounded figure of its own, and a result
//! that is exact is returned as `rust_decimal` gave it, scale and all, so
//! nothing exact changes.
//!
//! A `Decimal` is `m x 10^-s` with `|m| < 2^96` and `s <= 28`. Every
//! quantity compared below is at most `2^96 x 10^28 < 2^190`, or a
//! product `2^96 x 2^96 = 2^192`, so 256 bits hold all of them.
use rust_decimal::Decimal;
/// An unsigned 256-bit integer: `hi x 2^128 + lo`. The field order makes
/// the derived `Ord` the numeric order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Wide {
hi: u128,
lo: u128,
}
impl Wide {
const ZERO: Wide = Wide { hi: 0, lo: 0 };
fn from_u128(lo: u128) -> Wide {
Wide { hi: 0, lo }
}
/// `a x b`, in full.
fn mul_wide(a: u128, b: u128) -> Wide {
const HALF: u128 = (1 << 64) - 1;
let (a1, a0) = (a >> 64, a & HALF);
let (b1, b0) = (b >> 64, b & HALF);
let p00 = a0 * b0;
let p01 = a0 * b1;
let p10 = a1 * b0;
let p11 = a1 * b1;
// The middle column: three 64-bit terms, under 3 x 2^64.
let mid = (p00 >> 64) + (p01 & HALF) + (p10 & HALF);
Wide {
lo: (mid << 64) | (p00 & HALF),
hi: p11 + (p01 >> 64) + (p10 >> 64) + (mid >> 64),
}
}
fn checked_add(self, other: Wide) -> Option<Wide> {
let (lo, carry) = self.lo.overflowing_add(other.lo);
let hi = self
.hi
.checked_add(other.hi)?
.checked_add(u128::from(carry))?;
Some(Wide { hi, lo })
}
/// `self x k`, `None` past 256 bits.
fn checked_mul_small(self, k: u128) -> Option<Wide> {
let low = Wide::mul_wide(self.lo, k);
let hi = self.hi.checked_mul(k)?.checked_add(low.hi)?;
Some(Wide { hi, lo: low.lo })
}
/// `(self / 10, self % 10)`.
fn div_rem_10(self) -> (Wide, u128) {
const HALF: u128 = (1 << 64) - 1;
let hi = self.hi / 10;
let carry = self.hi % 10;
let upper = (carry << 64) | (self.lo >> 64);
let lower = ((upper % 10) << 64) | (self.lo & HALF);
(
Wide {
hi,
lo: ((upper / 10) << 64) | (lower / 10),
},
lower % 10,
)
}
/// The value as a `u128`, when it fits.
fn to_u128(self) -> Option<u128> {
(self.hi == 0).then_some(self.lo)
}
/// `self x 10^k`, `None` past 256 bits.
fn checked_scale_up(self, mut k: u32) -> Option<Wide> {
let mut value = self;
while k > 0 {
let step = k.min(38);
value = value.checked_mul_small(10u128.pow(step))?;
k -= step;
}
Some(value)
}
}
/// `mantissa x 10^k`, as a 256-bit magnitude.
fn scaled(magnitude: u128, k: u32) -> Option<Wide> {
Wide::from_u128(magnitude).checked_scale_up(k)
}
/// `a + b`: `rust_decimal`'s sum when it is the exact sum, else `None`.
pub(super) fn exact_add(a: Decimal, b: Decimal) -> Option<Decimal> {
let sum = Decimal::checked_add(a, b)?;
sum_is_exact(a, b, sum).then_some(sum)
}
/// `a - b`: `rust_decimal`'s difference when it is the exact difference,
/// else `None`.
pub(super) fn exact_sub(a: Decimal, b: Decimal) -> Option<Decimal> {
let difference = Decimal::checked_sub(a, b)?;
sum_is_exact(a, -b, difference).then_some(difference)
}
/// `a x b`: `rust_decimal`'s product when it is the exact product, else
/// `None`.
pub(super) fn exact_mul(a: Decimal, b: Decimal) -> Option<Decimal> {
let product = Decimal::checked_mul(a, b)?;
product_is_exact(a, b, product).then_some(product)
}
/// Is `a + b == sum` as rationals? At the common scale `s` this is
/// `ma 10^(s-sa) + mb 10^(s-sb) - ms 10^(s-ss) == 0`; the terms are moved
/// by sign so each side is a sum of magnitudes (no signed arithmetic, no
/// overflow: every term is under 2^190). Any failure to compute is "not
/// exact", the safe answer.
fn sum_is_exact(a: Decimal, b: Decimal, sum: Decimal) -> bool {
let (ma, mb, ms) = (a.mantissa(), b.mantissa(), sum.mantissa());
let (sa, sb, ss) = (a.scale(), b.scale(), sum.scale());
if sa == sb && sb == ss {
// The common case (cents plus cents): no rescaling. Mantissas are
// under 2^96, so the i128 sum cannot overflow.
return ma + mb == ms;
}
let s = sa.max(sb).max(ss);
// The terms of a + b + (-sum), by sign.
let mut positive = Wide::ZERO;
let mut negative = Wide::ZERO;
for (mantissa, scale, flip) in [(ma, sa, false), (mb, sb, false), (ms, ss, true)] {
let Some(term) = scaled(mantissa.unsigned_abs(), s - scale) else {
return false;
};
let counts_negative = (mantissa < 0) != flip;
let side = if counts_negative {
&mut negative
} else {
&mut positive
};
let Some(next) = side.checked_add(term) else {
return false;
};
*side = next;
}
positive == negative
}
/// Is `a x b == product` as rationals? The exact product is
/// `ma x mb` at scale `sa + sb` (up to 2^192, at scale up to 56), compared
/// with `mp` at scale `sp` by scaling the side with fewer places up; an
/// overflow past 256 bits means that side is larger than the other, so
/// unequal.
fn product_is_exact(a: Decimal, b: Decimal, product: Decimal) -> bool {
let (ma, mb, mp) = (a.mantissa(), b.mantissa(), product.mantissa());
let exact = Wide::mul_wide(ma.unsigned_abs(), mb.unsigned_abs());
if exact == Wide::ZERO {
return mp == 0;
}
if mp == 0 || ((ma < 0) != (mb < 0)) != (mp < 0) {
return false;
}
let exact_scale = a.scale() + b.scale();
let held = Wide::from_u128(mp.unsigned_abs());
if exact_scale >= product.scale() {
held.checked_scale_up(exact_scale - product.scale()) == Some(exact)
} else {
exact.checked_scale_up(product.scale() - exact_scale) == Some(held)
}
}
/// The exact product `a x b` as a `Decimal` that rounds to a multiple of
/// any step of `step_scale` places (or fewer) the way the exact product
/// would, for a product `Decimal` cannot hold: the case
/// [`exact_mul`] refused.
///
/// The product is held in 256 bits and cut down a digit at a time until it
/// fits `Decimal`, remembering whether any cut digit was not zero (a
/// sticky digit, appended as a final `1`). At least one real digit is
/// kept below the step's own places, so the first digit past the step is
/// real and every later one is only "zero or not": that decides a tie
/// (a half followed by zeros) and the directed modes exactly as the full
/// product would, so the one rounding that follows is the correctly
/// rounded one. `None` when the product is too large to hold with those
/// digits: the figure times 10^(step places + 2) must fit 96 bits, so a
/// figure past about 7.9e26 at a whole-unit step, 7.9e24 at a cent (10^9
/// times a journal line's cap). For the same reason a step of 27 or 28
/// places is always `None` here: `Decimal` ends at 28 places, so there is
/// no place below such a step for the real digit and the sticky one. That
/// refuses some figures whose rounded result `Decimal` could hold (1e-28
/// squared to a step of 1e-27 is zero); a refusal, never a guess, and no
/// currency's step is within twenty places of it (pinned in the bridge:
/// `a_step_of_27_places_refuses_a_product_that_is_not_exact`). A zero
/// product is exact and never gets here.
pub(super) fn mul_for_rounding(a: Decimal, b: Decimal, step_scale: u32) -> Option<Decimal> {
let negative = (a.mantissa() < 0) != (b.mantissa() < 0);
let mut digits = Wide::mul_wide(a.mantissa().unsigned_abs(), b.mantissa().unsigned_abs());
let mut scale = a.scale() + b.scale();
let mut sticky = false;
loop {
// The candidate: the digits kept, then the sticky digit if any.
let (mantissa, candidate_scale) = if sticky {
(
digits
.checked_mul_small(10)
.and_then(|d| d.checked_add(Wide::from_u128(1)))
.and_then(Wide::to_u128),
scale + 1,
)
} else {
(digits.to_u128(), scale)
};
if let Some(m) = mantissa
&& candidate_scale <= Decimal::MAX_SCALE
&& let Ok(m) = i128::try_from(m)
&& let Ok(d) =
Decimal::try_from_i128_with_scale(if negative { -m } else { m }, candidate_scale)
{
return Some(d);
}
if scale <= step_scale + 1 {
return None;
}
let (rest, digit) = digits.div_rem_10();
digits = rest;
sticky |= digit != 0;
scale -= 1;
}
}
#[cfg(test)]
mod tests {
//! The 256-bit helpers against `num_bigint`, which shares no code with
//! them: they are private, so the bridge reaches them only through the
//! operations; these check them directly, edges included.
use super::*;
use num_bigint::BigUint;
use proptest::prelude::*;
fn big(w: Wide) -> BigUint {
(BigUint::from(w.hi) << 128u32) + BigUint::from(w.lo)
}
fn edge_u128() -> impl Strategy<Value = u128> {
prop_oneof![
any::<u128>(),
Just(0u128),
Just(1),
Just(u128::MAX),
Just(u128::from(u64::MAX)),
Just(u128::from(u64::MAX) + 1),
Just((1u128 << 96) - 1),
]
}
fn arb_wide() -> impl Strategy<Value = Wide> {
(edge_u128(), edge_u128()).prop_map(|(hi, lo)| Wide { hi, lo })
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(5000))]
#[test]
fn mul_wide_is_the_full_product(a in edge_u128(), b in edge_u128()) {
prop_assert_eq!(big(Wide::mul_wide(a, b)), BigUint::from(a) * BigUint::from(b));
}
#[test]
fn add_and_mul_small_are_exact_or_refuse(w in arb_wide(), o in arb_wide(), k in edge_u128()) {
let limit = BigUint::from(1u8) << 256u32;
let sum = big(w) + big(o);
prop_assert_eq!(w.checked_add(o).map(big), (sum < limit).then_some(sum));
let product = big(w) * BigUint::from(k);
prop_assert_eq!(w.checked_mul_small(k).map(big), (product < limit).then_some(product));
}
#[test]
fn div_rem_10_divides(w in arb_wide()) {
let (q, r) = w.div_rem_10();
prop_assert_eq!(big(q) * 10u8 + BigUint::from(r), big(w));
prop_assert!(r < 10);
}
#[test]
fn scale_up_is_a_power_of_ten(m in edge_u128(), k in 0u32..=60) {
let want = BigUint::from(m) * BigUint::from(10u8).pow(k);
let limit = BigUint::from(1u8) << 256u32;
prop_assert_eq!(scaled(m, k).map(big), (want < limit).then_some(want));
}
}
}
+69 -5
View File
@@ -12,7 +12,8 @@ use rust_decimal::Decimal;
pub trait Amount: Copy + Ord {
/// Zero.
const ZERO: Self;
/// `self + rhs`, or `None` when it cannot be represented exactly.
/// `self + rhs`, or `None` when it cannot be represented exactly (for
/// [`Decimal`], never a sum `rust_decimal` had to round: K-U10).
fn checked_add(self, rhs: Self) -> Option<Self>;
/// `-self`, or `None` when it cannot be represented.
fn checked_neg(self) -> Option<Self>;
@@ -27,9 +28,45 @@ pub trait Amount: Copy + Ord {
fn from_u32(n: u32) -> Option<Self>;
/// `self * rhs`, or `None` when it cannot be represented exactly.
///
/// A quantity times a unit price (a document line, BS-arap-3) is the one
/// use: it never rounds.
/// A quantity times a unit price (a document line, BS-arap-3), a
/// category's book amount times its percent, and the other products
/// that are the amount itself: it never rounds. For [`Decimal`] that
/// is a check, not a given (K-U10): `rust_decimal` rounds a product
/// whose mantissa passes 96 bits or whose scale passes 28, and this
/// refuses it instead.
fn checked_mul(self, rhs: Self) -> Option<Self>;
/// `self * rhs` as the amount type multiplies, which for [`Decimal`] is
/// `rust_decimal`'s: exact where the product fits 96 bits and scale
/// 28, otherwise rounded to what it holds. `None` only on overflow.
///
/// This is the engine's rounding product, as [`Amount::checked_div`]
/// is its rounding division, and for the same use: a proportional
/// share (`whole x weight / total`, [`crate::kernel::share_of`]) whose
/// weight is a percent or a ratio of many places (33.333...3, twenty
/// seven places) is a rounded figure by construction, and has always
/// been computed this way, to the digit. Nothing else calls it; a
/// product that is the amount is [`Amount::checked_mul`]. A machine
/// integer never rounds, so there it is `checked_mul`.
fn checked_mul_rounded(self, rhs: Self) -> Option<Self> {
self.checked_mul(rhs)
}
/// `self * rhs`, computed exactly and rounded once to a whole multiple
/// of `step` in `mode`; `None` when `step` is not positive or the
/// result cannot be represented.
///
/// The one use is a foreign amount at a rate ([`crate::kernel::fx_booked`]).
/// For [`Decimal`] the exact product may need more than 96 bits (ten
/// places each, D-75, is twenty places, and past 7.9e8 the mantissa
/// passes `Decimal`'s): it is held wider than `Decimal` for the one
/// rounding, never rounded early and then again. Two refusals come
/// with that, both far from any books: a product that is not exact
/// and is past about 7.9e26 divided by 10^(the step's places), and a
/// product that is not exact at a step of 27 or 28 places (the
/// rounding needs two places below the step, and `Decimal` ends at
/// 28). An exact product is rounded at any step.
fn checked_mul_round_to_step(self, rhs: Self, step: Self, mode: Rounding) -> Option<Self> {
super::round::round_step(self.checked_mul(rhs)?, step, mode)
}
/// `self / rhs` exactly, or `None` when `rhs` is zero or the quotient
/// is not a whole amount of `Self` (never a rounded share).
fn checked_div_exact(self, rhs: Self) -> Option<Self>;
@@ -79,8 +116,16 @@ pub const MAX_LINE_SCALE: u32 = 10;
impl Amount for Decimal {
const ZERO: Self = Decimal::ZERO;
// Exact or `None` (K-U10): `rust_decimal`'s own add and multiply round a
// result that needs more than 96 bits (or a scale past 28) instead of
// refusing it; `decimal_exact` checks the figure is the exact one.
fn checked_add(self, rhs: Self) -> Option<Self> {
Decimal::checked_add(self, rhs)
super::decimal_exact::exact_add(self, rhs)
}
// `rust_decimal`'s own subtraction, checked the same way (it is not
// `self + (-rhs)` for a zero: that gives a negative zero).
fn checked_sub(self, rhs: Self) -> Option<Self> {
super::decimal_exact::exact_sub(self, rhs)
}
fn checked_neg(self) -> Option<Self> {
Some(-self)
@@ -92,11 +137,30 @@ impl Amount for Decimal {
Some(Decimal::from(n))
}
fn checked_mul(self, rhs: Self) -> Option<Self> {
super::decimal_exact::exact_mul(self, rhs)
}
fn checked_mul_rounded(self, rhs: Self) -> Option<Self> {
Decimal::checked_mul(self, rhs)
}
fn checked_mul_round_to_step(self, rhs: Self, step: Self, mode: Rounding) -> Option<Self> {
if let Some(product) = super::decimal_exact::exact_mul(self, rhs) {
return super::round::round_step(product, step, mode);
}
// The exact product does not fit `Decimal`: round it once, from a
// wider integer, not twice.
if step <= Decimal::ZERO {
return None;
}
let proxy = super::decimal_exact::mul_for_rounding(self, rhs, step.normalize().scale())?;
super::round::round_step(proxy, step, mode)
}
fn checked_div_exact(self, rhs: Self) -> Option<Self> {
let q = self.checked_div(rhs)?;
(q.checked_mul(rhs) == Some(self)).then_some(q)
// The exact product, not `rust_decimal`'s: a rounded quotient
// times the divisor rounds back to the dividend there (10 / 3 is
// 3.333...3, and 3.333...3 x 3 is held as 10), which would pass a
// rounded share as an exact one.
(super::decimal_exact::exact_mul(q, rhs) == Some(self)).then_some(q)
}
fn checked_div(self, rhs: Self) -> Option<Self> {
Decimal::checked_div(self, rhs)
+44 -53
View File
@@ -1,11 +1,11 @@
//! U1: foreign-currency conversion, the booking of a foreign amount at
//! the transaction-date rate (kernel sweep, `plan/kernel-sweep-audit.md`
//! section 3). The one place foreign x rate becomes booked money: the
//! product is computed exactly and rounded once, by [`round_step`], to
//! product is computed exactly and rounded once, by [`round_step`](super::round_step), to
//! the base currency's smallest unit. No call site multiplies by a rate
//! itself.
use super::round::{Rounding, round_step};
use super::round::Rounding;
use crate::Currency;
use crate::kernel::Amount;
use rust_decimal::Decimal;
@@ -16,34 +16,27 @@ use rust_decimal::Decimal;
///
/// The rate's precision is carried by the value itself: a `Decimal`
/// rate keeps its own scale (1.0834567 is exact), and the product is the
/// `T::checked_mul` product before the single rounding. At `i64` (the
/// Kani model) amounts and the rate are plain integers in the smallest
/// unit, and the same law is proved of the product.
/// exact one before the single rounding. At `i64` (the Kani model)
/// amounts and the rate are plain integers in the smallest unit, and the
/// same law is proved of the product.
///
/// **The precondition that makes the product exact (D-75).** On
/// `Decimal`, `checked_mul` is exact only while the product keeps its
/// full scale: that scale (the two scales added) must be within 28, and
/// the product's mantissa (the two mantissas multiplied) must fit
/// `Decimal`'s 96 bits, under 7.9e28. A foreign amount and a rate of at
/// most [`MAX_LINE_SCALE`](super::MAX_LINE_SCALE) (10) places each,
/// trailing zeros not counted, meet the first half: a product of at most
/// 20 places, under 28. `Ledger::add_line_fx` enforces that bound on
/// every new line (never on replay). The second half is not enforced:
/// a product of 20 places past about 7.9e8 needs more than 96 bits, and
/// `Decimal` then drops places (see below). Under both halves the
/// product is the exact one and the result is rounded exactly once.
/// Outside them `Decimal::checked_mul` keeps the behaviours it has
/// always had, which this function inherits and does not hide: a
/// product that does not fit is rounded by `Decimal` (to 28 places, or
/// to the places 96 bits hold) before this function rounds it (a second
/// rounding, so a result can sit a unit off the exact product's:
/// 0.99999999999999999999999999 x 0.005 is 0.00499999999999999999999999995
/// exactly but 0.005 as held, and books 0.01; 1050000010.0000000001 x
/// 9.9999999999 is 10500000099.89 to the cent but 10500000099.895 as
/// held, and books 10500000099.90), and a product below 1e-28 (1e-28 x
/// 1e-28) underflows to zero. Invariants 2 and 3 are stated for
/// products that are exact; invariant 1 (a whole multiple of the step)
/// holds regardless. The bridge pins both behaviours.
/// **The exact product on `Decimal` (D-75, K-U10).** A foreign amount and
/// a rate of at most [`MAX_LINE_SCALE`](super::MAX_LINE_SCALE) (10) places
/// each, trailing zeros not counted, have an exact product of at most 20
/// places, and `Ledger::add_line_fx` enforces that bound on every new
/// line (never on replay). The product's mantissa can still pass
/// `Decimal`'s 96 bits (a product of twenty places past about 7.9e8), and
/// `Decimal::checked_mul` then drops places. `Amount::checked_mul_round_to_step`
/// does not use it for that case: it holds the exact product in 256 bits,
/// cuts it down only as far as `Decimal` needs (remembering whether any
/// cut digit was not zero), and rounds once, so 1050000010.0000000001 x
/// 9.9999999999 (10500000099.89499999999999999999 exactly) books
/// 10500000099.89, where it booked 10500000099.90 through a rounded
/// 10500000099.895. The same holds past ten places: a product below 1e-28
/// (1e-28 x 1e-28) rounds to zero because its exact value does, and
/// 0.99999999999999999999999999 x 0.005 books 0.00 (the engine refuses
/// such an input all the same, D-75). `None` only for a figure too large
/// to hold with its rounding digits (about 7.9e24 at a cent).
///
/// ```text
/// GOAL: book a foreign amount in the ledger's one money: the exact
@@ -60,43 +53,41 @@ use rust_decimal::Decimal;
/// bookspec's Lean).
/// INVARIANTS:
/// 1. Some(r) is a whole multiple of step: r = n x step for an
/// integer n. None when step <= 0, when rate <= 0, or when T's
/// checked_mul cannot hold the product (the exact product, under
/// the precondition above) or the rounded result cannot be held.
/// 2. Under the precondition (both halves: the product is exact), in
/// HalfAwayFromZero (the mode add_line_fx books in) r is within
/// integer n. None when step <= 0, when rate <= 0, or when the
/// rounded result cannot be held.
/// 2. In HalfAwayFromZero (the mode add_line_fx books in) r is within
/// half a step of the exact product foreign x rate, an exact half
/// going to the multiple farther from zero.
/// 3. Under the precondition, positive foreign and rate give a
/// non-negative r, and a positive r whenever the exact product
/// reaches half a step (a smaller product rounds to zero, which
/// the caller refuses as it does today). The sign never crosses
/// zero.
/// going to the multiple farther from zero: the product is rounded
/// once, from the exact one, however many bits it needs (K-U10).
/// 3. Positive foreign and rate give a non-negative r, and a positive
/// r whenever the exact product reaches half a step (a smaller
/// product rounds to zero, which the caller refuses as it does
/// today). The sign never crosses zero.
/// 4. On Decimal the value equals the pre-kernel computation
/// (checked_mul, then round_minor half away from zero) exactly;
/// (checked_mul, then round_minor half away from zero) exactly
/// wherever that product was exact; where Decimal had rounded the
/// product first, the figure is now the once-rounded one;
/// fx_booked_minor also keeps its scale.
/// SCENARIOS:
/// 1. IF 100.00 at 1.0834567 to the cent: SHOULD book 108.35.
/// 2. IF 10.00 at 151.237 to the yen (step 1): SHOULD book 1512.
/// 3. IF the rate is zero or negative: SHOULD be None, never a guess.
/// 4. IF foreign x rate overflows: SHOULD be None, never a panic.
/// 4. IF foreign x rate is too large to hold: SHOULD be None, never a
/// panic.
/// 5. IF foreign is 0.99999999999999999999999999 (26 places) and
/// the rate 0.005 to the cent: outside the precondition, books
/// 0.01 where the exact product is under half a cent BECAUSE
/// Decimal rounded the product first; the engine refuses such an
/// input (D-75), and the bridge pins this behaviour.
/// the rate 0.005 to the cent: SHOULD book 0.00, the exact product
/// being under half a cent (it booked 0.01 when Decimal rounded the
/// product first); the engine refuses such an input (D-75).
/// 6. IF foreign 1050000010.0000000001 at 9.9999999999 to the cent
/// (ten places each, a product past 96 bits): outside the
/// precondition's second half, books 10500000099.90 where the
/// exact product rounds to 10500000099.89; the bridge pins this
/// open edge.
/// (ten places each, a product past 96 bits): SHOULD book
/// 10500000099.89, the exact product's cent (it booked
/// 10500000099.90 when Decimal rounded the product first).
/// ```
pub fn fx_booked<T: Amount>(foreign: T, rate: T, step: T, mode: Rounding) -> Option<T> {
if rate <= T::ZERO {
return None;
}
let exact = foreign.checked_mul(rate)?;
round_step(exact, step, mode)
foreign.checked_mul_round_to_step(rate, step, mode)
}
/// [`fx_booked`] at a currency's minor unit, on `Decimal`: the spelling
@@ -126,7 +117,7 @@ pub fn fx_booked_minor(
if rate <= Decimal::ZERO {
return None;
}
return foreign.checked_mul(rate);
return Amount::checked_mul(foreign, rate);
};
let step = Decimal::try_from_i128_with_scale(1, places).ok()?;
let rounded = fx_booked(foreign, rate, step, mode)?;
+1
View File
@@ -69,6 +69,7 @@
mod allocate;
mod control;
mod decimal_exact;
mod entries;
mod fx;
mod payroll;
+2 -2
View File
@@ -31,8 +31,8 @@ use super::{Amount, Rounding, round_step, share_of};
/// 1. Some(r) is round_step(part / whole × 100, step, mode), computed
/// division first and then the multiplication, the order every call
/// site used before U6. For Decimal the quotient is exact while it
/// fits 28 significant digits and the product while it fits the
/// 96-bit mantissa; either operation rounds at that edge (K-U10).
/// fits 28 significant digits and rounds past them; the product by
/// 100 is exact or refused, never rounded (K-U10).
/// For a machine integer the division truncates toward zero.
/// 2. None when whole <= 0, step <= 0, or a quotient, product or
/// rounded result is not representable. Never a panic.
+2 -1
View File
@@ -1908,7 +1908,8 @@ impl Ledger {
// under Decimal's 28) and keeps its scale: the booked amount is
// rounded once, not after Decimal's own rounding of the product.
// (A 20-place product past about 7.9e8 still outgrows Decimal's 96
// bits; kernel::fx_booked's spec block names that open edge.)
// bits; since K-U10 the kernel holds that product in 256 bits for
// the one rounding, so it too is booked from the exact product.)
// The command's bound, never replay's: a journal's older line with
// a finer foreign amount opens as it was booked (replay_add_line_fx).
if !crate::parties::is_replaying() {
+13 -6
View File
@@ -69,6 +69,17 @@ impl Currency {
self.minor_units().unwrap_or(crate::kernel::MAX_LINE_SCALE)
}
/// One allocation unit as an amount: `1` at [`Self::allocation_places`]
/// (a cent, a whole yen, a thousandth of a dinar, the finest a line
/// carries for a code with no minor unit). This is the one place that
/// turns the places into an amount, so a split and a check of that
/// split take their unit from the same rule and cannot drift apart
/// (BS-partner-1 statement 4: the allocation is the split of the
/// amount to the base currency's smallest unit).
pub fn allocation_unit(&self) -> Decimal {
Decimal::new(1, self.allocation_places())
}
/// The three-letter code, e.g. `"USD"`.
pub fn code(&self) -> &str {
std::str::from_utf8(&self.0).expect("currency codes are ASCII by construction")
@@ -134,9 +145,7 @@ impl Money {
/// panic, never rounded).
pub fn checked_add(self, rhs: Money) -> Result<Money, LedgerError> {
self.check_currency(&rhs)?;
let amount = self
.amount
.checked_add(rhs.amount)
let amount = crate::kernel::Amount::checked_add(self.amount, rhs.amount)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{} plus {}", self, rhs)))?;
Ok(Money::new(amount, self.currency))
}
@@ -145,9 +154,7 @@ impl Money {
/// `TooLargeToCompute` when the difference is past exact arithmetic.
pub fn checked_sub(self, rhs: Money) -> Result<Money, LedgerError> {
self.check_currency(&rhs)?;
let amount = self
.amount
.checked_sub(rhs.amount)
let amount = crate::kernel::Amount::checked_sub(self.amount, rhs.amount)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{} minus {}", self, rhs)))?;
Ok(Money::new(amount, self.currency))
}
+25 -22
View File
@@ -22,10 +22,11 @@
//! INVARIANTS:
//! 1. The parts sum to the whole, for every policy.
//! 2. Under largest remainder each part is within one unit (the step)
//! of its exact share: `-total < part x total - whole x weight <=
//! total` at step one. The upper bound is inclusive on `i64` (its
//! division truncates); the bridge checks the strict `Decimal`
//! bound.
//! of its exact share: `-total < part x total - whole x weight <
//! total` at step one, and a part whose share is exact takes no
//! unit. Both rest on the ranking by the exact remainder (K-U10,
//! D-76): `i64`'s division truncates, and the ranking no longer
//! reads the quotient.
//! 3. No part is negative or above the whole for non-negative weights
//! that do not exceed the total.
//! 4. A zero total gives zeros; all-zero weights hand the whole out by
@@ -33,7 +34,7 @@
//! units as there are parts.
//! 5. Overflow is `None`, never a panic.
//! SCENARIOS:
//! 1. IF 101 by 1/1/1 to the unit: SHOULD be 34/34/33 (the rounded
//! 1. IF 101 by 1/1/1 to the unit: SHOULD be 34/34/33 (the exact
//! remainders tie, so the units go to the earlier parts), never
//! 33/34/34.
//! 2. IF a quotient rounds up across the step: `share_floor_with`
@@ -44,8 +45,8 @@
//! Bounds: amounts up to 1,000, weights up to 100, totals fixed (10 and
//! 0), steps 1 and 10. The laws are about the shape of the split, not the
//! magnitude; Lean proves them of the exact-share model at any size, and
//! the bridge checks the `Decimal` engine, whose ranking uses the rounded
//! quotient.
//! the bridge checks the `Decimal` engine, which ranks the same exact
//! remainders.
use crate::kernel::{self, Leftover, Rounding, share_floor_with, share_of, split_by_weights_into};
@@ -93,23 +94,28 @@ fn split_by_weights_sums() {
}
/// Each part is within one step of its share: scaled by the total,
/// `part x total - whole x weight` is above `-total` and at most `total`.
/// `part x total - whole x weight` is above `-total` and below `total`,
/// and a part whose share is exact takes no unit.
///
/// The upper bound is inclusive on the `i64` model: its division
/// truncates, so a part that divides exactly can still take a unit when
/// another part's truncation left one over (`whole = 5`, weights 2/3/5:
/// the first's 1 becomes 2, exactly one step above its truncated share).
/// The `Decimal` quotient keeps the fraction, a part with no remainder
/// never takes a unit, and the bridge checks the strict bound there
/// (`decimal_split_satisfies_the_kani_laws`); Lean's `shares_of_near`
/// proves it for the exact-share model at any size.
/// The upper bound was inclusive on the `i64` model while the ranking
/// read the quotient: `i64`'s division truncates, every remainder read
/// as zero, and a part that divided exactly could take the unit another
/// part's truncation left over (`whole = 5`, weights 2/3/5: the first's 1
/// became 2). The ranking is the exact remainder `whole x weight - part x
/// total` since K-U10 (D-76), which no division touches, so the unit goes
/// to a part that is short (1, 2, 2) and the bound is strict here as on
/// `Decimal` (`decimal_split_satisfies_the_kani_laws`); Lean's
/// `shares_of_near` proves it for the exact-share model at any size.
#[kani::proof]
fn split_by_weights_within_one_step() {
let whole = any_whole();
let (parts, _) = split(whole, 1, Leftover::LargestRemainder).expect("in range");
for i in 0..N {
let drift = parts[i] * TOTAL - whole * WEIGHTS[i];
assert!(-TOTAL < drift && drift <= TOTAL);
assert!(-TOTAL < drift && drift < TOTAL);
if (whole * WEIGHTS[i]) % TOTAL == 0 {
assert_eq!(drift, 0);
}
}
kani::cover!(
parts
@@ -119,11 +125,8 @@ fn split_by_weights_within_one_step() {
"a part off its exact share by the rounding"
);
kani::cover!(
parts
.iter()
.enumerate()
.any(|(i, &p)| p * TOTAL - whole * WEIGHTS[i] == TOTAL),
"a part exactly one step above its truncated share"
(whole * WEIGHTS[0]) % TOTAL == 0 && whole % TOTAL != 0,
"a unit is handed out while the first part's share is exact"
);
}
+149
View File
@@ -311,6 +311,155 @@ fn a_close_split_drifts_by_the_regime_it_was_made_under() {
);
}
/// BS-partner-1 statement 4 (the allocation is the split to the base
/// currency's smallest unit) and WB-ledger-16 invariant 8: a JPY close is
/// checked at the allocation's unit -- a whole yen, JPY having no minor
/// unit below it -- not at a cent. A drift of half a yen is under that
/// unit; a drift of a whole yen after the true-up is not.
#[test]
fn a_jpy_close_is_checked_at_the_allocations_unit() {
// The one helper both the split and its audit use.
assert_eq!(Currency::JPY.allocation_unit(), dec("1"));
assert_eq!(Currency::USD.allocation_unit(), dec("0.01"));
// A code ISO 4217 gives no minor unit splits at the finest a line
// carries, so its audit unit is that, not a cent.
assert_eq!(
Currency::new("XAU").unwrap().allocation_unit(),
dec("0.0000000001")
);
let yen = Currency::JPY.allocation_unit();
let m = |running: &str, exact: &str| MemberSplit {
capital: 3001,
share: dec("0.5"),
part: dec(running),
running: dec(running),
exact: dec(exact),
};
// Half a yen of drift is under one yen (it would be fifty cents'
// worth of drift at a cent unit, and flagged there).
assert!(audit::check_split(1, "Jan", &[m("100.5", "100")], yen, true).is_empty());
// A whole yen after the true-up is a finding (statement 5's >= unit).
let f = audit::check_split(1, "Jan", &[m("101", "100")], yen, true);
assert_eq!(codes(&f), ["close_split_drifts"]);
// End to end: a yen members close splits in whole yen and the audit
// of the closed period raises no close finding.
let mut l = Ledger::new(Currency::JPY);
let cash = l
.add_account("1000", "Bank", AccountType::Asset, None, false)
.unwrap();
let revenue = l
.add_account("4000", "Sales", AccountType::Revenue, None, false)
.unwrap();
let caps: Vec<u64> = ["3001", "3002"]
.iter()
.map(|c| {
l.add_account(c, c, AccountType::Equity, None, false)
.unwrap()
})
.collect();
let e = l.create_entry(d(1, 5), "sale");
l.add_line(e, cash, Side::Debit, Money::new(dec("101"), Currency::JPY))
.unwrap();
l.add_line(
e,
revenue,
Side::Credit,
Money::new(dec("101"), Currency::JPY),
)
.unwrap();
l.post_entry(e).unwrap();
let jan = l.create_period("2026-01", d(1, 1), d(1, 31)).unwrap();
let members = caps
.iter()
.map(|&capital| MemberClose {
capital,
share: dec("0.5"),
distributions: None,
})
.collect();
l.close_period_to(jan, &CloseTo::Members(members)).unwrap();
// 101 yen at 50/50 splits 51 / 50 whole yen (exact 50.5 each).
let balances: Vec<Decimal> = caps
.iter()
.map(|&a| l.account_balance(a).unwrap())
.collect();
assert_eq!(balances, [dec("51"), dec("50")]);
let f = run(&l, &Settings::default(), &all_receipts(&l), d(12, 31));
assert!(
!codes(&f).contains(&"close_split_drifts"),
"{:?}",
codes(&f)
);
}
/// BS-partner-1 statement 6 and WB-ledger-16 invariant 8: before the
/// true-up, a legacy last-absorbs close's largest legitimate drift is
/// derived (the rule states the per-member facts, not the bound): with
/// n members and unit u, each member but the last was rounded to within
/// u/2, and the last absorbed the sum of those roundings, up to
/// (n-1)*u/2 -- so 3u/2 with four members and 2u with five (floored at
/// u, which statement 6's per-close and run allowances give). At that
/// drift a close is not flagged; one unit past it, it is. After the
/// true-up, BS-partner-1 statement 5's strict bound holds instead: a
/// drift of a unit or more is flagged.
#[test]
fn a_legacy_last_absorbs_close_drifts_by_member_count_before_its_true_up() {
let unit = dec("0.01");
// A split of `n` members whose last-listed member carries `drift`
// (running against an exact 1.00) and whose others are exact.
let split = |n: usize, drift: &str| -> Vec<MemberSplit> {
(0..n)
.map(|i| {
let running = if i + 1 == n {
dec("1.00") + dec(drift)
} else {
dec("1.00")
};
MemberSplit {
capital: 3001 + i as u64,
share: dec("0.25"),
part: running,
running,
exact: dec("1.00"),
}
})
.collect()
};
// Four members: largest legitimate drift 3 * 0.005 = 0.015, either way.
assert!(audit::check_split(1, "Jan", &split(4, "0.015"), unit, false).is_empty());
assert!(audit::check_split(1, "Jan", &split(4, "-0.015"), unit, false).is_empty());
// Anything past it is flagged, exactly one member: a tenth of a
// unit past (a bound of two units would let this through), and a
// whole unit past.
for drift in ["0.016", "-0.016", "0.025"] {
let f = audit::check_split(1, "Jan", &split(4, drift), unit, false);
assert_eq!(codes(&f), ["close_split_drifts"], "{drift}");
}
// Three members and two: the bound is the unit itself, as it was.
assert!(audit::check_split(1, "Jan", &split(3, "0.01"), unit, false).is_empty());
assert!(audit::check_split(1, "Jan", &split(2, "0.01"), unit, false).is_empty());
for n in [2, 3] {
let f = audit::check_split(1, "Jan", &split(n, "0.011"), unit, false);
assert_eq!(codes(&f), ["close_split_drifts"], "{n} members");
}
// Five members: largest legitimate drift 4 * 0.005 = 0.02.
assert!(audit::check_split(1, "Jan", &split(5, "0.02"), unit, false).is_empty());
assert!(audit::check_split(1, "Jan", &split(5, "-0.02"), unit, false).is_empty());
for drift in ["0.021", "0.03"] {
let f = audit::check_split(1, "Jan", &split(5, drift), unit, false);
assert_eq!(codes(&f), ["close_split_drifts"], "{drift}");
}
// After the true-up the same splits answer to statement 5: the
// four-member split at its legacy bound is past one unit, so it is
// flagged, and one just under a unit is not.
let f = audit::check_split(1, "Jan", &split(4, "0.015"), unit, true);
assert_eq!(codes(&f), ["close_split_drifts"]);
assert!(audit::check_split(1, "Jan", &split(4, "0.009"), unit, true).is_empty());
let f = audit::check_split(1, "Jan", &split(4, "0.01"), unit, true);
assert_eq!(codes(&f), ["close_split_drifts"]);
}
/// BS-partner-1 statement 6 and 8 (WB-partner-1): a count is trued up by
/// the first close under the cumulative rule that posts an entry, not by
/// a close of an older rule or one that posts nothing; the books say so
+151
View File
@@ -0,0 +1,151 @@
//! `docs/command-steps.md` lists every command on `Ledger`, with the step
//! of bookspec's Lean model it is.
//!
//! bookspec proves its laws for every state a `Step` reaches. A command
//! that changes the books and is no step is outside those proofs, so the
//! page has to name every command, and a new one has to be placed (or
//! written down as not covered) before it ships. This test reads the
//! source and the page and fails when they differ.
use std::collections::{BTreeMap, BTreeSet};
const SOURCE: &str = include_str!("../src/ledger.rs");
const PAGE: &str = include_str!("../../../docs/command-steps.md");
/// The steps of the two models (`Bookspec.Step`, `Bookspec.Documents.Step`),
/// and `none` for a command that is no step.
const STEPS: &[&str] = &[
"addAccount",
"draft",
"post",
"reverse",
"openPeriod",
"close",
"closeToRetained",
"discard",
"record",
"document",
"doc.reverse",
"writeOff",
"assign",
"release",
"markSent",
"none",
];
/// The commands that are no step of the model. Adding one here is
/// admitting a hole in what the proofs cover: the page says what closes it.
const NO_STEP: &[&str] = &["renumber_account"];
/// Every `pub fn` of `impl Ledger` that takes `&mut self`, by name.
fn commands() -> BTreeSet<String> {
let start = SOURCE
.find("\nimpl Ledger {")
.expect("ledger.rs has one `impl Ledger {`");
// The block ends at the first line that is a lone closing brace.
let body = &SOURCE[start + 1..];
let end = body.find("\n}\n").expect("the impl block closes");
let lines: Vec<&str> = body[..end].lines().collect();
let mut found = BTreeSet::new();
for (i, line) in lines.iter().enumerate() {
let Some(rest) = line.strip_prefix(" pub fn ") else {
continue;
};
let name: String = rest
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.collect();
// The signature runs to the line that opens the body.
let signature: String = lines[i..]
.iter()
.take_while(|l| !l.trim_end().ends_with('{'))
.chain(lines[i..].iter().find(|l| l.trim_end().ends_with('{')))
.copied()
.collect::<Vec<_>>()
.join(" ");
if signature.contains("&mut self") {
found.insert(name);
}
}
found
}
/// The page's table: command to its steps.
fn rows() -> BTreeMap<String, Vec<String>> {
let table = PAGE
.split("## Every command")
.nth(1)
.expect("the page has the section `## Every command`");
let mut rows = BTreeMap::new();
for line in table.lines() {
let cells: Vec<&str> = line.split('|').map(str::trim).collect();
// `| `name` | steps | note |` splits into ["", name, steps, note, ""].
if cells.len() < 4 || !cells[1].starts_with('`') {
continue;
}
let name = cells[1].trim_matches('`').to_string();
let steps = cells[2].split(',').map(|s| s.trim().to_string()).collect();
assert!(
rows.insert(name.clone(), steps).is_none(),
"docs/command-steps.md lists `{name}` twice"
);
}
rows
}
/// Every command has a row, and every row a command.
#[test]
fn every_command_is_on_the_page() {
let commands = commands();
assert!(
commands.len() > 100,
"found only {} commands: the reader of ledger.rs is broken",
commands.len()
);
let listed: BTreeSet<String> = rows().into_keys().collect();
let missing: Vec<_> = commands.difference(&listed).collect();
let stale: Vec<_> = listed.difference(&commands).collect();
assert!(
missing.is_empty() && stale.is_empty(),
"docs/command-steps.md and `impl Ledger` differ.\n\
Commands with no row (add one, with the model's step it is, or a \
new `Step` in bookspec): {missing:?}\n\
Rows with no command (remove them): {stale:?}"
);
}
/// Every row names steps the model has.
#[test]
fn every_row_names_a_step_of_the_model() {
for (command, steps) in rows() {
assert!(!steps.is_empty(), "`{command}` names no step");
for step in &steps {
assert!(
STEPS.contains(&step.as_str()),
"`{command}` names `{step}`, which is no step of the model"
);
}
}
}
/// The commands that are no step are the ones written down, and no others.
#[test]
fn the_commands_outside_the_model_are_the_ones_named() {
let outside: BTreeSet<String> = rows()
.into_iter()
.filter(|(_, steps)| steps.iter().any(|s| s == "none"))
.map(|(command, _)| command)
.collect();
let named: BTreeSet<String> = NO_STEP.iter().map(|s| s.to_string()).collect();
assert_eq!(
outside, named,
"a command marked `none` on the page must be in NO_STEP, and the \
page's \"No step\" section must say what closes it"
);
for (command, steps) in rows() {
assert!(
steps.len() == 1 || !steps.iter().any(|s| s == "none"),
"`{command}` is `none` and a step at once"
);
}
}
+7 -5
View File
@@ -17,9 +17,11 @@
//!
//! Exact only up to the sums the books reach. Near `Decimal::MAX` the add
//! rounds dust away (`MAX + 0.4` gives `Some(MAX)`, found by unit K-U4 and
//! pinned below; plan unit K-U10 makes the kernel refuse it), and a product
//! whose scale can't fit 28 places is rounded (the reason for decision
//! D-75's ten-place bound on foreign amounts and rates).
//! pinned below), and a product whose scale can't fit 28 places is rounded
//! (the reason for decision D-75's ten-place bound on foreign amounts and
//! rates). These are `rust_decimal`'s own behaviours, pinned here as
//! such; the kernel's `Amount for Decimal` refuses both (K-U10, checked
//! in `tests/kernel_bridge/decimal_exact.rs`).
//!
//! This is a test of the dependency, not of the engine. When a property
//! fails, the finding is `rust_decimal`'s, and the failing case stays here
@@ -436,8 +438,8 @@ fn checked_add_and_sub_return_none_past_the_maximum() {
/// Inexact at the edge: within one unit of `Decimal::MAX`, `checked_add`
/// rounds the fraction away instead of refusing (K-U4's finding). Pinned
/// so the day `rust_decimal` or the kernel (unit K-U10) makes it exact,
/// this test says so.
/// so the day `rust_decimal` makes it exact, this test says so; the
/// kernel's `Amount::checked_add` refuses it (K-U10).
#[test]
fn checked_add_rounds_dust_away_next_to_the_maximum() {
let dust = Decimal::new(4, 1);
@@ -291,58 +291,31 @@ proptest! {
prop_assert_eq!(cents(&got), want);
}
/// The exact reference ranks the exact remainders; the kernel ranks
/// the rounded quotients' remainders. With a small non-terminating
/// total the two orders agree except at an exact tie, which this
/// property excludes and `finding_ties_follow_the_rounded_quotient`
/// pins.
/// The exact reference ranks the exact remainders, and so does the
/// kernel (K-U10): with any weights, ties included (equal weights,
/// the 4/1/1 shape, a whole that leaves equal remainders), the split
/// is the reference's, at whole units and at the cent.
#[test]
fn largest_remainder_ranks_like_the_exact_reference(
whole_start in 0i64..=2_000,
weights in prop::collection::vec(1i64..=9, 2..=4),
whole in 0i64..=100_000,
weights in prop::collection::vec(1i64..=9, 2..=5),
) {
// Distinct weights, and a total with a factor of 3 or 7 (a
// non-terminating division), by construction: no case is
// rejected, and no exact tie is left to the property.
let mut weights = weights;
weights.sort_unstable();
for (i, w) in weights.iter_mut().enumerate() {
*w += i as i64;
}
let plain: i64 = weights.iter().sum();
if plain % 3 != 0 && plain % 7 != 0 {
*weights.last_mut().unwrap() += 3 - plain % 3;
}
let total: i64 = weights.iter().sum();
let whole = (whole_start..whole_start + total)
.find(|&w| {
let mut rems: Vec<i128> = weights
.iter()
.map(|&x| (i128::from(w) * i128::from(x)) % i128::from(total))
.collect();
rems.sort_unstable();
rems.dedup();
rems.len() == weights.len()
})
.expect("whole ≡ 1 mod total leaves distinct remainders");
let decimal_weights: Vec<Decimal> = weights.iter().copied().map(Decimal::from).collect();
let got = split_by_weights_with(
Decimal::from(whole),
&decimal_weights,
Decimal::from(total),
Decimal::ONE,
|x| round_step(x, Decimal::ONE, Rounding::TowardZero),
Leftover::LargestRemainder,
)
.unwrap();
let want = reference(
i128::from(whole),
&weights.iter().map(|&w| i128::from(w)).collect::<Vec<_>>(),
i128::from(total),
1,
)
.unwrap();
prop_assert_eq!(got.iter().map(|&p| integer(p)).collect::<Vec<_>>(), want);
let wide: Vec<i128> = weights.iter().map(|&w| i128::from(w)).collect();
for places in [0u32, 2] {
let got = decimal_split(
Decimal::new(whole, places),
&decimal_weights,
Decimal::from(total),
places,
Leftover::LargestRemainder,
)
.unwrap();
let want = reference(i128::from(whole), &wide, i128::from(total), 1).unwrap();
let got = if places == 0 { got.iter().map(|&p| integer(p)).collect() } else { cents(&got) };
prop_assert_eq!(got, want);
}
}
/// `share_floor_with` is the exact floor of the rational, even when
@@ -571,14 +544,13 @@ fn split_into_matches_the_allocating_split() {
);
}
/// The EM's finding, pinned rather than fixed: a split ranks the rounded
/// quotients' remainders, so an exact tie goes where the 28th digit sends
/// it, not to the earlier part. 20.00 split 4/1/1 over 6 gives
/// 13.33/3.34/3.33 (exact ranking would give 13.34/3.33/3.33), and 20 at
/// whole units gives 13/4/3 (exact would give 14/3/3). The pre-U3 sites
/// did the same. The owner decides the exact ranking in K-U10.
/// K-U10 (the owner's decision): a split ranks the exact remainders, so an
/// exact tie goes to the earlier part, as the docs and the Lean model say.
/// 20.00 split 4/1/1 over 6 is 13.34/3.33/3.33 (the rounded quotients'
/// ranking gave 13.33/3.34/3.33), and 20 at whole units is 14/3/3 (it gave
/// 13/4/3). Equal weights tie on every odd cent and give it to the first.
#[test]
fn finding_ties_follow_the_rounded_quotient() {
fn ties_go_to_the_earlier_part() {
let weights = [Decimal::from(4), Decimal::ONE, Decimal::ONE];
let got = decimal_split(
parse("20.00"),
@@ -590,7 +562,7 @@ fn finding_ties_follow_the_rounded_quotient() {
.unwrap();
assert_eq!(
got.iter().map(Decimal::to_string).collect::<Vec<_>>(),
["13.33", "3.34", "3.33"]
["13.34", "3.33", "3.33"]
);
let got = decimal_split(
Decimal::from(20),
@@ -602,7 +574,21 @@ fn finding_ties_follow_the_rounded_quotient() {
.unwrap();
assert_eq!(
got.iter().map(Decimal::to_string).collect::<Vec<_>>(),
["13", "4", "3"]
["14", "3", "3"]
);
// A negative total keeps the share's own order: ties still go first.
let neg = [Decimal::from(-4), Decimal::from(-1), Decimal::from(-1)];
let got = decimal_split(
parse("20.00"),
&neg,
Decimal::from(-6),
2,
Leftover::LargestRemainder,
)
.unwrap();
assert_eq!(
got.iter().map(Decimal::to_string).collect::<Vec<_>>(),
["13.34", "3.33", "3.33"]
);
}
@@ -77,16 +77,17 @@ fn dec_wide(cents: i128) -> Decimal {
Decimal::from_i128_with_scale(cents, 2)
}
/// `Decimal`'s answer against the exact reference: the same figure, or
/// `None` or a rounded figure when the reference is `None`. FINDING (K-U8, the K-U4 finding
/// again): where a step's exact result does not fit the 96-bit mantissa at
/// scale 2, `rust_decimal` does not refuse but rounds the result to a
/// coarser scale (so `Amount::checked_add` is not "exact or `None`" near
/// the top of the range, not only at `Decimal::MAX`). The reference is
/// `None` there and `Decimal` is `Some` at a scale below 2; the
/// assertion pins that shape, and the canary test below flips when the
/// fix lands in `impl Amount for Decimal`.
fn same_or_rounded(
/// `Decimal`'s answer against the exact reference: the same figure at
/// scale 2, or `None` where the reference is `None`. K-U8's finding
/// (the K-U4 finding again) was that where a step's exact result did not
/// fit the 96-bit mantissa at scale 2, `rust_decimal` did not refuse but
/// rounded the result to a coarser scale; K-U10 closed it, so a figure
/// that is not the exact one is a failure. One shape is not a rounding:
/// an exact sum whose last digit is a zero fits a coarser scale (so the
/// reference's cents overflow at that step and `Decimal`'s figure does
/// not, and a later step may bring it back to scale 2); it must equal
/// the exact value.
fn exact_or_refused(
got: Option<Decimal>,
want: Option<i128>,
exact: i128,
@@ -94,18 +95,13 @@ fn same_or_rounded(
match (got, want) {
(Some(g), Some(w)) => prop_assert_eq!((g.mantissa(), g.scale()), (w, 2)),
(None, None) => {}
// Rounded at a coarser scale at some step (a later step may bring
// it back to scale 2): not exact, and no panic; the finding.
// The figure is still close to the exact value (`exact`, in
// cents): each coarser step loses at most one unit of its scale
// (at worst the whole units, 100 cents), over at most four steps.
// (A later step can bring the scale back to 2, so the bound is
// not tied to the final scale.)
(Some(g), None) => {
let shown = g.mantissa() * 10i128.pow(2u32.saturating_sub(g.scale()));
let cents = g
.mantissa()
.checked_mul(10i128.pow(2u32.saturating_sub(g.scale())));
prop_assert!(
g.scale() <= 2 && (shown - exact).abs() <= 400,
"{g} is not within four whole units of {exact} cents"
g.scale() <= 2 && cents == Some(exact),
"{g} is not the exact {exact} cents"
);
}
(None, Some(w)) => prop_assert!(false, "refused an exact {w}"),
@@ -160,15 +156,15 @@ proptest! {
let (a, b, c, d, e) = (f[0], f[1], f[2], f[3], f[4]);
let got = kernel::aging_total(dec_wide(a), dec_wide(b), dec_wide(c), dec_wide(d), dec_wide(e));
let want = ref_chain(&[(a, true), (b, true), (c, true), (d, true), (e, true)]);
same_or_rounded(got, want, a + b + c + d + e)?;
exact_or_refused(got, want, a + b + c + d + e)?;
let got = kernel::control_difference(dec_wide(a), dec_wide(b), dec_wide(c));
let want = ref_chain(&[(a, true), (b, false), (c, false)]);
same_or_rounded(got, want, a - b - c)?;
exact_or_refused(got, want, a - b - c)?;
let got = kernel::reconciliation_total(dec_wide(a), dec_wide(b), dec_wide(c), dec_wide(d));
let want = ref_chain(&[(a, true), (b, true), (c, true), (d, false)]);
same_or_rounded(got, want, a + b + c - d)?;
exact_or_refused(got, want, a + b + c - d)?;
}
}
@@ -231,16 +227,14 @@ fn reconciliation_laptop() {
);
}
/// FINDING (K-U8, K-U10 candidate), pinned as a canary: the dust the K-U4
/// finding saw at `Decimal::MAX` is wider than that. Two cents-scale
/// figures whose exact sum needs more than 96 bits at scale 2 sum to a
/// rounded figure at scale 1, not to `None`. Here 0.01 plus the largest
/// scale-2 figure is 792281625142643375935439503.36, which `rust_decimal`
/// returns as 792281625142643375935439503.4. Reachable only with figures
/// near 7.9 x 10^26, a hundred billion times a journal line's cap, so the
/// engine's line cap keeps it out of every ordinary path.
/// K-U8's finding, closed by K-U10: the dust the K-U4 finding saw at
/// `Decimal::MAX` was wider than that. Two cents-scale figures whose exact
/// sum needs more than 96 bits at scale 2 summed to a rounded figure at
/// scale 1, not to `None`: 0.01 plus the largest scale-2 figure is
/// 792281625142643375935439503.36, which `rust_decimal` returns as
/// 792281625142643375935439503.4. The kernel now refuses it.
#[test]
fn finding_decimal_add_rounds_scale_near_the_top() {
fn a_sum_past_exact_arithmetic_is_refused() {
let top = Decimal::from_i128_with_scale((1i128 << 96) - 1, 2);
let got = kernel::aging_total(
Decimal::new(1, 2),
@@ -249,8 +243,12 @@ fn finding_decimal_add_rounds_scale_near_the_top() {
Decimal::ZERO,
top,
);
assert_eq!(got, None);
// The old chain's figure, for the record: rounded.
assert_eq!(
got.map(|g| (g.mantissa(), g.scale())),
Decimal::new(1, 2)
.checked_add(top)
.map(|g| (g.mantissa(), g.scale())),
Some((7922816251426433759354395034, 1))
);
}
@@ -270,6 +268,24 @@ fn arb_decimal() -> impl Strategy<Value = Decimal> {
.prop_map(|(m, s)| Decimal::from_i128_with_scale(m, s))
}
fn rat(d: Decimal) -> num_rational::BigRational {
num_rational::BigRational::new(
num_bigint::BigInt::from(d.mantissa()),
num_bigint::BigInt::from(10u8).pow(d.scale()),
)
}
/// `rust_decimal`'s `a + b` (or `a - b`) as it returned it, only when it
/// is the exact result: the reference the kernel's checked sum must equal.
fn exact_only(got: Option<Decimal>, a: Decimal, b: Decimal, add: bool) -> Option<Decimal> {
let exact = if add {
rat(a) + rat(b)
} else {
rat(a) - rat(b)
};
got.filter(|g| rat(*g) == exact)
}
fn shown(d: Option<Decimal>) -> String {
d.map_or("None".into(), |d| format!("{d} (scale {})", d.scale()))
}
@@ -279,26 +295,28 @@ proptest! {
/// The routed sites give the figures, scales and refusals the
/// hand-written chains they replaced did (K-U8's compatibility check),
/// compared as strings: the old `AgingRow::total`, the old
/// `control_check` difference, the old `Reconciliation::total`.
/// compared as strings, except that a step whose result `rust_decimal`
/// had to round is now refused (K-U10): the old `AgingRow::total`, the
/// old `control_check` difference, the old `Reconciliation::total`,
/// each step filtered through an exact rational reference.
#[test]
fn kernel_matches_the_replaced_chains(f in prop::array::uniform5(arb_decimal())) {
let old_aging = [f[1], f[2], f[3], f[4]]
.into_iter()
.try_fold(f[0], Decimal::checked_add);
.try_fold(f[0], |a, b| exact_only(Decimal::checked_add(a, b), a, b, true));
prop_assert_eq!(
shown(kernel::aging_total(f[0], f[1], f[2], f[3], f[4])),
shown(old_aging)
);
let old_diff = f[0].checked_sub(f[1]).and_then(|d| d.checked_sub(f[2]));
let old_diff = exact_only(Decimal::checked_sub(f[0], f[1]), f[0], f[1], false)
.and_then(|d| exact_only(Decimal::checked_sub(d, f[2]), d, f[2], false));
prop_assert_eq!(
shown(kernel::control_difference(f[0], f[1], f[2])),
shown(old_diff)
);
let old_recon = f[0]
.checked_add(f[1])
.and_then(|x| x.checked_add(f[2]))
.and_then(|x| x.checked_sub(f[3]));
let old_recon = exact_only(Decimal::checked_add(f[0], f[1]), f[0], f[1], true)
.and_then(|x| exact_only(Decimal::checked_add(x, f[2]), x, f[2], true))
.and_then(|x| exact_only(Decimal::checked_sub(x, f[3]), x, f[3], false));
prop_assert_eq!(
shown(kernel::reconciliation_total(f[0], f[1], f[2], f[3])),
shown(old_recon)
@@ -0,0 +1,631 @@
//! K-U10 bridge properties: `impl Amount for Decimal`'s add, subtract and
//! multiply are exact or `None`, never rounded (BS-ledger-1: a product the
//! arithmetic cannot hold MUST be refused; BS-entry-4).
//!
//! Kani works on `i64`, which never rounds, so the claim rests here: the
//! kernel's `Decimal` result is compared with `rust_decimal`'s own
//! (the "old" behaviour) and with an independent exact reference
//! (`num_rational::BigRational`, sharing no code with the kernel) over
//! the whole mantissa (to 2^96 - 1) and scale (0 to 28) range, edges
//! included. The law, per operation:
//!
//! 1. `Some(r)` is the exact result: `r` equals the rational one.
//! 2. Where the old result was exact, the kernel returns it unchanged,
//! compared as strings (value and scale): nothing exact moves.
//! 3. Where the old result was rounded, the kernel returns `None`.
//! 4. Where the old result was `None`, so is the kernel's.
//! 5. `Some` exactly when the exact result is a `Decimal` at all (a
//! mantissa under 2^96 at some scale of 0 to 28), decided from the
//! rational alone, with none of `rust_decimal`'s arithmetic: nothing
//! representable is refused. Laws 2 to 4 compare with `rust_decimal`;
//! this one does not, so it would catch `rust_decimal` rounding a
//! result it could have held.
//!
//! And over the posted range (BS-entry-4's line cap and ten places) the
//! kernel equals the old for every input.
use ledger_core::kernel::{Amount, MAX_LINE_AMOUNT, MAX_LINE_SCALE};
use num_bigint::BigInt;
use num_rational::BigRational;
use proptest::prelude::*;
use rust_decimal::Decimal;
fn rat(d: Decimal) -> BigRational {
BigRational::new(
BigInt::from(d.mantissa()),
BigInt::from(10u8).pow(d.scale()),
)
}
fn shown(d: Option<Decimal>) -> String {
d.map_or("None".into(), |d| format!("{d} (scale {})", d.scale()))
}
/// What the kernel must return, given what `rust_decimal` returned and
/// the exact result: the old figure if it is exact, else `None`.
fn expected(old: Option<Decimal>, exact: &BigRational) -> Option<Decimal> {
old.filter(|o| rat(*o) == *exact)
}
/// Whether an exact rational is a `Decimal`: `m x 10^-s` with `|m| < 2^96`
/// and `s <= 28`. The fewest places that make it whole are tried in turn;
/// more places only make the mantissa longer.
fn representable(q: &BigRational) -> bool {
let ten = BigRational::from_integer(BigInt::from(10u8));
let mut scaled = q.clone();
for _ in 0..=28 {
if scaled.is_integer() {
return scaled.numer().magnitude().bits() <= 96;
}
scaled *= &ten;
}
false
}
/// Any `Decimal`: mantissas across the whole 96 bits (small, near the
/// top, trailing zeros) at every scale.
fn arb_decimal() -> impl Strategy<Value = Decimal> {
let top = (1i128 << 96) - 1;
(
prop_oneof![
-1_000i128..=1_000,
-1_000_000_000_000i128..=1_000_000_000_000,
-top..=top,
(top - 1_000)..=top,
-top..=-(top - 1_000),
(-top / 1_000_000..=top / 1_000_000).prop_map(|m| m * 1_000_000),
Just(top),
Just(-top),
Just(0),
],
0u32..=28,
)
.prop_map(|(m, s)| Decimal::from_i128_with_scale(m, s))
}
/// A decimal and a second one at a nearby scale or the same: the
/// rescaling edge of an add is where the rounding lives.
fn arb_pair() -> impl Strategy<Value = (Decimal, Decimal)> {
prop_oneof![
(arb_decimal(), arb_decimal()),
(arb_decimal(), 0u32..=28, -1_000i128..=1_000)
.prop_map(|(a, s, m)| (a, Decimal::from_i128_with_scale(m, s))),
(arb_decimal(), -1_000i128..=1_000)
.prop_map(|(a, m)| (a, Decimal::from_i128_with_scale(m, a.scale()))),
]
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(30000))]
/// Add: laws 1 to 4, over the whole range.
#[test]
fn add_is_exact_or_none((a, b) in arb_pair()) {
let got = Amount::checked_add(a, b);
let old = Decimal::checked_add(a, b);
let exact = rat(a) + rat(b);
if let Some(r) = got {
prop_assert_eq!(rat(r), exact.clone(), "{} + {} is rounded", a, b);
}
prop_assert_eq!(shown(got), shown(expected(old, &exact)));
prop_assert_eq!(got.is_some(), representable(&exact), "{} + {}", a, b);
}
/// Subtract: the same laws, against `rust_decimal`'s own subtraction
/// (so a zero stays a plain zero).
#[test]
fn sub_is_exact_or_none((a, b) in arb_pair()) {
let got = Amount::checked_sub(a, b);
let old = Decimal::checked_sub(a, b);
let exact = rat(a) - rat(b);
if let Some(r) = got {
prop_assert_eq!(rat(r), exact.clone(), "{} - {} is rounded", a, b);
}
prop_assert_eq!(shown(got), shown(expected(old, &exact)));
prop_assert_eq!(got.is_some(), representable(&exact), "{} - {}", a, b);
}
/// Multiply: the same laws.
#[test]
fn mul_is_exact_or_none((a, b) in arb_pair()) {
let got = Amount::checked_mul(a, b);
let old = Decimal::checked_mul(a, b);
let exact = rat(a) * rat(b);
if let Some(r) = got {
prop_assert_eq!(rat(r), exact.clone(), "{} x {} is rounded", a, b);
}
prop_assert_eq!(shown(got), shown(expected(old, &exact)));
prop_assert_eq!(got.is_some(), representable(&exact), "{} x {}", a, b);
}
/// Whatever the kernel refuses, `rust_decimal` either refused or
/// rounded: the kernel never refuses an exact figure `rust_decimal`
/// held (restating laws 2 and 3 as the refusal's only two causes).
#[test]
fn a_refusal_is_an_overflow_or_a_rounding((a, b) in arb_pair()) {
for (got, old, exact) in [
(Amount::checked_add(a, b), Decimal::checked_add(a, b), rat(a) + rat(b)),
(Amount::checked_mul(a, b), Decimal::checked_mul(a, b), rat(a) * rat(b)),
] {
if got.is_none() {
prop_assert!(old.is_none_or(|o| rat(o) != exact));
}
}
}
}
/// A figure a posted line can carry (BS-entry-4): at most
/// `MAX_LINE_AMOUNT`, at most `MAX_LINE_SCALE` places once trailing zeros
/// are dropped; stored at any raw scale that still holds it.
fn arb_line_amount() -> impl Strategy<Value = Decimal> {
(0u32..=MAX_LINE_SCALE, any::<bool>()).prop_flat_map(|(scale, negative)| {
let cap = 10i128.pow(15 + scale);
(0i128..=cap, 0u32..=28).prop_map(move |(m, want)| {
let m = if negative { -m } else { m };
// Up to `want` extra trailing zeros: the same value at a raw
// scale of up to 28, as far as 96 bits hold it.
let mut pad = 0;
while pad < want
&& scale + pad < 28
&& m.checked_mul(10i128.pow(pad + 1))
.is_some_and(|p| p.unsigned_abs() < 1u128 << 96)
{
pad += 1;
}
Decimal::from_i128_with_scale(m * 10i128.pow(pad), scale + pad)
})
})
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(20000))]
/// Over the posted range, add and subtract equal `rust_decimal`'s, to
/// the character, and are never `None`.
#[test]
fn posted_range_sums_are_unchanged(a in arb_line_amount(), b in arb_line_amount()) {
prop_assert!(a.abs() <= MAX_LINE_AMOUNT && b.abs() <= MAX_LINE_AMOUNT);
prop_assert!(a.normalize().scale() <= MAX_LINE_SCALE);
let add = Amount::checked_add(a, b);
let sub = Amount::checked_sub(a, b);
prop_assert!(add.is_some() && sub.is_some());
prop_assert_eq!(shown(add), shown(Decimal::checked_add(a, b)));
prop_assert_eq!(shown(sub), shown(Decimal::checked_sub(a, b)));
}
/// Over the posted range, an FX product (a foreign amount and a
/// rate of at most ten places each, D-75) is the old product to the
/// character whenever its mantissa product fits 96 bits (the exact
/// product is then representable), and `None` where it does not and
/// the old one rounded.
#[test]
fn posted_range_fx_products_are_unchanged_or_refused(
fm in 0i128..=10i128.pow(25),
fs in 0u32..=MAX_LINE_SCALE,
rm in 0i128..=10i128.pow(13),
rs in 0u32..=MAX_LINE_SCALE,
) {
let foreign = Decimal::from_i128_with_scale(fm, fs);
let rate = Decimal::from_i128_with_scale(rm, rs);
let got = Amount::checked_mul(foreign, rate);
let old = Decimal::checked_mul(foreign, rate);
let fits = fm.checked_mul(rm).is_some_and(|p| p < (1i128 << 96));
if fits {
prop_assert!(got.is_some());
prop_assert_eq!(shown(got), shown(old));
} else {
// Past 96 bits at the full scale: the old product was rounded
// unless the product's own trailing zeros made it fit.
prop_assert_eq!(shown(got), shown(expected(old, &(rat(foreign) * rat(rate)))));
}
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(1500))]
/// A running total of posted lines (1e18 at the worst, ten places: a
/// 29-digit mantissa) is unchanged at every step.
#[test]
fn posted_range_running_totals_are_unchanged(
lines in proptest::collection::vec(arb_line_amount(), 0..=100)
) {
let mut old = Decimal::ZERO;
let mut new = Decimal::ZERO;
for l in lines {
old = Decimal::checked_add(old, l).expect("posted sums fit");
new = Amount::checked_add(new, l).expect("posted sums stay exact");
prop_assert_eq!(shown(Some(new)), shown(Some(old)));
}
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(24))]
/// The same over thousands of lines, where the total's mantissa comes
/// near 2^96 (5,000 lines of 10^15 at ten places is 5e28 of 7.9e28):
/// every step is `rust_decimal`'s, and none is refused.
#[test]
fn posted_range_running_totals_of_thousands_of_lines_are_unchanged(
lines in proptest::collection::vec(arb_line_amount(), 4000..=5000),
same_sign in any::<bool>(),
) {
let mut old = Decimal::ZERO;
let mut new = Decimal::ZERO;
for l in lines {
let l = if same_sign { l.abs() } else { l };
old = Decimal::checked_add(old, l).expect("posted sums fit");
new = Amount::checked_add(new, l).expect("posted sums stay exact");
prop_assert_eq!(shown(Some(new)), shown(Some(old)));
}
}
}
/// Where a running total stops being exact: 7,922 lines of the largest
/// ten-place amount under the cap (999999999999999.9999999999, a mantissa
/// of 10^25 - 1) sum exactly; the next one passes 2^96 at ten places.
/// `rust_decimal` drops a place and rounds; the kernel refuses.
#[test]
fn a_running_total_is_refused_where_it_would_first_round() {
let line = Decimal::from_i128_with_scale(10i128.pow(25) - 1, 10);
assert!(line.in_line_range());
let mut old = Decimal::ZERO;
let mut new = Decimal::ZERO;
for n in 1..=7_922 {
old = Decimal::checked_add(old, line).unwrap();
new = Amount::checked_add(new, line).unwrap_or_else(|| panic!("line {n} is exact"));
assert_eq!(shown(Some(new)), shown(Some(old)), "line {n}");
}
assert_eq!(
rat(new),
rat(line) * BigRational::from_integer(BigInt::from(7_922))
);
let rounded = Decimal::checked_add(old, line).unwrap();
assert_ne!(rat(rounded), rat(old) + rat(line), "rust_decimal rounds");
assert_eq!(Amount::checked_add(new, line), None);
}
/// The K-U4 canary, flipped: a sum within one unit of `Decimal::MAX`
/// that `rust_decimal` rounds is refused, and the exact ones stand.
#[test]
fn a_sum_past_exact_arithmetic_is_refused_at_the_maximum() {
let max = Decimal::MAX;
assert_eq!(Decimal::checked_add(max, Decimal::new(4, 1)), Some(max));
assert_eq!(Amount::checked_add(max, Decimal::new(4, 1)), None);
assert_eq!(Amount::checked_add(max, Decimal::new(5, 1)), None);
assert_eq!(Amount::checked_add(max, Decimal::ONE), None);
assert_eq!(Amount::checked_add(max, Decimal::ZERO), Some(max));
assert_eq!(
Amount::checked_add(max, -Decimal::ONE),
Some(max - Decimal::ONE)
);
assert_eq!(Amount::checked_sub(Decimal::MIN, Decimal::new(4, 1)), None);
}
/// The K-U8 canary, flipped: `0.01 + 792281625142643375935439503.35`.
#[test]
fn a_sum_past_exact_arithmetic_is_refused_near_the_top() {
let top = Decimal::from_i128_with_scale((1i128 << 96) - 1, 2);
let cent = Decimal::new(1, 2);
assert_eq!(
shown(Decimal::checked_add(cent, top)),
"792281625142643375935439503.4 (scale 1)",
"rust_decimal rounds the exact ...503.36"
);
assert_eq!(Amount::checked_add(cent, top), None);
assert_eq!(Amount::checked_add(top, cent), None);
// The sums that are exact stay.
assert_eq!(
Amount::checked_add(-cent, top),
Decimal::checked_add(-cent, top)
);
}
/// The K-U1 canary, flipped: `1050000010.0000000001 x 9.9999999999` is
/// 10500000099.89499999999999999999 exactly, 20 places, 96 bits short;
/// `rust_decimal` held 10500000099.895 and the engine booked ...99.90.
/// The product is refused.
#[test]
fn a_product_past_exact_arithmetic_is_refused() {
let foreign: Decimal = "1050000010.0000000001".parse().unwrap();
let rate: Decimal = "9.9999999999".parse().unwrap();
let held = Decimal::checked_mul(foreign, rate).unwrap();
assert_ne!(rat(held), rat(foreign) * rat(rate), "rust_decimal rounded");
assert_eq!(held.to_string(), "10500000099.895000000000000000");
assert_eq!(Amount::checked_mul(foreign, rate), None);
// K-U3's square, reachable below the line cap at ten places.
let n: Decimal = "123456789.0123456789".parse().unwrap();
assert_eq!(
shown(Decimal::checked_mul(n, n)),
"15241578753238836.750190519988 (scale 12)"
);
assert_eq!(Amount::checked_mul(n, n), None);
// Past scale 28 the old product rounds (or underflows to zero).
let tiny = Decimal::from_i128_with_scale(1, 28);
assert_eq!(Decimal::checked_mul(tiny, tiny), Some(Decimal::ZERO));
assert_eq!(Amount::checked_mul(tiny, tiny), None);
}
/// Exact products with trailing zeros stay, even where the full-scale
/// mantissa would pass 96 bits (a scale test would refuse these): 100 x
/// 0.3333333333333333333333333333 is 33.333...3300 exactly.
#[test]
fn an_exact_product_that_only_looks_wide_is_kept() {
let third = Decimal::from_i128_with_scale(3_333_333_333_333_333_333_333_333_333, 28);
let hundred = Decimal::ONE_HUNDRED;
let got = Amount::checked_mul(third, hundred);
assert_eq!(shown(got), shown(Decimal::checked_mul(third, hundred)));
assert!(got.is_some());
// 10^20 at scale 20 (one) squared: 10^40 mantissa, value 1.
let one = Decimal::from_i128_with_scale(10i128.pow(20), 20);
assert_eq!(
shown(Amount::checked_mul(one, one)),
shown(Decimal::checked_mul(one, one))
);
assert_eq!(
Amount::checked_mul(one, one).map(rat),
Some(rat(Decimal::ONE))
);
}
/// Zero is exact in every shape, and a zero factor never refuses.
#[test]
fn zero_is_exact() {
let z28 = Decimal::from_i128_with_scale(0, 28);
let big = Decimal::MAX;
assert_eq!(
shown(Amount::checked_mul(z28, big)),
shown(Decimal::checked_mul(z28, big))
);
assert!(Amount::checked_mul(z28, z28).is_some());
assert_eq!(Amount::checked_add(z28, big), Some(big));
assert_eq!(
Amount::checked_add(Decimal::ZERO, z28).map(|d| d.is_zero()),
Some(true)
);
}
// ---------------------------------------------------------------- FX
use ledger_core::kernel::Rounding;
/// `q` rounded to an integer in `mode`, exactly (no kernel code).
fn round_rational(q: &BigRational, mode: Rounding) -> BigInt {
let n = q.numer();
let d = q.denom();
let truncated = n / d;
let rem = n - &truncated * d;
let zero = BigInt::from(0);
let negative = rem < zero;
let twice = if negative { -&rem } else { rem.clone() } * 2;
let away = if negative { -1 } else { 1 };
match mode {
Rounding::TowardZero => truncated,
Rounding::TowardNegativeInfinity => {
if negative {
truncated - 1
} else {
truncated
}
}
Rounding::HalfAwayFromZero => {
if twice >= *d {
truncated + away
} else {
truncated
}
}
Rounding::HalfToEven => {
if twice > *d || (twice == *d && truncated.bit(0)) {
truncated + away
} else {
truncated
}
}
}
}
fn arb_mode() -> impl Strategy<Value = Rounding> {
prop_oneof![
Just(Rounding::TowardZero),
Just(Rounding::TowardNegativeInfinity),
Just(Rounding::HalfAwayFromZero),
Just(Rounding::HalfToEven),
]
}
/// A foreign amount or rate of at most ten places (D-75) and up to
/// `digits` digits of mantissa, so products reach 2^96 and past it.
fn arb_ten_place(digits: u32) -> impl Strategy<Value = Decimal> {
(0i128..10i128.pow(digits), 0u32..=MAX_LINE_SCALE)
.prop_map(|(m, s)| Decimal::from_i128_with_scale(m, s))
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(30000))]
/// `checked_mul_round_to_step` is the exact product rounded once, in
/// every mode, at the steps the books use (one, a cent, a mill), at
/// steps of 5 and 25 of them, and at steps of any number of places,
/// whether or not the exact product fits 96 bits, ties and signs
/// included. `None` only where the kernel says so: the figure times
/// 10^(the step's places + 2) does not fit 96 bits (one real digit
/// below the step and the sticky digit have no room), or the step has
/// 27 or 28 places (no room below it at all).
#[test]
fn the_fx_product_is_rounded_once_from_the_exact_one(
foreign in arb_ten_place(26),
rate in arb_ten_place(14),
places in prop_oneof![4 => 0u32..=3, 1 => 0u32..=28],
unit in prop_oneof![Just(1i128), Just(5i128), Just(25i128)],
mode in arb_mode(),
negative in any::<bool>(),
) {
let foreign = if negative { -foreign } else { foreign };
// A step that is not a power of ten too (a nickel, 0.025): its
// half steps sit one place below it, where the kept digit is real.
let step = Decimal::from_i128_with_scale(unit, places);
let got = Amount::checked_mul_round_to_step(foreign, rate, step, mode);
let exact = rat(foreign) * rat(rate);
let count = round_rational(&(exact.clone() / rat(step)), mode);
let want = BigRational::from_integer(count) * rat(step);
match got {
Some(g) => prop_assert_eq!(rat(g), want, "{} x {} to {} places, {:?}", foreign, rate, places, mode),
None => {
// The digits the rounding needs: the figure to one place
// below the step, then the sticky digit.
let step_places = step.normalize().scale();
let needed = (exact.clone()
* BigRational::from_integer(BigInt::from(10u8).pow(step_places + 2)))
.to_integer();
let room = (BigInt::from(1u8) << 96u32) - BigInt::from(10u8);
prop_assert!(
step_places >= 27 || *needed.magnitude() >= *room.magnitude(),
"{} x {} to a step of {} refused though it is only {}", foreign, rate, step, want
);
}
}
}
}
/// The K-U1 edge, now rounded once: the exact product is
/// 10500000099.89499999999999999999, so the cent is 10500000099.89 (the
/// engine used to book ...99.90, off by a cent, by rounding twice).
#[test]
fn the_k_u1_edge_books_the_cent_the_exact_product_gives() {
let foreign: Decimal = "1050000010.0000000001".parse().unwrap();
let rate: Decimal = "9.9999999999".parse().unwrap();
let cent = Decimal::new(1, 2);
assert_eq!(
Amount::checked_mul_round_to_step(foreign, rate, cent, Rounding::HalfAwayFromZero),
Some("10500000099.89".parse().unwrap())
);
// Products straddling a half cent by digits far below the cent, with
// a 97-bit mantissa (so they cannot take the plain path): the sticky
// digit puts each on its side of the tie.
let rate: Decimal = "1.0000000001".parse().unwrap();
let book = |foreign: &str, mode| {
Amount::checked_mul_round_to_step(foreign.parse().unwrap(), rate, cent, mode)
};
let above = "1000000000.0050000001"; // 1000000000.10500000010050000001
let below = "1000000000.0049999999"; // 1000000000.10499999990049999999
assert!(
Decimal::checked_mul(above.parse().unwrap(), rate)
.is_some_and(|p| { rat(p) != rat(above.parse().unwrap()) * rat(rate) })
);
assert_eq!(
book(above, Rounding::HalfAwayFromZero),
Some("1000000000.11".parse().unwrap())
);
assert_eq!(
book(above, Rounding::HalfToEven),
Some("1000000000.11".parse().unwrap())
);
assert_eq!(
book(above, Rounding::TowardZero),
Some("1000000000.10".parse().unwrap())
);
assert_eq!(
book(below, Rounding::HalfAwayFromZero),
Some("1000000000.10".parse().unwrap())
);
}
/// A step of 27 or 28 places leaves no place below it for the digit and
/// the sticky digit the one rounding needs (`Decimal` ends at 28), so a
/// product that is not exact is refused there in every mode, though its
/// rounded figure (zero, here) is a `Decimal`. A refusal, never a guess;
/// no currency's step is near it. At 26 places the same product rounds.
#[test]
fn a_step_of_27_places_refuses_a_product_that_is_not_exact() {
let tiny = Decimal::from_i128_with_scale(1, 28);
for mode in [
Rounding::TowardZero,
Rounding::TowardNegativeInfinity,
Rounding::HalfAwayFromZero,
Rounding::HalfToEven,
] {
for places in [27, 28] {
let step = Decimal::from_i128_with_scale(1, places);
assert_eq!(
Amount::checked_mul_round_to_step(tiny, tiny, step, mode),
None
);
// A product that is exact is rounded there as at any step.
assert_eq!(
Amount::checked_mul_round_to_step(Decimal::ONE, step, step, mode),
Some(step)
);
}
let step = Decimal::from_i128_with_scale(1, 26);
assert_eq!(
Amount::checked_mul_round_to_step(tiny, tiny, step, mode),
Some(Decimal::ZERO)
);
}
}
// ------------------------------------------------------ exact division
proptest! {
#![proptest_config(ProptestConfig::with_cases(30000))]
/// `checked_div_exact` is the exact quotient or `None`: never a
/// quotient `rust_decimal` rounded (10 / 3), whose product with the
/// divisor rounds back to the dividend; and `Some` whenever the exact
/// quotient is a `Decimal`, so an exact division is never refused.
#[test]
fn div_exact_is_exact_or_none(a in arb_line_amount(), m in 1i128..100_000, s in 0u32..=4) {
let b = Decimal::from_i128_with_scale(m, s);
let got = Amount::checked_div_exact(a, b);
if let Some(q) = got {
prop_assert_eq!(rat(q) * rat(b), rat(a), "{} / {} gave {}", a, b, q);
}
prop_assert_eq!(got.is_some(), representable(&(rat(a) / rat(b))), "{} / {}", a, b);
}
/// The same over the whole range of `Decimal`, divisors that divide
/// evenly included (a quotient times a divisor, divided back).
#[test]
fn div_exact_over_the_whole_range((a, b) in arb_pair(), back in any::<bool>()) {
let b = if b.is_zero() { Decimal::ONE } else { b };
// Half the cases: a dividend built as a product, so the exact
// quotient exists and is a `Decimal`.
let a = if back { Amount::checked_mul(a, b).unwrap_or(a) } else { a };
let exact = rat(a) / rat(b);
let got = Amount::checked_div_exact(a, b);
if let Some(q) = got {
prop_assert_eq!(rat(q), exact.clone(), "{} / {} gave {}", a, b, q);
}
prop_assert_eq!(got.is_some(), representable(&exact), "{} / {}", a, b);
}
}
/// A third, a seventh, a ninth: no exact quotient, so `None`, where the
/// check through `rust_decimal`'s rounding product let each through. A
/// quarter and a basis-point division are exact and are kept.
#[test]
fn a_rounded_quotient_is_not_an_exact_one() {
let d = |s: &str| s.parse::<Decimal>().unwrap();
for (a, b) in [
("10", "3"),
("20", "3"),
("10", "7"),
("80", "9"),
("10", "6"),
("1000000.00", "3"),
] {
assert_eq!(
Amount::checked_div_exact(d(a), d(b)),
None,
"{a} / {b} has no exact quotient"
);
}
assert_eq!(Amount::checked_div_exact(d("10"), d("4")), Some(d("2.5")));
assert_eq!(
Amount::checked_div_exact(d("123456.78") * d("250"), d("10000")),
Some(d("3086.4195"))
);
assert_eq!(Amount::checked_div_exact(d("1"), d("0")), None);
}
+16 -15
View File
@@ -335,8 +335,8 @@ fn ten_places_each_is_exact_through_the_engine() {
/// D-75's bound is what keeps the reference and the engine equal: the
/// K-U1 review's input, 0.99999999999999999999999999 (26 places) x 0.005,
/// is 0.00499999999999999999999999995 exactly (under half a cent, so
/// 0.00), but `Decimal` rounds the product to 28 places first and the
/// kernel books 0.01. The engine refuses any foreign amount or rate of
/// 0.00); `Decimal` rounded the product to 28 places first and the
/// kernel booked 0.01 (K-U10: it now books 0.00 too). The engine refuses any foreign amount or rate of
/// eleven or more places before it computes.
#[test]
fn past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses() {
@@ -355,8 +355,8 @@ fn past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses() {
);
assert_eq!(
fx_booked_minor(foreign, rate, Currency::USD, Rounding::HalfAwayFromZero),
Some(parse("0.01")),
"outside D-75 the kernel inherits Decimal's early rounding"
Some(parse("0.00")),
"outside D-75 too, the product is rounded once, from the exact one (K-U10)"
);
let (mut ledger, cash, entry) = usd_books();
for (foreign, rate) in [
@@ -376,17 +376,18 @@ fn past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses() {
}
/// The other half of exactness (found by this bridge, reported with
/// D-75): ten places each keep the product's scale within 28, but
/// `Decimal`'s mantissa is 96 bits (7.9e28), and a product of twenty
/// places past about 7.9e8 does not fit. `Decimal` then drops places
/// from the product, and the kernel rounds the already rounded value.
/// 1050000010.0000000001 x 9.9999999999 is 10500000099.89499999999999999999
/// exactly, and 10500000099.89 to the cent, but `Decimal` holds
/// 10500000099.895 and the kernel books 10500000099.90. Pinned as it is
/// today, outside the precondition of `fx_booked` (which says the
/// mantissas' product must fit); a unit to refuse it is the owner's call.
/// D-75, closed by K-U10): ten places each keep the product's scale
/// within 28, but `Decimal`'s mantissa is 96 bits (7.9e28), and a product
/// of twenty places past about 7.9e8 does not fit. `Decimal` used to drop
/// places from the product and the kernel rounded the already rounded
/// value: 1050000010.0000000001 x 9.9999999999 is
/// 10500000099.89499999999999999999 exactly, and 10500000099.89 to the
/// cent, but `Decimal` held 10500000099.895 and the kernel booked
/// 10500000099.90. The kernel now holds the exact product wide for its
/// one rounding, so it books what the reference does, and `Amount`'s own
/// product refuses what `Decimal` cannot hold (decimal_exact.rs).
#[test]
fn the_mantissa_edge_is_outside_the_precondition_and_pinned() {
fn the_mantissa_edge_books_the_exact_products_cent() {
let foreign = parse("1050000010.0000000001");
let rate = parse("9.9999999999");
assert_eq!(foreign.scale(), 10);
@@ -403,6 +404,6 @@ fn the_mantissa_edge_is_outside_the_precondition_and_pinned() {
);
assert_eq!(
fx_booked_minor(foreign, rate, Currency::USD, Rounding::HalfAwayFromZero),
Some(parse("10500000099.90"))
Some(parse("10500000099.89"))
);
}
@@ -9,12 +9,14 @@
// One file per kernel-sweep unit; the properties above stay here.
mod allocate;
mod control;
mod decimal_exact;
mod entries;
mod fx;
mod payroll;
mod ratio;
mod round;
mod schedule;
mod ties;
mod total;
use ledger_core::kernel::{self, Amount, LineError};
@@ -242,16 +242,25 @@ fn the_edges() {
// 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).
// a hundred steps at the cent: the K-U10 item (the division's, left
// as it is), which is why the callers refuse totals of 10^26 or more
// (EXACT_LIMIT). The sum of the parts is exact or refused (K-U10):
// 599 parts of 1.3e26 at the cent need more than 96 bits at scale 2,
// and `rust_decimal` used to round that sum.
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");
let parts = decimal_parts(widest, parse(step), months);
if months == 600 && step != "1" {
assert_eq!(
parts, None,
"{months} months at {step}: the sum is not exact"
);
continue;
}
let parts =
parts.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)),
kernel::total(parts.iter().copied()),
Some(widest),
"{months} months at {step}"
);
@@ -0,0 +1,408 @@
//! K-U10: what ranking the leftover cents by the exact remainder moves.
//!
//! `split_by_weights_into` used to rank its largest remainders by
//! `Decimal`'s rounded quotient (28 significant digits), so an exact tie
//! was decided by the quotient's last digit; it now ranks the exact
//! integer remainder `whole x weight - part x total`, ties to the earlier
//! part. This file keeps the old ranking as a reference (`old_split`,
//! built from the kernel's own public `share_of`, `round_places` and
//! `apportion`, exactly as the kernel built it) and measures, over
//! realistic inputs, how often the two differ and by how much. Run it
//! with `--nocapture` to see the table the owner's decision rests on:
//!
//! ```text
//! cargo test -p ledger-core --test kernel_bridge ties -- --nocapture
//! ```
//!
//! Realistic inputs: whole-cent amounts up to 1,000,000.00, two to five
//! parties, weights that are whole percentages or small integers.
use ledger_core::kernel::{
Leftover, Rounding, apportion, round_places, share_of, split_by_weights_with,
};
use rust_decimal::Decimal;
fn cents(c: i64) -> Decimal {
Decimal::new(c, 2)
}
/// The ranking the kernel had before K-U10: each remainder is the rounded
/// quotient less its rounded-down part.
fn old_split(whole: Decimal, weights: &[Decimal], total: Decimal) -> Vec<Decimal> {
let shares: Vec<Decimal> = weights
.iter()
.map(|&w| share_of(whole, w, total).unwrap())
.collect();
let mut parts: Vec<Decimal> = shares
.iter()
.map(|&s| round_places(s, 2, Rounding::TowardZero).unwrap())
.collect();
let rems: Vec<Decimal> = shares.iter().zip(&parts).map(|(s, p)| s - p).collect();
apportion(whole, &mut parts, &rems, cents(1)).unwrap();
parts
}
fn new_split(whole: Decimal, weights: &[Decimal], total: Decimal) -> Vec<Decimal> {
split_by_weights_with(
whole,
weights,
total,
cents(1),
|x| round_places(x, 2, Rounding::TowardZero),
Leftover::LargestRemainder,
)
.unwrap()
}
/// True when two parts have an equal exact remainder `whole x w - part x
/// total` (before the leftover is handed out): the only place the two
/// rankings can part.
fn has_exact_tie(whole: Decimal, weights: &[Decimal], total: Decimal) -> bool {
let rems: Vec<Decimal> = weights
.iter()
.map(|&w| {
let share =
round_places(share_of(whole, w, total).unwrap(), 2, Rounding::TowardZero).unwrap();
// The exact floor: a quotient that rounded up across a cent is
// taken back, as `share_floor_with` does.
let mut part = share;
while part * total > whole * w {
part -= cents(1);
}
whole * w - part * total
})
.collect();
(0..rems.len()).any(|i| (i + 1..rems.len()).any(|j| rems[i] == rems[j]))
}
/// A small deterministic generator (xorshift64*): the sweep is the same on
/// every machine and every run.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
}
#[derive(Default)]
struct Tally {
runs: u64,
differ: u64,
max_moved_cents: i64,
examples: Vec<String>,
}
impl Tally {
fn run(&mut self, whole: Decimal, weights: &[Decimal]) {
let total: Decimal = weights.iter().copied().sum();
let old = old_split(whole, weights, total);
let new = new_split(whole, weights, total);
self.runs += 1;
// Both sum to the whole, exactly, whatever the ranking.
assert_eq!(old.iter().copied().sum::<Decimal>(), whole);
assert_eq!(new.iter().copied().sum::<Decimal>(), whole);
if old == new {
return;
}
self.differ += 1;
// They differ only where an exact tie gave the ranking a choice,
// and by at most one cent a part.
assert!(
has_exact_tie(whole, weights, total),
"{whole} by {weights:?}: differ without an exact tie"
);
for (o, n) in old.iter().zip(&new) {
let moved = ((o - n).abs() * Decimal::from(100)).trunc();
let moved = i64::try_from(moved.mantissa()).unwrap();
assert!(moved <= 1, "{whole} by {weights:?}: moved {moved} cents");
self.max_moved_cents = self.max_moved_cents.max(moved);
}
if self.examples.len() < 3 {
let show = |v: &[Decimal]| {
v.iter()
.map(|d| d.to_string())
.collect::<Vec<_>>()
.join(" / ")
};
self.examples.push(format!(
"{whole} by {} -> was {}, now {}",
weights
.iter()
.map(|d| d.to_string())
.collect::<Vec<_>>()
.join("/"),
show(&old),
show(&new)
));
}
}
fn report(&self, name: &str) {
println!(
"{name:<44} {:>8} runs {:>8} differ {:>7.3}% max {} cent/part",
self.runs,
self.differ,
100.0 * self.differ as f64 / self.runs as f64,
self.max_moved_cents
);
for e in &self.examples {
println!(" e.g. {e}");
}
}
}
const RUNS: u64 = 60_000;
/// A random whole of 0.01 to 1,000,000.00; `dollars` rounds it to whole
/// dollars (round amounts are the realistic ones, and tie more).
fn random_whole(rng: &mut Rng, dollars: bool) -> Decimal {
let c = 1 + rng.below(100_000_000) as i64;
if dollars {
cents(((c + 99) / 100) * 100)
} else {
cents(c)
}
}
fn random_percentages(rng: &mut Rng) -> Vec<Decimal> {
let n = 2 + rng.below(4) as usize;
// A random composition of 100 into n positive whole percentages.
let mut cuts: Vec<u64> = Vec::new();
while cuts.len() < n - 1 {
let c = 1 + rng.below(99);
if !cuts.contains(&c) {
cuts.push(c);
}
}
cuts.sort_unstable();
let mut prev = 0;
let mut out = Vec::new();
for c in cuts.iter().copied().chain(std::iter::once(100)) {
out.push(Decimal::from(c - prev));
prev = c;
}
out
}
fn random_small_integers(rng: &mut Rng) -> Vec<Decimal> {
let n = 2 + rng.below(4) as usize;
(0..n).map(|_| Decimal::from(1 + rng.below(5))).collect()
}
/// The splits an agreement is likely to name.
const COMMON: &[&[i64]] = &[
&[50, 50],
&[60, 40],
&[70, 30],
&[75, 25],
&[80, 20],
&[90, 10],
&[34, 33, 33],
&[40, 30, 30],
&[50, 25, 25],
&[60, 20, 20],
&[25, 25, 25, 25],
&[40, 20, 20, 20],
&[20, 20, 20, 20, 20],
];
/// Equal weights: every remainder is `w x (whole - n x part)`, equal for
/// every part, so both rankings give the leftover cents to the earliest
/// parts and never differ. Two 50/50 members, thirds, quarters: no cent
/// moves, ever.
#[test]
fn equal_weights_never_differ() {
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
let mut t = Tally::default();
for i in 0..RUNS {
let n = 2 + rng.below(4) as usize;
let w = Decimal::from(1 + rng.below(100));
let weights = vec![w; n];
t.run(random_whole(&mut rng, i % 2 == 0), &weights);
}
t.report("equal weights (2-5 parties)");
assert_eq!(t.differ, 0);
}
/// Two parties never differ, whatever the weights. With two parts the
/// leftover is at most one cent, and the two remainders sum to `total` times
/// that cent, so they tie only at exactly half a cent over `total` each:
/// both shares then end in exactly half a cent, the quotient terminates,
/// and the rounded quotient ranks them as the exact one does. A two-member
/// company (the live books' shape) is therefore unmoved by K-U10.
#[test]
fn two_parties_never_differ() {
let mut rng = Rng(0x2545_F491_4F6C_DD1D);
let mut t = Tally::default();
for i in 0..RUNS {
let weights = [
Decimal::from(1 + rng.below(10_000)),
Decimal::from(1 + rng.below(10_000)),
];
t.run(random_whole(&mut rng, i % 2 == 0), &weights);
}
// And the smallest weights, where ties are the most frequent.
for a in 1..=12u64 {
for b in 1..=12u64 {
for c in 1..=300 {
t.run(cents(c), &[Decimal::from(a), Decimal::from(b)]);
}
}
}
t.report("two parties, any weights");
assert_eq!(t.differ, 0);
}
/// The measurement: how often the old and new rankings differ, by class
/// of weights and of amount. Asserts only the structure (both sum to the
/// whole; a difference needs an exact tie and is at most a cent a part);
/// the rates are printed for the owner.
#[test]
fn what_exact_tie_ranking_moves() {
println!();
for dollars in [false, true] {
let kind = if dollars {
"whole dollars"
} else {
"any cents"
};
let mut rng = Rng(0xD1B5_4A32_D192_ED03);
let mut t = Tally::default();
for _ in 0..RUNS {
let w = random_percentages(&mut rng);
t.run(random_whole(&mut rng, dollars), &w);
}
t.report(&format!("whole percentages, {kind}"));
let mut t = Tally::default();
for _ in 0..RUNS {
let w: Vec<Decimal> = COMMON[rng.below(COMMON.len() as u64) as usize]
.iter()
.map(|&p| Decimal::from(p))
.collect();
t.run(random_whole(&mut rng, dollars), &w);
}
t.report(&format!("common agreements, {kind}"));
let mut t = Tally::default();
for _ in 0..RUNS {
let w = random_small_integers(&mut rng);
t.run(random_whole(&mut rng, dollars), &w);
}
t.report(&format!("small integers 1-5, {kind}"));
}
// The K-1 property split's real shape: weights are the members'
// credits in one entry (whole dollars to 10,000), the whole at most
// their sum.
let mut rng = Rng(0xA076_1D64_78BD_642F);
let mut t = Tally::default();
for _ in 0..RUNS {
let n = 2 + rng.below(4) as usize;
let w: Vec<Decimal> = (0..n)
.map(|_| Decimal::from(1 + rng.below(10_000)))
.collect();
let total: Decimal = w.iter().copied().sum();
let pool = cents(1 + rng.below(total.mantissa() as u64 * 100) as i64);
t.run(pool, &w);
}
t.report("K-1 credits, whole dollars to 10,000");
// The 4/1/1 shape, every whole-dollar amount to 100.
let mut t = Tally::default();
for d in 1..=100 {
t.run(
Decimal::from(d),
&[Decimal::from(4), Decimal::ONE, Decimal::ONE],
);
}
t.report("4/1/1, $1 to $100 whole dollars");
}
/// The pinned examples, in dollars and cents, with both answers.
#[test]
fn the_pinned_examples_move_as_the_owner_was_told() {
let w = [Decimal::from(4), Decimal::ONE, Decimal::ONE];
let six = Decimal::from(6);
let show = |v: Vec<Decimal>| v.iter().map(Decimal::to_string).collect::<Vec<_>>();
assert_eq!(
show(old_split(cents(2000), &w, six)),
["13.33", "3.34", "3.33"]
);
assert_eq!(
show(new_split(cents(2000), &w, six)),
["13.34", "3.33", "3.33"]
);
}
/// Weights of `places` places that sum to `total` exactly: `n - 1` of
/// `total / n` rounded down, and a last one taking what is left. Built on
/// the mantissas: `Decimal` cannot hold the running sum of percents of 27
/// places (88.888...8 has 29 digits and passes its 96 bits), and would
/// round it without a word, which is the fault K-U10 closed in the kernel.
fn even_weights(total: i128, n: u32, places: u32) -> Vec<Decimal> {
let whole = total * 10i128.pow(places);
let w = whole / i128::from(n);
let last = whole - w * i128::from(n - 1);
let mut weights = vec![Decimal::from_i128_with_scale(w, places); n as usize];
*weights.last_mut().unwrap() = Decimal::from_i128_with_scale(last, places);
assert_eq!(weights.iter().map(Decimal::mantissa).sum::<i128>(), whole);
weights
}
/// K-U10 made the kernel's product exact or refused. A split by shares
/// of 28 places that sum to one (as a convention's shares do) or by
/// percents of 27 places that sum to 100 (thirds, sevenths, ninths) has
/// products past `Decimal`'s 28 digits, so the ranking uses the rounding
/// product there: the split is made, not refused, the parts sum to the
/// whole, and each is within a cent of its share. A negative whole is
/// rounded down, as apportioning requires (the parts rounded toward zero
/// would pass the whole, which `apportion` refuses).
#[test]
fn a_split_by_weights_of_27_places_is_made_not_refused() {
let cent = cents(1);
for (total, places) in [(1i128, 28u32), (100, 27)] {
for n in [3u32, 6, 7, 9, 11] {
let weights = even_weights(total, n, places);
let total = Decimal::from_i128_with_scale(total, 0);
let amounts = (1..=400_000i64)
.step_by(37)
.chain([23_769, 99_999_999_999_999_999, 100_000_000_000_000_000])
.flat_map(|c| [c, -c]);
for c in amounts {
let whole = cents(c);
let mode = if c < 0 {
Rounding::TowardNegativeInfinity
} else {
Rounding::TowardZero
};
let parts = split_by_weights_with(
whole,
&weights,
total,
cent,
|x| round_places(x, 2, mode),
Leftover::LargestRemainder,
)
.unwrap_or_else(|| panic!("{whole} by {n} parts of {places} places was refused"));
assert_eq!(
parts.iter().copied().sum::<Decimal>(),
whole,
"{whole} by {n}"
);
for (p, &wt) in parts.iter().zip(&weights) {
let share = share_of(whole, wt, total).unwrap();
assert!(
(*p - share).abs() < cent,
"{whole} by {n}: {p} for a share of {share}"
);
}
}
}
}
}
+11 -12
View File
@@ -121,23 +121,22 @@ fn decimal_edge_table() {
);
}
/// FINDING (K-U4), pinned as a canary: `rust_decimal` rounds sub-unit dust
/// away when a sum lands on `Decimal::MAX`, so `Amount::checked_add` for
/// `Decimal` is not exact at the very edge (`MAX + 0.4 = MAX`, but `MAX +
/// 0.5` is `None`). The kernel's "exact or `None`" contract (and `total`'s
/// invariant 2) therefore holds for `Decimal` everywhere except figures
/// within one unit of `Decimal::MAX` (~7.9 x 10^28, 10^13 times a journal
/// line's cap). The fix belongs in `impl Amount for Decimal`
/// (`kernel/entries.rs`), not in `total`; when it lands this test fails
/// and is flipped to expect `None`. See docs/proofs/k-u4.md.
/// K-U4's finding, closed by K-U10: `rust_decimal` rounds sub-unit dust
/// away when a sum lands on `Decimal::MAX` (`MAX + 0.4 = MAX`, but `MAX +
/// 0.5` is `None`), so `Amount::checked_add` for `Decimal` was not "exact
/// or `None`" within one unit of `Decimal::MAX`. `impl Amount for Decimal`
/// now checks the sum is the exact one, so `total`'s invariant 2 holds
/// there too: the rounded sum is refused. See docs/proofs/k-u4.md and
/// k-u10.md.
#[test]
fn finding_decimal_add_rounds_dust_at_the_edge() {
fn a_sum_past_exact_arithmetic_is_refused() {
let max = Decimal::MAX;
let dust = Decimal::new(4, 1);
assert_eq!(
kernel::total([max, dust]),
rust_decimal::Decimal::checked_add(max, dust),
Some(max),
"rust_decimal rounds the 0.4 away"
"rust_decimal rounds the 0.4 away; the kernel does not"
);
assert_eq!(kernel::total([max, dust]), None);
assert_eq!(kernel::total([max, Decimal::new(5, 1)]), None);
}
+7 -2
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
description = "Read-only, live desktop view of wanderbooks books."
[[bin]]
@@ -17,8 +18,12 @@ ledger-config = { path = "../ledger-config" }
ledger-import = { path = "../ledger-import" }
ledger-vault = { path = "../ledger-vault" }
ledger-package = { path = "../ledger-package" }
eframe = { version = "0.36", default-features = false, features = ["default_fonts", "wgpu", "wayland", "x11", "persistence"] }
egui = "0.36"
# No `default_fonts`, on eframe or on egui: egui's own font set includes
# Ubuntu Light, under the Ubuntu Font Licence, which Debian and Fedora class
# as non-free. The viewer names every font it draws with (theme.rs,
# assets/fonts/README.md), and `just deny` refuses that licence.
eframe = { version = "0.36", default-features = false, features = ["wgpu", "wayland", "x11", "persistence"] }
egui = { version = "0.36", default-features = false }
egui_extras = { version = "0.36", features = ["image", "datepicker", "serde"] }
egui-phosphor = "0.14"
# Markdown documents, drawn as text. No image loading (no `load-images`,
@@ -0,0 +1,31 @@
The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License
The work in the DejaVu project was committed to the public domain.
Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera"
MIT License
Copyright (c) 2018 Source Foundry Authors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
BITSTREAM VERA LICENSE
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions:
The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera".
This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names.
The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org.
Binary file not shown.
@@ -0,0 +1,92 @@
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font
creation efforts of academic and linguistic communities, and to
provide a free and open framework in which fonts may be shared and
improved in partnership with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to
any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software
components as distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to,
deleting, or substituting -- in part or in whole -- any of the
components of the Original Version, by changing formats or by porting
the Font Software to a new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed,
modify, redistribute, and sell modified and unmodified copies of the
Font Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components, in
Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created using
the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
# The viewer's fonts
Every font the viewer draws with is in this folder or in
`crates/ledger-import/fonts/` (the PDFs' fonts, which the viewer shares),
each beside its licence. `theme.rs` (`font_definitions`) names them all;
egui's own default font set is switched off, since it includes Ubuntu
Light under the Ubuntu Font Licence 1.0, which Debian and Fedora class as
non-free. `deny.toml` does not allow that licence, so the crate that
carries it (`epaint_default_fonts`) cannot come back unnoticed.
| File | What it draws | Licence | From |
|---|---|---|---|
| `InterTab-Regular.ttf`, `InterTab-SemiBold.ttf`, `InterTab-Bold.ttf` | All text. Inter with tabular figures made the default and the private-use glyphs removed; named "InterTab" as a modified version | SIL OFL 1.1 (`Inter-LICENSE.txt`); Copyright 2016 The Inter Project Authors, no reserved font name | https://github.com/rsms/inter |
| `Hack-Regular.ttf` | Fixed-width text: identifiers, hashes, JSON | MIT, and the Bitstream Vera licence for the Vera outlines it descends from (`Hack-LICENSE.txt`) | `epaint_default_fonts` 0.36.2, unchanged |
| `NotoEmoji-Regular.ttf` | Symbols and emoji, one colour | SIL OFL 1.1 (`NotoEmoji-LICENSE.txt`); Copyright 2013 Google Inc. | `epaint_default_fonts` 0.36.2, unchanged |
| `emoji-icon-font.ttf` | Symbols Noto Emoji lacks (arrows on a menu, the date picker) | MIT (`emoji-icon-font-LICENSE.txt`); Copyright 2014 John Slegers | `epaint_default_fonts` 0.36.2, unchanged |
Phosphor's icons come from the `egui-phosphor` crate (MIT).
Why these licences fit a program under MIT OR Apache-2.0: the SIL Open
Font License lets a font be bundled, embedded and shipped with any
software, sold or free. It asks that the font not be sold by itself, that
its copyright and licence travel with it, and that a changed font stay
under the OFL without a name the authors reserved. It is the licence of
Inter itself and of the Noto fonts, and Debian, Fedora, the FSF and the
OSI all accept it. The Bitstream Vera licence asks the same things. None
of them reaches the program's own code.
SHA-256 of each file, so a changed font is a seen change:
```
a7ef8d15be539471b4a21095930d39f3af50f676de32a21ee515225692c8d0b4 InterTab-Bold.ttf
0e41e795bbb28ee70c6417349e430149c19e98d87485e6b6308e1ab142ee43ca InterTab-Regular.ttf
366d6fc641ac090310828b5e9c3c33331bf0699f84cb421b283502e18ae4fcd7 InterTab-SemiBold.ttf
15f55cc0c85a2988d2b4b3a8cdb5d77fdfbaf319e1bb5309d725db9818fb7125 Hack-Regular.ttf
415dc6290378574135b64c808dc640c1df7531973290c4970c51fdeb849cb0c5 NotoEmoji-Regular.ttf
f426bec371f484646d002717e2c555a95cd5145e635d83a48bbef83f3abf18ca emoji-icon-font.ttf
```
@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2014 John Slegers
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Binary file not shown.
+12 -8
View File
@@ -993,10 +993,8 @@ impl Books {
Some(_) => 3,
None => 0,
};
(loss > Decimal::ZERO && months > 0).then(|| {
(loss / Decimal::from(months))
.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointAwayFromZero)
})
(loss > Decimal::ZERO && months > 0)
.then(|| crate::fmt::round_display(loss / Decimal::from(months), 2))
});
Kpis {
cash: cash[1],
@@ -1774,7 +1772,6 @@ impl Books {
e: &ledger_core::JournalEntry,
party: PartyId,
) -> Vec<(AccountId, Decimal)> {
use rust_decimal::RoundingStrategy::ToZero;
let Some(info) = self
.entry_index
.get(&e.id())
@@ -1843,7 +1840,7 @@ impl Books {
let Some(part) = v.checked_mul(fraction) else {
return Vec::new();
};
scaled.push((a, part.round_dp_with_strategy(2, ToZero)));
scaled.push((a, truncate_cents(part)));
}
}
let Some(left) = own
@@ -2065,11 +2062,18 @@ impl Books {
/// going to the first account, so the parts sum to `share` exactly. None
/// when amount times share is past exact arithmetic (both near the line
/// limit), never a panic or a rounded guess.
/// `part` truncated to cents through the kernel's one rounding
/// primitive: a split's leftover policy (toward zero, the rest to the
/// first part), not display rounding, so it never rounds a share up.
fn truncate_cents(part: Decimal) -> Decimal {
ledger_core::kernel::round_places(part, 2, ledger_core::kernel::Rounding::TowardZero)
.unwrap_or(part)
}
pub fn share_of_what_for(
flow: &ledger_core::parties::EntryFlow,
share: Decimal,
) -> Option<Vec<(AccountId, Decimal)>> {
use rust_decimal::RoundingStrategy::ToZero;
if share == flow.net || flow.what_for.is_empty() {
return Some(flow.what_for.clone());
}
@@ -2081,7 +2085,7 @@ pub fn share_of_what_for(
.iter()
.map(|(a, v)| {
let part = v.checked_mul(share)?.checked_div(flow.net)?;
Some((*a, part.round_dp_with_strategy(2, ToZero)))
Some((*a, truncate_cents(part)))
})
.collect::<Option<_>>()?;
let have = parts
+10 -1
View File
@@ -788,7 +788,16 @@ pub fn build(dir: &Path, today: NaiveDate) -> Result<(), StoreError> {
let date = day(m, 1);
if in_range(date) {
let gross = rng.amount(450, 1600);
let fee = (gross * Decimal::new(10, 2)).round_dp(2) + Decimal::new(30, 2);
// A booked figure, so the kernel's rounding and not the
// display's: ten percent to the cent, a half to the even
// cent, as these books have always been drawn.
let fee = ledger_core::kernel::round_places(
gross * Decimal::new(10, 2),
2,
ledger_core::kernel::Rounding::HalfToEven,
)
.expect("a tenth of a four-digit sale rounds to the cent")
+ Decimal::new(30, 2);
let net = gross - fee;
let e = s.create_entry(date, "Gumroad payout — template sales")?;
s.add_line(e, checking, Side::Debit, usd(net))?;
+62 -18
View File
@@ -62,21 +62,30 @@ pub fn dollars(d: Decimal) -> String {
}
}
/// The one display rounding, shared with every other renderer.
pub use ledger_import::format::round_display;
/// Rounded for chart axes and tight tiles: `$1.2k`, `$3.4M`, `$950`.
/// Exact decimal arithmetic: a money amount never goes through a float,
/// not even to shorten it for an axis.
pub fn compact(d: Decimal) -> String {
let f: f64 = d.try_into().unwrap_or(0.0);
let a = f.abs();
let s = if a >= 1_000_000.0 {
format!("${:.1}M", a / 1_000_000.0)
} else if a >= 10_000.0 {
format!("${:.0}k", a / 1_000.0)
} else if a >= 1_000.0 {
format!("${:.1}k", a / 1_000.0)
let a = d.abs();
let scaled = |divisor: Decimal, places: u32| {
a.checked_div(divisor)
.map(|v| round_display(v, places))
.unwrap_or(a)
};
let s = if a >= Decimal::from(1_000_000) {
format!("${:.1}M", scaled(Decimal::from(1_000_000), 1))
} else if a >= Decimal::from(10_000) {
format!("${:.0}k", scaled(Decimal::from(1_000), 0))
} else if a >= Decimal::from(1_000) {
format!("${:.1}k", scaled(Decimal::from(1_000), 1))
} else {
format!("${a:.0}")
format!("${:.0}", round_display(a, 0))
};
// No sign on what rounds to zero ("$0", not "−$0").
if f < 0.0 && s != "$0" {
if d.is_sign_negative() && !d.is_zero() && s != "$0" {
format!("\u{2212}{s}")
} else {
s
@@ -127,14 +136,22 @@ pub fn plain(display: &str) -> Option<String> {
})
}
/// A percent change from `prev` to `now`, if `prev` isn't zero.
pub fn pct_change(prev: Decimal, now: Decimal) -> Option<f64> {
if prev.is_zero() {
return None;
}
let p: f64 = prev.try_into().ok()?;
let n: f64 = now.try_into().ok()?;
Some((n - p) / p.abs() * 100.0)
/// A percent change from `prev` to `now`: `(now - prev) / prev * 100`
/// to one place, half away from zero. `None` when `prev` is zero or
/// negative: a change from no base, or from a negative base, has no
/// honest percent (the one rule every percent in the viewer follows;
/// the caller shows nothing, or "—", for `None`).
pub fn pct_change(prev: Decimal, now: Decimal) -> Option<Decimal> {
let part = now.checked_sub(prev)?;
let mut x = ledger_core::kernel::percent_of(
part,
prev,
Decimal::new(1, 1),
ledger_core::kernel::Rounding::HalfAwayFromZero,
)?;
// One place always, so no change prints "0.0", never "0" or "-0.0".
x.rescale(1);
Some(x)
}
/// `Oct 12, 2026`.
@@ -276,4 +293,31 @@ mod tests {
assert_eq!(plain("1e3"), None);
assert_eq!(plain(""), None);
}
/// pct_change: exact decimal percent to one place; no percent of a
/// zero or negative base (the viewer's one percent rule).
#[test]
fn a_percent_change_is_decimal_or_none() {
assert_eq!(pct_change(dec("200"), dec("250")), Some(dec("25.0")));
assert_eq!(pct_change(dec("200"), dec("150")), Some(dec("-25.0")));
assert_eq!(pct_change(dec("3"), dec("4")), Some(dec("33.3")));
assert_eq!(pct_change(dec("0"), dec("5")), None);
assert_eq!(pct_change(dec("-100"), dec("-50")), None);
assert_eq!(pct_change(dec("-100"), dec("50")), None);
// No negative zero: no change is +0.0.
assert_eq!(
pct_change(dec("100"), dec("100")).map(|p| p.to_string()),
Some("0.0".into())
);
}
/// compact: decimal shortening, half away from zero, no "-$0".
#[test]
fn compact_is_decimal() {
assert_eq!(compact(dec("1250000")), "$1.3M");
assert_eq!(compact(dec("1150000")), "$1.2M");
assert_eq!(compact(dec("10500")), "$11k");
assert_eq!(compact(dec("999")), "$999");
assert_eq!(compact(dec("-0.4")), "$0");
}
}
+7 -2
View File
@@ -24,9 +24,14 @@ pub fn kind_label(k: CapitalKind) -> &'static str {
}
}
/// A share as a percent: 0.5 → "50%", 0.3333 → "33.33%".
/// A share as a percent: 0.5 → "50%", 0.3333 → "33.33%". A share is a
/// stored fraction, not a ratio of two amounts, so this is exact
/// decimal multiplication (never a float, never rounded); only a
/// negative zero is dropped.
pub fn percent(share: Decimal) -> String {
format!("{}%", (share * Decimal::ONE_HUNDRED).normalize())
let p = share * Decimal::ONE_HUNDRED;
let p = if p.is_zero() { Decimal::ZERO } else { p };
format!("{}%", p.normalize())
}
/// One statement row: an indented label, an amount column, and an
+6 -2
View File
@@ -190,7 +190,7 @@ fn runway(ui: &mut Ui, b: &Books) {
ui.label(RichText::new("The figures are too large to compute.").color(p.muted));
return;
};
let net = net.round_dp(2);
let net = fmt::round_display(net, 2);
let big = |ui: &mut Ui, label: &str, value: String, color| {
ui.vertical(|ui| {
ui.label(
@@ -224,7 +224,11 @@ fn runway(ui: &mut Ui, b: &Books) {
if net < Decimal::ZERO {
// Checked: a sub-cent average (lines an earlier version
// booked) makes a runway past any calendar.
let months_left = b.kpis.cash.checked_div(-net).map(|m| m.round_dp(1));
let months_left = b
.kpis
.cash
.checked_div(-net)
.map(|m| fmt::round_display(m, 1));
let out = months_left
.and_then(|m| m.checked_mul(Decimal::from(30)))
.and_then(|d| u64::try_from(d).ok())
+12 -7
View File
@@ -64,8 +64,10 @@ fn headline(b: &Books) -> String {
fmt::dollars(k.liabilities)
);
if let Some(burn) = k.monthly_burn {
if burn > Decimal::ZERO && k.cash > Decimal::ZERO {
let months = (k.cash / burn).round_dp(1);
if burn > Decimal::ZERO
&& k.cash > Decimal::ZERO
&& let Some(months) = k.cash.checked_div(burn).map(|m| fmt::round_display(m, 1))
{
s.push_str(&format!(
" Lately you spend {} a month more than you earn: about {} months of runway.",
fmt::dollars(burn),
@@ -100,11 +102,11 @@ fn change(
p: &theme::Palette,
) -> Option<(String, egui::Color32)> {
let pct = fmt::pct_change(prev, now)?;
let good = (pct >= 0.0) == up_is_good;
let arrow = if pct >= 0.0 { "▲" } else { "▼" };
let good = (pct >= Decimal::ZERO) == up_is_good;
let arrow = if pct >= Decimal::ZERO { "▲" } else { "▼" };
Some((
format!("{arrow} {:.0}% vs {what}", pct.abs()),
if pct.abs() < 0.5 {
format!("{arrow} {}% vs {what}", fmt::round_display(pct.abs(), 0)),
if pct.abs() < Decimal::new(5, 1) {
p.muted
} else if good {
p.positive
@@ -134,7 +136,10 @@ fn kpis(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
.collect();
let runway = match k.monthly_burn {
Some(burn) if burn > Decimal::ZERO && k.cash > Decimal::ZERO => (
format!("{} mo", (k.cash / burn).round_dp(1)),
k.cash.checked_div(burn).map_or_else(
|| "—".to_string(),
|m| format!("{} mo", fmt::round_display(m, 1)),
),
Some((format!("burning {}/mo", fmt::compact(burn)), p.warning)),
),
_ if k.first_entry.is_none() => ("—".to_string(), None),
+17 -9
View File
@@ -18,15 +18,20 @@ use ledger_core::reports::profit_and_loss_for_period;
use rust_decimal::Decimal;
use std::collections::BTreeMap;
/// `part` as a percent of `whole`, to one place, half to even (the
/// margin rule the books use, `kernel::percent_of`). `None` when
/// `whole` is zero or negative: a percent of no base, or of a negative
/// base, means nothing, and the page shows "—" for it.
pub(crate) fn pct(part: Decimal, whole: Decimal) -> Option<Decimal> {
part.checked_div(whole)?
.checked_mul(Decimal::from(100))
.map(|x| {
// One place always, so 100% prints as "100.0", as 64.0 does.
let mut x = x.round_dp(1);
x.rescale(1);
x
})
let mut x = ledger_core::kernel::percent_of(
part,
whole,
Decimal::new(1, 1),
ledger_core::kernel::Rounding::HalfToEven,
)?;
// One place always, so 100% prints as "100.0", as 64.0 does.
x.rescale(1);
Some(x)
}
pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
@@ -269,7 +274,7 @@ fn spending_changes(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
ui.painter().text(
egui::pos2(x, r.center().y),
egui::Align2::RIGHT_CENTER,
fmt::money(v.round_dp(2)),
fmt::money(fmt::round_display(*v, 2)),
theme::regular(13.0),
if *flag { p.warning } else { p.text },
);
@@ -438,6 +443,9 @@ mod tests {
assert_eq!(pct(cents(500), cents(500)).unwrap().to_string(), "100.0");
assert_eq!(pct(cents(-100), cents(200)).unwrap().to_string(), "-50.0");
assert_eq!(pct(Decimal::MAX, Decimal::new(1, 2)), None);
// No percent of a negative base.
assert_eq!(pct(cents(100), cents(-200)), None);
assert_eq!(pct(cents(-100), cents(-200)), None);
}
/// "Invoiced by customer, this year": this fiscal year's invoices only.
+48 -7
View File
@@ -242,10 +242,14 @@ impl Table {
(None, Some(b)) => Some(-b),
_ => None,
};
// No percent of a zero or negative base: it would mislead.
let pct = match (diff, b) {
(Some(d), Some(b)) if !b.is_zero() => {
Some((d / b.abs() * Decimal::from(100)).round_dp(1))
}
(Some(d), Some(b)) => ledger_core::kernel::percent_of(
d,
b,
Decimal::new(1, 1),
ledger_core::kernel::Rounding::HalfToEven,
),
_ => None,
};
r.cells.push(Cell {
@@ -268,15 +272,20 @@ impl Table {
.and_then(|r| r.cells.first())
.and_then(|c| c.value)
.unwrap_or_default();
if income.is_zero() {
if income <= Decimal::ZERO {
return;
}
self.columns.push("% of income".into());
self.pct_from = Some(self.columns.len() - 1);
for r in &mut self.rows {
if let Some(v) = r.cells.first().and_then(|c| c.value) {
r.cells
.push(Cell::of((v / income * Decimal::from(100)).round_dp(1)));
let p = ledger_core::kernel::percent_of(
v,
income,
Decimal::new(1, 1),
ledger_core::kernel::Rounding::HalfToEven,
);
r.cells.push(p.map_or_else(Cell::none, Cell::of));
}
}
}
@@ -334,7 +343,7 @@ impl Table {
for c in &r.cells {
out.push('\t');
if let Some(v) = c.value {
out.push_str(&v.round_dp(2).to_string());
out.push_str(&crate::fmt::round_display(v, 2).to_string());
}
}
out.push('\n');
@@ -2401,6 +2410,38 @@ mod tests {
assert_eq!(prior(&st, NaiveDate::MIN, d(2026, 1, 1)), None);
}
/// The change column: no percent of a zero or negative base.
#[test]
fn a_change_from_a_negative_base_has_no_percent() {
let table = |now: i64, prior: i64| {
let mut t = Table::new(vec!["Now".into(), "Prior".into()]);
t.row(
Kind::Line,
"Rent",
vec![Cell::of(Decimal::from(now)), Cell::of(Decimal::from(prior))],
);
t.add_change();
t
};
// From a positive base: (150 - 100) / 100 = 50.0%.
assert_eq!(
table(150, 100).rows[0].cells[3].value,
Some(Decimal::new(500, 1))
);
// From a negative or zero base: a change, but no percent.
assert_eq!(table(-50, -100).rows[0].cells[3].value, None);
assert_eq!(table(50, 0).rows[0].cells[3].value, None);
// A share of negative income adds no column at all.
let mut t = Table::new(vec!["Now".into()]);
t.row(
Kind::Subtotal,
"Total income",
vec![Cell::of(Decimal::from(-100))],
);
t.add_share_of_income();
assert_eq!(t.columns.len(), 1);
}
/// too_many_columns: a split's column count, counted from the months
/// (each started interval a column), only when past MAX_COLUMNS.
#[test]
+192 -41
View File
@@ -2,8 +2,8 @@
//! Inter with tabular figures, and the spacing the whole app shares.
use egui::{
Color32, Context, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Margin, Stroke,
TextStyle, Visuals,
Color32, Context, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, FontTweak,
Margin, Stroke, TextStyle, Visuals,
};
use std::sync::Arc;
@@ -104,6 +104,8 @@ pub fn pal(ctx: &Context) -> Palette {
pub const SEMIBOLD: &str = "semibold";
pub const BOLD: &str = "bold";
/// The fixed-width face, by the name it is registered under.
const MONO: &str = "Hack";
pub fn regular(size: f32) -> FontId {
FontId::new(size, FontFamily::Proportional)
@@ -122,63 +124,101 @@ pub fn install_fonts(ctx: &Context) {
ctx.set_fonts(font_definitions());
}
/// The viewer's fonts: Inter with tabular figures frozen in, so every
/// number in the app lines up digit for digit; egui's own fonts and
/// Phosphor's icons as fallbacks in every family; then the PDFs' Noto
/// fallbacks (`ledger_import::fonts::FALLBACKS`: Chinese, Japanese,
/// Korean, Arabic, Hebrew, Thai, Devanagari), the very bytes the PDFs use,
/// so a name in any of those scripts shows as written, never as empty
/// boxes, and no font is in the binary twice. (egui shapes each word,
/// joining Arabic and setting it right to left, but doesn't reorder the
/// words of a right-to-left phrase: they read left to right.)
/// The viewer's fonts, every one named here and kept in `assets/fonts/`
/// with its licence (`assets/fonts/README.md`); egui's own default set is
/// switched off, since it carries Ubuntu Light under a licence Debian and
/// Fedora class as non-free:
///
/// - Inter with tabular figures frozen in, so every number in the app
/// lines up digit for digit: the text face, in three weights.
/// - Hack for fixed-width text (identifiers, hashes, JSON), with Inter
/// behind it for the letters Hack lacks.
/// - Phosphor's icons, then Noto Emoji and the emoji icon font, as
/// fallbacks: the symbols egui's own widgets and a Markdown document
/// draw (a submenu's arrow, the date picker's calendar, an alert's
/// mark), and an emoji in a memo.
/// - The PDFs' Noto fallbacks (`ledger_import::fonts::FALLBACKS`: Chinese,
/// Japanese, Korean, Arabic, Hebrew, Thai, Devanagari), the very bytes
/// the PDFs use, so a name in any of those scripts shows as written,
/// never as empty boxes, and no font is in the binary twice. (egui
/// shapes each word, joining Arabic and setting it right to left, but
/// doesn't reorder the words of a right-to-left phrase: they read left
/// to right.)
pub fn font_definitions() -> FontDefinitions {
let mut fonts = FontDefinitions::default();
let add = |fonts: &mut FontDefinitions, name: &str, bytes: &'static [u8]| {
fonts
.font_data
.insert(name.to_owned(), Arc::new(FontData::from_static(bytes)));
let mut fonts = FontDefinitions::empty();
let add = |fonts: &mut FontDefinitions, name: &str, data: FontData| {
fonts.font_data.insert(name.to_owned(), Arc::new(data));
};
// The two symbol fonts are drawn a little smaller, as egui draws them,
// so a symbol sits with the text beside it.
let smaller = |bytes: &'static [u8], scale: f32| {
FontData::from_static(bytes).tweak(FontTweak {
scale,
..Default::default()
})
};
add(
&mut fonts,
"InterTab-Regular",
include_bytes!("../assets/fonts/InterTab-Regular.ttf"),
FontData::from_static(include_bytes!("../assets/fonts/InterTab-Regular.ttf")),
);
add(
&mut fonts,
"InterTab-SemiBold",
include_bytes!("../assets/fonts/InterTab-SemiBold.ttf"),
FontData::from_static(include_bytes!("../assets/fonts/InterTab-SemiBold.ttf")),
);
add(
&mut fonts,
"InterTab-Bold",
include_bytes!("../assets/fonts/InterTab-Bold.ttf"),
FontData::from_static(include_bytes!("../assets/fonts/InterTab-Bold.ttf")),
);
add(
&mut fonts,
MONO,
FontData::from_static(include_bytes!("../assets/fonts/Hack-Regular.ttf")),
);
add(
&mut fonts,
"NotoEmoji-Regular",
smaller(
include_bytes!("../assets/fonts/NotoEmoji-Regular.ttf"),
0.81,
),
);
add(
&mut fonts,
"emoji-icon-font",
smaller(include_bytes!("../assets/fonts/emoji-icon-font.ttf"), 0.90),
);
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
let fallbacks: Vec<String> = fonts
.families
.get(&FontFamily::Proportional)
.cloned()
.unwrap_or_default();
// Text first, icons as a fallback. The bundled Inter copies have their
// private-use glyphs removed, so Phosphor's icons (which live there)
// are never shadowed.
let family = |primary: &str| {
let mut v = vec![primary.to_owned()];
v.extend(fallbacks.iter().cloned());
v
// Text first, then icons and symbols. The bundled Inter copies have
// their private-use glyphs removed, so Phosphor's icons (which live
// there) are never shadowed.
let symbols = ["NotoEmoji-Regular", "emoji-icon-font"];
let family = |first: &[&str]| -> Vec<String> {
first
.iter()
.chain(&symbols)
.map(|name| (*name).to_owned())
.collect()
};
fonts
.families
.insert(FontFamily::Proportional, family("InterTab-Regular"));
fonts.families.insert(
FontFamily::Proportional,
family(&["InterTab-Regular", "phosphor"]),
);
fonts.families.insert(
FontFamily::Name(SEMIBOLD.into()),
family("InterTab-SemiBold"),
family(&["InterTab-SemiBold", "phosphor"]),
);
fonts.families.insert(
FontFamily::Name(BOLD.into()),
family(&["InterTab-Bold", "phosphor"]),
);
fonts
.families
.insert(FontFamily::Name(BOLD.into()), family("InterTab-Bold"));
.insert(FontFamily::Monospace, family(&[MONO, "InterTab-Regular"]));
for (name, bytes) in &ledger_import::fonts::FALLBACKS {
add(&mut fonts, name, bytes);
add(&mut fonts, name, FontData::from_static(bytes));
for list in fonts.families.values_mut() {
list.push((*name).to_owned());
}
@@ -278,10 +318,10 @@ mod tests {
use super::*;
/// font_definitions: every family ends with the PDFs' Noto fallbacks,
/// in their order, after Inter, egui's fonts and the icons, each font
/// the very bytes ledger-import bundles (the same pointer: one copy in
/// the binary); and a name in each script shows with real glyphs in
/// every family the viewer uses.
/// in their order, after its own face, the icons and the symbol fonts,
/// each Noto font the very bytes ledger-import bundles (the same
/// pointer: one copy in the binary); and a name in each script shows
/// with real glyphs in every family the viewer uses.
#[test]
fn every_family_falls_back_to_the_noto_fonts() {
let defs = font_definitions();
@@ -300,6 +340,7 @@ mod tests {
assert_eq!(list[list.len() - names.len()..], names[..], "{family:?}");
}
assert!(defs.families[&FontFamily::Proportional][0] == "InterTab-Regular");
assert!(defs.families[&FontFamily::Monospace][0] == MONO);
for (name, bytes) in &ledger_import::fonts::FALLBACKS {
let data: &[u8] = &defs.font_data[*name].font;
assert!(
@@ -334,4 +375,114 @@ mod tests {
}
}
}
/// font_definitions: the viewer draws with the fonts it names and no
/// others. egui's default set is off (it carries Ubuntu Light, under
/// the Ubuntu Font Licence), so a family is exactly what theme.rs
/// lists; and without that set nothing the viewer shows turns into an
/// empty box: every character egui's widgets, the date picker and a
/// Markdown document draw by themselves, and every character in the
/// viewer's own source, has a glyph.
#[test]
fn the_viewer_names_every_font_and_draws_every_symbol() {
assert!(
FontDefinitions::default().font_data.is_empty(),
"egui's default fonts are compiled in: a dependency switched `default_fonts` on"
);
let defs = font_definitions();
let mut bundled: Vec<&str> = defs.font_data.keys().map(String::as_str).collect();
bundled.sort_unstable();
let mut expected = vec![
"Hack",
"InterTab-Bold",
"InterTab-Regular",
"InterTab-SemiBold",
"NotoEmoji-Regular",
"emoji-icon-font",
"phosphor",
];
expected.extend(ledger_import::fonts::FALLBACKS.iter().map(|(n, _)| *n));
expected.sort_unstable();
assert_eq!(bundled, expected);
for (family, list) in &defs.families {
for name in list {
assert!(defs.font_data.contains_key(name), "{family:?}: {name}");
}
}
let ctx = Context::default();
ctx.set_fonts(defs);
let mut out = ctx.run_ui(egui::RawInput::default(), |_| {});
out.textures_delta.clear();
// egui's `has_glyph` says no for every character the replacement
// glyph's own font draws (here Noto Emoji), so it cannot be the
// whole test. What decides is what is drawn: a character is missing
// when its glyph is the one drawn for a code point no font has.
let glyph = |c: char, id: &FontId| {
let galley =
ctx.fonts_mut(|f| f.layout_no_wrap(c.to_string(), id.clone(), Color32::WHITE));
galley.rows[0].row.glyphs[0].uv_rect
};
const NO_FONT_HAS: char = '\u{0378}';
let missing = |text: &str, id: &FontId| -> Vec<char> {
let blank = glyph(NO_FONT_HAS, id);
text.chars()
.filter(|c| {
!c.is_whitespace()
&& !ctx.fonts_mut(|f| f.has_glyph(id, *c))
&& glyph(*c, id) == blank
})
.collect()
};
// The test can fail: an unassigned code point is missing, and so
// is a letter of a script no bundled font covers (Cherokee).
const CHEROKEE: char = '\u{13E3}';
assert_eq!(
missing("a\u{0378}\u{2022}\u{13E3}", &regular(14.0)),
vec![NO_FONT_HAS, CHEROKEE]
);
// What the libraries draw: a submenu's arrow and the arrow keys
// (egui), the date picker's calendar and its arrows (egui_extras),
// a code block's copy button and the five alert marks
// (egui_commonmark), a check mark, a bullet, an ellipsis.
let libraries = "⏵⏴⏶⏷📆🗐✔❕💡💬🔴⚙•…";
for id in [regular(14.0), semibold(14.0), bold(14.0)] {
assert_eq!(missing(libraries, &id), Vec::<char>::new(), "{id:?}");
}
// What the viewer itself draws: every character of its source
// outside the comments.
let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut files = vec![src];
let mut seen = 0;
while let Some(path) = files.pop() {
if path.is_dir() {
files.extend(std::fs::read_dir(&path).unwrap().map(|e| e.unwrap().path()));
continue;
}
if path.extension().is_none_or(|e| e != "rs") {
continue;
}
for (n, line) in std::fs::read_to_string(&path).unwrap().lines().enumerate() {
let code = line.trim_start();
if code.starts_with("//") {
continue;
}
// A private-use character is a Phosphor icon by its
// escape, and a variation selector draws nothing.
let drawn: String = code
.chars()
.filter(|c| !c.is_ascii() && *c != '\u{FE0F}')
.collect();
seen += drawn.chars().count();
assert_eq!(
missing(&drawn, &regular(14.0)),
Vec::<char>::new(),
"{}:{}",
path.display(),
n + 1
);
}
}
assert!(seen > 50, "the source walk found {seen} characters");
}
}
+119
View File
@@ -0,0 +1,119 @@
//! K-U9: one display rounding, and no float in a money path.
//!
//! The behavioural half uses the public formatting API. The source
//! half is a scoped grep: the display files that shorten or ratio
//! money must not name `round_dp` (they go through
//! `ledger_import::round_display` or `kernel::percent_of`), and a
//! float conversion of a decimal may appear only at the xlsx cell
//! boundary, where the cell itself is a binary double and the value
//! is written as a number only when it is exactly representable.
use rust_decimal::Decimal;
use std::path::{Path, PathBuf};
use std::str::FromStr;
fn dec(s: &str) -> Decimal {
Decimal::from_str(s).unwrap()
}
fn crate_src(krate: &str, file: &str) -> String {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
std::fs::read_to_string(root.join(krate).join("src").join(file))
.unwrap_or_else(|e| panic!("{krate}/src/{file}: {e}"))
}
fn all_rs(dir: &Path, out: &mut Vec<PathBuf>) {
for e in std::fs::read_dir(dir).unwrap() {
let p = e.unwrap().path();
if p.is_dir() {
all_rs(&p, out);
} else if p.extension().is_some_and(|x| x == "rs") {
out.push(p);
}
}
}
/// Display rounding: half away from zero, never a negative zero.
#[test]
fn display_rounding_is_half_away_and_never_negative_zero() {
let r = ledger_import::round_display;
assert_eq!(r(dec("1.005"), 2), dec("1.01"));
assert_eq!(r(dec("-1.005"), 2), dec("-1.01"));
assert_eq!(r(dec("2.5"), 0), dec("3"));
assert_eq!(r(dec("-0.004"), 2).to_string(), "0.00");
assert_eq!(ledger_import::format_amount(dec("-0.004")), "0.00");
assert_eq!(ledger_import::format_amount(dec("-1.005")), "(1.01)");
// The viewer re-exports the same function.
assert_eq!(ledger_gui::fmt::round_display(dec("1.005"), 2), dec("1.01"));
}
/// A percentage of a zero or negative base is shown as nothing.
#[test]
fn a_percent_of_a_zero_or_negative_base_is_none() {
assert_eq!(
ledger_gui::fmt::pct_change(dec("200"), dec("250")),
Some(dec("25.0"))
);
assert_eq!(ledger_gui::fmt::pct_change(dec("0"), dec("5")), None);
assert_eq!(ledger_gui::fmt::pct_change(dec("-100"), dec("-50")), None);
}
/// No `round_dp` left in the display paths, and no float conversion
/// of a decimal outside the xlsx cell boundary.
#[test]
fn no_round_dp_or_float_conversion_in_money_display_paths() {
for (krate, file) in [
("ledger-gui", "fmt.rs"),
("ledger-gui", "books.rs"),
("ledger-gui", "demo.rs"),
("ledger-gui", "pages/profit.rs"),
("ledger-gui", "pages/reports.rs"),
("ledger-gui", "pages/overview.rs"),
("ledger-gui", "pages/cash.rs"),
("ledger-gui", "pages/capital.rs"),
("ledger-import", "report.rs"),
("ledger-import", "pdf.rs"),
("ledger-import", "xlsx.rs"),
("ledger-import", "format.rs"),
("ledger-package", "text.rs"),
] {
assert!(
!crate_src(krate, file).contains("round_dp"),
"{krate}/src/{file} must use round_display / kernel rounding"
);
}
// fmt's percent and compact paths (everything above `bytes`, which
// sizes a byte count, not money) name no float at all.
let fmt_src = crate_src("ledger-gui", "fmt.rs");
let (money_half, _) = fmt_src
.split_once("pub fn bytes")
.expect("fmt::bytes exists");
assert!(
!money_half.contains("f64"),
"fmt money paths must be Decimal"
);
assert!(
!money_half.contains("f32"),
"fmt money paths must be Decimal"
);
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
for krate in [
"ledger-gui",
"ledger-import",
"ledger-package",
"ledger-mcp",
] {
let mut files = Vec::new();
all_rs(&root.join(krate).join("src"), &mut files);
for f in files {
let text = std::fs::read_to_string(&f).unwrap();
if text.contains("to_f64") {
assert!(
f.ends_with("xlsx.rs"),
"to_f64 only at the xlsx cell boundary: {f:?}"
);
}
}
}
}
+4 -3
View File
@@ -324,9 +324,10 @@ fn origins_and_parties() {
fn percent_change_and_tax_forms() {
let d = |s: &str| s.parse::<Decimal>().unwrap();
assert_eq!(fmt::pct_change(d("0"), d("5")), None);
assert_eq!(fmt::pct_change(d("100"), d("150")), Some(50.0));
assert_eq!(fmt::pct_change(d("200"), d("150")), Some(-25.0));
assert_eq!(fmt::pct_change(d("-100"), d("-50")), Some(50.0));
assert_eq!(fmt::pct_change(d("100"), d("150")), Some(d("50.0")));
assert_eq!(fmt::pct_change(d("200"), d("150")), Some(d("-25.0")));
// K-U9: no percent of a negative base (it misleads); Decimal, never f64.
assert_eq!(fmt::pct_change(d("-100"), d("-50")), None);
use ledger_core::TaxForm::*;
for (f, number) in [
(ScheduleC, "Schedule C"),
+1
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
description = "wanderbooks: the books open while something holds them (the host, its leases, the helper and the agents' bridge)."
[dependencies]
+2 -1
View File
@@ -3,6 +3,7 @@ name = "ledger-import"
version = "0.1.0"
edition = "2024"
license = "MIT OR Apache-2.0"
publish.workspace = true
[dependencies]
ledger-core = { path = "../ledger-core" }
@@ -11,7 +12,7 @@ rust_decimal = "1"
chrono = "0.4"
serde = { version = "1", features = ["derive"] }
thiserror = "2"
rust_xlsxwriter = "0.90"
rust_xlsxwriter = "0.102"
typst-as-lib = { version = "0.17", default-features = false }
typst-pdf = "0.15.1"
typst = "0.15.1"
+70
View File
@@ -0,0 +1,70 @@
//! The one rounding for presentation: an amount rounded for display,
//! never for the books. Every renderer that shortens an amount to a
//! fixed number of places goes through [`round_display`], so a display
//! change never changes a booked figure and a booked figure never
//! changes because of a display change.
//!
//! ```text
//! GOAL: one definition of display rounding for every renderer.
//! SOURCE: CONVENTION (US accounting presentation: an amount shown to a
//! fixed number of places rounds half away from zero, as
//! crate::report::format_amount has always done).
//! INVARIANTS:
//! 1. round_display(amount, places) is amount rounded to `places`
//! decimal places, half away from zero, through the kernel's one
//! rounding primitive (ledger_core::kernel::round_places).
//! 2. Never a negative zero: a result that is zero is "0.00", never
//! "-0.00" and never "(0.00)".
//! 3. Display only: the result is for printing. Callers never book it.
//! SCENARIOS:
//! 1. IF 1.005 to two places: SHOULD be 1.01 (and -1.005, -1.01).
//! 2. IF -0.004 to two places: SHOULD be 0.00, never a negative zero.
//! 3. IF 2.5 to zero places: SHOULD be 3 (and -2.5, -3).
//! ```
use ledger_core::kernel::Rounding;
use rust_decimal::Decimal;
/// `amount` rounded to `places` decimal places for display: half away
/// from zero, never a negative zero. See the module spec.
pub fn round_display(amount: Decimal, places: u32) -> Decimal {
match ledger_core::kernel::round_places(amount, places, Rounding::HalfAwayFromZero) {
Some(r) => r,
// Rounding to fewer places cannot grow an amount past Decimal's
// range in practice; past exact arithmetic, show the amount
// itself (with no negative zero) rather than a wrong figure.
None if amount.is_zero() => Decimal::ZERO,
None => amount,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
fn dec(s: &str) -> Decimal {
Decimal::from_str(s).unwrap()
}
#[test]
fn half_away_from_zero() {
assert_eq!(round_display(dec("1.005"), 2), dec("1.01"));
assert_eq!(round_display(dec("-1.005"), 2), dec("-1.01"));
assert_eq!(round_display(dec("2.5"), 0), dec("3"));
assert_eq!(round_display(dec("-2.5"), 0), dec("-3"));
assert_eq!(round_display(dec("1.004"), 2), dec("1.00"));
assert_eq!(round_display(dec("1234567.891"), 2), dec("1234567.89"));
}
#[test]
fn never_a_negative_zero() {
for s in ["-0.004", "-0.00", "-0", "0"] {
let r = round_display(dec(s), 2);
assert_eq!(r, Decimal::ZERO, "{s}");
assert!(!r.is_sign_negative(), "{s}");
}
assert_eq!(round_display(dec("-0.004"), 2).to_string(), "0.00");
assert_eq!(round_display(dec("-0.4"), 0).to_string(), "0");
}
}
+2
View File
@@ -19,6 +19,7 @@ pub mod chart_csv;
/// The one reader, now the `ledger-reader` crate (D-61), kept at its old path.
pub use ledger_reader as extract;
pub mod fonts;
pub mod format;
pub mod iif;
pub mod invoice_pdf;
pub mod labels;
@@ -32,6 +33,7 @@ pub use asset_register::{asset_register_pdf, asset_register_xlsx};
pub use bank_csv::{BankCsvError, BankTransaction, DateOrder, parse_bank_csv, parse_bank_csv_with};
pub use chart_csv::{ChartRow, parse_chart_csv};
pub use extract::{ExtractError, page_count, page_png, pdf_lines, pdf_text, text_of, xlsx_text};
pub use format::round_display;
pub use iif::{
Iif, IifAccount, IifChange, IifClass, IifError, IifField, LeftOut, MEMO_MAX, NAME_MAX,
NUMBER_MAX, QbAccountType, iif_accounts, iif_classes, journal_to_iif,
+1 -1
View File
@@ -83,7 +83,7 @@ pub fn template_data(st: &Statement, meta: &ReportMeta) -> serde_json::Value {
"currency": r.currency,
"amounts": r.amounts.iter().enumerate().map(|(i, a)| a.map(|a| {
if st.percent_from.is_some_and(|f| i >= f) {
let a = a.round_dp(1);
let a = crate::format::round_display(a, 1);
let negative = a.is_sign_negative() && !a.is_zero();
return serde_json::json!({
"digits": format!("{}%", a.abs().normalize()),
+2 -2
View File
@@ -632,7 +632,7 @@ pub fn period_label(start: NaiveDate, end: NaiveDate) -> String {
/// to the cent.
/// ```
pub fn format_amount(d: Decimal) -> String {
let rounded = d.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointAwayFromZero);
let rounded = crate::format::round_display(d, 2);
let negative = rounded.is_sign_negative() && !rounded.is_zero();
let fixed = format!("{:.2}", rounded.abs());
let (int, frac) = fixed.split_once('.').expect("two decimals");
@@ -664,7 +664,7 @@ pub struct AmountParts {
/// Split an amount for aligned accounting display. Exact: no floats.
pub fn amount_parts(d: Decimal) -> AmountParts {
let rounded = d.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointAwayFromZero);
let rounded = crate::format::round_display(d, 2);
AmountParts {
digits: format_amount(rounded.abs()),
negative: rounded.is_sign_negative() && !rounded.is_zero(),
+1 -1
View File
@@ -442,7 +442,7 @@ fn exact_text(d: Decimal) -> String {
/// cents, at most 15 significant digits. None otherwise.
fn exact_f64(d: Decimal) -> Option<f64> {
use rust_decimal::prelude::ToPrimitive;
let cents = d.round_dp(2);
let cents = crate::format::round_display(d, 2);
if cents != d || cents.abs() > Decimal::new(999_999_999_999_999, 2) {
return None;
}
+1
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
description = "The books server's MCP tools for wanderbooks: the AI-first bookkeeping interface over ledger-store."
[lib]
+1
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
description = "wanderbooks' CPA handoff package and the reports and worksheets it shares with the server: built from the books read-only, by the server or the viewer."
[dependencies]
+5 -1
View File
@@ -22,7 +22,10 @@ use rust_decimal::Decimal;
/// "318.42", "1000.00". Padding only, never rounding: an exact amount with
/// more places (an FX-converted line) keeps them. Never "-0".
pub fn money(n: Decimal) -> String {
let mut n = if n.is_zero() { Decimal::ZERO } else { n };
// Padding only, never rounding: the display rounding at the
// amount's own scale (at least two places) is the identity, and it
// is what drops a negative zero.
let mut n = ledger_import::round_display(n, n.scale().max(2));
if n.scale() < 2 {
n.rescale(2);
}
@@ -42,6 +45,7 @@ pub fn total_text(total: Option<Decimal>) -> String {
/// share, never on its spelling.
pub fn share_text(n: Decimal) -> String {
let mut n = n.normalize();
n = ledger_import::round_display(n, n.scale().max(2));
if n.scale() < 2 {
n.rescale(2);
}
+2 -1
View File
@@ -3,6 +3,7 @@ name = "ledger-reader"
version = "0.1.0"
edition = "2024"
license = "MIT OR Apache-2.0"
publish.workspace = true
description = "The one reader: a PDF's text and pages, an XLSX's cells as exact decimal strings (plan P6, D-61)."
[dependencies]
@@ -17,7 +18,7 @@ hayro = { version = "0.8", features = ["embed-fonts"] }
hayro-interpret = "0.8"
kurbo = "0.13"
zip = { version = "9.0.1", default-features = false, features = ["deflate"] }
quick-xml = "0.38"
quick-xml = "0.42"
[lints]
workspace = true
+96 -27
View File
@@ -494,29 +494,59 @@ fn read_zip(zip: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str) -> Option<Stri
Some(String::from_utf8_lossy(&bytes).into_owned())
}
/// What a reference in a cell's text stands for: `&amp;` is `&`, `&#233;`
/// is `é`. The parser hands a reference over as its own event, apart from
/// the text around it, so a reader that skipped it would turn `AT&amp;T`
/// into `ATT`. A name that is none of XML's five is kept as it was written:
/// a workbook has no DTD to define another.
fn reference_text(r: &quick_xml::events::BytesRef<'_>) -> Result<String, ExtractError> {
if let Some(c) = r
.resolve_char_ref()
.map_err(|e| ExtractError::Xlsx(e.to_string()))?
{
return Ok(c.to_string());
}
let name: &str = r;
Ok(match quick_xml::escape::resolve_predefined_entity(name) {
Some(text) => text.to_owned(),
None => format!("&{name};"),
})
}
/// The text of each `<si>` in `xl/sharedStrings.xml`, rich-text runs
/// concatenated.
fn shared_strings(xml: &str) -> Result<Vec<String>, ExtractError> {
use quick_xml::events::Event;
let mut reader = quick_xml::Reader::from_str(xml);
let mut out = Vec::new();
let mut current: Option<String> = None;
let mut in_text = false;
loop {
match reader.read_event() {
Ok(quick_xml::events::Event::Start(e)) if e.name().as_ref() == b"si" => {
Ok(Event::Start(e)) if e.name().as_ref() == "si" => {
current = Some(String::new());
}
Ok(quick_xml::events::Event::End(e)) if e.name().as_ref() == b"si" => {
Ok(Event::End(e)) if e.name().as_ref() == "si" => {
out.push(current.take().unwrap_or_default());
}
Ok(quick_xml::events::Event::Start(e)) if e.name().as_ref() == b"t" => in_text = true,
Ok(quick_xml::events::Event::End(e)) if e.name().as_ref() == b"t" => in_text = false,
Ok(quick_xml::events::Event::Text(t)) if in_text => {
Ok(Event::Start(e)) if e.name().as_ref() == "t" => in_text = true,
Ok(Event::End(e)) if e.name().as_ref() == "t" => in_text = false,
Ok(Event::Text(t)) if in_text => {
if let Some(s) = &mut current {
s.push_str(&t.decode().map_err(|e| ExtractError::Xlsx(e.to_string()))?);
s.push_str(&t.xml10_content());
}
}
Ok(quick_xml::events::Event::Eof) => break,
Ok(Event::CData(t)) if in_text => {
if let Some(s) = &mut current {
s.push_str(&t.xml10_content());
}
}
Ok(Event::GeneralRef(r)) if in_text => {
if let Some(s) = &mut current {
s.push_str(&reference_text(&r)?);
}
}
Ok(Event::Eof) => break,
Ok(_) => {}
Err(e) => return Err(ExtractError::Xlsx(e.to_string())),
}
@@ -537,30 +567,32 @@ fn sheet_cells(xml: &str, shared: &[String]) -> Result<String, ExtractError> {
let mut inline = String::new();
let mut in_inline_text = false;
loop {
// The text this event adds to the cell being read, if any.
let mut text: Option<String> = None;
match reader.read_event() {
Ok(Event::Start(e)) => match e.name().as_ref() {
b"row" => row = Vec::new(),
b"c" => {
"row" => row = Vec::new(),
"c" => {
cell_type.clear();
value.clear();
inline.clear();
for a in e.attributes().flatten() {
if a.key.as_ref() == b"t" {
cell_type = String::from_utf8_lossy(&a.value).into_owned();
if a.key.as_ref() == "t" {
cell_type = a.value.into_owned();
}
}
}
b"v" => {
"v" => {
in_value = true;
value.clear();
}
b"is" => in_inline = true,
b"t" if in_inline => in_inline_text = true,
"is" => in_inline = true,
"t" if in_inline => in_inline_text = true,
_ => {}
},
Ok(Event::End(e)) => match e.name().as_ref() {
b"row" => rows.push(std::mem::take(&mut row)),
b"c" => {
"row" => rows.push(std::mem::take(&mut row)),
"c" => {
let text = match cell_type.as_str() {
"s" => value
.parse::<usize>()
@@ -576,23 +608,25 @@ fn sheet_cells(xml: &str, shared: &[String]) -> Result<String, ExtractError> {
};
row.push(text);
}
b"v" => in_value = false,
b"is" => in_inline = false,
b"t" if in_inline => in_inline_text = false,
"v" => in_value = false,
"is" => in_inline = false,
"t" if in_inline => in_inline_text = false,
_ => {}
},
Ok(Event::Text(t)) => {
let text = t.decode().map_err(|e| ExtractError::Xlsx(e.to_string()))?;
if in_inline_text {
inline.push_str(&text);
} else if in_value {
value.push_str(&text);
}
}
Ok(Event::Text(t)) => text = Some(t.xml10_content().into_owned()),
Ok(Event::CData(t)) => text = Some(t.xml10_content().into_owned()),
Ok(Event::GeneralRef(r)) => text = Some(reference_text(&r)?),
Ok(Event::Eof) => break,
Ok(_) => {}
Err(e) => return Err(ExtractError::Xlsx(e.to_string())),
}
if let Some(text) = text {
if in_inline_text {
inline.push_str(&text);
} else if in_value {
value.push_str(&text);
}
}
}
Ok(rows
.iter()
@@ -622,4 +656,39 @@ mod tests {
));
assert!(text_of(&bytes, "text/plain", "big.txt").is_none());
}
/// A reference in a cell is its character, not a gap: `AT&amp;T` reads
/// `AT&T`. The parser reports each reference as its own event, and a
/// reader that took only the text events would return `ATT` (it did,
/// from quick-xml 0.38 until this test).
#[test]
fn a_reference_in_a_cell_is_its_character() {
let shared = shared_strings(
"<sst><si><t>AT&amp;T</t></si>\
<si><r><t>caf&#233; </t></r><r><t>&lt;3&gt; &quot;x&quot; &apos;y&apos; &#x41;</t></r></si>\
<si><t>&nbsp;kept</t></si></sst>",
)
.unwrap();
assert_eq!(shared, ["AT&T", "café <3> \"x\" 'y' A", "&nbsp;kept"]);
let cells = sheet_cells(
"<worksheet><sheetData><row>\
<c t=\"s\"><v>0</v></c>\
<c t=\"inlineStr\"><is><t>R&amp;D</t></is></c>\
<c t=\"str\"><v>a&lt;b</v></c>\
<c><v>12.50</v></c>\
<c t=\"b\"><v>1</v></c>\
</row></sheetData></worksheet>",
&shared,
)
.unwrap();
assert_eq!(cells, "AT&T\tR&D\ta<b\t12.50\tTRUE");
}
/// A character reference that names no character is refused, not
/// dropped.
#[test]
fn a_reference_to_no_character_is_refused() {
assert!(shared_strings("<sst><si><t>&#xFFFFFFFF;</t></si></sst>").is_err());
}
}
+2 -1
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
description = "Durable persistence for wanderbooks: a hash-chained JSONL journal as the source of truth, content-addressed blob store, and a disposable SQLite projection."
[dependencies]
@@ -13,7 +14,7 @@ ledger-core = { path = "../ledger-core" }
# must be callable here rather than only from the server. It is pure and
# deterministic (no I/O, no network, no time source).
ledger-reader = { path = "../ledger-reader" }
rusqlite = { version = "0.32", features = ["bundled"] }
rusqlite = { version = "0.41", features = ["bundled", "fallible_uint"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
chrono = "0.4"
+1 -1
View File
@@ -3629,7 +3629,7 @@ fn projection_but_names(dir: &std::path::Path) -> Vec<(String, Vec<String>)> {
.into_iter()
.map(|t| {
let mut stmt = conn.prepare(&format!("SELECT * FROM \"{t}\"")).unwrap();
let names: Vec<String> = stmt.column_names().iter().map(|c| c.to_string()).collect();
let names: Vec<String> = stmt.column_names().map(str::to_string).collect();
let mut rows: Vec<String> = stmt
.query_map([], |r| {
Ok((0..names.len())
+1
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
description = "wanderbooks' encrypted TIN vault: full taxpayer identification numbers and W-9 files, outside the journal"
[dependencies]
+86
View File
@@ -0,0 +1,86 @@
# What a dependency must be for wanderbooks to build on it (`just deny`,
# part of `just check`). Four questions, each a refusal:
# advisories: no known vulnerability (RustSec), nothing yanked
# licenses: only licences that fit a program shipped MIT OR Apache-2.0
# sources: crates.io, and the one git repository named below
# bans: no dependency by wildcard version
# An exception goes here with its reason and a date, never on the command
# line.
[graph]
# The viewer, the server-only build and every platform's dependencies.
all-features = true
[advisories]
yanked = "deny"
# "Unmaintained" is not "vulnerable". A crate wanderbooks itself depends on
# must be maintained, since that one is ours to replace. One that arrives
# through typst or the egui stack (bincode, yaml-rust, paste, rustybuzz,
# ttf-parser, zvariant on 2026-11-09) is theirs to replace, and a known
# vulnerability in it is still refused above.
unmaintained = "workspace"
# RustSec ids deliberately lived with, each with why and since when.
ignore = [
# quick-xml 0.38 (a slow or memory-hungry parse of hostile XML). The
# reader's own quick-xml, which does parse files from outside, is 0.42.
# This older copy comes through typst (typst -> hayagriva ->
# citationberg) and parses citation styles only. wanderbooks renders
# its own compiled-in templates, with no bibliography and no file
# access, so no XML from outside reaches it. Remove these two lines
# when typst moves to a citationberg on quick-xml 0.41 or later.
# Since 2026-11-09.
{ id = "RUSTSEC-2026-0194", reason = "typst's citationberg only; no outside XML reaches it" },
{ id = "RUSTSEC-2026-0195", reason = "typst's citationberg only; no outside XML reaches it" },
]
[licenses]
# Permissive licences, and two that are not plain permissive, each for
# a named crate:
# MPL-2.0: option-ext (through dirs). File-level copyleft: it binds
# changes to that crate's own files, and we ship it unchanged.
# CDLA-Permissive-2.0: Mozilla's root certificates (webpki-root-certs).
# No font licence is on the list (OFL-1.1, Ubuntu-font-1.0): a crate that
# brings fonts under one is refused. The OFL itself fits (Inter is under
# it); the point is that every font the program ships is a file in this
# repository beside its licence (crates/ledger-gui/assets/fonts/README.md,
# crates/ledger-import/fonts/), not something a dependency carried in.
# That keeps out egui's default set (epaint_default_fonts), which holds
# Ubuntu Light under the Ubuntu Font Licence 1.0, non-free to Debian and
# Fedora.
# GPL and LGPL appear in the tree only as one choice of an OR (self_cell,
# r-efi); cargo-deny takes the permissive side. A crate offering only a
# copyleft licence is refused here, which is the point.
allow = [
"MIT",
"MIT-0",
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"BSD-2-Clause",
"BSD-3-Clause",
"ISC",
"Zlib",
"0BSD",
"BSL-1.0",
"CC0-1.0",
"Unlicense",
"Unicode-3.0",
"bzip2-1.0.6",
"MPL-2.0",
"CDLA-Permissive-2.0",
]
confidence-threshold = 0.9
[bans]
# Several versions of one crate are a cost in build time, not a risk:
# the GUI stack brings many. A wildcard version is a risk.
multiple-versions = "allow"
wildcards = "deny"
allow-wildcard-paths = true
[sources]
unknown-registry = "deny"
unknown-git = "deny"
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
# bookspec, the specification and its checker (D-68), pinned by rev in
# crates/ledger-core/Cargo.toml.
allow-git = ["https://git.swaits.com/swaits/bookspec"]
+27
View File
@@ -0,0 +1,27 @@
{{! Plain-text notices for the third-party crates the program links
(`just notices`). The `text` field is licence text, not HTML: triple
braces keep it as it is. }}
THIRD-PARTY NOTICES
wanderbooks is licensed under MIT OR Apache-2.0. It is built with the
third-party Rust crates named below, each under the licence named in its
section, and each licence's text follows. Where a section's text has a
placeholder for its copyright line, the crates' own licence files are
given after the last section, under LICENCE FILES AS PACKAGED. The fonts
the program embeds are listed at the end of this file, under FONTS, each
with its licence. A build-time or development-only dependency is not part
of the program as shipped and is not listed here.
{{#each licenses}}
================================================================================
{{{name}}}
================================================================================
Used by:
{{#each used_by}}
{{crate.name}} {{crate.version}}
{{/each}}
{{{text}}}
{{/each}}
+2 -1
View File
@@ -13,7 +13,8 @@ depends=('gcc-libs' 'glibc')
provides=('wanderbooks')
conflicts=('wanderbooks')
options=('!lto' '!strip')
# The tarball holds usr/bin/wanderbooks, usr/share/applications/ and
# The tarball holds usr/bin/wanderbooks, usr/share/applications/,
# usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt and
# usr/share/wanderbooks/install-method (which makes `wanderbooks update`
# refuse and send the owner to pacman).
source=("wanderbooks_${pkgver}_x86_64.tar.gz::https://github.com/swaits/wanderbooks/releases/download/v${pkgver}/wanderbooks_${pkgver}_x86_64.tar.gz")
+3 -1
View File
@@ -36,7 +36,8 @@ sed "s/^version = \".*\"/version = \"$version\"/
s#^out-dir = .*#out-dir = \"$PWD/$out\"#
s#\"target/release\"#\"$PWD/$stage\"#
s#\"deploy/packaging/#\"$PWD/deploy/packaging/#
s#\"LICENSE-MIT\"#\"$PWD/LICENSE-MIT\"#" \
s#\"LICENSE-MIT\"#\"$PWD/LICENSE-MIT\"#
s#^\"THIRD-PARTY-NOTICES.txt\"#\"$PWD/THIRD-PARTY-NOTICES.txt\"#" \
deploy/packaging/packager.toml >"$config"
# The AppImage tools are themselves AppImages; run them without FUSE.
export APPIMAGE_EXTRACT_AND_RUN=1
@@ -45,6 +46,7 @@ assets='assets = [
{ source = "'$PWD/$stage'/wanderbooks", dest = "/usr/bin/wanderbooks", mode = "0755" },
{ source = "deploy/packaging/install-method-rpm", dest = "/usr/share/wanderbooks/install-method", mode = "0644" },
{ source = "deploy/packaging/wanderbooks-static.desktop", dest = "/usr/share/applications/wanderbooks.desktop", mode = "0644" },
{ source = "THIRD-PARTY-NOTICES.txt", dest = "/usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt", mode = "0644" },
]'
cargo generate-rpm -p crates/ledger-cli --set-metadata "version=\"$version\"" --set-metadata "$assets" -o "$out/"
rm -rf "$stage"
+4
View File
@@ -28,9 +28,13 @@ depends = ["libc6", "libgcc-s1"]
[deb.files]
"deploy/packaging/install-method-deb" = "usr/share/wanderbooks/install-method"
# The notices the third-party licences ask to travel with the program
# (`just notices`); `wanderbooks licenses` prints the same text.
"THIRD-PARTY-NOTICES.txt" = "usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt"
[pacman]
depends = ["gcc-libs", "glibc"]
[pacman.files]
"deploy/packaging/install-method-aur" = "usr/share/wanderbooks/install-method"
"THIRD-PARTY-NOTICES.txt" = "usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt"
+4
View File
@@ -51,6 +51,10 @@ test "$before" = "$after"
test "$head_before" = "$(head_of)"
if as_tester 'wanderbooks update' >/tmp/update.out 2>&1; then echo "update did not refuse" >&2; exit 1; fi
grep -q 'package manager' /tmp/update.out
# The new package carries the third-party notices, as a file and in the
# program, and the two are the same text.
test -s /usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt
as_tester 'wanderbooks licenses' | tail -n +3 | cmp -s - /usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt
as_tester 'wanderbooks close' >/dev/null 2>&1 || true
echo "OK"
INNER
+1 -1
View File
@@ -38,7 +38,7 @@ the specification in `bookspec/` (which never depends on the engine).
| `ledger-mcp` | the books server: the MCP tools (122), resources, the handbook, scopes, the door and the access log, backups' scheduling | all of the above |
| `ledger-host` | the host and its leases, the agent bridge (`wanderbooks mcp`), tokens in 0600 files under the data root (D-63), the owner's commands, uploads and downloads, `update` and `rollback` (P11a), books homes and how to start an agent in one (P11b) | `ledger-store`, `ledger-mcp`, `ledger-config` |
| `ledger-gui` | the viewer: read-only, live, egui; the Books menu hands work to the server; the agent dock and the first-run page (P11b) | `ledger-core`, `ledger-store`, `ledger-config`, `ledger-import`, `ledger-package`, `ledger-vault`, `ledger-host` |
| `ledger-cli` | `wanderbooks`, the one executable: every mode (`serve`, `server`, `host`, `mcp`, `gui`, `setup`, `books`, `token`, `connect`, `doctor`, …) and the over-the-wire test suites | everything |
| `ledger-cli` | `wanderbooks`, the one executable: every mode (`serve`, `server`, `host`, `mcp`, `gui`, `setup`, `books`, `token`, `connect`, `doctor`, `licenses`, …) and the over-the-wire test suites | everything |
| `bookspec/checker`, `bookspec/runner` | the example schema and parser, the rule catalogue, the `Engine` trait; the per-rule runner | nothing of ours (the adapter in `ledger-core`'s tests depends on them) |
Dependency direction is always inward toward `ledger-core`; nothing in
+244
View File
@@ -0,0 +1,244 @@
# Commands and steps: what the Lean model covers
bookspec's Lean proves its laws about the books over time for every state
`Reachable` from empty books by a `Step`. The engine changes the books
through 119 public commands on `Ledger`. This page maps each command to
the step or steps it is, so "every reachable state" can be read for what
it covers, and names what it does not.
The map is kept whole by a test
(`crates/ledger-core/tests/command_steps.rs`): a public command on
`Ledger` that takes `&mut self` and has no row here fails the build, and
so does a row for a command that is gone. A new command gets a row, and
if it is not one of the model's steps, a new `Step` in bookspec with its
preservation proof (AGENTS.md, formal methods, item 3).
## The model's steps
Two models run side by side (bookspec `lean/Bookspec/Exec/Doc.lean`,
"Composition"): the ledger (the chart, the posted log, drafts, periods)
and the documents (tagged lines, control accounts, sends).
| Step | Model | What it is |
|---|---|---|
| `addAccount` | ledger | a new account, its code not taken |
| `draft` | ledger | a draft entry (and a line added to one), not in a closed period |
| `post` | ledger | a draft posted: balanced, on known accounts, not in a closed period |
| `reverse` | ledger | a posted entry's mirror, at most once, never a close, not dated before the original |
| `openPeriod` | ledger | a period that nests with or lies apart from every other |
| `close`, `closeToRetained` | ledger | an open period closed, in order, with no draft in it |
| `discard` | ledger | a draft removed |
| `record` | ledger | a record of how the books are kept: no account, entry or period changes |
| `document` | documents | lines posted with their documents (an invoice, a bill, a settlement) |
| `doc.reverse` | documents | the mirror of lines that carry documents |
| `writeOff` | documents | a write-off, above zero and at most what is owed |
| `assign`, `release` | documents | an account takes or gives up a control role |
| `markSent` | documents | a send recorded on an invoice |
## What the map is, and is not
- **A reading, checked two ways, proved in neither.** No proof ties a
Rust command to a Lean step. Two machine checks do: bookspec's examples
(the engine answers each recorded command as the record says), and the
differential test `crates/ledger-core/tests/bookspec/lean_model.rs`,
which runs random command sequences through the engine and the Lean
model and compares every figure and refusal. That test reaches an entry
drafted and posted, a reversal, a close to retained earnings, an
invoice and a bill. It does not reach a standalone `openPeriod`, a close
with explicit targets, a draft left unposted (so `discard`), or an
account added after the first event; those are by review.
- **`record` covers 71 commands.** They change nothing the ledger model
keeps, so every law about balances, statements and periods holds across
them with nothing to prove. Some keep a register with rules of its own
(the note says which); see "Registers" below.
- **Several steps in one command** run inside `Ledger::atomically`: all
of them happen or none does.
## Not covered
### No step: `renumber_account`
The model's chart is a list of codes, and its lines name accounts by
code. The engine's lines name accounts by id, and a renumber changes one
code and no entry. In the model that is a renaming of one code across the
chart and the log, which no step does. The engine refuses a taken code
(`check_renumber_account`), so codes stay distinct, and its tests check
that no balance moves; neither is a theorem. Closes with a `renumber`
step in bookspec: codes stay distinct, and every balance is the old one
under the new code.
### Doors: 17 commands that take what an older version wrote
A journal line an older version accepted must replay (BS-entry-4), so
each rule added later has a door beside the command: the same change
without the newer check. A store calls a door only for a line its journal
already holds. Most drop checks the model does not carry (a size bound, a
minor unit, a text rule). Four drop one the model's step requires:
| Door | The step's condition it does not check |
|---|---|
| `create_entry` | `draft`: the date is in no closed period |
| `replay_generate_recurring` | `draft`: the same |
| `replay_create_period` | `openPeriod`: no partial overlap |
| `replay_reverse_entry` | `reverse`: the reversal is not dated before the original |
So books replayed from a journal written before those rules can stand in
a state the model does not reach, and a caller of the engine that uses a
door for new work can put them there. What still holds, read from the
proofs: the preservation of `Inv.distinct`, `Inv.accepted` and
`Inv.known` (distinct codes, every posted entry balanced and on known
accounts) uses none of the four conditions, so the trial balance and the
accounting equation hold in those books too. `Inv.draftsOpen` (no draft
in a closed period) does not. That reading is not yet a theorem. Closes
with: a `ReplayStep` relation in bookspec (the steps without the four
conditions) and the proof that the three invariants hold in every state
it reaches.
`create_entry` is a door by its doc comment only: its name does not say
so, and it is public. The store calls `try_create_entry` first.
### Registers: state with rules of its own
These are `record` to the ledger model. Their arithmetic is proved as
functions (bookspec `Schedule`, `Prorate`, `Deductible`, `Payroll`,
`Apportion`); how they change over time is tested, not modelled:
- **Fixed assets**: registered, corrected, linked to an acquisition,
depreciated by runs, disposed once.
- **Schedules**: a month posts at most once while its posting stands, and
is due again when that posting is reversed.
- **Recurring entries**: an occurrence is generated at most once.
- **Payroll runs**: a run is recorded with the entry that posted it.
### The pair is one set of books by construction
bookspec says so itself (`Exec/Doc.lean`): that the documents' lines are
exactly the ledger's posted lines is kept by how the runner is built, not
proved. The engine's side of the same fact is `Ledger::atomically` and
the control check (`Ledger::control_check`), which are tested.
## Every command
In source order. "door" in a note marks a command that exists for replay.
| Command | Step | Note |
|---|---|---|
| `register_schedule` | record | register: schedules |
| `register_schedule_under` | record | register: schedules |
| `replay_register_schedule` | record | register: schedules |
| `replay_register_schedule_under` | record | register: schedules |
| `post_schedule_month` | draft, post, record | register: schedules (the month is marked posted) |
| `register_recurring` | record | register: recurring entries |
| `replay_register_recurring` | record | register: recurring entries |
| `generate_recurring` | draft, record | register: recurring entries (the occurrence is marked generated) |
| `replay_generate_recurring` | draft, record | door: no closed-period check; register: recurring entries |
| `add_account` | addAccount | |
| `add_control_account` | addAccount | |
| `replay_add_account` | addAccount | door: without the child-type and blank-text rules; a taken code is still refused |
| `renumber_account` | none | changes a code the chart holds; see "No step" |
| `rename_account` | record | |
| `replay_rename_account` | record | |
| `assign_role` | assign, release | `None` is the release |
| `set_account_tax` | record | |
| `create_entry` | draft | door: no closed-period check (replay, and the engine's own entries, which post at once) |
| `try_create_entry` | draft | |
| `add_line` | draft | |
| `replay_add_line` | draft | door: without the account check and the size bound; the post still refuses |
| `add_line_fx` | draft | |
| `replay_add_line_fx` | draft | door: without the account check and the size bound; the post still refuses |
| `post_entry` | post | |
| `replay_post_entry` | post | door: without the minor-unit check |
| `set_draft_state` | record | a note on a draft: no line moves |
| `replay_set_draft_state` | record | a note on a draft: no line moves |
| `discard_draft` | discard | |
| `replay_discard_draft` | discard | |
| `note_entry_origin` | record | what posted an entry, and its journal line |
| `expect_posted_seq` | record | what posted an entry, and its journal line |
| `stamp_unstamped` | record | what posted an entry, and its journal line |
| `reverse_entry` | reverse, doc.reverse | the document step when a line carries a document |
| `replay_reverse_entry` | reverse, doc.reverse | door: without the date order and the document checks |
| `register_asset` | record | register: fixed assets |
| `replay_register_asset` | record | register: fixed assets |
| `set_asset_tag` | record | register: fixed assets |
| `set_asset_serial` | record | register: fixed assets |
| `set_asset_acquisition` | record | register: fixed assets |
| `replay_set_asset_acquisition` | record | register: fixed assets |
| `restore_asset_acquisition` | record | register: fixed assets |
| `set_asset_description` | record | register: fixed assets |
| `set_asset_basis` | record | register: fixed assets |
| `replay_set_asset_basis` | record | register: fixed assets |
| `replay_set_asset_tax_basis` | record | register: fixed assets |
| `correct_asset` | record | register: fixed assets |
| `replay_correct_asset` | record | register: fixed assets |
| `record_depreciation_run` | record | register: fixed assets |
| `dispose_asset` | record | register: fixed assets |
| `replay_dispose_asset` | record | register: fixed assets |
| `create_period` | openPeriod | |
| `replay_create_period` | openPeriod | door: without the nesting rule and the calendar bound |
| `close_period` | addAccount, closeToRetained | the account only when retained earnings has none yet |
| `close_period_to` | addAccount, close | the account only when a target role has none yet |
| `add_customer` | record | |
| `add_vendor` | record | |
| `set_vendor_1099` | record | |
| `replay_vendor_1099` | record | |
| `set_vendor_w9_flag` | record | |
| `add_instrument` | record | |
| `set_entry_instrument` | record | |
| `set_entry_vendor` | record | |
| `add_party` | record | |
| `update_party` | record | |
| `set_party_role` | record | |
| `set_party_w9` | record | |
| `set_party_tin` | record | |
| `set_party_creditor` | record | |
| `set_party_w4` | record | |
| `set_entry_party` | record | |
| `set_entry_parties` | record | |
| `replay_set_entry_parties` | record | |
| `set_entry_no_party` | record | |
| `create_invoice` | addAccount, draft, post, document | the account only when the control role has none yet |
| `create_invoice_with` | addAccount, draft, post, document | the account only when the control role has none yet |
| `create_bill` | addAccount, draft, post, document | the account only when the control role has none yet |
| `create_bill_with` | addAccount, draft, post, document | the account only when the control role has none yet |
| `mark_sent` | markSent | |
| `replay_invoice_sent` | markSent | |
| `settle` | addAccount, draft, post, document | a settlement is a document step (bookspec `settle_posts_a_document_step`) |
| `receive_payment` | addAccount, draft, post, document | a settlement is a document step (bookspec `settle_posts_a_document_step`) |
| `receive_payment_with` | addAccount, draft, post, document | a settlement is a document step (bookspec `settle_posts_a_document_step`) |
| `pay_bill` | addAccount, draft, post, document | a settlement is a document step (bookspec `settle_posts_a_document_step`) |
| `pay_bill_with` | addAccount, draft, post, document | a settlement is a document step (bookspec `settle_posts_a_document_step`) |
| `write_off` | addAccount, draft, post, writeOff | |
| `void_document` | reverse, doc.reverse | |
| `replay_invoice` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded |
| `replay_invoice_with` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded |
| `replay_bill` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded |
| `replay_bill_with` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded |
| `replay_invoice_payment` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded |
| `replay_invoice_payment_at` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded |
| `replay_invoice_write_off` | writeOff | door: as above |
| `replay_bill_payment` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded |
| `replay_bill_payment_at` | document | door: tags the lines of an entry its own events already replayed; nothing is bounded |
| `mark_cleared` | record | |
| `set_fx_rate` | record | |
| `run_payroll` | addAccount, draft, post, record | register: payroll runs |
| `remit_payroll_taxes` | draft, post | |
| `replay_payroll_run` | record | register: payroll runs |
| `apply_settings` | record | |
| `annotate_attachment` | record | |
| `replay_annotate_attachment` | record | |
| `set_entry_settles` | record | |
| `replay_set_entry_settles` | record | |
| `apply_convention` | record | |
| `apply_convention_source` | record | |
| `apply_decision_source` | record | |
| `apply_open_item_source` | record | |
| `apply_retire_convention` | record | |
| `apply_decision` | record | |
| `apply_open_item` | record | |
| `apply_resolve_item` | record | |
| `apply_approval` | record | |
| `add_class` | record | |
| `set_line_class` | record | a note on a draft: no line moves |
| `replay_class` | record | |
| `set_project` | record | |
| `replay_set_project` | record | |
+6
View File
@@ -6,3 +6,9 @@ entries. Started 2026-11-09; earlier tasks were not logged.
Columns: date | type (scout, run/verify, implement, refactor, debug, review) | provider/model/effort | size | wall-clock to report | tokens | outcome | rework | note
2026-11-09 | implement | muse / muse-wonder-1.0 / reasoningEffort high | small | 2h25m (machine at load 90+; the code was done in ~13 min) | | accepted after fixes | me, ~10 min: boundary assertions a tenth of a unit past the bound; its raw arithmetic in audit.rs still to route through the kernel | V-D3; sent before the tier policy; the bound covers one legacy close, not several
2026-11-09 | refactor | muse / muse-wonder-1.0 / reasoningEffort high | medium (17 files, +498/-62) | 4h13m (machine at load 50-90) | | accepted after one fix | me, ~5 min: the demo books' booked fee was put on the display rounding; back on the kernel's, rule unchanged | K-U9; sent before the tier policy; worked from a base 16 commits old, so it reported a traceability failure that main does not have; its report matched its diff
2026-11-09 | implement | opencode / opencode-go/deepseek-v4.1-flash / variant high | medium (10 files, 369 lines beside the generated file) | 1h15m | | accepted after rework | me, ~1 h: the check takes 2 minutes, not seconds; a failure hint; why `--offline`; and the real gap, 70 crates whose notice was a licence text with a placeholder copyright line, closed with a second script | third-party notices; the brief was followed to the letter and every DONE-MEANS output matched; it did not look at whether the generated text carried what the licences ask for, which the brief did not ask it to
2026-11-09 | debug/hard implement | claudeAgent / claude-sonnet-5-5 / effort high | large (14 files, +1144/-152) | 6h20m (machine shared with three other workers) | | accepted after rework | me, ~1 h: `checked_div_exact` accepted a rounded quotient (10 / 3), fixed with tests; then the review's fixes (below) | K-U10a, exact Decimal sums and products; the design (256-bit product, a sticky digit, one rounding) was its own and held up under review; its properties proved a figure returned is exact, not that an exact figure is never refused
2026-11-09 | review | muse / muse-wonder-full-1.0 / reasoningEffort high | large (the K-U10a diff) | 1h05m | | six findings, all reproduced: one refusal the docs did not state (a step of 27 or 28 places), four gaps in what the properties covered, stale sentences; no wrong figure in 400,000 sampled pairs | me, ~1 h: the properties now also prove nothing representable is refused; the refusal stated and pinned | worth its cost: the completeness gap is the kind the author's own tests cannot see; it ran no cargo, Kani or Lean itself
2026-11-09 | debug/hard implement | claudeAgent / claude-sonnet-5-5 / effort high | medium (7 files) | 4h (machine shared) | | accepted after rework | me, ~1.5 h: its ranking used the exact product, which K-U10a makes a refusal for weights of 27 places (now the rounding product, with a test); it ran no Kani, and Kani then failed the unit: a cover in `split_by_weights_within_one_step` could no longer be reached, since the exact ranking makes the bound strict on i64 (harness tightened) | K-U10b, ties by the exact remainder; its measurement of what moves (`ties.rs`) was what the owner's decision needed; worked from a stale base again
+128
View File
@@ -0,0 +1,128 @@
# K-U9: display rounding, and percentages in Decimal
_Folded into `docs/verification.md` by the integrator; this note is the
unit's own record._
Kernel sweep unit U9 (`plan/kernel-sweep-audit.md` section 3, "display
rounding"). Display only: no kernel function, no Kani harness, no Lean
theorem (the audit and `docs/proofs/README.md` say so for U9). The
rounding it shares is the kernel's already-proved `round_places`
(K-U2, law 40); the percentages it shares are `kernel::percent_of`
(K-U6).
## The API
```rust
// ledger-import::format (re-exported at the crate root)
pub fn round_display(amount: Decimal, places: u32) -> Decimal
```
Half away from zero to `places`, through
`ledger_core::kernel::round_places(..., Rounding::HalfAwayFromZero)`,
never a negative zero. It is the rounding half of
`ledger-import::report::format_amount`, lifted out so every renderer
shares it: `format_amount` and `amount_parts` call it at two places,
`ledger-import::pdf`'s percent column at one place,
`ledger-import::xlsx::exact_f64` at two places (before its exactness
check), `ledger-package::text`'s `money`/`share_text` at the amount's
own scale (the identity there: padding only, never rounding, as those
functions promise), and `ledger-gui::fmt` re-exports it for the pages.
## The percent rule (one rule for every percent)
A percent of a zero or negative whole is `None`, and the page shows
nothing (a KPI tile keeps no sub-line) or "—" (a table cell). That is
`kernel::percent_of`'s rule, and K-U9 adopts it everywhere:
- `ledger-gui::fmt::pct_change` returns `Option<Decimal>` (it was
`Option<f64>`, dividing money amounts in binary floating point):
`(now - prev) / prev * 100` to one place, half away from zero, via
`percent_of`. A negative `prev` gave a signed percent before; now
`None`.
- `ledger-gui::pages::profit::pct` (margins, shares of invoiced
income): `percent_of` at one place, half to even — the books' margin
mode, as `contribution_margin_pct` uses. A negative revenue base
gave a percent before; now `None`, shown as "—".
- `ledger-gui::pages::reports`' change column: was
`diff / base.abs() * 100`, a percent of a negative base with the sign
hidden; now `percent_of(diff, base, ...)`, `None` for base <= 0.
The "% of income" column likewise adds no column when total income
is zero or negative (it added none for zero before).
- `ledger-gui::pages::capital::percent`: a member's share is a stored
fraction, not a ratio of two amounts, so it stays exact decimal
multiplication by 100 with no rounding; only a negative zero is
dropped. No float was involved.
## Sites routed
- `ledger-import`: `report::format_amount`, `report::amount_parts`,
`pdf` percent column, `xlsx::exact_f64` — through `round_display`.
- `ledger-package::text::money`, `share_text` — through
`round_display` at their own scale (identity; see above).
- `ledger-gui::fmt::compact`: was `f64` (`try_into`, `{:.1}` prints).
Now decimal division by 1,000 / 1,000,000 and `round_display`. Two
displayed figures change, both f64 artefacts: 1,250,000 shows
"$1.3M" (was "$1.2M": 1.25 in binary is slightly under), 10,500 shows
"$11k" (was "$10k": float formatting rounds 10.5 to even).
- `ledger-gui::fmt::pct_change` and its caller
`pages/overview::change` ("▲ 12% vs …" text and the 0.5% colour
threshold): Decimal throughout.
- `pages/overview` runway months, `pages/cash` average net and runway,
`pages/profit` spending row, `pages/reports` change / share / TSV,
`books` monthly-burn average, `demo` platform fee: `round_dp(1|2)`
through `round_display` (checked division where the old code divided
raw under a guard).
- `books`' two share splits truncated to cents with `ToZero`: that is
a leftover policy, not display rounding, so it now goes through
`kernel::round_places(..., TowardZero)` as `truncate_cents`, with no
change of value.
## Floats kept, with why
- `ledger-gui::charts` (`f(Decimal) -> f64`, `ticks`, sparklines,
`pages/overview`/`cash` spark vectors, `widgets::Kpi::spark`): pixel
coordinates and axis scales computed for layout only. Every hover
and label that states a figure reads the original `Decimal`
(`fmt::dollars`, `fmt::compact`); no printed amount is computed in
a float.
- egui layout `f32`s (column widths, row heights), colour maths in
`schemes.rs`, image sizes in `receipts.rs`: geometry and colour,
never money.
- Time `f64`s (`app::since_update`, `widgets` timers,
`pages/reports::pdf_done`, `pages/transactions::since_update`):
egui's clock, never money.
- `fmt::bytes` (`n as f64`): a byte count for "12.3 KB", not money.
- `ledger-import::labels` geometry (`f64` millimetre/point layout),
`asset_register`'s life-in-months cell (`f64::from(months)`: a
count), `xlsx` entry-id cells (`as f64`: an id): layout and counts.
- `ledger-import::xlsx::exact_f64` (`to_f64`): the one sanctioned
conversion — an xlsx cell is a binary double, and a value is
written as a number only when it is whole cents of at most 15
significant digits, exactly representable; anything else is text.
- `ledger-mcp::types` `visit_f64`: serde's visitor signature for
refusing a float TIN, not a computation.
- `ledger-import::templates::equal_shares`: owner-percentage template
(audit class (c)), last-absorbs so the shares sum to 100; not a
display rounding of a money amount, left as is.
## Tests
- `crates/ledger-import/src/format.rs`: half away from zero at ties,
never a negative zero.
- `ledger-gui::fmt` tests: `pct_change` decimal-or-none (zero and
negative bases), `compact` decimal ties.
- `ledger-gui::pages::profit` tests: no percent of a negative base.
- `ledger-gui::pages::reports` tests: the change column has no
percent from a zero or negative base; no "% of income" column for
negative income.
- `crates/ledger-gui/tests/display_rounding.rs`: the rules through
the public API, plus a scoped source check (no `round_dp` in the
display files; no `f64` in `fmt`'s money half; `to_f64` only in
`xlsx.rs`).
No golden changes. Displayed values that changed are the two
`compact` ties above and the percents of negative bases (now "—" /
no sub-line instead of a signed figure). One existing test encoded
the old negative-base percent (`ledger-gui/tests/view_model.rs`:
`pct_change(-100, -50)` was `Some(50.0)`); it now expects `None`,
per the rule above.
+1 -1
View File
@@ -49,7 +49,7 @@ the precondition, and states that `Decimal::checked_mul`'s two
behaviours outside it are inherited, not hidden: rounding past scale 28
(and past 96 bits), and `1e-28 x 1e-28` underflowing to zero.
**An open edge, not closed by D-75.** The 96-bit half of the
**An open edge, not closed by D-75 (closed since by K-U10, `docs/proofs/k-u10.md`).** The 96-bit half of the
precondition is not enforced: ten places each still allow a product of
twenty places past about 7.9e8, which needs more than 96 bits.
`1050000010.0000000001 x 9.9999999999` is 10500000099.89499999999999999999
+212
View File
@@ -0,0 +1,212 @@
# K-U10: `Decimal`'s sums and products are exact or refused (`kernel/decimal_exact.rs`)
_Folded into `docs/verification.md` ("The kernel sweep" and "What is and
isn't proved"); this note is the unit's own record._
Plan unit K-U10a (`plan/p14-bookspec.md`, the K-U10 row). Rules: BS-ledger-1
(a product the arithmetic cannot hold MUST be refused; a foreign amount is
booked as the exact product rounded once) and BS-entry-4 (what a line can
carry). The tie-ranking item of the K-U10 row (`split_by_weights_into`'s
exact remainders) is an owner decision and is **not** in this unit.
## The findings
`rust_decimal`'s `checked_add` and `checked_mul` return `None` only when
the integer part overflows. When the exact result needs more than 96 bits
of mantissa at the operands' scale, or a scale past 28, they return a
**rounded** `Some`:
| Operation | Exact | `rust_decimal` | Found by |
|---|---|---|---|
| `MAX + 0.4` | 79228162514264337593543950335.4 | `Some(MAX)` | K-U4 |
| `0.01 + 792281625142643375935439503.35` | …503.36 | `…503.4` | K-U8 |
| `1050000010.0000000001 x 9.9999999999` | 10500000099.89499999999999999999 | `10500000099.895000000000000000` | K-U1 |
| `123456789.0123456789²` | 15241578753238836.75019051998750190521 | `15241578753238836.750190519988` | K-U3 |
| `1e-28 x 1e-28` | 1e-56 | `Some(0)` | K-U1 |
`checked_div` (rounds at 28 significant digits) is the engine's rounding
division and is unchanged.
A sixth, found in review of this unit: `checked_div_exact` ("never a
rounded share") checked its quotient by multiplying back with
`rust_decimal`'s product. A rounded quotient times the divisor rounds back
to the dividend (`10 / 3` is 3.333…3 at 28 places, and 3.333…3 x 3 is held
as 10), so `10 / 3`, `10 / 7`, `80 / 9` and `1000000.00 / 3` each came back
`Some`. Its one caller divides a basis-point product by 10,000, which is
always exact, so no figure was wrong. It now multiplies back with
`exact_mul` and refuses them.
## The method
`impl Amount for Decimal` (`kernel/entries.rs`) runs `rust_decimal`'s
operation and then checks, in 256-bit integers, that the figure it returned
**equals the exact result as a rational**; if not, `None`. It never builds a
figure of its own, so:
1. `Some(r)` is the exact sum or product (checked, not assumed).
2. A result that was exact is returned **as `rust_decimal` gave it, scale
and all**: nothing exact moves, by construction.
3. A result that was rounded is `None`; one that was `None` stays `None`.
The check (`decimal_exact.rs`): a `Decimal` is `m x 10^-s`, `|m| < 2^96`,
`s <= 28`. For a sum `a + b = r`, at the common scale `s = max(sa, sb, sr)`
every term `m x 10^(s-si)` is under `2^96 x 10^28 < 2^190`, so the equation
is `Σ positive terms == Σ negative terms` over unsigned 256-bit values,
with no overflow possible. For a product, `ma x mb` (under `2^192`, at
scale `sa + sb <= 56`) is compared with `mr` at scale `sr` by scaling the
side with fewer places up; overflow past 256 bits means that side is the
larger, so unequal. Zero and sign are handled first. Any failure to compute
answers "not exact".
**Why not "refuse a sum whose result scale fell below the operands'".** The
K-U10 row's test is sound for a rounding but not complete as an exactness
test in the other direction: it would refuse exact figures (a product whose
full-scale mantissa passes 96 bits but whose last digits are zeros, like
`100 x 0.3333333333333333333333333333` = 33.33…3300, which `percent_of`
computes for every ratio, or `10^20 x 10^-20` squared) and `periods.rs`'s
hand-written scale check does exactly that. Comparing values is the
complete test, so nothing exact is refused (`an_exact_product_that_only_looks_wide_is_kept`,
and law 5 of the bridge properties: `Some` exactly when the exact result
is a `Decimal`, decided from the rational alone).
`Amount::checked_sub` for `Decimal` is `rust_decimal`'s subtraction under
the same check. The trait default (`self + (-rhs)`) gave `-0` for `0 - 0`;
this keeps the old inherent subtraction's `0`, which is also what
`Money::checked_sub` had (`Money::checked_add` and `checked_sub` now go
through `Amount`, so they inherit the fix).
## Two products that must keep rounding or round once
Making `checked_mul` exact would have refused posted-range inputs, found by
running the suite (`spec_cash_flow`:
`a_shared_government_payment_splits_to_the_cent`):
- **Shares** (`share_of`, `share_floor_with`, so `split_by_weights_with`)
multiply a cent amount by a percent of 27 places
(`33.333333333333333333333333333`), whose exact product needs 29 places;
then divide, which rounds anyway. They use a new
`Amount::checked_mul_rounded` (`rust_decimal`'s own product; on integers
`checked_mul`), so every share is the figure it always was, to the digit.
- **A foreign amount at a rate** (`fx_booked`) is not rounded early:
`Amount::checked_mul_round_to_step` holds the exact product in 256 bits,
cuts it only as far as `Decimal` needs while remembering whether any cut
digit was non-zero (a sticky digit, kept below at least one real digit
past the step), and rounds **once** with `round_step`. The sticky digit
decides a tie (a half followed by zeros) and the directed modes as the
full product would. Consequence: `1050000010.0000000001 x 9.9999999999`
books **10500000099.89**, the exact product's cent, where it booked
10500000099.90 through a rounded 10500000099.895. This is the one posted
behaviour that changes (the D-75 ten-place bound alone does not make the
product fit 96 bits, past about 7.9e8). `None` only for a figure too large
to hold with its rounding digits (about 7.9e24 at a cent, 10^9 times a
journal line's cap).
Everywhere else a product is the amount itself (`line_amount`,
`deductible_amount`, `percent_of`, the gold/no-minor-unit FX product) and
uses `checked_mul`: exact or `None`, each caller turning `None` into its
existing refusal.
## Kani
None added. Kani works on `i64`, which never rounds; `Decimal` is out of its
reach (one symbolic `Decimal` add runs for more than ten minutes), so the
claim rests on the bridge properties below and on Lean's laws over exact
rationals, which these results now equal. The traceability gate's
`EXCEPTIONS` is unchanged: the new items are `pub(super)` helpers and trait
methods, not kernel functions.
## Bridge properties (`tests/kernel_bridge/decimal_exact.rs`)
Compared against `rust_decimal`'s own result (the old behaviour) and an
independent `num_rational::BigRational` reference, over every mantissa to
`2^96 - 1` (small, near the top, trailing zeros) and every scale 0 to 28, at
30,000 cases each:
| Property | Law |
|---|---|
| `add_is_exact_or_none` | `Some(r)` equals the rational sum; equals the old result to the character where that was exact; `None` where it was rounded or `None`; and `Some` exactly when the rational sum is a `Decimal` (a mantissa under 2^96 at a scale of 0 to 28), decided with none of `rust_decimal`'s arithmetic, so nothing representable is refused |
| `sub_is_exact_or_none` | the same, against `rust_decimal`'s subtraction (zero included) |
| `mul_is_exact_or_none` | the same, for products |
| `a_refusal_is_an_overflow_or_a_rounding` | the kernel refuses only where `rust_decimal` overflowed or rounded |
| `posted_range_sums_are_unchanged` | every line-range figure (≤ 10^15, ≤ 10 places, any raw scale holding it): add and subtract equal the old to the character and are never `None` |
| `posted_range_running_totals_are_unchanged` | a running total of up to 100 line-range figures is unchanged at every step |
| `posted_range_running_totals_of_thousands_of_lines_are_unchanged` | the same for 4,000 to 5,000 lines, all of one sign in half the cases, where the total's mantissa comes within a factor of two of 2^96 |
| `a_running_total_is_refused_where_it_would_first_round` | 7,922 lines of 999999999999999.9999999999 sum exactly; the 7,923rd passes 2^96 at ten places, where `rust_decimal` drops a place and rounds and the kernel refuses |
| `posted_range_fx_products_are_unchanged_or_refused` | foreign (≤ 10^25 mantissa, ≤ 10 places) x rate (≤ 10 places): identical to the old whenever the mantissa product fits 96 bits; otherwise the old figure only if it was exact, else `None` |
| `the_fx_product_is_rounded_once_from_the_exact_one` | `checked_mul_round_to_step` equals the exact rational product rounded once, in each of four modes, at steps of 1, 5 and 25 units of 1, 0.1, 0.01 and 0.001 (a step that is not a power of ten has its half steps one place below it), signs and ties included, and at steps of any number of places up to 28; `None` only where the exact product times 10^(the step's places + 2) does not fit 96 bits, or the step has 27 or 28 places (`a_step_of_27_places_refuses_a_product_that_is_not_exact` pins that one) |
| `div_exact_is_exact_or_none` | a quotient `checked_div_exact` returns, times the divisor, is the dividend as a rational (`a_rounded_quotient_is_not_an_exact_one` names the thirds, sevenths and ninths), and it returns one whenever the exact quotient is a `Decimal` |
| `div_exact_over_the_whole_range` | the same over every `Decimal`, half the dividends built as a product so the exact quotient exists |
Also: the three flipped canaries (below), `an_exact_product_that_only_looks_wide_is_kept`,
`zero_is_exact`, `the_k_u1_edge_books_the_cent_the_exact_products_cent`
(and, in `fx.rs`, `the_mantissa_edge_books_the_exact_products_cent`), and
four unit tests inside `decimal_exact.rs` that check the private 256-bit
helpers (`mul_wide`, `checked_add`, `checked_mul_small`, `div_rem_10`,
`scale_up`) against `num_bigint` with edge values.
## Canaries flipped
| Was | Is |
|---|---|
| `total::finding_decimal_add_rounds_dust_at_the_edge` | `total::a_sum_past_exact_arithmetic_is_refused` |
| `control::finding_decimal_add_rounds_scale_near_the_top` | `control::a_sum_past_exact_arithmetic_is_refused` |
| `fx::the_mantissa_edge_is_outside_the_precondition_and_pinned` | `fx::the_mantissa_edge_books_the_exact_products_cent` |
| (new, K-U1/K-U3 products) | `decimal_exact::a_product_past_exact_arithmetic_is_refused` |
| (new) | `decimal_exact::a_sum_past_exact_arithmetic_is_refused_at_the_maximum`, `…_near_the_top` |
Tests whose expectation moved (all outside what a posted line carries;
each a rounded figure that is now refused or correctly rounded):
- `fx::past_ten_places_…` now books 0.00 (the exact product's cent) where
it booked 0.01; the engine still refuses the input (D-75).
- `schedule::the_edges`: 599 parts of 1.3e26 at the cent sum past 96 bits at
scale 2; `rust_decimal` rounded that sum, the kernel refuses it (and
`EXACT_LIMIT` keeps the callers out of it).
- `control::kernel_matches_the_replaced_chains` and
`decimal_matches_i128_reference` now compare with each step's rounded
results refused.
## What did not change
- `checked_div`, the engine's rounding division.
- Every golden and every existing test outside the list above.
- Direct calls of the inherent `Decimal::checked_add/_sub/_mul` outside the
kernel (about 70 sites in `reports`, `tax_capital`, `assets`, `arap`,
`periods`, `schedules`, …) still round at the 96-bit edge: not converted,
because `periods.rs` shares by a many-place percent, for one, relies on a
rounded product, and each is unreachable below about 7.9e26. A follow-up
can convert them one by one against its own refusal.
## What the independent review found
A second model read the unit before it merged (2026-11-09) and sampled
400,000 random pairs against the 256-bit arithmetic: no wrong `Some`. Its
findings, each reproduced before it was acted on:
- **One refusal the docs did not state.** `checked_mul_round_to_step`
returns `None` for a product that is not exact at a step of 27 or 28
places, though the rounded figure can be a `Decimal` (1e-28 squared to
a step of 1e-27 is zero). The one rounding needs a real digit and a
sticky digit below the step, and `Decimal` has no place for them past
28. Kept, stated in the trait and in `mul_for_rounding`, and pinned by a
test: it is a refusal, no step in any books is near it, and removing it
means dividing in 256 bits for a case nothing reaches.
- **The properties proved soundness, not completeness.** They compared
the kernel with an expectation built from `rust_decimal`'s own result,
so a refusal of something exact could not fail them. Now each of add,
subtract, multiply and exact division is also `Some` exactly when the
rational result is a `Decimal`, decided from the rational alone. All
hold; nothing was refused that should not be.
- **The FX property reached steps of 0 to 3 places only** and accepted any
`None` past 10^23. It now covers steps of every scale and accepts a
`None` only at the two bounds the code documents.
- **Running totals reached 100 lines.** Now thousands, to within a factor
of two of the mantissa's end, and the first refusal is pinned (line
7,923 of the largest ten-place amount).
- **Three stale sentences**: `percent_of`'s product (exact or refused
since this unit, only the division rounds), the header of
`allocate.rs`, and this page's table.
The sampling is a test, not a proof: the 256-bit helpers have no Kani
harness of their own (see "Kani" above), and rest on the bridge
properties and the unit tests against `num_bigint`.
+38 -27
View File
@@ -73,12 +73,14 @@ split when the whole divides), the step is 1 (or 10 for the floor
harness), and the bounds are `whole` 0 to 1,000 (100 for the floor
harness). The laws are about the shape of the split, not the magnitude;
Lean proves them of the exact-share model at any size, and the bridge
checks the `Decimal` engine, whose ranking uses the rounded quotient.
checks the `Decimal` engine, whose ranking is the exact remainder (K-U10:
`whole × weight − part × total`, ties to the earlier part, the same
quantity `share_floor_with` returns).
| Harness | Law | Verification |
|---|---|---|
| `split_by_weights_sums` | 18 | the parts sum to the whole exactly; a shortfall is handed out; the largest weight takes more. 23.9 s (2 covers) |
| `split_by_weights_within_one_step` | 42 | each part is above `-total` and at most `total` from its share, scaled by the total; a part off its share and a part exactly one step above are reached. 14.4 s (2 covers) |
| `split_by_weights_within_one_step` | 42 | each part is above `-total` and below `total` from its share, scaled by the total, and a part whose share is exact takes no unit; a part off its share, and a unit handed out while the first part's share is exact, are reached. 22 s (2 covers) |
| `split_by_weights_no_part_exceeds` | 18 | no part is negative or above the whole. 12.4 s (1 cover) |
| `split_by_weights_first_absorbs` | 18 | the first part is its rounded share plus the shortfall; the sum is the whole; no part exceeds it. 2.3 s (1 cover) |
| `split_by_weights_last_absorbs` | 18 | the last part is the whole less the others; the sum is the whole; no part exceeds it. 4.3 s (1 cover) |
@@ -86,13 +88,16 @@ checks the `Decimal` engine, whose ranking uses the rounded quotient.
| `share_of_refuses_overflow` | 42 | `share_of(whole, 2, 1) = whole × 2` exactly when the product fits; a zero total and an overflowing product are `None`, never a panic. 0.47 s (2 covers) |
| `share_floor_is_the_exact_floor` | 42 | the part is a multiple of the step, one more step passes the share, and the remainder is exact below `step × total`; the correction down is reached. 5.1 s (2 covers) |
The upper bound of `split_by_weights_within_one_step` is inclusive on
the `i64` model: its division truncates, so a part that divides exactly
can still take a unit when another part's truncation left one over
(`whole = 5`, weights 2/3/5: the first's 1 becomes 2, exactly one step
above its truncated share). The `Decimal` quotient keeps the fraction, a
part with no remainder never takes a unit, and the bridge checks the
strict bound there.
The upper bound of `split_by_weights_within_one_step` was inclusive on
the `i64` model until K-U10: `i64`'s division truncates, the ranking read
the quotient, and a part that divided exactly could take the unit another
part's truncation left over (`whole = 5`, weights 2/3/5: the first's 1
became 2). The ranking is now the exact remainder, which no division
touches, so the split is 1, 2, 2 and the bound is strict on `i64` as on
`Decimal`. Kani said so itself: with the exact ranking the old cover "a
part exactly one step above its truncated share" could not be reached,
and `just prove` fails on a cover that cannot. The harness now asserts
the strict bound and that an exact share takes no unit.
`share_floor_is_the_exact_floor` needed `#[kani::unwind(4)]`: without a
bound on the correction loops, CBMC tried to unwind them without end and
@@ -143,10 +148,9 @@ harness 500.8 s, the run inside its 3600-second cap). Lean:
no-rounding split, at the scales the call sites produce.
- `decimal_edges_are_none_or_exact`: `Decimal::MAX`, a product past it, a
zero total, and scale 28: each `None` or exact, never a panic.
- `largest_remainder_ranks_like_the_exact_reference`: random distinct
weights over a non-terminating total (a factor of 3 or 7), against the
exact `i128` reference's ranking; exact ties are pinned below, not left
to fail this property.
- `largest_remainder_ranks_like_the_exact_reference`: random weights (ties
included, since K-U10) at whole units and at the cent, against the exact
`i128` reference's ranking.
- `the_absorbing_parts_keep_the_old_scale`: the strings, scale included,
for 4860 by 6/0.7/0.5 (first `4050`, as the old `split_first` gave) and
902 by 1/0.000001/0.000001 (first `902.00`); last absorbs against the
@@ -154,9 +158,10 @@ harness 500.8 s, the run inside its 3600-second cap). Lean:
- `split_into_matches_the_allocating_split`: the fixed-array
`split_by_weights_into` and `split_by_weights_with` agree, scale
included (the gate requires a bridge that calls the fixed-array form).
- `finding_ties_follow_the_rounded_quotient`: 20.00 split 4/1/1 over 6 is
13.33/3.34/3.33, and 20 whole is 13/4/3, not the exact tie's earlier
part (K-U10 decides).
- `ties_go_to_the_earlier_part`: 20.00 split 4/1/1 over 6 is
13.34/3.33/3.33, and 20 whole is 14/3/3 (K-U10: the ranking is exact;
the rounded quotient gave 13.33/3.34/3.33 and 13/4/3). A negative total
keeps the share's own order.
- `share_floor_refuses_past_the_correction_cap`: the review's
0.1113 × 5909471247797156928749568911.8 ÷ 0.11134381908633486049673
returns `None` promptly instead of hanging.
@@ -208,9 +213,9 @@ the `allocW_*` theorems were reused, not restated.
`split` at ~684 is not arithmetic (it reads `k1_detail` rows) and
needed no routing.
2. **The `i64` model's division truncates.** The Kani within-one-step
bound is therefore inclusive on `i64`; the `Decimal` bridge checks the
strict bound for the engine. This is a model statement, not an engine
change.
bound was therefore inclusive on `i64` while the ranking read the
quotient; since K-U10 ranks the exact remainder it is strict there
too (above).
3. **K-U10, Decimal's edges.** At `Decimal`'s 96-bit mantissa edge,
`checked_div`'s rounding can move a share across a step, and
`checked_mul`'s rounding hides it from `share_floor_with`'s correction.
@@ -249,11 +254,17 @@ the `allocW_*` theorems were reused, not restated.
checked arithmetic), and `the_absorbing_parts_keep_the_old_scale`
compares strings. `LastAbsorbs` was already the old `plug_last` and the
no-places conventions split, and the same property checks it.
7. **Ties follow the rounded quotient.** `split_by_weights_into` ranks the
rounded quotients' remainders, not exact rationals, so an exact tie goes
where the 28th digit sends it, not to the earlier part:
20.00 split 4/1/1 over 6 is `13.33, 3.34, 3.33` (exact ranking would be
`13.34, 3.33, 3.33`), and 20 whole is `13, 4, 3` (exact would be
`14, 3, 3`). The pre-U3 sites did the same. Pinned by
`finding_ties_follow_the_rounded_quotient`; the owner decides the exact
ranking in K-U10, and the ranking is unchanged here.
7. **Ties go to the earlier part, exactly (K-U10).** The first version of
`split_by_weights_into` (and the pre-U3 call sites) ranked the leftover
units by the rounded quotients' remainders, so an exact tie went where
the quotient's 28th digit sent it: 20.00 split 4/1/1 over 6 was
`13.33, 3.34, 3.33` and 20 whole was `13, 4, 3`. It now ranks the exact
integer remainder `whole × weight − part × total` (the quantity
`share_floor_with` returns; the sign flipped for a negative total), so
a tie goes to the earlier part, as `apportion`'s docs and bookspec's
`Apportion.lean` (`remW`, `allocNat`: ties to the earlier member) say:
`13.34, 3.33, 3.33` and `14, 3, 3`. Pinned by
`ties_go_to_the_earlier_part`; `tests/kernel_bridge/ties.rs` keeps the
old ranking as a reference and measures what the change moves. A
recomputed past report can differ from what it showed before by a cent
between parties (a posted entry never moves).
+1 -1
View File
@@ -19,7 +19,7 @@ only listing was `opencode` / `opencode/muse-ember-1.0`). The owner's rule
(2026-11-09): keep checking Muse Code for it, and use it from the day it is
listed there, not through OpenCode. Check with `orchestrator_capabilities`
(`search: "ember"`) before each batch of delegations; until it is listed,
run-only tasks go to the scout row. Last checked 2026-11-09 16:40 MST: not
run-only tasks go to the scout row. Last checked 2026-11-09 21:05 MST: not
listed.
Rules that do not change with the data: set provider, model and effort on
+16 -3
View File
@@ -519,9 +519,20 @@ INVARIANTS:
rule that posted an entry (its true-up, statement 6; the close
journals its rule and whether it posted), a member's running total
MUST be under one minor unit from its exact share, so a drift of a
unit or more is a finding. Before that true-up the count may still
carry the rounding of closes made under the older rules, so only a
drift beyond one unit is. Closes under the older rules are not read.
unit or more is a finding. The unit is the allocation's own
(`Currency::allocation_unit`, on `allocation_places`: a whole yen
for JPY, the finest a line carries for a code with no minor unit),
never a cent taken separately. Before that true-up the count may
still carry the rounding of closes made under the older rules, so
only a drift beyond B(n) is a finding, where B(n) = max(one unit,
(n-1) half-units) for n members: a unit with three or fewer
members, 1.5 units with four, 2 units with five. B(n) is DERIVED:
BS-partner-1 statement 6 states the per-member facts it comes from
(a last-absorbs close rounded each member but the last to within
half a unit, and the last absorbed up to half a unit for each of
the others; under a unit for each run break and each per-close
close), not the bound itself. Closes under the older rules are not
read.
SCENARIOS:
1. The same books audited twice through one day: one run, one
workpaper; the second call files and journals nothing.
@@ -552,6 +563,8 @@ journal feature `audits`.
(`the_cash_flow_check_says_what_it_found`,
`control_accounts_report_differences_unattached_lines_and_overpaid_documents`,
`a_close_split_drifts_by_the_regime_it_was_made_under`,
`a_jpy_close_is_checked_at_the_allocations_unit`,
`a_legacy_last_absorbs_close_drifts_by_member_count_before_its_true_up`,
`a_count_is_trued_up_by_the_first_cumulative_close_that_posts`,
`a_reversal_without_its_own_receipt_is_info_and_only_when_the_policy_would_cover_it`,
`the_bar_setting_parses_what_it_names_and_refuses_the_rest`,
+9 -1
View File
@@ -21,12 +21,15 @@ promise.
| 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 |
| Model coverage | every public command on `Ledger` is named on `docs/command-steps.md` with the step of the Lean model it is, and the commands that are no step are a pinned list (3) | `tests/command_steps.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`, bookspec `gnucash/oracle/` | `just oracle` | ~2 min | weekly |
| 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 <target> <secs>` | 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 |
| Dependencies | no crate in the lock file with a known vulnerability (RustSec) or yanked; none under a licence that does not fit MIT OR Apache-2.0; none from a source `deny.toml` does not name; none of our own unmaintained (4) | `deny.toml`, each exception with its reason and date | `just deny` (in `just check`, the lint part) | seconds, needs the network | every change, and weekly (`scheduled.yml`), since an advisory is published when it is, not when we push. First run, 2026-11-09: 23 advisories; closed by upgrades (quick-xml, rusqlite, rust_xlsxwriter, rmcp, rustls, tokio, zstd, pulldown-cmark) but two, lived with in `deny.toml` |
| Notices | every crate the program links and every font it embeds, with the licence text each asks to travel with (1, the licence itself) | `THIRD-PARTY-NOTICES.txt`, written by cargo-about from `ledger-cli`'s manifest, by `scripts/notices-packaged.py` (the crates' own licence files, where cargo-about could only give a licence's standard text with a placeholder for the copyright line) and from the licence files beside the fonts | `just notices`; `just notices-check` (in `just check`, the lint part) | ~2 min (12 CPU-minutes: it reads every crate's files for licence text) | every change that touches a dependency or a font. `just notices` writes the file; `just notices-check` fails when a dependency changed and the file was not regenerated, and the fix is `just notices` and committing the result |
| Benchmarks | a baseline (6) | `ledger-core/benches/books.rs`, `ledger-store/benches/store.rs` | `just bench` | ~2 min | none (no budget, by decision) |
| Coverage | the code lines, regions and branches the suites execute (6) | `ledger-core` and `ledger-store` library sources (`src/proofs.rs` is Kani-only and excluded, as are test and bench files) | `just coverage` (HTML and a per-file table in `target/coverage/`), `just coverage-check` (docs/coverage-floor.md's floor, 0.5 pp tolerance) | ~1–3 h (nightly branch coverage) | weekly (`scheduled.yml`) |
| Mutation | can the tests fail? | `ledger-core` (2026-10-13: 1,011 caught + 13 timeouts of 1,024 viable, 0 missed) | `just mutants` | ~3 h | weekly |
@@ -37,7 +40,12 @@ promise.
| Mutation (MCP) | can the tests fail? | `ledger-mcp` (2026-10-14: from 197 caught + 5 timeouts of 328 viable (62%) to 314 caught + 2 timeouts of 331; of its 15 survivors, five then killed by targeted tests (the settings file beside the books, year earnings with an open period and with last year's partial close, year 1, a failed flush), one dead guard removed (`profit_and_loss_by_class` skipping placeholders, which never take postings), nine equivalent: `money` rescaling an amount already at two places, the lock wait's deadline instant, `year_earnings` starting the day the year starts either way, the bank import's rehearsal sides (a line's side can't make a draft refuse) and its zero-amount side (zero rows are dropped by the parser), a disposal's zero gain adding zero, and the CPA package index summing debits instead of credits (entries balance)) | `just mutants-mcp` | ~1 h | weekly |
| Mutation (GUI) | can the tests fail? | `ledger-gui` view model and formatting (2026-10-14: 140 caught of 176 viable on the full run, then 92 of 99 on a targeted rerun of the money paths after new tests; of its 7 survivors, one then killed by a test (burn over exactly one month, confirmed by a rerun of `compute_kpis`'s 48 mutants), two dead arms removed (`parties`' bill arms: the ledger tags bill entries with their vendor, which wins), four equivalent: an entry's debits vs its credits (they balance), the three-month burn boundary (both paths give 3), burn over zero covered months (only when the first entry is after the window, which then holds no loss), and `compact`'s sign test at zero (zero prints "$0" unsigned either way)) | retired 2026-10-18 (owner: it crushed the machine; for the viewer, test its two musts directly: it never writes the books, `tests/read_only.rs`, and every figure it shows is the engine's, `tests/view_model.rs`) | | never |
CI: `.github/workflows/check.yml` runs `just check` on every push;
CI: `.github/workflows/check.yml` runs `just check` on every push, as
five parts on five runners side by side (the justfile's `check_shards`:
`lint`, `gui-unit`, `gui-tests`, `cli`, `rest`; on one runner the job took
72 minutes on 2026-11-09). `just check` here runs the same five in turn,
`just check-shard <part>` one of them, and the lint part fails if the
workflow's list is not the justfile's;
`two-user.yml` the self-host deployment's two-account check (P9a);
`scheduled.yml` runs the proofs, the oracle, the coverage report and floor,
and the fuzz targets weekly. Mutation ran there in shards until 2026-10-29 (`just mutants-mcp 3/16` runs the fourth of sixteen; GitHub stops a job at six hours), and is now local only (D-59). Test timeouts are three times each run's own baseline, never under the recipe's floor, so a slower runner doesn't report false timeouts. The viewer has no mutation job. Development mutation runs are paused until the P12 max-testing pass (D-33, 2026-10-20): each unit records its targets in a **For P12** paragraph instead. Mutation testing is a local run, not a CI job (the owner, 2026-10-29, D-59): the weekly shards were removed from `scheduled.yml`, and the "weekly" in the mutation rows above is history (the 2026-10-26 run: real survivors and timeouts in every crate, the debt P12 clears).
+78 -29
View File
@@ -188,6 +188,13 @@ Each step carries the checks the engine makes before it mutates. These
theorems hold in **every state reachable from empty books, by any
sequence of commands, of any length**:
"Commands" there are the model's steps. Which command of the engine is
which step is `docs/command-steps.md`: 119 commands, of which one
(`renumber_account`) is no step, and 17 are the doors a journal is
replayed through, four of which do not make a check the model's step
requires. That page says what the theorems below do and do not cover for
each, and `tests/command_steps.rs` fails when a command has no row.
11. **The invariant holds**: chart codes are unique, every posted entry is
acceptable and on known accounts, and no draft is dated in a closed
period. (That last one is why the store can journal a post before
@@ -885,7 +892,7 @@ replay rules.
`largest_remainder_ranks_like_the_exact_reference`,
`the_absorbing_parts_keep_the_old_scale`,
`split_into_matches_the_allocating_split`,
`finding_ties_follow_the_rounded_quotient`,
`ties_go_to_the_earlier_part`,
`share_floor_refuses_past_the_correction_cap`,
`finding_the_quotients_rounding_can_cross_a_step`
- `split_by_weights_with` is an `EXCEPTIONS` wrapper (it allocates two
@@ -981,20 +988,22 @@ kernel. What the proofs and their reviews found, beyond the tidying:
decimal places, before computing and never on replay (D-75,
`ValueOutOfRange`); `past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses`
pins it.
- **The 96-bit half of that precondition is not enforced.** Ten places
- **The 96-bit half of that precondition was not enforced.** Ten places
each still allow a product of twenty places past about 7.9e8, which
needs more than 96 bits: `1050000010.0000000001 × 9.9999999999` is
`10500000099.89499999999999999999` exactly (10500000099.89 to the cent)
but `Decimal` holds 10500000099.895 and the engine books
10500000099.90. `the_mantissa_edge_is_outside_the_precondition_and_pinned`
pins it; refusing it is the owner's decision (K-U10).
- **`Decimal`'s addition is not exact in the top unit of `MAX`.**
but `Decimal` held 10500000099.895 and the engine booked
10500000099.90. Closed by K-U10: the kernel holds the product in 256
bits and rounds it once, so the line books 10500000099.89
(`the_mantissa_edge_books_the_exact_products_cent`). A line already
posted is not recomputed: replay reads the booked amount.
- **`Decimal`'s addition was not exact in the top unit of `MAX`.**
`Decimal::MAX.checked_add(0.4)` is `Some(MAX)`: `rust_decimal` rounds
sub-unit dust when the sum needs a 97th bit (`MAX + 0.5` is `None`), so
the kernel's "exact or `None`" contract fails there for every function
the kernel's "exact or `None`" contract failed there for every function
that adds, not only `total`. No posted line reaches it (the line cap is
10^15); `finding_decimal_add_rounds_dust_at_the_edge` and
`decimal_edge_table` pin it, and it is K-U10's to settle.
10^15). Closed by K-U10: the kernel's sum is the exact one or `None`
(`a_sum_past_exact_arithmetic_is_refused`, `decimal_edge_table`).
- **A share's quotient can cross a step, and its product's rounding can
hide it.** At `Decimal`'s 96-bit mantissa edge, `checked_div`'s rounding
can move a share across a step and `checked_mul`'s rounding hides that
@@ -1007,7 +1016,12 @@ kernel. What the proofs and their reviews found, beyond the tidying:
division carries the same edge: `MAX / 2` rounds before the step, so the
part is not within half a step of the exact quotient (`the_edges` pins
it); the engine's callers refuse totals of `EXACT_LIMIT` (10^26) or
more, so no schedule reaches it. Both are K-U10 items.
more, so no schedule reaches it. K-U10 settled the products: a product
that is the amount itself (`checked_mul`) is exact or refused, so the
square above is `None`; a share's product keeps rounding, under its own
name (`checked_mul_rounded`), since a share by a percent of 27 places
is a rounded figure by construction and is divided next. The division
(`checked_div`) is the engine's rounding division and is unchanged.
- **One panic became a refusal.** `k1::share_property`'s old
`apportion(...).expect(...)` would panic at that edge; the kernel
returns `None` and the site reports `TooLargeToCompute`.
@@ -1024,13 +1038,33 @@ kernel. What the proofs and their reviews found, beyond the tidying:
337.50`, the kernel `4050.00, …`), and that scale reaches `Part.amount`.
The kernel computes the old expression, pinned by
`the_absorbing_parts_keep_the_old_scale`.
- **Ties follow the rounded quotient.** The split ranks the rounded
quotients' remainders, not exact rationals, so an exact tie goes where
the 28th digit sends it: 20.00 split 4/1/1 over 6 is `13.33, 3.34,
3.33` (exact ranking `13.34, 3.33, 3.33`), and 20 whole is `13, 4, 3`
(exact `14, 3, 3`). The pre-sweep sites did the same;
`finding_ties_follow_the_rounded_quotient` pins it, and the owner decides
the exact ranking in K-U10, unchanged here.
- **Ties go to the earlier part, exactly (K-U10).** The split ranked the
rounded quotients' remainders, so an exact tie went where the 28th digit
sent it: 20.00 split 4/1/1 over 6 was `13.33, 3.34, 3.33` and 20 whole
was `13, 4, 3`. The pre-sweep sites did the same, and K-U3 kept it and
pinned it. It now ranks the exact remainder `whole x weight - part x
total` (as `share_floor_with` does), so a tie goes to the earlier part:
`13.34, 3.33, 3.33` and `14, 3, 3`, which is what bookspec's
`Apportion.lean` models (`remW`, ties to the earlier member).
`ties_go_to_the_earlier_part` pins it, and `tests/kernel_bridge/ties.rs`
measures what it moves against the old ranking: nothing between two
parts or by equal weights, at most a cent a part elsewhere. The owner
decided for the exact ranking (D-76, 2026-11-09). Kani then found the
same on whole numbers: with the exact ranking a part whose share is
exact can no longer take a leftover unit (5 by 2/3/5 is 1, 2, 2, where
the truncated quotients gave 2, 1, 2), so a cover in
`split_by_weights_within_one_step` could not be reached; the harness
now asserts the strict bound and that an exact share takes no unit.
- **`Decimal`'s sums and products are exact or refused (K-U10).**
`rust_decimal` rounds a sum or product it cannot hold and returns
`Some`; the kernel's `Amount for Decimal` now checks each result in 256
bits and refuses a rounded one. `checked_div_exact` accepted a rounded
quotient that multiplied back (`10 / 3`), found in review of the unit;
it refuses them. An independent review then found the bridge
properties proved a returned figure exact, not that an exact figure is
never refused; they now prove both, from the rational alone. One
refusal remains by design: a product that is not exact, rounded to a
step of 27 or 28 places. `docs/proofs/k-u10.md` has the account.
- **The sweep changed no posted figure.** Every golden and existing test
passed unchanged. `round_places` reproduces `round_dp_with_strategy` to
the character except a negative-zero input (which no call site can
@@ -1085,16 +1119,19 @@ Be precise about the claims:
checked; the sweep's bridge properties compare the engine to an
independent exact `i128` reference for every step, count and amount the
`Decimal` type can hold.
- **The sweep's `Decimal` edges are pinned, not refused.** `checked_mul`
rounds at 96 bits (`fx`'s `the_mantissa_edge_is_outside_the_precondition_and_pinned`
and `123456789.0123456789²`), `checked_div` rounds at 28 significant
digits (K-U3's `finding_the_quotients_rounding_can_cross_a_step`, K-U5's
`the_edges` at `Decimal::MAX / 2`), and `checked_add` rounds sub-unit
dust in the top unit of `MAX` (K-U4's
`finding_decimal_add_rounds_dust_at_the_edge`). None is reachable by a
posted line (the line cap is 10^15, and schedules refuse totals of
`EXACT_LIMIT` or more), so the laws hold at the engine's inputs; whether
the kernel should refuse these shapes outright is K-U10's decision.
- **The sweep's `Decimal` sums and products are refused at their edges;
its divisions are pinned.** Since K-U10 the kernel's `checked_add`,
`checked_sub` and `checked_mul` for `Decimal` are exact or `None`
(`tests/kernel_bridge/decimal_exact.rs`: `Some` exactly when the exact
result is a `Decimal`), and a foreign amount at a rate is rounded once
from the exact product. Two operations round, each by name:
`checked_div` at 28 significant digits (K-U3's
`finding_the_quotients_rounding_can_cross_a_step`, K-U5's `the_edges`
at `Decimal::MAX / 2`) and a share's `checked_mul_rounded`. Neither
edge is reachable by a posted line (the line cap is 10^15, and
schedules refuse totals of `EXACT_LIMIT` or more), so the laws hold at
the engine's inputs. Not proved by Kani: the 256-bit helpers, which
rest on the bridge properties and unit tests against `num_bigint`.
- **The FX overflow harness proves two concrete cases, not every
overflow.** `fx_booked_refuses_overflow` proves `i64::MAX × 2` and
`100 × i64::MAX` (step 1) are `None`, and that a non-positive rate is
@@ -1240,7 +1277,9 @@ just prove-all # both
```
`just prove` runs every Kani harness but the justfile's `kani_slow`, in
parallel (`-j $(nproc)`), the whole run under a 30-minute timeout; fetches
parallel (`-j $(nproc)`), each harness under a 15-minute cap
(`KANI_HARNESS_CAP`, seconds) and the whole run under a 30-minute one
(`KANI_FAST_CAP`, seconds); fetches
and builds bookspec's Lean proofs (seconds; the git dependency is pinned in
`verify/lean/lakefile.toml` and its manifest); and fails if any theorem
depends on anything beyond Lean's standard axioms (`propext`,
@@ -1257,6 +1296,16 @@ 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.
**A run that is cut off says what it left (2026-11-09).** Until then the
fast set had the one 30-minute cap and nothing else: on a machine busy
with other builds `timeout` ended it with exit 124, and the output named
neither a failed harness nor an unfinished one, so "red" could not be
told from "slow". Now a run that does not verify every harness lists
each one that failed, each that ran past its own cap, and each that
never finished, and a cut-off run says so and how to give it longer:
`KANI_FAST_CAP=7200 just prove`. The caps are not the proof: raising one
changes how long a harness may take, never what it must show.
**Why the split (2026-10-21, the P3 surface review).** With all of P3 the
suite is 55 harnesses. One `just prove` at four jobs (a CI runner's
cores), on the development laptop under heavy load from other work (a
@@ -1380,7 +1429,7 @@ included):
| `fx_booked_positive_for_positive` | 41 | prove | 3.2 |
| `fx_booked_refuses_overflow` | 41 | prove | 2.6 |
| `split_by_weights_sums` | 18 | prove | 23.9 |
| `split_by_weights_within_one_step` | 42 | prove | 14.4 |
| `split_by_weights_within_one_step` | 42 | prove | 22 |
| `split_by_weights_no_part_exceeds` | 18 | prove | 12.4 |
| `split_by_weights_first_absorbs` | 18 | prove | 2.3 |
| `split_by_weights_last_absorbs` | 18 | prove | 4.3 |
+49 -63
View File
@@ -30,18 +30,6 @@ dependencies = [
"zeroize",
]
[[package]]
name = "ahash"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
dependencies = [
"cfg-if",
"once_cell",
"version_check",
"zerocopy",
]
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -734,9 +722,9 @@ dependencies = [
[[package]]
name = "ctutils"
version = "0.4.3"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574"
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
dependencies = [
"cmov",
]
@@ -1265,7 +1253,7 @@ checksum = "d99fc21d493812643aae86d53b7bbd02f376434a90317e8a790bc209fdd6605e"
dependencies = [
"bytemuck",
"foldhash",
"hashbrown 0.17.1",
"hashbrown",
"log",
"peniko",
"png",
@@ -1282,7 +1270,7 @@ checksum = "9f1218dedd5348c1b166ec3b8b3cbca49d2f527bd43b3fa072ea5123c523ed3f"
dependencies = [
"bytemuck",
"foldhash",
"hashbrown 0.17.1",
"hashbrown",
"log",
"peniko",
"png",
@@ -1311,15 +1299,6 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
@@ -1331,11 +1310,11 @@ dependencies = [
[[package]]
name = "hashlink"
version = "0.9.1"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb"
dependencies = [
"hashbrown 0.14.5",
"hashbrown",
]
[[package]]
@@ -1945,7 +1924,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown 0.17.1",
"hashbrown",
"rayon",
"serde",
"serde_core",
@@ -2211,7 +2190,7 @@ dependencies = [
"ledger-vault",
"rust_decimal",
"serde_json",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -2221,9 +2200,9 @@ dependencies = [
"hayro 0.8.0",
"hayro-interpret 0.8.0",
"kurbo",
"quick-xml 0.38.4",
"quick-xml 0.42.0",
"thiserror",
"zip 9.1.3",
"zip",
]
[[package]]
@@ -2301,9 +2280,9 @@ dependencies = [
[[package]]
name = "libsqlite3-sys"
version = "0.30.1"
version = "0.39.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3"
dependencies = [
"cc",
"pkg-config",
@@ -3131,9 +3110,9 @@ dependencies = [
[[package]]
name = "rmcp"
version = "3.8.0"
version = "3.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8be15815186873ea063bf005011d16c356804973489e40c39116ae3a2878d1f"
checksum = "d24a7e92f4bcaa36b97fa93c4fa7ca8f3e669eced949345b3462dba333c7f909"
dependencies = [
"async-trait",
"base64 0.23.1",
@@ -3152,6 +3131,7 @@ dependencies = [
"schemars",
"serde",
"serde_json",
"sha2 0.11.1",
"sse-stream",
"thiserror",
"tokio",
@@ -3164,9 +3144,9 @@ dependencies = [
[[package]]
name = "rmcp-macros"
version = "3.8.0"
version = "3.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b0748e054a5f5598b3213cf72099ae6b2745ba4d996c59ccf455150a7dbb839"
checksum = "b3140f24a766f80f9ec1607bde85680959a69b83d46fa9ce87dadab7e67ab029"
dependencies = [
"darling",
"proc-macro2",
@@ -3197,10 +3177,19 @@ dependencies = [
]
[[package]]
name = "rusqlite"
version = "0.32.1"
name = "rsqlite-vfs"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7"
dependencies = [
"thiserror",
]
[[package]]
name = "rusqlite"
version = "0.41.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594"
dependencies = [
"bitflags 2.13.2",
"fallible-iterator",
@@ -3208,6 +3197,7 @@ dependencies = [
"hashlink",
"libsqlite3-sys",
"smallvec",
"sqlite-wasm-rs",
]
[[package]]
@@ -3229,11 +3219,11 @@ dependencies = [
[[package]]
name = "rust_xlsxwriter"
version = "0.90.2"
version = "0.102.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2be778223b36bb449b2ef2df4856ced2d311680818a7310db5c5dc370170f935"
checksum = "6ca3d0e879a578c1313c2800ab0c6c029d38eed18098675e50341a30d32372ed"
dependencies = [
"zip 4.6.1",
"zip",
]
[[package]]
@@ -3577,6 +3567,16 @@ version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
[[package]]
name = "sqlite-wasm-rs"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36bd8e29bf08189a005b2df1df99823aa0861cabe9044e5f31ed54ca292ee618"
dependencies = [
"cc",
"rsqlite-vfs",
]
[[package]]
name = "sse-stream"
version = "0.2.6"
@@ -3740,7 +3740,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"getrandom 0.3.4",
"once_cell",
"rustix",
"windows-sys",
@@ -4622,7 +4622,7 @@ dependencies = [
"bytemuck",
"fearless_simd 0.4.1",
"guillotiere",
"hashbrown 0.17.1",
"hashbrown",
"log",
"peniko",
"png",
@@ -4639,7 +4639,7 @@ dependencies = [
"bytemuck",
"fearless_simd 0.4.1",
"guillotiere",
"hashbrown 0.17.1",
"hashbrown",
"log",
"peniko",
"png",
@@ -4671,7 +4671,7 @@ checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0"
dependencies = [
"bytemuck",
"glifo 0.1.1",
"hashbrown 0.17.1",
"hashbrown",
"png",
"vello_common 0.0.8",
]
@@ -4684,7 +4684,7 @@ checksum = "ed1fec424fbba6acf6cbc78bb526447eb77590d95f40419d598870fe37535212"
dependencies = [
"bytemuck",
"glifo 0.4.0",
"hashbrown 0.17.1",
"hashbrown",
"png",
"vello_common 0.3.0",
]
@@ -5075,20 +5075,6 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "zip"
version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
dependencies = [
"arbitrary",
"crc32fast",
"flate2",
"indexmap",
"memchr",
"zopfli",
]
[[package]]
name = "zip"
version = "9.1.3"
+110 -8
View File
@@ -11,14 +11,86 @@ netlify := "npm_config_ignore_scripts=true npx --yes netlify-cli@27"
default:
@just --list
# The parts `check` is cut into. A laptop runs them one after another
# (`just check`); CI runs each on a runner of its own, side by side
# (.github/workflows/check.yml), because one runner took 72 minutes for the
# lot on 2026-11-09 (56 of them tests, one binary at a time). There is one
# definition, `check-shard`, so the two cannot drift: what CI checks is
# what `just check` checks. `rest` is every crate not named by another
# part, so a new crate is tested without anyone adding it to a list.
check_shards := "lint gui-unit gui-tests cli rest"
# Everything CI should check: format, clippy and rustdoc (zero warnings), tests
check: sweep-test-tmp
cargo fmt --all --check
cargo clippy --workspace --all-targets -- -D warnings
RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --quiet
cargo test --workspace
@just server-only
@just sweep-test-tmp
#!/usr/bin/env bash
set -euo pipefail
for shard in {{check_shards}}; do just check-shard "$shard"; done
just sweep-test-tmp
# One part of `check` (one of check_shards)
check-shard shard:
#!/usr/bin/env bash
set -euo pipefail
case "{{shard}}" in
lint)
cargo fmt --all --check
cargo clippy --workspace --all-targets -- -D warnings
RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --quiet
just server-only
just check-shards-agree
just deny
just notices-check
;;
# The viewer's tests are half of the suite's time, in two halves
# of their own: its unit tests, and its integration tests. Between
# them they are every target `cargo test -p ledger-gui` runs: the
# library, the executable, each file under tests/, the doc tests.
gui-unit)
cargo test -p ledger-gui --lib --bins
cargo test -p ledger-gui --doc
;;
gui-tests) cargo test -p ledger-gui --test '*' ;;
cli) cargo test -p ledger-cli ;;
rest) cargo test --workspace --exclude ledger-gui --exclude ledger-cli ;;
*)
echo "check-shard: no part named '{{shard}}' (the parts: {{check_shards}})" >&2
exit 1
;;
esac
# What every dependency must be (deny.toml): free of known vulnerabilities
# (the RustSec database, fetched now), not yanked, under a licence that
# fits MIT OR Apache-2.0, and from crates.io or the bookspec repository.
# The first run (2026-11-09) found 23 advisories in the lock file. A new
# advisory turns this red on an unchanged tree: that is its job, and the
# weekly run makes it within a week of the advisory, push or no push.
deny:
cargo deny check
# The third-party notices every licence asks to travel with
# (THIRD-PARTY-NOTICES.txt): each crate the `wanderbooks` binary links and
# its licence text, then the fonts embedded, each with its licence. Writes
# the file; commit it.
notices:
scripts/notices.sh
# Whether THIRD-PARTY-NOTICES.txt still matches the dependencies: a crate
# added, removed or upgraded without regenerating it fails (`just notices`).
notices-check:
scripts/notices.sh --check
# CI's list of parts is this file's: a part CI never runs is a check
# nobody makes, and a part only CI names fails there, not here.
check-shards-agree:
#!/usr/bin/env bash
set -euo pipefail
ci=$(sed -n 's/^ *shard: \[\(.*\)\] *$/\1/p' .github/workflows/check.yml | tr -d ' ' | tr ',' '\n' | sort)
here=$(tr ' ' '\n' <<<"{{check_shards}}" | sort)
if [ -z "$ci" ] || [ "$ci" != "$here" ]; then
echo "check.yml runs [$(echo $ci)], the justfile's check_shards are [$(echo $here)]" >&2
exit 1
fi
echo "check: CI runs every part ($(echo $here))"
# The server-only build (plan D-22, for another machine) builds, passes
# clippy and the one executable's own tests, and links no window libraries.
@@ -164,8 +236,38 @@ _kani set:
if [ "{{set}}" = fast ]; then
args=()
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")"
# Two caps, both in seconds. KANI_HARNESS_CAP is one harness's:
# Kani stops that harness and carries on with the rest.
# KANI_FAST_CAP is the whole set's: on a machine busy with other
# builds the set needs more than its 30 minutes, and until
# 2026-11-09 it was cut off there with exit 124 and nothing named.
# Either way the harnesses that failed and the ones that never
# finished are listed below.
status=0
timeout "${KANI_FAST_CAP:-1800}" cargo kani -j "$(nproc)" --output-format terse --exact \
-Z unstable-options --harness-timeout "${KANI_HARNESS_CAP:-900}s" "${args[@]}" |
tee "$logs/fast.log" || status=$?
if [ "$status" != 0 ] || ! checked "$logs/fast.log" "$(wc -l <<<"$names")"; then
# With -j Kani prints a harness's whole block when it ends:
# "Checking harness <name>..." down to its "VERIFICATION:-" line.
awk -v cap="${KANI_HARNESS_CAP:-900}" '
NR == FNR { asked[$1] = 1; next }
match($0, /Checking harness [^ ]+\.\.\./) { h = substr($0, RSTART + 17, RLENGTH - 20); next }
/VERIFICATION:- / && h != "" { ended[h] = 1; if ($0 !~ /VERIFICATION:- SUCCESSFUL/) failed[h] = 1; last = h; h = ""; next }
/CBMC timed out/ && last != "" { timed[last] = 1 }
END {
for (n in asked) {
if (n in timed) print "Kani: ran past its " cap " s (KANI_HARNESS_CAP): " n
else if (n in failed) print "Kani: FAILED: " n
else if (!(n in ended)) print "Kani: not finished: " n
}
}' <(printf '%s\n' $names) "$logs/fast.log" | sort >&2
if [ "$status" = 124 ]; then
echo "Kani: the fast set was cut off at ${KANI_FAST_CAP:-1800} s; on a busy machine give it longer (KANI_FAST_CAP=7200 just prove)" >&2
fi
echo "Kani (fast): not verified (exit $status), see $logs/fast.log" >&2
exit 1
fi
else
cargo kani --only-codegen --output-format terse
failed=0
+7
View File
@@ -26,6 +26,13 @@ node = "26"
# `just coverage`: line and branch coverage of the core and the store
# (docs/coverage-floor.md).
"cargo:cargo-llvm-cov" = "0.9.1"
# `just deny` (in `just check`): no dependency with a known vulnerability,
# none yanked, none under a licence that does not fit MIT OR Apache-2.0,
# none from a source nobody named (deny.toml).
cargo-deny = "0.20.2"
# `just notices`: cargo-about reads every crate the program links and the
# licence it carries, to write THIRD-PARTY-NOTICES.txt.
"cargo:cargo-about" = { version = "0.9.3", features = ["cli"] }
# A compile cache shared by every jj workspace's target dir: point
# cargo's build.rustc-wrapper at it (~/.cargo/config.toml).
sccache = "0.18.0"
+190
View File
@@ -0,0 +1,190 @@
# Triage, 2026-11-09
What a full evaluation of the project found, in the order it should be
worked. Each item says what is wrong, how it is known, what closes it and
who does it. "Mine" is the orchestrating session; "worker" is a delegated
model (`docs/routing.md`); "owner" is Steve.
The engine itself is in good shape: 36 parity items done, more than 188
Lean theorems, 97 Kani harnesses, every rule cited by its bookspec id,
95.5% of ledger-core's lines covered. Nothing below is a wrong number in the live
books. The gaps are in what the gates do not see.
## P0: broken now
1. **`portable-windows` was red for four pushes and nobody looked.** Only
`check` was being read. Cause: a test named a Unix path for
`backup.folder`. Fixed in 5cad55023, pushed with 0ef1ef2c2, and that
commit's Windows gate read green on 2026-11-09 (all four gates green).
Closed. The rule since: read all four gates after every batch push.
## P1: a promise of the manual that is not kept, or a correctness risk
1. **The kernel rule is not met and nothing enforced it.** Bar item 1
says money arithmetic lives in `kernel/` and nowhere else.
`scripts/raw-decimal-arith.sh` (95ae7717d) asks the compiler, and at
8ad55e82a it lists **210 places in ledger-core** that add, subtract,
multiply, negate or sum a `Decimal` outside the kernel: raw operators
that panic on overflow, and `checked_*` calls that reach rust_decimal's
methods (which round silently past 28 digits) instead of the kernel's.
The outer crates, after K-U9: **ledger-gui 123** (the viewer computes
averages, shares and totals of its own in `books.rs` and the pages;
137 before K-U9), ledger-import 18 (was 22), ledger-mcp 19,
ledger-package 13, ledger-store 8, ledger-config 2, and none in
ledger-cli, ledger-host, ledger-reader and ledger-vault. Closes with:
- K-U11a, ledger-core: every site routed through the kernel (branch
`k-u11a`; a script driven by the compiler's own spans, so no site is
hand-copied). 199 of the 210 are done and committed there; the last
11 waited for K-U10a's exact operations, now on main. Mine.
- K-U12, the outer crates. Worker or script, decided on the counts.
- The script in `just check` at zero, so the count cannot rise again.
2. **Decimal sums and products rounded silently.** Done (K-U10a, merged
e632855f1). `Decimal::checked_add` and `checked_mul` return a rounded
answer when the exact one needs more than 28 digits; the kernel's
`Amount for Decimal` now gives the exact answer or refuses, and a
foreign amount is rounded once from a 256-bit product. Within the line
cap no sum moves and no golden moved. One figure a new line can book
does move: 1050000010.0000000001 at 9.9999999999 books 10500000099.89,
the exact product's cent, where the double rounding booked .90 (posted
lines are not recomputed). What the worker's own run missed and the
checks found: `checked_div_exact` accepted a rounded quotient (10 / 3);
the independent review's six findings, all reproduced (a refusal at
steps of 27 and 28 places the docs did not state, four gaps in what
the properties covered, stale sentences). Not proved: the 256-bit
helpers have no Kani harness (checked against exact rationals by
property instead; `docs/proofs/k-u10.md` says why).
3. **An exact tie between shares went where Decimal's 28th digit sent
it.** Done (K-U10b, merged 5e9591725). The docs and bookspec's Lean
say a tie goes to the earlier part; the engine ranked rounded
remainders, so 20.00 by 4/1/1 came out 13.33 / 3.34 / 3.33. The owner
decided on 2026-11-09 (D-76): exact ranking from now on (13.34 / 3.33
/ 3.33). No golden moved; of the engine's splits only the K-1
worksheet's share of contributed property can differ, by a cent a
part. Kani then found the same rule on whole numbers: a part whose
share is exact never takes a leftover unit (5 by 2/3/5 is 1, 2, 2),
and the harness now asserts it with the strict bound. The worker had
not run Kani; its cover would have failed `just prove`.
4. **The audit's close check** (V-D3, merged abafa94a5, 09a8707e2): it
checked a JPY close at a cent, and its pre-true-up bound ignored the
member count. Left open: the bound covers one legacy close, not
several in one set of books.
5. **Rounding for display was done outside the kernel** in ledger-gui,
ledger-import and ledger-package, each with its own copy, and the
viewer's percentages were f64. Done (K-U9, merged 0e9990f11): one
`round_display` through the kernel, percentages by the kernel's
`percent_of`. A change against a zero or negative base now shows no
percentage.
6. **Recorded regression seeds that no test read.** Fixed (129a90dcf): the
failures are replayed again, and a seed file no test reads fails the
build.
7. **`overflow-checks` was off in the release profile.** An integer
overflow in the shipped program wrapped silently where the test build
would panic. Fixed (724edc61f), checked with a release build.
8. **The live books are not on `documents_v2` or `schedule_minor_unit`.**
Two format upgrades the code supports and the live file has not taken.
Owner (exact commands when he is ready).
9. **P12 step 2 has never run on today's code**: the overnight mutation
and fuzz run (`just p12-night`). Owner, overnight.
## P2: the gates themselves
1. **CI's `check` took 72 minutes**, one test binary at a time. Done
(5544a3e66): five parts on five runners from one definition in the
justfile, and the lint part fails if CI's list is not the justfile's.
Not yet seen on CI: the first push shows it.
2. **`just prove` had one 1800 s cap for all 97 Kani harnesses.** On a
loaded machine it was cut off with no failure named. Done (fe3b10e2d):
a cap per harness, and a run that does not verify everything lists
what failed, what ran past its cap and what never finished.
3. **There was no supply-chain gate.** Done: `just deny` (cargo-deny,
`deny.toml`) in the lint part of `just check` and in the weekly run.
Its first run found 23 known vulnerabilities in the lock file, one
unsound crate, two yanked and nine unmaintained. Closed by upgrades
(quick-xml 0.42, rusqlite 0.41, rust_xlsxwriter 0.102, rmcp 3.9,
rustls, tokio, zstd, pulldown-cmark); two quick-xml advisories remain
for the copy typst brings, which parses nothing from outside, and are
written down in `deny.toml`. The upgrade also found a wrong answer:
**the XLSX reader dropped every `&amp;` and `&#...;` in a cell**
(`AT&amp;T` read as `ATT`), since the parser reports a reference as
its own event and the reader took only the text. Fixed with a test.
The licence list allows two that are not plain permissive: MPL-2.0
(one crate, unchanged) and CDLA-Permissive-2.0 (Mozilla's root
certificates). It allows no font licence: egui's default font set
carried Ubuntu Light under the Ubuntu Font Licence, which Debian and
Fedora class as non-free, so that set is switched off and the viewer
names its own fonts (Inter, Hack, Noto, two symbol fonts; OFL 1.1, MIT
and Bitstream Vera), each beside its licence
(`crates/ledger-gui/assets/fonts/README.md`).
4. **The packages carried no third-party licence notices.** The fonts
(OFL, MIT, Bitstream Vera) and the MIT, Apache and BSD crates all ask
that their notice travel with a binary. Done (merged 9d1cb28f2, then
two commits of mine): `THIRD-PARTY-NOTICES.txt` is generated from the
lock file (`just notices`: cargo-about for the crates, the font
licences beside it), compiled into the program (`wanderbooks
licenses`), and `just notices-check` in the lint part fails when it is
out of date (about 2 minutes). What checking it found: for 70 crates
cargo-about could give only a licence's standard text with a
placeholder where the copyright line goes (`Copyright (c) <year>
<copyright holders>`), since their own licence file is a compound one
(chrono, libm, aws-lc, the windows crates) or they were packaged with
none (egui, objc2, wasmi). MIT, BSD and ISC ask for the notice itself,
so the file now also gives those crates' own licence files whole, and
names the repository of the 35 packaged with none. The bundled C
libraries are covered: zstd's and AWS-LC's notices come from their
`-sys` crates, and SQLite is in the public domain. The .deb, the .rpm
and the Arch tarball carry the file under `/usr/share/doc/wanderbooks/`
and the package test compares it with what the program prints; **no
package was built to check those entries** (the first `just
package-linux` does). The AppImage, the .dmg and the Windows program
carry it compiled in.
5. **The Lean model of the books covers 14 steps; the Rust `Ledger` has
119 commands**, and no list mapped one to the other, so "every
reachable state" covered less than it read. The inventory is done
(`docs/command-steps.md`, kept whole by `tests/command_steps.rs`): 71
commands are the `record` step, 11 are one step, 19 are several steps
run as one, 17 are replay doors and one is no step. What it found, each
closing with Lean in bookspec (hard implementation, then the pin moves):
- `renumber_account` is no step of the model. A `renumber` step: codes
stay distinct, and every balance is the old one under the new code.
- Four doors apply a change without a check the model's step requires
(`create_entry`, `replay_generate_recurring`, `replay_create_period`,
`replay_reverse_entry`), so books replayed from an old journal can be
outside `Reachable`. The laws that rest on distinct codes, acceptable
entries and known accounts still hold, by reading the proofs; a
`ReplayStep` relation and its theorem would make that proved.
- The registers (fixed assets, schedules, recurring entries, payroll
runs) have proved arithmetic and no step model of how they change.
- Nothing proves a Rust command is its Lean step. Two tests check it:
bookspec's examples and the differential test (`lean_model.rs`),
which does not reach a standalone period, a close with explicit
targets, a draft left unposted or an account added late. Extend it.
6. **Coverage is measured only for ledger-core and ledger-store.**
7. **Three allocation preludes are still outside the kernel**
(`try_allocate`, `allocate_cumulative`, `tax_capital::split`): they
prepare the remainders the kernel then apportions. Each needs a Kani
harness, a Lean theorem and a bridge property. Hard implementation.
## P3: drift and debt
- `plan/roadmap.md` Phase 3 and a few other pages describe an older state.
- bookspec: 39 CHOICE options and 2 rules (BS-asset-9, BS-partner-16)
without examples; the second implementation (X-O, hledger), X-K2 and
L-G4 are not started.
- `ledger.rs` is past 9,000 lines; `reports.rs`, `parties.rs` and
`cashflow.rs` are large too. Not a correctness problem.
## The owner's alone
Mac, Windows and clean-Linux trials; the first `release` run; the icon;
signing (D-64); the re-audit (P10); Q-6 before P9b.
## Order of work
1. Land what is in flight: V-D3, K-U9, K-U10a, K-U10b (all four done).
2. K-U11a on top of them, then K-U12, then the detector in `just check`.
3. `overflow-checks`, the CI split, `just prove`'s cap, `cargo-deny`
(all four done).
4. One gate at the end (`just check`, `just prove`), one push, four gates
read.
5. The steps the inventory found missing (bookspec), the allocation
preludes, then bookspec's examples and second implementation.
+4 -1
View File
@@ -40,6 +40,8 @@ merged. bookspec main is at 2b3b6c9 (wanderbooks pinned there).
of bookspec's theorem list (151 of 177). Kept and pinned: an exact tie
between shares goes where Decimal's 28th digit sends it, as it always
has (K-U10 puts exact ranking to the owner, with the cents it moves).
Decided since (D-76, merged 5e9591725): a tie goes to the earlier
part, ranked on exact remainders.
**Next**: X-H1d's fixes, X-H1e; S-C8, S-E4, V-D3 (small, from the
reviews); K-U6..U9, K-U10 (with the owner's tie-break decision); X-K2,
@@ -78,7 +80,8 @@ reviewed by a second model before it merged:
refuse; a reversal could be dated before its original (D-73); a
26-place foreign amount booked a cent the product never reached
(D-75). Found, scheduled: rust_decimal's add and multiply round at
their edges (K-U10).
their edges (K-U10; closed 2026-11-09, merged e632855f1: the kernel's
sums and products are exact or refused).
- **Coverage**: a report and floor (core 90%, store 92%, weekly), and
rust_decimal checked against exact rationals (V-D).
+1
View File
@@ -2198,6 +2198,7 @@ The owner decisions of 2026-10-16 (at the top of this document) replace the form
| D-73 | A reversal's date (owner, 2026-11-08, the question tool: "Every reversal on or after") | **Every reversal MUST be dated on or after the entry it reverses, for every kind of entry (was enforced only for document reversals and schedule runs): a correction comes after what it corrects. bookspec BS-ledger-5 states it; the engine's `check_reversal` refuses an earlier date; the Lean model's `reverse` step requires it (unit L-G1).** Found when the Lean model was made executable. In the same pass, a close with nothing to close was confirmed to post no entry and still close the period (the engine's INVARIANT 5; an entry needs two lines), and BS-period-1 is worded to say so. |
| D-74 | A refusal when several rules are broken (owner, 2026-11-08, the question tool: "Any broken rule counts") | **When one command breaks several rules, an engine may refuse it with any rule it actually breaks; bookspec's examples test one broken rule at a time, and the Lean-model differential test (L-G5) checks that the engine's reason is one of the rules the command breaks.** Found by L-G5: the engine checks each line as it is added, the model checks the date and the whole entry first, so a command with two faults was refused with different words. |
| D-75 | Foreign amounts and FX rates are bounded (owner, 2026-11-08, the question tool: "Cap them at 10 places") | **A new line's foreign amount and its FX rate take at most 10 decimal places each, as a base amount already does (B-28's bounds; never on replay), so foreign × rate always fits a Decimal exactly and the booked base amount is rounded once.** Found by the K-U1 review: with a 26-place foreign amount, rust_decimal rounded the product to 28 places before the engine rounded it to the cent, booking a cent the exact product doesn't reach. |
| D-76 | A tie between shares (owner, 2026-11-09, the question tool: "Exact, from now on") | **When a split leaves cents over and two parts have the same exact remainder, the cent goes to the earlier part. The remainders ranked are the exact ones, `whole × weight − part × total`, never the difference of quotients rounded at Decimal's 28th digit.** Found by K-U10b: the docs and bookspec's Lean (`Apportion`) said a tie goes to the earlier part, and the engine ranked rounded quotients, so 20.00 by 4/1/1 came out 13.33 / 3.34 / 3.33 where the rule gives 13.34 / 3.33 / 3.33. No golden file moves; no part moves by more than a cent; a split between two parts, or by equal weights, cannot differ. Splits already posted are not recomputed (posted is forever). Of the engine's splits by largest remainder only one can differ: the K-1 worksheet's share of contributed property among the members' credits in one entry (`k1::share_property`), computed on reading, which divides by the credits' total. A convention's template split and the close rule of 2026-10-13 (`periods::allocate`, frozen for replay) split by shares that sum to one, where nothing is divided and the old ranking was already the exact one. Where a weight of 27 places makes a product past Decimal's 28 digits, the split is still made, ranked by the nearest figures Decimal holds. Kani then showed the same rule on whole numbers: a part whose share is exact never takes a leftover unit (5 by 2/3/5 is 1, 2, 2, not 2, 1, 2), and the harness asserts it. |
### 10.2 Deferred
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env python3
"""The third part of THIRD-PARTY-NOTICES.txt (`scripts/notices.sh`).
cargo-about gives each crate the text of the licence it names. Where it
cannot match a crate's own licence file to that licence (a compound file:
two licences in one, or a text with a preamble), or the crate was packaged
with no licence file at all, it prints the licence's standard text, whose
copyright line is a placeholder ("Copyright (c) <year> <copyright
holders>"). MIT, BSD and ISC ask for the copyright notice itself, so a
placeholder does not carry what they ask for.
This script reads cargo-about's output (argument 1), finds every section
whose text holds such a placeholder, and writes to standard output:
- every licence file those crates were packaged with, whole, each
distinct text once, under the crates that carry it;
- the crates packaged with no licence file, each with the repository its
manifest names, where its notices are.
It reads the crates where cargo has them (`cargo metadata --locked
--offline`), so the output depends on Cargo.lock and nothing else.
"""
import json
import os
import re
import subprocess
import sys
RULE = "=" * 80
THIN = "-" * 80
PLACEHOLDER = re.compile(r"<(year|owner|copyright holders?|name of author)>", re.I)
LICENCE_FILE = re.compile(r"^(licen[sc]e|copying|copyright|notice|unlicense)", re.I)
def placeholder_crates(about):
"""(name, version) of every crate in a section with a placeholder."""
lines = about.split("\n")
# A section starts at a rule, a name, a rule.
starts = [
i
for i in range(len(lines) - 2)
if lines[i] == RULE and lines[i + 2] == RULE and lines[i + 1] != ""
]
found = set()
for n, start in enumerate(starts):
end = starts[n + 1] if n + 1 < len(starts) else len(lines)
body = lines[start + 3 : end]
if "Used by:" not in body:
continue
at = body.index("Used by:") + 1
crates = []
while at < len(body) and body[at].startswith(" "):
name, version = body[at].split()
crates.append((name, version))
at += 1
if PLACEHOLDER.search("\n".join(body[at:])):
found.update(crates)
return sorted(found)
def packages():
"""(name, version) -> (directory, repository), from cargo."""
out = subprocess.run(
[
"cargo", "metadata", "--format-version", "1", "--locked", "--offline",
"--all-features", "--manifest-path", "crates/ledger-cli/Cargo.toml",
],
check=True,
capture_output=True,
text=True,
).stdout
return {
(p["name"], p["version"]): (os.path.dirname(p["manifest_path"]), p.get("repository") or "")
for p in json.loads(out)["packages"]
}
def licence_files(directory):
"""The licence files at a crate's root, and in a LICENSES folder there."""
files = []
for name in sorted(os.listdir(directory)):
path = os.path.join(directory, name)
if not LICENCE_FILE.match(name):
continue
if os.path.isfile(path):
files.append((name, path))
elif os.path.isdir(path):
for inner in sorted(os.listdir(path)):
if os.path.isfile(os.path.join(path, inner)):
files.append((f"{name}/{inner}", os.path.join(path, inner)))
return files
def text_of(path):
with open(path, "rb") as f:
raw = f.read()
try:
text = raw.decode("utf-8")
except UnicodeDecodeError:
text = raw.decode("latin-1")
lines = [line.rstrip() for line in text.replace("\r\n", "\n").split("\n")]
return "\n".join(lines).strip("\n")
def main():
with open(sys.argv[1], encoding="utf-8") as f:
crates = placeholder_crates(f.read())
if not crates:
return
known = packages()
texts = {} # the text's words -> (text, ["name version (file)"]), first seen first
bare = []
for name, version in crates:
if (name, version) not in known:
sys.exit(f"notices: cargo metadata does not list {name} {version}")
directory, repository = known[(name, version)]
files = licence_files(directory)
if not files:
if not repository:
sys.exit(
f"notices: {name} {version} has no licence file and names no "
"repository: add its notice by hand in scripts/notices-packaged.py"
)
bare.append((f"{name} {version}", repository))
for label, path in files:
text = text_of(path)
# The same text, wrapped or indented differently, is one text.
key = " ".join(text.split())
texts.setdefault(key, (text, []))[1].append(f"{name} {version} ({label})")
print(RULE)
print("LICENCE FILES AS PACKAGED")
print(RULE)
print()
print("Some sections above give a licence's standard text, whose copyright line")
print("is a placeholder: the crate's own licence file is a compound one (two")
print("licences in one file, or a text with a preamble), or the crate was")
print("packaged with no licence file. For every crate in such a section, the")
print("licence files it was packaged with are given here, whole. A text that")
print("several crates carry word for word is given once.")
print()
for text, carriers in texts.values():
print(THIN)
print("Packaged with:")
for carrier in carriers:
print(f" {carrier}")
print(THIN)
print()
print(text)
print()
if bare:
print(THIN)
print("Packaged with no licence file")
print(THIN)
print()
print("The crates below name their licence in their manifest (it is the one")
print("they are listed under above) and were packaged with no licence file.")
print("Their copyright notices are in their source repositories:")
print()
width = max(len(crate) for crate, _ in bare)
for crate, repository in bare:
print(f" {crate.ljust(width)} {repository}")
print()
main()
+178
View File
@@ -0,0 +1,178 @@
#!/usr/bin/env bash
# The third-party notices the program must travel with (MIT, Apache-2.0,
# BSD, ISC, Zlib, SIL OFL 1.1 and the rest all ask that their copyright
# notice and licence text go with every copy).
#
# scripts/notices.sh write THIRD-PARTY-NOTICES.txt
# scripts/notices.sh --check fail if it is out of date (`just notices-check`)
#
# The file has three parts. The first is cargo-about's: every crate the
# `wanderbooks` binary links, with the licence it carries and that
# licence's text. cargo-about reads the manifest of `ledger-cli` (the one
# executable), every feature and every platform the program ships on, so
# the list is what the program contains, not what this machine happens to
# build. Where cargo-about cannot match a crate's own licence file (a
# compound file, or none packaged) it prints the licence's standard text,
# whose copyright line is a placeholder; MIT, BSD and ISC ask for the
# notice itself. So the second part (`scripts/notices-packaged.py`) gives
# the licence files those crates were packaged with, whole, and names the
# repository of each crate packaged with none. The third part is the fonts
# the program embeds: each file under `crates/ledger-gui/assets/fonts/`
# and `crates/ledger-import/fonts/`, with the licence file beside it. A
# font file that no entry below names fails the script, so a new font
# cannot ship without its notice.
#
# The output is plain text, says nothing about this machine (no dates, no
# absolute paths), and is the same on two runs; `--check` compares it with
# the committed file byte for byte, so a changed dependency shows up as a
# red `just check` until the file is regenerated and committed.
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
out=THIRD-PARTY-NOTICES.txt
case "${1:-}" in
"" | --check) ;;
*)
echo "usage: scripts/notices.sh [--check]" >&2
exit 2
;;
esac
check=${1:-}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
# Which licence each bundled font carries. Every `*.ttf` and `*.otf`
# under the two font folders must match one pattern here; a new font is
# added here beside its licence file, never left out of the notices.
font_map=(
"crates/ledger-gui/assets/fonts/InterTab-*.ttf|crates/ledger-gui/assets/fonts/Inter-LICENSE.txt"
"crates/ledger-gui/assets/fonts/Hack-Regular.ttf|crates/ledger-gui/assets/fonts/Hack-LICENSE.txt"
"crates/ledger-gui/assets/fonts/NotoEmoji-Regular.ttf|crates/ledger-gui/assets/fonts/NotoEmoji-LICENSE.txt"
"crates/ledger-gui/assets/fonts/emoji-icon-font.ttf|crates/ledger-gui/assets/fonts/emoji-icon-font-LICENSE.txt"
# The PDFs' Inter is the same font and licence as the viewer's.
"crates/ledger-import/fonts/Inter-*.ttf|crates/ledger-gui/assets/fonts/Inter-LICENSE.txt"
"crates/ledger-import/fonts/NotoSans*-Regular.ttf|crates/ledger-import/fonts/NotoSans-LICENSE.txt"
"crates/ledger-import/fonts/NotoSansCJKsc-*.otf|crates/ledger-import/fonts/NotoSansCJK-LICENSE.txt"
)
# font -> licence, filled from font_map below.
declare -A font_licence=()
for entry in "${font_map[@]}"; do
pattern=${entry%%|*}
licence=${entry#*|}
matched=0
for file in $pattern; do
[ -f "$file" ] || continue
font_licence["$file"]=$licence
matched=1
done
if [ "$matched" -eq 0 ]; then
echo "notices: no font matches $pattern (the map in scripts/notices.sh is stale)" >&2
exit 2
fi
done
# Every font file must be accounted for: a font that no entry names has
# no notice to travel with.
fonts=$(find crates/ledger-gui/assets/fonts crates/ledger-import/fonts \
-type f \( -name '*.ttf' -o -name '*.otf' \) | sort)
for font in $fonts; do
if [ -z "${font_licence[$font]:-}" ]; then
echo "notices: no licence for $font: add it to the map in scripts/notices.sh" >&2
exit 1
fi
done
# The fonts section, grouped by licence file: every font that carries a
# licence is listed, then that licence's text once.
font_section() {
echo "================================================================================"
echo "FONTS"
echo "================================================================================"
echo
echo "The program embeds the fonts below. Each font file is listed under"
echo "the licence it carries, and that licence's text follows."
echo
local seen=() entry licence font found seen_licence
for entry in "${font_map[@]}"; do
licence=${entry#*|}
found=0
for seen_licence in ${seen[@]+"${seen[@]}"}; do
[ "$seen_licence" = "$licence" ] && found=1
done
[ "$found" -eq 0 ] || continue
seen+=("$licence")
if [ ! -f "$licence" ]; then
echo "notices: no licence file $licence" >&2
exit 1
fi
echo "--------------------------------------------------------------------------------"
echo "$licence"
echo "--------------------------------------------------------------------------------"
echo
echo "Fonts:"
while IFS= read -r font; do
[ -n "$font" ] || continue
[ "${font_licence[$font]:-}" = "$licence" ] || continue
echo " $font"
done <<<"$fonts"
echo
cat "$licence"
echo
done
}
# One full copy of the notices, in $1.
write_notices() {
local target=$1
command -v cargo >/dev/null || {
echo "notices: cargo is not installed (mise install)" >&2
exit 2
}
# --offline: cargo-about reads only the crates' own packaged files.
# Without it, a crate packaged without its licence file is looked up
# in its git repository, so the file could change with no change
# here. The cost: such a crate gets the licence's standard text,
# without the copyright line its repository holds (the second part
# of the file names that repository). The manifest is
# ledger-cli's, the one executable: that dependency graph is what the
# binary links.
if ! cargo about generate --locked --all-features --offline \
-m crates/ledger-cli/Cargo.toml -c about.toml \
deploy/notices/about.hbs > "$work/about.txt"; then
echo "notices: cargo-about failed. It reads every crate in Cargo.lock from the local" >&2
echo "registry, every platform's included: if one is missing, run \`cargo fetch --locked\` first." >&2
exit 2
fi
command -v python3 >/dev/null || {
echo "notices: python3 is not installed" >&2
exit 2
}
python3 scripts/notices-packaged.py "$work/about.txt" > "$work/packaged.txt"
{
cat "$work/about.txt"
echo
cat "$work/packaged.txt"
font_section
} > "$work/all.txt"
# Plain text: trailing whitespace off every line, and exactly one
# newline at the end (the licence files and cargo-about differ).
sed 's/[[:space:]]*$//' "$work/all.txt" > "$work/clean.txt"
printf '%s\n' "$(cat "$work/clean.txt")" > "$target"
}
if [ "$check" = --check ]; then
write_notices "$work/check.txt"
if ! cmp -s "$work/check.txt" "$out"; then
diff -u "$out" "$work/check.txt" | head -40 >&2 || true
echo 'THIRD-PARTY-NOTICES.txt is out of date: run `just notices` and commit the result' >&2
exit 1
fi
echo "notices: $out is up to date"
else
write_notices "$out"
echo "notices: wrote $out"
fi
+6 -1
View File
@@ -72,10 +72,15 @@ printf 'disallowed-methods = [%s]\n' "$methods" > "$work/all/clippy.toml"
printf 'arithmetic-side-effects-allowed = ["rust_decimal::Decimal", "rust_decimal::decimal::Decimal"]\n'
} > "$work/rest/clippy.toml"
# The library and the programs: a package with no library (ledger-cli) is
# its programs alone, and cargo refuses `--lib` there.
targets=(--bins)
if [ -f "crates/$pkg/src/lib.rs" ]; then targets=(--lib --bins); fi
# One clippy run: the findings as `file<TAB>line<TAB>column<TAB>lint<TAB>what<TAB>source`.
run() {
local name=$1 status=0
CLIPPY_CONF_DIR="$work/$name" cargo clippy --quiet -p "$pkg" --lib \
CLIPPY_CONF_DIR="$work/$name" cargo clippy --quiet -p "$pkg" "${targets[@]}" \
--target-dir "target/raw-arith/$name" --message-format=json -- \
-A clippy::all -W clippy::arithmetic_side_effects -W clippy::disallowed_methods \
> "$work/$name.json" 2> "$work/$name.err" || status=$?