Repository navigation
perf(query): stop copying the account inventory twice per row - #2088
Conversation
`account_balance` cost 34s on a 6,000-transaction ledger (#2086). Three changes, none of which removes the growth term — see below. `Value::Inventory` and `PostingContext::account_balance` hold an `Arc` rather than a `Box`. Reading the column deep-copied every lot a SECOND time, on top of the copy the context already held, so a query that merely tests `account_balance != 0` paid two O(lots) copies per row to answer a boolean. `Arc::clone` also makes `Value` cheap to clone generally, which the aggregation paths get for free. `rendered_inventory_positions` built a std `HashMap` — SipHash, grown from empty — once per output row and inserted once per lot. That was 17.8% of the run in `sip::Hasher::write` plus 11.7% in `reserve_rehash`. Now `FxHashMap`, sized up front. The hasher is free to change because the sort below it is total; the comment on its label arm records why. The pre-WHERE copy is deferred past the filter unless the WHERE clause itself reads the column, which is the treatment `balance` got in #1085. Measured at 6,000 transactions, cold cache: select account, account_balance 33.93s -> 26.11s ... where account_balance != 0 3.19s -> 2.42s ## What this does not fix Still quadratic. One O(lots) copy per row remains, because the engine's inventory keeps moving and each row needs the state at its own posting. Removing it needs snapshots that are cheap by construction — the structurally-shared backing #1086 added for the cumulative balance — and the engine's inventories are `Owned` precisely so booking is fast. Worth separating from the headline number: at 6,000 transactions this query legitimately produces 409MB of output, with lines up to 83,775 characters, because a running lot-level inventory per row IS O(rows x lots) of text. The defect is the internal path — 3.19s to answer a query that returns a single row. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
There was a problem hiding this comment.
Pull request overview
This PR optimizes BQL query execution and rendering by reducing per-row inventory copying and lowering hashing overhead when rendering inventories, targeting constant-factor improvements for account_balance-heavy queries in rustledger-query.
Changes:
- Switch
Value::InventoryandPostingContext::account_balanceto useArc<Inventory>to avoid deep-copying inventories when values are cloned/propagated. - Defer the pre-WHERE
account_balancesnapshot until after filtering unless the WHERE clause itself readsaccount_balance. - Speed up inventory rendering aggregation by replacing per-row
std::collections::HashMap(SipHash) with a pre-sizedrustc_hash::FxHashMap.
Reviewed changes
Copilot reviewed 9 out of 10 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/rustledger/src/cmd/query/output.rs | Use FxHashMap to reduce hashing overhead when aggregating inventory lots for output; update tests to construct Value::Inventory via Arc. |
| crates/rustledger/Cargo.toml | Add rustc-hash dependency for the CLI crate to support FxHashMap usage in query output. |
| crates/rustledger-query/src/executor/types.rs | Change Value::Inventory and PostingContext::account_balance to store Arc<Inventory>. |
| crates/rustledger-query/src/executor/tests.rs | Update hashing tests to construct Value::Inventory with Arc. |
| crates/rustledger-query/src/executor/system_tables.rs | Update #postings table construction to handle Arc-backed inventories and new scan_postings signature. |
| crates/rustledger-query/src/executor/mod.rs | Add where_reads_account_balance gating and defer the account_balance clone past WHERE when safe. |
| crates/rustledger-query/src/executor/execution.rs | Update execution paths to emit Value::Inventory(Arc<...>) instead of boxing/cloning inventories. |
| crates/rustledger-query/src/executor/evaluation.rs | Make account_balance column evaluation use Arc::clone (cheap) rather than deep-cloning inventories. |
| crates/rustledger-query/src/executor/aggregation.rs | Update aggregation results to return Arc-backed inventories. |
| Cargo.lock | Record rustc-hash as a resolved dependency. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
📊 Benchmark Results
vs main branch (2026-08-18)
What do these numbers mean?
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Full benchmark — and the headline is memory, not timeFive workload shapes at two sizes for
Roughly half the memory at every size, which is the Arc doing exactly what it was for: the context and the The 20,000 row is the interesting one, and it nearly fooled me. My first measurement read: An 11× regression — except main was not finishing. So the honest summary is that halving the footprint moves the OOM threshold out past 20,000 transactions, and the timing comparison at that size is meaningless because there is nothing on the other side to compare against. Worth recording as a measurement lesson, since it is the same trap in a new form: I have twice this session mistaken a failed run for a fast one. Timing a command without checking its exit status measures whatever happened, not what you asked for. Correctness review
146 suites green; clippy, fmt and doc clean. |
Copilot's review. The `Value::Inventory` doc still said "Boxed to reduce enum size", and the note next to `where_reads_balance` still said `account_balance` needs no analogous gate — which this change made untrue in both cases. Both now describe what the code does: `Arc` keeps the enum small AND makes the value cheap to clone, and `account_balance` gets the same treatment as `balance` by a different mechanism — filled late rather than refreshed late, since the eager update already made it the running total. Copilot's third comment, that `rustc_hash::FxBuildHasher` is a type and would not compile, is incorrect: it is a unit struct (`pub struct FxBuildHasher;`), so the bare path is a value. Left as written. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…build Review of my own diff, two findings. The significance test compared the gap against two standard deviations of INDIVIDUAL RUNS, but the quantity being compared is two means, whose uncertainty is the standard error — smaller by sqrt(runs). At these numbers that made the test fire only above ~14%, so a real 10% regression would have been reported as noise. It now uses the standard error of the difference, which resolves ~3%, plus an effect-size floor of 3% so a difference that is statistically visible but too small to act on is not dressed up as a finding. Worth being explicit that my original validation was against the wrong scenario: I checked the rule against #2088's -12%, but that gap came from comparing runners, which measuring both sides in one job removes. The rule has to be judged on same-runner data, and simulated at 20 runs with the observed per-run spread it reports +5%, +10% and -12% while treating identical binaries and a +2% change as noise. The base also built into its own target directory, which is a cold build of every dependency and the most likely way this job would have started timing out. The two commits share a dependency graph, so it now builds into the same directory and recompiles only the workspace crates. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Partly addresses #2086 — and corrects that issue's framing, which overstated the defect.
select account, account_balance where account ~ 'HOOL'select count(account) where … and account_balance != 0Three changes
Value::InventoryandPostingContext::account_balancehold anArc, not aBox. Reading the column deep-copied every lot a second time, on top of the copy the context already held — so a query that merely testsaccount_balance != 0paid two O(lots) copies per row to answer a boolean.Arc::clonealso makesValuecheap to clone generally, which the aggregation paths get for free.rendered_inventory_positionsused a stdHashMap. SipHash, grown from empty, built once per output row with one insert per lot: 17.8% of the run insip::Hasher::writeplus 11.7% inreserve_rehash. NowFxHashMap, sized up front. The hasher is safe to change because the sort below it is total — the comment on its label arm records why that matters.The pre-WHERE copy is deferred past the filter unless the WHERE clause reads the column, which is the treatment
balancegot in #1085. Selective queries stop paying for rows they reject.What this does not fix, and a correction to #2086
Still quadratic. One O(lots) copy per row remains, because the engine's inventory keeps moving and each row needs the state at its own posting. Removing it needs snapshots that are cheap by construction — the structurally-shared backing #1086 added for the cumulative balance — while the engine's inventories are
Ownedprecisely so booking is fast. That is a larger change and belongs on its own.And #2086's headline overstates the defect. I filed it as "34s for a query". Measuring properly:
select account, account_balance …A running lot-level inventory per row genuinely is O(rows × lots) of text, so most of that 34s is output the query asked for. The real defect is the third line — 3.19s to answer a query returning a single row — which is what these changes target.
Verification
146 suites green; clippy (1.97.0), fmt and doc clean.
Note it needs #2087 (an unrelated latent flake in
apply_rollback_properties) to go green in CI — proptest surfaced that while I was measuring this, and it reproduces on main.🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr