Skip to content

fix(validate)!: pad from one shared plan as beancount does, and drop E2004 - #2898

Merged
robcohen merged 6 commits into
mainfrom
fix/pad-balance-parity
Nov 9, 2026
Merged

robcohen merged 6 commits into
mainfrom
fix/pad-balance-parity

Conversation

@robcohen

@robcohen robcohen commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

What changed

The validator's padding was a second implementation of rustledger_booking::process_pads, and the two had drifted from each other and from beancount (#2896). Now there is one pad computation, rustledger_booking::plan_pads. It follows beancount's ops/pad.py on the points below; it still differs from it on others (other pads' padding in the inventories it measures, balances on child accounts, cost lots, tolerance), tracked in #2901:

  • Inventories cover every account a posting names, opened or not.
  • Per target account, a balance uses the latest pad dated strictly before it.
  • A balance in a currency uses up that currency for the pads before it, whatever its difference.
  • A pad is used only when it inserts padding. Otherwise it is an Unused Pad entry (E2003).

It has two consumers:

  • process_pads writes the plan out as the padding transactions that rledger report balances, BQL and #balances read.
  • The validator computes the plan over its late stream, in its own walk order. It adds each padding entry to its booked inventories at the pad, where beancount dates and inserts its padding entry. Balances are then compared plainly; the validator has no pad logic of its own.

E2004 is removed (see Breaking below).

Canonical vs drift guard

The validator now calls the canonical. It runs plan_pads once, only when the stream has a pad, over the sorted view it already walks. So it neither re-sorts nor copies the directives.

What each side still computes for itself is the inventory a balance is compared against: booked lots in the validator, units in process_pads. The drift guard crates/rustledger-validate/tests/pad_parity_test.rs compares the two end to end. It covers every #2896 shape, plus the pad-date shape and the p15 shape below, with an ordinary pad as a control. On each shape it checks that:

  • the validator's balance failures equal the failures on the same ledger with each pad replaced by process_pads' padding;
  • the unused pads agree;
  • both match bean-check / bean-query.

It fails against the round-1 code, on the pad-date shape.

Before / after, against beancount 3.2.3 (full bean-check / bean-query output)

Shape beancount main this PR
pad to an unopened target, txn -30 into it, balance 100 (never opened, or opened later) target 100, source -130 70 / -100 100 / -130
unopened target whose txns already reach the balance no padding, Unused Pad entry pads a further 100 no padding, E2003
balance on an unopened target (50 held, 100 asserted) Balance failed skipped (never opened) E2001
same, balance holds no failure no failure no failure
all open: pad, balance 0, balance 10 Unused Pad entry + Balance failed nothing E2003 + E2001
same with an unopened target unused + failed E1001s only E1001s + E2003 + E2001
pad 01-09, pad 01-10, balance 100, balance 200 Unused Pad entry (01-09) + Balance failed (01-12) E2004 only E2003 (01-09) + E2001 (01-12)
p15: pad 01-02, balance 100 USD, pad 01-04, balance 10 EUR, balance 50 USD clean false E2004 clean
pad Assets:A Equity:O 01-03, balance Equity:O -100 USD 01-05, balance Assets:A 100 USD 01-10 clean false E2001 on Equity:O clean
account referenced before its later open (posting, pad, balance) Invalid reference to inactive account "used on D but not opened until O" / "was never opened" "is inactive on D (not opened until O)" for all three

The E1001 lines are otherwise unchanged. bean-check repeats an unknown account's error per directive, as discussed on #2895.

Breaking: E2004 removed

E2004 ("Multiple pad directives") was an rledger-only error. The superseded pad is an E2003, which is what beancount reports for it. E2004 also fired falsely, on p15.

It is removed from:

  • the validator;
  • ErrorCode (MultiplePadForBalance) and its code tables;
  • the LSP code lens BALANCE_ERROR_CODES;
  • the tests.

docs/reference/errors.md and spec/core/validation.md keep the number as "removed in 0.25.0" and retired, so it is not reused. The CHANGELOG entry is under Breaking.

Performance

plan_pads measures each padded balance through a prefix index: rustledger_core::for_each_strict_subaccount, one range query shared with the validator's sum_account_subtree. It keeps units only, not lot inventories. Round 2 scanned every account per padded balance, which made rledger check and the LSP quadratic.

test_plan_pads_sums_each_balance_over_its_subtree_only counts the accounts read, where they are read (a newtype over the totals counts every get and every iteration). With 2,000 accounts it reads 2,000. A plain scan that adds only the matching accounts reads 4,003,999 and fails it. In core, for_each_strict_subaccount_visits_exactly_the_strict_subtree checks the exact strict subtree on 8,655 generated names (deep, Unicode, prefix siblings, shared paths across roots) and bounds the keys read per query with a counting key. A filtered full scan in core reads 8,655 per query and fails it.

rledger check (release, min of 9 interleaved runs) on N accounts, each with a transaction, a pad and a balance. The machine was loaded, so absolute numbers are noisy; compare the columns.

N main round 2 (from the review's run; main was 0.34 / 0.80 / 3.1 s there) this PR
10k 0.46 s 1.44 s 0.43 s
20k 0.58 s 7.0 s 0.61 s
40k 0.70 s 46.6 s 0.82 s

Still quadratic, on main as well (not changed here): merge_with_padding inserts each padding transaction into the sorted vector one by one, as its doc already notes, with a revisit condition. So BQL and report balances on this shape take 35 s at 40k on main and 32 s here. A one-pass merge would fix it; that is a possible follow-up.

Corpus comparison

I compared origin/main and this branch, each built in its own target dir, on all 1,136 ledgers (405 in-tree, 731 compat). Each run captured rledger check, rledger report balances, SELECT account, sum(position) GROUP BY account and SELECT * FROM #balances.

  • report balances: unchanged on every file.
  • BQL rows: unchanged. Only the error preamble printed before the table differs.
  • Exit status: unchanged on every file.
  • 63 files differ:
    • 59 gain Balance failed for a balance on an account with no open, plus the matching #balances discrepancy. Each of them already failed on that account's E1001, so no ledger goes from passing to failing.
      • On 57, bean-check reports the same number of Balance failed errors.
      • The other 2 are the two copies of ParserEntryTypes.BalanceWithCost. bean-check drops that balance over a syntax error ({ on a balance). rledger reports the parse error (P0012) and still validates the recovered balance, so it is not comparable.
    • 4 change only the not-yet-open wording, from "used on D but not opened until O" to "is inactive on D (not opened until O)": fava tests_data_errors, cozumel2015, and the loader glob_test fixtures.
  • No corpus file changes its unused-pad count, and none has an E2004.

Other behavior to note

The advisory E1004 (not reported by check; reported by rledger lint closed-nonempty) now sees padding in a source account that is closed later on the pad's day, because the padding is dated at the pad. This is the same as any posting before a close, and it is pinned in test_validate_pad_reports_a_closed_account.

Cache

WASM CACHE_VERSION 85 (loader v63, unchanged by this PR), because cached error lists change. v84 is #2872's (via #2903) and v82 #2893's, both merged in from main; v83 was never released. The loader cache is unaffected.

Not in this PR (possible follow-up)

beancount pads only when the difference exceeds the balance tolerance, but plan_pads pads any non-zero difference. For example, 100.004 held against balance 100.00 is padded by -0.004 where beancount pads nothing. Fixing that needs balance_tolerance moved from rustledger-validate down to booking.

How to test

cargo test -p rustledger-booking --all-features pad
cargo test -p rustledger-booking --test tla_behavior_replay
cargo test -p rustledger-validate --test pad_parity_test
cargo test -p rustledger-validate --test validation_integration_test pad
cargo test -p rustledger --test decimal_overflow_test

Verification

  • cargo test --workspace --all-features --no-fail-fast passes. The CLI snapshots for validation-errors.beancount are updated: its balance on a never-opened account now fails, and bean-check agrees.
  • cargo clippy --workspace --all-features --all-targets -- -D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps and cargo fmt --check pass.
  • STRICT_BASELINE=1 corpus and CST baselines pass. No parser change, so no baseline rows moved.
  • The new tests fail with the fix reverted:
    • against main: the process_pads unit tests, the TLA pad replay, the drift guard and the integration tests;
    • against round 1: the drift guard (pad-date shape), the p15 and two-pad tests, and the closed-source advisory.

Closes #2896

🤖 Generated with Claude Code

…eancount does

The validator padded its own inventories with a second copy of the pad
rule in `rustledger_booking::process_pads`, and the two drifted from each
other and from beancount (#2896). Both now go through one
`rustledger_booking::PadTracker`, beancount's `ops/pad.py` rule: the
latest pad dated before a balance, once per currency, a zero difference
using the currency up without using the pad, and a superseded pad never
used again. Each side keeps its own inventories, and a new drift guard
(`pad_parity_test`) compares them end to end on the #2896 shapes.

- An unopened target's own postings count: bean-query 100 / -130, where
  it padded 70 / -100. One its postings already satisfy is not padded,
  and the pad is unused.
- A balance on an unopened account is compared (E2001).
- `pad`, `balance 0`, `balance 10` is E2003 plus E2001.
- A superseded pad no longer pads a later balance (E2003 plus E2001).
- A pad or balance before the account's later open says the account is
  inactive, not never opened.

WASM cache v83 (v82 is #2893's).

Closes #2896

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 8, 2026 07:56
@codecov

codecov Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.36842% with 22 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/pad.rs 94.85% 14 Missing ⚠️
...ates/rustledger-validate/src/validators/balance.rs 85.00% 6 Missing ⚠️
crates/rustledger-core/src/inventory/mod.rs 98.48% 1 Missing ⚠️
crates/rustledger-validate/src/lib.rs 98.61% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 52.4ms ± 2.2ms 787.9ms ± 3.1ms 15.0x 43.2 MB / 51.1 MB
investment 78.8ms ± 0.6ms 2904.9ms ± 17.0ms 36.9x 58.9 MB / 59.1 MB
fifo 75.2ms ± 1.0ms 14572.8ms ± 56.7ms 193.8x 44.9 MB / 59.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 51.4ms ± 0.4ms 52.4ms ± 2.2ms +2.1% ✅ within noise 42.8 MB → 43.2 MB (+0.8%)
investment 78.3ms ± 0.9ms 78.8ms ± 0.6ms +0.6% ✅ within noise 53.8 MB → 58.9 MB (+9.5%)
fifo 75.7ms ± 1.1ms 75.2ms ± 1.0ms -0.7% ✅ within noise 54.8 MB → 44.9 MB (-18.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 1.0ms, investment 0.5ms, fifo 0.7ms), 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 8, 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

…E2004

The validator now takes its padding from `rustledger_booking::plan_pads`,
the computation `process_pads` is built on, instead of a rule of its own,
and adds each padding entry to its inventories at the `pad`, where
beancount dates it. A balance on the pad's source between the pad and the
balance it satisfies no longer fails falsely.

BREAKING CHANGE: E2004 (multiple pads for one balance) is removed, with
`ErrorCode::MultiplePadForBalance`. A superseded pad is an unused pad
(E2003), as in beancount, and E2004 fired falsely on a pad that had already
padded another currency. The code is retired in the docs.

- A pad amount that cannot be computed or applied is reported at its
  balance, which is not compared, as before.
- One not-yet-open wording for postings, pads and balances: "is inactive
  on D (not opened until O)".
- `account_inventory` uses the entry API.
- Drift guard and integration tests cover the pad-date shape and the
  currency case (p15), both clean in bean-check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen robcohen changed the title fix(validate): apply one pad rule to padding and balance checks, as beancount does fix(validate)!: pad from one shared plan as beancount does, and drop E2004 Nov 9, 2026
`plan_pads` summed each padded balance's subtree by scanning every
account, so `rledger check` and the LSP, which now run it on any ledger
with a pad, were quadratic: 40k accounts with a pad and a balance each
took 46 s. It now keeps a lexical index of its accounts and visits a
subtree by range query, through `rustledger_core::for_each_strict_subaccount`,
which the validator's `sum_account_subtree` now shares. It also keeps
units per currency instead of lot inventories, the only thing a pad reads.

A regression test counts the inventories read: 2,000 for 2,000 padded
balances, where the scan read 4,003,999.

Also corrects the #2895 CHANGELOG entry (no E2004, both padding halves
land) and the PadCorrect spec comment (padding is dated at the pad).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen and others added 3 commits November 9, 2026 00:52
Resolves the WASM cache and CHANGELOG conflicts with #2897: v82 is
#2897's (loader v62), and this branch's note moves to v83 over loader
v62.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tches

The complexity test counted matches inside `subtree_units`, so a plain
scan that adds only the matching accounts passed it. Account totals are
now a newtype whose `get` and iteration count each account where it is
read: 2,000 reads for 2,000 padded balances, and 4,003,999 with that scan
swapped in.

A core test pins `for_each_strict_subaccount` on 8,655 generated names
(deep trees, Unicode, prefix siblings such as Assets:A / Assets:AB, the
same paths under several roots): it visits exactly the strict subtree,
and reads few keys per query through a counting `Borrow<str>` key, so a
filtered full scan in core fails it (8,655 keys per query). The function
is generic over the key for that.

Also notes that units alone cannot answer beancount's pad-at-cost check
(#2901), and that `PadInventories::add` skips `Inventory::add`'s
near-ceiling check (#2554).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolves the WASM cache and CHANGELOG conflicts with #2903: v84 is
#2872's (loader v63), and this branch's note moves to v85 over loader
v63 (v83 was never released). Both sides of the CHANGELOG are kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit b7abb65 into main Nov 9, 2026
71 of 72 checks passed
@robcohen
robcohen deleted the fix/pad-balance-parity branch November 9, 2026 14:19
robcohen added a commit that referenced this pull request Nov 11, 2026
…s beancount does (#2920)

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

Beancount pads each account with a `pad` on its own (`ops/pad.py`): the
group sees balances on the account and its sub-accounts, measures them
against the real postings of the account and its sub-accounts plus its
own padding only, leaves a difference within the balance's tolerance
alone, and reports `Attempt to pad an entry with cost` once per lot held
at cost in the padded currency. `rustledger_booking::plan_pads`, which
the validator, the balance view, BQL and `#balances` all read, now
applies that rule:

- A pad on a parent pads it for a balance on a sub-account, and such a
  balance uses up the parent pad's currency.
- A pad counts no other pad's padding, into a sub-account or out of the
  account as a source.
- A difference within the balance's tolerance is not padded (an
  `Unused Pad entry`), so `balance_tolerance` moves next to the rule in
  `rustledger-booking`, and the pad functions take the ledger's
  `tolerance_multiplier`.
- Padding a currency held at cost is the new `E2005`, checked by the
  validator against its booked lots; the padding is still inserted.

The two pad-date rows of #2901 were already fixed by #2898; they are
pinned in `pad_parity_test`, which now covers every #2901 shape against
bean-check / bean-query 3.2.3.

On the 1,045 in-tree and compatibility ledgers, `rledger check`,
`report balances`, BQL balances and `#balances` are unchanged.

WASM cache v86: the `Ledger` payload gains the multiplier, and cached
error lists change. The loader cache is unaffected.

Closes #2901

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(validate): keep pad groups linear, and report pads at cost and tolerances as beancount does

Review round 1 of #2920:

- Each pad group keeps a running total of its real postings, as
  beancount keeps `pad_balance`: seeded once when the group's first
  `pad` comes, then moved by each posting (O(depth)). Summing the
  subtree at every balance made a parent pad with balances on many
  sub-accounts quadratic. A new test counts the accounts read and
  fails on the per-balance walk.
- `E2005` skips the subtree walk for a currency never booked at cost,
  counts positions as one merged inventory does (a lot held in two
  sub-accounts is one, as in beancount), and its message shows what the
  pad group holds (`PlannedPadding::held`), not other pads' padding.
- `pad_parity_test` takes each shape's `tolerance_multiplier` and adds
  the multiplier-2 shape, lots in sub-accounts, the merged lot, the
  group-only message, and a balance just beyond the tolerance. The
  loader's balance view gets tests for `tolerance_multiplier` and for
  `inferred_tolerance_default`, which beancount ignores here. All of
  these were checked against bean-check / bean-query 3.2.3.
- Held FFI options whose `tolerance_multiplier` is not a decimal are
  reported and replaced by the default, which `info()` then echoes.
- `scripts/compat-values.py` counts `E2005` as a pad error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* perf(validate): keep pads at cost, many currencies and overflowed totals linear, and print E2005 as beancount does

Review round 2 of #2920:

- The "pad an entry with cost" check reads only accounts a posting at
  cost was booked to, per currency, under the padded account: a lot at
  cost elsewhere in the ledger no longer makes every padded balance walk
  the subtree. `rustledger_booking::plan_pads` copies the group's
  holdings (`PlannedPadding::held`, now an `Option`) only when such an
  account sits under the group, and the validator moves it rather than
  cloning it. Guard tests count the accounts read.
- A pad group keeps its running totals in hash maps, so a group holding
  many currencies stays linear, and a total that leaves `Decimal`'s range
  carries on in `BigDecimal` instead of re-summing the subtree at every
  later balance. Guard tests for both.
- `python_inventory_str` / `python_position_str` move from
  `rustledger-query` to `rustledger-core`, and the E2005 message uses
  them: the inventory is sorted and printed as bean-check prints it.
- `rustledger_core::strict_subaccounts`, the range query behind
  `for_each_strict_subaccount`, as an iterator.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(booking): report pads at cost from each pad group's own inventory, as beancount's pad_balance

Review round 3 of #2920. Each pad group now keeps beancount's
`pad_balance` itself: a running inventory of the real postings under
its account and its own padding, positions (lots at cost included)
merged as `Inventory.add_position` merges them and kept in the order
they came. Groups exist from the start of the walk, so each posting
updates the groups among its account's ancestors, O(depth).

"Attempt to pad an entry with cost" (E2005) is read from that inventory
by the plan (`PlannedPadding::at_cost`, a new `PaddedAtCost`) and
printed through the canonical `python_inventory_str`, so ties come out
in the order bean-check prints them. The validator only reports it, and
`process_pads` reports it too. Gone: the validator's `cost_accounts`
index, `lots_at_cost`, `shown_balance`, and the plan's `held` copy and
cost-account gate.

- Guards count the work (group updates and printed positions) on the
  #2920 review's scenarios A, E, F, F2 and H, and a lot outside the
  group computes nothing for it.
- Parity shapes for the four tie orders, checked against bean-check.
- The overflow-and-back total stays exact, a documented deviation
  from beancount's 28-digit context, pinned by a test.
- `sell_gains` prints its inventories through `python_inventory_str`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(booking): enter a transaction's sub-accounts in beancount's account order, keep a joined lot's latest cost, and count inventory work

Review round 4 of #2920:

- Beancount collects a pad group's postings account by account, in the
  order `realization.postings_by_account` first met each account, and
  stable-sorts them by date, type and line, which one transaction's
  postings share. The plan now ranks accounts as the walk first meets
  them (opens, closes, balances, notes, documents, a pad's account then
  source, custom account values, postings as written) and applies each
  transaction's postings in that rank order, so ties print as bean-check
  prints them.
- A joined lot keeps the cost it was last written with, as
  `add_amount` rebuilds the position with the incoming cost.
- The linearity guards count work where it happens: every
  `GroupInventory::add`, every lot check and every printed position. A
  mutant that rebuilds the inventory at each padding now fails them.
- The validator reports E2005 before the overflow early return, so a
  balance where one group cannot be represented and another pads at
  cost reports it, as `process_pads` does.
- `strict_subaccounts` is gone again (no caller), and the
  `for_each_strict_subaccount` doc no longer names `plan_pads`. The
  `process_pads` and `PadResult::errors` docs name E2005.

New parity shapes, checked against bean-check 3.2.3: both open orders,
accounts first met through a posting, and a joined lot's latest cost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(booking): rank a pad group's accounts in beancount's entry order

Review round 5 of #2920. Beancount's `realization.postings_by_account`
meets accounts in its entry order, `(date, SORT_ORDER, lineno)`, where a
`pad` ranks with the date's transactions, notes and customs. The plan
walked in booking order, which puts a same-date pad first, so a pad
written after a note met its accounts too early.

- New `rustledger_core::beancount_entry_sort_key`, beancount's
  `entry_sortkey` with the source location standing for the line.
- `plan_pads` takes each directive's `SourcePosition` and ranks the
  accounts in one pass in that order, before the booking-order walk. The
  validator passes its spans; `merge_with_padding_spanned` and
  `Ledger::balance_view` pass theirs through the new
  `process_pads_spanned`; plain `process_pads` falls back to input order.
- Parity shapes for every registration arm (note, document, balance, a
  pad's account and source, custom, close, posting) and for a note, a
  transaction and a custom before a same-date pad, checked against
  bean-check 3.2.3. A loader test pins the located path.
- `see` looks the account up before cloning it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(wasm,ffi): pad and validate with source locations on every surface

The FFI and WASM pad expansion went through plain `process_pads`, which
ranks accounts by stream order: on a loaded (booking-ordered) ledger a
same-date `pad` met its accounts before a note written above it, so an
"Attempt to pad an entry with cost" could list tied positions in a
different order from `rledger check` on the same ledger.

- `rustledger_booking::process_pads_at` pads plain directives with a
  parallel list of `SourcePosition`s; `process_pads` documents what its
  input order promises (the padding never depends on it; only E2005 tie
  order does, and only a source-ordered stream suits it).
- WASM: `helpers::pad_expansion` pads with the kept spans for both
  `expandPads` surfaces, and the WASM ledgers validate with their spans
  as `rledger check` and the FFI do, so their errors also carry their
  own lines (cached `ParsedLedger` errors change, under WASM v91).
- ffi-wasi `expand_pads` takes a `position_of` for its tags
  (`line_position`, `file_line_position`).
- Drift guard `test_pad_at_cost_ties_agree_across_surfaces`: one ledger
  with a note above a same-date pad answers bean-check's
  `(1 CCC, 1 DDD, ...)` through the validator, `process_pads_spanned`,
  the WASM expansion and WASM validation, and pads the same through
  `balance_view`, the WASM expansion and ffi-wasi `expand_pads`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(booking,wasm): rank pad accounts by beancount's line number, and keep a restored WASM ledger's lines

Review round 6 of #2920:

- Beancount's `entry_sortkey` is `(date, SORT_ORDER, lineno)` with the
  line number whichever file it is in, and line 0 for a plugin's entry.
  `SourcePosition` is now that line. The validator reads it through the
  new `ValidationOptions::source_lines` (`SourceLines`), which
  `rustledger_loader::source_lines` builds from a source map; the loader
  and the LSP's multi-file path set it. Without it, a source directive's
  offset stands in and a plugin's directive is 0. Loader tests pin both
  shapes checked against bean-check 3.2.3: an account opened on line 2
  of an included file before one opened on line 5 of the main file
  (whatever the byte offsets), and an `auto_accounts` open first.
- `process_pads_spanned` is gone: the merges discard errors, and only
  `process_pads_at` (the WASM expansions) reports them with lines.
- The WASM `Ledger` keeps each directive's line (`directive_lines`) and
  stores it in its cache payload, so `fromCache(...).expandPads()`
  answers as `getErrors()` does. `from_files` delegates to a native
  `from_file_map`, so the drift guard covers the multi-file `Ledger`
  before and after a cache round trip.
- The drift guard's ffi-wasi part is native-only, so
  `wasm-pack test --node` compiles again.
- ffi-wasi `expand_pads` is back to main's API (padding only, which no
  input order changes).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(booking,loader,ffi): order pad ties by plugin line and file, and validate the FFI and WASM with the ledger's options

Review round 7 of #2920:

- The FFI component's `validate` and `load` validated with a default
  `ValidationOptions`, which ignored `tolerance_multiplier`. ffi-wasi's
  `LoadResult` now carries `validation_options`, built with the
  canonical `validation_options_from_options` and the source map's
  positions, and the component validates with them. The WASM validation
  had the same default set and now builds its options the same way.
  Drift guards compare both against `rledger check` with
  `tolerance_multiplier` 2 and 99.97 held: `Unused Pad entry` with a
  pad before `balance 100.00 USD`, and nothing without it, as
  bean-check 3.2.3 reports.
- `SourcePosition` is now a struct: the line and the file's place in
  the load. A plugin's directive has the line the plugin gave it (read
  from the source map's placeholder), ranked ahead of every file, as
  `auto_accounts` and `currency_accounts` put their entries ahead of
  the parsed ones. A source file's directive is ranked by its file id,
  so a tie on the line between two files goes by file, not by booking
  order.
- `auto_accounts` numbers an open by its account's place among every
  account the ledger names, opened ones included, and
  `currency_accounts` numbers its opens by their sorted place, as
  beancount's plugins do.
- `rustledger_loader::source_lines` no longer copies every line table:
  a file's table is built from its shared text on the first lookup,
  and placeholders added after it was taken are seen.
  `source_lines_overlaid` reads an editor buffer's lines from its text;
  the LSP passes the edited buffer.
- The WASM `Ledger` keeps each directive's position, and its cache
  payload stores the file rank beside the line (still v91).

Loader tests, each checked against bean-check 3.2.3: a tie through a
nested include, a same-line note in the main file against a pad in an
include (both ways round), an `auto_accounts` open tied with a written
one, and the known difference where beancount reads files breadth
first and the loader depth first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* perf(booking): track only postings in a pad group, and build the entry order only when a lot at cost can print it

Review round 8 of #2920:

- A posting outside every pad group no longer resolves its lot or
  joins the transaction's group list: whether an account falls in a
  group is answered once per account.
- The entry order (the account ranks, and sorting a transaction's
  postings by them) only shows in an "Attempt to pad an entry with
  cost" message, so it is built only when a posting under a group
  carries a cost. Then only accounts in a group are ranked, and a
  transaction's postings are sorted only when two fall in one group.
- `pad_plan_reads_positions` says when the plan reads positions; the
  validator looks up each directive's line only then.
- CHANGELOG: the plugin `open` lines also fix BQL `filename` / `lineno`
  and `#accounts` meta, and locate a `currency_accounts` open's error
  at `<currency_accounts>:N`. The v91 note says the plugin-open lines
  moved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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 and balance behaviour around unopened accounts and zero-difference balances differs from beancount

1 participant