Skip to content

perf(booking)!: merge padding transactions in one pass, not one insert each - #2919

Merged
robcohen merged 3 commits into
mainfrom
perf/merge-with-padding
Nov 10, 2026
Merged

robcohen merged 3 commits into
mainfrom
perf/merge-with-padding

Conversation

@robcohen

@robcohen robcohen commented Nov 9, 2026

Copy link
Copy Markdown
Member

What changed

Every consumer of the pad-expanded stream (merge_with_padding, merge_with_padding_owned, merge_with_padding_spanned, and through them Ledger::balance_view, the CLI query path, wasm and the FFI component; plus ffi-wasi's expand_pads) placed each synthesized padding transaction with pad_insertion_index. That meant one full scan and one Vec::insert per synth, O(n x k). With a pad per account, rledger report balances and BQL were quadratic. The pad_insertion_index doc comment named this as the condition to revisit ("If a ledger ever arrives with pads in the thousands, merge the (date-sorted) synths in one pass instead").

pad_insertion_index is replaced by rustledger_booking::merge_padding_into_sorted(sorted, synths, date_of). It's a single-pass merge, generic over the element type, so all three element shapes (Directive, Spanned<Directive>, (Directive, tag)) call the one canonical rule instead of each driving the index helper themselves. This removes a public function from rustledger-booking, hence the ! and a Breaking CHANGELOG entry.

How the merge works

  1. The stream is sorted exactly as before. Each consumer keeps its existing stable sort_by_key(date) over the booking-sorted input, so this adds no new sort key and re-derives nothing.
  2. The synths are stably sorted by date (sort_by_cached_key, one key computation per synth).
  3. One pass over the sorted stream: before pushing each original, emit every pending synth dated strictly earlier than it. Then append whatever synths remain.

Why the order is identical

The old rule inserted each synth, in turn, after the last element dated on or before it. So a synth lands after every original and every earlier-inserted synth dated on or before it, and ahead of everything dated later. The final sequence is therefore:

That is exactly what the merge emits: a strict < puts the synth after same-date originals, and stable sorting keeps same-date synths in their original order.

Tests (in crates/rustledger-booking/src/pad.rs):

  • test_merge_padding_into_sorted_matches_one_by_one_insert compares against a test-only copy of the old algorithm over 200 seeded random shapes. These are tie-heavy (1 to 8 distinct dates), with synths dated before, inside and after the stream and arriving in arbitrary order; every element is distinct, so equality pins order.
  • test_merge_with_padding_matches_one_by_one_insert_on_a_padded_ledger runs the same comparison end to end through merge_with_padding on 60 padded accounts. Their pads share dates with each other, with unrelated transactions and with unrelated balances.
  • test_merge_padding_into_sorted_is_linear is the regression test. It counts date lookups (at most 2 per element). I temporarily put the one-by-one insert back inside merge_padding_into_sorted, and it failed with merge made 37507500 date lookups for n = 5000, k = 5000; a linear merge makes at most 30000. Both equivalence tests passed against that reverted version, as they should.
  • All existing placement tests (#2150, #2188, the spanned and ffi-wasi per-consumer pins) pass unchanged.

Measurements

Release builds of main (b7abb65, after #2898) and this branch, in separate worktrees and target dirs. The ledgers are N accounts, each with an open, a transaction, a pad and a later balance, spread over 1,500 dates, plus a pad-free ledger of 100,000 transactions over 50 accounts. BQL is SELECT account, sum(position) GROUP BY account.

Instructions (cachegrind, deterministic). Main at 40k was not run under valgrind; extrapolating its 4x per doubling gives about 140G and 165G.

Ledger Command main branch
10k pads report balances 9.18G 0.53G
10k pads BQL 10.96G 0.99G
10k pads check 0.46G 0.46G
20k pads report balances 35.65G 1.07G
20k pads BQL 41.84G 1.98G
20k pads check 0.92G 0.92G
40k pads report balances n/a 2.15G
40k pads BQL n/a 3.98G
40k pads check n/a 1.87G
100k txns, no pads report balances 1.376G 1.376G
100k txns, no pads BQL 2.605G 2.605G
100k txns, no pads check 1.618G 1.615G

On main, each doubling multiplies the count by about 4. On the branch it doubles. The pad-free ledger and check (which never used the merge) are unchanged.

Wall clock. Best of 5 interleaved runs (2 where a run exceeded 10 s), in seconds. The machine was shared with other builds (load average 25 to 57), so later rows are noisy; trust the instruction counts above for ratios.

Ledger Command main branch
10k pads report balances 1.06 0.09
10k pads BQL 1.33 0.15
10k pads check 0.08 0.09
20k pads report balances 4.55 0.20
20k pads BQL 4.72 0.30
20k pads check 0.15 0.15
40k pads report balances 16.7 0.34
40k pads BQL 81 to 171 (load) 1.5 user / 2.6 wall
40k pads check 1.28 1.32
100k txns, no pads report balances / BQL / check 1.3 / 2.1 / 0.94 user 1.3 / 2.0 / 0.95 user

Byte-identical output

On every ledger in the tree (382 .beancount/.bean files outside tests/compatibility/files) and in the compat corpus (731 files), main and branch outputs were compared with cmp on stdout+stderr+exit code for rledger report <file> balances, rledger query <file> "SELECT * FROM #postings" and rledger check <file>. Result: 3,339 of 3,339 identical. The generated 10k and 20k pad ledgers (20k emits 40,000 padding postings in #postings) are also identical on all three commands.

Checks run locally

cargo test --workspace --all-features --no-fail-fast, cargo clippy --workspace --all-features --all-targets -- -D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps, cargo fmt --all --check, and the STRICT corpus_baseline and cst_baseline all pass. No cache bump: output does not change.

Closes #2904

🤖 Generated with Claude Code

…t each

Every consumer of the pad-expanded stream (merge_with_padding, its owned
and spanned variants, Ledger::balance_view, and ffi-wasi's expand_pads)
inserted each synthesized padding transaction into the date-sorted
directive vector one at a time, at an index found by scanning the whole
vector: O(n x k). On a ledger with a pad per account, `rledger report
balances` and BQL were quadratic.

pad_insertion_index is replaced by merge_padding_into_sorted, a generic
single-pass merge: the synths are stably sorted by date, and each is
emitted just before the first original dated strictly after it. That is
exactly the order the one-by-one insert produced (originals first on a
date tie, synths in their own order among themselves), which a test pins
against a copy of the old algorithm on randomized tie-heavy shapes and
end to end through merge_with_padding. A second test counts date lookups
and fails on the old insert (37,507,500 against a bound of 30,000).

Instructions on 20,000 padded accounts: report balances 35.7G -> 1.1G,
BQL 41.8G -> 2.0G, and the branch's counts double from 20,000 to 40,000.
Output is byte-identical to main on every in-tree and compat ledger.

Closes #2904

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:14
@github-actions

github-actions Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 36.6ms ± 0.7ms 506.3ms ± 12.0ms 13.8x 42.6 MB / 51.1 MB
investment 61.2ms ± 4.1ms 1815.1ms ± 14.9ms 29.7x 58.9 MB / 59.0 MB
fifo 57.1ms ± 1.3ms 9440.3ms ± 178.9ms 165.4x 44.6 MB / 58.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 37.7ms ± 4.3ms 36.6ms ± 0.7ms -3.0% ✅ within noise 42.8 MB → 42.6 MB (-0.5%)
investment 59.2ms ± 2.6ms 61.2ms ± 4.1ms +3.3% ✅ within noise 58.6 MB → 58.9 MB (+0.6%)
fifo 58.6ms ± 7.3ms 57.1ms ± 1.3ms -2.6% ✅ within noise 44.6 MB → 44.6 MB (-0.1%)

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

@codecov

codecov Bot commented Nov 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.27536% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/pad.rs 99.27% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@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

robcohen and others added 2 commits November 9, 2026 10:59
balance_view hands its owned vector to merge_with_padding_owned rather
than inlining the merge; merge_padding_into_sorted bounds date_of calls
at 2(n + k) in total, not twice per element; and the same-date-Balance
note describes the placement rule, not the removed function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit 943cb82 into main Nov 10, 2026
67 of 68 checks passed
@robcohen
robcohen deleted the perf/merge-with-padding branch November 10, 2026 06:17
robcohen added a commit that referenced this pull request Nov 10, 2026
Brings in #2908 (strict account validator; loader v66, WASM v87),
#2919 and #2924. Keeps this branch at loader v68 / WASM v90 with one
note per version, drops the merged warn_if_invalid_root (rejection now
goes through check_root), and adds the issue's `A😀` root to the
rejected-name tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 10, 2026
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]>
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.

perf: report balances and BQL are quadratic on ledgers with many pads (merge_with_padding)

1 participant