Skip to content

perf(core): give HIFO and STRICT_WITH_SIZE plan halves and a shared ordered walk - #2092

Merged
robcohen merged 3 commits into
mainfrom
perf/hifo-ordered-index
Aug 19, 2026
Merged

robcohen merged 3 commits into
mainfrom
perf/hifo-ordered-index

Conversation

@robcohen

Copy link
Copy Markdown
Member

Fixes #2091. Both methods were quadratic; on a ledger whose sells name an exact cost, at 20,000 transactions:

method main this PR
HIFO 7.79s 0.58s 13.4×
STRICT_WITH_SIZE 2.42s 0.29s 8.3×
STRICT / FIFO / LIFO / AVERAGE / NONE 0.27–0.33s 0.27–0.29s unchanged

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 preview book uses — answered from &self only for STRICT, FIFO and LIFO:

BookingMethod::StrictWithSize | BookingMethod::Hifo
| BookingMethod::Average | BookingMethod::None => self.clone().reduce(units, cost_spec, method),

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_hifo also carried its own copy of the ordered walk — scan every slot, sort by cost, sum for sufficiency, take — which is plan_ordered with a different key. It now shares that walk and gets the maintained index and early stop with it. LotOrder records which key an inventory's index is sorted by; reduce builds 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_size additionally narrows through cost_index before filtering, as plan_strict does.

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 of self lets the binary search read positions on 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_first and 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

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

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
@github-actions

github-actions Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 40.6ms ± 5.5ms 24.2 MB
beancount 752.2ms ± 3.4ms 50.6 MB
Comparison 18.5x faster 2.1x less

vs main branch (2026-08-19)

Metric main this PR Change
Time 38.8ms 40.6ms +4.6% ✅
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 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.08257% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/booking.rs 99.29% 1 Missing ⚠️
crates/rustledger-core/src/inventory/mod.rs 98.68% 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 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 + OrderedIndex so an inventory tracks which ordering its ordered index is sorted by, enabling reuse across FIFO/LIFO/HIFO.
  • Converts HIFO and STRICT_WITH_SIZE preview 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.

@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

robcohen and others added 2 commits August 19, 2026 11:36
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
@robcohen

Copy link
Copy Markdown
Member Author

Deep correctness review of both halves

Reviewed 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

try_reduce_predicts_reduce (500 cases, all seven booking methods) asserts the preview and the commit agree exactly — which is precisely the invariant this PR risks, since try_reduce now returns a planned result where it used to clone the inventory and execute. It passes.

Its limit is worth stating: it compares the BookingResult, not the resulting inventory, and both sides share the plan code — so it cannot see an ordering error. The method tests cover that (six fail on a reversed cost key, verified by mutation).

Two decisions checked by mutation, one gap found

plan_strict_with_size carries two behaviour-bearing choices I rewrote. I mutated each:

mutation caught?
pick the LAST exact-size match instead of the first ✅ test_strict_with_size_multiple_exact_matches_picks_oldest
total-match fallback walks LIFO instead of FIFO ❌ nothing failed

The second is a test that does not test its name. strict_with_size_total_match_falls_back_to_fifo asserted only the total basis — 3000 either way, because a total match consumes every matching lot and any order sums the same. Fixed in 843b17d: it now asserts the matched lots come back oldest-first, and fails on the flip.

That branch is one this PR rewrote — plan_ordered(.., LotOrder::Date, false) where it used to be reduce_ordered(.., false) — so nothing but the function name recorded which direction was intended.

Checked and sound

  • Tie-breaking. The old sorts were stable over iter_slots(), so equal keys stayed in ascending slot order. The index build sorts by order_key alone (stable, same input order) and the incremental insert compares (order_key, slot) — consistent, and the differential test covers maintenance.
  • Candidate narrowing cannot lose a lot. plan_strict_with_size narrows through cost_index before filtering. A lot that matches a cost-naming spec necessarily has that cost key; a spec naming no cost returns None from cost_candidates and falls back to the scan, which is what keeps cost-less lots reachable.
  • Ambiguity counts are unaffected by that narrowing, for the same reason — n counts lots that pass matches_cost_spec, and narrowing only removes lots that would have failed it.
  • Index/order mismatch is safe. ordered_candidates returns None when the stored ordering is not the one asked for, so a STRICT_WITH_SIZE total-match fallback asking for Date against a HIFO account's cost-ordered index scans rather than answering wrongly.
  • Dead code removed. reduce_from_lot had no callers left once both methods planned; clippy caught it.

146 suites green; clippy, fmt and doc clean.

@robcohen
robcohen merged commit 77412ad into main Aug 19, 2026
57 of 59 checks passed
@robcohen
robcohen deleted the perf/hifo-ordered-index branch August 19, 2026 12:30
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.

HIFO and STRICT_WITH_SIZE still scan every lot per reduction (HIFO: 18s at 20k, 101x for 10x input)

2 participants