Repository navigation
perf: linear error rendering and {} sales from many-lot accounts - #2624
Merged
Merged
Conversation
#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
…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
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.
Checks on the final production code (rounds 2–4 changed only tests and docs):
🤖 Generated with Claude Code |
Contributor
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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, socheckcost O(errors × file size).report.rsnow gives miette anIndexedSource. 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 startscontext_lines_before + 1lines 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). BothLedgerErrorRendererandreport_parse_errorsuse it.2.
{}sale cost currency (booking)A
{}sale whose cost currency comes from the account (#2589'sreduction_overridesand its fallback) calledheld_cost_currency, which walked every lot. That walk grew 16x for 4x the input.CostIndexnow 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 newInventory::sole_cost_currencyanswers from them: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, asis_reduced_bydoes.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 throughInventory::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 ascurrencies()skips an empty position. The walk is kept as a fallback for an unbuilt cache, and as the definition adebug_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_removegrew 15.7x from 4k to 16k transactions. LIFO also inserted every new lot at the front.by_currencyis now aVecDeque, which is O(1) at both ends. The entry is found by binary search on the same(key, slot)orderordered_index_insertuses, 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 isplan_strictcounting the matching lots for the message ("1000 lots match"), so it is O(lots) per error. I left that alone.Measurements
Callgrind, release (
profilingprofile) with mimalloc,BEANCOUNT_DISABLE_LOAD_CACHE=1,rledger check.mainis 612e162, built into a separate target dir; both binaries are copied and named.{}sales, n = 1,000-1 {}sales, n = 1,000 / 2,000 / 4,000fifoprofiling shape, 10k / 20ksimple10ktagged/multicurrency10kinvestment10k / 20kThe
investmentcost 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
check,query BALANCES, andquery SELECT date, account, position, balance, cost(position), weight(position)over the repo's 397 ledgers and the 742-file compat corpus, withmainand this PR, cache off andNO_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, becausemaintook 112 s of wall time on it under load. Harness self-check: the same sweep against an oldermainbinary reports 50 differing outputs.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-testpasses.report::tests::windowed_read_matches_miettes_whole_file_readcompares 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\ris not a line break.inventory::tests::the_sole_cost_currency_follows_every_index_mutationwalks 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 whenremove_slotstops 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_lotscovers a commodity that is sold out, a cost-less position netted to zero, and a shared-store zero lot.units_cachenever 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_buildmakes, 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.--all-features, 0 failed:rustledger-core645 passed,rustledger-booking312,rustledger-validate157,rustledger1016. 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 unmodifiedorigin/mainsource. It passes at normal load.cargo clippy --all-features --all-targets -D warnings, the release-config clippy (-p rustledger --no-default-features --features mimalloc,ag-rledger),cargo fmt, andcargo doc -D warningsfor the changed crates.No
CACHE_VERSIONbump: booked output and the archived types are unchanged.CostIndexand the ordered index are#[serde(skip)]and rebuilt.Closes #2604
🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr