Repository navigation
perf(core): tombstone removed lots and index them by cost - #2066
Merged
Merged
Conversation
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.
Contributor
📊 Benchmark Results
vs main branch (2026-08-16)
What do these numbers mean?
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
There was a problem hiding this comment.
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_indexkeyed by(units currency, per-unit cost, cost currency)to narrow STRICT lot-matching candidates when a spec names a per-unit cost. - Remove
positions_mutand replace it withmodify_positionsthat 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::removenow 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.
Contributor
✅ Compatibility Test Results
What's tested
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Lot matching was the last superlinear term: every reduction compared its cost spec against every lot — 25.1% of a 20,000-transaction
investmentrun, growing 111× for 10× the input. Answering that from an index needs lot indices that survive removals, which needs removal to stop shifting.PositionStore::Ownedis now sparse —Vec<Option<Position>>plus a live count — so removing a lot leaves a tombstone and renumbers nothing. On top of that,cost_indexgroups cost-bearing lots by (units currency, per-unit cost, cost currency), andplan_stricttakes its candidates from there when the spec names an explicit per-unit cost.Measured
Cachegrind, both sides rebuilt at HEAD, base
9ef20d85ed: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 — andInventory::lenis documented as counting them, withcurrency_accountsbranching oninv.len() == 1to match Python. Encoding one as the other would have changed that plugin,Serialize, the FFI and wasm converters, the account validator andreport 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".Slotscarries its live count becauselen,is_emptyand 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. Withgetit 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_mutis gone. It handed out&mut Vec<Position>, which the sparse backing cannot produce, and writing through it could desync the live count.modify_positionstakes 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_lotno longer shiftssimple_index. Nothing moves now, so shifting would renumber entries that did not — caught byremoving_a_lot_repairs_the_index_of_a_later_cost_less_lot, which was written for the opposite mechanism and now pins this one.reduce_mergetests assertedpositions[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;
addnot 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