Repository navigation
perf(core): stop rebuilding and rescanning on every ordered reduction - #2085
Conversation
A FIFO ledger was quadratic. 20k transactions took 9.1s, growing 93x for 10x the input; the same size on the `investment` shape takes 0.04s. Now 0.29s and linear. Two costs, both per reduction and both proportional to lots held. `commit_updates` tombstoned the drained lots with a `retain` over every slot and then called `rebuild_index()`, which walks every slot again and rehashes every key. But `updates` already names the slots that changed, so the repair is now proportional to the lots the reduction touched — the treatment `commit_from_lot` got in #2063, applied to the multi-lot half. On its own this was 5.2x. `plan_ordered` then scanned every slot, applied the cost-spec predicate to each, sorted the survivors and summed them, to take from the front. `ordered_index` keeps each currency's lots in (date, slot) order, so the walk starts where the answer is and stops once the reduction is covered. The up-front sufficiency sum went with it: that existed to guarantee a failed reduction does not mutate, which the plan/commit split (#2061) made structural — exhausting the walk reports the same shortfall having visited the same lots. The index costs +2.35% on `investment` and +0.9-1.3% on the other three shapes, which is the honest trade for removing the growth term. It is built on the first reduction under an ordered method and maintained from `add` only once built, so a ledger whose reductions resolve through `cost_index` never pays for it. Two things the differential test caught, neither of which the existing 480 core tests noticed: - The index must hold COST-LESS positions too. An empty cost spec matches one (`matches_cost_spec`: `(None, true)`), so ordered selection can drain one, and omitting them chose a different lot than the scan. `commit_from_lot` documents the same subtlety. - The first version of that test was vacuous: it called `plan_ordered` directly, which never builds the index, so it compared the scan against itself and passed against a deliberately reversed tiebreak. Adds a `fifo` shape to the workload generator. The existing four reach ordered selection twice in 2k transactions between them, which is why this survived the six superlinear terms fixed in #2059-#2067. Fixes #2083 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
📊 Benchmark Results
vs main branch (2026-08-18)
What do these numbers mean?
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
Pull request overview
Improves rustledger-core inventory reduction performance for ordered booking methods (FIFO/LIFO/HIFO), eliminating quadratic behavior on workloads dominated by bare {} reductions (Fixes #2083) by avoiding full-slot rescans and full index rebuilds per reduction.
Changes:
- Adds and maintains a per-currency
(date, slot)-ordered lot index to let ordered reductions walk from the front/back and stop once covered. - Updates the multi-lot commit path to repair caches incrementally using the update set, instead of rebuilding and rehashing all indices per reduction.
- Extends profiling workload generation with a new
fifoshape that exercises the ordered-selection{}path; adds a differential test ensuring indexed selection matches the prior scan behavior.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| scripts/gen-profile-workload.py | Adds a fifo profiling shape to exercise bare {} ordered reductions and catch scaling regressions. |
| crates/rustledger-core/src/position.rs | Short-circuits matches_cost_spec for empty specs to avoid per-field matching work in the hot ordered-selection path. |
| crates/rustledger-core/src/inventory/mod.rs | Introduces ordered_index and related build/maintenance logic; integrates index building into reduce and cache rebuild flows. |
| crates/rustledger-core/src/inventory/booking.rs | Reworks plan_ordered to use the ordered index (with scan fallback) and updates commit_updates to avoid retain + full rebuild_index. |
Suppressed comments (3)
crates/rustledger-core/src/inventory/mod.rs:1758
- The doc comment above
cost_index_removeappears to be stale/misaligned: it starts by describingsign_indexadjustments, but the function iscost_index_removeand also mutatesordered_index. Please rewrite/split the comment so it documents whatcost_index_removeactually does (and avoid mixing it withsign_index_bump’s contract).
/// Adjust `sign_index` for the position currently at `idx` by `delta`.
///
/// Called with `-1` before changing or removing a lot and `+1` after, so
/// a sign flip lands in the right bucket.
/// Drop `idx` from [`Self::cost_index`]. Called wherever a lot is
/// tombstoned, since the slot stays valid but the lot is gone.
pub(super) fn cost_index_remove(&mut self, idx: usize) {
crates/rustledger-core/src/inventory/mod.rs:1868
ordered_candidatesis documented as returning “cost-bearing slots”, but the index is built from every slot (build_ordered_index/try_rebuild_index_frompush all positions). Either adjust the doc comment to match the implementation, or enforce “cost-bearing only” consistently (but that would conflict with{}matching cost-less lots).
/// Cost-bearing slots of `currency` in FIFO order, or `None` when the
/// index cannot answer and the caller must scan.
fn ordered_candidates(&self, currency: &crate::Currency) -> Option<&[usize]> {
if self.ordered_index.is_empty() {
return None;
}
crates/rustledger-core/src/inventory/booking.rs:590
plan_orderedintroduces a&mut dyn Iterator(walk) to switch direction. This adds dynamic dispatch in a hot loop and can inhibit inlining. Consider using two explicit loops/branches (if reverse { for idx in candidates.iter().rev() { … } } else { … }) to keep the per-lot overhead minimal.
let mut forward;
let mut backward;
let walk: &mut dyn Iterator<Item = usize> = if reverse {
backward = candidates.iter().rev().copied();
&mut backward
} else {
forward = candidates.iter().copied();
&mut forward
};
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Review of my own diff, plus a correction to the numbers in the PR.
`rebuild_index` repopulated `ordered_index` unconditionally, and both
compaction and rollback call it — so an inventory acquired the index (and
its maintenance) whether or not ordered selection was ever used, which
defeated building it on demand. It now preserves whether the index was
built rather than deciding.
`cost_index_remove` cloned the currency and probed the index on every
drained lot, including for inventories that never built one. The map is
also `Option<Box<..>>` now: an inventory that never needs it carries a
pointer instead of three words plus an allocation, on a type created per
account and cloned per BQL output row.
The regressions reported in the PR description were mostly not real. The
two binaries had been built with different toolchains — one inside `nix
develop` (1.96.0) and one outside (1.97.0) — which `cg_annotate --diff`
exposed as equal-and-opposite entries for the same functions under
`drop_in_place` versus `drop_glue` naming. Rebuilt identically:
simple -0.03%
tagged +0.03%
multicurrency +0.04%
investment +2.02%
and the investment figure is codegen noise too: forcing the scan path in
ONE binary, via an environment variable, moves it 45k instructions out of
1.36 billion — 0.003%. That shape books under STRICT, so it resolves
through `cost_index` and never builds an ordered index at all.
So: no measurable cost to ledgers that do not use ordered selection, and
the ones that do are the ones getting 32x.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Deep review of my own diff — and a correction to the numbers aboveThe regressions in the description were mostly not real. The two binaries I compared had been built with different toolchains: one inside Rebuilt identically:
And the investment figure is noise too. Forcing the scan path in one binary via an environment variable — same compilation, one branch — moves it 45k instructions out of 1.36 billion, 0.003%. That shape books under STRICT, so it resolves through So the honest cost is: nothing measurable for ledgers that do not use ordered selection, and the ones that do are the ones getting 32×. The FIFO numbers are unchanged under matched toolchains (5.0× / 9.8× / 32.2× at 2k / 6k / 20k). CI's benchmark reported +6.9%, which I now believe is the same artifact plus wall-clock variance; it is worth re-reading once this push lands. Two architectural problems this review found
Completeness auditThe index is only sound if every path that adds a lot indexes it — a stale entry is harmless (the walk re-checks liveness, sign and the spec) but a missing one hides a lot the reduction should have seen. Every such path:
That last one is the one I most wanted to check: a rolled-back transaction restores lots that the failed attempt had removed from the index, and a missing entry there would be a wrong answer rather than a slow one. It rebuilds, so it is covered — and now that rebuild preserves builtness, a rollback no longer silently hands the index to an inventory that never wanted it. |
Copilot's review: the field, its accessor, its builder and the comment in `plan_ordered` all described `ordered_index` as holding "cost-bearing lots", while the code indexes every position. Worth more than a wording fix. The first version really did index only cost-bearing lots, and that was a wrong-lot-selection bug: an empty cost spec matches a cost-less position (`matches_cost_spec`: `(None, true)`), so ordered selection can drain one, and omitting them chose a different lot than the scan. Leaving the old description in place would have documented the bug as the design — the same shape as the three stale "O(1) clone" comments that hid quadratics through #2056. All four sites now say every lot, and say why the cost-less ones are there. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…r HIFO Two findings from reviewing my own diff for architectural correctness. Removing `plan_ordered`'s up-front sufficiency sum changed which error a doubly-broken reduction reports. Sufficiency used to be settled before any basis arithmetic ran, so a reduction that was both short of units and unrepresentable reported the shortfall — the half the ledger author can act on. Walking lazily reached the `checked_mul` first and reported the overflow instead. Nothing asked for that change and no test covered it: the whole suite passed either way. The overflow is now recorded and raised only once the reduction is known to be satisfiable, which restores the old precedence exactly: `NoMatchingLot`, then `InsufficientUnits`, then `Overflow`. `insufficient_units_are_reported_even_when_the_basis_would_overflow` pins it, and fails if the error returns eagerly again. `reduce_hifo` does not use `plan_ordered` — it sorts by cost and carries its own scan — so gating the index build on `Hifo` built a map nothing reads. FIFO and LIFO only now. Worth noting that HIFO's scan is the same shape this PR fixes and is still quadratic; it needs a cost-ordered index rather than this date-ordered one. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Architectural review, round twoTwo more findings, both in Error precedence changed silentlyRemoving the up-front sufficiency sum changed which error a doubly-broken reduction reports. Sufficiency used to be settled before any basis arithmetic ran, so a reduction that was both short of units and unrepresentable reported the shortfall — the half a ledger author can act on. Walking lazily reaches the The overflow is now recorded and raised only once the reduction is known satisfiable, restoring the old order exactly: This is the kind of thing removing a "redundant" check costs: the check was also establishing an ordering, and only one of its two jobs was obvious. The index was being built for HIFO, which never reads it
Worth stating plainly: HIFO ledgers are still quadratic. Ruled out
Gates: 146 suites, clippy/fmt/doc clean. FIFO unchanged at 31.7x on 20k. |
Third architectural pass, on the half I had reviewed least. `commit_updates` used to finish with `retain(|p| !p.is_empty())` over the WHOLE inventory, so any reduction that happened to cross two lots also deleted every unrelated zero-unit position as a side effect. Those are not scrap: `Inventory::len` counts them and `currency_accounts` branches on `len() == 1` to match Python, so whether one survived depended on whether some other reduction was multi-lot. The incremental repair removes what it drained and nothing else. `a_multi_lot_reduction_leaves_unrelated_empty_lots_alone` pins it and fails on main. Getting there took two attempts: the first fixture added a zero-unit position directly, which `add` drops outright, so the test passed on both sides while proving nothing. A cost-less lot NETTING to zero is the only way one exists — which is the case `Inventory::len`'s contract is actually about. Also asserts the invariant the repair introduced. Adjusting one currency's running total is only correct because every producer of `ReductionPlan::Updates` filters on `units.currency` first; the old rebuild recomputed every currency and so could not have noticed that being violated. Checked before the loop, since afterwards the drained lots are tombstones and indexing one panics. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Architectural review, round three — the half I had reviewed leastEverything so far looked at the new index. This pass looked at A multi-lot reduction was sweeping unrelated empty lotsThe old Those are not scrap.
Getting there took two attempts, which is the part worth reporting: my first fixture added a zero-unit position directly, and Reviewers may reasonably prefer main's behavior here — it is a change in what An invariant the repair introduced, now assertedAdjusting one currency's running total is only correct because every producer of Also checked, no change needed
Gates: 146 suites, clippy/fmt/doc clean. |
Architectural review, round four — the per-row cloneThe risk worth checking this round was the one #2066 nearly reintroduced: an O(lots) structure landing inside BQL's per-row Two clones happen per row. That clone was already O(lots): Measured, to be sure rather than to argue: Slightly faster, because the cheaper reduce more than pays for the larger clone. No regression on the path most at risk. But that number should not be 35 secondsWhile measuring it I checked the growth on
8.9× for 3× input — quadratic, and unrelated to this PR. My branch tracks it almost exactly (33.81s), which is itself the evidence: the reduce got ~30× faster and the total barely moved, so the cost is the per-posting clone of the whole account inventory, not the reduction. That is the same family as #1086, and the Cumulative state of this reviewFour passes, six findings, none of which the 146-suite run caught:
Plus Copilot's doc/semantics mismatch, which was the same bug the code had already had. |
* test(booking): stop the rollback property failing at random
`a_failed_transaction_restores_the_account_exactly` assumed its doomed
final leg — overselling `STK` by 100,000 — always fails. It does not. A
generated prefix of `{*}` merges can empty the account, and an empty cost
spec against an empty account is an AUGMENTATION rather than a failed
reduction. Beancount's `book_reductions` makes the same call: reduction
only `if balance.is_reduced_by(units)`, else augment. So the transaction
succeeded, the property reported "the doomed leg must reject the
transaction", and whether CI saw it depended on which prefix proptest
happened to generate.
Found by proptest generating `[Merge, Merge, Merge, Merge]` while I was
measuring something unrelated. It reproduces on every commit I tried,
including before #2085 and #2081, so it has been latent since the file
was added in #2067.
The doomed posting now reduces a commodity the generated legs never
mention, seeded once up front. That makes "this leg always fails" a fact
about the fixture rather than a hope about the prefix, and the prefix
still exercises every mutation shape the undo log has to cover.
Verified: the seed that fails on main passes here, eight randomized runs
pass, and the property still catches a rollback bug — neutering
`has_reduction` so the undo log is never armed fails it.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
* test(booking): reuse per_unit for the anchor and drop a stale commodity name
Copilot's review. The anchor lot spelled out a `CostSpec` that `per_unit`
already builds, which is how a fixture drifts from the shape the rest of
the file uses; and two comments called the generated commodity `STK`
while the constant has been `X` since the file was written.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
* test(booking): snapshot the commodity in the rollback property
Review of my own change. `holdings` compared units, cost and lot date but
not the commodity, which was harmless while the account held one. This
change gave it two — the generated legs work on one, the doomed leg
reduces the other — so a rollback that restored the right numbers against
the wrong commodity would have compared equal.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
---------
Co-authored-by: Claude Opus 5 <[email protected]>
This PR changes a workflow file and nothing else, so both sides were built from identical Rust source — and the first run reported `simple` at +3.1%, clearing both tests and printing a colored verdict for a difference that no code caused. The standard error only describes variance WITHIN a run. Two binaries built from the same source still differ run to run through code layout, page placement and a shared runner's neighbors, and that component is invisible to the SEM: with 20 tight samples a 2ms systematic offset clears 2σ comfortably. The effect floor is what covers it, so it has to sit above the observed noise rather than at its edge — and testing three shapes is three chances to trip it. Observed identical-build differences: +3.1% in CI, and -3.3%, +3.0%, +2.5%, -2.5% locally. 5% covers those. Re-verified in both directions: the pre-#2085 quadratic still reports +1788.9% on `fifo`, and every identical-source pair now reads within noise.
…2098) The PR benchmark generated its own ledger inline, and every transaction in it was a plain two-posting expense: no cost specs, no lots, no reductions. Booking and the whole inventory engine ran zero times, so the quadratics fixed in #2083, #2086 and #2091 could not have appeared here however sound the comparison was. `gen-profile-workload.py` already documents that workload as the floor, not the benchmark, and records that it leaves booking at 0.3%. It now generates `simple`, `investment` and `fifo` through that script, and reports each on its own row against its own base with significance applied per shape. Verified against the commit before #2085: `simple` reads -1.4% within noise while `fifo` reports +1788.9%, so the regression the old workload could not see is now the headline. Both tools were also being measured warm — bean-check writes a picklecache, rledger writes its own, and hyperfine's warmup populated both. On `fifo` that is 18.4s cold against 0.3s warm, and rledger's cache short-circuits the parser, so a parser regression was invisible regardless of workload. Disabled through `BEANCOUNT_DISABLE_LOAD_CACHE`, Python beancount's own variable which rledger honors deliberately. The effect floor moved from 3% to 5%, measured rather than guessed: this PR touches only a workflow file, so both sides were identical Rust source, and 3% still reported `simple` as slower. The comment body is built by the step that computes the numbers instead of being assembled from interpolated step outputs, which is how the footer once claimed sampling that never happened. Closes #2096. Follow-up in #2097: `investment` fails under bean-check because rustledger's STRICT accepts an ambiguous lot match beancount rejects.
Fixes #2083. A FIFO ledger was quadratic: 20,000 transactions took 9.1s, growing 93× for 10× the input. The same size on the
investmentshape takes 0.04s.Growth for 10× input: 93× → ~11×. Linear. All timings are cold runs with
.beancount.cachedeleted between them — a warm run is a different measurement, and mixing the two is how my first set of numbers came out wrong.Two costs, both per reduction, both proportional to lots held
commit_updatesrebuilt every index. It tombstoned drained lots with aretainover every slot, then calledrebuild_index(), which walks every slot again and rehashes every key — per reduction.updatesalready names the slots that changed, so the repair is now proportional to the lots the reduction touched. This is the treatmentcommit_from_lotgot in #2063, applied to the multi-lot half; on its own it was 5.2×.plan_orderedscanned everything to take from the front. Every slot walked, the cost-spec predicate applied to each, the survivors sorted, then summed for a sufficiency check.ordered_indexnow keeps each currency's lots in(date, slot)order, so the walk starts where the answer is and stops once the reduction is covered.The up-front sufficiency sum went with it. That existed to guarantee a failed reduction does not mutate — which the plan/commit split (#2061) made structural, since
plan_orderednow only computes and the caller commits. Exhausting the walk reports the same shortfall, having visited the same lots.The trade
That is the honest cost of the index, and it is a constant against a growth term removed. It is built on the first reduction under an ordered booking method and maintained from
addonly once built, so a ledger whose reductions all resolve throughcost_indexnever pays for it. Binary-search removal rather thanretaintook theinvestmentfigure from +6.06% to +2.35%; the remainder is structural (an extra field on a type that is cloned per BQL output row).What the differential test caught
the_ordered_index_selects_what_the_scan_selectsruns both paths over an inventory with out-of-order dates, a duplicate date, a date-less lot, a second currency and a cost-less lot, across three specs and both directions. The existing 480 core tests noticed neither of these:matches_cost_spec:(None, true) => true), so ordered selection can drain one — omitting them selected a different lot than the scan.commit_from_lotdocuments the same subtlety forsimple_index.plan_ordereddirectly, which never builds the index, so it compared the scan against itself — and passed against a deliberately reversed tiebreak. It now builds the index explicitly and asserts it is non-empty. Both facts are in the test's doc comment, because the failure mode is silent.Workload coverage
Adds a
fifoshape togen-profile-workload.py. The existing four shapes reach ordered selection twice in 2,000 transactions between them —investmentwrites every sell with an explicit cost, which resolves throughcost_index— which is why a quadratic survived the six superlinear terms fixed in #2059–#2067. The most common real-world reduction spec was simply not represented.Verification
146 test suites green; clippy (1.97.0), fmt and doc clean. The differential test is mutation-checked: reversing the index tiebreak fails it.
🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr