Skip to content

perf(core): structural sharing for Inventory positions to fix JOURNAL OOM (#1086) - #1087

Merged
robcohen merged 5 commits into
mainfrom
perf/issue-1086-im-vector-inventory
May 11, 2026
Merged

robcohen merged 5 commits into
mainfrom
perf/issue-1086-im-vector-inventory

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

  • Switches Inventory.positions from Vec<Position> to im::Vector<Position> so per-row balance snapshots in JOURNAL/SELECT cost O(1) (Arc bump on RRB-tree root) instead of O(M) per row.
  • Eliminates O(N·M) memory blowup that crashes WASM on large-inventory JOURNAL queries.
  • Comes with a measurable booking-mutation regression (O(log M) instead of O(1)) that scales with inventory size.

Closes #1086.

The problem

PR #940 added a cumulative balance column to JOURNAL. Each row stores a clone of cumulative_balance at that point in the stream. With Vec backing, that's an O(M) clone per row, so memory scales O(N·M) — quadratic when each posting opens a unique lot.

Reproduced natively on a synthetic ledger (10k transactions, each opens a unique lot):

N RSS (pre-fix) Elapsed
500 25 MB 0.2s
1000 63 MB 0.9s
2000 206 MB 3.7s
5000 1.2 GB 12.7s
10000 4.7 GB → panic 52s

WASM has a 4 GB linear memory ceiling. It dies well before native does.

The fix

im::Vector is a persistent RRB-tree. .clone() bumps an Arc on the root; subsequent mutations on either side path-copy only the affected nodes. Holding N snapshots that descend from a single base costs O(base + Σ deltas), not O(N · base).

Post-fix on the same workload:

N RSS (pre-fix) RSS (post-fix) Reduction
500 25 MB 19 MB 24%
1000 63 MB 22 MB 65%
2000 206 MB 31 MB 85%
5000 1.2 GB 61 MB 95%
10000 4.7 GB (panic) 108 MB 97.7%

Realistic active-trader workload (alternating buy/sell, FIFO booking):

N RSS (pre-fix) RSS (post-fix)
5000 1.2 GB 58 MB
20000 18.8 GB 196 MB

Tradeoff

im::Vector mutations are O(log M) per op vs O(1) amortized for Vec. Booking benchmarks regress:

benchmark pre-fix post-fix delta absolute per-op
reduce_fifo/10 3.22 µs 4.07 µs +26% +85 ns
reduce_fifo/100 189 µs 352 µs +86% +1.6 µs
reduce_fifo/500 4.37 ms 13.87 ms +217% +19 µs
benchmark pre-fix post-fix delta
inventory_clone/10 319 ns 37 ns −88%
inventory_clone/3 130 ns 37 ns −71%

Per-op overhead scales with inventory size M. Users with large inventories pay the booking tax — but they're the same users who hit the JOURNAL OOM today, so net-positive for them. Typical users (M ≤ 10) eat ~85 ns/op; sub-millisecond impact on rledger check.

Why not a hybrid (Vec for booking, im::Vector for JOURNAL only)?

Considered carefully. A clean implementation requires either:

  1. Generic-over-backing on Inventory (substantial refactor — every method parameterized)
  2. A delta-export API from every mutation (new public surface, replay logic in executor)

Either is a reasonable follow-up if the booking regression bites someone in real measurement. But pure-Vec snapshots fundamentally cannot avoid the O(N·M) memory shape — there is no structural sharing to amortize against.

Surface changes

  • Inventory::positions() now returns impl Iterator<Item = &Position> (was &[Position]) to abstract over the backing type.
  • Added Inventory::position_list() -> Vec<&Position> for the handful of callers (BQL tests, FFI/WASM convert paths) that need slice-style access.
  • Internal self.positions.push(...) → push_back(...) for the im::Vector API.
  • rkyv derives removed from Inventory: im::Vector has no rkyv impl, and no code path archives an Inventory (verified during the SmallVec experiment for perf(booking): SmallVec for BookingResult::matched and Inventory::positions #1069). Serde wire format unchanged.

Test plan

  • cargo test -p rustledger-core -p rustledger-booking -p rustledger-validate -p rustledger-query --all-features — 1046 tests, 0 failures
  • cargo clippy -p ... -- -D warnings — clean on all touched crates including rustledger-wasm, rustledger-ffi-wasi
  • cargo fmt --all -- --check — clean
  • Native stress test (adversarial unique-lot workload): 4.7 GB → 108 MB at N=10000
  • Native stress test (realistic FIFO trader): 18.8 GB → 196 MB at N=20000
  • Manual WASM smoke test (would require building wasm-pack, not blocking)

Known follow-up

rustledger/src/cmd/query/output.rs:154 panics with "Formatting argument out of range" when a single rendered Inventory cell exceeds format-machinery limits (e.g., 5000+ positions in one cell). Pre-existing bug — was previously masked by the OOM. Will file a separate issue.

🤖 Generated with Claude Code

…pshots (#1086)

Changes Inventory.positions from Vec<Position> to im::Vector<Position>
so cumulative-balance snapshots in JOURNAL/SELECT cost O(1) (Arc bump
on the persistent RRB-tree root) instead of O(M) per row. This makes
the per-row clone in `execute_journal` and the cumulative-balance
context build in `collect_postings` non-load-bearing for memory.

## The problem

PR #940 added a cumulative `balance` column to JOURNAL output. The
executor materializes every row's `PostingContext` (and the JOURNAL
hot loop materializes every row) holding a snapshot of
`cumulative_balance` at that point. With Vec backing, each snapshot
is a full O(M) clone of the position list. Memory scales as O(N·M)
in the worst case, O(N²) when each posting opens a unique lot.

Native stress test, JOURNAL on N rows with N unique lots:
  N=500:    25 MB / 0.2s
  N=1000:   63 MB / 0.9s
  N=2000:  206 MB / 3.7s
  N=5000:  1.2 GB / 12.7s
  N=10000: 4.7 GB → panic

WASM (4 GB linear memory ceiling) dies well before native does.

## The fix

`im::Vector` is a persistent RRB-tree. `.clone()` bumps an Arc on the
root and shares the entire tree with the source. Subsequent mutations
on either side path-copy only the affected nodes. Net effect: holding
N snapshots that descend from a single base costs O(base + sum deltas),
not O(N * base).

After fix, same workload:
  N=500:    19 MB / 0.2s
  N=1000:   22 MB / 0.9s
  N=2000:   31 MB / 3.5s
  N=5000:   61 MB / 11.6s
  N=10000: 108 MB / 50s

Realistic active-trader workload (alternating buy/sell, FIFO):
  N=20000 old:  18.8 GB / 3:27
  N=20000 new:  196 MB / 3:07     (99% memory reduction)

## Tradeoff

`im::Vector` mutations are O(log M) per op, vs O(1) amortized for
`Vec`. The constant factor is non-trivial. Booking benchmarks regress:

  reduce_fifo/10:  3.22 µs → 4.07 µs   (+26%,  +85 ns/op)
  reduce_fifo/100: 189 µs → 352 µs     (+86%,  +1.6 µs/op)
  reduce_fifo/500: 4.37 ms → 13.87 ms  (+217%, +19 µs/op)

The per-op overhead scales with inventory size M. The users who feel
the booking tax are users with very large inventories — the same
users who hit the JOURNAL OOM today. Net positive for them.

For typical users (M <= 10), per-op overhead is ~85 ns; total impact
on `rledger check` is sub-millisecond per ledger.

## Surface changes

- `Inventory::positions()` now returns an iterator (was `&[Position]`)
  to abstract over the backing type
- Added `Inventory::position_list()` returning `Vec<&Position>` for
  the few call sites that need slice-style access (BQL test fixtures
  and integration tests)
- Internal `self.positions.push(...)` -> `push_back(...)` for
  `im::Vector` API
- `rkyv` derives removed from `Inventory`: `im::Vector` has no rkyv
  impl, and no code path archives an Inventory (confirmed during the
  SmallVec experiment for #1069). Serde wire format unchanged
  (sequence-typed, identical for both backings).

## Why not a hybrid (Vec for booking, im::Vector for JOURNAL only)

Considered. A clean implementation requires either generic-over-
backing on Inventory (substantial refactor) or a delta-export API
on every mutation (new public surface). Either path is reasonable
follow-up if the booking regression bites someone in real
measurement, but pure-Vec snapshots cannot avoid the O(N*M) memory
shape — they would be free of structural sharing.

## Known follow-ups

- `rustledger/src/cmd/query/output.rs:154` panics with
  "Formatting argument out of range" when a single rendered Inventory
  cell exceeds format-machinery limits (e.g. 5000+ positions in one
  row). Pre-existing; surfaces in the adversarial unique-lot
  workload after the memory fix lifts the OOM. Will file separately.

Closes #1086

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 11, 2026 21:00
@robcohen
robcohen requested a review from a team as a code owner May 11, 2026 21:00
@github-actions

github-actions Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 31.9ms ± 0.5ms 21.7 MB
beancount 882ms ± 9.3ms 50.2 MB
Comparison 27.6x faster 2.3x less

vs main branch (2026-05-11)

Metric main this PR Change
Time 34.2ms 31.9ms -6.7% 🟢
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 addresses JOURNAL/SELECT out-of-memory behavior caused by cloning growing Inventory snapshots per row by switching Inventory.positions to a persistent structurally-shared container (im::Vector). It updates the Inventory positions API and propagates call-site changes across query execution, output formatting, WASM/FFI conversions, and tests, plus adds dependency/supply-chain updates for the new crate.

Changes:

  • Replaced Inventory.positions: Vec<Position> with im::Vector<Position> to make Inventory::clone() O(1) via structural sharing and prevent O(N·M) snapshot blowups.
  • Updated Inventory access patterns (positions() iterator + position_list()) and migrated downstream callers accordingly.
  • Added im dependency (and its transitive deps) plus supply-chain configuration/audit updates.

Reviewed changes

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

Show a summary per file
File Description
supply-chain/imports.lock Adds an audit entry for a newly introduced transitive dependency (bitmaps).
supply-chain/config.toml Adds exemptions for im and transitive deps used by the new persistent vector.
crates/rustledger/src/cmd/query/output.rs Updates inventory iteration to match the new iterator-based positions() API.
crates/rustledger-wasm/src/convert.rs Adjusts WASM conversion to use position_list() for slice-like access.
crates/rustledger-validate/src/validators/account.rs Updates inventory iteration after positions() API change.
crates/rustledger-query/tests/bql_integration_test.rs Updates tests to use position_list() where slice semantics are needed.
crates/rustledger-query/src/executor/operators.rs Updates inventory comparison logic to use iterator-based access.
crates/rustledger-query/src/executor/mod.rs Updates executor functions to work with iterator-based positions() access.
crates/rustledger-query/src/executor/functions/util.rs Updates CONVERT logic to work with iterator-based positions() access.
crates/rustledger-query/src/executor/functions/position.rs Updates position-related functions to work with iterator-based positions() access.
crates/rustledger-ffi-wasi/src/convert.rs Updates FFI-WASI conversion iteration after positions() API change.
crates/rustledger-core/src/inventory/mod.rs Core change: switches backing store to im::Vector, changes positions() API, adds position_list(), removes rkyv derives from Inventory.
crates/rustledger-core/src/inventory/booking.rs Updates booking mutations to use push_back for im::Vector.
crates/rustledger-core/Cargo.toml Adds im dependency to core crate.
crates/rustledger-booking/src/book.rs Updates tests to use iterator-based access (next() instead of first()).
Cargo.toml Adds im to workspace dependencies with serde feature.
Cargo.lock Locks im and transitive deps; updates some transitive versions (e.g., windows-sys).
Comments suppressed due to low confidence (3)

crates/rustledger-query/src/executor/mod.rs:686

  • This Value::Inventory → NUMBER implementation now allocates a Vec<&Position> just to check emptiness/single-currency and sum. This is a new per-call allocation compared to the prior slice-based code and can show up in hot query paths. You can do the same logic in a single pass over inv.positions() (track first currency + running total; early-return NULL on mismatch) without collecting.
                    Value::Inventory(inv) => {
                        // For inventory, only return a number if all positions share the same
                        // currency. Summing across different currencies is not meaningful.
                        let positions: Vec<&Position> = inv.positions().collect();
                        if positions.is_empty() {
                            return Ok(Value::Number(Decimal::ZERO));
                        }
                        let first_currency = &positions[0].units.currency;
                        let all_same_currency = positions
                            .iter()
                            .all(|p| &p.units.currency == first_currency);
                        if all_same_currency {
                            let total: Decimal = positions.iter().map(|p| p.units.number).sum();
                            Ok(Value::Number(total))

crates/rustledger-query/src/executor/functions/util.rs:172

  • CONVERT now collects result.positions() into Vec<&Position> to check empty / single-position. That introduces an avoidable allocation; you can determine “empty vs exactly one vs many” by peeking the iterator (next() twice) without materializing a Vec. This keeps CONVERT’s steady-state overhead lower for large inventories (the main target of this PR).
                }
                // If result has single currency matching target, return as Amount
                // If result is empty, return zero in target currency (issue #586)
                let positions: Vec<&Position> = result.positions().collect();
                if positions.is_empty() {
                    Ok(Value::Amount(Amount::new(Decimal::ZERO, &target_currency)))
                } else if positions.len() == 1 && positions[0].units.currency == target_currency {
                    Ok(Value::Amount(positions[0].units.clone()))
                } else {
                    Ok(Value::Inventory(Box::new(result)))

crates/rustledger-wasm/src/convert.rs:150

  • value_to_cell switched from inv.positions() to inv.position_list(), which forces an O(N) allocation of a Vec<&Position> even though the code only iterates once. Consider iterating directly over inv.positions() here to avoid the extra allocation in the WASM/JSON conversion path (especially for large inventories, which are the motivating case for this PR).
        Value::Inventory(inv) => {
            let positions = inv.position_list();
            CellValue::Inventory {
                positions: positions
                    .iter()
                    .map(|p| PositionValue {
                        units: AmountValue {
                            number: p.units.number.to_string(),
                            currency: p.units.currency.to_string(),
                        },
                    })
                    .collect(),
            }

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@codecov

codecov Bot commented May 11, 2026 •

Copy link
Copy Markdown

@github-actions

github-actions Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 98%
Full AST Match 99%
Total Files 786
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 2 commits May 11, 2026 16:39
…panic

`std::fmt::rt::Argument::from_usize` panics with "Formatting argument
out of range" when a dynamic `{:width$}` width parameter exceeds
`u16::MAX = 65,535` — a stdlib internal limit on the format-args
encoding for runtime-supplied widths. This was masked by the OOM
fixed in the previous commit, but the previously-OOM-ing adversarial
JOURNAL workload now reaches the formatter and trips this panic
instead.

Repro before this commit (post-im::Vector fix):
  rledger query stress_lots_3000.beancount "JOURNAL 'Assets:Stocks'"
  -> panic at output.rs:154: "Formatting argument out of range"

The threshold is exactly where stdlib's u16 cap bites:
  N=2700 lots: cell width ~64,797 chars  -> ok
  N=2800 lots: cell width ~67,197 chars  -> panic

## Fix

Clamp every column width at `u16::MAX` before passing it to `write!`.
When the formatted cell content exceeds the cap, `write!` writes the
content verbatim — `{:width$}` does not truncate when content is
wider than the requested width, it just produces no padding. Padding
to >65k chars couldn't align meaningfully in any terminal anyway, so
this is the correct fallback behavior.

After this commit, the same stress workload completes cleanly:
  N=3000:  40 MB / 7.8s   exit 0
  N=5000:  59 MB / 21.2s  exit 0
  N=10000: 106 MB / 95s   exit 0

## Test

Added `test_write_text_does_not_panic_on_cells_wider_than_u16_max`:
build a `QueryResult` with a 70,000-char cell and assert `write_text`
returns `Ok` and emits the content verbatim. Without the cap, this
test panics inside std::fmt; with the cap, it passes.

Refs #1086

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses Copilot review feedback on PR #1087:

1. `executor/mod.rs` NUMBER on `Value::Inventory`: was collecting
   `inv.positions()` into `Vec<&Position>` to check empty/single-
   currency. Rewritten as a single pass over the iterator that tracks
   the first currency and running total, bailing to `Null` on any
   currency mismatch. No allocation in the hot path.

2. `executor/functions/util.rs` CONVERT: was collecting `result.positions()`
   into `Vec<&Position>` to determine empty/single/many. Rewritten to
   peek the first two positions; the single-match `Amount` is cloned
   eagerly (O(1) — `Decimal` + interned `currency`) so the iterator
   borrow can be dropped before `result` is moved into the boxed
   `Value::Inventory`.

3. `wasm/convert.rs` `value_to_cell`: was calling `position_list()`
   (allocates `Vec<&Position>`) just to iterate once. Switched back to
   iterating `inv.positions()` directly into the `.collect()` for the
   serializable `CellValue::Inventory`.

4. `inventory/mod.rs` `positions` field doc: previously claimed "no
   measurable regression at realistic inventory sizes" — stale, copied
   from the prior `SmallVec` experiment. Rewritten to state the actual
   measured trade-off (+85 ns/op at M=10, +1.6 µs/op at M=100, +19 µs/op
   at M=500) and acknowledge the pre-1.0 break of dropping `rkyv` derives
   from `Inventory`.

No behavior change; all 1046 tests on touched crates still pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen

Copy link
Copy Markdown
Member Author

Addressed all Copilot review feedback in bc511b1:

Inline comments (replied directly):

  • inventory/mod.rs:318 rkyv break — pre-1.0 break, intentional. Doc updated to flag for downstream callers.
  • inventory/mod.rs:311 stale 'no measurable regression' claim — rewrote with the actual measured numbers (+85 ns/op at M=10, +1.6 µs/op at M=100, +19 µs/op at M=500).

Three suppressed comments on Vec<&Position> allocations — all valid, all fixed:

  • executor/mod.rs NUMBER on Inventory: single-pass over the iterator (track first currency + running sum, bail to Null on mismatch). No allocation in the hot path.
  • executor/functions/util.rs CONVERT: peek the first two positions, clone the single-match Amount eagerly (O(1) — Decimal + interned currency) so the borrow can be dropped before result is moved.
  • wasm/convert.rs value_to_cell: dropped the position_list() call, iterate inv.positions() directly into the .collect().

These were genuine allocator regressions I introduced when migrating call sites off the old slice-returning positions() API. Thanks Copilot.

All 1046 tests on touched crates still pass; clippy + fmt clean.

@robcohen
robcohen merged commit 3542392 into main May 11, 2026
45 checks passed
@robcohen
robcohen deleted the perf/issue-1086-im-vector-inventory branch May 11, 2026 23:24
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.

perf(query): JOURNAL clones growing cumulative_balance per matching posting (same shape as #1080, separate path)

2 participants