Repository navigation
perf(core): give HIFO and STRICT_WITH_SIZE plan halves and a shared ordered walk - #2092
Conversation
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
📊 Benchmark Results
vs main branch (2026-08-19)
What do these numbers mean?
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
Pull request overview
Improves rustledger-core inventory booking performance by eliminating per-reduction full-inventory clones for HIFO and STRICT_WITH_SIZE, and by sharing a single ordered “planned walk” implementation across FIFO/LIFO/HIFO with a lazily-built, order-aware index.
Changes:
- Introduces
LotOrder+OrderedIndexso an inventory tracks which ordering its ordered index is sorted by, enabling reuse across FIFO/LIFO/HIFO. - Converts
HIFOandSTRICT_WITH_SIZEpreview paths (try_reduce) to plan from&self(no clone) and commit separately, matching the existing plan/commit design. - Extends the scan-vs-index equivalence test to also exercise the new HIFO cost ordering.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| crates/rustledger-core/src/inventory/mod.rs | Reworks ordered_index into an order-aware OrderedIndex, adds LotOrder and order_key, and rebuild logic keyed by ordering. |
| crates/rustledger-core/src/inventory/booking.rs | Refactors try_reduce and booking methods to use planned HIFO / STRICT_WITH_SIZE, and generalizes plan_ordered to accept LotOrder. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
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
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
Deep correctness review of both halvesReviewed HIFO and STRICT_WITH_SIZE separately, since they change different things — HIFO's selection moves onto a shared walk, STRICT_WITH_SIZE keeps its own branching and only stops cloning. What guards the conversion
Its limit is worth stating: it compares the Two decisions checked by mutation, one gap found
The second is a test that does not test its name. That branch is one this PR rewrote — Checked and sound
146 suites green; clippy, fmt and doc clean. |
Fixes #2091. Both methods were quadratic; on a ledger whose sells name an exact cost, at 20,000 transactions:
All seven booking methods now sit between 0.27s and 0.58s. HIFO was 27× slower than FIFO on the same ledger for no reason a user could see.
The cost was not where the issue said it was
I filed #2091 pointing at their lot scans, because that is what #2083 had just fixed one function over. The scans are real but secondary.
try_reduce— the previewbookuses — answered from&selfonly for STRICT, FIFO and LIFO:An O(lots) copy of the whole inventory per reducing posting. #2061 split the first three and left a comment calling the rest "mechanical to convert". This converts the two that measured quadratic.
reduce_hifoalso carried its own copy of the ordered walk — scan every slot, sort by cost, sum for sufficiency, take — which isplan_orderedwith a different key. It now shares that walk and gets the maintained index and early stop with it.LotOrderrecords which key an inventory's index is sorted by;reducebuilds the one the account's method consumes. An account has one booking method, so that is one index with a recorded ordering rather than two kept in step.reduce_strict_with_sizeadditionally narrows throughcost_indexbefore filtering, asplan_strictdoes.Two things measuring caught that reading would not
My first index insert was itself quadratic. To dodge a borrow conflict it materialized every key in the currency per
add— so the growth term moved rather than left, and HIFO measured 7.73s → 7.86s. Taking the index out ofselflets the binary search readpositionson each probe. Without measuring after the change, this would have shipped as a "fix".The scan-equivalence test cannot see an ordering error. Both sides call
order_key, so reversing it moves them together and the test stays green — I verified that by mutating it. The orderings are pinned by the method tests instead (test_hifo_reduces_highest_cost_firstand five others fail on the reversed key), and the test now documents that division rather than implying coverage it does not have.Left alone deliberately
AVERAGE and NONE still preview by cloning. Both measure flat here — AVERAGE holds one pooled lot per commodity, NONE matches no lots — so the copy is small. Converting them on speculation is how the previous "mechanical" note aged into two quadratics.
Verification
✓ No errors found) — worth stating, because the first STRICT_WITH_SIZE measurement in HIFO and STRICT_WITH_SIZE still scan every lot per reduction (HIFO: 18s at 20k, 101x for 10x input) #2091 was taken on a ledger that failed to book and was therefore profiling the error path. Corrected on the issue.🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr