Skip to content

perf(core): answer is_reduced_by from cached counts, not a scan - #2062

Merged
robcohen merged 3 commits into
mainfrom
perf/is-reduced-by-index
Aug 16, 2026
Merged

robcohen merged 3 commits into
mainfrom
perf/is-reduced-by-index

Conversation

@robcohen

Copy link
Copy Markdown
Member

is_reduced_by scanned every lot to decide whether a posting reduces or augments. It runs once per posting over a list that grows as lots accumulate, which made it the largest single item left in the investment profiling shape at 9.0% of the run, growing 93× for 10× the input.

units_cache now carries, per currency, the position counts split by sign and cost-bearing-ness alongside the running total, so the question is a map lookup.

Measured

Cachegrind, both sides rebuilt at HEAD, base 7ac19057eb:

workload main branch delta
investment 2k 147,905,237 144,287,622 −2.45%
investment 20k 4,386,867,143 3,888,192,458 −11.37%
simple 20k 853,838,870 859,506,410 +0.66%
tagged 10k 681,599,654 684,549,044 +0.43%

The two small regressions are real, not noise — cachegrind is deterministic. Maintaining the counts costs every ledger; only ledgers that book cost specs collect. simple never even calls is_reduced_by, because is_booking_reduction short-circuits on cost.is_some() first. I'm accepting that deliberately: 11.4% off the shape that was superlinear, against half a percent on shapes that are not. Happy to drop it if you'd rather not pay that.

They started much worse. A separate index hung off the same key added a third hash of an interned string per posting and measured +5.56% on simple. Folding the counts into the entry add already touches, and fusing add's read-then-write into a single get_mut, brought it to +0.66%.

Scaling for 10× input improves 29.7× → 26.9×. Still superlinear — the O(lots) rebuild_index on the multi-lot commit path is untouched.

Why the scan stays

is_reduced_by_scan is kept as the definition the counts are checked against by a debug_assert on every call, and as the fallback when the cache is unbuilt — it is #[serde(skip)], so a deserialized inventory has positions and no cache.

Test

the_sign_index_tracks_every_mutation_path walks every path that can move a lot between buckets and, at each step, asserts the incrementally maintained counts equal a fresh rebuild. That invariant is stronger than "the answers agree": an unmaintained cache still answers correctly via the fallback, so a path that quietly stopped maintaining it would restore the O(lots) cost with the suite still green.

Five mutations run against it, all five caught. Two needed fixtures the first version lacked, and both are worth knowing:

  • the removal path is only reachable through STRICT's single-lot commit, which maintains caches incrementally. A FIFO-only test never touches it, because FIFO rebuilds instead.
  • reclassifying a lot on commit only matters for a SHORT lot covered to exactly zero: is_sign_positive answers true for zero, so the lot changes bucket in the instant before removal. A long lot is capped at zero from above and never leaves its bucket, so no long-only fixture can show it.

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

`is_reduced_by` scanned every lot to decide whether a posting reduces or
augments. It runs once per posting over a list that grows as lots
accumulate, which made it the largest single item left in the `investment`
profiling shape at 9.0% of the run, growing 93x for 10x the input.

`units_cache` now carries, per currency, the position counts split by sign
and by cost-bearing-ness alongside the running total, so the question is a
map lookup. `is_reduced_by` keeps the scan as `is_reduced_by_scan`: it is
the definition the counts are checked against by a `debug_assert` on every
call, and the fallback when the cache is unbuilt (it is `#[serde(skip)]`,
so a deserialized inventory has positions and no cache).

ONE map, not two. A separate index hung off the same key added a third hash
of an interned string per posting and measured +5.56% on the cost-spec-free
`simple` shape. Folding the counts into the entry `add` already touches,
and fusing `add`'s read-then-write into a single `get_mut`, brought that to
+0.66%.

Cachegrind, both sides rebuilt at HEAD, base 7ac1905:

    investment 2k     147,905,237 -> 144,287,622   -2.45%
    investment 20k  4,386,867,143 -> 3,888,192,458 -11.37%
    simple 20k        853,838,870 ->   859,506,410  +0.66%
    tagged 10k        681,599,654 ->   684,549,044  +0.43%

The two small regressions are real, not noise — cachegrind is
deterministic. Maintaining the counts costs every ledger; only ledgers that
book cost specs collect. `simple` never even calls `is_reduced_by`, because
`is_booking_reduction` short-circuits on `cost.is_some()` first. Accepted
deliberately: 11.4% off the shape that was superlinear, against half a
percent on shapes that are not.

Scaling for 10x input improves 29.7x -> 26.9x. Still superlinear — the
O(lots) `rebuild_index` on the multi-lot commit path is untouched.

`the_sign_index_tracks_every_mutation_path` walks every path that can move
a lot between buckets and, at each step, asserts the incrementally
maintained counts equal a fresh rebuild. That invariant is stronger than
"the answers agree": an unmaintained cache still answers correctly via the
fallback, so a path that quietly stopped maintaining it would restore the
O(lots) cost with the suite still green.

Five mutations were run against it and all five are caught. Two needed
fixtures the first version lacked, and both are worth knowing:

  - the removal path is only reachable through STRICT's single-lot commit,
    which maintains caches incrementally; a FIFO-only test never touches it
    because FIFO rebuilds instead.
  - reclassifying a lot on commit only matters for a SHORT lot covered to
    exactly zero. `is_sign_positive` answers true for zero, so the lot
    changes bucket in the instant before removal. A long lot is capped at
    zero from above and never leaves its bucket, so no long-only fixture
    can show it.
@robcohen
robcohen requested a review from a team as a code owner August 15, 2026 22:34
Copilot AI lite review requested due to automatic review settings August 15, 2026 22:34
@codecov

codecov Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.56710% with 1 line in your changes missing coverage. Please review.

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

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 36.6ms ± 0.3ms 24.2 MB
beancount 914ms ± 11.6ms 50.6 MB
Comparison 25x faster 2.1x less

vs main branch (2026-08-15)

Metric main this PR Change
Time 38.3ms 36.6ms -4.4% ✅
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

Self-review of the sign-counts change.

`SignCounts::bump` took an `i64` and ended in
`saturating_add_signed(delta.try_into().unwrap_or(0))`. For a value outside
`i32` — which no caller can produce — that silently applies NO change,
leaving the counts wrong with nothing to show for it. The parameter is now
`i32`, feeding `saturating_add_signed` directly, with a `debug_assert` that
callers move one lot at a time.

`add`'s insert branch ignores `vacated`, which is correct but only because
`merge_idx` comes from `simple_index`, so a merge target is always a lot
`add` already counted and whose currency therefore has an entry. Stated as
a `debug_assert` rather than left for the next reader to re-derive.

No behavior change; the measured numbers are unaffected.

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 optimizes rustledger-core’s Inventory::is_reduced_by by replacing a per-call scan over lots with an O(1) lookup using per-currency cached sign/count statistics, trading a small constant overhead in all ledgers for a large improvement in cost-spec-heavy workloads.

Changes:

  • Extend units_cache to store per-currency running totals plus sign/cost-bearing position counts (CurrencyStats/SignCounts) used by is_reduced_by.
  • Rework is_reduced_by to answer from cached counts (with scan fallback for unbuilt caches and a debug-mode consistency check against the scan).
  • Update hot mutation paths (add, cache rebuild, and commit_from_lot) and add a new regression test to ensure the cached counts stay consistent across mutation paths.

Reviewed changes

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

File Description
crates/rustledger-core/src/inventory/mod.rs Adds per-currency cached sign/count stats, updates add/cache rebuild logic to maintain them, and switches is_reduced_by to O(1) lookup with scan verification + new invariants test.
crates/rustledger-core/src/inventory/booking.rs Updates the single-lot reduction commit path to maintain the new cached sign/count stats during in-place lot mutation/removal.

💡 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%, 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

Three review findings, all real.

`SignCounts::opposite` summed the cost-bearing and cost-less counts with
`+`. These are lot counts and cannot realistically reach `u32::MAX`, but a
wrap reads as "no matching lot" — which books a reduction as an
augmentation and duplicates the lot, the #875-class bug the predicate
exists to prevent. Saturating errs the other way and `> 0` is all the
caller asks. I had noticed this while reviewing and filed it as minor; a
wrap that flips the answer in the unsafe direction is not minor.

`units()` told callers to "ensure cache is built via rebuild_caches() after
deserialization". No such function has ever existed — `rebuild_index` is
the real one — and deserialization has rebuilt the caches since the
`#[serde(try_from = "InventoryWire")]` change, so the advice was wrong
twice over.

`positions_mut`'s new note pointed at `compact()` for rebuilding the caches
without saying that it also DROPS every empty position. A caller refreshing
caches would silently lose a deliberately-kept zero-unit lot.

Also adds `an_unbuilt_cache_falls_back_to_the_scan_rather_than_answering_no`
for the branch codecov flagged. `positions_mut` is the one route to an
inventory holding lots with no cache, and the fallback is what stops that
inventory reporting a sale as a purchase. Mutation-checked: deleting the
fallback fails that test, and dropping the cost-less term from the
`AllPositions` arm fails too.
@robcohen
robcohen merged commit 6166f7f into main Aug 16, 2026
76 of 78 checks passed
@robcohen
robcohen deleted the perf/is-reduced-by-index branch August 16, 2026 00:48
robcohen added a commit that referenced this pull request Aug 18, 2026
…le name

Copilot's review, all three findings.

The module doc named `the_detector_can_report_dirty`, which was renamed
to `the_comparison_can_report_dirty` when the self-check moved from
asserting the product still has the bug to exercising the comparator.

The seed buys were applied under `if ... .is_ok()`, so a regression in
`apply` would have silently skipped them and let the property hold
vacuously — the exact failure mode this file exists to prevent. They are
fixtures; they now assert. So does applying a transaction that booked:
`apply`'s precondition is booked input and `book` just produced it, so
that pair failing is itself a defect rather than a case to skip. Only an
unbookable transaction is still skipped, which is a different failure and
says nothing about this invariant.

The ordering pre-pass built two `Vec`s per transaction; it now classifies
once into a `u64` bitmask, with source order beyond the 64th posting.

The other half of that finding does not apply: the pre-pass and
`apply_posting` ask the same predicate about deliberately DIFFERENT
state — pre-transaction versus live — and sharing one answer between them
would reintroduce the divergence this PR fixes. Nor is the call a scan:
`is_reduced_by` has read per-currency sign counts since #2062, so both
calls are hash lookups.

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
…ns (#2081)

* test(booking): detect book/apply disagreement over holdings (#2070)

`book` and `apply` are two derivations of the same quantity, and nothing
checked that they agree. #2070 is what that costs: for a buy and a
reduction in ONE transaction, the journal and the engine report different
cost bases, silently.

The invariant is that the engine's holdings equal the sum of the booked
postings. It compares units and basis rather than lot structure, because
ADR-0007 deliberately lets the engine pool while the journal keeps
per-lot costs — pooling preserves both totals, so this asserts only what
the two representations must agree on and stays silent about the
representation itself.

Proptest over four booking methods and the four reduction shapes
(explicit cost, bare `{}`, `{*}`, and buys) shrinks #2070 to a
two-posting minimal case: hold 40 @ 100, then buy 1 @ 101 and `{*}`-sell
1 in the same transaction, and the two answers differ by 0.0244.

Finding worth recording: the run also surfaced a SECOND, unrelated class
— a pooled cost like 7939/79 does not terminate, so the engine stores it
rounded on the remainder while the journal keeps the un-rounded sum, and
the two differ in the 25th significant digit. That is inherent to
per-unit average costing rather than a disagreement about a decision, so
`within_rounding_residue` absorbs it, at a bar twenty orders of magnitude
below the divergence this file hunts.

The self-check tests the COMPARATOR, not the product. Asserting "the
known-bad shape still diverges" inverts the moment the bug is fixed,
leaving the harness unguarded exactly when it starts mattering.

Verified in both states: fails on `main`, passes with the
`research/2070-apply-order` prototype applied.

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

* fix(booking): apply a transaction's reductions before its augmentations

`book` decides every posting against the inventory as it stood before the
transaction, threaded with that transaction's earlier reductions and
nothing else. That is not an accident of implementation: beancount's
`book_reductions` does the same, and its comment states the reason — an
augmentation's cost may still need interpolation, so it is not a
resolvable position yet.

`apply` mutated in posting order, so a buy earlier in the transaction was
already in the account when a later reduction ran. For a spec naming a
concrete lot that changes nothing. For the two that RE-DERIVE a pool,
`AVERAGE` and `{*}`, it moves the pool — and the engine then disagreed
with the journal about cost basis, silently:

    2024-02-01 * "buy then sell in ONE transaction"
      Assets:Stock   10 X {120.00 USD}
      Assets:Stock   -5 X {}

booked postings 1,700.00 USD of basis; the engine held 1,650.00.

Ordering the cost-bearing reductions first restores the agreement.
Classifying against the pre-transaction inventory rather than threading
decides ORDER only — `apply_posting` classifies each posting itself
against live state — and the disagreement can only run one way, since
threading removes units and so can only make a posting look less like a
reduction.

Nothing that used to load stops loading: `book` already rejects a
reduction covered only by its own transaction's augmentation, so it is
the stricter gate either way. Verified unchanged on that ledger.

Fixes #2070

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

* fix(booking): address review — assert seeds, classify once, fix a stale name

Copilot's review, all three findings.

The module doc named `the_detector_can_report_dirty`, which was renamed
to `the_comparison_can_report_dirty` when the self-check moved from
asserting the product still has the bug to exercising the comparator.

The seed buys were applied under `if ... .is_ok()`, so a regression in
`apply` would have silently skipped them and let the property hold
vacuously — the exact failure mode this file exists to prevent. They are
fixtures; they now assert. So does applying a transaction that booked:
`apply`'s precondition is booked input and `book` just produced it, so
that pair failing is itself a defect rather than a case to skip. Only an
unbookable transaction is still skipped, which is a different failure and
says nothing about this invariant.

The ordering pre-pass built two `Vec`s per transaction; it now classifies
once into a `u64` bitmask, with source order beyond the 64th posting.

The other half of that finding does not apply: the pre-pass and
`apply_posting` ask the same predicate about deliberately DIFFERENT
state — pre-transaction versus live — and sharing one answer between them
would reintroduce the divergence this PR fixes. Nor is the call a scan:
`is_reduced_by` has read per-currency sign counts since #2062, so both
calls are hash lookups.

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