Repository navigation
perf(query): stop #postings materializing balances no query reads - #2173
Conversation
`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
There was a problem hiding this comment.
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
SelectQueryintobuild_postings_table(viaget_builtin_table) and gateScanNeeds { 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
#postingsshapes, 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 Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
✅ Compatibility Test Results
What's tested
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.
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.
* 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.
What
build_postings_tablehardcodedScanNeeds { balance: true, account_balance: true, .. }, so everyFROM #postingsquery paid for the per-postingcumulative
Inventoryclones — the #1080 runaway — even when nothingreferenced 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:
SELECT count(account) FROM #postingsSELECT account FROM #postingsSELECT account … WHERE account_balance != 0SELECT count(balance) FROM #postingsSELECT * FROM #postingsSELECT *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%:
SELECT count(account) FROM #postingsSELECT account, balance FROM #postingsThe snapshots are retained
Inventorycopies, so not taking them frees moreproportionally than it saves in time. The second row is the control: a query
that genuinely reads
balanceis 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:
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 bothmistakes produced silently empty balances rather than an error:
where_clause: None. The table is built first and filteredafterwards, so nothing is read "at WHERE time" and both
where_reads_*arefalse.
account_balanceinto every row regardless of theSELECT list, so the table is the output. Gating on
output_references_columnreleased the snapshot before the row was built,and
WHERE account_balance != 0returned zero rows instead of twenty.SELECT *includesbalanceandaccount_balance— thedefault source's
WILDCARD_COLUMNSexcludes both — so a wildcard must forcethem 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_balanceone 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.rsonly exercised the default source, neverFROM #postings— which is how a 7× gap went unnoticed:SELECT count(account) FROM #postingstook 681 ms against 93 ms for the samequery without the
FROM. Adding two system-table shapes took the harness from88.7M to 457.4M instructions, i.e. those two shapes are ~80% of the profile.
The callgrind profile is allocator-dominated —
_int_malloc18.8%,_int_free_chunk6.9%,memcpy5.4%,free5.2%, plusdrop_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:
#postingsstill builds every column regardlessof 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