Repository navigation
fix(validate)!: pad parents, sub-accounts, tolerances and cost lots as beancount does - #2920
Merged
Merged
Conversation
…s 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]>
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 |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
…lerances 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]>
WASM cache v88: v86 is #2905's on main, v87 is claimed by #2908. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in #2919's linear merge_padding_into_sorted (with the tolerance_multiplier threaded through), #2908 and #2924. WASM cache v88, loader pin 66. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…als 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]>
Brings in #2922. WASM cache v88 (main holds v87), loader pin 66. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…, 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]>
Brings in #2926. WASM cache v91 (main holds v89, #2923 claims v90), loader pin 67. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Nov 10, 2026
Brings in #2923. WASM cache v91 (main holds v90), loader pin 68. The held-options session keeps both checks: the tolerance multiplier and the booking method. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nt 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]>
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]>
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]>
This was referenced Nov 10, 2026
…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]>
# Conflicts: # CHANGELOG.md
…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]>
robcohen
added a commit
that referenced
this pull request
Nov 10, 2026
…plugin" read-only (#2930) * fix(loader)!: read option values as beancount does, and make option "plugin" read-only Part 1 of #2925, checked against bean-check 3.2.3. - Booleans use beancount's two vocabularies: the converter options (render_commas, use_precise_interpolation, allow_pipe_separator, insert_pythonpath) read 1/true/yes as true; infer_tolerance_from_cost, read by grammar.option, reads true/on/1. Any other word reads as false and is the new E7011 warning, so check passes as bean-check does. parse_bool_word keeps serving metadata unchanged. - inferred_tolerance_default and display_precision share one parser that splits at the last colon followed by a number (A:B:0.01 is currency A:B) and rejects a sign (USD:-0.01). Text after the number stays E7002, a deliberate deviation. - tolerance_multiplier is read as D(): empty is 0, commas are stripped, exponents are accepted. NaN and Infinity stay E7002 (not representable). - experiment_explicit_tolerances and use_legacy_fixed_tolerances are unknown (E7001); their Options and CachedOptions fields are removed. - option "plugin" is E7005 (may not be set) instead of E7004, from an included file too. - E7007 is dropped: a valid account_rounding gives no diagnostic. - long_string_maxlines accepts any value, as beancount has no converter. Loader cache v69, WASM cache v92 (v91 is left to #2920). BREAKING CHANGE: render_commas "yes", infer_tolerance_from_cost "on" and tolerance maps like "A:B:0.01" now read as beancount reads them; the two dead options are errors; Options loses two public fields. Refs #2925 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(loader): review round 1 on option values - tolerance_multiplier drops every `_` as CPython's Decimal does (1__0, _1, 1._5, 1e_1), rejecting only an all-underscore value, and reads a zero significand as 0 at any exponent (0e100). - Tolerance maps need the colon on the first line, as beancount's `.*` does not cross a newline. - Deviation 3 is documented in full: values outside rust_decimal's range, and non-ASCII digits in a tolerance map, are E7002. - The converter test pins that `on` and `off` are not its words. - rledger doctor list-options prints the loader's known_options with option_value_kind, instead of a hand-written copy; a test keeps the descriptions in step. - CHANGELOG Breaking lists the included `filename`, exponent tolerance maps and the moved diagnostic codes. Refs #2925 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(loader): review round 2 on option values - Numbers are read exactly or rejected: a value rust_decimal cannot hold exactly (out of range, or too many digits, e.g. 1E-31) is E7002 instead of silently rounded, in tolerance_multiplier and the tolerance maps. The range is checked on the value, so 10e-29 and 0.1e29 are accepted. - Tolerance maps accept trailing whitespace, as beancount does; other trailing text stays E7002 (deviation 2). - option_value_kind gives long_string_maxlines "any", and a drift guard sets a value of each declared kind and asserts `set` accepts it. - docs/reference/options.md lists use_precise_interpolation and insert_pythonpath, and a test checks the table against known_options. - CHANGELOG: Breaking says what changed per option; Added lists the new loader API and the doctor list-options change; deviation 3 covers non-ASCII digits in any numeric option and inexact values. Refs #2925 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(loader): review round 3 on option values - exact_decimal is linear in its input: leading zeros are skipped once and the trailing zeros to drop are counted, not popped one rescan at a time. A 160k-digit display_precision value was quadratic (30 s). - It also drops trailing zeros while the coefficient is past 96 bits, so 79228162514264337593543950335.0 and 10000000000000000000000000000.0 are held again, as on main and in beancount. - A zero's exponent is bounded by Python's MIN_ETINY / MAX_EMAX, so 0e99999999999999999999 is an error as in bean-check. - Whitespace is Python's str.isspace, in tolerance_multiplier and after a tolerance map's number. - insert_pythonpath is described as accepted with no effect. - CHANGELOG: tolerance_multiplier and USD:0_5 Breaking bullets, corrected Fixed wording, display_precision's 28-place limit under deviation 3. Refs #2925 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(loader): review round 4 on option values - tolerance_multiplier strips in beancount's order: D() drops commas and spaces, then Decimal strips whitespace, then drops `_`. So "_\t1", "1\t_" and "1<U+3000>_" are E7002, as in bean-check; "_ 1" stays 1. - Tests pin the 96-bit pop loop with 29-digit coefficients and the MIN_ETINY edge for a zero's exponent. - Deviation 3 says display_precision keeps at most 28 places where beancount keeps any number, that dropping a trailing zero to fit 96 bits lowers it, and lists sNaN. Refs #2925 Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(loader): move a misplaced comment in the 96-bit test Refs #2925 Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
…y 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]>
# Conflicts: # CHANGELOG.md # crates/rustledger-wasm/src/cache.rs
robcohen
added a commit
that referenced
this pull request
Nov 11, 2026
Take #2920 (WASM cache v94). This branch moves its WASM cache to v95, pinned at loader v70; v93 was never released. Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Nov 26, 2026
…de order
beancount parses included files breadth first (`_parse_recursive` pops the
front of its source list and appends each file's includes) and its stable
entry sort keeps that order for entries tied on (date, SORT_ORDER, lineno).
The loader reads depth first and ranked a file by its id, so an E2005
("Attempt to pad an entry with cost") listed tied positions from nested
includes in a different order than bean-check 3.2.3.
- SourceMap records every include that names a loaded file, in order,
duplicates and cycles included (`add_include`, `includes`), and
`parse_ranks` replays beancount's BFS over them (dedupe on pop), so a
file included twice takes its place from the include met first.
- `source_lines` (the one source of positions for the validator, the WASM
`Ledger`, ffi-wasi/component and the LSP) ranks files by `parse_ranks`;
`SourcePosition::in_parsed_file` is new.
- The loader cache archives the include lists (`CacheEntry::includes`),
loader CACHE_VERSION 76 -> 77; WASM pin 77, WASM CACHE_VERSION 134 (133 is
reserved by a parallel parser change) since its archived file ranks move.
- #2920's pinned known difference flips to a parity assertion; new parity
tests for a three-level tree, duplicate and cyclic includes and a glob,
all checked against bean-check 3.2.3, plus drift guards across the CLI
(cold and cache hit), WASM `Ledger` (and restored), ffi-wasi and the LSP.
Closes #2936
Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen
added a commit
that referenced
this pull request
Nov 26, 2026
…de order (#3037) beancount parses included files breadth first (`_parse_recursive` pops the front of its source list and appends each file's includes) and its stable entry sort keeps that order for entries tied on (date, SORT_ORDER, lineno). The loader reads depth first and ranked a file by its id, so an E2005 ("Attempt to pad an entry with cost") listed tied positions from nested includes in a different order than bean-check 3.2.3. - SourceMap records every include that names a loaded file, in order, duplicates and cycles included (`add_include`, `includes`), and `parse_ranks` replays beancount's BFS over them (dedupe on pop), so a file included twice takes its place from the include met first. - `source_lines` (the one source of positions for the validator, the WASM `Ledger`, ffi-wasi/component and the LSP) ranks files by `parse_ranks`; `SourcePosition::in_parsed_file` is new. - The loader cache archives the include lists (`CacheEntry::includes`), loader CACHE_VERSION 76 -> 77; WASM pin 77, WASM CACHE_VERSION 134 (133 is reserved by a parallel parser change) since its archived file ranks move. - #2920's pinned known difference flips to a parity assertion; new parity tests for a three-level tree, duplicate and cyclic includes and a glob, all checked against bean-check 3.2.3, plus drift guards across the CLI (cold and cache hit), WASM `Ledger` (and restored), ffi-wasi and the LSP. Closes #2936 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
Beancount pads each account that has a
padon its own (beancount/ops/pad.py). That pad group sees every balance on the account or on any of its sub-accounts. It measures each one against the real postings of the account and its sub-accounts plus the group's own padding, and nothing else. It does not pad a difference within the balance's tolerance. When it pads a currency that is held at cost, it reportsAttempt to pad an entry with cost.rustledger_booking::plan_padsnow follows that rule, and it is still the single pad computation behind the validator,process_pads, the balance view, BQL and#balances:PadInventoriesholds real postings only, and each group adds its own padding on top. Another group's padding is not counted, whether it went into a sub-account or came out of this account as that pad's source. Padding that would overflow either account's total in the ledger is still refused and reported (Decimal overflow in Inventory::add panics the CLI on valid ledger input #1863). That check now runs against a separate per-account padding total.balance_tolerancemoves fromrustledger-validatetorustledger-booking, next to the pad rule (CANONICAL: the balance check and the pad rule both call it). Because of that,process_pads,plan_pads,merge_with_padding{,_owned,_spanned}and the FFIexpand_padsnow take the ledger'stolerance_multiplier. Every caller passes its ledger's option. Callers with no options (query-entries, tests) passDEFAULT_TOLERANCE_MULTIPLIER.E2005(ErrorCode::PadWithCost). Plan entries carry units only, so the validator checks its booked lots at each balance the plan padded for. It reports the error once per lot held at cost, as beancount does, and the padding is still inserted.pad_parity_testnow covers every #2901 shape. For each one it checks the padding (account and amount), the balance failures, the unused pads and the cost errors against beancount, and it checks the validator againstprocess_pads. I confirmed the guard can fail: four separate mutations each make it fail (padding within tolerance, skipping the ancestor groups, ignoring a group's own padding, dropping the cost check).Against beancount 3.2.3 (full bean-check and bean-query output)
pad A Equity:O(01-03),balance Equity:O -100(01-05),balance A 100(01-10)pad A:Sub,balance A 100in between,balance A:Sub 100pad A,balance A:Sub 100(30 inA:Other),balance A 200Balance failedA:Sub (0) and A (100)pad A,balance A:B 30(held),balance A 100Unused Pad entry;Balance failedA (30)pad Aandpad A:Sub(same day),balance A:Sub 40,balance A 100Balance failedA (80)pad A:B,balance A:B 100,pad A,balance A 150Balance failedA (250)pad A B,balance A 100,pad B Equity:O,balance B 0Unused Pad entry;Balance failedB (-100); BQL B -10010 STK {10 USD},balance 15 STKAttempt to pad an entry with cost; pads 5 STKE2005once; pads 5 STKE2005twicebalance 10 STKUnused Pad entrybalance 100.00, thenbalance 100.004Unused Pad entry, nothing elseBalance failedon 100.004 (got 100.000)balance 100 ~ 1, thenbalance 100Unused Pad entry;Balance failed(99.5)The
E2005message is word for word what bean-check prints (since round 2 it goes through the canonicalpython_inventory_str).Ties follow beancount's entry order,
(date, SORT_ORDER, lineno). The line number counts whichever file a directive is in. A plugin's entry has the line the plugin gives it, and it comes ahead of the parsed entries on the same line, as in beancount. A tie on the line between two files goes to the file read first.Known difference: beancount reads files breadth first and the loader reads them depth first. So a tie on the same date, type and line between a file included from an include and a file the parent includes later goes the other way (pinned by
test_pad_ranks_a_tied_line_by_the_loaders_depth_first_file_order). The LSP reads the edited buffer's lines from its text, but another open buffer's lines still come from its file as loaded.Corpus
I ran
rledger check,rledger report <file> balances, BQLSELECT account, sum(position) GROUP BY accountandSELECT * FROM #balanceson all 1,045 in-tree and compatibility ledgers (tests/compatibility/files, 23 of them with pads). I compared a build of origin/main (b7abb65, after #2898) with this branch. There is no difference: no ledger in the corpus has any of these shapes.Caches
WASM cache v94: main holds v92 (#2930), #2931 holds v93, and v88 and v91 were never released (#2926 took v89 and #2930 took v92 first). The loader pin is main's 69. There is no loader bump from this PR, because parser output and the archived directive layout are unchanged. The
Ledgerpayload gainstolerance_multiplier, sofromCachepads with the ledger's own option. It also gainsdirective_linesanddirective_file_ranks, so a restored ledger orders pad ties asgetErrors()does. The cached error lists change.Breaking
tolerance_multiplier.rustledger_validate::balance_toleranceis nowrustledger_booking::balance_tolerance.ErrorCodegainsPadWithCost.rustledger_ffi_wasi::helpers::{LoadResult, FileLoad}gaintolerance_multiplier.These are listed in the CHANGELOG.
How to test
Gates I ran: the full workspace tests (6,604 passed), clippy
-D warnings,RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps,cargo fmt --check, and theSTRICT_BASELINE=1corpus and CST baselines.Review round 1
pad_balance. The total is seeded once, from one subtree walk, when the group's firstpadcomes. After that, each posting moves the groups of its account and its ancestors, which costs O(depth). Before this, a parent pad with a balance on each of many sub-accounts summed the whole subtree at every balance. The newtest_plan_pads_parent_pad_reads_its_subtree_oncecounts accounts read: 401 for 400 sub-accounts, where the per-balance walk reads 160,801 and fails it.E2005only walks the subtree for a currency that some posting booked at cost.pad_parity_testnow runs each shape under its owntolerance_multiplier, and a multiplier-2 shape is added: 99.97 held,pad,balance 100.00 USDgivesUnused Pad entryand no padding (bean-check). New loader tests inbalance_view_test.rscheck the same ledger throughLedger::balance_viewand validation, and check thatinferred_tolerance_default "USD:0.05"is ignored there, padding 0.03 (bean-query). These mutations now each fail a test:DEFAULT_TOLERANCE_MULTIPLIERin the validator'splan_padscall,Ledger::balance_view,E2005counts merged positions. Lots are gathered into one inventory first, so the same lot held inA:BandA:Subis one position and gives one error, as in beancount ((14 STK { 10 USD, 2024-01-02})).E2005shows only the group's own holdings. The message shows the lots at cost, plus what the pad group held without cost: its real units and its own earlier padding (PlannedPadding::held, beancount'spad_balance). Other pads' padding is no longer shown. With pads onA:Band thenA, both messages are(10 STK { 10 USD, 2024-01-02}), as in bean-check.E2005is tested on a sub-account lot. There are new parity shapes for a lot in a sub-account, the merged lot, and the two-group message. Removing the sub-account walk now fails the test.scripts/compat-values.pynow classifies^E200[345]$as pad errors.tolerance_multiplierstill means the default. A non-empty value that is not a decimal is now reported as a session error,invalid tolerance_multiplier "two" (...); using the default 0.5. The held record is rewritten to the value used, soinfo()echoes what pads. This has a new test.merge_padding_into_sortedis kept, withtolerance_multiplierthreaded through), fix(parser): lex an account component with any non-ASCII start, as beancount does #2908 and chore(scripts): exit the parity harness's forked worker through finally #2924.check,report balances, BQLsum(position),#balances) found no difference, byte for byte. That includes the 23 ledgers with apadline in my copy of the corpus.padon the parent and a balance on the sub-account:checktakes 0.39 s user on this branch against 0.51 s on main, and BQLsum(position)0.22 s against 0.40 s. Both of these regression tests pass:test_plan_pads_parent_pad_reads_its_subtree_onceand perf(booking)!: merge padding transactions in one pass, not one insert each #2919'stest_merge_padding_into_sorted_is_linear.All new shapes were checked against bean-check / bean-query 3.2.3. Gates: workspace tests, clippy
-D warnings, rustdoc-Dwarnings,cargo fmt --check, and the STRICT baselines.Review round 2
PlannedPadding::held(now anOption) is copied only when one of those accounts is under the pad group, found with one range query that stops at the first match.LedgerState::cost_accounts) and reads only those accounts under the target.validators::balance::testscount the accounts read. A lot outside the subtree reads 0, and a lot inside reads 1 per padded balance. With a ledger-wide gate plus a subtree walk they read 90,300 and 90,600, and fail.heldis built only when a cost lot may fire E2005, and the validator moves it instead of cloning it.test_plan_pads_copies_holdings_only_for_a_lot_at_cost. It fails when the copy is made for every padding.Decimal's range now carries on inBigDecimal. It reads as unrepresentable only while it is out of range, and it is never re-summed.test_plan_pads_overflowed_group_total_reads_its_subtree_once: 303 reads. The previous implementation reads 91,203 and fails it.python_inventory_strandpython_position_strmove fromrustledger-querytorustledger-core(CANONICAL: BQLstr(), the conversions narration, and now E2005 all use them).(20 USD, 5 STK, 10 STK {10 USD, 2024-01-02}).rustledger_core::strict_subaccountsis the range query behindfor_each_strict_subaccount, exposed as an iterator.Release timings (user CPU seconds, one run each on a shared machine; check is
rledger check --no-cache, BQL isSELECT account, sum(position) GROUP BY account):padbefore each sub-account's balance1 STK {10.00 USD}lot outside the subtreepad, 2,000 balancespadon the top accountChecks on the final branch:
balance_view's default multiplier, the doubled tolerance, the sub-account lot walk removed, padding within tolerance, and the E2005 check dropped.padline, and on all 1,045 in-tree and compatibility ledgers, release builds of this branch and main produce byte-identical output forcheck,report balances, BQLsum(position)and#balances.Review round 3
There is now one rule, in one place, as beancount's
pad.pyhas it.pad_balanceitself.Inventory.add_positionmerges them. A lot that nets to zero is dropped, and a dropped lot that comes back goes last, as a Python dict key does.rustledger_booking::plan_padsreads E2005 from the group's inventory asPlannedPadding::at_cost: Option<PaddedAtCost>, which holds the lots at cost and the inventory printed through the canonicalpython_inventory_str.process_padsreports it too.cost_accountsindex,lots_at_costandshown_balance, and the plan'sheldcopy with its cost-account gate.RunningTotalsnow carries the AGENTS.md deviation comment. A running total that passes through100000000000000000000000000001stays exact. bean-check rounds that total in its 28-digit context, so it pads the lost 1 and still fails the balance (probe checked).test_plan_pads_keeps_an_overflowed_total_exactpins our behavior.sell_gainsnow prints its inventories throughpython_inventory_strinstead of its own copy ofCURRENCY_ORDERand the sort key. Its tests and the corpus are unchanged.PlannedPadding::at_cost(PaddedAtCost) and the move ofpython_inventory_strto core.Mutations. Each of these fails a test:
balance_view's default multiplier, the doubled tolerance, a group missing its sub-accounts' lots, padding within the tolerance, the E2005 check dropped);The M1b gate and the validator-side index no longer exist.
Release timings. User CPU seconds, one run each, measured while other jobs held the machine at a load average near 40. Wall-clock times are not meaningful under that load.
padbefore each sub-account's balancesum(position)padon the top account{}Corpus. Release builds of this branch and main (6afd960) produce byte-identical output on all 1,045 in-tree and compatibility ledgers, 23 of them with a
padline. Compared:check,report balances, BQLsum(position),#balances, andstr(sum(position)).Review round 4
realization.postings_by_accountfirst met each account. It then stable-sorts them by date, type and line, and one transaction's postings share a line.add_amountrebuilds the position with the incoming cost. Parity shape:{10 USD}joined by{10.00 USD, 2024-01-02}prints(2 STK {10.00 USD, 2024-01-02}).GroupInventory::add, every lot check and every printed position is counted.process_padsdoes. There is a new test, and putting the check back behind the return fails it.strict_subaccountsis removed: it had no caller. Thefor_each_strict_subaccountdoc no longer namesplan_pads. Theprocess_padsandPadResult::errorsdocs now name E2005.Review round 5
Accounts are ranked in beancount's entry order. A same-date
padnow meets its accounts at its own line.rustledger_core::beancount_entry_sort_key. It is beancount'sentry_sortkey,(date, SORT_ORDER, lineno), with the source location (file id, offset) standing for the line, and it has a core test.booking_sort_keydiffers from it only forpad.plan_padsranks accounts in one pass ordered by that key, before the walk. The walk itself keeps the booking order.span_info), frommerge_with_padding_spannedand fromLedger::balance_view, through the newprocess_pads_spanned.process_padsfalls back to input order, which is right for a stream in source order. The FFI and WASM surfaces now pass their locations too (see the follow-up below), so no surface ranks by booking order any more.pad, each(1 CCC, 1 DDD, ...)as bean-check prints it.test_loaded_pad_ranks_accounts_in_beancount_entry_order) covers the located path. It fails when the validator drops the locations.Every registration arm has a test. I added parity shapes for the opens alone (
(1 CCC, 1 DDD, ...)) and for one2023-12-31line namingAssets:A:D((1 DDD, 1 CCC, ...)):notedocumentbalance 0 DDDcustom "x" Assets:A:Dcustom "x" "s" Assets:A:D 2 Assets:A:Cclose, 1 EEEElast)I checked each against bean-check 3.2.3. Removing any one arm of
see_directive(open, close, balance, note, document, pad account, pad source, custom, posting) fails a test. Ranking in booking order instead of entry order fails the same-date shapes.seelooks the account up before cloning it.Gates: workspace tests, clippy
-D warnings, rustdoc-Dwarnings, fmt, and the STRICT baselines.Review round 5, follow-up: one answer on every surface
The gap I had written up is now closed rather than documented.
rustledger_booking::process_pads_atpads plain directives with a parallel list ofSourcePositions.process_padskeeps its input-order fallback. Its rustdoc now states what that promises: the padding never depends on input order. Only the tie order in an E2005 message does, and only a stream in source order suits the fallback. Its remaining non-test caller is the plainmerge_with_padding, which discards errors.helpers::pad_expansionpads with the kept spans for bothexpandPadssurfaces.rledger checkand the FFI do. Their validation errors therefore carry their own lines instead of their date's first line. A span from a plugin's placeholder file is ignored there. CachedParsedLedgererrors change; this is noted under WASM v91.expand_padstakes aposition_offor its tags, eitherline_positionorfile_line_position(file id from the source map, then line).rustledger-wasmtest_pad_at_cost_ties_agree_across_surfacesuses one ledger with a note written above a same-date pad.(1 CCC, 1 DDD, ...)through the validator (rledger check),process_pads_spanned, the WASM expansion, and WASM validation.balance_view, the WASM expansion, and ffi-wasiexpand_pads.Release timings. User CPU seconds, main d21a576 against this branch. The machine load average was about 9, which is quieter than earlier runs, so these numbers sit below the round-3 table.
sum(position)on A)Corpus. I compared release builds on all 1,045 in-tree and compatibility ledgers, producing six outputs for each, 6,270 in total:
checkcheckwithplugin "beancount.plugins.sellgains"report balancessum(position)#balancesstr(sum(position))All 6,270 are byte-identical. In 7 of them (
checkwith sellgains), the only difference is the scratch directory name in an absolute path the error message prints.Review round 6
wasm-pack test --nodecompiles and passes again (31 tests). The drift guard's ffi-wasi part is now#[cfg(not(target_arch = "wasm32"))].Accounts are ranked by beancount's line number.
SourcePositionis now the line beancount uses inentry_sortkey: the line in its file, whichever file that is, and 0 for a plugin's entry.ValidationOptions::source_lines(SourceLines), whichrustledger_loader::source_linesbuilds from a source map. The loader and the LSP's multi-file path set it.helpers::offset_linesgives the WASM expansion the same values.test_pad_ranks_accounts_by_line_across_files: an account opened on line 2 of an included file, after a 300-character line, ranks before one opened on line 5 of the main file, though its byte offset is larger.test_pad_ranks_a_plugins_open_first: anauto_accountsopen ranks first.A restored WASM
Ledgerkeeps its lines. TheLedgernow keepsdirective_linesand stores them in its cache payload (still WASM v91), sofromCache(...).expandPads()answers asgetErrors()does.from_filesnow delegates to a nativefrom_file_map.Ledgerbefore and after a cache round trip.ParsedLedgeroffsets.Removed:
process_pads_spanned. The merges discard errors, so onlyprocess_pads_at(the WASM expansions) needs lines.ffi-wasi
expand_padsis back to main's API. It only pads, and no input order changes padding.position_of,line_positionandfile_line_positionare gone.CHANGELOG now says:
validateSourceandParsedLedger(fromFiles/validateMultiFilealready went through the loader);column/end_line/end_column;tolerance: 0.10.The v91 note now says both payloads' error lists move, and that
Ledgergainsdirective_lines.Verification:
wasm-pack test --node: 31 passed.-D warnings, rustdoc-Dwarnings, fmt and the STRICT baselines are clean.check,checkwith sellgains,report balances, BQLsum(position),#balances,str(sum(position))).Review round 7
validateandloadbuiltValidationOptions::default(), which ignoredtolerance_multiplier.LoadResultnow carriesvalidation_options. It is built with the canonicalvalidation_options_from_optionsplus the source map's positions, and the component validates with it.validateSource,ParsedLedger) also used a default set. It now builds its options the same way.test_validate_and_load_read_the_tolerance_multiplier_as_check_does(ffi-component) andtest_wasm_validation_reads_the_tolerance_multiplier_as_check_does(WASM). Each compares the surface withrledger checkon two ledgers withoption "tolerance_multiplier" "2"and 99.97 held. With a pad beforebalance 100.00 USD, bean-check 3.2.3 andcheckgiveUnused Pad entry. Without the pad, both give nothing.SourcePositionis now a struct holding the line and the file's place in the load.rustledger_loader::source_linesreads a placeholder's stored line. The placeholder table is now shared through anArc, so placeholders a plugin adds after the session started are still seen.offset_linesis replaced bysource_positions, which goes through the samesource_lines.ValidationOptions::source_lines. Every surface that has a source map now passes it: the loader, the LSP, ffi-component and the WASM.auto_accountsnumbered an open by its place among the accounts it opened. It now numbers it by its place among every account the ledger names, opened ones included, as beancount'senumerate(sorted(accounts_first.items()))does.currency_accountsnow setslinenoto its sorted index. It used to set none.open Assets:A:Con line 1 andauto_accounts.(1 B1X, 1 CCC, 1 B2X, 1 DDD, ...). That is not the(1 B1X, 1 B2X, 1 CCC, 1 DDD, ...)quoted in the review. The order comes fromAssets:A:B1= 1 tying with C on line 1 (the plugin's entry goes first), thenB2= 2, thenD= 4.(1 B1X, 1 B2X, 1 DDD, 1 CCC, ...). This round matches bean-check.test_pad_ranks_a_plugins_open_by_the_line_the_plugin_gives_itand in the WASM drift guard, which covers check,ParsedLedger,Ledgerand its cache round trip.test_created_open_is_numbered_by_its_sorted_placepinscurrency_accounts.beancount_entry_sort_key,SourcePosition, the tests).A tie on the line now breaks by file rank instead of booking order: plugin entries first, then 1 + file id.
File ids are depth-first, not beancount's breadth-first order. They agree except when a file included from an include ties with a file its parent includes later.
Checked against bean-check 3.2.3:
(1 CCC, 1 DDD, 1 EEE, ...)(1 CCC, 1 DDD, ...)(1 DDD, 1 CCC, ...)(1 DDD, 1 CCC, ...)(1 XXX, 1 YYY, 1 ZZZ, ...)(1 XXX, 1 ZZZ, 1 YYY, ...)(1 XXX, 1 ZZZ, 1 YYY, ...), a known difference, pinnedTrue breadth-first order needs the include graph, and the graph is not where it is needed.
load_recursiverecords no parent per file, so theSourceMaphas none. The loader cache (CacheEntry::into_load_result) rebuilds the map from a flat file list.Doing it properly means three things: record each file's includer and include order in
SourceMap; archive that in the loader cache (loaderCACHE_VERSION68 to 69, and the WASM pin and version with it); and derive the BFS rank insource_lines. That is a cache-format change, so I stopped as instructed. It is a self-contained follow-up if wanted.source_linesno longer copies any line table. Each file's table is built from its shared text on the first lookup, and only when the ledger has a pad. A file whose text was dropped hands over the table the drop kept.source_lines_overlaidreads a buffer's lines from its text. Both LSP paths pass the edited buffer. Another open buffer's lines still come from its file as loaded, because that path only has the buffer's directives (see the known difference above).Inventory::add_with_totalis new", "posting_lot_totalis now public"). The new items (SourcePosition,SourceLines,source_lines_overlaid,process_pads_at,beancount_entry_sort_key,LoadResult::validation_options) are listed in the Breaking entry, and the behavior changes in the Fixed entry.directive_file_ranksand the validation-options change.Mutations, each caught:
auto_accountsnumbering only the accounts it opens;currency_accountsnumbering only the accounts it creates;Verification:
Workspace tests: 6,721 passed, 0 failed.
wasm-pack test --node: 35 passed.Clippy
-D warnings, rustdoc-Dwarningsand fmt are clean.Corpus: release builds of this branch and main (d21a576) are byte-identical across all 1,045 in-tree ledgers × 6 outputs (
check,check --format json,report balances, BQLsum(position),#balances,str(sum(position))).Timing on a generated 120k-line, 251-file ledger with 250 pads (
rledger check, hyperfine, 20 runs):Round 7 adds no cost over round 6. The PR as a whole costs about 13% over main on this pad-heavy ledger, and outputs are identical.
Review round 8
Perf: work only for postings in a pad group.
Position::from_postingand is not added to the transaction's group list.PadTracker::coversanswers once per account whether the account falls in a group.order_if_costs, a pre-scan): the account ranking pass, and the sort inpost_transaction. In that caseseeranks only accounts that fall in a group, and a transaction's postings are sorted only when two of them fall in one group.rustledger_booking::pad_plan_reads_positionsreports when the plan reads positions. The validator looks up each directive's line only then, so a ledger with a pad but no lot at cost under it builds no line tables.test_pad_tracker_ranks_only_when_a_group_holds_a_cost.Timing.
rledger check, hyperfine, 25 runs, against main d21a576 (before the merge, on a quieter machine):CHANGELOG. The Fixed entry now also says:
filename/linenoand the#accountsmeta forauto_accountsandcurrency_accountsopens now match bean-query;currency_accountsopen is located at<currency_accounts>:N, where it was<unknown>with the plugin note.The cache note says plugin-open lines changed.
Merged origin/main (fix(loader)!: read option values as beancount does, and make option "plugin" read-only #2930, be6193f). The CHANGELOG and
cache.rsconflicts are resolved with both sides kept.cache.rs.Verification, after the merge:
wasm-pack test --node: 35 passed.-D warnings, rustdoc-Dwarningsand fmt are clean.Closes #2901
🤖 Generated with Claude Code