Repository navigation
perf(core): structural sharing for Inventory positions to fix JOURNAL OOM (#1086) - #1087
Conversation
…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]>
📊 Benchmark Results
vs main branch (2026-05-11)
What do these numbers mean?
|
There was a problem hiding this comment.
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>withim::Vector<Position>to makeInventory::clone()O(1) via structural sharing and prevent O(N·M) snapshot blowups. - Updated
Inventoryaccess patterns (positions()iterator +position_list()) and migrated downstream callers accordingly. - Added
imdependency (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→NUMBERimplementation now allocates aVec<&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 overinv.positions()(track first currency + running total; early-returnNULLon 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
CONVERTnow collectsresult.positions()intoVec<&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_cellswitched frominv.positions()toinv.position_list(), which forces anO(N)allocation of aVec<&Position>even though the code only iterates once. Consider iterating directly overinv.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 Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
|
| 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
…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]>
|
Addressed all Copilot review feedback in bc511b1: Inline comments (replied directly):
Three suppressed comments on
These were genuine allocator regressions I introduced when migrating call sites off the old slice-returning All 1046 tests on touched crates still pass; clippy + fmt clean. |
Summary
Inventory.positionsfromVec<Position>toim::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.Closes #1086.
The problem
PR #940 added a cumulative
balancecolumn to JOURNAL. Each row stores a clone ofcumulative_balanceat that point in the stream. WithVecbacking, 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):
WASM has a 4 GB linear memory ceiling. It dies well before native does.
The fix
im::Vectoris 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:
Realistic active-trader workload (alternating buy/sell, FIFO booking):
Tradeoff
im::Vectormutations are O(log M) per op vs O(1) amortized forVec. Booking benchmarks regress: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:
Inventory(substantial refactor — every method parameterized)Either is a reasonable follow-up if the booking regression bites someone in real measurement. But pure-
Vecsnapshots fundamentally cannot avoid the O(N·M) memory shape — there is no structural sharing to amortize against.Surface changes
Inventory::positions()now returnsimpl Iterator<Item = &Position>(was&[Position]) to abstract over the backing type.Inventory::position_list() -> Vec<&Position>for the handful of callers (BQL tests, FFI/WASM convert paths) that need slice-style access.self.positions.push(...)→push_back(...)for theim::VectorAPI.rkyvderives removed fromInventory:im::Vectorhas norkyvimpl, 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 failurescargo clippy -p ... -- -D warnings— clean on all touched crates including rustledger-wasm, rustledger-ffi-wasicargo fmt --all -- --check— cleanKnown follow-up
rustledger/src/cmd/query/output.rs:154panics 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