Repository navigation
fix(validate)!: pad from one shared plan as beancount does, and drop E2004 - #2898
Merged
Merged
Conversation
…eancount does The validator padded its own inventories with a second copy of the pad rule in `rustledger_booking::process_pads`, and the two drifted from each other and from beancount (#2896). Both now go through one `rustledger_booking::PadTracker`, beancount's `ops/pad.py` rule: the latest pad dated before a balance, once per currency, a zero difference using the currency up without using the pad, and a superseded pad never used again. Each side keeps its own inventories, and a new drift guard (`pad_parity_test`) compares them end to end on the #2896 shapes. - An unopened target's own postings count: bean-query 100 / -130, where it padded 70 / -100. One its postings already satisfy is not padded, and the pad is unused. - A balance on an unopened account is compared (E2001). - `pad`, `balance 0`, `balance 10` is E2003 plus E2001. - A superseded pad no longer pads a later balance (E2003 plus E2001). - A pad or balance before the account's later open says the account is inactive, not never opened. WASM cache v83 (v82 is #2893's). Closes #2896 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Contributor
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
…E2004 The validator now takes its padding from `rustledger_booking::plan_pads`, the computation `process_pads` is built on, instead of a rule of its own, and adds each padding entry to its inventories at the `pad`, where beancount dates it. A balance on the pad's source between the pad and the balance it satisfies no longer fails falsely. BREAKING CHANGE: E2004 (multiple pads for one balance) is removed, with `ErrorCode::MultiplePadForBalance`. A superseded pad is an unused pad (E2003), as in beancount, and E2004 fired falsely on a pad that had already padded another currency. The code is retired in the docs. - A pad amount that cannot be computed or applied is reported at its balance, which is not compared, as before. - One not-yet-open wording for postings, pads and balances: "is inactive on D (not opened until O)". - `account_inventory` uses the entry API. - Drift guard and integration tests cover the pad-date shape and the currency case (p15), both clean in bean-check. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`plan_pads` summed each padded balance's subtree by scanning every account, so `rledger check` and the LSP, which now run it on any ledger with a pad, were quadratic: 40k accounts with a pad and a balance each took 46 s. It now keeps a lexical index of its accounts and visits a subtree by range query, through `rustledger_core::for_each_strict_subaccount`, which the validator's `sum_account_subtree` now shares. It also keeps units per currency instead of lot inventories, the only thing a pad reads. A regression test counts the inventories read: 2,000 for 2,000 padded balances, where the scan read 4,003,999. Also corrects the #2895 CHANGELOG entry (no E2004, both padding halves land) and the PadCorrect spec comment (padding is dated at the pad). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Nov 9, 2026
Resolves the WASM cache and CHANGELOG conflicts with #2897: v82 is #2897's (loader v62), and this branch's note moves to v83 over loader v62. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tches The complexity test counted matches inside `subtree_units`, so a plain scan that adds only the matching accounts passed it. Account totals are now a newtype whose `get` and iteration count each account where it is read: 2,000 reads for 2,000 padded balances, and 4,003,999 with that scan swapped in. A core test pins `for_each_strict_subaccount` on 8,655 generated names (deep trees, Unicode, prefix siblings such as Assets:A / Assets:AB, the same paths under several roots): it visits exactly the strict subtree, and reads few keys per query through a counting `Borrow<str>` key, so a filtered full scan in core fails it (8,655 keys per query). The function is generic over the key for that. Also notes that units alone cannot answer beancount's pad-at-cost check (#2901), and that `PadInventories::add` skips `Inventory::add`'s near-ceiling check (#2554). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolves the WASM cache and CHANGELOG conflicts with #2903: v84 is #2872's (loader v63), and this branch's note moves to v85 over loader v63 (v83 was never released). Both sides of the CHANGELOG are kept. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Nov 9, 2026
robcohen
added a commit
that referenced
this pull request
Nov 11, 2026
…s beancount does (#2920) * fix(validate)!: pad parents, sub-accounts, tolerances and cost lots as beancount does Beancount pads each account with a `pad` on its own (`ops/pad.py`): the group sees balances on the account and its sub-accounts, measures them against the real postings of the account and its sub-accounts plus its own padding only, leaves a difference within the balance's tolerance alone, and reports `Attempt to pad an entry with cost` once per lot held at cost in the padded currency. `rustledger_booking::plan_pads`, which the validator, the balance view, BQL and `#balances` all read, now applies that rule: - A pad on a parent pads it for a balance on a sub-account, and such a balance uses up the parent pad's currency. - A pad counts no other pad's padding, into a sub-account or out of the account as a source. - A difference within the balance's tolerance is not padded (an `Unused Pad entry`), so `balance_tolerance` moves next to the rule in `rustledger-booking`, and the pad functions take the ledger's `tolerance_multiplier`. - Padding a currency held at cost is the new `E2005`, checked by the validator against its booked lots; the padding is still inserted. The two pad-date rows of #2901 were already fixed by #2898; they are pinned in `pad_parity_test`, which now covers every #2901 shape against bean-check / bean-query 3.2.3. On the 1,045 in-tree and compatibility ledgers, `rledger check`, `report balances`, BQL balances and `#balances` are unchanged. WASM cache v86: the `Ledger` payload gains the multiplier, and cached error lists change. The loader cache is unaffected. Closes #2901 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(validate): keep pad groups linear, and report pads at cost and tolerances as beancount does Review round 1 of #2920: - Each pad group keeps a running total of its real postings, as beancount keeps `pad_balance`: seeded once when the group's first `pad` comes, then moved by each posting (O(depth)). Summing the subtree at every balance made a parent pad with balances on many sub-accounts quadratic. A new test counts the accounts read and fails on the per-balance walk. - `E2005` skips the subtree walk for a currency never booked at cost, counts positions as one merged inventory does (a lot held in two sub-accounts is one, as in beancount), and its message shows what the pad group holds (`PlannedPadding::held`), not other pads' padding. - `pad_parity_test` takes each shape's `tolerance_multiplier` and adds the multiplier-2 shape, lots in sub-accounts, the merged lot, the group-only message, and a balance just beyond the tolerance. The loader's balance view gets tests for `tolerance_multiplier` and for `inferred_tolerance_default`, which beancount ignores here. All of these were checked against bean-check / bean-query 3.2.3. - Held FFI options whose `tolerance_multiplier` is not a decimal are reported and replaced by the default, which `info()` then echoes. - `scripts/compat-values.py` counts `E2005` as a pad error. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(validate): keep pads at cost, many currencies and overflowed totals linear, and print E2005 as beancount does Review round 2 of #2920: - The "pad an entry with cost" check reads only accounts a posting at cost was booked to, per currency, under the padded account: a lot at cost elsewhere in the ledger no longer makes every padded balance walk the subtree. `rustledger_booking::plan_pads` copies the group's holdings (`PlannedPadding::held`, now an `Option`) only when such an account sits under the group, and the validator moves it rather than cloning it. Guard tests count the accounts read. - A pad group keeps its running totals in hash maps, so a group holding many currencies stays linear, and a total that leaves `Decimal`'s range carries on in `BigDecimal` instead of re-summing the subtree at every later balance. Guard tests for both. - `python_inventory_str` / `python_position_str` move from `rustledger-query` to `rustledger-core`, and the E2005 message uses them: the inventory is sorted and printed as bean-check prints it. - `rustledger_core::strict_subaccounts`, the range query behind `for_each_strict_subaccount`, as an iterator. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(booking): report pads at cost from each pad group's own inventory, as beancount's pad_balance Review round 3 of #2920. Each pad group now keeps beancount's `pad_balance` itself: a running inventory of the real postings under its account and its own padding, positions (lots at cost included) merged as `Inventory.add_position` merges them and kept in the order they came. Groups exist from the start of the walk, so each posting updates the groups among its account's ancestors, O(depth). "Attempt to pad an entry with cost" (E2005) is read from that inventory by the plan (`PlannedPadding::at_cost`, a new `PaddedAtCost`) and printed through the canonical `python_inventory_str`, so ties come out in the order bean-check prints them. The validator only reports it, and `process_pads` reports it too. Gone: the validator's `cost_accounts` index, `lots_at_cost`, `shown_balance`, and the plan's `held` copy and cost-account gate. - Guards count the work (group updates and printed positions) on the #2920 review's scenarios A, E, F, F2 and H, and a lot outside the group computes nothing for it. - Parity shapes for the four tie orders, checked against bean-check. - The overflow-and-back total stays exact, a documented deviation from beancount's 28-digit context, pinned by a test. - `sell_gains` prints its inventories through `python_inventory_str`. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(booking): enter a transaction's sub-accounts in beancount's account order, keep a joined lot's latest cost, and count inventory work Review round 4 of #2920: - Beancount collects a pad group's postings account by account, in the order `realization.postings_by_account` first met each account, and stable-sorts them by date, type and line, which one transaction's postings share. The plan now ranks accounts as the walk first meets them (opens, closes, balances, notes, documents, a pad's account then source, custom account values, postings as written) and applies each transaction's postings in that rank order, so ties print as bean-check prints them. - A joined lot keeps the cost it was last written with, as `add_amount` rebuilds the position with the incoming cost. - The linearity guards count work where it happens: every `GroupInventory::add`, every lot check and every printed position. A mutant that rebuilds the inventory at each padding now fails them. - The validator reports E2005 before the overflow early return, so a balance where one group cannot be represented and another pads at cost reports it, as `process_pads` does. - `strict_subaccounts` is gone again (no caller), and the `for_each_strict_subaccount` doc no longer names `plan_pads`. The `process_pads` and `PadResult::errors` docs name E2005. New parity shapes, checked against bean-check 3.2.3: both open orders, accounts first met through a posting, and a joined lot's latest cost. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(booking): rank a pad group's accounts in beancount's entry order Review round 5 of #2920. Beancount's `realization.postings_by_account` meets accounts in its entry order, `(date, SORT_ORDER, lineno)`, where a `pad` ranks with the date's transactions, notes and customs. The plan walked in booking order, which puts a same-date pad first, so a pad written after a note met its accounts too early. - New `rustledger_core::beancount_entry_sort_key`, beancount's `entry_sortkey` with the source location standing for the line. - `plan_pads` takes each directive's `SourcePosition` and ranks the accounts in one pass in that order, before the booking-order walk. The validator passes its spans; `merge_with_padding_spanned` and `Ledger::balance_view` pass theirs through the new `process_pads_spanned`; plain `process_pads` falls back to input order. - Parity shapes for every registration arm (note, document, balance, a pad's account and source, custom, close, posting) and for a note, a transaction and a custom before a same-date pad, checked against bean-check 3.2.3. A loader test pins the located path. - `see` looks the account up before cloning it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(wasm,ffi): pad and validate with source locations on every surface The FFI and WASM pad expansion went through plain `process_pads`, which ranks accounts by stream order: on a loaded (booking-ordered) ledger a same-date `pad` met its accounts before a note written above it, so an "Attempt to pad an entry with cost" could list tied positions in a different order from `rledger check` on the same ledger. - `rustledger_booking::process_pads_at` pads plain directives with a parallel list of `SourcePosition`s; `process_pads` documents what its input order promises (the padding never depends on it; only E2005 tie order does, and only a source-ordered stream suits it). - WASM: `helpers::pad_expansion` pads with the kept spans for both `expandPads` surfaces, and the WASM ledgers validate with their spans as `rledger check` and the FFI do, so their errors also carry their own lines (cached `ParsedLedger` errors change, under WASM v91). - ffi-wasi `expand_pads` takes a `position_of` for its tags (`line_position`, `file_line_position`). - Drift guard `test_pad_at_cost_ties_agree_across_surfaces`: one ledger with a note above a same-date pad answers bean-check's `(1 CCC, 1 DDD, ...)` through the validator, `process_pads_spanned`, the WASM expansion and WASM validation, and pads the same through `balance_view`, the WASM expansion and ffi-wasi `expand_pads`. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(booking,wasm): rank pad accounts by beancount's line number, and keep a restored WASM ledger's lines Review round 6 of #2920: - Beancount's `entry_sortkey` is `(date, SORT_ORDER, lineno)` with the line number whichever file it is in, and line 0 for a plugin's entry. `SourcePosition` is now that line. The validator reads it through the new `ValidationOptions::source_lines` (`SourceLines`), which `rustledger_loader::source_lines` builds from a source map; the loader and the LSP's multi-file path set it. Without it, a source directive's offset stands in and a plugin's directive is 0. Loader tests pin both shapes checked against bean-check 3.2.3: an account opened on line 2 of an included file before one opened on line 5 of the main file (whatever the byte offsets), and an `auto_accounts` open first. - `process_pads_spanned` is gone: the merges discard errors, and only `process_pads_at` (the WASM expansions) reports them with lines. - The WASM `Ledger` keeps each directive's line (`directive_lines`) and stores it in its cache payload, so `fromCache(...).expandPads()` answers as `getErrors()` does. `from_files` delegates to a native `from_file_map`, so the drift guard covers the multi-file `Ledger` before and after a cache round trip. - The drift guard's ffi-wasi part is native-only, so `wasm-pack test --node` compiles again. - ffi-wasi `expand_pads` is back to main's API (padding only, which no input order changes). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(booking,loader,ffi): order pad ties by plugin line and file, and validate the FFI and WASM with the ledger's options Review round 7 of #2920: - The FFI component's `validate` and `load` validated with a default `ValidationOptions`, which ignored `tolerance_multiplier`. ffi-wasi's `LoadResult` now carries `validation_options`, built with the canonical `validation_options_from_options` and the source map's positions, and the component validates with them. The WASM validation had the same default set and now builds its options the same way. Drift guards compare both against `rledger check` with `tolerance_multiplier` 2 and 99.97 held: `Unused Pad entry` with a pad before `balance 100.00 USD`, and nothing without it, as bean-check 3.2.3 reports. - `SourcePosition` is now a struct: the line and the file's place in the load. A plugin's directive has the line the plugin gave it (read from the source map's placeholder), ranked ahead of every file, as `auto_accounts` and `currency_accounts` put their entries ahead of the parsed ones. A source file's directive is ranked by its file id, so a tie on the line between two files goes by file, not by booking order. - `auto_accounts` numbers an open by its account's place among every account the ledger names, opened ones included, and `currency_accounts` numbers its opens by their sorted place, as beancount's plugins do. - `rustledger_loader::source_lines` no longer copies every line table: a file's table is built from its shared text on the first lookup, and placeholders added after it was taken are seen. `source_lines_overlaid` reads an editor buffer's lines from its text; the LSP passes the edited buffer. - The WASM `Ledger` keeps each directive's position, and its cache payload stores the file rank beside the line (still v91). Loader tests, each checked against bean-check 3.2.3: a tie through a nested include, a same-line note in the main file against a pad in an include (both ways round), an `auto_accounts` open tied with a written one, and the known difference where beancount reads files breadth first and the loader depth first. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(booking): track only postings in a pad group, and build the entry order only when a lot at cost can print it Review round 8 of #2920: - A posting outside every pad group no longer resolves its lot or joins the transaction's group list: whether an account falls in a group is answered once per account. - The entry order (the account ranks, and sorting a transaction's postings by them) only shows in an "Attempt to pad an entry with cost" message, so it is built only when a posting under a group carries a cost. Then only accounts in a group are ranked, and a transaction's postings are sorted only when two fall in one group. - `pad_plan_reads_positions` says when the plan reads positions; the validator looks up each directive's line only then. - CHANGELOG: the plugin `open` lines also fix BQL `filename` / `lineno` and `#accounts` meta, and locate a `currency_accounts` open's error at `<currency_accounts>:N`. The v91 note says the plugin-open lines moved. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed
The validator's padding was a second implementation of
rustledger_booking::process_pads, and the two had drifted from each other and from beancount (#2896). Now there is one pad computation,rustledger_booking::plan_pads. It follows beancount'sops/pad.pyon the points below; it still differs from it on others (other pads' padding in the inventories it measures, balances on child accounts, cost lots, tolerance), tracked in #2901:Unused Pad entry(E2003).It has two consumers:
process_padswrites the plan out as the padding transactions thatrledger report balances, BQL and#balancesread.pad, where beancount dates and inserts its padding entry. Balances are then compared plainly; the validator has no pad logic of its own.E2004is removed (see Breaking below).Canonical vs drift guard
The validator now calls the canonical. It runs
plan_padsonce, only when the stream has a pad, over the sorted view it already walks. So it neither re-sorts nor copies the directives.What each side still computes for itself is the inventory a balance is compared against: booked lots in the validator, units in
process_pads. The drift guardcrates/rustledger-validate/tests/pad_parity_test.rscompares the two end to end. It covers every #2896 shape, plus the pad-date shape and the p15 shape below, with an ordinary pad as a control. On each shape it checks that:padreplaced byprocess_pads' padding;It fails against the round-1 code, on the pad-date shape.
Before / after, against beancount 3.2.3 (full bean-check / bean-query output)
padto an unopened target, txn -30 into it,balance 100(never opened, or opened later)Unused Pad entryE2003balanceon an unopened target (50 held, 100 asserted)Balance failedE2001pad,balance 0,balance 10Unused Pad entry+Balance failedE2003+E2001E1001s onlyE1001s +E2003+E2001pad 01-09,pad 01-10,balance 100,balance 200Unused Pad entry(01-09) +Balance failed(01-12)E2004onlyE2003(01-09) +E2001(01-12)pad 01-02,balance 100 USD,pad 01-04,balance 10 EUR,balance 50 USDE2004pad Assets:A Equity:O 01-03,balance Equity:O -100 USD 01-05,balance Assets:A 100 USD 01-10E2001onEquity:Oopen(posting,pad,balance)Invalid reference to inactive accountThe E1001 lines are otherwise unchanged. bean-check repeats an unknown account's error per directive, as discussed on #2895.
Breaking:
E2004removedE2004("Multiple pad directives") was an rledger-only error. The superseded pad is anE2003, which is what beancount reports for it.E2004also fired falsely, on p15.It is removed from:
ErrorCode(MultiplePadForBalance) and its code tables;BALANCE_ERROR_CODES;docs/reference/errors.mdandspec/core/validation.mdkeep the number as "removed in 0.25.0" and retired, so it is not reused. The CHANGELOG entry is under Breaking.Performance
plan_padsmeasures each padded balance through a prefix index:rustledger_core::for_each_strict_subaccount, one range query shared with the validator'ssum_account_subtree. It keeps units only, not lot inventories. Round 2 scanned every account per padded balance, which maderledger checkand the LSP quadratic.test_plan_pads_sums_each_balance_over_its_subtree_onlycounts the accounts read, where they are read (a newtype over the totals counts everygetand every iteration). With 2,000 accounts it reads 2,000. A plain scan that adds only the matching accounts reads 4,003,999 and fails it. In core,for_each_strict_subaccount_visits_exactly_the_strict_subtreechecks the exact strict subtree on 8,655 generated names (deep, Unicode, prefix siblings, shared paths across roots) and bounds the keys read per query with a counting key. A filtered full scan in core reads 8,655 per query and fails it.rledger check(release, min of 9 interleaved runs) on N accounts, each with a transaction, a pad and a balance. The machine was loaded, so absolute numbers are noisy; compare the columns.Still quadratic, on main as well (not changed here):
merge_with_paddinginserts each padding transaction into the sorted vector one by one, as its doc already notes, with a revisit condition. So BQL andreport balanceson this shape take 35 s at 40k on main and 32 s here. A one-pass merge would fix it; that is a possible follow-up.Corpus comparison
I compared origin/main and this branch, each built in its own target dir, on all 1,136 ledgers (405 in-tree, 731 compat). Each run captured
rledger check,rledger report balances,SELECT account, sum(position) GROUP BY accountandSELECT * FROM #balances.report balances: unchanged on every file.Balance failedfor a balance on an account with noopen, plus the matching#balancesdiscrepancy. Each of them already failed on that account'sE1001, so no ledger goes from passing to failing.Balance failederrors.ParserEntryTypes.BalanceWithCost. bean-check drops that balance over a syntax error ({on a balance). rledger reports the parse error (P0012) and still validates the recovered balance, so it is not comparable.tests_data_errors,cozumel2015, and the loaderglob_testfixtures.E2004.Other behavior to note
The advisory
E1004(not reported bycheck; reported byrledger lint closed-nonempty) now sees padding in a source account that is closed later on the pad's day, because the padding is dated at the pad. This is the same as any posting before a close, and it is pinned intest_validate_pad_reports_a_closed_account.Cache
WASM
CACHE_VERSION85 (loader v63, unchanged by this PR), because cached error lists change. v84 is #2872's (via #2903) and v82 #2893's, both merged in from main; v83 was never released. The loader cache is unaffected.Not in this PR (possible follow-up)
beancount pads only when the difference exceeds the balance tolerance, but
plan_padspads any non-zero difference. For example,100.004held againstbalance 100.00is padded by-0.004where beancount pads nothing. Fixing that needsbalance_tolerancemoved fromrustledger-validatedown to booking.How to test
Verification
cargo test --workspace --all-features --no-fail-fastpasses. The CLI snapshots forvalidation-errors.beancountare updated: its balance on a never-opened account now fails, and bean-check agrees.cargo clippy --workspace --all-features --all-targets -- -D warnings,RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-depsandcargo fmt --checkpass.STRICT_BASELINE=1corpus and CST baselines pass. No parser change, so no baseline rows moved.process_padsunit tests, the TLA pad replay, the drift guard and the integration tests;Closes #2896
🤖 Generated with Claude Code