Skip to content

perf(core): pick the inventory backing by use, not one for both - #2056

Merged
robcohen merged 3 commits into
mainfrom
perf/inventory-vec
Aug 15, 2026
Merged

robcohen merged 3 commits into
mainfrom
perf/inventory-vec

Conversation

@robcohen

Copy link
Copy Markdown
Member

−23% instructions on a lot-heavy ledger, with the #1086 memory guarantee held at 31.2 MB against main's 31.0 MB.

Depends on #2055 for the investment workload this is measured against.

Two uses, opposite requirements

Inventory stored positions in imbl::Vector for every use. That was chosen for #1086: BQL's JOURNAL emits one row per posting, each holding a clone of the running balance, so a contiguous copy per row costs O(rows × lots). Structural sharing makes the clone O(1). Measured on 2000 lots × 2000 rows: 31 MB with sharing, 395 MB without — the constraint is real and current.

But booking wants the opposite. It mutates constantly, snapshots only on the conditional overflow-rollback path, and pays RRB costs on every access — reduce_ordered filters, sorts, then indexes matched lots, and indexed access into an RRB tree is O(log M), not O(1). On the investment workload imbl::Vector's iterator alone was ~13% of all instructions, across ~1500 reductions averaging 72 positions.

So the backing now follows the use: PositionStore::Owned(Vec) by default, Shared(imbl::Vector) for the two BQL running balances that are cloned per row. Both are Inventory; the choice is made at construction via Inventory::new_shared.

It subsumes a workaround

reduce opened with an unconditional deep copy:

self.positions = self.positions.iter().cloned().collect();

That existed because mutating a structurally-shared imbl::Vector in place drives imbl-sized-chunks' copy-on-write into a use-after-free of the interned Arc<str> inside Position. It discarded the O(1)-clone benefit the type was chosen for, on every reduction.

It's now positions.make_owned() — the same O(M) materialization, but landing in a Vec, so every subsequent access in the reduction is contiguous instead of an RRB walk, and there is still nothing shared to corrupt.

An approach that doesn't work, recorded

My first attempt took positions out into a local Vec and threaded it through the reduction. That is unsound here: add, rebuild_index and units are called from inside the reduction methods and read self.positions, so they would have operated on an emptied field without failing loudly. Switching the backing instead leaves every helper working on whichever representation is present.

Measured — all four workloads, 2000 transactions

workload main hybrid
investment 278,077,331 214,080,673 −23.01%
simple 119,011,447 118,185,519 −0.69%
tagged 185,400,257 184,621,209 −0.42%
multicurrency 174,747,950 173,902,694 −0.48%

The three non-lot workloads barely move — the expected shape, since they reduce almost nothing. On the old single workload this change would have looked like noise.

Verification

Instructions aren't wall-clock; a hyperfine confirmation on the investment shape is worth doing before claiming a user-visible speedup.

🤖 Generated with Claude Code

https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG

@robcohen
robcohen requested a review from a team as a code owner August 15, 2026 01:40
Copilot AI lite review requested due to automatic review settings August 15, 2026 01:40
@codecov

codecov Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.50000% with 15 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/mod.rs 86.84% 15 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 38ms ± 2ms 24.4 MB
beancount 732.3ms ± 3.5ms 50.7 MB
Comparison 19.3x faster 2.1x less

vs main branch (2026-08-14)

Metric main this PR Change
Time 37.3ms 38ms +1.9% ✅
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

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::Inventory for two distinct usage patterns: booking (mutation-heavy) vs. BQL running-balance snapshots (clone-heavy). It introduces a hybrid internal backing so booking defaults to contiguous storage while query running balances opt into structural sharing to avoid the #1086 row-per-snapshot blow-up.

Changes:

  • Added an internal PositionStore to let Inventory store positions as either Owned(Vec<Position>) or Shared(imbl::Vector<Position>).
  • Introduced Inventory::new_shared() and switched SELECT/JOURNAL running-balance accumulators in rustledger-query to use it.
  • Updated booking mutation paths to use the new push abstraction and to materialize shared storage into owned storage on reduction (make_owned()).

Reviewed changes

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

File Description
crates/rustledger-query/src/executor/mod.rs Uses Inventory::new_shared() for the JOURNAL cumulative balance accumulator to keep per-row balance snapshots structurally shared.
crates/rustledger-query/src/executor/execution.rs Uses Inventory::new_shared() for SELECT/JOURNAL running balances that are cloned once per output row.
crates/rustledger-core/src/inventory/mod.rs Implements PositionStore, updates Inventory internals and APIs to support owned vs shared backings, and adds Inventory::new_shared().
crates/rustledger-core/src/inventory/booking.rs Updates booking paths to use the new PositionStore push API (and related calls) while relying on make_owned() before mutation-heavy reductions.

💡 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

robcohen added a commit that referenced this pull request Aug 15, 2026
Four Copilot findings on #2056, all valid. The first was worth 2.5
percentage points.

`PositionStore::iter` returned `Box<dyn Iterator>`, so every call heap-
allocated and dispatched dynamically — on `units`, `merge`, `at_cost`,
equality and every reduction pass, which are exactly the paths this change
exists to make cheaper. Replaced with a stack-allocated enum iterator:

    investment  -23.01%  ->  -25.52%

The other three were documentation and coverage:

`positions_mut`'s rustdoc still described returning `&mut imbl::Vector` and
discussed structural-sharing mutation costs; it returns `&mut Vec` after
forcing the contiguous backing. It now says that, including what the
conversion costs when the inventory was shared.

The field's rustdoc still read as though every `Inventory` is persistent.
It now names the dual backing first and keeps the persistent-vector notes as
what they are — the reason the SHARED variant still exists.

`new_shared` had no test. The backing is a private enum, so nothing outside
the module can observe it: `new_shared` could have quietly returned the
contiguous backing and the only symptom would have been BQL's JOURNAL memory
going from 31 MB back to 395 MB on a large ledger. Now pinned, including
that `add` KEEPS the shared backing (converting there would restore the
blow-up), that `reduce` deliberately converts, and that a serde round-trip
lands in `Owned`. Mutation-checked: making `new_shared` return `Owned` fails
it.

Re-verified: full workspace tests, clippy 1.97, fmt, and the #1086 budget at
31.3 MB against main's 31.0 MB.
-23% instructions on a lot-heavy ledger, with the #1086 memory guarantee
held at 31.2 MB against main's 31.0 MB.

`Inventory` stored positions in `imbl::Vector` for every use. That was
chosen for #1086: BQL's JOURNAL emits one row per posting, each holding a
CLONE of the running balance, so a contiguous copy per row costs
O(rows x lots) memory. Structural sharing makes the clone O(1) and the chain
O(base + deltas). Measured on 2000 lots x 2000 rows: 31 MB with sharing,
395 MB without.

But booking wants the opposite. It mutates constantly and snapshots only on
the conditional overflow-rollback path, and it pays RRB costs on every
access: `reduce_ordered` filters, sorts, then INDEXES the matched lots, and
indexed access into an RRB tree is O(log M) rather than O(1). On the new
`investment` workload `imbl::Vector`'s iterator alone was ~13% of all
instructions, over ~1500 reductions at an average of 72 positions.

So the backing now follows the use. `PositionStore` is `Owned(Vec)` by
default — booking's representation — and `Shared(imbl::Vector)` for the two
BQL running balances that are cloned per row. Both are `Inventory`; the
choice is made at construction via `Inventory::new_shared`.

This also subsumes a workaround. `reduce` opened with an unconditional
`self.positions = self.positions.iter().cloned().collect()`, there because
mutating a structurally-SHARED `imbl::Vector` in place drives
`imbl-sized-chunks`' copy-on-write into a use-after-free of the interned
`Arc<str>` inside `Position`. That deep copy discarded the O(1)-clone
benefit the type was chosen for, on every reduction. It is now
`positions.make_owned()`: the same O(M) materialization, but it lands in a
`Vec`, so every subsequent access in the reduction is contiguous rather than
an RRB walk, and there is still nothing shared to corrupt.

An earlier attempt at this took the positions out into a local `Vec` and
threaded it through the reduction. That is unsound here: `add`,
`rebuild_index` and `units` are called from inside the reduction methods and
read `self.positions`, so they would have operated on an emptied field
without failing loudly. Switching the BACKING instead leaves every helper
working on whichever representation is present.

Measured, all four workloads at 2000 transactions:

    investment     278,077,331 -> 214,080,673   -23.01%
    simple         119,011,447 -> 118,185,519    -0.69%
    tagged         185,400,257 -> 184,621,209    -0.42%
    multicurrency  174,747,950 -> 173,902,694    -0.48%

The three non-lot workloads barely move, which is the expected shape: they
reduce almost nothing.

Serde is unchanged — `PositionStore` serializes as a plain sequence for both
backings, and a round-trip lands in `Owned`.

Full workspace tests pass; BQL compat stays at 0 effective mismatches.
Four Copilot findings on #2056, all valid. The first was worth 2.5
percentage points.

`PositionStore::iter` returned `Box<dyn Iterator>`, so every call heap-
allocated and dispatched dynamically — on `units`, `merge`, `at_cost`,
equality and every reduction pass, which are exactly the paths this change
exists to make cheaper. Replaced with a stack-allocated enum iterator:

    investment  -23.01%  ->  -25.52%

The other three were documentation and coverage:

`positions_mut`'s rustdoc still described returning `&mut imbl::Vector` and
discussed structural-sharing mutation costs; it returns `&mut Vec` after
forcing the contiguous backing. It now says that, including what the
conversion costs when the inventory was shared.

The field's rustdoc still read as though every `Inventory` is persistent.
It now names the dual backing first and keeps the persistent-vector notes as
what they are — the reason the SHARED variant still exists.

`new_shared` had no test. The backing is a private enum, so nothing outside
the module can observe it: `new_shared` could have quietly returned the
contiguous backing and the only symptom would have been BQL's JOURNAL memory
going from 31 MB back to 395 MB on a large ledger. Now pinned, including
that `add` KEEPS the shared backing (converting there would restore the
blow-up), that `reduce` deliberately converts, and that a serde round-trip
lands in `Owned`. Mutation-checked: making `new_shared` return `Owned` fails
it.

Re-verified: full workspace tests, clippy 1.97, fmt, and the #1086 budget at
31.3 MB against main's 31.0 MB.
@robcohen
robcohen force-pushed the perf/inventory-vec branch from ee119ac to b25532c Compare August 15, 2026 02:12
@robcohen
robcohen enabled auto-merge (squash) August 15, 2026 02:12
@robcohen

Copy link
Copy Markdown
Member Author

Wall-clock confirmation

The PR claimed −25.52% in instructions; that isn't the same as a user-visible speedup, so here it is measured directly. rledger check on a 10,000-transaction investment ledger (33,263 lines), hyperfine, 3 warmup + 12 runs, --no-cache:

mean range
main 487.9 ms ± 9.1 474.0 – 506.5
this branch 415.6 ms ± 9.9 391.3 – 429.6

1.17 ± 0.04× faster — ranges don't overlap, so it's well outside the harness's noise band.

The gap between −25.5% instructions and −14.8% elapsed is the expected shape: instructions aren't cycles, and parsing still dominates wall-clock on this workload even after the inventory work.

Both binaries were rebuilt from their current HEADs for this comparison. Worth stating because main's release binary was stale by four merges when I started, and comparing against a stale binary has produced a wrong perf conclusion twice in this session already.

CI's Documentation job caught this: `positions_mut` is public and its
rewritten doc linked `[PositionStore::Owned]` and `[PositionStore::Shared]`,
but that enum is private. `cargo doc -D warnings` rejects a public doc
linking a private item.

Says the same thing in prose, pointing at `Inventory::new_shared` — which IS
public — for the shared case, and notes why the link is absent so the next
person does not helpfully re-add it.

My own fault for missing it: I ran tests, clippy and fmt on the commit that
introduced those links, and dropped `cargo doc` from that particular gate
run. It is the one check that catches rustdoc errors, and the repo has been
bitten by exactly this before.
@robcohen
robcohen merged commit 33e8837 into main Aug 15, 2026
67 of 69 checks passed
@robcohen
robcohen deleted the perf/inventory-vec branch August 15, 2026 03:08
robcohen added a commit that referenced this pull request Aug 15, 2026
… parse (#2057)

* perf(parser): compute the formatter alignment on demand, not on every parse

7.6%-12.4% fewer instructions depending on workload, by not doing work most
callers never read.

`parse_via_cst_inner` computed `compute_alignment` eagerly and stored it in
`ParseResult.alignment`. That walk goes through the RED ast accessors
(`Posting::flag`, `Amount::is_arithmetic`, ...), and rowan allocates a
`Box<NodeData>` per red node with no recycling. So every `rledger check`,
every LSP diagnostic pass and every `load` paid for a full formatter pass
whether or not it ever formatted anything.

It is not a small tax. dhat on the `simple` workload:

    50,325 blocks  RED Box<NodeData>    34.2% of all allocations
    40,053 blocks  GREEN node

The derived view cost more allocations than the green tree it derives from.

Only the formatter reads the value — `format_source_with_parsed`, and
through it the LSP's formatting, range-formatting and inlay hints, plus
`doctor roundtrip`. The field is now a `OnceLock` behind
`ParseResult::alignment()`, so those callers pay for it and nobody else
does. Their caching contract is unchanged: first call computes, later calls
are free, and the value still equals a fresh `compute_alignment` on the same
tree, which is what `parse_result_alignment_cache::*` pins.

`OnceLock`, not `OnceCell`: `ParseResult` is shared as `Arc<ParseResult>`
across the LSP's threads, and there is a compile-time assertion in this file
that it stays `Send + Sync`.

Measured, 2000 transactions per shape:

    simple         118,186,605 -> 103,592,947   -12.35%
    multicurrency  173,907,155 -> 158,761,387    -8.71%
    tagged         184,579,083 -> 169,001,365    -8.44%
    investment     207,113,683 -> 191,351,889    -7.61%

Wall clock, `rledger check --no-cache`, 10k transactions, hyperfine 12 runs:

    simple      132.5 ms -> 121.2 ms   1.09x
    investment  414.7 ms -> 395.4 ms   1.05x

Both binaries rebuilt from their current HEADs for that comparison. Worth
saying because the first run of it reported 1.23x against a main binary that
predated #2056 by forty minutes — the win looked twice as large as it is.

New test pins the laziness itself. Nothing else can: the value is identical
either way, so a reintroduced eager computation would be invisible to every
other test while costing 7.6%-12.4% of the program. Mutation-checked by
restoring the eager call.

How this was found is worth recording, because three plausible explanations
came first and all were wrong. The guarded `extract_*` passes were not it —
`simple` triggers none of them and still allocates 50k red nodes. Top-level
red iteration was not it — the green fast path succeeds 1999/2000.
`fixup_directive_spans` was not it — its `find` short-circuits at the first
non-trivia token. Only the dhat stacks named the real caller, and an
ablation confirmed the size before any code was written.

* fix(parser): address review on the lazy alignment cache

Three Copilot findings on #2057, all real:

1. The fuzz target still read `green.alignment` as a field, so
   `fuzz_green_eq_red` failed to compile. Fuzz targets live outside the
   workspace with their own manifest, so `cargo build --workspace
   --all-targets` never touched them — only the Fuzz CI job caught it.
   Now calls `alignment()`, which is what the target wants anyway: it
   must compare the VALUE both paths produce, so forcing it on both is
   the point.

2. `alignment()` fell back to `PostingAlignment::default()` when the
   root would not cast to `SourceFile`. That formats the whole file to
   the wrong columns while looking like it worked. Now `expect`s, as
   `format_node_grouped` already does on the same breach, with the
   matching `#[allow(clippy::expect_used)]` and a `# Panics` section.

3. The field's rustdoc still described the eager cache and a "refresh
   the cache" flow that lazy computation makes moot. Rewritten to the
   actual contract, plus the two stale `parse_result.alignment` prose
   references in cst/format.rs.

The fuzz lockfile also picks up rowan 0.16.1 -> 0.17.0; it had drifted
behind the workspace lock, which is already on 0.17.0.

* docs(parser): retire the dangling producer-only-invariant references

Self-review of the lazy-alignment change. Three call sites pointed at a
"producer-only invariant" heading in the `ParseResult::alignment`
rustdoc that the lazy rewrite removed. What they actually describe is
`format_source_with_parsed`'s own pairing contract — the caller must
pass the `source` the `parse_result` came from — so it is now named
there instead of by dangling reference.

Also: the `parse_result_alignment_cache` failure message still blamed
"parse_via_cst forgot to call compute_alignment" and "refreshing the
cache in the converter", neither of which can happen now; it would have
sent the next reader to the wrong file. Retargeted at the two things
that CAN diverge: the accessor's `GroupingStyle` and compute_alignment
itself. Plus a missing blank doc line before `# Panics`.
robcohen added a commit that referenced this pull request Aug 15, 2026
#2061)

* docs(core): correct the O(1)-clone claim in Inventory::reduce

The `make_owned` comment said `self.positions` is "often structurally
shared — the booking engine clones an account's inventory into a working
copy via imbl's O(1) clone".

That has not been true since #2056 made the store a hybrid.
`PositionStore::default()` is `Owned(Vec)`, so `BookingEngine`'s
inventories are owned and the per-transaction working copy it takes in
`book()` is a DEEP O(lots) copy. The structurally-shared case is BQL's
snapshots via `Inventory::new_shared`.

This is not a cosmetic correction. Profiling found that copy to be the
dominant superlinear term left in the pipeline — `Position::clone` grows
104x for 10x the input on the `investment` shape, chain
`Position::clone <- Inventory::clone <- BookingEngine::book`/`::apply` —
and a comment asserting the clone is O(1) is a good reason nobody looked
at it. The rest of the comment, on why in-place mutation of a shared
`imbl::Vector` corrupts the interned `Arc<str>`, is untouched and still
correct.

* perf(core): compute reductions from &self, so previewing stops copying

`Inventory::try_reduce` was `self.clone().reduce(..)` — it deep-copied every
lot in an account to preview a reduction that touches one or two of them.
`BookingEngine::book` then took its own working copy of each touched
account's inventory, per transaction, for the same reason. Both are O(lots),
and lots accumulate, so booking grew superlinearly with ledger size.

Each affected method is now split into a `plan_*` half that computes from
`&self` and a commit half that applies the result:

    reduce_from_lot  = plan_from_lot  + commit_from_lot
    reduce_ordered   = plan_ordered   + commit_updates
    reduce_strict    = plan_strict    + commit_plan

The selection logic lives in the `plan_*` half and ONLY there — the mutating
path calls it too. That is the point: `try_reduce` duplicating `reduce`'s
selection is precisely the drift `try_reduce_equivalence` was written for,
after it had already happened once. STRICT_WITH_SIZE, HIFO, AVERAGE, NONE and
the `{*}` merge operator still preview by cloning; correct, just O(lots), and
mechanical to convert when something needs it.

`book` now clones an inventory only for an account with MORE THAN ONE
reducing posting in the transaction — the case where a second posting must
see what the first took. With a single posting nothing reads the mutation
back, so it previews against the live inventory and copies nothing.

Cachegrind, both sides rebuilt at HEAD, base a218920:

    investment 2k    182,434,646  -> 161,811,594   -11.30%
    investment 20k 7,651,077,174  -> 5,784,989,413 -24.39%
    simple 20k     2,251,393,629  -> 2,251,388,486   0.00%

`simple` is unchanged because it books no cost specs, which is the shape of
the change: it removes work proportional to accumulated lots.

Mechanism confirmed rather than inferred — `Position::clone` went from 1.30G
instructions to 0.32G (-76%), `drop_glue::<Position>` from 5.3% to 1.8%.

Scaling for 10x input improves 41.9x -> 35.8x. Still superlinear: the
remaining terms are `is_reduced_by`, an O(lots) scan per posting that is now
the largest at 9.0%, and the O(lots) `rebuild_index` on the commit path.
Neither is touched here.

`two_reducing_postings_on_one_account_see_each_other` pins the case the
working copy still exists for: 10 units held, 6 and 6 sold in one
transaction must fail on insufficient units, and 6 and 4 must succeed.
Mutation-checked — removing the working copy entirely fails that test and
the existing `test_multi_posting_crosses_lot_boundary`.

* docs(core): the booking engine no longer takes the per-transaction copy

Brings the comment corrected two commits ago up to date with the refactor
that followed it in this PR: `book` previews through `try_reduce` now and
copies only for an account with more than one reducing posting.

* fix(core): a failed multi-lot reduction no longer drains lots

Found while reviewing the plan/commit split, and fixed by it.

`reduce_ordered` states the rule itself — "a failed reduction must leave the
inventory untouched" — and enforced it for the sufficiency check, which runs
before the loop. The cost-basis OVERFLOW check did not get the same
treatment: it lived inside the mutation loop, so a reduction that overflowed
on the Nth lot returned `Err` with lots 1..N-1 already drained. The validator
reduces against live `LedgerState` inventories, so that partial drain
corrupts every later balance assertion on the account.

Computing the whole plan before committing any of it makes the rule hold for
both checks by construction, so this needed no separate fix — only a test.

Verified as a real defect rather than a hypothetical: the new test was
transplanted onto main (9211cff) and fails there, with the first of two
lots at 0 units while the reduction reports `Err(Overflow)`.

Also addresses review feedback on the phrasing of the corrected `make_owned`
comment, and notes why the `self.inventories[..]` index in `book` cannot
panic.
robcohen added a commit that referenced this pull request Aug 16, 2026
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.
robcohen added a commit that referenced this pull request Aug 16, 2026
* perf(core): tombstone removed lots and index them by cost

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.

* fix(core): state the index asymmetry correctly and test modify_positions

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.

* fix(core): keep the cost index off shared snapshots

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.

* test(core): round-trip an inventory that holds a tombstone

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 added a commit that referenced this pull request Aug 17, 2026
* perf(booking): undo what changed instead of copying what exists

`apply` snapshotted every touched account with `Inventory::clone` before
mutating, so a failed transaction could be rolled back. The comment
justifying it said the positions were an `imbl::Vector` whose clone is O(1).
That stopped being true at #2056, when booking's backing became owned — the
guard silently turned into an O(lots) copy per touched account per
transaction and grew into the largest superlinear term left in the pipeline.

A reduction touches one or two lots. `apply` now records an undo log of the
slots it actually writes.

Cachegrind, both sides rebuilt at HEAD, base f3ac855:

    investment 2k    136,693,394 -> 122,452,140   -10.42%
    investment 20k 2,650,674,155 -> 1,209,849,439 -54.36%
    simple 20k       860,854,747 ->   863,447,163  +0.30%
    tagged 10k       684,347,183 ->   686,524,070  +0.32%

Scaling for 10x input: 19.4x -> 9.9x. `investment` is LINEAR — an ablation
that removes the snapshot entirely measures 9.9x and -56.2%, so this captures
96% of what was there and the curve is now flat, not merely flatter.

RECORDING LIVES IN THE BACKING, not at the eleven call sites that mutate
positions. Those all funnel through `PositionStore`'s primitives and the
field is private, so hooking `IndexMut`, `push_slot` and `set_dead` is
complete BY CONSTRUCTION; hooking call sites would be complete only until
someone adds a twelfth. A debug-only witness copy taken at `begin_undo` is
compared against the restored inventory, so a future mutation path that
bypasses the log fails loudly in tests rather than corrupting a ledger.

Compaction moved out of `reduce` into `Inventory::compact_if_sparse`, called
by `apply` on commit: compaction renumbers slots, and the undo log refers to
them, so it cannot run mid-transaction. That is also the only moment no
rollback can still be required.

The +0.3% on the cost-spec-free shapes is real, not noise. It is the
`undo_open` field and the per-posting commit pass, which is skipped entirely
when nothing was recorded — only reductions create tombstones and any
reduction makes `rollback_needed` true, so `!recording` means there is
nothing to compact or commit.

Four mutations were run and two SURVIVED, exposing untested log paths that
are now covered:

  - a lot fully DRAINED before the failure. On the common paths the lot is
    zeroed through `IndexMut` first, which already records it, so removing
    the capture in `set_dead` changes nothing — except on `{*}` merge, which
    drops matched lots through `retain_slots` without writing them. That is
    the case that tells the two apart, and a rejected merge would otherwise
    destroy every lot it consumed.
  - a lot ADDED before the failure, which would be left behind as a phantom.

Restoring in reverse order pops created slots while they are still last;
forward order is not wrong, only wasteful, so a mutation swapping it survives
by design and the comment says so.

Also removes a `debug_assert` I added claiming tombstones cannot dominate
while a log is open. A `{*}` merge tombstones every matched lot and pushes
one, so they legitimately can, and the assertion fired on valid input.

* fix(core): compact whenever no undo log is open, not only on commit

Correctness review of my own change, and this one was a real defect.

Moving compaction out of `reduce` into `apply`'s commit path tied it to the
booking engine. The Late validator keeps its OWN inventories across
transactions and calls `Inventory::reduce` directly
(`validators/transaction.rs`), so it never reached that commit path — its
inventories would have accumulated one dead slot per closed lot for the life
of the ledger, and scanned every one of them on every later reduction. That
is precisely the unbounded growth tombstones needed compaction to prevent,
reintroduced in a second caller.

The measurement hid it: `apply`'s win dominates the profile, so the run still
showed -54% while the validator quietly degraded.

The constraint was never "compact at commit" — it is "do not renumber slots
while an undo log refers to them". So `reduce` compacts unless a log is open,
which restores the previous behavior for every caller that does not run a
transaction, and keeps the deferral for the one that does.

`tombstones_are_compacted_rather_than_accumulating` goes back to driving
compaction through `reduce` alone, with no engine and no explicit call — the
way the validator does. Mutation-checked in both directions: removing the
compaction fails it, and compacting unconditionally (while a log is open)
fails the rollback tests.

Also asserts that `begin_undo` is only called on an owned backing. Recording
does not exist on the shared one, so a shared inventory would set
`undo_open`, capture nothing, and roll back nothing while reporting success.
Unreachable today — `BookingEngine` populates its map only through
`entry().or_default()` and takes no inventory from outside — and now asserted
so it stays unreachable.

Measurements are unchanged: investment 20k -54.34%, scaling 19.4x -> 9.9x.

* fix(booking): open exactly one undo log per account, not one per posting

Second correctness pass on this PR.

`apply` opened logs with `if !inv.undo_is_open() { inv.begin_undo(); }`. That
handles two postings on one account, but it also defeats the assertion inside
`begin_undo` that says it must not be called twice — the guard would silently
adopt a log left over from an earlier transaction and roll back to the wrong
point rather than failing loudly.

The accounts are now deduplicated first and `begin_undo` is called exactly
once each, so its assertion is load-bearing again. Verified: removing the
deduplication makes `test_multi_posting_crosses_lot_boundary` fire that
assertion, so the path is genuinely exercised rather than merely present.

Also checked and found sound, recorded here so the next reader need not
re-derive it:

  - No undo state can reach the wire. `undo_open` and `undo_witness` are
    `#[serde(skip)]`, and `Slots.undo` is unreachable because `PositionStore`
    serializes through a hand-written `collect_seq(self.iter())` rather than a
    derive.
  - Rollback restores the derived caches, `cost_index` included, because it
    ends in `rebuild_index`.
  - A slot pushed during a transaction cannot already be in the log: its index
    is the length before the push, and only rollback pops.
  - `apply_posting` mutates nothing outside `self.inventories`, so nothing
    else needs undoing.

* fix(booking): make the rollback guard independent of state it can change

Third correctness pass, and this one is a user-facing bug that predates this
PR.

`rollback_needed` decides up front whether to prepare a rollback, and
`has_reduction` asked whether each posting reduces something the account holds
AT THAT MOMENT. A transaction can falsify that itself:

    2024-01-01 * "buy then oversell"
      Assets:Stock   10 X {100.00 USD}
      Assets:Stock  -20 X {100.00 USD}

Against an empty account the answer was "no reduction", so nothing was
prepared. The second posting then failed, and `apply` hit its own "the guard
is unsound" assertion — turning an ordinary bad ledger into a panic out of
`rledger check`. Reproduced on main (f3ac855) as well as here, so this PR
neither caused nor previously fixed it; it is being fixed here because it is
the same guard this PR rewrites around.

Carrying a cost spec is what makes a posting able to reduce, and that does not
depend on inventory state, so the transaction cannot falsify it. Strictly more
conservative than the old test: every posting it used to catch carries a cost
spec too.

It is also cheaper, because it reads the posting instead of doing a map lookup
and an `is_booking_reduction` per posting. That removes the small regression
this PR had on cost-spec-free ledgers:

    simple 20k   main 860,854,747 -> 860,069,804   -0.09%   (was +0.30%)
    investment 2k             -> 122,184,256      -10.62%
    investment 20k            -> 1,206,894,976    -54.47%

`a_transaction_that_creates_and_then_oversells_a_lot_errors_rather_than_panicking`
pins the error path and that the buy is rolled back with it. Mutation-checked:
restoring the state-dependent guard fails it.

* test(booking): property-test transaction rollback under randomized failure

Fourth correctness pass. Nothing new found by reading, so this changes
technique rather than re-reading.

`booking_properties.rs` pins that a failed `Inventory::reduce` does not
mutate — one posting. `apply` is the transaction: it can apply several
postings and then fail on a later one, and must undo everything it already
did. Nothing property-tested that.

It mattered less when `apply` cloned each touched account, because restoring
a whole copy is total by construction and cannot get the restoration wrong.
With an undo log, completeness is a property of the recording hooks, and the
hand-written tests only cover interleavings someone thought of — which is
exactly how two of the four earlier mutations survived and needed dedicated
cases for a drained lot and an added one.

`a_failed_transaction_restores_the_account_exactly` generates them instead:
randomized prefixes of buys (which push a slot), sells (which write a lot in
place or drain it) and `{*}` merges (which drop every matched lot at once),
followed by a leg that cannot succeed. The account must come back byte for
byte.

Worth more than the count of cases: this ONE property catches all three
recording hooks being broken — `IndexMut`, `set_dead` and `push_slot` — where
the hand-written suite needed three separate tests and initially missed two
of them.

* perf(core): make undo recording O(1) and dedupe the commit pass

Two review findings, both real.

`Slots::record` scanned the log linearly to answer "have I captured this slot
already?". For one or two slots that beats hashing, but `{*}` merge records
every matched lot, making recording O(k^2) in the lots merged — a fresh
quadratic inside the change that removed one. An `FxHashSet<usize>` answers
it in a couple of instructions and the common case loses nothing.

`apply`'s commit pass iterated postings, so a transaction with several
postings on one account re-entered `compact_if_sparse` for it. Compaction is
O(slots) when it fires. The pass now deduplicates, as the begin_undo pass
already did.

Investigating the first turned up something worth writing down: removing the
deduplication does NOT fail any test, and that is correct rather than a gap.
Rollback restores in REVERSE order, so when a slot is captured twice the
earliest entry — the true prior value — is applied last and wins. The dedup
bounds the log's size; reverse order is what makes duplicates safe. They are
independent, and only dropping BOTH corrupts a rollback. Both comments now
say so, because the previous note called forward order "merely wasteful",
which is true only while the dedup holds.

    investment 20k  1,209,859,775   (-54.36% vs main)
    simple 20k        859,416,021   (-0.17% vs main)
robcohen added a commit that referenced this pull request Aug 18, 2026
Copilot's review: the field, its accessor, its builder and the comment in
`plan_ordered` all described `ordered_index` as holding "cost-bearing
lots", while the code indexes every position.

Worth more than a wording fix. The first version really did index only
cost-bearing lots, and that was a wrong-lot-selection bug: an empty cost
spec matches a cost-less position (`matches_cost_spec`: `(None, true)`),
so ordered selection can drain one, and omitting them chose a different
lot than the scan. Leaving the old description in place would have
documented the bug as the design — the same shape as the three stale
"O(1) clone" comments that hid quadratics through #2056.

All four sites now say every lot, and say why the cost-less ones are
there.

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
…#2085)

* perf(core): stop rebuilding and rescanning on every ordered reduction

A FIFO ledger was quadratic. 20k transactions took 9.1s, growing 93x for
10x the input; the same size on the `investment` shape takes 0.04s. Now
0.29s and linear.

Two costs, both per reduction and both proportional to lots held.

`commit_updates` tombstoned the drained lots with a `retain` over every
slot and then called `rebuild_index()`, which walks every slot again and
rehashes every key. But `updates` already names the slots that changed,
so the repair is now proportional to the lots the reduction touched —
the treatment `commit_from_lot` got in #2063, applied to the multi-lot
half. On its own this was 5.2x.

`plan_ordered` then scanned every slot, applied the cost-spec predicate
to each, sorted the survivors and summed them, to take from the front.
`ordered_index` keeps each currency's lots in (date, slot) order, so the
walk starts where the answer is and stops once the reduction is covered.
The up-front sufficiency sum went with it: that existed to guarantee a
failed reduction does not mutate, which the plan/commit split (#2061)
made structural — exhausting the walk reports the same shortfall having
visited the same lots.

The index costs +2.35% on `investment` and +0.9-1.3% on the other three
shapes, which is the honest trade for removing the growth term. It is
built on the first reduction under an ordered method and maintained from
`add` only once built, so a ledger whose reductions resolve through
`cost_index` never pays for it.

Two things the differential test caught, neither of which the existing
480 core tests noticed:

- The index must hold COST-LESS positions too. An empty cost spec
  matches one (`matches_cost_spec`: `(None, true)`), so ordered
  selection can drain one, and omitting them chose a different lot than
  the scan. `commit_from_lot` documents the same subtlety.
- The first version of that test was vacuous: it called `plan_ordered`
  directly, which never builds the index, so it compared the scan
  against itself and passed against a deliberately reversed tiebreak.

Adds a `fifo` shape to the workload generator. The existing four reach
ordered selection twice in 2k transactions between them, which is why
this survived the six superlinear terms fixed in #2059-#2067.

Fixes #2083

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

* perf(core): box the ordered index and keep it unbuilt until needed

Review of my own diff, plus a correction to the numbers in the PR.

`rebuild_index` repopulated `ordered_index` unconditionally, and both
compaction and rollback call it — so an inventory acquired the index (and
its maintenance) whether or not ordered selection was ever used, which
defeated building it on demand. It now preserves whether the index was
built rather than deciding.

`cost_index_remove` cloned the currency and probed the index on every
drained lot, including for inventories that never built one. The map is
also `Option<Box<..>>` now: an inventory that never needs it carries a
pointer instead of three words plus an allocation, on a type created per
account and cloned per BQL output row.

The regressions reported in the PR description were mostly not real. The
two binaries had been built with different toolchains — one inside `nix
develop` (1.96.0) and one outside (1.97.0) — which `cg_annotate --diff`
exposed as equal-and-opposite entries for the same functions under
`drop_in_place` versus `drop_glue` naming. Rebuilt identically:

    simple         -0.03%
    tagged         +0.03%
    multicurrency  +0.04%
    investment     +2.02%

and the investment figure is codegen noise too: forcing the scan path in
ONE binary, via an environment variable, moves it 45k instructions out of
1.36 billion — 0.003%. That shape books under STRICT, so it resolves
through `cost_index` and never builds an ordered index at all.

So: no measurable cost to ledgers that do not use ordered selection, and
the ones that do are the ones getting 32x.

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

* docs(core): say that the ordered index holds cost-less lots too

Copilot's review: the field, its accessor, its builder and the comment in
`plan_ordered` all described `ordered_index` as holding "cost-bearing
lots", while the code indexes every position.

Worth more than a wording fix. The first version really did index only
cost-bearing lots, and that was a wrong-lot-selection bug: an empty cost
spec matches a cost-less position (`matches_cost_spec`: `(None, true)`),
so ordered selection can drain one, and omitting them chose a different
lot than the scan. Leaving the old description in place would have
documented the bug as the design — the same shape as the three stale
"O(1) clone" comments that hid quadratics through #2056.

All four sites now say every lot, and say why the cost-less ones are
there.

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

* fix(core): keep insufficiency ahead of overflow, and stop indexing for HIFO

Two findings from reviewing my own diff for architectural correctness.

Removing `plan_ordered`'s up-front sufficiency sum changed which error a
doubly-broken reduction reports. Sufficiency used to be settled before
any basis arithmetic ran, so a reduction that was both short of units and
unrepresentable reported the shortfall — the half the ledger author can
act on. Walking lazily reached the `checked_mul` first and reported the
overflow instead. Nothing asked for that change and no test covered it:
the whole suite passed either way.

The overflow is now recorded and raised only once the reduction is known
to be satisfiable, which restores the old precedence exactly:
`NoMatchingLot`, then `InsufficientUnits`, then `Overflow`.
`insufficient_units_are_reported_even_when_the_basis_would_overflow`
pins it, and fails if the error returns eagerly again.

`reduce_hifo` does not use `plan_ordered` — it sorts by cost and carries
its own scan — so gating the index build on `Hifo` built a map nothing
reads. FIFO and LIFO only now. Worth noting that HIFO's scan is the same
shape this PR fixes and is still quadratic; it needs a cost-ordered index
rather than this date-ordered one.

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

* fix(core): stop a multi-lot reduction sweeping unrelated empty lots

Third architectural pass, on the half I had reviewed least.

`commit_updates` used to finish with `retain(|p| !p.is_empty())` over the
WHOLE inventory, so any reduction that happened to cross two lots also
deleted every unrelated zero-unit position as a side effect. Those are
not scrap: `Inventory::len` counts them and `currency_accounts` branches
on `len() == 1` to match Python, so whether one survived depended on
whether some other reduction was multi-lot. The incremental repair
removes what it drained and nothing else.

`a_multi_lot_reduction_leaves_unrelated_empty_lots_alone` pins it and
fails on main. Getting there took two attempts: the first fixture added
a zero-unit position directly, which `add` drops outright, so the test
passed on both sides while proving nothing. A cost-less lot NETTING to
zero is the only way one exists — which is the case `Inventory::len`'s
contract is actually about.

Also asserts the invariant the repair introduced. Adjusting one
currency's running total is only correct because every producer of
`ReductionPlan::Updates` filters on `units.currency` first; the old
rebuild recomputed every currency and so could not have noticed that
being violated. Checked before the loop, since afterwards the drained
lots are tombstones and indexing one panics.

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