Repository navigation
perf(core): compute reductions from &self, so previewing stops copying - #2061
Conversation
The `make_owned` comment said `self.positions` is "often structurally shared — the booking engine clones an account's inventory into a working copy via imbl's O(1) clone". That has not been true since #2056 made the store a hybrid. `PositionStore::default()` is `Owned(Vec)`, so `BookingEngine`'s inventories are owned and the per-transaction working copy it takes in `book()` is a DEEP O(lots) copy. The structurally-shared case is BQL's snapshots via `Inventory::new_shared`. This is not a cosmetic correction. Profiling found that copy to be the dominant superlinear term left in the pipeline — `Position::clone` grows 104x for 10x the input on the `investment` shape, chain `Position::clone <- Inventory::clone <- BookingEngine::book`/`::apply` — and a comment asserting the clone is O(1) is a good reason nobody looked at it. The rest of the comment, on why in-place mutation of a shared `imbl::Vector` corrupts the interned `Arc<str>`, is untouched and still correct.
There was a problem hiding this comment.
Pull request overview
This PR updates the in-code documentation in rustledger-core to correct an outdated claim about Inventory::reduce’s cloning behavior after the PositionStore hybrid backing change (#2056), clarifying that booking uses owned inventories (deep clone) while BQL snapshots may use structural sharing.
Changes:
- Correct the comment in
Inventory::reduceto state that structural sharing applies to BQL snapshots (Inventory::new_shared), not the booking engine. - Document that
BookingEngine::bookclones inventories deeply (O(lots)) due toPositionStore::default()beingOwned(Vec). - Add brief profiling context explaining why the prior O(1)-clone claim was misleading for performance investigations.
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
📊 Benchmark Results
vs main branch (2026-08-15)
What do these numbers mean?
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
`Inventory::try_reduce` was `self.clone().reduce(..)` — it deep-copied every
lot in an account to preview a reduction that touches one or two of them.
`BookingEngine::book` then took its own working copy of each touched
account's inventory, per transaction, for the same reason. Both are O(lots),
and lots accumulate, so booking grew superlinearly with ledger size.
Each affected method is now split into a `plan_*` half that computes from
`&self` and a commit half that applies the result:
reduce_from_lot = plan_from_lot + commit_from_lot
reduce_ordered = plan_ordered + commit_updates
reduce_strict = plan_strict + commit_plan
The selection logic lives in the `plan_*` half and ONLY there — the mutating
path calls it too. That is the point: `try_reduce` duplicating `reduce`'s
selection is precisely the drift `try_reduce_equivalence` was written for,
after it had already happened once. STRICT_WITH_SIZE, HIFO, AVERAGE, NONE and
the `{*}` merge operator still preview by cloning; correct, just O(lots), and
mechanical to convert when something needs it.
`book` now clones an inventory only for an account with MORE THAN ONE
reducing posting in the transaction — the case where a second posting must
see what the first took. With a single posting nothing reads the mutation
back, so it previews against the live inventory and copies nothing.
Cachegrind, both sides rebuilt at HEAD, base a218920:
investment 2k 182,434,646 -> 161,811,594 -11.30%
investment 20k 7,651,077,174 -> 5,784,989,413 -24.39%
simple 20k 2,251,393,629 -> 2,251,388,486 0.00%
`simple` is unchanged because it books no cost specs, which is the shape of
the change: it removes work proportional to accumulated lots.
Mechanism confirmed rather than inferred — `Position::clone` went from 1.30G
instructions to 0.32G (-76%), `drop_glue::<Position>` from 5.3% to 1.8%.
Scaling for 10x input improves 41.9x -> 35.8x. Still superlinear: the
remaining terms are `is_reduced_by`, an O(lots) scan per posting that is now
the largest at 9.0%, and the O(lots) `rebuild_index` on the commit path.
Neither is touched here.
`two_reducing_postings_on_one_account_see_each_other` pins the case the
working copy still exists for: 10 units held, 6 and 6 sold in one
transaction must fail on insufficient units, and 6 and 4 must succeed.
Mutation-checked — removing the working copy entirely fails that test and
the existing `test_multi_posting_crosses_lot_boundary`.
Brings the comment corrected two commits ago up to date with the refactor that followed it in this PR: `book` previews through `try_reduce` now and copies only for an account with more than one reducing posting.
Found while reviewing the plan/commit split, and fixed by it. `reduce_ordered` states the rule itself — "a failed reduction must leave the inventory untouched" — and enforced it for the sufficiency check, which runs before the loop. The cost-basis OVERFLOW check did not get the same treatment: it lived inside the mutation loop, so a reduction that overflowed on the Nth lot returned `Err` with lots 1..N-1 already drained. The validator reduces against live `LedgerState` inventories, so that partial drain corrupts every later balance assertion on the account. Computing the whole plan before committing any of it makes the rule hold for both checks by construction, so this needed no separate fix — only a test. Verified as a real defect rather than a hypothetical: the new test was transplanted onto main (9211cff) and fails there, with the first of two lots at 0 units while the reduction reports `Err(Overflow)`. Also addresses review feedback on the phrasing of the corrected `make_owned` comment, and notes why the `self.inventories[..]` index in `book` cannot panic.
|
Deep review of the refactor itself (Copilot's review above was generated on the docs-only commit, before the refactor landed, so its overview describes only that). A latent bug the split fixes
Computing the plan before committing any of it makes the rule hold for both checks by construction — no separate fix, only a test. Verified as real, not hypothetical: Equivalence points checked
Residual risk, stated plainlyThe gate deciding which accounts get a working copy must stay in step with the reduction path's own gate. Drifting toward cloning more only wastes work; drifting toward cloning less would silently drop a second posting's view of the first. That is pinned by Compat is 100% (check / BQL / full AST) and the benchmark job reports −3.7% wall clock. |
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
…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]>
…#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]>
Both were quadratic. On a ledger whose sells name an exact cost, at
20,000 transactions:
HIFO 7.79s -> 0.58s 13.4x
STRICT_WITH_SIZE 2.42s -> 0.29s 8.3x
All seven booking methods now sit between 0.27s and 0.58s, where HIFO was
27x slower than FIFO on the same ledger.
The dominant cost was not their lot scans, which is where I started
looking. `try_reduce` — the preview `book` uses — answered from `&self`
only for STRICT, FIFO and LIFO; everything else went through
`self.clone().reduce(..)`, an O(lots) copy of the inventory per reducing
posting. #2061 left that as "mechanical to convert" when it split the
first three. This converts the two that were measurably quadratic.
`reduce_hifo` also carried its own copy of the ordered walk — scan every
slot, sort by cost, sum for sufficiency, take — which is what
`plan_ordered` already does with a date key. It now shares that walk, so
it gets the maintained index and the early stop too: `LotOrder` says
which key an inventory's index is sorted by, and `reduce` builds the one
the account's method consumes. An account has one booking method, so this
is one index with a recorded ordering rather than two kept in step.
`reduce_strict_with_size` additionally narrows through `cost_index`
before filtering, the way `plan_strict` does.
Two things worth recording, both found by measuring rather than reading:
- My first version of the index insert materialized every key in the
currency to dodge a borrow conflict, making each `add` O(lots) — the
quadratic moved rather than left. Taking the index out of `self` lets
the binary search read `positions` per probe.
- The scan-equivalence test cannot see an ordering error, because both
sides call `order_key`; reversing it leaves the test green. Verified by
mutating it. The orderings are pinned by the method tests instead, and
the test now says so.
AVERAGE and NONE still preview by cloning. Both measure flat here —
AVERAGE holds one pooled lot per commodity and NONE matches no lots — so
the copy is small, and converting them on speculation is how the last
"mechanical" note aged.
Fixes #2091
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…rdered walk (#2092) * perf(core): give HIFO and STRICT_WITH_SIZE plan halves and a shared walk Both were quadratic. On a ledger whose sells name an exact cost, at 20,000 transactions: HIFO 7.79s -> 0.58s 13.4x STRICT_WITH_SIZE 2.42s -> 0.29s 8.3x All seven booking methods now sit between 0.27s and 0.58s, where HIFO was 27x slower than FIFO on the same ledger. The dominant cost was not their lot scans, which is where I started looking. `try_reduce` — the preview `book` uses — answered from `&self` only for STRICT, FIFO and LIFO; everything else went through `self.clone().reduce(..)`, an O(lots) copy of the inventory per reducing posting. #2061 left that as "mechanical to convert" when it split the first three. This converts the two that were measurably quadratic. `reduce_hifo` also carried its own copy of the ordered walk — scan every slot, sort by cost, sum for sufficiency, take — which is what `plan_ordered` already does with a date key. It now shares that walk, so it gets the maintained index and the early stop too: `LotOrder` says which key an inventory's index is sorted by, and `reduce` builds the one the account's method consumes. An account has one booking method, so this is one index with a recorded ordering rather than two kept in step. `reduce_strict_with_size` additionally narrows through `cost_index` before filtering, the way `plan_strict` does. Two things worth recording, both found by measuring rather than reading: - My first version of the index insert materialized every key in the currency to dodge a borrow conflict, making each `add` O(lots) — the quadratic moved rather than left. Taking the index out of `self` lets the binary search read `positions` per probe. - The scan-equivalence test cannot see an ordering error, because both sides call `order_key`; reversing it leaves the test green. Verified by mutating it. The orderings are pinned by the method tests instead, and the test now says so. AVERAGE and NONE still preview by cloning. Both measure flat here — AVERAGE holds one pooled lot per commodity and NONE matches no lots — so the copy is small, and converting them on speculation is how the last "mechanical" note aged. Fixes #2091 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * fix(core): HIFO must rank a cost-less lot below every costed one Copilot's review, and a real behavior change I had shipped into the PR. The scan this replaced counted a missing cost as `Decimal::ZERO` before reversing, so a cost-less lot sorted LAST in a highest-cost-first walk. Ordering on `Option<Decimal>` put it FIRST instead, because `None` sorts before `Some` — the opposite lot, for the same input. An empty cost spec matches a cost-less position, so HIFO can reach one. `hifo_takes_costed_lots_before_costless_ones` pins it, and fails on the `Option` key: the index flips from [1, 0] to [0, 1] and the reduction drains the cost-less lot. Worth noting how nearly this test shipped vacuous. Checking it against the old key appeared to pass, which would have meant it proved nothing — except the mutation had silently not applied, because `cargo fmt` had collapsed the expression onto one line and the patch still matched the old three-line form. The lesson is the same one this session keeps teaching: a mutation that "survives" is a claim about the edit as much as about the test, and it is worth printing what actually changed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * test(core): assert the order the STRICT_WITH_SIZE fallback claims Review of my own diff. `strict_with_size_total_match_falls_back_to_fifo` asserted only the total cost basis, which is 3000 whichever end the walk starts from — a total match consumes every matching lot, so any order sums the same. The test's subject is the ORDER, and flipping the fallback to LIFO left it green. Now asserts the matched lots come back oldest-first, and fails on that flip. The branch is one I rewrote in this PR, so the gap was worth closing here: `plan_strict_with_size` reaches the fallback through `plan_ordered(.., LotOrder::Date, false)` where it used to call `reduce_ordered(.., false)`, and nothing but the name said which direction was intended. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr --------- Co-authored-by: Claude Opus 5 <[email protected]>
Inventory::try_reducewasself.clone().reduce(..)— it deep-copied every lot in an account to preview a reduction touching one or two of them.BookingEngine::bookthen took its own working copy of each touched account's inventory, per transaction, for the same reason. Both are O(lots), lots accumulate, so booking grew superlinearly with ledger size.The change
Each affected method splits into a
plan_*half computed from&selfand a commit half that applies it:reduce_from_lotplan_from_lotcommit_from_lotreduce_orderedplan_orderedcommit_updatesreduce_strictplan_strictcommit_planSelection logic lives in the
plan_*half and only there — the mutating path calls it too. That's the point:try_reduceduplicatingreduce's selection is exactly the drifttry_reduce_equivalencewas written for, after it had already happened once.STRICT_WITH_SIZE, HIFO, AVERAGE, NONE and the
{*}merge operator still preview by cloning. Correct, just O(lots), and mechanical to convert when something needs it.booknow clones only for an account with more than one reducing posting in a transaction — the case where a second posting must see what the first took. With a single posting nothing reads the mutation back, so it previews against the live inventory and copies nothing.Measured
Cachegrind, both sides rebuilt at HEAD, base
a218920251:investment2kinvestment20ksimple20ksimpleis unchanged because it books no cost specs — which is the shape of the change: it removes work proportional to accumulated lots.Mechanism confirmed, not inferred.
Position::clonewent from 1.30G instructions to 0.32G (−76%);drop_glue::<Position>from 5.3% to 1.8% of the run.Scaling for 10× input improves 41.9× → 35.8×. Still superlinear, and I want to be plain about that: the remaining terms are
is_reduced_by— an O(lots) scan per posting, now the single largest at 9.0% — and the O(lots)rebuild_indexon the commit path. Neither is touched here.Correctness
two_reducing_postings_on_one_account_see_each_otherpins the case the working copy still exists for: 10 units held, 6 and 6 sold in one transaction must fail on insufficient units; 6 and 4 must succeed. Mutation-checked — removing the working copy entirely fails that test and the existingtest_multi_posting_crosses_lot_boundary.The
try_reduce_equivalenceproptest (try_reduce(&inv, op) == reduce(&mut inv.clone(), op), every booking method, randomized inventories) passes throughout and is the main guard on the split.Also in here
Two commits correcting
reduce'smake_ownedcomment, which claimed the booking engine's working copy was an imbl O(1) clone. That stopped being true at #2056 and is a good part of why the copy went unexamined — it was the one piece of evidence pointing the wrong way while I was chasing this. The second commit brings it up to date with the refactor.Gates:
cargo test --workspace --all-features(141 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