Skip to content

perf(booking): undo what changed instead of copying what exists - #2067

Merged
robcohen merged 6 commits into
mainfrom
perf/apply-undo-log
Aug 17, 2026
Merged

robcohen merged 6 commits into
mainfrom
perf/apply-undo-log

Conversation

@robcohen

Copy link
Copy Markdown
Member

apply snapshotted every touched account with Inventory::clone before mutating, so a failed transaction could be rolled back. The comment justifying it said the positions were an imbl::Vector whose clone is O(1) — that stopped being true at #2056, when booking's backing became owned. The guard silently turned into an O(lots) copy per touched account per transaction and grew into the largest superlinear term left in the pipeline.

A reduction touches one or two lots. apply now records an undo log of the slots it actually writes.

Measured

Cachegrind, both sides rebuilt at HEAD, base f3ac855ca2:

workload main branch delta
investment 2k 136,693,394 122,452,140 −10.42%
investment 20k 2,650,674,155 1,209,849,439 −54.36%
simple 20k 860,854,747 863,447,163 +0.30%
tagged 10k 684,347,183 686,524,070 +0.32%

Scaling for 10× input: 19.4× → 9.9×. investment is now linear. An ablation removing the snapshot entirely measures 9.9× and −56.2%, so this captures 96% of what was available and the curve is flat rather than merely flatter.

The +0.3% on cost-spec-free shapes is real, not noise — the undo_open field plus the per-posting commit pass. That pass is skipped entirely when nothing was recorded: only reductions create tombstones, and any reduction makes rollback_needed true, so !recording means there is nothing to compact or commit.

Why recording lives in the backing

Eleven call sites mutate positions across two files. Threading a log through each is how you miss one — and a missed site means rollback silently fails on an error path that is rare and hard to test.

They all funnel through PositionStore's primitives, and the field is private, so hooking IndexMut, push_slot and set_dead is complete by construction. Hooking call sites would be complete only until someone adds a twelfth.

A debug-only witness copy taken at begin_undo is compared against the restored inventory, so a future mutation path that bypasses the log fails loudly in tests rather than corrupting a ledger.

Compaction moved out of reduce into Inventory::compact_if_sparse, called by apply on commit. Compaction renumbers slots and the undo log refers to them, so it cannot run mid-transaction — and commit is also the only moment no rollback can still be required.

Verification

Four mutations run; two survived, and both exposed genuinely untested log paths that are now covered:

  • A lot fully DRAINED before the failure. On the common paths the lot is zeroed through IndexMut first, which already records it, so removing set_dead's capture changes nothing — except on {*} merge, which drops matched lots through retain_slots without writing them. That is the case that tells the two apart, and a rejected merge would otherwise destroy every lot it consumed.
  • A lot ADDED before the failure, which would be left behind as a phantom.

The pre-existing a_failing_transaction_is_rolled_back_whole only checked the cash leg's total — adequate when rollback restored a whole copy, since that cannot get lots wrong. Lot-level restoration is now a real obligation, so it is asserted directly.

Restoring in reverse order pops created slots while they are still last; forward order is not wrong, only wasteful, so a mutation swapping it survives by design and the comment says so.

Also removes a debug_assert I added claiming tombstones cannot dominate while a log is open. A {*} merge tombstones every matched lot and pushes one, so they legitimately can — the assertion fired on valid input.

Gates: cargo test --workspace --all-features (142 suites), cargo +1.97.0 clippy --workspace --all-features --all-targets -- -D warnings, cargo fmt --all -- --check, RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --all-features.

🤖 Generated with Claude Code

`apply` snapshotted every touched account with `Inventory::clone` before
mutating, so a failed transaction could be rolled back. The comment
justifying it said the positions were an `imbl::Vector` whose clone is O(1).
That stopped being true at #2056, when booking's backing became owned — the
guard silently turned into an O(lots) copy per touched account per
transaction and grew into the largest superlinear term left in the pipeline.

A reduction touches one or two lots. `apply` now records an undo log of the
slots it actually writes.

Cachegrind, both sides rebuilt at HEAD, base f3ac855:

    investment 2k    136,693,394 -> 122,452,140   -10.42%
    investment 20k 2,650,674,155 -> 1,209,849,439 -54.36%
    simple 20k       860,854,747 ->   863,447,163  +0.30%
    tagged 10k       684,347,183 ->   686,524,070  +0.32%

Scaling for 10x input: 19.4x -> 9.9x. `investment` is LINEAR — an ablation
that removes the snapshot entirely measures 9.9x and -56.2%, so this captures
96% of what was there and the curve is now flat, not merely flatter.

RECORDING LIVES IN THE BACKING, not at the eleven call sites that mutate
positions. Those all funnel through `PositionStore`'s primitives and the
field is private, so hooking `IndexMut`, `push_slot` and `set_dead` is
complete BY CONSTRUCTION; hooking call sites would be complete only until
someone adds a twelfth. A debug-only witness copy taken at `begin_undo` is
compared against the restored inventory, so a future mutation path that
bypasses the log fails loudly in tests rather than corrupting a ledger.

Compaction moved out of `reduce` into `Inventory::compact_if_sparse`, called
by `apply` on commit: compaction renumbers slots, and the undo log refers to
them, so it cannot run mid-transaction. That is also the only moment no
rollback can still be required.

The +0.3% on the cost-spec-free shapes is real, not noise. It is the
`undo_open` field and the per-posting commit pass, which is skipped entirely
when nothing was recorded — only reductions create tombstones and any
reduction makes `rollback_needed` true, so `!recording` means there is
nothing to compact or commit.

Four mutations were run and two SURVIVED, exposing untested log paths that
are now covered:

  - a lot fully DRAINED before the failure. On the common paths the lot is
    zeroed through `IndexMut` first, which already records it, so removing
    the capture in `set_dead` changes nothing — except on `{*}` merge, which
    drops matched lots through `retain_slots` without writing them. That is
    the case that tells the two apart, and a rejected merge would otherwise
    destroy every lot it consumed.
  - a lot ADDED before the failure, which would be left behind as a phantom.

Restoring in reverse order pops created slots while they are still last;
forward order is not wrong, only wasteful, so a mutation swapping it survives
by design and the comment says so.

Also removes a `debug_assert` I added claiming tombstones cannot dominate
while a log is open. A `{*}` merge tombstones every matched lot and pushes
one, so they legitimately can, and the assertion fired on valid input.
@robcohen
robcohen requested a review from a team as a code owner August 16, 2026 21:23
Copilot AI lite review requested due to automatic review settings August 16, 2026 21:23
@github-actions

github-actions Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.3ms ± 4.2ms 24.3 MB
beancount 634.4ms ± 4.8ms 50.7 MB
Comparison 18.5x faster 2.1x less

vs main branch (2026-08-16)

Metric main this PR Change
Time 31.1ms 34.3ms +10.3% 🔴
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

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

This PR improves the performance characteristics of booking rollback by replacing per-account Inventory::clone snapshots with a slot-level undo log recorded inside the inventory backing. This targets the regression introduced when booking inventories became owned (post-#2056), where cloning stopped being O(1) and became proportional to lots per touched account.

Changes:

  • Add undo-log recording/commit/rollback primitives to Inventory / PositionStore (and move compaction to an explicit commit-time hook).
  • Update BookingEngine::apply to open undo logs for touched inventories, rollback via logs on failure, and compact on commit.
  • Strengthen rollback tests to assert lot-level restoration across multiple mutation shapes (in-place edits, drained removals, added lots, {*} merge).

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
crates/rustledger-core/src/inventory/mod.rs Introduces slot-level undo logging and exposes Inventory::{begin_undo,commit_undo,rollback_undo,compact_if_sparse} to support rollback without deep cloning.
crates/rustledger-booking/src/book.rs Switches apply rollback from snapshot cloning to undo logs; defers compaction to commit boundary.
crates/rustledger-booking/tests/apply_precondition_test.rs Adds lot-level rollback tests covering multiple undo paths (double-touch, drained+added, {*} merge).

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread crates/rustledger-booking/src/book.rs Resolved
@codecov

codecov Bot commented Aug 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.92265% with 11 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/mod.rs 92.80% 10 Missing ⚠️
crates/rustledger-booking/src/book.rs 97.61% 1 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%, 169 masked)
Full AST Match 100%
Total Files 812
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

Correctness review of my own change, and this one was a real defect.

Moving compaction out of `reduce` into `apply`'s commit path tied it to the
booking engine. The Late validator keeps its OWN inventories across
transactions and calls `Inventory::reduce` directly
(`validators/transaction.rs`), so it never reached that commit path — its
inventories would have accumulated one dead slot per closed lot for the life
of the ledger, and scanned every one of them on every later reduction. That
is precisely the unbounded growth tombstones needed compaction to prevent,
reintroduced in a second caller.

The measurement hid it: `apply`'s win dominates the profile, so the run still
showed -54% while the validator quietly degraded.

The constraint was never "compact at commit" — it is "do not renumber slots
while an undo log refers to them". So `reduce` compacts unless a log is open,
which restores the previous behavior for every caller that does not run a
transaction, and keeps the deferral for the one that does.

`tombstones_are_compacted_rather_than_accumulating` goes back to driving
compaction through `reduce` alone, with no engine and no explicit call — the
way the validator does. Mutation-checked in both directions: removing the
compaction fails it, and compacting unconditionally (while a log is open)
fails the rollback tests.

Also asserts that `begin_undo` is only called on an owned backing. Recording
does not exist on the shared one, so a shared inventory would set
`undo_open`, capture nothing, and roll back nothing while reporting success.
Unreachable today — `BookingEngine` populates its map only through
`entry().or_default()` and takes no inventory from outside — and now asserted
so it stays unreachable.

Measurements are unchanged: investment 20k -54.34%, scaling 19.4x -> 9.9x.
Second correctness pass on this PR.

`apply` opened logs with `if !inv.undo_is_open() { inv.begin_undo(); }`. That
handles two postings on one account, but it also defeats the assertion inside
`begin_undo` that says it must not be called twice — the guard would silently
adopt a log left over from an earlier transaction and roll back to the wrong
point rather than failing loudly.

The accounts are now deduplicated first and `begin_undo` is called exactly
once each, so its assertion is load-bearing again. Verified: removing the
deduplication makes `test_multi_posting_crosses_lot_boundary` fire that
assertion, so the path is genuinely exercised rather than merely present.

Also checked and found sound, recorded here so the next reader need not
re-derive it:

  - No undo state can reach the wire. `undo_open` and `undo_witness` are
    `#[serde(skip)]`, and `Slots.undo` is unreachable because `PositionStore`
    serializes through a hand-written `collect_seq(self.iter())` rather than a
    derive.
  - Rollback restores the derived caches, `cost_index` included, because it
    ends in `rebuild_index`.
  - A slot pushed during a transaction cannot already be in the log: its index
    is the length before the push, and only rollback pops.
  - `apply_posting` mutates nothing outside `self.inventories`, so nothing
    else needs undoing.
Third correctness pass, and this one is a user-facing bug that predates this
PR.

`rollback_needed` decides up front whether to prepare a rollback, and
`has_reduction` asked whether each posting reduces something the account holds
AT THAT MOMENT. A transaction can falsify that itself:

    2024-01-01 * "buy then oversell"
      Assets:Stock   10 X {100.00 USD}
      Assets:Stock  -20 X {100.00 USD}

Against an empty account the answer was "no reduction", so nothing was
prepared. The second posting then failed, and `apply` hit its own "the guard
is unsound" assertion — turning an ordinary bad ledger into a panic out of
`rledger check`. Reproduced on main (f3ac855) as well as here, so this PR
neither caused nor previously fixed it; it is being fixed here because it is
the same guard this PR rewrites around.

Carrying a cost spec is what makes a posting able to reduce, and that does not
depend on inventory state, so the transaction cannot falsify it. Strictly more
conservative than the old test: every posting it used to catch carries a cost
spec too.

It is also cheaper, because it reads the posting instead of doing a map lookup
and an `is_booking_reduction` per posting. That removes the small regression
this PR had on cost-spec-free ledgers:

    simple 20k   main 860,854,747 -> 860,069,804   -0.09%   (was +0.30%)
    investment 2k             -> 122,184,256      -10.62%
    investment 20k            -> 1,206,894,976    -54.47%

`a_transaction_that_creates_and_then_oversells_a_lot_errors_rather_than_panicking`
pins the error path and that the buy is rolled back with it. Mutation-checked:
restoring the state-dependent guard fails it.
…ilure

Fourth correctness pass. Nothing new found by reading, so this changes
technique rather than re-reading.

`booking_properties.rs` pins that a failed `Inventory::reduce` does not
mutate — one posting. `apply` is the transaction: it can apply several
postings and then fail on a later one, and must undo everything it already
did. Nothing property-tested that.

It mattered less when `apply` cloned each touched account, because restoring
a whole copy is total by construction and cannot get the restoration wrong.
With an undo log, completeness is a property of the recording hooks, and the
hand-written tests only cover interleavings someone thought of — which is
exactly how two of the four earlier mutations survived and needed dedicated
cases for a drained lot and an added one.

`a_failed_transaction_restores_the_account_exactly` generates them instead:
randomized prefixes of buys (which push a slot), sells (which write a lot in
place or drain it) and `{*}` merges (which drop every matched lot at once),
followed by a leg that cannot succeed. The account must come back byte for
byte.

Worth more than the count of cases: this ONE property catches all three
recording hooks being broken — `IndexMut`, `set_dead` and `push_slot` — where
the hand-written suite needed three separate tests and initially missed two
of them.
Two review findings, both real.

`Slots::record` scanned the log linearly to answer "have I captured this slot
already?". For one or two slots that beats hashing, but `{*}` merge records
every matched lot, making recording O(k^2) in the lots merged — a fresh
quadratic inside the change that removed one. An `FxHashSet<usize>` answers
it in a couple of instructions and the common case loses nothing.

`apply`'s commit pass iterated postings, so a transaction with several
postings on one account re-entered `compact_if_sparse` for it. Compaction is
O(slots) when it fires. The pass now deduplicates, as the begin_undo pass
already did.

Investigating the first turned up something worth writing down: removing the
deduplication does NOT fail any test, and that is correct rather than a gap.
Rollback restores in REVERSE order, so when a slot is captured twice the
earliest entry — the true prior value — is applied last and wins. The dedup
bounds the log's size; reverse order is what makes duplicates safe. They are
independent, and only dropping BOTH corrupts a rollback. Both comments now
say so, because the previous note called forward order "merely wasteful",
which is true only while the dedup holds.

    investment 20k  1,209,859,775   (-54.36% vs main)
    simple 20k        859,416,021   (-0.17% vs main)
@robcohen
robcohen enabled auto-merge (squash) August 17, 2026 02:53
@robcohen
robcohen merged commit 44c0ebd into main Aug 17, 2026
79 of 81 checks passed
@robcohen
robcohen deleted the perf/apply-undo-log branch August 17, 2026 03:19
robcohen added a commit that referenced this pull request Aug 17, 2026
The mismatch is detected after `reduce` has already merged and drained,
so it relies on `apply`'s undo log (#2067) to restore the lots. A
cost-bearing negative posting always opens one, but a half-merged
inventory is exactly the silent corruption the check exists to prevent,
so assert it rather than assume it. Mutating `has_reduction` to `false`
fails the new assertion.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen added a commit that referenced this pull request Aug 17, 2026
Deep review of my own diff found three defects in the precondition, two
of them panics.

1. It fired on postings that never merge. `apply_posting` reduces only
   when `is_booking_reduction` says so; an augmentation carrying an
   explicit `{110.00 USD, *}` is ADDED, and comparing it against a pool
   it will not build rejected a valid posting. Now gated on the same
   canonical predicate, so the two cannot disagree.

2. Rejecting a `{*}` that CLOSES A SHORT panicked. A reduction is not
   the same thing as a negative posting — closing a short reduces
   cost-bearing lots with positive units. `rollback_needed` counts by
   sign (deliberately: reading current state to answer it caused the
   #2067 panic), so such a posting reached `apply`'s "the guard is
   unsound" assert with no undo log open. `has_reduction` now counts
   `{*}` postings in both directions: sign-independent, state-
   independent, and only `{*}` widens the gate, so the #1897 snapshot
   regression stays closed.

3. It rejected a buy and a `{*}` sale in ONE transaction. Booking books
   every posting against the inventory as it stood BEFORE the
   transaction; `apply` mutates sequentially. The earlier buy therefore
   moves the pool the sale meets, and the recorded cost is not
   comparable against it. The check now runs only for an account this
   transaction has not already touched — the state booking actually saw.

Also drops a stale doc header on `has_reduction` claiming it uses
`Inventory::is_booking_reduction`; it has not since #2067, and the
inline comment right below it explains why it must not.

Each fix has a test that fails without it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen added a commit that referenced this pull request Aug 18, 2026
…ay (#2069)

* fix(booking): carry `{*}` into application instead of resolving it away

`{*}` is the one cost spec that is an OPERATION rather than a filter.
Every other spec selects among lots that already exist, so booking can
safely resolve it into the single lot it picked and clear the marker.
`{*}` merges the pool and only then reduces it, so resolving it into the
per-unit cost of the pool it created names a lot that does not exist
until the merge has run. The application pass then reported
`No matching lot` for holdings the account plainly had, and a ledger
beancount accepts failed `rledger check` (#2068).

The single-lot rewrite now carries `cost_spec.merge` through, so
application re-runs the merge rather than searching for its result.

Carrying an operation has one cost a filter does not: the booked posting
is only meaningful against the inventory it was booked against, and
applied to different state it would silently build a different pool.
Booking records the per-unit cost of the pool it computed, so
`apply_posting` compares that against what the re-executed merge
produced and reports the new `BookingError::MergeMismatch` on a
disagreement — a wrong pool is the outcome this codebase treats as worse
than any error.

`reduce_merge` returns a single synthetic matched position by design, so
the multi-lot expansion branch cannot see a `{*}` reduction; this one
site is the whole fix.

Fixes #2068

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

* test(booking): pin that a rejected merge rolls the pool back

The mismatch is detected after `reduce` has already merged and drained,
so it relies on `apply`'s undo log (#2067) to restore the lots. A
cost-bearing negative posting always opens one, but a half-merged
inventory is exactly the silent corruption the check exists to prevent,
so assert it rather than assume it. Mutating `has_reduction` to `false`
fails the new assertion.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

* fix(booking): check the merge as a precondition, not after mutating

Copilot's review caught two things on the checksum, and the second one
was hiding a false positive I had shipped.

`apply_posting` is not only `apply`'s inner loop — the query executor
calls it directly to replay a FILTERED transaction stream. There a
different pool is the CORRECT answer for the stream it was given, not
evidence of corruption, so the checksum aborted any query whose FROM
filter excluded one of the merged lots:

  select account, account_balance from not (narration ~ 'lot 1')
  => evaluation error: {*} merge ... produced a pool cost of 120.00,
     but booking recorded 110.00

The check now lives in `apply`, which is the caller whose contract is
"reproduce booking's decision", and it runs BEFORE the merge mutates
anything rather than reporting after. That also answers the review's
other point: a precondition that reports post-mutation depends on
rollback to stay honest, and `apply_posting`'s own contract goes back to
"reduce only errors when the lot it would match is missing".

Knowing the pool without building it needs the selection half of
`reduce_merge` callable from `&self`, so `{*}` gets the plan/commit split
(#2061): `plan_merge` computes which lots merge and at what average,
`reduce_merge` commits it, and `merged_pool_cost` exposes the read-only
half. One implementation, two callers — perturbing the plan's pool fails
six `reduce_merge` tests, so the commit half really does consume it.

`MergeMismatch` now carries `Amount`s rather than bare decimals: the pool
cost is denominated in the COST currency, so `110.00 USD` where the
message previously read `110.00` next to a commodity named `X`.

Checked per posting rather than as a pre-pass over the transaction: an
earlier posting of the same transaction can legitimately change the pool
a later `{*}` sees.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

* fix(booking): only check a merge against the state booking saw

Deep review of my own diff found three defects in the precondition, two
of them panics.

1. It fired on postings that never merge. `apply_posting` reduces only
   when `is_booking_reduction` says so; an augmentation carrying an
   explicit `{110.00 USD, *}` is ADDED, and comparing it against a pool
   it will not build rejected a valid posting. Now gated on the same
   canonical predicate, so the two cannot disagree.

2. Rejecting a `{*}` that CLOSES A SHORT panicked. A reduction is not
   the same thing as a negative posting — closing a short reduces
   cost-bearing lots with positive units. `rollback_needed` counts by
   sign (deliberately: reading current state to answer it caused the
   #2067 panic), so such a posting reached `apply`'s "the guard is
   unsound" assert with no undo log open. `has_reduction` now counts
   `{*}` postings in both directions: sign-independent, state-
   independent, and only `{*}` widens the gate, so the #1897 snapshot
   regression stays closed.

3. It rejected a buy and a `{*}` sale in ONE transaction. Booking books
   every posting against the inventory as it stood BEFORE the
   transaction; `apply` mutates sequentially. The earlier buy therefore
   moves the pool the sale meets, and the recorded cost is not
   comparable against it. The check now runs only for an account this
   transaction has not already touched — the state booking actually saw.

Also drops a stale doc header on `has_reduction` claiming it uses
`Inventory::is_booking_reduction`; it has not since #2067, and the
inline comment right below it explains why it must not.

Each fix has a test that fails without it.

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 18, 2026
…#2085)

* perf(core): stop rebuilding and rescanning on every ordered reduction

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

* perf(core): box the ordered index and keep it unbuilt until needed

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

* docs(core): say that the ordered index holds cost-less lots too

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

* fix(core): keep insufficiency ahead of overflow, and stop indexing for 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

* fix(core): stop a multi-lot reduction sweeping unrelated empty lots

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

---------

Co-authored-by: Claude Opus 5 <[email protected]>
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]>
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.

2 participants