Skip to content

perf: linear error rendering and {} sales from many-lot accounts - #2624

Merged
robcohen merged 4 commits into
mainfrom
perf/fifo-reduction-linear
Oct 12, 2026
Merged

robcohen merged 4 commits into
mainfrom
perf/fifo-reduction-linear

Conversation

@robcohen

@robcohen robcohen commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

What

#2604 measured 9.8G instructions for a FIFO account with 1,000 distinct-cost lots and 333 {} sales, growing about 3.8x per doubling, and suspected booking. I profiled the issue's ledger (it is byte-identical to the one the #2589 review generated) and found four separate quadratic terms. One is in error rendering, and it accounts for 96% of the 9.8G. Three are in booking.

1. Error rendering (the 9.8G)

The issue's ledger opens its accounts on 2020-01-01 and dates its transactions from 2000, so every one of its 2,666 transactions draws an E1001 ("was never opened"). With the accounts opened first, the same ledger checks in 0.03 s.

96.4% of the run was miette's <[u8] as SourceCode>::read_span. To turn a byte span into line numbers, it counts lines from byte 0 of the file on every call, so check cost O(errors × file size).

report.rs now gives miette an IndexedSource. It indexes the file's line starts once, finds the span's line by binary search, runs miette's own routine over a window that starts context_lines_before + 1 lines earlier, and rebases the result (offset, line, line count) onto the whole file. Lines split exactly as miette splits them (\n, \r\n, lone \r). Both LedgerErrorRenderer and report_parse_errors use it.

2. {} sale cost currency (booking)

A {} sale whose cost currency comes from the account (#2589's reduction_overrides and its fallback) called held_cost_currency, which walked every lot. That walk grew 16x for 4x the input.

CostIndex now counts its slots per cost currency. Those counts change only where the map gains or loses a slot, so they move in step with it by construction. The new Inventory::sole_cost_currency answers from them:

  • one counted currency is the answer whenever any cost-bearing lot is non-empty (checked against the sign counts, O(currencies));
  • several counted currencies fall back to the walk.

The counts inherit the map's asymmetry: they may still count a slot whose lot went empty, but never miss a lot. A debug_assert_eq! checks every answer against the walk, as is_reduced_by does.

3. Number-only {} sale currencies (booking)

A sale whose units name no currency (Assets:Stock -1 {}, #2490) resolves it from the account's one currency through Inventory::currencies(), which walked every lot. Its cost grew 2.5x and then 2.9x per doubling, on a ledger bean-check accepts.

currencies() now answers from the per-currency sign counts that the units cache already maintains. A zero lot is in no bucket (#2385), exactly as currencies() skips an empty position. The walk is kept as a fallback for an unbuilt cache, and as the definition a debug_assert_eq! checks against.

4. Ordered-index removal (booking)

Draining a lot removed its entry from the ordered index with Vec::remove, which shifts every later entry. Every ordered method walks forward and consumes the front (a descending method reverses its key, never the walk), so a FIFO account that drained a lot on each sale paid O(lots) per sale: cost_index_remove grew 15.7x from 4k to 16k transactions. LIFO also inserted every new lot at the front.

by_currency is now a VecDeque, which is O(1) at both ends. The entry is found by binary search on the same (key, slot) order ordered_index_insert uses, then verified, with the linear scan as fallback. The walk reads the deque's two halves in order.

STRICT, LIFO, HIFO

LIFO and HIFO show the same two terms and the same fix. STRICT with {} against many lots is an ambiguity error on every sale by definition, unless the sale takes the whole account. Its per-error cost is plan_strict counting the matching lots for the message ("1000 lots match"), so it is O(lots) per error. I left that alone.

Measurements

Callgrind, release (profiling profile) with mimalloc, BEANCOUNT_DISABLE_LOAD_CACHE=1, rledger check. main is 612e162, built into a separate target dir; both binaries are copied and named.

Ledger main this PR Change
#2604's ledger (1,000 lots, accounts opened late) 9,754M 369M −96.2%
same, 2,000 lots 38,267M 733M −98.1% (main 3.9x per doubling, PR 2.0x)
FIFO, n lots + n/3 one-unit {} sales, n = 1,000 109M 98M −9.3%
n = 2,000 234M 191M −18.4%
n = 4,000 554M 379M −31.6% (main 2.16x / 2.36x per doubling, PR 1.94x / 1.98x)
LIFO, n = 4,000 554M 379M −31.6%
HIFO, n = 4,000 581M 406M −30.1%
FIFO, one lot drained per priced sale, 4k / 16k txns 326M / 1,919M 278M / 1,093M −14.9% / −43.0% (PR 1.98x per doubling)
number-only -1 {} sales, n = 1,000 / 2,000 / 4,000 143M / 378M / 1,146M 98M / 191M / 379M −31% / −50% / −67% (main 2.65x / 3.03x per doubling, PR 1.94x / 1.99x)
fifo profiling shape, 10k / 20k 560M / 1,181M 530M / 1,060M −5.3% / −10.3%
simple 10k 358.6M 358.5M −0.02%
tagged / multicurrency 10k +0.01% / +0.00%
investment 10k / 20k 540.5M / 1,078.0M 542.4M / 1,081.9M +0.36% / +0.36%

The investment cost is the per-cost-currency counts that every cost-bearing lot now keeps. A first version that kept two inline entries cost +0.66%; one inline entry (spilling only for multi-cost-currency accounts) brought it to +0.36%.

CPU time: a 716 KB compat-corpus ledger with 9,875 errors (double-entry-generator/example_oklink_example-oklink-output.beancount) takes 0.17 s instead of 19.7 s of user time. Wall clock was 1.0 s against 112.5 s, but that was measured at a load average of about 43, so the CPU figure is the one to trust.

How tested

  • Byte-identical output. I ran check, query BALANCES, and query SELECT date, account, position, balance, cost(position), weight(position) over the repo's 397 ledgers and the 742-file compat corpus, with main and this PR, cache off and NO_COLOR. All 3,417 outputs are identical. The oklink ledger's 5.6 MB of errors needed the per-command timeout raised to 400 s, because main took 112 s of wall time on it under load. Harness self-check: the same sweep against an older main binary reports 50 differing outputs.
  • Booking fuzzer (scripts/compat-booking-fuzz.py, beancount 3.2.3): seeds 0–1999 give 2000/2000 lot-selection and 2000/2000 number-only ledgers agreed, 0 divergences. --self-test passes.
  • New tests, each shown to fail against a broken version of the code it pins:
    • report::tests::windowed_read_matches_miettes_whole_file_read compares every field of the windowed read (data, span, line, column, line count, name) with miette's whole-file read. It covers every span start in the file, lengths 0–3, 9 and 40 (multi-line and past the end), and before/after context 0–3 / 0–2 set independently, over 300 random sources mixing all three terminators plus hand-picked edges (more than 200,000 reads). It fails when the window ignores the context, when the window drops its extra line ("\n\n\n"'s empty span at byte 1 then reads differently, because miette's span-end arithmetic clamps at offset 0), and when a lone \r is not a line break.
    • inventory::tests::the_sole_cost_currency_follows_every_index_mutation walks one inventory through add, a STRICT drain, a rolled-back add, a FIFO multi-lot drain plus compaction, a serde round trip, and a shared store holding a zero lot. It checks the answer, the walk, and the counts themselves. It fails when remove_slot stops decrementing. The answer alone cannot catch that, because an over-count falls back to the walk, which only costs time.
    • inventory::tests::currencies_leaves_out_a_currency_with_only_empty_lots covers a commodity that is sold out, a cost-less position netted to zero, and a shared-store zero lot. units_cache never forgets a currency, so all three keep their cache entry. It fails when the count filter is removed.
    • inventory::tests::draining_keeps_the_ordered_index_equal_to_a_fresh_build makes, for FIFO, LIFO and HIFO, a sale naming a middle lot by cost and date, then drains everything. After every sale it checks that the maintained index equals a freshly built one. It fails when the removal is skipped, and when the wrong deque entry is removed.
  • Suites, all with --all-features, 0 failed: rustledger-core 645 passed, rustledger-booking 312, rustledger-validate 157, rustledger 1016. On an earlier run, under a load average of 40–55, plugin_conformance::python_plugins_back_to_back_after_a_timeout (a deadline-timing test) failed, and it failed the same way on unmodified origin/main source. It passes at normal load.
  • Workspace cargo clippy --all-features --all-targets -D warnings, the release-config clippy (-p rustledger --no-default-features --features mimalloc,ag-rledger), cargo fmt, and cargo doc -D warnings for the changed crates.

No CACHE_VERSION bump: booked output and the archived types are unchanged. CostIndex and the ordered index are #[serde(skip)] and rebuilt.

Closes #2604

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

#2604's 9.8G instructions (1,000 lots, 333 `{}` sales) were 96% error
rendering: the ledger opens its accounts after its transactions, so all
2,666 transactions draw E1001, and miette's text source counts lines from
byte 0 for every snippet, which makes `check` O(errors x file size). The
renderer now indexes line starts once and hands miette a window starting
a few lines before the span, rebased onto the whole file, so output is
byte-identical (pinned field by field against miette's whole-file read).

Two booking terms remained, and LIFO/HIFO had the same ones:
- a `{}` sale taking the account's cost currency (#2589) walked every lot
  to find it; CostIndex now counts its slots per cost currency and
  `Inventory::sole_cost_currency` answers from the counts, falling back to
  the walk for several currencies.
- draining a lot removed it from the ordered index with `Vec::remove`,
  shifting every later entry, at the front where every ordered method
  consumes; the index is a VecDeque and the entry is found by binary
  search.

Callgrind (release, mimalloc, cache off): #2604's ledger 9,754M -> 369M;
FIFO n lots + n/3 sales at 1k/2k/4k 109M/234M/554M -> 98M/191M/379M
(1.9x, 2.0x per doubling); fifo shape 20k -10.3%; investment +0.36%.
Booked output byte-identical across the repo and compat corpus; booking
fuzzer agrees with beancount on seeds 0-1999.

Closes #2604

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner October 11, 2026 18:33
robcohen and others added 3 commits October 11, 2026 18:46
…unts

Review round 1 of #2604: a `{}` sale whose units name no currency
(`-1 {}`, #2490) resolves it through `Inventory::currencies()`, which
walked every lot, so such sales from a many-lot account were O(lots)
each (1,000 / 2,000 / 4,000 lots: 143M / 378M / 1,146M instructions,
2.65x then 3.03x per doubling; bean-check accepts the ledger).

The units cache already counts each currency's non-empty lots by sign,
and leaves a zero lot out exactly as `currencies()` leaves out an empty
position, so the answer comes from those counts (98M / 191M / 379M).
The walk stays as the fallback for an unbuilt cache and as the
definition a debug assertion checks against.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…ed read

Review round 2 of #2604: the equivalence test only used spans of 0-3
bytes and equal context before and after, while a ledger error's span
covers a whole multi-line transaction. It now also uses lengths 9 and
40 and sets the context before and after independently.

It also showed the window's extra line is load-bearing, not the harmless
margin the comment called it: miette computes a span's end as
`(offset + len).saturating_sub(1)`, which clamps for an empty span at
local offset 0, so a window starting at the span's own line read
"\n\n\n"'s empty span at byte 1 differently. The comment now says so,
and the test fails if the extra line is dropped.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Review round 3 of #2604: the 112 s figure for the 9,875-error corpus
ledger was wall-clock time measured at a load average of about 43. Its
user time is 19.7 s against 0.17 s, which is the figure that does not
depend on the machine's load.

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

Copy link
Copy Markdown
Member Author

Review rounds (#2604)

Each round was a fresh adversarial read of what the previous round changed, plus one area of the PR not yet reread. Rounds that changed production code also reran the differential, fuzz and suite checks below.

Round Head reviewed Findings Fix (commit)
1 aea27d7 A third per-sale walk (perf, MEDIUM). A number-only {} sale (-1 {}, #2490) resolves its currency through Inventory::currencies(), which walked every lot. 1,000 / 2,000 / 4,000 lots cost 143M / 378M / 1,146M instructions (2.65x then 3.03x per doubling); bean-check accepts the ledger. currencies() now answers from the units cache's per-currency sign counts, which leave a zero lot out exactly as it leaves out an empty position: 98M / 191M / 379M. New test currencies_leaves_out_a_currency_with_only_empty_lots, which fails when the count filter is removed. a0381f2
2 a0381f2 Test gap (LOW). The windowed-read equivalence test used only 0–3-byte spans and equal before/after context, while a ledger error's span covers a multi-line transaction. Widening it showed that the window's extra line is load-bearing, not the harmless margin the comment claimed. miette computes the span end as (offset + len).saturating_sub(1), which clamps for an empty span at local offset 0, so without the extra line "\n\n\n"'s empty span at byte 1 reads differently. The comment now says this, and the test fails if the line is dropped. 7382936
3 7382936 Docs (LOW). The CHANGELOG's "1.0 s instead of 112 s" for the 9,875-error corpus ledger was wall time at a load average of about 43. It is now user CPU time, 0.17 s against 19.7 s. 748bbc7
4 748bbc7 None. I reread the round-3 change against the measurement files, and the three new core tests. All three inventory walks (apply, the validator's update_inventories, BQL replay_posting) run on the changed Inventory internals, and the sweep's BALANCES and SELECT … balance outputs are identical. —

Checks on the final production code (rounds 2–4 changed only tests and docs):

  • Differential against main (612e162): check, query BALANCES, and query SELECT date, account, position, balance, cost(position), weight(position) over the repo's 397 ledgers and the 742-file compat corpus, cache off. 3,417 / 3,417 outputs identical. Self-check: an older main binary differs on 50.
  • Booking fuzzer against beancount 3.2.3, seeds 0–1999: 2000/2000 lot-selection and 2000/2000 number-only ledgers agreed, 0 divergences; --self-test passes.
  • Suites (--all-features): core 645, booking 312, validate 157, rustledger 1016, 0 failed. Workspace clippy -D warnings, the release-config clippy, and cargo doc -D warnings.
  • Mutation checks: each new test fails against a deliberately broken version of the code it guards:
    • the window ignores the context;
    • the window drops its extra line;
    • a lone \r is not a line break;
    • remove_slot stops counting;
    • the ordered removal is skipped;
    • the wrong deque entry is removed;
    • currencies() stops filtering.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

@github-actions

github-actions Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 29.0ms ± 0.5ms 412.9ms ± 4.6ms 14.3x 51.3 MB / 50.1 MB
investment 45.3ms ± 0.4ms 1622.3ms ± 30.2ms 35.8x 57.4 MB / 58.1 MB
fifo 45.2ms ± 0.2ms 8664.8ms ± 111.2ms 191.5x 57.4 MB / 57.6 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 29.5ms ± 1.5ms 29.0ms ± 0.5ms -1.9% ✅ within noise 51.3 MB → 51.3 MB (-0.1%)
investment 44.8ms ± 0.5ms 45.3ms ± 0.4ms +1.2% ✅ within noise 57.3 MB → 57.4 MB (+0.2%)
fifo 48.1ms ± 2.2ms 45.2ms ± 0.2ms -5.9% 🟢 faster 57.2 MB → 57.4 MB (+0.3%)

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

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.65871% with 14 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/mod.rs 96.36% 11 Missing ⚠️
crates/rustledger/src/report.rs 97.32% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

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 819
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
robcohen merged commit ca56fa5 into main Oct 12, 2026
68 of 71 checks passed
@robcohen
robcohen deleted the perf/fifo-reduction-linear branch October 12, 2026 03:19
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(booking): {} sales from a FIFO account with many lots are quadratic

1 participant