- The 13K-character instructions (clients cut them short) become a
connect text of at most 1,400 characters whose first 512 stand alone,
plus books.handbook and books://handbook/{section}: the old guidance by
section, with no helper commands, home paths, pull requests or
file-reading suggestions (tool_text_lint).
- Every tool has a title and read-only/destructive hints; no
requiresUserInteraction anywhere (owner decision 2026-10-16).
- books.import_local_file reads only regular files inside the import
roots (the downloads folder by default, or --import-root), never the
data dir, books dir, vault or the key's folder, no symlink escapes or
hard links, and the file opened must be the file checked.
- The store lock is a tokio mutex taken off the runtime threads.
- get_info refreshes settings first; a bare books://digest reads.
Review fixes (P0 review, 2026-10-16):
- Fail closed: a tokio mutex never poisons and spawn_blocking caught the
panic, so after a panic mid-mutation the server kept serving a Store
behind its journal. A panic (the task, or while holding the store)
now stops the shared store; every later request on every session is
refused with a plain message; a restart re-verifies the journal. The
join error goes through redact_refusal and never carries the panic's
text.
- books.set_w9 w9_file_path read any path (a link named w9.pdf to the
vault key was stored and get_w9 wrote it out): it now goes through the
import roots' lockdown, its type judged on the canonical path.
- Sealed even inside a root: the key file in force, where a linked one
leads, both folders, and the default key folder whatever the settings
say. Refusals check the roots first, so outside them every path gets
one message (no probing what exists); inside, other books-dir files say
to copy them out first.
- The open is O_NOFOLLOW | O_NONBLOCK (a pipe swapped in after the check
can't hang a thread) and must match the checked file's device and
inode. New dependency: libc (unix only), for those two open flags,
which std doesn't name.
- Default import roots are the downloads folder only (the plan); files
with full TINs (get_w9, vendor_1099 include_tins, the CPA package with
TINs) are never written into an import root, and the server refuses to
import any file it wrote with TINs (by SHA-256).
- set_tin and set_w9 overwrite vault records: destructive_hint = true;
annotations_complete pins the key tools' hints. The read-only hint is
checked in behaviour on every spec_mcp call (journal and data-dir files
unchanged).
- Text: the connect text names the settings file as the one local file
to edit, says every entry balances on real accounts and names its
party, says invoice/bill/payment/payroll tools post unchecked, rewords
the exemptions, and shows the company name as one plain line; the
handbook takes section "all", lists its ids in the schema and says to
read contract first; books.settings drops the config.json path and no
error names the data dir or the key file. tool_text_lint covers the
whole tool JSON and resources and bans git/commit/WL-0001; tool
descriptions over 700 characters are pinned to today's eight (P5).
- digest: an empty since= is bare; the default date is pinned on every
day of a month.
Round-2 review fixes (2026-10-16):
- TIN files (B-26): the in-memory, per-session set of TIN-file hashes
became one registry beside the vault (vault/tin-files.sha256, hashes
only), shared by every session and every later server. It holds the
W-9 set_w9 reads (recorded as read), get_w9 copies, 1099 worksheets
with TINs, CPA packages with TINs and each file in one that holds a
TIN; a file is recorded before it is written, and a failure refuses.
import_local_file, attach_receipt and file_document (base64 was never
checked) refuse a recorded file, and a text file (by type, name, or
UTF-8/UTF-16 decoding) holding a full TIN. Not caught: an altered
binary copy; the docs say so (P2/P7 remove the path tools).
- The text check is narrow (owner/engineer decision, 2026-10-16: bank
exports are filed for reconciliation, and has_full_tin's "nine digits
however separated" refused their routing numbers, long references and
dates run into amounts). Text is refused when it holds (a) a TIN the
vault holds for a party, anywhere, as nine digits, 3-2-4 joined by
hyphens, spaces or dots, or 2-7 joined by a hyphen or space, compared
on the server against the decrypted vault and never returned or
logged (a vault that can't be opened leaves (b)); or (b) a stand-alone
printed SSN (123-45-6789) or EIN (12-3456789) shape: no digit, and no
hyphen or dot followed by a digit, beside it. Full-width digits and
Unicode hyphens and spaces read as ASCII. has_full_tin still guards
refusals and results (redact_refusal). Known limit, for P7: a refusal
under (a) tells the agent a text it chose holds a vault TIN.
New dependency: zeroize in ledger-mcp (already in the workspace
through ledger-vault, same major version), so the vault's TINs decoded
for the scan are wiped from memory on drop as the vault's own are.
- Mutation testing of the final P0 diff (docs/testing.md): tests for
each law a survivor broke (handbook titles, a dropped default root, a
.jpg W-9, the waker, the walk's folder flags against a link and a
pipe, the 40-link limit, save paths refused as such, the package
marking only its TIN files, a registry that can't be read, text types,
the short receipt rule's counts and a 12-character code). Simpler
code where only a race could tell: inspect places an existing path by
canonicalize itself (no second comparison), read_checked's read limit
is its one size check, openat fails on -1 as specified. The 25 MiB
upload test removes its 50 MB of books however it ends.
- The GUI's stale-rule prompt no longer says to open a pull request: it
asks the agent to find the figure from the rule's official authority,
confirm it with the human, pass it explicitly, and tell the human so it
can be reported upstream (as the handbook says); a lib test pins it and
bans files, git, GitHub and pull requests from every attention prompt.
- Import roots (local_files.rs INVARIANT 0): XDG_DOWNLOAD_DIR="$HOME/"
made $HOME (or /) the root. No root may be /, the home folder or hold
it, or hold the books, data dir, vault or a key: a named one stops the
server at startup, a default one is dropped; the default falls back to
~/Downloads only if that is a real folder other than $HOME; with no
root, an import says so.
- The read is a component walk from / with openat(O_NOFOLLOW |
O_DIRECTORY) per folder and O_NOFOLLOW | O_NONBLOCK for the file, so a
folder swapped for a link after the check fails; no step may land on a
protected inode (one renamed into a root); dev/ino and nlink stay. No
/proc. Portable to macOS. (libc's openat, two small unsafe blocks.)
- One refusal for missing, dangling and outside paths: resolved()
follows every link, dangling ones too, so a link's target existing or
not no longer changes the answer.
- Sealing: the key files (in force, default) and their targets always;
their folders only when not $HOME, not a root, not holding a root; and
~/.config/wanderbooks whatever XDG_CONFIG_HOME says.
- Agent text (I-12): RuleNotKnown names the authority (IRS, with its
address) and says to tell the human, never a repo path, PR or GitHub;
the digest's stale_rules drop the repo catalog and path for it; vault,
outside-books, STOPPED and local-file refusals name no git, path or
flag. tool_text_lint bans docs/, .md, /home, data dir, --data-dir,
--import-root, vault.key, .jsonl, sqlite, .gitignore, github, pull
request, and also lints every error template (scanned from source),
built error texts, and the server's refusal constants.
- The receipt rule told (ReceiptPolicy::rule) is the one enforced: the
exact threshold in the base currency (no "$", no rounding), required
and exempt accounts, reversals exempt; the connect text fits 1,400
characters by dropping reasons, then codes, never the rule.
- The connect text follows the parties setting; "offer books.digest"
everywhere. shown_name drops Unicode format characters (bidi, zero
width).
- read_only_tools_change_nothing compares file contents, the database
by every row, the vault and the settings file (raw database bytes did
not change either; rows are the stable comparison).
- import_local_file takes the name and type from the canonical path;
the digest's journal repair says when the tail was set aside, not the
journal's file name; "version-history messages" back in the TIN rule;
openWorldHint false on every tool, pinned in annotations_complete.
- Outside the MCP crate, for the same texts: ledger-core's DatedRule
gains `authority` (the statute or publication with its address) and
RuleNotKnown carries it; ledger-store's "sqlite error" reads "database
error"; ledger-config's ReceiptPolicy::rule takes the base currency.
New dev-dependency: rusqlite in ledger-mcp (already in the workspace,
same version and features as ledger-store), to read the database's
rows in read_only_tools_change_nothing.
- The filing scan is no TIN oracle (tin_files.rs INVARIANT 4): text
holding more than two TIN-shaped numbers (any rendering rule (a)
reads) that end in a known TIN's last four (the books' TIN and W-9
facts, via known_tin_last4, before the vault is opened; then the
vault's own) is refused with TIN_PROBE, the same words whether or not
one is the vault's TIN; only one or two candidates are compared
against the vault. Tests: unit
text_probing_for_a_tin_is_refused_alike_whether_or_not_it_holds_it,
one_or_two_candidates_are_compared_against_the_vault; over HTTP
text_probing_for_a_tin_is_refused_alike_by_every_filing_tool.
Plan: plan/served.md P0, section 6 "Immediate hole (P0)", 4.1, 4.3, 4.9.
Review round 3. S1: a panic stops the server for every session, so no
input may reach one. Dates are four-digit years (new ledger_core::
calendar, 0001-01-01..9999-12-31): the MCP's parse_date is strict
YYYY-MM-DD, periods are bounded, last_day_of_month returns a refusal
(server and store); schedules, assets, recurring entries, periods,
documents, disposals and entries refuse dates outside the calendar, and
replay refuses such journal dates. Every amount a command takes is at
most a line's (draft lines by size, document lines, payouts, payroll,
statements, shares, tax basis, proceeds, recurring templates), on
replay too, so sums are exact; the 1099 vendor part and the K-1
property share use checked products (TooLargeToCompute); a recurring
run makes at most 1,000 drafts. tests/hostile_args.rs drives every tool
with schema-derived hostile arguments and every resource with generated
URIs, asserting the server never stops; the audit's panics are pinned.
S2: a `.` or `..` path name is refused as NO_SUCH_FILE up front. S3:
NUL-interleaved UTF-16 without a byte-order mark is scanned both ways.
S4: resource-read refusals are TIN-redacted. S5: set_w9 records its W-9
only once the call passes every check, just before the vault write.
S8: idempotentHint only on verify, run_depreciation, run_schedules,
run_recurring, set_party_roles (a repeat leaves journal and vault
alone; spec_vault checks every candidate twice); every tool's hints
pinned in one table. C1: books.settings lists receipt_required_accounts
and receipt_exempt_accounts uncut. C2: the default company name reads
"a new company". C3: the parties rule names no-party reasons. C4/C5:
the handbook names the settings file only as books.settings' books_toml,
and restores "check books.digest and offer it". C6: an import root
inside the books, data dir or vault is refused at startup. The lint
catches `just` however it ends and where the books are;
digest_resource_bare_reads reads the server's month.
Review round 4 (2026-10-17): round 3's bounds ran in replay too, so
journals main wrote and reopened (an entry dated 0000-06-01 or
+10000-01-01, a draft line of 2e15, an asset ending past 9999, a basis
or share past the line limit, sub-cent document and payroll lines) no
longer opened. Posted is forever: the bounds are the commands' only.
- Replay applies main's rule exactly: parse_date takes any date chrono
reads; replay_add_line(_fx) has no size bound (add_line/add_line_fx
do); replay_register_asset/correct_asset (chrono overflow only),
replay_set_asset_tax_basis (check_journaled), replay_set_entry_parties
(check_shares_journaled), replay_register_recurring
(validate_recurring_journaled), replay_register_schedule (months 1 to
600), replay_create_period (order only), replay_dispose_asset, and no
line, date, payment or payroll range checks in replay_invoice/bill,
their payments and replay_payroll_run.
- Derived figures over such books refuse (TooLargeToCompute,
DateOutOfRange), never panic: amortization plans, depreciation into
chrono's last month (and the true-up for lives past 9999), intervals,
document totals and aging, net pay and payroll plans, money flows and
share resolution, the asset register, receipt-policy debits; the MCP
tools and the viewer show what can't be computed.
- tests/fixtures/old-books: the review's 13 journals, its control and 15
more edges, written by main's Store API with main's figures
(expected.json); every one opens in the writer and the viewer to those
figures, every derived figure computes or refuses, every MCP tool and
GUI page answers; hostile_args restarts the server after each
property; each bound has a command/replay test pair.
Final review: a schedule's plan refuses a total of 10^26 or more
(TooLargeToCompute) instead of letting Decimal round its cents silently,
and a null `remaining` in the schedule output is always explained by
plan_error. Replay is unaffected: no journaled schedule month can belong
to a total that large (the line limit bounds every posted month).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T3gXMVt7XJPi6ens1or9Dj
793 lines
28 KiB
Rust
793 lines
28 KiB
Rust
//! No command reaches an overflow or a date chrono can't hold: every amount
|
|
//! a new command takes is at most a journal line's
|
|
//! (kernel::MAX_LINE_AMOUNT), every date is in the calendar the books keep
|
|
//! (ledger_core::calendar), and what can't be computed exactly is refused,
|
|
//! never wrapped or panicked on (P0 review round 3, finding S1: a panic
|
|
//! stops the books server). The bounds are the commands' only: replay
|
|
//! accepts every line an earlier version accepted (rules.md B-28, posted
|
|
//! is forever; P0 review round 4), so each bound here has its pair, a
|
|
//! replay of an old line past it, accepted.
|
|
//!
|
|
//! ```text
|
|
//! GOAL: a command the books can't hold is refused with a reason, the
|
|
//! ledger unchanged; a replayed line an earlier version wrote past
|
|
//! the same bound is accepted exactly as written.
|
|
//! SOURCE: DECISION (P0 review round 3, 2026-10-16, S1; round 4,
|
|
//! 2026-10-17); kernel.rs MAX_LINE_AMOUNT (rules.md: a line over a
|
|
//! quadrillion is a mistake); calendar.rs (four-digit years).
|
|
//! ```
|
|
|
|
use chrono::{Datelike, NaiveDate};
|
|
use ledger_core::kernel::MAX_LINE_AMOUNT;
|
|
use ledger_core::{
|
|
AccountId, AccountType, Currency, DocumentLine, Frequency, Ledger, LedgerError, Money,
|
|
NewRecurring, NewSchedule, PayrollLine, Side,
|
|
};
|
|
use rust_decimal::Decimal;
|
|
|
|
fn d(y: i32, m: u32, day: u32) -> NaiveDate {
|
|
NaiveDate::from_ymd_opt(y, m, day).unwrap()
|
|
}
|
|
|
|
fn usd(a: Decimal) -> Money {
|
|
Money::new(a, Currency::USD)
|
|
}
|
|
|
|
/// One past the largest a line may be.
|
|
fn too_big() -> Decimal {
|
|
MAX_LINE_AMOUNT + Decimal::new(1, 2)
|
|
}
|
|
|
|
struct Books {
|
|
ledger: Ledger,
|
|
cash: AccountId,
|
|
prepaid: AccountId,
|
|
revenue: AccountId,
|
|
expense: AccountId,
|
|
}
|
|
|
|
fn books() -> Books {
|
|
let mut ledger = Ledger::new(Currency::USD);
|
|
let mut add = |code: &str, ty| ledger.add_account(code, code, ty, None, false).unwrap();
|
|
let cash = add("1000", AccountType::Asset);
|
|
let prepaid = add("1300", AccountType::Asset);
|
|
let revenue = add("4000", AccountType::Revenue);
|
|
let expense = add("6000", AccountType::Expense);
|
|
add("3000", AccountType::Equity);
|
|
Books {
|
|
ledger,
|
|
cash,
|
|
prepaid,
|
|
revenue,
|
|
expense,
|
|
}
|
|
}
|
|
|
|
/// A date outside the calendar is refused wherever a command takes one:
|
|
/// a draft, a period, a schedule's months, a recurring entry, a document.
|
|
#[test]
|
|
fn dates_outside_the_calendar_are_refused_everywhere() {
|
|
let mut b = books();
|
|
for far in [NaiveDate::MAX, NaiveDate::MIN, d(10000, 1, 1), d(0, 12, 31)] {
|
|
assert_eq!(
|
|
b.ledger.try_create_entry(far, "far").unwrap_err(),
|
|
LedgerError::DateOutOfRange(far)
|
|
);
|
|
assert_eq!(
|
|
b.ledger.create_period("far", far, far).unwrap_err(),
|
|
LedgerError::DateOutOfRange(far)
|
|
);
|
|
}
|
|
assert_eq!(
|
|
b.ledger
|
|
.create_period("far", d(2026, 1, 1), d(10000, 1, 1))
|
|
.unwrap_err(),
|
|
LedgerError::DateOutOfRange(d(10000, 1, 1))
|
|
);
|
|
b.ledger.try_create_entry(d(1, 1, 1), "first day").unwrap();
|
|
b.ledger
|
|
.try_create_entry(d(9999, 12, 31), "last day")
|
|
.unwrap();
|
|
b.ledger
|
|
.create_period("last", d(9999, 12, 1), d(9999, 12, 31))
|
|
.unwrap();
|
|
// A schedule whose months run past the calendar's last day.
|
|
let schedule = |start: NaiveDate, months: u32| NewSchedule {
|
|
description: "Insurance".into(),
|
|
kind: ledger_core::schedules::ScheduleKind::PrepaidExpense,
|
|
total: usd(Decimal::new(30000, 2)),
|
|
start,
|
|
months,
|
|
balance_account: b.prepaid,
|
|
pl_account: b.expense,
|
|
};
|
|
for (start, months) in [
|
|
(d(9999, 12, 15), 2),
|
|
(d(9999, 1, 1), 13),
|
|
(NaiveDate::MAX, 1),
|
|
(d(0, 6, 1), 1),
|
|
] {
|
|
assert!(
|
|
b.ledger.register_schedule(schedule(start, months)).is_err(),
|
|
"{start} + {months}"
|
|
);
|
|
}
|
|
b.ledger
|
|
.register_schedule(schedule(d(9999, 1, 1), 12))
|
|
.unwrap();
|
|
// A recurring entry starting or ending outside it.
|
|
let recurring = |start: NaiveDate, end: Option<NaiveDate>| NewRecurring {
|
|
description: "Rent".into(),
|
|
lines: vec![
|
|
(b.expense, Side::Debit, usd(Decimal::ONE)),
|
|
(b.cash, Side::Credit, usd(Decimal::ONE)),
|
|
],
|
|
frequency: Frequency::Monthly,
|
|
start,
|
|
end,
|
|
};
|
|
for (start, end) in [
|
|
(NaiveDate::MIN, None),
|
|
(d(2026, 1, 1), Some(NaiveDate::MAX)),
|
|
] {
|
|
assert!(matches!(
|
|
b.ledger.register_recurring(recurring(start, end)),
|
|
Err(LedgerError::DateOutOfRange(_))
|
|
));
|
|
}
|
|
// An invoice due outside it.
|
|
let customer = b.ledger.add_customer("Client").unwrap();
|
|
let line = vec![DocumentLine {
|
|
description: "work".into(),
|
|
amount: Decimal::ONE,
|
|
}];
|
|
assert_eq!(
|
|
b.ledger
|
|
.create_invoice(customer, d(2026, 1, 1), NaiveDate::MAX, line.clone())
|
|
.unwrap_err(),
|
|
LedgerError::DateOutOfRange(NaiveDate::MAX)
|
|
);
|
|
let _ = b.revenue;
|
|
}
|
|
|
|
/// The pairs of dates_outside_the_calendar_are_refused_everywhere: each
|
|
/// replay of an old line dated past the calendar is accepted as written.
|
|
#[test]
|
|
fn replayed_dates_outside_the_calendar_are_accepted() {
|
|
let mut b = books();
|
|
for far in [NaiveDate::MAX, NaiveDate::MIN, d(10000, 1, 1), d(0, 12, 31)] {
|
|
let e = b.ledger.create_entry(far, "far");
|
|
assert_eq!(b.ledger.get_entry(e).unwrap().date(), far);
|
|
let p = b.ledger.replay_create_period("far", far, far).unwrap();
|
|
assert_eq!(b.ledger.get_period(p).unwrap().start, far);
|
|
}
|
|
// Only the order is checked on replay.
|
|
assert!(matches!(
|
|
b.ledger
|
|
.replay_create_period("backwards", d(2026, 2, 1), d(2026, 1, 1)),
|
|
Err(LedgerError::InvalidPeriodRange { .. })
|
|
));
|
|
let schedule = |start: NaiveDate, months: u32| NewSchedule {
|
|
description: "Insurance".into(),
|
|
kind: ledger_core::schedules::ScheduleKind::PrepaidExpense,
|
|
total: usd(Decimal::new(30000, 2)),
|
|
start,
|
|
months,
|
|
balance_account: b.prepaid,
|
|
pl_account: b.expense,
|
|
};
|
|
for (start, months) in [
|
|
(d(9999, 12, 15), 2),
|
|
(d(9999, 6, 1), 12),
|
|
(NaiveDate::MAX, 1),
|
|
(d(0, 6, 1), 1),
|
|
] {
|
|
let id = b
|
|
.ledger
|
|
.replay_register_schedule(schedule(start, months))
|
|
.unwrap_or_else(|e| panic!("{start} + {months}: {e}"));
|
|
assert_eq!(b.ledger.get_schedule(id).unwrap().start, start);
|
|
}
|
|
// The month bounds are main's: 1 to 600.
|
|
assert!(
|
|
b.ledger
|
|
.replay_register_schedule(schedule(d(2026, 1, 1), 601))
|
|
.is_err()
|
|
);
|
|
let recurring = |start: NaiveDate, end: Option<NaiveDate>| NewRecurring {
|
|
description: "Rent".into(),
|
|
lines: vec![
|
|
(b.expense, Side::Debit, usd(Decimal::ONE)),
|
|
(b.cash, Side::Credit, usd(Decimal::ONE)),
|
|
],
|
|
frequency: Frequency::Monthly,
|
|
start,
|
|
end,
|
|
};
|
|
for (start, end) in [
|
|
(NaiveDate::MIN, None),
|
|
(d(2026, 1, 1), Some(NaiveDate::MAX)),
|
|
] {
|
|
b.ledger
|
|
.replay_register_recurring(recurring(start, end))
|
|
.unwrap();
|
|
}
|
|
let customer = b.ledger.add_customer("Client").unwrap();
|
|
let vendor = b.ledger.add_vendor("Supplier").unwrap();
|
|
let line = vec![DocumentLine {
|
|
description: "work".into(),
|
|
amount: Decimal::ONE,
|
|
}];
|
|
b.ledger
|
|
.replay_invoice(1, customer, NaiveDate::MIN, NaiveDate::MAX, line.clone(), 1)
|
|
.unwrap();
|
|
b.ledger
|
|
.replay_bill(1, vendor, d(0, 1, 1), d(10000, 1, 1), line, 1)
|
|
.unwrap();
|
|
let mut add = |code: &str, ty| b.ledger.add_account(code, code, ty, None, false).unwrap();
|
|
let equipment = add("1500", AccountType::Asset);
|
|
let accum = add("1501", AccountType::Asset);
|
|
let depreciation = add("6100", AccountType::Expense);
|
|
let asset = |purchase_date: NaiveDate, useful_life_months: u32| ledger_core::NewAsset {
|
|
description: "Late".into(),
|
|
purchase_date,
|
|
cost: usd(Decimal::new(120000, 2)),
|
|
salvage_value: usd(Decimal::ZERO),
|
|
useful_life_months,
|
|
cost_account: equipment,
|
|
accum_depr_account: accum,
|
|
expense_account: depreciation,
|
|
};
|
|
for (date, life) in [
|
|
(d(9999, 1, 1), 60),
|
|
(d(2026, 1, 1), 120_000),
|
|
(d(0, 1, 1), 1),
|
|
] {
|
|
assert_eq!(
|
|
b.ledger.register_asset(asset(date, life)).unwrap_err(),
|
|
if date.year() == 0 {
|
|
LedgerError::DateOutOfRange(date)
|
|
} else {
|
|
LedgerError::AssetDateOverflow
|
|
}
|
|
);
|
|
b.ledger.replay_register_asset(asset(date, life)).unwrap();
|
|
}
|
|
// Replay keeps main's one date rule: the life's end is a date chrono
|
|
// holds.
|
|
assert_eq!(
|
|
b.ledger
|
|
.replay_register_asset(asset(d(262_142, 1, 1), 12))
|
|
.unwrap_err(),
|
|
LedgerError::AssetDateOverflow
|
|
);
|
|
let id = b
|
|
.ledger
|
|
.replay_register_asset(asset(d(2026, 1, 1), 12))
|
|
.unwrap();
|
|
let fix = |purchase_date: NaiveDate| ledger_core::AssetCorrection {
|
|
cost: usd(Decimal::new(120000, 2)),
|
|
salvage_value: usd(Decimal::ZERO),
|
|
useful_life_months: 60,
|
|
purchase_date,
|
|
};
|
|
assert_eq!(
|
|
b.ledger.correct_asset(id, fix(d(9999, 1, 1))).unwrap_err(),
|
|
LedgerError::AssetDateOverflow
|
|
);
|
|
b.ledger
|
|
.replay_correct_asset(id, fix(d(9999, 1, 1)))
|
|
.unwrap();
|
|
assert_eq!(b.ledger.get_asset(id).unwrap().purchase_date, d(9999, 1, 1));
|
|
// A disposal dated past the calendar.
|
|
let proceeds = usd(Decimal::ZERO);
|
|
assert_eq!(
|
|
b.ledger
|
|
.dispose_asset(id, d(10000, 1, 1), proceeds)
|
|
.unwrap_err(),
|
|
LedgerError::DateOutOfRange(d(10000, 1, 1))
|
|
);
|
|
b.ledger
|
|
.replay_dispose_asset(id, d(10000, 1, 1), proceeds)
|
|
.unwrap();
|
|
}
|
|
|
|
/// An amount larger than a line may be is refused wherever a command takes
|
|
/// one, so every sum the books make of them is exact.
|
|
#[test]
|
|
fn amounts_larger_than_a_line_are_refused_everywhere() {
|
|
let mut b = books();
|
|
let big = too_big();
|
|
// A draft line, as it is added; replayed as an older version wrote it.
|
|
let e = b.ledger.try_create_entry(d(2026, 1, 1), "big").unwrap();
|
|
assert_eq!(
|
|
b.ledger
|
|
.add_line(e, b.expense, Side::Debit, usd(big))
|
|
.unwrap_err(),
|
|
LedgerError::AmountOutOfRange
|
|
);
|
|
for a in [big, Decimal::MAX, -Decimal::MAX] {
|
|
b.ledger
|
|
.replay_add_line(e, b.expense, Side::Debit, usd(a))
|
|
.unwrap();
|
|
}
|
|
assert_eq!(b.ledger.get_entry(e).unwrap().lines().len(), 3);
|
|
// Its post refuses it, never a panic.
|
|
assert!(b.ledger.post_entry(e).is_err());
|
|
// Document lines, and their replay.
|
|
let customer = b.ledger.add_customer("Client").unwrap();
|
|
let lines = |a: Decimal| {
|
|
vec![
|
|
DocumentLine {
|
|
description: "a".into(),
|
|
amount: a,
|
|
},
|
|
DocumentLine {
|
|
description: "b".into(),
|
|
amount: Decimal::ONE,
|
|
},
|
|
]
|
|
};
|
|
for a in [big, Decimal::MAX, Decimal::new(1, 11)] {
|
|
assert!(matches!(
|
|
b.ledger
|
|
.create_invoice(customer, d(2026, 1, 1), d(2026, 2, 1), lines(a)),
|
|
Err(LedgerError::ValueOutOfRange(_))
|
|
));
|
|
}
|
|
// Replayed as journaled: whatever its lines, a document is restored;
|
|
// a total past exact arithmetic is refused where it is computed.
|
|
for (id, a) in [(1, big), (2, Decimal::new(1, 11)), (3, Decimal::MAX)] {
|
|
b.ledger
|
|
.replay_invoice(id, customer, d(2026, 1, 1), d(2026, 2, 1), lines(a), id)
|
|
.unwrap();
|
|
}
|
|
assert_eq!(
|
|
b.ledger.get_invoice(2).unwrap().total(),
|
|
Ok(Decimal::new(100_000_000_001, 11))
|
|
);
|
|
assert!(matches!(
|
|
b.ledger.get_invoice(3).unwrap().total(),
|
|
Err(LedgerError::TooLargeToCompute(_))
|
|
));
|
|
assert!(matches!(
|
|
b.ledger.ar_aging(d(2026, 3, 1)),
|
|
Err(LedgerError::TooLargeToCompute(_))
|
|
));
|
|
// A recurring template's lines.
|
|
let recurring = NewRecurring {
|
|
description: "x".into(),
|
|
lines: vec![
|
|
(b.expense, Side::Debit, usd(Decimal::MAX)),
|
|
(b.expense, Side::Debit, usd(Decimal::ONE)),
|
|
(b.cash, Side::Credit, usd(Decimal::ONE)),
|
|
],
|
|
frequency: Frequency::Monthly,
|
|
start: d(2026, 1, 1),
|
|
end: None,
|
|
};
|
|
assert_eq!(
|
|
b.ledger.register_recurring(recurring.clone()).unwrap_err(),
|
|
LedgerError::AmountOutOfRange
|
|
);
|
|
// On replay, one whose debits overflow Decimal is refused (no version
|
|
// could have written it: main panicked on it), never a panic; one past
|
|
// the line limit that balances is accepted.
|
|
assert!(matches!(
|
|
b.ledger.replay_register_recurring(recurring),
|
|
Err(LedgerError::TooLargeToCompute(_))
|
|
));
|
|
let half = Decimal::MAX / Decimal::TWO;
|
|
b.ledger
|
|
.replay_register_recurring(NewRecurring {
|
|
description: "x".into(),
|
|
lines: vec![
|
|
(b.expense, Side::Debit, usd(half)),
|
|
(b.cash, Side::Credit, usd(half)),
|
|
],
|
|
frequency: Frequency::Monthly,
|
|
start: d(2026, 1, 1),
|
|
end: None,
|
|
})
|
|
.unwrap();
|
|
// Payroll figures, run and replayed.
|
|
let payroll = |fed: Decimal, ss: Decimal| PayrollLine {
|
|
employee_name: "Dana".into(),
|
|
employee: None,
|
|
gross_pay: Decimal::ONE,
|
|
federal_withholding: fed,
|
|
state_withholding: fed,
|
|
ss_employee: Decimal::ZERO,
|
|
medicare_employee: Decimal::ZERO,
|
|
ss_employer: ss,
|
|
medicare_employer: Decimal::ONE,
|
|
other_deductions: Decimal::ZERO,
|
|
};
|
|
for line in [
|
|
payroll(Decimal::MAX, Decimal::ONE),
|
|
payroll(Decimal::ZERO, big),
|
|
] {
|
|
assert!(matches!(
|
|
b.ledger.run_payroll(d(2026, 1, 31), vec![line], b.cash),
|
|
Err(LedgerError::ValueOutOfRange(_))
|
|
));
|
|
}
|
|
// Replayed as journaled, sub-cent and past the limit alike; a net
|
|
// past exact arithmetic is refused where it is computed.
|
|
let fine = payroll(Decimal::new(1, 12), Decimal::ONE);
|
|
let huge = payroll(Decimal::ZERO, big);
|
|
b.ledger
|
|
.replay_payroll_run(1, d(2026, 1, 31), vec![fine, huge], 1)
|
|
.unwrap();
|
|
let mut over = payroll(Decimal::ZERO, Decimal::ONE);
|
|
over.gross_pay = -Decimal::MAX;
|
|
over.federal_withholding = Decimal::MAX;
|
|
assert!(matches!(
|
|
over.net_pay(),
|
|
Err(LedgerError::TooLargeToCompute(_))
|
|
));
|
|
assert!(
|
|
ledger_core::payroll::check_payroll_ranges(&[payroll(MAX_LINE_AMOUNT, MAX_LINE_AMOUNT)])
|
|
.is_ok()
|
|
);
|
|
// A statement balance in a reconciliation.
|
|
for balance in [-Decimal::MAX, big, -big] {
|
|
assert!(matches!(
|
|
b.ledger
|
|
.reconciliation_report(b.cash, d(2026, 1, 31), balance),
|
|
Err(LedgerError::ValueOutOfRange(_))
|
|
));
|
|
}
|
|
let report = b
|
|
.ledger
|
|
.reconciliation_report(b.cash, d(2026, 1, 31), -MAX_LINE_AMOUNT)
|
|
.unwrap();
|
|
assert_eq!(report.difference, MAX_LINE_AMOUNT);
|
|
// A payout's lines and its deposit.
|
|
let payout = |revenue: Decimal, deposit: Decimal| ledger_core::Payout {
|
|
deposit_account: b.cash,
|
|
deposit,
|
|
revenue: vec![ledger_core::PayoutLine {
|
|
account: b.revenue,
|
|
amount: revenue,
|
|
class: None,
|
|
}],
|
|
fees: vec![],
|
|
adjustments: vec![],
|
|
};
|
|
for p in [payout(big, big), payout(Decimal::ONE, -Decimal::MAX)] {
|
|
assert!(matches!(
|
|
ledger_core::payout_plan(&p, b.ledger.chart()),
|
|
Err(LedgerError::ValueOutOfRange(_))
|
|
));
|
|
}
|
|
assert!(
|
|
ledger_core::payout_plan(&payout(MAX_LINE_AMOUNT, MAX_LINE_AMOUNT), b.ledger.chart())
|
|
.is_ok()
|
|
);
|
|
// A contributor's basis.
|
|
let basis = |b: Decimal| ledger_core::TaxBasis {
|
|
rule: ledger_core::TaxBasisRule::Carryover,
|
|
contributor_basis: Some(b),
|
|
};
|
|
assert!(basis(big).check().is_err());
|
|
assert!(basis(MAX_LINE_AMOUNT).check().is_ok());
|
|
// On replay: every journaled basis passed check_journaled.
|
|
let cents_max = Decimal::MAX.round_dp(2) / Decimal::ONE_HUNDRED;
|
|
assert!(basis(big.round_dp(2)).check_journaled().is_ok());
|
|
assert!(basis(cents_max.round_dp(2)).check_journaled().is_ok());
|
|
assert!(basis(-Decimal::ONE).check_journaled().is_err());
|
|
// A party's share of an entry.
|
|
let share = |a: Decimal| {
|
|
vec![ledger_core::PartyShare {
|
|
party: 1,
|
|
share: ledger_core::shares::Share::Amount(a),
|
|
}]
|
|
};
|
|
let known = |_| true;
|
|
assert!(ledger_core::shares::check_shares(&share(big.round_dp(2)), known).is_err());
|
|
assert!(ledger_core::shares::check_shares(&share(MAX_LINE_AMOUNT), known).is_ok());
|
|
// On replay: every journaled share passed check_shares_journaled.
|
|
assert!(ledger_core::shares::check_shares_journaled(&share(big.round_dp(2)), known).is_ok());
|
|
assert!(ledger_core::shares::check_shares_journaled(&share(Decimal::MAX), known).is_ok());
|
|
assert!(ledger_core::shares::check_shares_journaled(&share(Decimal::ZERO), known).is_err());
|
|
}
|
|
|
|
/// The ledger-level pairs for a basis and shares: the command refuses past
|
|
/// the limit; replay of the old line is accepted, and what it feeds (the
|
|
/// register, the shares' resolution) refuses what it can't compute.
|
|
#[test]
|
|
fn replayed_bases_and_shares_past_the_limit_are_accepted() {
|
|
let mut b = books();
|
|
let mut add = |code: &str, ty| b.ledger.add_account(code, code, ty, None, false).unwrap();
|
|
let equipment = add("1500", AccountType::Asset);
|
|
let accum = add("1501", AccountType::Asset);
|
|
let depreciation = add("6100", AccountType::Expense);
|
|
// Decimal's largest is a whole number of cents, as every version
|
|
// required of a basis and a share.
|
|
let cents_max = Decimal::MAX;
|
|
let basis = ledger_core::TaxBasis {
|
|
rule: ledger_core::TaxBasisRule::Carryover,
|
|
contributor_basis: Some(cents_max),
|
|
};
|
|
for _ in 0..2 {
|
|
let id = b
|
|
.ledger
|
|
.register_asset(ledger_core::NewAsset {
|
|
description: "Laptop".into(),
|
|
purchase_date: d(2026, 1, 1),
|
|
cost: usd(Decimal::new(240000, 2)),
|
|
salvage_value: usd(Decimal::ZERO),
|
|
useful_life_months: 24,
|
|
cost_account: equipment,
|
|
accum_depr_account: accum,
|
|
expense_account: depreciation,
|
|
})
|
|
.unwrap();
|
|
assert!(matches!(
|
|
b.ledger.set_asset_tax_basis(id, basis),
|
|
Err(LedgerError::InvalidTaxBasis(_))
|
|
));
|
|
b.ledger.replay_set_asset_tax_basis(id, basis).unwrap();
|
|
assert_eq!(b.ledger.get_asset(id).unwrap().tax, Some(basis));
|
|
}
|
|
assert!(matches!(
|
|
ledger_core::fixed_asset_register(&b.ledger, d(2026, 12, 31)),
|
|
Err(LedgerError::TooLargeToCompute(_))
|
|
));
|
|
let a = b
|
|
.ledger
|
|
.add_party("A", &[ledger_core::Role::Member])
|
|
.unwrap();
|
|
let c = b
|
|
.ledger
|
|
.add_party("C", &[ledger_core::Role::Member])
|
|
.unwrap();
|
|
let e = b.ledger.try_create_entry(d(2026, 3, 1), "rent").unwrap();
|
|
b.ledger
|
|
.add_line(e, b.expense, Side::Debit, usd(Decimal::TEN))
|
|
.unwrap();
|
|
b.ledger
|
|
.add_line(e, b.cash, Side::Credit, usd(Decimal::TEN))
|
|
.unwrap();
|
|
b.ledger.post_entry(e).unwrap();
|
|
let shares = [a, c].map(|party| ledger_core::PartyShare {
|
|
party,
|
|
share: ledger_core::shares::Share::Amount(cents_max),
|
|
});
|
|
assert!(matches!(
|
|
b.ledger.set_entry_parties(e, &shares),
|
|
Err(LedgerError::InvalidParty(_))
|
|
));
|
|
b.ledger.replay_set_entry_parties(e, &shares).unwrap();
|
|
assert_eq!(b.ledger.entry_parties(e), &shares);
|
|
let money = ledger_core::parties::money_accounts(&b.ledger, &[b.cash]);
|
|
let why = ledger_core::shares::resolve(b.ledger.get_entry(e).unwrap(), &shares, &money, &[])
|
|
.unwrap_err();
|
|
assert!(why.contains("too large to compute"), "{why}");
|
|
// Replay still checks what every version checked.
|
|
assert_eq!(
|
|
b.ledger.replay_set_entry_parties(99, &shares).unwrap_err(),
|
|
LedgerError::UnknownEntry(99)
|
|
);
|
|
}
|
|
|
|
/// A replayed payment is as journaled: no bound but exact arithmetic (a
|
|
/// paid amount past it is refused, never wrapped). The command's bound is
|
|
/// the balance (Overpayment).
|
|
#[test]
|
|
fn replayed_payments_are_as_journaled() {
|
|
let mut b = books();
|
|
let customer = b.ledger.add_customer("Client").unwrap();
|
|
let invoice = b
|
|
.ledger
|
|
.create_invoice(
|
|
customer,
|
|
d(2026, 1, 1),
|
|
d(2026, 2, 1),
|
|
vec![DocumentLine {
|
|
description: "work".into(),
|
|
amount: Decimal::new(10000, 2),
|
|
}],
|
|
)
|
|
.unwrap();
|
|
assert!(matches!(
|
|
b.ledger
|
|
.receive_payment(invoice, d(2026, 1, 15), too_big(), b.cash),
|
|
Err(LedgerError::Overpayment(..))
|
|
));
|
|
b.ledger
|
|
.replay_invoice_payment(invoice, too_big(), 98)
|
|
.unwrap();
|
|
b.ledger
|
|
.replay_invoice_payment(invoice, Decimal::MAX - too_big(), 99)
|
|
.unwrap();
|
|
assert_eq!(
|
|
b.ledger.get_invoice(invoice).unwrap().amount_paid,
|
|
Decimal::MAX
|
|
);
|
|
assert!(matches!(
|
|
b.ledger.replay_invoice_payment(invoice, Decimal::ONE, 100),
|
|
Err(LedgerError::TooLargeToCompute(_))
|
|
));
|
|
// Refused before anything changed.
|
|
assert_eq!(
|
|
b.ledger.get_invoice(invoice).unwrap().amount_paid,
|
|
Decimal::MAX
|
|
);
|
|
}
|
|
|
|
/// A disposal's proceeds are a line of its entry, and its date a day of
|
|
/// the calendar, for a new disposal; a replayed one is as journaled, and
|
|
/// its amounts (disposal_amounts, pure) are computed, never a panic.
|
|
#[test]
|
|
fn disposal_proceeds_and_dates_are_bounded() {
|
|
let mut b = books();
|
|
let mut add = |code: &str, ty| b.ledger.add_account(code, code, ty, None, false).unwrap();
|
|
let equipment = add("1500", AccountType::Asset);
|
|
let accum = add("1501", AccountType::Asset);
|
|
let depreciation = add("6100", AccountType::Expense);
|
|
let laptop = || ledger_core::NewAsset {
|
|
description: "Laptop".into(),
|
|
purchase_date: d(2026, 1, 1),
|
|
cost: usd(Decimal::new(240000, 2)),
|
|
salvage_value: usd(Decimal::ZERO),
|
|
useful_life_months: 24,
|
|
cost_account: equipment,
|
|
accum_depr_account: accum,
|
|
expense_account: depreciation,
|
|
};
|
|
let id = b.ledger.register_asset(laptop()).unwrap();
|
|
for proceeds in [Decimal::MAX, too_big()] {
|
|
assert_eq!(
|
|
b.ledger
|
|
.dispose_asset(id, d(2026, 6, 30), usd(proceeds))
|
|
.unwrap_err(),
|
|
LedgerError::AmountOutOfRange
|
|
);
|
|
let asset = b.ledger.get_asset(id).unwrap().clone();
|
|
let amounts = ledger_core::disposal_amounts(&asset, d(2026, 6, 30), usd(proceeds)).unwrap();
|
|
assert_eq!(amounts.gain_loss, proceeds - amounts.book_value);
|
|
}
|
|
assert_eq!(
|
|
b.ledger
|
|
.dispose_asset(id, NaiveDate::MAX, usd(Decimal::ONE))
|
|
.unwrap_err(),
|
|
LedgerError::DateOutOfRange(NaiveDate::MAX)
|
|
);
|
|
// Disposal amounts at chrono's last day: computed.
|
|
let asset = b.ledger.get_asset(id).unwrap().clone();
|
|
let amounts = ledger_core::disposal_amounts(&asset, NaiveDate::MAX, usd(Decimal::ONE)).unwrap();
|
|
assert_eq!(amounts.book_value, Decimal::ZERO);
|
|
b.ledger
|
|
.dispose_asset(id, d(2026, 6, 30), usd(MAX_LINE_AMOUNT))
|
|
.unwrap();
|
|
// Replayed past both bounds: accepted as journaled.
|
|
let old = b.ledger.register_asset(laptop()).unwrap();
|
|
b.ledger
|
|
.replay_dispose_asset(old, NaiveDate::MAX, usd(Decimal::MAX))
|
|
.unwrap();
|
|
assert!(matches!(
|
|
b.ledger.get_asset(old).unwrap().status,
|
|
ledger_core::AssetStatus::Disposed { date, .. } if date == NaiveDate::MAX
|
|
));
|
|
// Replay keeps what every version checked: no disposal twice, none
|
|
// before the purchase, no negative proceeds.
|
|
assert_eq!(
|
|
b.ledger
|
|
.replay_dispose_asset(old, NaiveDate::MAX, usd(Decimal::ONE))
|
|
.unwrap_err(),
|
|
LedgerError::AssetAlreadyDisposed(old)
|
|
);
|
|
let early = b.ledger.register_asset(laptop()).unwrap();
|
|
assert!(matches!(
|
|
b.ledger
|
|
.replay_dispose_asset(early, d(2025, 1, 1), usd(Decimal::ONE)),
|
|
Err(LedgerError::DisposalBeforePurchase(_))
|
|
));
|
|
assert!(matches!(
|
|
b.ledger
|
|
.replay_dispose_asset(early, d(2026, 2, 1), usd(-Decimal::ONE)),
|
|
Err(LedgerError::NegativeProceeds(_))
|
|
));
|
|
}
|
|
|
|
/// The bounds are the line limit exactly: a new draft line (base or
|
|
/// foreign) and a recurring template's line may be as large as a line, and
|
|
/// no larger; a replayed one past it is accepted as journaled.
|
|
#[test]
|
|
fn the_bound_is_the_line_limit_itself() {
|
|
let mut b = books();
|
|
let e = b.ledger.try_create_entry(d(2026, 1, 1), "max").unwrap();
|
|
for amount in [MAX_LINE_AMOUNT, -MAX_LINE_AMOUNT] {
|
|
b.ledger
|
|
.add_line(e, b.cash, Side::Debit, usd(amount))
|
|
.unwrap();
|
|
}
|
|
for amount in [too_big().round_dp(2), -too_big().round_dp(2)] {
|
|
assert_eq!(
|
|
b.ledger
|
|
.add_line(e, b.cash, Side::Debit, usd(amount))
|
|
.unwrap_err(),
|
|
LedgerError::AmountOutOfRange
|
|
);
|
|
}
|
|
// A foreign line: its base amount, foreign x rate, is what's bounded.
|
|
b.ledger
|
|
.add_line_fx(
|
|
e,
|
|
b.cash,
|
|
Side::Debit,
|
|
Currency::EUR,
|
|
MAX_LINE_AMOUNT,
|
|
Decimal::ONE,
|
|
)
|
|
.unwrap();
|
|
assert_eq!(
|
|
b.ledger
|
|
.add_line_fx(
|
|
e,
|
|
b.cash,
|
|
Side::Debit,
|
|
Currency::EUR,
|
|
MAX_LINE_AMOUNT,
|
|
Decimal::TWO
|
|
)
|
|
.unwrap_err(),
|
|
LedgerError::AmountOutOfRange
|
|
);
|
|
// Replayed as an earlier version booked them: past the limit too.
|
|
for amount in [too_big(), -too_big(), Decimal::MAX] {
|
|
b.ledger
|
|
.replay_add_line_fx(
|
|
e,
|
|
b.cash,
|
|
Side::Debit,
|
|
usd(amount),
|
|
Currency::EUR,
|
|
Decimal::ONE,
|
|
)
|
|
.unwrap();
|
|
b.ledger
|
|
.replay_add_line(e, b.cash, Side::Debit, usd(amount))
|
|
.unwrap();
|
|
}
|
|
assert_eq!(b.ledger.get_entry(e).unwrap().lines().len(), 9);
|
|
let recurring = |a: Decimal| NewRecurring {
|
|
description: "max".into(),
|
|
lines: vec![
|
|
(b.expense, Side::Debit, usd(a)),
|
|
(b.cash, Side::Credit, usd(a)),
|
|
],
|
|
frequency: Frequency::Monthly,
|
|
start: d(2026, 1, 1),
|
|
end: None,
|
|
};
|
|
b.ledger
|
|
.register_recurring(recurring(MAX_LINE_AMOUNT))
|
|
.unwrap();
|
|
assert_eq!(
|
|
b.ledger
|
|
.register_recurring(recurring(too_big()))
|
|
.unwrap_err(),
|
|
LedgerError::AmountOutOfRange
|
|
);
|
|
let old = b
|
|
.ledger
|
|
.replay_register_recurring(recurring(too_big()))
|
|
.unwrap();
|
|
// Its occurrences generate drafts as journaled; their post refuses.
|
|
let draft = b
|
|
.ledger
|
|
.replay_generate_recurring(old, d(2026, 1, 1))
|
|
.unwrap();
|
|
assert_eq!(
|
|
b.ledger.get_entry(draft).unwrap().lines()[0].amount.amount,
|
|
too_big()
|
|
);
|
|
assert_eq!(
|
|
b.ledger.post_entry(draft).unwrap_err(),
|
|
LedgerError::AmountOutOfRange
|
|
);
|
|
}
|