Skip to content

perf(core): tombstone removed lots and index them by cost - #2066

Merged
robcohen merged 4 commits into
mainfrom
perf/position-tombstones
Aug 16, 2026
Merged

robcohen merged 4 commits into
mainfrom
perf/position-tombstones

Conversation

@robcohen

Copy link
Copy Markdown
Member

Lot matching was the last superlinear term: every reduction compared its cost spec against every lot — 25.1% of a 20,000-transaction investment run, growing 111× for 10× the input. Answering that from an index needs lot indices that survive removals, which needs removal to stop shifting.

PositionStore::Owned is now sparse — Vec<Option<Position>> plus a live count — so removing a lot leaves a tombstone and renumbers nothing. On top of that, cost_index groups cost-bearing lots by (units currency, per-unit cost, cost currency), and plan_strict takes its candidates from there when the spec names an explicit per-unit cost.

Measured

Cachegrind, both sides rebuilt at HEAD, base 9ef20d85ed:

workload main branch delta
investment 2k 137,583,909 136,706,645 −0.64%
investment 20k 3,152,823,895 2,650,810,136 −15.92%
simple 20k 859,095,775 860,837,918 +0.20%

Scaling for 10× input improves 22.9× → 19.4× — the first time this curve has moved rather than just the constant on it.

The two halves only work together, and that is measured rather than assumed. With tombstones alone the same workload was +14.47% and the curve got worse (25.4×), because scans walk up to twice the slots for nothing. The index is what pays for them. I built it in that order and measured the intermediate state deliberately.

Design decisions worth reviewing

The tombstone is an explicit None, not a zero-unit position. A zero-unit lot is live and visible — cost-less lots merge through zero — and Inventory::len is documented as counting them, with currency_accounts branching on inv.len() == 1 to match Python. Encoding one as the other would have changed that plugin, Serialize, the FFI and wasm converters, the account validator and report balances.

Compaction runs at the top of reduce — the one point where no slot index is held — once tombstones outnumber live lots, so slots stay within 2× the real count and a long-lived account cannot degrade toward "every lot it ever held". Slots carries its live count because len, is_empty and that trigger all run per reduction and must not scan.

Candidate lookup uses get, not indexing: a stale entry names a tombstone, and indexing one panics. With get it is a wasted candidate the predicate discards. Both arms apply the same predicate, so the index only narrows what is examined — it never decides a match.

Breaks and behavior changes

  • positions_mut is gone. It handed out &mut Vec<Position>, which the sparse backing cannot produce, and writing through it could desync the live count. modify_positions takes a closure, hands it a dense vector with tombstones already dropped, and rebuilds every derived cache afterwards — which also fixes the stale-cache footgun its own docs warned about. Pre-1.0 break; no in-tree callers.
  • commit_from_lot no longer shifts simple_index. Nothing moves now, so shifting would renumber entries that did not — caught by removing_a_lot_repairs_the_index_of_a_later_cost_less_lot, which was written for the opposite mechanism and now pins this one.
  • Three reduce_merge tests asserted positions[0]; the merged lot is appended after the tombstoned originals, so they now read through the iterator, which is what every consumer sees.

Verification

Six mutations, all caught: no compaction; removal shifting again; the index returning no candidates; a drained lot left indexed; add not indexing; the rebuild skipping the index.

The drained-lot case needed a test asserting the index directly — the tolerant lookup means no behavioral test can see the difference, and I only found the gap because the mutation survived.

New tests: a_removal_does_not_renumber_the_lots_after_it (the property the whole design exists to provide), tombstones_are_compacted_rather_than_accumulating, draining_a_lot_removes_it_from_the_cost_index.

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

Lot matching was the last superlinear term: every reduction compared its
cost spec against every lot, 25.1% of a 20,000-transaction `investment` run
and growing 111x for 10x the input. Answering that from an index needs lot
indices that survive removals, which needs removal to stop shifting.

`PositionStore::Owned` is now sparse — `Vec<Option<Position>>` plus a live
count — so removing a lot leaves a tombstone and renumbers nothing. On top
of that, `cost_index` groups cost-bearing lots by (units currency, per-unit
cost, cost currency), and `plan_strict` takes its candidates from there when
the spec names an explicit per-unit cost.

Cachegrind, both sides rebuilt at HEAD, base 9ef20d8:

    investment 2k    137,583,909 -> 136,706,645    -0.64%
    investment 20k 3,152,823,895 -> 2,650,810,136 -15.92%
    simple 20k       859,095,775 ->   860,837,918  +0.20%

Scaling for 10x input improves 22.9x -> 19.4x — the first time this curve
has moved rather than just the constant on it.

THE TWO HALVES ONLY WORK TOGETHER, which is measured, not assumed: with
tombstones alone the same workload was +14.47% and the curve got WORSE
(25.4x), because scans walk up to twice the slots for nothing. The index is
what pays for them.

The tombstone is an explicit `None`, not a zero-unit position. A zero-unit
lot is live and visible — cost-less lots merge through zero — and
`Inventory::len` is documented as counting them, with `currency_accounts`
branching on `inv.len() == 1` to match Python. Encoding one as the other
would have changed that plugin, `Serialize`, the FFI and wasm converters,
the account validator and `report balances`.

Compaction runs at the top of `reduce`, the one point where no slot index is
held, once tombstones outnumber live lots — so slots stay within 2x the real
count and a long-lived account cannot degrade toward "every lot it ever
held". `Slots` carries its live count because `len`, `is_empty` and that
trigger all run per reduction and must not scan.

Two consequences worth naming:

  - `positions_mut` is gone. It handed out `&mut Vec<Position>`, which the
    sparse backing cannot produce, and writing through it could desync the
    live count. `modify_positions` takes a closure, hands it a dense vector
    with tombstones already dropped, and rebuilds every derived cache after
    — which also fixes the stale-cache footgun its own docs warned about.
    Pre-1.0 break; no in-tree callers.
  - `commit_from_lot` no longer shifts `simple_index`. Nothing moves now, so
    shifting would renumber entries that did not — caught by
    `removing_a_lot_repairs_the_index_of_a_later_cost_less_lot`, which was
    written for the opposite mechanism and now pins this one.

Candidate lookup uses `get`, not indexing: a stale entry names a tombstone,
and indexing one panics. With `get` it is a wasted candidate the predicate
discards. Both arms of the lookup apply the SAME predicate, so the index
only narrows what is examined and never decides a match.

Mutation-checked, all caught: no compaction; removal shifting again; the
index returning no candidates; a drained lot left indexed; `add` not
indexing; the rebuild skipping the index. The drained-lot case needed a test
asserting the index directly — the tolerant lookup means no behavioral test
can see it.
@robcohen
robcohen requested a review from a team as a code owner August 16, 2026 15:41
Copilot AI lite review requested due to automatic review settings August 16, 2026 15:41
@github-actions

github-actions Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 28.7ms ± 0.6ms 24.2 MB
beancount 590ms ± 2.3ms 50.7 MB
Comparison 20.6x faster 2.1x less

vs main branch (2026-08-16)

Metric main this PR Change
Time 35.8ms 28.7ms -19.8% 🟢
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 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.72422% with 22 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/mod.rs 94.38% 22 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

This PR improves rustledger-core inventory reduction performance by making lot storage removal-stable (tombstones) and introducing a cost-keyed candidate index used by STRICT reductions that specify an explicit per-unit cost.

Changes:

  • Replace contiguous Vec<Position> storage with a sparse slot vector (Vec<Option<Position>> + live count) to keep slot indices stable across removals and enable indexing.
  • Add and maintain a cost_index keyed by (units currency, per-unit cost, cost currency) to narrow STRICT lot-matching candidates when a spec names a per-unit cost.
  • Remove positions_mut and replace it with modify_positions that rebuilds all derived caches after mutation.

Reviewed changes

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

File Description
crates/rustledger-core/src/inventory/mod.rs Introduces sparse slot-backed lot storage, compaction, cost_index, and a safer modify_positions API that rebuilds caches.
crates/rustledger-core/src/inventory/booking.rs Updates STRICT matching to use indexed candidates when possible and adapts single-lot commit behavior to tombstone-based removals.
Suppressed comments (1)

crates/rustledger-core/src/inventory/booking.rs:1036

  • This comment still describes the pre-tombstone behavior (“removing shifts every later position down one”). PositionStore::remove now leaves a tombstone and does not renumber slots, so this is misleading for future maintenance.
            // Removing shifts every later position down one, so the stored
            // indices past `idx` are now off by one. Patch the MAP rather than
            // rescanning the positions to rebuild it.
            //

💡 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

Review catches on #2066, and the first is a defect in my own comment.

I wrote that "a stale or missing entry costs correctness nothing that the
predicate would not catch". Only half of that is true, and the false half is
the dangerous one. A STALE entry is harmless — it names a tombstone or a lot
that no longer matches, and the predicate discards it. A MISSING entry is
not: the lot is never offered to the predicate at all, so a reduction that
should have matched it reports no matching lot, or books as an augmentation
and duplicates the position.

That asymmetry is the entire safety argument for taking candidates from an
index, and my wording invited a future reader to treat maintenance as
optional. Restated, with the tests that hold it named.

`Slots::set_dead` used `get_mut`, so an out-of-range slot silently did
nothing and left `live` desynced — surfacing later as a wrong compaction
trigger with nothing pointing back at the cause. It keeps the release
behavior (a ledger should not abort over an internal index slip) and gains a
`debug_assert`.

Also adds the test `modify_positions` never had. It is public API this PR
introduces, and codecov was right that it was uncovered: nothing checked
that the closure sees a DENSE vector, nor that units totals, the cost-less
merge index and the cost index all describe what the closure left. Skipping
the rebuild now fails it; a no-op control still passes, so the test
discriminates rather than firing on any edit.
Found reviewing my own change, and it undid the thing #2056 was built for.

`Inventory` derives `Clone`, and the BQL executor clones a shared running
balance ONCE PER OUTPUT ROW — the comment directly above that call says the
per-row clone is what #1086 is about, and that structural sharing is what
makes it O(1). `cost_index` holds roughly an entry per distinct cost, and
`rebuild_index` was building it for every backing, so each of those per-row
clones started copying an O(lots) map. That is the O(rows x lots) blow-up the
shared backing exists to prevent, reintroduced through a side door.

No profile here would have caught it: the workloads run no BQL, and the
index is invisible in results.

The index is for BOOKING, and only the owned backing books, so it is built
only for `Owned`. Snapshots keep an empty map and clone it for free.

That leaves an inventory that is Owned-but-unindexed possible in principle
(a snapshot converted by `make_owned`), and a MISSING entry is the unsafe
direction — the lot never reaches the predicate. So `cost_candidates` returns
`None` on an empty index and the caller scans, which is always correct. Same
shape as `units_cache`'s unbuilt-cache fallback, and for the same reason.

`a_shared_snapshot_carries_no_cost_index` pins all three parts: the snapshot
carries no index, the owned backing still builds one, and a snapshot with no
index still books correctly by scanning. Mutation-checked: indexing shared
inventories fails it, and removing the scan fallback fails it.

The win is unaffected — `investment` 20k measures 2,650,693,061 against
2,650,810,136 before the guard.
Every existing round-trip test builds its inventory with `add` alone, so
none of them contains a drained lot — the sparse backing went through serde
entirely untested. That matters twice: the wire format is pinned by
downstream snapshots, and a leaked hole would deserialize into a lot that
does not exist.

`a_drained_lot_does_not_reach_the_wire` drains a lot, checks the serialized
positions array carries only the survivor, and checks the round trip comes
back DENSE with working caches — it books the surviving lot afterwards,
which exercises the rebuilt cost index rather than just the units total.

The first version of the assertion was wrong and the test caught me rather
than the code: it searched the whole JSON string for "null", which `Cost`'s
optional `date` and `label` produce legitimately. It now inspects the
positions array itself.

Mutation-checked: a `from_live` that miscounts the live positions fails it,
and a no-op control still passes.
@robcohen
robcohen enabled auto-merge (squash) August 16, 2026 17:18
@robcohen
robcohen merged commit f3ac855 into main Aug 16, 2026
57 of 59 checks passed
@robcohen
robcohen deleted the perf/position-tombstones branch August 16, 2026 17:41
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