Repository navigation
fix(query): skip cumulative-balance clone when query doesn't reference it (closes #1080) - #1085
Conversation
…e it (closes #1080) PR #940 introduced two computed columns to the BQL executor: balance (cumulative WHERE-filtered running total) and account_balance (per-account running total). Each PostingContext built in collect_postings carried snapshot clones of both. For long-running WHERE-filtered scans like SELECT account WHERE account ~ "^Assets" LIMIT 10 on a 22k-posting ledger, the cumulative_balance Inventory grows monotonically — meaning we cloned a thousand-position Inventory ~2-3 times per posting, producing ~12 GB of total allocation churn and ~5.8 GB peak WASM heap (reported on issue #1080). The existing optimization comment at line 477-478 gated the pre-WHERE clone on "is there a WHERE clause at all?". That gate fired for any query with a WHERE, regardless of whether anything actually read the column. The user's query has WHERE but reads neither balance nor account_balance — we were doing the entire clone churn for nothing. Fix: walk the SelectQuery AST once at the top of collect_postings via the new query_references_column helper, checking every relevant query part (SELECT targets, WHERE, GROUP BY, HAVING, PIVOT BY, ORDER BY, FROM filter). Use the result to gate: * The per-posting cumulative_balance.clone() (pre-WHERE + post-WHERE) * The cumulative_balance.add() update (no-op if no one reads balance) * The account_balances.entry().or_default().add() update * The account_balances.get().cloned() snapshot Queries that reference neither column (the common case) skip the entire balance-tracking + clone path. Queries that reference either keep the existing semantics bit-for-bit — existing tests all pass. Added test_query_references_column_covers_all_query_parts: parses SELECT-statements that reference balance in every position (SELECT target, WHERE, ORDER BY, GROUP BY, function arg, BETWEEN bound) and confirms the helper detects each. Plus negative cases for queries that don't reference balance. Closes #1080 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR addresses the severe WASM allocation/performance regression in #1080 by avoiding expensive per-posting cloning/updating of the balance (cumulative) and account_balance (per-account) running-state snapshots when the query does not actually reference those columns.
Changes:
- Refactors
collect_postingsto accept the fullSelectQueryand precompute whetherbalance/account_balanceare referenced anywhere in the query AST. - Gates
cumulative_balancecloning/updating andaccount_balancesmap updates based on those reference checks to avoid wasted work. - Adds
expr_references_column/query_references_columnhelpers and a new unit test to ensure query-part coverage.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| crates/rustledger-query/src/executor/mod.rs | Adds AST reference-walk helpers and uses them to gate expensive balance/account_balance snapshot work in collect_postings; adds targeted unit test. |
| crates/rustledger-query/src/executor/execution.rs | Updates SELECT execution to call the refactored collect_postings(&SelectQuery). |
💡 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! |
📊 Benchmark Results
vs main branch (2026-05-11)
What do these numbers mean?
|
|
| 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
Two valid findings: (1) expr_references_column did not traverse the OVER clause of Expr::Window — partition_by and order_by inside the window spec were ignored. A query like SUM(amount) OVER (PARTITION BY balance) would have produced a false negative and skipped the cumulative balance materialization, breaking the query at runtime. Added recursion through call.over.partition_by and call.over.order_by[].expr. Test: test_expr_references_column_walks_window_over_clause. (2) Pre-WHERE clone of cumulative_balance was unconditional whenever needs_balance was true. Pre-fix the gate was where_clause.is_some() — a query like SELECT balance FROM #postings (no WHERE) did 1 clone per posting, but my first cut did 2. Tightened the pre-WHERE gate to where_reads_balance (does the WHERE clause specifically read balance?). The post-WHERE refresh still fires whenever needs_balance is true. account_balance keeps the unconditional needs_account_balance gate because (unlike balance) it's NOT refreshed post-WHERE — its single slot is always the pre-WHERE update value, so the gate must allow SELECT account_balance to read it even without a WHERE. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Deep re-review (post-Copilot fixes)Walking the diff fresh after the ✅ Correctness audit1. 2. ORDER BY aliases handled correctly. A query like 3. Asymmetric gating is correct. The diff carries an explicit comment about the asymmetry — verified against the semantics:
Inverting either gate would break correctness:
4. Subqueries: the "opaque" treatment is correct. A query like
|
`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. Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr Co-authored-by: Claude Opus 5 <[email protected]>
) * perf(query): stop #postings materializing balances no query reads `build_postings_table` hardcoded `ScanNeeds { balance: true, account_balance: true, .. }`, so every `FROM #postings` query paid for the per-posting cumulative `Inventory` clones -- the #1080 runaway -- even when nothing referenced either column. The default source has gated this since #1085; the system table never did. On a 40k-posting ledger, best of three: SELECT count(account) FROM #postings 676ms -> 442ms -34% SELECT account FROM #postings 719ms -> 479ms -33% SELECT account ... WHERE account_balance != 0 746ms -> 521ms -30% SELECT count(balance) FROM #postings 686ms -> 588ms -14% SELECT * FROM #postings 1608ms -> 1620ms 0% `SELECT *` is unchanged by design: a wildcard reads every column. The flags do NOT carry `collect_postings`'s meaning here, and reusing that computation verbatim was wrong twice. This scan gets `where_clause: None` -- the table is built first and filtered afterwards -- so nothing is read at WHERE time. And the table materializes `account_balance` into every row regardless of the SELECT list, so the TABLE is the output: gating on `output_references_column` released the snapshot before the row was built, and `WHERE account_balance != 0` returned zero rows instead of twenty. Separately, this table's `SELECT *` includes `balance` and `account_balance` -- the default source's `WILDCARD_COLUMNS` excludes both -- so a wildcard must force them on, or those columns come back empty. Both mistakes produced silently empty balances rather than an error, and both were caught by diffing query output against a baseline binary rather than by the test suite, which passed throughout. The new test pins each one and was confirmed to fail against each. Also extends `examples/profile_query.rs` to cover the system-table path. It profiled only the default source, which is why a 7x gap between `SELECT count(account) FROM #postings` (681ms) and the same query without the FROM (93ms) went unnoticed. Adding the two shapes took the harness from 88.7M to 457.4M instructions. Refs #2169 * refactor(query): require the query in get_builtin_table Self-review catch on #2173. I threaded the query in as an `Option` with a conservative all-true fallback for a caller that does not exist: there is exactly one call site and it always passes `Some`. The fallback could never run and could never be tested, so it was untestable code shaped like a safety net -- the kind that rots into a wrong answer once someone does add a caller and does not notice which branch they get. The parameter is now required and the branch is gone. A future caller that genuinely cannot supply a query will have to make that choice explicitly rather than inherit it. All 19 output-equality shapes still match the baseline binary, and the measured win is unchanged (count(account) 440ms, SELECT * 1620ms). * docs(query): record the memory win and the scaling shape Review addition on #2173. The change was justified on wall clock alone; peak RSS is the larger effect and was not measured. On a 40k-posting ledger, three samples each, stable to 0.1%: count(account) FROM #postings goes 517MB -> 233MB, -55%. The snapshots are retained Inventory copies, so not taking them frees more proportionally than it saves in time. Control: a query that does read balance is 780MB -> 757MB, essentially unchanged, as it must be. Measured at 5k and 20k transactions as well. Both before and after scale linearly on a 4x workload (4.06 and 4.10), so this is a constant factor and not a complexity fix -- the #1080 quadratic was already dealt with elsewhere. Worth stating so the win is not mistaken for one.
* perf(query): skip #postings columns the query cannot observe
Five of this table's 31 columns hold most of its cost: the structured
`entry` object and the three metadata maps (`meta`, `_entry_meta`,
`_posting_meta`). They are now built only when the query can observe
them.
On a 40k-posting ledger, best of three:
SELECT count(account) FROM #postings 433ms/227MB -> 240ms/131MB
SELECT account FROM #postings 484ms/229MB -> 296ms/133MB
SELECT meta('k') FROM #postings 482ms/228MB -> 290ms/135MB
SELECT * FROM #postings 1617ms/844MB -> 1419ms/766MB
With #2173 that is 681ms/517MB -> 240ms/131MB for the first, -65% and
-75%.
The other 26 columns were measured and left alone: stubbing both
`StringSet` columns moved 443ms to 437ms. Gating them would cost more in
review surface than it saves.
Three ways to reach a gated column, each of which fails SILENTLY when the
gate is too tight -- a missed one yields Null, not an error:
* By name, including through an attribute: `entry.narration` reaches
`entry` because `expr_references_column` recurses into
`Attribute`/`Subscript` operands.
* By FUNCTION: `META`, `ENTRY_META`, `ANY_META` and `POSTING_META` are
dispatched by name and then read `_posting_meta` / `_entry_meta` off
the row. A query calling `meta('key')` names neither column, so
gating on column references alone drops the data it needs. Detected
with a new `query_calls_any_function`, which mirrors
`query_references_column`'s clause coverage and walks the OVER
clause -- the case Copilot caught on #1085.
* By wildcard, which forces on only what `SELECT *` can SHOW. This
table's wildcard emits `meta` but omits `entry` and the underscore
helpers, since `wildcard_hidden` drops the structured entry column to
match beanquery. Forcing all five was the first attempt and left
`SELECT *` with no improvement at all.
Verified by diffing query output against a main-built binary across 17
shapes, including `SELECT *, entry.narration` and
`SELECT * ORDER BY entry.narration`, and re-run after the clippy
refactor rather than assumed. Each of the three gates is confirmed to
fail its own assertion when removed.
Closes #2169
* fix(query): correct the gated-column count and re-attach a doc comment
Review catches on #2174, all three from Copilot.
The gated set is FOUR columns -- entry, meta, _entry_meta, _posting_meta
-- not five. I wrote five in the code comment, the commit message and the
PR body.
Inserting expr_calls_any_function above query_references_column detached
that function's doc comment onto the new one, leaving
query_references_column undocumented and the new helper described by
someone else's prose. Third time I have done this exact thing (#2148,
#2159), and the shape is always the same: adding an item directly above
one that already had a doc comment.
The metadata-function test looped over three of the four dispatched
names, omitting POSTING_META, so a gate that forgot it would have passed.
Confirmed the test now fails when POSTING_META alone is dropped from the
detected list.
* test(query): cover query_calls_any_function directly
Review addition on #2174. The new walker was only exercised through
#postings queries, and two of its arms cannot be reached that way:
`meta('k') BETWEEN ...` type-errors before the gate matters, and window
functions are rejected outright with an explicit FROM #postings. A direct
unit test now covers every clause and every expression shape, mirroring
the sibling test for query_references_column.
Each arm was confirmed to fail the test when made to return false.
Removing an arm outright does not compile: the match is exhaustive with
no catch-all, so a future Expr variant is a build error rather than a
silent false -- worth having, since a false negative here materializes
nothing and meta('k') returns Null with no error.
Also corrects the claim that walking the OVER clause was load-bearing
here. It mirrors expr_references_column so the two stay
interchangeable; this call site cannot reach it.
* docs(query): record the instruction-count measurement
Review addition on #2174. The wall-clock numbers were the only evidence,
and they move with machine load. Callgrind on the profiling harness puts
the combined #2169 + #2173 effect at 457.4M -> 244.2M instructions, -47%,
which does not.
It also closes the loop on the harness gap #2173 fixed: the system-table
shapes added there are exactly the ones that improved, so the harness now
measures the path it previously could not see.
Summary
Closes #1080 (the WASM 49 GB / multi-minute query regression reported by @alensiljak).
The regression was introduced by PR #940 (
fix(query): makebalancea cumulative WHERE-filtered total), which landed just after v0.14.1 was released to npm. PR #940 added two computed BQL columns (balanceandaccount_balance) and built per-postingPostingContextsnapshots holding clonedInventoryviews of both running balances.For a query like
SELECT account WHERE account ~ "^Assets" LIMIT 10against the user's ledger (22k Asset postings, 855 accounts), thecumulative_balanceInventorygrows monotonically — meaning we were cloning a 1000+-positionInventory~2-3 times per posting, producing ~12 GB of allocation churn in WASM linear memory and ~5.8 GB peak heap. The page hung for minutes while the OS paged the WASM memory in and out.The query doesn't reference
balanceoraccount_balance. The entire clone storm was wasted work.Root cause
The pre-fix code at
executor/mod.rs:479-501had one gate (where_clause.is_some()) that fired for any query with a WHERE, regardless of what that WHERE actually referenced:A query with
WHERE account ~ "^Assets"(which has nothing to do withbalance) still paid the per-posting clone cost.Fix
Walk the
SelectQueryAST once at the top ofcollect_postingsvia a newquery_references_columnhelper, then gate the work:When
needs_balanceisfalse:cumulative_balance.clone()cumulative_balance.add()update (no one reads it)cumulative_balance.clone()refreshctx.balancestaysNoneSame gating for
account_balanceviaaccount_balancesmap updates.Queries that DO reference either column keep the exact pre-fix code path — semantics preserved bit-for-bit. All 523 existing query tests pass.
query_references_columnWalks every query part:
Case-insensitive column-name match. Subqueries in FROM are treated as opaque (their inner references don't surface to the outer iterator). Tested with the new
test_query_references_column_covers_all_query_partstest which exercisesbalancein every position (target / WHERE / ORDER BY / GROUP BY / function arg / BETWEEN bound).Expected impact
For the user's specific query (
SELECT account WHERE account ~ "^Assets" LIMIT 10on 22k postings):cumulative_balanceallocation churn is entirely eliminatedFor queries that DO read
balance/account_balance: no change. Semantics, tests, perf all identical to pre-fix.For queries that read neither (the common case for browsing / filtering / projection queries): proportional speedup matching what the user reported on v0.14.1.
Test plan
cargo test -p rustledger-query --all-features— 523 tests pass, including the newtest_query_references_column_covers_all_query_partscargo check --workspace --all-features --all-targets— cleancargo fmt --all -- --check— cleancargo clippy -p rustledger-query --all-features --all-targets -- -D warnings— clean🤖 Generated with Claude Code