Skip to content

fix(query): replay transactions in the order booking read them - #2382

Merged
robcohen merged 2 commits into
mainfrom
fix/query-replay-order-2380
Sep 22, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/query-replay-order-2380

Conversation

@robcohen

@robcohen robcohen commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

What

The BQL executor now replays each transaction the way book read it, through the same walk BookingEngine::apply uses since #2379. It used to go one posting at a time against live state.

Ledger bean-query BALANCES main this PR
+10 X {100}, -20 X {100} in one txn -10 X {100.00 USD} Not enough units -10 X {100.00 USD}
holding 2 @ 100: +9 {101}, -2 {100}, -2 {100} 9 {101} -2 {100} No matching lot 9 {101} -2 {100}
AVERAGE: 10 @ 100, then +10 X (no cost), -4 X {} (no AVERAGE) 16 {50} 6 {100} and 10 (= report balances)
lots 10 @ 100, 10 @ 120, then +5 {130}, -4 {*} (no {*}) 21 {114} 16 {110} and 5 {130} (= report balances)

How

  • BookingEngine::walk_step (private) is the one per-posting decision: reduce now, defer, or add now. apply is rewritten on top of it with no change in behavior.
  • replay_transaction replays a whole transaction; the executor's FROM ... OPEN ON carry-in uses it.
  • begin_replay → TransactionReplay is a cursor stepped once per posting. account_snapshot returns the state the walk reaches over the postings so far, counting augmentations still held back. It shares the engine's Arc unless something is held back for that account, so the BQL account_balance copies the account inventory twice per row (quadratic) #2086 copy-avoidance still holds.
  • Like replay_posting, both are replays: no {*} precondition and no rollback, because a filtered stream legitimately meets a different pool ([Bug]: BQL BALANCES shows unmerged lots and a dangling negative for AVERAGE-booked accounts #1985). replay_posting is kept for single-posting callers; nothing in the workspace uses it now, and its docs point to the new API.

account_balance semantics: a row shows the account after its transaction's postings up to and including that row, read the way booking read them: a sale never reduces a lot bought earlier in the same transaction. Documented in docs/reference/bql.md.

Is the behavior change OK? Yes: it is a correction, not a new interpretation. Over 3000 generated ledgers that check accepts (FIFO/LIFO/STRICT/AVERAGE, cost-less legs, several buys and sales per transaction):

count vs report balances
BALANCES changed (all AVERAGE) 116 PR matches in all 116; main in none
main refused, PR answers 17 PR matches in all 17
account_balance changed, BALANCES same (all AVERAGE) 4 the PR's mid-transaction value is the pool the next sale is booked from
unchanged 443 all FIFO/LIFO/STRICT ledgers main could answer

Values change only where main's disagreed with the journal's own booked costs.

Evidence

  • Drift guard (query_report_realization_parity_test): four new shapes. Each fails on main independently: two refusals, 16 @ 50, and 21 @ 114.
  • account_balance per-row values pinned for the [Booking]: book accepts transactions apply refuses (intermittent book_apply_agreement failure; deterministic seed) #2368 ledger; main fails with No matching lot.
  • Workspace cargo test --all-features green; clippy and cargo doc -D warnings clean.
  • Output identity: check, BALANCES and an account_balance query are byte-identical to main on seven benchmark ledgers.
  • Callgrind (mimalloc, cache off) vs main, as check / BALANCES / account_balance:
ledger check BALANCES account_balance
simple -0.03% -0.58% -0.38%
money +0.02% -0.19% +0.22%
fifo +0.02% -0.08% (OOM on both, #2383)
investment 0.00% -0.01% -0.01%

Pre-existing, not addressed: SELECT account, account_balance WHERE account ~ '^Assets' on the 20k-transaction FIFO bench ledger reaches 28 GB of RSS and is OOM-killed on main as well: #2383.

Closes #2380

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

The BQL executor replayed each transaction one posting at a time through
`replay_posting`, against live state: the walk #2368 fixed in `apply` and the
validator. So `BALANCES` refused ledgers `check` accepts. `+10 X {100}` then
`-20 X {100}` in one transaction failed with `Not enough units` where
bean-query answers `-10 X {100.00 USD}`. On an AVERAGE account, cost-less units
written ahead of a sale joined that sale's pool, and `BALANCES` showed
`16 X {50}` where `report balances` shows `6 X {100}` beside `10 X`.

The walk decision is now one private `BookingEngine::walk_step`, used by
`apply` and by a new public replay: `replay_transaction` for the state after a
transaction, and `begin_replay`, a `TransactionReplay` cursor stepped once per
posting, for the executor's per-posting `account_balance`. Like
`replay_posting` it runs no `{*}` precondition and no rollback (#1985).

`account_balance` after a posting is the state the walk reaches over the
postings up to and including it: reductions as `book` classified them, plus
the augmentations seen so far. That is unchanged for every transaction without
a sale after a buy; the cursor shares the engine's copy unless an augmentation
is held back on that account.

Tests:
- The BALANCES-vs-report drift guard gains three shapes (both #2368 ledgers
  with bean-query's holdings, and the AVERAGE case). Each fails on main on its
  own: two refusals and `16 @ 50`.
- A query test pins the per-posting `account_balance` values of the #2368
  ledger; main fails it with `No matching lot`.

`check`, `BALANCES` and an `account_balance` query are byte-identical to main
on seven benchmark ledgers, and callgrind is flat (-0.58% to +0.22%).

Closes #2380

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@codecov

codecov Bot commented Sep 21, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.11765% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/book.rs 93.82% 5 Missing ⚠️
crates/rustledger-query/src/executor/mod.rs 95.23% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 44.4ms ± 1.8ms 818.4ms ± 6.4ms 18.4x 51.0 MB / 50.1 MB
investment 67.1ms ± 0.6ms 3006.6ms ± 40.5ms 44.8x 56.8 MB / 58.1 MB
fifo 64.8ms ± 1.2ms 15474.6ms ± 225.5ms 238.7x 55.1 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 43.8ms ± 0.5ms 44.4ms ± 1.8ms +1.2% ✅ within noise 51.1 MB → 51.0 MB (-0.1%)
investment 67.4ms ± 0.7ms 67.1ms ± 0.6ms -0.5% ✅ within noise 57.0 MB → 56.8 MB (-0.4%)
fifo 65.2ms ± 1.0ms 64.8ms ± 1.2ms -0.6% ✅ within noise 56.7 MB → 55.1 MB (-2.9%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.8ms, investment 0.4ms, 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

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 178 masked)
Full AST Match 100%
Total Files 813
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

Review of #2382 on whether the `account_balance` change is acceptable. Over
3000 generated ledgers, `BALANCES` changed on 116 (all AVERAGE) and in every
one the new result matches `report balances` and the old did not; the 17 the
query used to refuse now match too; FIFO, LIFO and STRICT ledgers it could
already answer are unchanged. A `{*}` sale after a same-transaction buy shows
the same pattern: main merged the buy into the pool (21 @ 114) while the
journal books the sale at 110.

- docs/reference/bql.md states the within-transaction meaning.
- The drift guard gains the `{*}` case; main fails it with 21 @ 114.
- The CHANGELOG entry says where values change instead of a looser bound.

Refs #2380

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

Copy link
Copy Markdown
Member Author

Deep review (head 2c17e46)

Verdict: the behavior change is OK, and the PR is ready once CI is green. No code defects found. Two gaps were closed in 2c17e46: the docs didn't say what account_balance means within a transaction, and {*} had no test.

Is the account_balance change acceptable?

It is a correction, not a new interpretation. Main replayed each posting against live state, so a purchase written earlier in a transaction could affect a later sale in it. Booking never allows that. Wherever this mattered, main's values contradicted the journal's own booked costs.

Evidence: 3000 generated ledgers that check accepts (FIFO/LIFO/STRICT/AVERAGE, cost-less legs, several buys and sales per transaction), main vs this PR, each compared against report balances (the apply realization):

outcome count who matches report balances
BALANCES changed (all AVERAGE) 116 PR 116/116, main 0/116
main refused (Not enough units / No matching lot), PR answers 17 PR 17/17
only mid-transaction account_balance rows changed (all AVERAGE) 4 PR's value is the pool the next sale is booked from
unchanged 443 every FIFO/LIFO/STRICT ledger main could answer

The comparator does report mismatches: it flagged main in all 116 changed cases. By hand, a {*} sale after a same-transaction buy shows the same pattern: main merged the buy into the pool (21 @ 114) while the journal books the sale at 110; the PR and the report hold 16 @ 110 and 5 @ 130.

Alternatives considered:

  • End-of-transaction value on every row: would change ordinary ledgers. Two buys on one account would show 8, 8 instead of 5, 8.
  • Keep live replay but stop erroring: it has no defined answer for the AVERAGE and {*} cases above.

The prefix-walk definition matches main wherever main agreed with booking, and its last row always equals report balances.

Compatibility: account_balance is a rustledger extension; beanquery has no such column (column "account_balance" not found). balance, the beanquery column, is untouched and still adds positions without booking. On the two #2368 ledgers, BALANCES now equals bean-query's.

Code

  • walk_step: apply's three arms are preserved exactly. AddNow skips touched and the precondition, as before; Reduce checks the precondition before the account's first mutation; Defer is unchanged. check output is byte-identical to main on seven ledgers.
  • TransactionReplay:
  • Executor:
    • No replay step runs between the pre-WHERE snapshot and the post-WHERE fill, so the deferred-fill comment stays true.
    • The replay is created only when account_balance is needed, the same gate replay_posting had.
    • A WHERE rejection still advances the replay, so account_balance stays independent of WHERE.
  • replay_posting: now unused in the workspace but public. It is kept, with docs pointing to the transaction-level replays.
  • Known duplicate: the validator's update_inventories still carries its own copy of the walk (different state type). Both sites cross-reference each other, per the canonical-function rules.

Evidence at this head

@robcohen
robcohen merged commit 8c0603f into main Sep 22, 2026
67 of 68 checks passed
@robcohen
robcohen deleted the fix/query-replay-order-2380 branch September 22, 2026 00:34
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.

BQL executor replays postings in the order #2368 fixed in apply: BALANCES fails on a same-transaction short

1 participant