Skip to content

fix(validate)!: pad parents, sub-accounts, tolerances and cost lots as beancount does - #2920

Merged
robcohen merged 17 commits into
mainfrom
fix/pad-remaining-parity
Nov 11, 2026
Merged

robcohen merged 17 commits into
mainfrom
fix/pad-remaining-parity

Conversation

@robcohen

@robcohen robcohen commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

What changed

Beancount pads each account that has a pad on 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 reports Attempt to pad an entry with cost.

rustledger_booking::plan_pads now follows that rule, and it is still the single pad computation behind the validator, process_pads, the balance view, BQL and #balances:

  • Parent and child accounts. A balance belongs to the pad group of its own account and to the group of every ancestor account. Each group pads into its own account. A balance on a sub-account uses up the parent pad's currency.
  • Own padding only. PadInventories holds 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.
  • Tolerance. balance_tolerance moves from rustledger-validate to rustledger-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 FFI expand_pads now take the ledger's tolerance_multiplier. Every caller passes its ledger's option. Callers with no options (query-entries, tests) pass DEFAULT_TOLERANCE_MULTIPLIER.
  • Cost. New 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 timing. The rows where padding was applied at the wrong date (the source balance in between, and the parent balance in between) were already fixed by fix(validate)!: pad from one shared plan as beancount does, and drop E2004 #2898. They are pinned here.

pad_parity_test now 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 against process_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)

Shape beancount 3.2.3 origin/main this PR
pad A Equity:O (01-03), balance Equity:O -100 (01-05), balance A 100 (01-10) clean, pads A 100 clean (fixed by #2898) clean, now pinned
pad A:Sub, balance A 100 in between, balance A:Sub 100 clean clean (#2898) clean, now pinned
pad A, balance A:Sub 100 (30 in A:Other), balance A 200 pads A 70; Balance failed A:Sub (0) and A (100) pads A 170; only A:Sub fails same as beancount
pad A, balance A:B 30 (held), balance A 100 Unused Pad entry; Balance failed A (30) pads A 70, clean same as beancount
pad A and pad A:Sub (same day), balance A:Sub 40, balance A 100 pads A 40 and A:Sub 40; Balance failed A (80) pads A:Sub 40, A 60, clean same as beancount
pad A:B, balance A:B 100, pad A, balance A 150 pads A:B 100, A 150; Balance failed A (250) pads A 50, clean same as beancount
pad A B, balance A 100, pad B Equity:O, balance B 0 Unused Pad entry; Balance failed B (-100); BQL B -100 pads B 100, clean; BQL B 0 same as beancount
pad onto 10 STK {10 USD}, balance 15 STK Attempt to pad an entry with cost; pads 5 STK pads 5 STK, nothing reported E2005 once; pads 5 STK
the same with two lots the error twice nothing reported E2005 twice
holds 10 STK at cost, balance 10 STK Unused Pad entry same same
100.004 held, balance 100.00, then balance 100.004 Unused Pad entry, nothing else pads -0.004; Balance failed on 100.004 (got 100.000) same as beancount
99.5 held, balance 100 ~ 1, then balance 100 Unused Pad entry; Balance failed (99.5) pads 0.5, clean same as beancount

The E2005 message is word for word what bean-check prints (since round 2 it goes through the canonical python_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, BQL SELECT account, sum(position) GROUP BY account and SELECT * FROM #balances on 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 Ledger payload gains tolerance_multiplier, so fromCache pads with the ledger's own option. It also gains directive_lines and directive_file_ranks, so a restored ledger orders pad ties as getErrors() does. The cached error lists change.

Breaking

  • The pad functions take tolerance_multiplier.
  • rustledger_validate::balance_tolerance is now rustledger_booking::balance_tolerance.
  • ErrorCode gains PadWithCost.
  • rustledger_ffi_wasi::helpers::{LoadResult, FileLoad} gain tolerance_multiplier.

These are listed in the CHANGELOG.

How to test

cargo test -p rustledger-validate --test pad_parity_test
cargo test -p rustledger-booking --lib pad
cargo test --workspace --all-features --no-fail-fast

Gates I ran: the full workspace tests (6,604 passed), clippy -D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps, cargo fmt --check, and the STRICT_BASELINE=1 corpus and CST baselines.

Review round 1

  • Linear again. Each pad group keeps a running total of its real postings, as beancount keeps pad_balance. The total is seeded once, from one subtree walk, when the group's first pad comes. 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 new test_plan_pads_parent_pad_reads_its_subtree_once counts accounts read: 401 for 400 sub-accounts, where the per-balance walk reads 160,801 and fails it. E2005 only walks the subtree for a currency that some posting booked at cost.
  • The tolerance multiplier is pinned. pad_parity_test now runs each shape under its own tolerance_multiplier, and a multiplier-2 shape is added: 99.97 held, pad, balance 100.00 USD gives Unused Pad entry and no padding (bean-check). New loader tests in balance_view_test.rs check the same ledger through Ledger::balance_view and validation, and check that inferred_tolerance_default "USD:0.05" is ignored there, padding 0.03 (bean-query). These mutations now each fail a test:
    • DEFAULT_TOLERANCE_MULTIPLIER in the validator's plan_pads call,
    • the same in Ledger::balance_view,
    • doubling the balance check's tolerance (caught by a new shape where a later balance is just beyond the tolerance: 0.016 against 0.01).
  • E2005 counts merged positions. Lots are gathered into one inventory first, so the same lot held in A:B and A:Sub is one position and gives one error, as in beancount ((14 STK { 10 USD, 2024-01-02})).
  • E2005 shows 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's pad_balance). Other pads' padding is no longer shown. With pads on A:B and then A, both messages are (10 STK { 10 USD, 2024-01-02}), as in bean-check.
  • E2005 is 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.py now classifies ^E200[345]$ as pad errors.
  • Held FFI options. An empty tolerance_multiplier still 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, so info() echoes what pads. This has a new test.
  • Merged origin/main twice. The first merge brought in fix(parser)!: require a flag or txn after a transaction's date, as beancount does #2909. The second brought in perf(booking)!: merge padding transactions in one pass, not one insert each #2919 (its linear merge_padding_into_sorted is kept, with tolerance_multiplier threaded 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.
  • Comparing release builds of this branch and main (943cb82) across all 1,045 in-tree and compatibility ledgers (check, report balances, BQL sum(position), #balances) found no difference, byte for byte. That includes the 23 ledgers with a pad line in my copy of the corpus.
  • Release timings for 10k sub-accounts, each with a daily pad on the parent and a balance on the sub-account: check takes 0.39 s user on this branch against 0.51 s on main, and BQL sum(position) 0.22 s against 0.40 s. Both of these regression tests pass: test_plan_pads_parent_pad_reads_its_subtree_once and perf(booking)!: merge padding transactions in one pass, not one insert each #2919's test_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

  • The E2005 check is scoped to the subtree.
    • Before: the gate was "this currency was ever booked at cost anywhere in the ledger", so a single lot elsewhere made every padded balance walk the target's whole subtree (B2).
    • Now the plan records, per currency, the accounts a posting at cost was booked to. PlannedPadding::held (now an Option) is copied only when one of those accounts is under the pad group, found with one range query that stops at the first match.
    • The validator keeps the same per-currency index (LedgerState::cost_accounts) and reads only those accounts under the target.
    • New guards in validators::balance::tests count 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.
  • No copy of every currency per padding.
    • A group's running totals and its padding are now hash maps.
    • held is built only when a cost lot may fire E2005, and the validator moves it instead of cloning it.
    • Guard test_plan_pads_copies_holdings_only_for_a_lot_at_cost. It fails when the copy is made for every padding.
  • Overflowed totals stay linear.
    • A running total that leaves Decimal's range now carries on in BigDecimal. It reads as unrepresentable only while it is out of range, and it is never re-summed.
    • Guard test_plan_pads_overflowed_group_total_reads_its_subtree_once: 303 reads. The previous implementation reads 91,203 and fails it.
  • The E2005 message matches beancount.
    • python_inventory_str and python_position_str move from rustledger-query to rustledger-core (CANONICAL: BQL str(), the conversions narration, and now E2005 all use them).
    • The message is now word for word what bean-check prints, sorted the same way. Probe p29 is a parity shape: (20 USD, 5 STK, 10 STK {10 USD, 2024-01-02}).
  • rustledger_core::strict_subaccounts is the range query behind for_each_strict_subaccount, exposed as an iterator.
  • Merged origin/main (fix(lint): load every lint's ledger through one shared helper, and refuse failed processing in closed-nonempty #2922).

Release timings (user CPU seconds, one run each on a shared machine; check is rledger check --no-cache, BQL is SELECT account, sum(position) GROUP BY account):

Scenario main check PR check main BQL PR BQL
A: 10k sub-accounts, parent pad before each sub-account's balance 0.61 0.48 0.22 0.25
B2: A in STK, plus one 1 STK {10.00 USD} lot outside the subtree 0.66 0.57 0.21 0.27
B2 at 20k 0.90 0.65
C: one account with 2,000 currencies, one pad, 2,000 balances 0.05 0.11 0.11 0.15
C at 5,000 currencies 0.29 0.49
D: 10k leaves 8 levels deep, pad on the top account 0.70 0.45 0.25 0.16
E: A at 20k with two sub-accounts holding 5e28 USD each 0.91 0.66 0.21 0.22
  • Every row is linear now. Before this round, B2 at 10k took 14.8 s, C at 2,000 took 6 to 12.5 s, and E at 20k took 11.2 s.
  • C grows faster than linear on main too: main keeps an account's per-currency totals in a small vector. The PR stays within about 2x of main there.
  • Peak memory is within about 25 MB of main in every case.

Checks on the final branch:

  • All round-1 mutations still fail their tests: the validator's and balance_view's default multiplier, the doubled tolerance, the sub-account lot walk removed, padding within tolerance, and the E2005 check dropped.
  • On the 23 corpus ledgers with a pad line, and on all 1,045 in-tree and compatibility ledgers, release builds of this branch and main produce byte-identical output for check, report balances, BQL sum(position) and #balances.

Review round 3

There is now one rule, in one place, as beancount's pad.py has it.

  • Each pad group keeps beancount's pad_balance itself.
    • The group holds a running inventory of the real postings under its account plus its own padding.
    • Positions, lots at cost included, merge the way Inventory.add_position merges them. A lot that nets to zero is dropped, and a dropped lot that comes back goes last, as a Python dict key does.
    • Positions keep the order they came in.
    • Groups exist from the start of the walk, so a posting updates the groups of its account and its ancestors, which is O(depth).
  • E2005 comes from the plan.
    • rustledger_booking::plan_pads reads E2005 from the group's inventory as PlannedPadding::at_cost: Option<PaddedAtCost>, which holds the lots at cost and the inventory printed through the canonical python_inventory_str.
    • The validator only reports it, and process_pads reports it too.
    • Removed: the validator's cost_accounts index, lots_at_cost and shown_balance, and the plan's held copy with its cost-account gate.
  • Ties print as bean-check prints them. The tie1 to tie4 parity shapes were each checked byte-identical against bean-check 3.2.3:
    • tie1: lots of one cost in two sub-accounts;
    • tie2 and tie4: plain positions in posting order and reversed;
    • tie3: lots of several currencies.
  • Linearity guards count the work done. The counted units are group updates per posting and positions printed. They cover the review's scenarios A, E, F, F2 and H. A separate plan-level test asserts that a lot outside the group computes nothing for it.
  • Overflow deviation documented. RunningTotals now carries the AGENTS.md deviation comment. A running total that passes through 100000000000000000000000000001 stays 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_exact pins our behavior.
  • sell_gains now prints its inventories through python_inventory_str instead of its own copy of CURRENCY_ORDER and the sort key. Its tests and the corpus are unchanged.
  • The CHANGELOG Breaking entry names PlannedPadding::at_cost (PaddedAtCost) and the move of python_inventory_str to core.
  • Merged origin/main (fix(parser): keep a BOM inside a string literal as string content, as beancount does #2926, fix(loader)!: keep an option's previous value when its new value is rejected, and refuse queries over a rejected booking_method #2923). In the held-options session, the tolerance-multiplier check and fix(loader)!: keep an option's previous value when its new value is rejected, and refuse queries over a rejected booking_method #2923's booking-method check now both run.

Mutations. Each of these fails a test:

  • the 6 round-1 mutations (the validator's and balance_view's default multiplier, the doubled tolerance, a group missing its sub-accounts' lots, padding within the tolerance, the E2005 check dropped);
  • M1a: a group counting lots of every currency;
  • M2: printing the inventory for every padding;
  • M3: dropping the wide total.

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.

Scenario main PR
A: 10k sub-accounts, parent pad before each sub-account's balance 0.68 0.53
A2: A's BQL sum(position) 0.42 0.27
B2: A in STK, one lot at cost outside the subtree 0.75 0.48
C: one account with 2,000 currencies 0.08 0.10
D: 10k leaves 8 levels deep, pad on the top account 0.69 0.67
E: 20k, two sub-accounts holding 5e28 USD each 1.71 1.37
F: 5k sub-accounts each keeping a lot at cost (E2005 at every balance) 0.41 0.52
F2: 20k sub-accounts buying and selling a lot with {} 2.68 1.79
H: 5k, one lot in P and 5k lots in other currencies outside P 0.47 0.54

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 pad line. Compared: check, report balances, BQL sum(position), #balances, and str(sum(position)).

Review round 4

  • Sub-account order within one transaction.
    • Beancount fills a pad group's postings account by account, in the order realization.postings_by_account first met each account. It then stable-sorts them by date, type and line, and one transaction's postings share a line.
    • The plan now ranks each account when the walk first meets it, registering the same directives realization.py registers: open, close, balance, note, document, a pad's account and then its source, a custom's account values, and postings as written.
    • Each transaction's postings enter the groups in that rank order.
    • New parity shapes cover both open orders, (1 DDD, 1 CCC, ...) against (1 CCC, 1 DDD, ...), and accounts first met through a posting.
  • A joined lot prints its latest cost, as add_amount rebuilds 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}).
  • Guards count inventory work where it happens.
    • Every GroupInventory::add, every lot check and every printed position is counted.
    • The bounds are exact per scenario: per posting one add, per padding one lot check and one add, plus the positions printed.
    • In a scratch copy I applied a mutant that rebuilds the group inventory at each padding by re-walking its log in order. It fails 5 guards.
  • E2005 beside an unrepresentable group. The validator now reports E2005 before the overflow early return. A balance where one group cannot be represented and another pads at cost now reports it, as process_pads does. There is a new test, and putting the check back behind the return fails it.
  • strict_subaccounts is removed: it had no caller. The for_each_strict_subaccount doc no longer names plan_pads. The process_pads and PadResult::errors docs now name E2005.
  • Each new behavior is mutation-checked. Dropping the rank sort, keeping the first cost, and moving the validator check back each fail a test.

Review round 5

  • Accounts are ranked in beancount's entry order. A same-date pad now meets its accounts at its own line.

    • New core key rustledger_core::beancount_entry_sort_key. It is beancount's entry_sortkey, (date, SORT_ORDER, lineno), with the source location (file id, offset) standing for the line, and it has a core test. booking_sort_key differs from it only for pad.
    • plan_pads ranks accounts in one pass ordered by that key, before the walk. The walk itself keeps the booking order.
    • Source locations reach the plan from the validator (span_info), from merge_with_padding_spanned and from Ledger::balance_view, through the new process_pads_spanned.
    • Plain process_pads falls 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.
    • New parity shapes: a note, a transaction, or a custom written before a same-date pad, each (1 CCC, 1 DDD, ...) as bean-check prints it.
    • A loader test (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 one 2023-12-31 line naming Assets:A:D ((1 DDD, 1 CCC, ...)):

    • note
    • document
    • balance 0 DDD
    • a pad's source
    • a pad's account
    • custom "x" Assets:A:D
    • custom "x" "s" Assets:A:D 2 Assets:A:C
    • close
    • a posting (, 1 EEEE last)

    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.

  • see looks 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_at pads plain directives with a parallel list of SourcePositions.
  • process_pads keeps 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 plain merge_with_padding, which discards errors.
  • WASM: helpers::pad_expansion pads with the kept spans for both expandPads surfaces.
  • WASM validation now uses spans. The WASM ledgers validate with their spans, as rledger check and 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. Cached ParsedLedger errors change; this is noted under WASM v91.
  • ffi-wasi: expand_pads takes a position_of for its tags, either line_position or file_line_position (file id from the source map, then line).
  • New drift guard: rustledger-wasm test_pad_at_cost_ties_agree_across_surfaces uses one ledger with a note written above a same-date pad.
    • The E2005 text and order match bean-check's (1 CCC, 1 DDD, ...) through the validator (rledger check), process_pads_spanned, the WASM expansion, and WASM validation.
    • The padding is the same through balance_view, the WASM expansion, and ffi-wasi expand_pads.
    • Unlocating the WASM expansion fails the guard. So does unlocating WASM validation.

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.

Scenario main PR
A 0.27 0.21
A2 (BQL sum(position) on A) 0.15 0.11
B2 0.28 0.19
C 0.02 0.04
D 0.29 0.21
E 0.58 0.46
F 0.17 0.19
F2 0.92 0.80
H 0.18 0.20

Corpus. I compared release builds on all 1,045 in-tree and compatibility ledgers, producing six outputs for each, 6,270 in total:

  • check
  • check with plugin "beancount.plugins.sellgains"
  • report balances
  • BQL sum(position)
  • #balances
  • str(sum(position))

All 6,270 are byte-identical. In 7 of them (check with sellgains), the only difference is the scratch directory name in an absolute path the error message prints.

Review round 6

  • wasm-pack test --node compiles 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. SourcePosition is now the line beancount uses in entry_sortkey: the line in its file, whichever file that is, and 0 for a plugin's entry.

    • The validator reads lines 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 byte offset stands in (plus 1), which orders one file the way its lines do, and a plugin's directive is 0. The single-source WASM, the FFI and the LSP buffer validation use this fallback. helpers::offset_lines gives the WASM expansion the same values.
    • New loader tests are checked against bean-check 3.2.3:
      • 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: an auto_accounts open ranks first.
    • Both tests fail when the loader stops passing lines, and when plugin entries stop being line 0.
    • The "known difference" text about cross-file order is gone from this body.
  • A restored WASM Ledger keeps its lines. The Ledger now keeps directive_lines and stores them in its cache payload (still WASM v91), so fromCache(...).expandPads() answers as getErrors() does.

    • from_files now delegates to a native from_file_map.
    • The drift guard covers the multi-file Ledger before and after a cache round trip.
    • Dropping the restored lines fails it, and so does dropping the ParsedLedger offsets.
  • Removed: process_pads_spanned. The merges discard errors, so only process_pads_at (the WASM expansions) needs lines.

  • ffi-wasi expand_pads is back to main's API. It only pads, and no input order changes padding. position_of, line_position and file_line_position are gone.

  • CHANGELOG now says:

    • the validation change covers validateSource and ParsedLedger (fromFiles / validateMultiFile already went through the loader);
    • errors now carry column / end_line / end_column;
    • the E2001 hint now prints tolerance: 0.10.

    The v91 note now says both payloads' error lists move, and that Ledger gains directive_lines.

Verification:

  • Workspace tests: 6,698 passed, 0 failed.
  • wasm-pack test --node: 31 passed.
  • Clippy -D warnings, rustdoc -Dwarnings, fmt and the STRICT baselines are clean.
  • Corpus: release builds of this branch and main (d21a576) are byte-identical across all 1,045 ledgers, 6,270 outputs in all (check, check with sellgains, report balances, BQL sum(position), #balances, str(sum(position))).

Review round 7

  • The FFI component validates with the ledger's options. Before this, validate and load built ValidationOptions::default(), which ignored tolerance_multiplier.
    • ffi-wasi's LoadResult now carries validation_options. It is built with the canonical validation_options_from_options plus the source map's positions, and the component validates with it.
    • The WASM validation (validateSource, ParsedLedger) also used a default set. It now builds its options the same way.
    • New drift guards: test_validate_and_load_read_the_tolerance_multiplier_as_check_does (ffi-component) and test_wasm_validation_reads_the_tolerance_multiplier_as_check_does (WASM). Each compares the surface with rledger check on two ledgers with option "tolerance_multiplier" "2" and 99.97 held. With a pad before balance 100.00 USD, bean-check 3.2.3 and check give Unused Pad entry. Without the pad, both give nothing.
    • Putting the default options back fails each guard.
  • Plugin entries use the line the plugin gives them.
    • SourcePosition is now a struct holding the line and the file's place in the load.
    • rustledger_loader::source_lines reads a placeholder's stored line. The placeholder table is now shared through an Arc, so placeholders a plugin adds after the session started are still seen.
    • The WASM offset_lines is replaced by source_positions, which goes through the same source_lines.
    • The validator's fallback, with no source map, still gives a plugin's directive line 0, because the line lives in the source map. This is documented on ValidationOptions::source_lines. Every surface that has a source map now passes it: the loader, the LSP, ffi-component and the WASM.
    • auto_accounts numbered 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's enumerate(sorted(accounts_first.items())) does.
    • currency_accounts now sets lineno to its sorted index. It used to set none.
  • s4 checked against bean-check 3.2.3. The ledger has an explicit open Assets:A:C on line 1 and auto_accounts.
    • bean-check prints (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 from Assets:A:B1 = 1 tying with C on line 1 (the plugin's entry goes first), then B2 = 2, then D = 4.
    • origin/main and round 6 printed (1 B1X, 1 B2X, 1 DDD, 1 CCC, ...). This round matches bean-check.
    • Pinned in test_pad_ranks_a_plugins_open_by_the_line_the_plugin_gives_it and in the WASM drift guard, which covers check, ParsedLedger, Ledger and its cache round trip.
    • test_created_open_is_numbered_by_its_sorted_place pins currency_accounts.
    • The docs that said "0 for a plugin's entry" are updated (beancount_entry_sort_key, SourcePosition, the tests).
  • Cross-file ties: partly done. I stopped where the include graph is missing.
    • 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:

      Shape bean-check round 6 this round
      s1: nested include, one level (1 CCC, 1 DDD, 1 EEE, ...) same same
      s3: same-line note in main, pad in include (1 CCC, 1 DDD, ...) (1 DDD, 1 CCC, ...) same as bean-check
      s3, swapped (1 DDD, 1 CCC, ...) same same
      s1b: main includes x then y, x includes z (1 XXX, 1 YYY, 1 ZZZ, ...) (1 XXX, 1 ZZZ, 1 YYY, ...) (1 XXX, 1 ZZZ, 1 YYY, ...), a known difference, pinned
    • True breadth-first order needs the include graph, and the graph is not where it is needed. load_recursive records no parent per file, so the SourceMap has 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 (loader CACHE_VERSION 68 to 69, and the WASM pin and version with it); and derive the BFS rank in source_lines. That is a cache-format change, so I stopped as instructed. It is a self-contained follow-up if wanted.

  • Nits.
    • source_lines no 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.
    • New source_lines_overlaid reads 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).
    • Unit tests cover the new behavior: later placeholders, dropped text and the overlay.
    • CHANGELOG: the repo has no "Added" section, and new public items are listed inside the Breaking and Fixed entries (for example "Inventory::add_with_total is new", "posting_lot_total is 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.
  • Merged origin/main (fix(query): bound expression depth for long operator chains #2927, d21a576). The CHANGELOG conflict is resolved with both entries kept. Main still holds WASM 90 / loader 68, so this stays WASM v91 with pin 68. The v91 note now names directive_file_ranks and the validation-options change.

Mutations, each caught:

  • file rank always 0;
  • placeholder line ignored;
  • plugin entries ranked after files;
  • auto_accounts numbering only the accounts it opens;
  • currency_accounts numbering only the accounts it creates;
  • the WASM positions back to byte offsets;
  • the WASM and ffi-component options back to default.

Verification:

  • Workspace tests: 6,721 passed, 0 failed.

  • wasm-pack test --node: 35 passed.

  • Clippy -D warnings, rustdoc -Dwarnings and 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, BQL sum(position), #balances, str(sum(position))).

  • Timing on a generated 120k-line, 251-file ledger with 250 pads (rledger check, hyperfine, 20 runs):

    • main 62.6 ms ± 2.7;
    • round 6 72.3 ms ± 1.7;
    • this round 71.0 ms ± 2.6.

    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.

    • A posting outside every pad group no longer runs Position::from_posting and is not added to the transaction's group list. PadTracker::covers answers once per account whether the account falls in a group.
    • The entry order only shows inside an "Attempt to pad an entry with cost" message, so two steps now run only when a posting under some group carries a cost (order_if_costs, a pre-scan): the account ranking pass, and the sort in post_transaction. In that case see ranks only accounts that fall in a group, and a transaction's postings are sorted only when two of them fall in one group.
    • New rustledger_booking::pad_plan_reads_positions reports 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.
    • New test: test_pad_tracker_ranks_only_when_a_group_holds_a_cost.
    • Every linearity guard and parity test still passes.
  • Timing. rledger check, hyperfine, 25 runs, against main d21a576 (before the merge, on a quieter machine):

    Ledger main this PR
    pads: 251 files, 120k lines, 250 pads 60.8 ms ± 2.3 65.4 ms ± 2.0 +8%
    pads with lots at cost under each group 259.6 ms ± 13.0 268.7 ms ± 6.4 +4%
    no pads (same ledger without pads) 58.6 ms ± 2.3 58.3 ms ± 2.3 0%
    one pad in 30k transactions (no postings under it) 57.1 ms ± 2.5 56.1 ms ± 2.6 0%
  • CHANGELOG. The Fixed entry now also says:

    • BQL filename / lineno and the #accounts meta for auto_accounts and currency_accounts opens now match bean-query;
    • an error on a currency_accounts open 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.rs conflicts are resolved with both sides kept.

Verification, after the merge:

  • Workspace tests: 6,747 passed, 0 failed (the loader, ffi and wasm crates included).
  • wasm-pack test --node: 35 passed.
  • Clippy -D warnings, rustdoc -Dwarnings and fmt are clean.
  • Corpus: release builds of this branch and main be6193f are byte-identical across all 1,045 ledgers × 6 outputs.

Closes #2901

🤖 Generated with Claude Code

…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]>
@robcohen
robcohen requested a review from a team as a code owner November 9, 2026 16:29
@github-actions

github-actions Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 51.7ms ± 3.7ms 798.9ms ± 6.0ms 15.5x 45.1 MB / 51.0 MB
investment 76.5ms ± 0.6ms 2911.7ms ± 37.0ms 38.1x 47.1 MB / 59.0 MB
fifo 74.9ms ± 0.9ms 14570.8ms ± 68.1ms 194.7x 49.1 MB / 59.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 50.6ms ± 0.5ms 51.7ms ± 3.7ms +2.1% ✅ within noise 45.1 MB → 45.1 MB (+0.1%)
investment 75.9ms ± 0.7ms 76.5ms ± 0.6ms +0.7% ✅ within noise 46.9 MB → 47.1 MB (+0.3%)
fifo 73.7ms ± 0.5ms 74.9ms ± 0.9ms +1.6% ✅ within noise 48.8 MB → 49.1 MB (+0.6%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 1.7ms, investment 0.4ms, fifo 0.5ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 826
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@codecov

codecov Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.94073% with 32 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/pad.rs 96.98% 22 Missing ⚠️
crates/rustledger-validate/src/lib.rs 82.75% 10 Missing ⚠️

📢 Thoughts on this report? Let us know!

robcohen and others added 2 commits November 9, 2026 21:30
…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]>
robcohen and others added 4 commits November 10, 2026 05:01
…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]>
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]>
robcohen and others added 3 commits November 10, 2026 11:33
…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]>
robcohen and others added 3 commits November 10, 2026 15:12
…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]>
…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
robcohen merged commit d728311 into main Nov 11, 2026
71 of 72 checks passed
@robcohen
robcohen deleted the fix/pad-remaining-parity branch November 11, 2026 02:51
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Pad behaviour still differs from beancount: padding date, parent/child accounts, cost positions, tolerance

1 participant