Skip to content

perf(query): stop copying the account inventory twice per row - #2088

Merged
robcohen merged 2 commits into
mainfrom
perf/account-balance-clone
Aug 18, 2026
Merged

robcohen merged 2 commits into
mainfrom
perf/account-balance-clone

Conversation

@robcohen

Copy link
Copy Markdown
Member

Partly addresses #2086 — and corrects that issue's framing, which overstated the defect.

query, 6,000 transactions, cold cache main this PR
select account, account_balance where account ~ 'HOOL' 33.93s 26.11s
select count(account) where … and account_balance != 0 3.19s 2.42s

Three changes

Value::Inventory and PostingContext::account_balance hold an Arc, not 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 used a std HashMap. SipHash, grown from empty, built once per output row with one insert per lot: 17.8% of the run in sip::Hasher::write plus 11.7% in reserve_rehash. Now FxHashMap, 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 balance got 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 Owned precisely 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:

6,000 txns
select account, account_balance … 34s, producing 409.6 MB of output (longest line 83,775 chars)
same query, column removed 0.14s
reads the column, returns ONE row 3.19s

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

`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
Copilot AI lite review requested due to automatic review settings August 18, 2026 22:09
@robcohen
robcohen requested a review from a team as a code owner August 18, 2026 22:09

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 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::Inventory and PostingContext::account_balance to use Arc<Inventory> to avoid deep-copying inventories when values are cloned/propagated.
  • Defer the pre-WHERE account_balance snapshot until after filtering unless the WHERE clause itself reads account_balance.
  • Speed up inventory rendering aggregation by replacing per-row std::collections::HashMap (SipHash) with a pre-sized rustc_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.

@github-actions

github-actions Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.4ms ± 0.6ms 24.2 MB
beancount 792.8ms ± 5.4ms 50.7 MB
Comparison 23x faster 2.1x less

vs main branch (2026-08-18)

Metric main this PR Change
Time 39.1ms 34.4ms -12.0% 🟢
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

@codecov

codecov Bot commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.60870% with 8 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-query/src/executor/mod.rs 80.95% 4 Missing ⚠️
crates/rustledger-query/src/executor/execution.rs 50.00% 3 Missing ⚠️
...rates/rustledger-query/src/executor/aggregation.rs 50.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 170 masked)
Full AST Match 100%
Total Files 811
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

Copy link
Copy Markdown
Member Author

Full benchmark — and the headline is memory, not time

Five workload shapes at two sizes for rledger check (unchanged, as expected — this PR only touches the query path), then the query path proper. All cold-cache, all three binaries built with the same toolchain.

N main this PR
6,000 33.96s / 4.96 GB 25.97s / 2.50 GB
10,000 95.03s / 14.3 GB 71.84s / 7.19 GB
14,000 185.15s / 27.1 GB 140.21s / 13.6 GB
20,000 OOM-killed 290s / 28.2 GB ✅

select account, account_balance where account ~ 'HOOL', on a 30 GB machine with no swap.

Roughly half the memory at every size, which is the Arc doing exactly what it was for: the context and the Value shared one inventory instead of holding two deep copies of it. Time follows at ~1.3×.

The 20,000 row is the interesting one, and it nearly fooled me. My first measurement read:

account_balance (full output)  20000   main 26.33s   this PR 289.65s   0.09x

An 11× regression — except main was not finishing. exit=137, zero bytes of output: the kernel killed it. Its 26 seconds was time-to-death, not time-to-answer. This PR completes the same query (exit=0, 3.0 GB of output) because it needs half the memory to do it.

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

  • The deferral gate is sound. expr_references_column walks every Expr variant with no _ arm, so a new variant is a compile error rather than a silently missed reference — which matters here, because a missed reference would make the column read Null during WHERE instead of failing loudly.
  • Differential output check: 8 query shapes (column in SELECT, in WHERE, in both, with ORDER BY, with GROUP BY, on a small account, absent entirely) — byte-identical between main and this PR. Mutation-checked: neutering the deferred fill makes 2 of them differ, so the harness covers the changed path.
  • Arc sharing is safe: nothing mutates an Inventory through a Value, and Arc<T>'s PartialEq/Hash delegate to T, so comparison and grouping semantics are unchanged.

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
@robcohen
robcohen merged commit dae640b into main Aug 18, 2026
79 of 81 checks passed
@robcohen
robcohen deleted the perf/account-balance-clone branch August 18, 2026 23:34
robcohen added a commit that referenced this pull request Aug 19, 2026
…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
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