Skip to content

perf(query): stop #postings materializing balances no query reads - #2173

Merged
robcohen merged 3 commits into
mainfrom
perf/postings-projection
Aug 28, 2026
Merged

robcohen merged 3 commits into
mainfrom
perf/postings-projection

Conversation

@robcohen

@robcohen robcohen commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

What

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.

40k-posting ledger, best of three, against a baseline binary built from the
same commit:

query base this PR
SELECT count(account) FROM #postings 676 ms 442 ms −34%
SELECT account FROM #postings 719 ms 479 ms −33%
SELECT account … WHERE account_balance != 0 746 ms 521 ms −30%
SELECT count(balance) FROM #postings 686 ms 588 ms −14%
SELECT * FROM #postings 1608 ms 1620 ms 0%

SELECT * unchanged by design — a wildcard reads every column.

Memory, which matters more than the time here

Peak RSS on the same 40k-posting ledger, three samples each and stable to
within 0.1%:

base this PR
SELECT count(account) FROM #postings 517 MB 233 MB (−55%)
SELECT account, balance FROM #postings 780 MB 757 MB (−3%)

The snapshots are retained Inventory copies, so not taking them frees more
proportionally than it saves in time. The second row is the control: a query
that genuinely reads balance is essentially unchanged, as it must be.

Constant factor, not a complexity fix

Measured at two workload sizes, because a 4× input should expose a changed
curve:

5k txns 20k txns ratio
base 165 ms 671 ms 4.06
this PR 106 ms 435 ms 4.10

Both linear on a 4× workload. This does not change the complexity class — the
#1080 quadratic was already dealt with elsewhere — it stops paying a constant
that nothing reads.

The gate does not mean what it means on the default path

Reusing collect_postings's computation verbatim was wrong twice, and both
mistakes produced silently empty balances rather than an error:

  • This scan gets where_clause: None. The table is built first and filtered
    afterwards, so nothing is read "at WHERE time" and both where_reads_* are
    false.
  • 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.
  • 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.

How they were caught

Not by the test suite, which passed throughout. By diffing query output
against a baseline binary across ten shapes — two differed, and the
WHERE account_balance one was returning nothing at all.

The new test pins both and was confirmed to fail against each mistake
separately.

Profiling harness had a blind spot

examples/profile_query.rs only exercised the default source, never
FROM #postings — which is how a 7× gap went unnoticed:
SELECT count(account) FROM #postings took 681 ms against 93 ms for the same
query without the FROM. Adding two system-table shapes took the harness from
88.7M to 457.4M instructions, i.e. those two shapes are ~80% of the profile.

The callgrind profile is allocator-dominated — _int_malloc 18.8%,
_int_free_chunk 6.9%, memcpy 5.4%, free 5.2%, plus
drop_glue::<Value> 3.1%.

Left for #2169

This fixes the balance half. The remaining gap to the default path is the
31-column row construction: #postings still builds every column regardless
of projection. Measured contributions — metadata columns are ~65 ms of 681 ms,
so the rest is spread across the string and position columns. That needs the
projection threaded into column construction, which is a larger change than
this one; #2169 stays open for it.

Refs #2169

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

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

Improves performance of the BQL #postings system table by avoiding per-posting running-balance snapshot materialization (Inventory clones) unless the query actually references balance and/or account_balance, aligning the system-table path with the already-gated default SELECT path and preventing the #1080-style runaway allocation cost from being paid unnecessarily.

Changes:

  • Thread the current SelectQuery into build_postings_table (via get_builtin_table) and gate ScanNeeds { balance, account_balance } based on query references, with wildcard (SELECT *) forcing both on.
  • Add an integration test that specifically guards against two previously observed “silently empty balances” failure modes for #postings.
  • Extend the query profiling harness to include #postings shapes, so system-table performance regressions are visible in profiling output.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated no comments.

Show a summary per file
File Description
crates/rustledger-query/src/executor/system_tables.rs Gates #postings running-balance snapshot materialization based on whether the query needs balance / account_balance (including wildcard handling).
crates/rustledger-query/src/executor/mod.rs Threads query context into builtin table construction so #postings can make need-based decisions.
crates/rustledger-query/src/executor/execution.rs Passes the query into get_builtin_table so builtin tables can be query-aware.
crates/rustledger-query/tests/bql_integration_test.rs Adds regression coverage ensuring #postings materializes balances when needed (WHERE on account_balance, and SELECT *).
crates/rustledger-query/examples/profile_query.rs Profiles #postings queries in addition to the default source to catch large perf gaps/regressions.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@codecov

codecov Bot commented Aug 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 48.7ms ± 4.3ms 752.2ms ± 6.3ms 15.4x 55.0 MB / 50.1 MB
investment 72.4ms ± 4.1ms 2816.5ms ± 26.7ms 38.9x 59.1 MB / 58.1 MB
fifo 70.5ms ± 3.6ms 16852.7ms ± 570.5ms 239.2x 61.1 MB / 57.7 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 50.1ms ± 4.4ms 48.7ms ± 4.3ms -2.9% ✅ within noise 55.0 MB → 55.0 MB (-0.1%)
investment 71.7ms ± 1.4ms 72.4ms ± 4.1ms +1.0% ✅ within noise 59.0 MB → 59.1 MB (+0.1%)
fifo 71.3ms ± 3.8ms 70.5ms ± 3.6ms -1.2% ✅ within noise 61.0 MB → 61.1 MB (+0.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 2.7ms, investment 2.0ms, fifo 2.3ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@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

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).
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
robcohen merged commit 78fba7d into main Aug 28, 2026
60 of 61 checks passed
@robcohen
robcohen deleted the perf/postings-projection branch August 28, 2026 14:28
robcohen added a commit that referenced this pull request Aug 28, 2026
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.
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.

2 participants