Skip to content

perf(query): snapshot account inventories by refcount, not by copying - #2089

Merged
robcohen merged 2 commits into
mainfrom
perf/inventory-cow
Aug 19, 2026
Merged

robcohen merged 2 commits into
mainfrom
perf/inventory-cow

Conversation

@robcohen

Copy link
Copy Markdown
Member

Closes #2086. Reading account_balance copied the account's whole inventory once per posting, so a query that reads the column and returns a single row still cost O(rows × lots).

N main this PR
2,000 0.31s / 303 MB 0.06s / 21 MB
6,000 2.55s / 2,495 MB 0.13s / 37 MB
14,000 — 0.42s / 68 MB
20,000 — 0.74s / 94 MB

select count(account) where account ~ 'HOOL' and account_balance != 0, cold cache. Linear now, and memory tracks the ledger rather than rows × lots.

How

The engine holds each account's inventory in an Arc and mutates through Arc::make_mut. Booking never shares one, so it gets &mut back and pays nothing. A caller that takes a snapshot makes the next mutation of that account copy once — the copy it actually asked for — instead of a copy per row whether anyone wanted one or not.

That alone changed nothing, which is the part worth recording. The executor stored every snapshot in its posting context for the life of the query, so the Arc was never unique again and every mutation copied anyway. The snapshot is now released once the filter has run, unless something downstream reads it. That release is what makes the refcount matter — the copy-on-write was inert without it.

Two approaches that do not work

  • A Shared-backed mirror updated with Inventory::add. add merges only cost-LESS positions; booked reductions would pile up as separate negative lots instead of netting, so account_balance would report 10 X {120} 10 X {100} -5 X {110} where it now reports the netted holding.
  • Mutating a shared imbl::Vector in place. make_owned's doc records the use-after-free of the interned Arc<str> inside Position that this caused during perf(core): pick the inventory backing by use, not one for both #2056.

What is unchanged, deliberately

A query that OUTPUTS an inventory per row is still O(rows × lots), because that is the size of what it returns — 6,000 transactions emit 409 MB. The defect was never that; it was paying the same price to answer a boolean.

Verification

  • Ten query shapes byte-identical against main (column in SELECT, in WHERE, in both, with ORDER BY on the column, with GROUP BY, alongside balance, and absent).
  • That check is mutation-tested: releasing a snapshot the output needs makes two of them differ.
  • 146 suites green; clippy, fmt and doc clean.

scan_postings takes a ScanNeeds struct now — six consecutive booleans at a call site said nothing about which was which, and clippy's too_many_arguments agreed.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

Closes the growth term in #2086. Reading `account_balance` copied the
account's entire inventory once per posting, so a query that reads the
column and returns a SINGLE row still cost O(rows x lots):

    select count(account) where account ~ 'HOOL' and account_balance != 0

      2,000 txns   0.31s   303 MB  ->  0.06s   21 MB
      6,000 txns   2.55s  2495 MB  ->  0.13s   37 MB
     14,000 txns      —            ->  0.42s   68 MB
     20,000 txns      —            ->  0.74s   94 MB

Linear now, and the memory is proportional to the ledger rather than to
rows x lots.

The engine holds each account's inventory in an `Arc` and mutates through
`Arc::make_mut`. Booking never shares one, so it hands back `&mut` and
the engine pays nothing. A caller that takes a snapshot makes the NEXT
mutation of that account copy once — the copy it asked for — instead of a
copy per row whether anyone wanted one or not.

That alone did nothing, which is the part worth recording: the executor
stored every snapshot in its posting context for the life of the query,
so the `Arc` was never unique again and every mutation copied anyway. The
snapshot is now released after the filter unless something downstream
reads it, which is what makes the refcount matter.

A mirror built with `Inventory::add` was the other candidate and does not
work: `add` merges only cost-LESS positions, so booked reductions would
pile up as separate negative lots instead of netting. Mutating a shared
`imbl::Vector` in place is also out — `make_owned`'s note records the
use-after-free that caused.

`scan_postings` takes a `ScanNeeds` struct now; six consecutive booleans
at a call site said nothing about which was which, and clippy agreed.

Unchanged: a query that OUTPUTS an inventory per row is still O(rows x
lots), because that is the size of what it returns. 6,000 transactions
emit 409MB. Ten query shapes verified byte-identical against main, and
the check is mutation-tested — releasing a snapshot the output needs
makes two of them differ.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner August 19, 2026 00:39
Copilot AI lite review requested due to automatic review settings August 19, 2026 00:39
@codecov

codecov Bot commented Aug 19, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.87234% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-query/src/executor/mod.rs 96.61% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 38.5ms ± 0.9ms 24.2 MB
beancount 926.3ms ± 5.8ms 50.4 MB
Comparison 24.1x faster 2.1x less

vs main branch (2026-08-18)

Metric main this PR Change
Time 39.1ms 38.5ms -1.5% ✅
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 a performance/memory blow-up in rustledger-query when a query references account_balance but does not actually need to materialize/retain full per-row inventory copies. It does so by making booking-engine inventories cheap to snapshot via refcounting (Arc + Arc::make_mut), and by tightening the executor’s lifetime management so snapshots taken only for WHERE can be dropped immediately after filtering.

Changes:

  • Switch BookingEngine’s per-account inventories to Arc<Inventory> and add inventory_snapshot() for O(1) snapshotting (copy-on-write on next mutation).
  • Refactor Executor::scan_postings call sites to pass a ScanNeeds struct (replacing positional booleans) and use it to decide when account_balance must be retained past WHERE.
  • Update #postings system table scan to the new ScanNeeds API.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
crates/rustledger-query/src/executor/mod.rs Introduces ScanNeeds, adds output_references_column(), and drops account_balance snapshots after WHERE unless downstream needs them.
crates/rustledger-query/src/executor/system_tables.rs Updates #postings scan to use ScanNeeds.
crates/rustledger-booking/src/book.rs Stores per-account inventories behind Arc, adds inventory_snapshot(), and uses Arc::make_mut for copy-on-write mutation.

💡 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%, 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

Copilot's review. `ScanNeeds` landed between `query_references_column`'s
doc comment and the function itself, so those five lines documented the
struct — describing it as something that "returns `true` if any part of a
`SelectQuery` references the given column" — and the function was left
bare. Wrong in generated docs and in IDE hovers, and exactly the kind of
thing a mechanical insertion gets wrong quietly.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit 105cc6c into main Aug 19, 2026
71 of 73 checks passed
@robcohen
robcohen deleted the perf/inventory-cow branch August 19, 2026 03:10
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.

BQL account_balance copies the account inventory twice per row (quadratic)

2 participants