Skip to content

perf(core): stop rebuilding and rescanning on every ordered reduction - #2085

Merged
robcohen merged 5 commits into
mainfrom
perf/plan-ordered-scan
Aug 18, 2026
Merged

robcohen merged 5 commits into
mainfrom
perf/plan-ordered-scan

Conversation

@robcohen

Copy link
Copy Markdown
Member

Fixes #2083. A FIFO ledger was quadratic: 20,000 transactions took 9.1s, growing 93× for 10× the input. The same size on the investment shape takes 0.04s.

N main this PR
2,000 0.10s 0.02s 5.0×
6,000 0.78s 0.08s 9.8×
20,000 9.11s 0.29s 31.4×

Growth for 10× input: 93× → ~11×. Linear. All timings are cold runs with .beancount.cache deleted 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_updates rebuilt every index. It tombstoned drained lots with a retain over every slot, then called rebuild_index(), which walks every slot again and rehashes every key — per reduction. updates already names the slots that changed, so the repair is now proportional to the lots the reduction touched. This is the treatment commit_from_lot got in #2063, applied to the multi-lot half; on its own it was 5.2×.

plan_ordered scanned 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_index now 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_ordered now only computes and the caller commits. Exhausting the walk reports the same shortfall, having visited the same lots.

The trade

shape change
investment +2.35%
tagged +1.33%
simple +1.16%
multicurrency +0.93%

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 add only once built, so a ledger whose reductions all resolve through cost_index never pays for it. Binary-search removal rather than retain took the investment figure 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_selects runs 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:

  1. The index must hold cost-less positions. An empty cost spec matches one (matches_cost_spec: (None, true) => true), so ordered selection can drain one — omitting them selected a different lot than the scan. commit_from_lot documents the same subtlety for simple_index.
  2. My 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. 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 fifo shape to gen-profile-workload.py. The existing four shapes reach ordered selection twice in 2,000 transactions between them — investment writes every sell with an explicit cost, which resolves through cost_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

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
@robcohen
robcohen requested a review from a team as a code owner August 18, 2026 15:05
Copilot AI lite review requested due to automatic review settings August 18, 2026 15:05
@github-actions

github-actions Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 39.3ms ± 0.5ms 24.3 MB
beancount 774.8ms ± 3.2ms 50.6 MB
Comparison 19.7x faster 2.1x less

vs main branch (2026-08-18)

Metric main this PR Change
Time 39.1ms 39.3ms +0.5% ✅
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@codecov

codecov Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.15498% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/mod.rs 96.49% 4 Missing ⚠️
crates/rustledger-core/src/inventory/booking.rs 99.35% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 fifo shape 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_remove appears to be stale/misaligned: it starts by describing sign_index adjustments, but the function is cost_index_remove and also mutates ordered_index. Please rewrite/split the comment so it documents what cost_index_remove actually does (and avoid mixing it with sign_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_candidates is documented as returning “cost-bearing slots”, but the index is built from every slot (build_ordered_index / try_rebuild_index_from push 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_ordered introduces 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.

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

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

Copy link
Copy Markdown
Member Author

Deep review of my own diff — and a correction to the numbers above

The regressions in the description were mostly not real. The two binaries I compared had been built with different toolchains: one inside nix develop (1.96.0), one outside (1.97.0). cg_annotate --diff exposed it — the same functions appearing as equal-and-opposite entries under drop_in_place<Posting> versus drop_glue::<Posting>, in parser code this PR never touches.

Rebuilt identically:

shape reported actual
simple +1.16% −0.03%
tagged +1.33% +0.03%
multicurrency +0.93% +0.04%
investment +2.35% +2.02%

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 cost_index and never builds an ordered index at all.

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

rebuild_index was building the index unconditionally. Compaction and rollback both 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, and is why gating the build changed nothing when I first measured it. It now preserves whether the index was built rather than deciding.

cost_index_remove paid for the index even when there wasn't one, cloning the currency and probing the map on every drained lot. Now guarded. The map is also Option<Box<..>>: an inventory that never needs one carries a pointer rather than three words plus an allocation, on a type created per account and cloned per BQL output row.

Completeness audit

The 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:

path covered by
Inventory::add indexes directly
reduce_average / merge_average (booking.rs:826) rebuild_index after
booking.rs:891 rebuild_index after
reduce_merge (booking.rs:1019) rebuild_index after
rewrite_positions (ex-positions_mut) rebuilds every derived cache
rollback of a failed transaction rollback_undo → rebuild_index

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.

robcohen and others added 2 commits August 18, 2026 15:50
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
@robcohen

Copy link
Copy Markdown
Member Author

Architectural review, round two

Two more findings, both in d444b6db7c, and both invisible to the test suite — it passed with each bug present.

Error precedence changed silently

Removing 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 checked_mul first and reports the overflow instead.

requested 99 units of a 10-unit lot whose basis overflows
  before: InsufficientUnits
  after:  Overflow            <- nothing asked for this

The overflow is now recorded and raised only once the reduction is known satisfiable, restoring the old order exactly: NoMatchingLot → InsufficientUnits → Overflow. insufficient_units_are_reported_even_when_the_basis_would_overflow pins it, and I checked it fails when the error returns eagerly again.

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

reduce_hifo sorts by cost and carries its own scan — it does not go through plan_ordered. Gating the build on Hifo therefore built and maintained a date-ordered map that nothing consults. FIFO and LIFO only now.

Worth stating plainly: HIFO ledgers are still quadratic. reduce_hifo's scan is the same shape this PR fixes, and it needs a cost-ordered index rather than this date-ordered one. Out of scope here, but it should not be assumed fixed by association.

Ruled out

  • Backing conversion. The index stores slot numbers, which mean different things for Owned and Shared. make_owned maps element i to slot i, preserving numbering, and runs at reduce's entry — before any build. There is no Owned → Shared path (new_shared constructs empty). So no index can outlive its backing.
  • Slot renumbering. compact_slots renumbers, which would invalidate every stored index; it is only reachable through compact_if_sparse, which rebuilds immediately and asserts it never runs with an open undo log.
  • Rollback. A failed transaction restores lots the attempt removed from the index; a missing entry there is a wrong answer, not a slow one. rollback_undo rebuilds, and the rebuild now preserves builtness so a rollback no longer hands the index to an inventory that never wanted one.
  • Preview versus commit. book calls try_reduce (&self, cannot build) while apply calls reduce (builds). So the first reduction on an account scans on the book side and indexes on the apply side — different code paths, same answer required. That is exactly what the scan-equivalence test asserts.

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
@robcohen

Copy link
Copy Markdown
Member Author

Architectural review, round three — the half I had reviewed least

Everything so far looked at the new index. This pass looked at commit_updates, which is the larger behavioral change, and found a semantic side effect I had not noticed.

A multi-lot reduction was sweeping unrelated empty lots

The old commit_updates finished with retain(|p| !p.is_empty()) over the whole inventory. So a reduction that happened to cross two lots also deleted every unrelated zero-unit position, anywhere in the account.

Those are not scrap. Inventory::len counts them and currency_accounts branches on len() == 1 to match Python, so whether an unrelated zero-unit lot survived depended on whether some other reduction happened to be 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 (len 1 where 2 is correct).

Getting there took two attempts, which is the part worth reporting: my first fixture added a zero-unit position directly, and add drops one outright — so the test passed on both branches while proving nothing. A cost-less lot netting to zero is the only way one exists, and that is precisely the case Inventory::len's contract is about. Second vacuous test in this PR; both were caught by checking that the fixture contained what I claimed.

Reviewers may reasonably prefer main's behavior here — it is a change in what len() reports for a specific shape. I think the sweeping was incidental rather than intended, but it is a decision worth making deliberately rather than inheriting it from a retain that was really there to drop drained lots.

An invariant the repair introduced, now asserted

Adjusting one currency's running total is only correct because every producer of ReductionPlan::Updates filters on units.currency before planning. The old rebuild_index() recomputed every currency and so could not have noticed that being violated; the incremental version silently drifts if it ever is. Now a debug_assert, placed before the loop because afterwards the drained lots are tombstones and indexing one panics.

Also checked, no change needed

  • Overflow on the incremental total. add_python_scale uses +, which panics, so I checked whether the delta can leave range. It cannot: each term is new - previous for a lot being reduced, so the terms share a sign and sum to the reduction, which is bounded by the account's holdings — in range by the invariant rebuild_index's own doc states (add rejects any sum that would overflow).
  • Undo coverage. The new path writes through IndexMut and remove, both of which record() into the undo log, so perf(booking): undo what changed instead of copying what exists #2067's rollback still sees every mutation.
  • Sign bucket bookkeeping. Mirrors commit_from_lot: drop the classification, write, re-add, and drop again if the lot drained — which is what makes a reduction through zero land in the right bucket.

Gates: 146 suites, clippy/fmt/doc clean.

@robcohen

Copy link
Copy Markdown
Member Author

Architectural review, round four — the per-row clone

The risk worth checking this round was the one #2066 nearly reintroduced: an O(lots) structure landing inside BQL's per-row Inventory clone, which is what #1086 exists to prevent.

Two clones happen per row. cumulative_balance is Inventory::new_shared(), and ordered_index_insert returns early for anything that is not Owned, so the index stays None there and that clone is untouched. The other is engine.inventory(&posting.account).cloned(), which clones the booking engine's inventory — Owned, and for a FIFO account now carrying the index.

That clone was already O(lots): positions, cost_index (one entry per distinct cost), units_cache, simple_index. The ordered index adds one entry per currency holding a Vec<usize> — one allocation and one memcpy, against cost_index's thousands of hash entries. So it raises a constant, not the complexity.

Measured, to be sure rather than to argue:

select account, account_balance where account ~ 'HOOL'    (6,000 txns)
  main      35.18s
  this PR   33.81s

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 seconds

While measuring it I checked the growth on main:

N account_balance query
2,000 3.88s
6,000 34.39s

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 needs_account_balance gate in the executor shows the clone was already known to be expensive — but it is still O(lots) per posting, so a 6,000-transaction ledger spends 34 seconds answering a query about it. Worth its own issue; I can file it with these numbers if wanted.

Cumulative state of this review

Four passes, six findings, none of which the 146-suite run caught:

pass finding
1 rebuild_index built the index unconditionally, defeating on-demand building
1 cost_index_remove paid for the index even when there wasn't one
2 error precedence silently changed (InsufficientUnits → Overflow)
2 index was built for HIFO, which never reads it
3 multi-lot reductions swept unrelated zero-unit lots
3 the single-currency invariant commit_updates now depends on was unasserted

Plus Copilot's doc/semantics mismatch, which was the same bug the code had already had.

@robcohen
robcohen merged commit 9a23a8d into main Aug 18, 2026
58 of 60 checks passed
@robcohen
robcohen deleted the perf/plan-ordered-scan branch August 18, 2026 20:26
robcohen added a commit that referenced this pull request Aug 18, 2026
* 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]>
robcohen added a commit that referenced this pull request Aug 19, 2026
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.
robcohen added a commit that referenced this pull request Aug 19, 2026
…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.
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.

plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions)

2 participants