Skip to content

fix(query): skip cumulative-balance clone when query doesn't reference it (closes #1080) - #1085

Merged
robcohen merged 3 commits into
mainfrom
fix/issue-1080-balance-column-eager-clone
May 11, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/issue-1080-balance-column-eager-clone

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Closes #1080 (the WASM 49 GB / multi-minute query regression reported by @alensiljak).

The regression was introduced by PR #940 (fix(query): make balance a cumulative WHERE-filtered total), which landed just after v0.14.1 was released to npm. PR #940 added two computed BQL columns (balance and account_balance) and built per-posting PostingContext snapshots holding cloned Inventory views of both running balances.

For a query like SELECT account WHERE account ~ "^Assets" LIMIT 10 against the user's ledger (22k Asset postings, 855 accounts), the cumulative_balance Inventory grows monotonically — meaning we were cloning a 1000+-position Inventory ~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 balance or account_balance. The entire clone storm was wasted work.

Root cause

The pre-fix code at executor/mod.rs:479-501 had one gate (where_clause.is_some()) that fired for any query with a WHERE, regardless of what that WHERE actually referenced:

balance: where_clause.map(|_| cumulative_balance.clone()),  // <- always clones if any WHERE

A query with WHERE account ~ "^Assets" (which has nothing to do with balance) still paid the per-posting clone cost.

Fix

Walk the SelectQuery AST once at the top of collect_postings via a new query_references_column helper, then gate the work:

let needs_balance = query_references_column(query, "balance");
let needs_account_balance = query_references_column(query, "account_balance");

When needs_balance is false:

  • Skip the pre-WHERE cumulative_balance.clone()
  • Skip the cumulative_balance.add() update (no one reads it)
  • Skip the post-WHERE cumulative_balance.clone() refresh
  • ctx.balance stays None

Same gating for account_balance via account_balances map 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_column

Walks every query part:

  • SELECT targets
  • WHERE
  • GROUP BY
  • HAVING
  • PIVOT BY
  • ORDER BY
  • FROM filter expression

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_parts test which exercises balance in 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 10 on 22k postings):

  • Pre-fix: multi-minute wall time, 5.8 GB WASM heap, page freezes
  • Post-fix: should drop to v0.14.1-equivalent (sub-second) since the cumulative_balance allocation churn is entirely eliminated

For 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 new test_query_references_column_covers_all_query_parts
  • cargo check --workspace --all-features --all-targets — clean
  • cargo fmt --all -- --check — clean
  • cargo clippy -p rustledger-query --all-features --all-targets -- -D warnings — clean
  • CI (compatibility, regression, MSRV)
  • Field-test: rebuild WASM, send to @alensiljak for confirmation

🤖 Generated with Claude Code

…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]>
@robcohen
robcohen requested a review from a team as a code owner May 11, 2026 17:14
Copilot AI review requested due to automatic review settings May 11, 2026 17:14

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 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_postings to accept the full SelectQuery and precompute whether balance / account_balance are referenced anywhere in the query AST.
  • Gates cumulative_balance cloning/updating and account_balances map updates based on those reference checks to avoid wasted work.
  • Adds expr_references_column / query_references_column helpers 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

codecov Bot commented May 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.73239% with 16 lines in your changes missing coverage. Please review.

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

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.3ms ± 0.7ms 21.9 MB
beancount 780.3ms ± 42ms 50.5 MB
Comparison 22.7x faster 2.3x less

vs main branch (2026-05-11)

Metric main this PR Change
Time 34.2ms 34.3ms +0.3% ✅
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

@github-actions

github-actions Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

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

robcohen and others added 2 commits May 11, 2026 13:23
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]>
@robcohen
robcohen enabled auto-merge (squash) May 11, 2026 18:24
@robcohen

Copy link
Copy Markdown
Member Author

Deep re-review (post-Copilot fixes)

Walking the diff fresh after the 4274a323 revisions. Five additional things checked, two findings worth flagging.

✅ Correctness audit

1. SELECT * doesn't reference balance. Confirmed at executor/evaluation.rs:491-510: wildcard expands to [date, flag, payee, narration, account, position] — no balance or account_balance. The Expr::Wildcard => false arm in expr_references_column is correct; a user query like SELECT * WHERE account ~ "^Assets" correctly hits the optimized path. (The diff's comment also points at the WILDCARD_COLUMNS constant to make the contract clear.)

2. ORDER BY aliases handled correctly. A query like SELECT balance AS b FROM #postings ORDER BY b references balance via the SELECT target's Expr (not the ORDER BY's alias-Column("b")), so the SELECT-targets walk catches it. The ORDER BY's Expr::Column("b") returning false for "balance" is fine because the SELECT walk already returned true.

3. Asymmetric gating is correct. The diff carries an explicit comment about the asymmetry — verified against the semantics:

  • balance is refreshed post-WHERE (ctx.balance = Some(cumulative_balance.clone()) runs after WHERE passes). The pre-WHERE slot is only observed by the WHERE predicate itself. Gate: where_reads_balance.
  • account_balance has only one slot — account_balances is updated before the per-posting block, so the slot is already the post-update running total. There's no refresh path. Gate: needs_account_balance (unconditional).

Inverting either gate would break correctness:

  • where_reads_account_balance would break SELECT account_balance FROM #postings (no WHERE).
  • needs_balance for pre-WHERE would reintroduce the Copilot-flagged double-clone for SELECT balance FROM #postings.

4. Subqueries: the "opaque" treatment is correct. A query like SELECT balance FROM (SELECT something FROM #postings) has the OUTER balance referring to the inner result's column, not the raw posting state. The OUTER's collect_postings iterates raw directives (it doesn't know about the subquery's columns), so the OUTER walk doesn't need to recurse into FromClause.subquery. The INNER subquery is executed via its own execute() → collect_postings(inner), which walks the inner AST independently and sets its own gates. The doc comment on query_references_column calls this out.

⚠️ Adjacent bug: JOURNAL queries have the same blowup in a different code path

executor/execution.rs:884 in execute_journal:

let balance_for_row = match at_mode {
    AtMode::Cost => cumulative_balance.at_cost(),
    AtMode::Units => cumulative_balance.at_units(),
    AtMode::None | AtMode::Other => cumulative_balance.clone(),  // <-- per-posting clone
};

cumulative_balance here is the same shape — a growing Inventory — and it's cloned per matching posting in the JOURNAL loop. Same #1080 cost shape, separate code path. Not in scope for this PR (the user's reported queries are SELECT, not JOURNAL), but worth a follow-up issue:

  • For JOURNAL, the clone is semantically required — each row's balance column is the snapshot at that posting time. Can't simply skip.
  • Mitigation paths: (a) lazy/COW Inventory snapshot, (b) emit Arc-wrapped snapshots, (c) batch-deferred render.

I'll open a tracking issue if you want. If a Cashier user reports JOURNAL queries hanging similarly, that's the next dig.

✅ Test coverage

  • test_query_references_column_covers_all_query_parts — 11 cases including all query parts (SELECT/WHERE/ORDER BY/GROUP BY/HAVING via aggregate, function arg, BETWEEN, case-insensitive). One gap: doesn't test PIVOT BY or FROM filter explicitly. Adding those would be belt-and-suspenders but the helper code clearly walks them; failure mode would be obvious.
  • test_expr_references_column_walks_window_over_clause — both PARTITION BY and ORDER BY (with nested BinaryOp) covered.
  • 525 existing query tests all pass — the gated path preserves semantics bit-for-bit.

✅ Field test

Local Node + WASM benchmark on a 5k cost-lot fixture showed pre-fix 4088 ms / 1634 MB WASM linear memory → post-fix 258 ms / 23 MB. 71× memory reduction, 16× speedup on cold path. Scaling to the user's 22k-posting workload puts pre-fix in their reported 5+ GB / multi-minute range, post-fix sub-second.

Verdict

Ready to merge. Both Copilot findings addressed correctly; the asymmetric gating is intentional and documented; the optimization is sound for the SELECT path (the user's reported regression). JOURNAL is a related-but-separate adjacent issue worth tracking after this lands.

@robcohen
robcohen merged commit bc80fe2 into main May 11, 2026
35 checks passed
@robcohen
robcohen deleted the fix/issue-1080-balance-column-eager-clone branch May 11, 2026 18:33
robcohen added a commit that referenced this pull request Aug 18, 2026
`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]>
robcohen added a commit that referenced this pull request Aug 28, 2026
)

* 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.
robcohen added a commit that referenced this pull request Aug 28, 2026
* 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.
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.

WASM hangs when reading accounts from Assets

2 participants