Skip to content

perf(query): skip #postings columns the query cannot observe - #2174

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

robcohen merged 4 commits into
mainfrom
perf/postings-column-projection

Conversation

@robcohen

@robcohen robcohen commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

What

Four of #postings' 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.

40k-posting ledger, best of three, against a binary built from main:

query before after
SELECT count(account) FROM #postings 433 ms / 227 MB 240 ms / 131 MB
SELECT account FROM #postings 484 ms / 229 MB 296 ms / 133 MB
SELECT meta('k') FROM #postings 482 ms / 228 MB 290 ms / 135 MB
SELECT * FROM #postings 1617 ms / 844 MB 1419 ms / 766 MB

With #2173 already merged, the first is 681 ms / 517 MB → 240 ms / 131 MB:
−65% time, −75% peak RSS.

Why only four columns

Measured, not guessed. Stubbing both StringSet columns moved 443 ms to
437 ms — noise. The other 26 are cheap enough that gating them would cost more
in review surface than it saves. A floor experiment (one real column of 31)
sits at 227 ms, so these four recover nearly all of what is available.

Three ways to reach a gated column

Each fails silently when the gate is too tight — a missed reader gets Null,
not an error — so each is pinned by a test:

  • 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 what it needs. New query_calls_any_function mirrors
    query_references_column's clause coverage, including the OVER clause —
    though that arm is not reachable from #postings, which rejects window
    functions outright; it is there so the two helpers stay interchangeable.

    The match is exhaustive with no catch-all, so a future Expr variant
    fails to compile rather than silently returning false. Two arms
    (Between, Window) cannot be exercised end-to-end here —
    meta('k') BETWEEN … type-errors first — so a direct unit test covers
    every shape, and each was confirmed to fail when its arm is made to
    return false.

  • By wildcard, which forces on only what SELECT * can actually SHOW.
    This table's wildcard emits meta but omits entry and the underscore
    helpers, because wildcard_hidden drops the structured entry column to match
    beanquery. Forcing all four on was my first attempt and left SELECT * with
    no improvement at all; narrowing it to what the wildcard emits is what
    made that row faster too.

Instruction counts, independent of the clock

examples/profile_query.rs under callgrind, same 3000-directive workload, on
the system-table shapes #2173 added to it:

pre-#2173:  457,416,198 Ir
this PR:    244,239,383 Ir      -47%

Instruction counts do not move with machine load or allocator behaviour, so
this corroborates the wall-clock table above rather than repeating it. It also
closes the loop on the harness gap: the shapes added in #2173 are exactly the
ones that improved.

Verification

  • Query output diffed against a main-built binary across 17 shapes,
    including SELECT *, entry.narration and
    SELECT * ORDER BY entry.narration — the cases where a wildcard and a named
    reference interact. All identical, with a negative control confirming the
    comparison discriminates.
  • Re-run after the clippy refactor rather than assuming a refactor preserves
    behaviour.
  • Each of the three gates confirmed to fail its own assertion when removed,
    checked one at a time.
  • Booked-value gate clean (known 34, found 34, new 0); corpus_parity
    divergences still exactly 20, matching main (pre-existing corpus_parity diverges under workspace feature unification when the debug component wasm is present #1809).
  • clippy at CI's 1.97, fmt, typos, rustdoc clean.

Closes #2169

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

codecov Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.00000% with 18 lines in your changes missing coverage. Please review.

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

📢 Thoughts on this report? Let us know!

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

Optimizes the #postings system table materialization in rustledger-query by skipping expensive-to-build columns (structured entry object and metadata maps) when the query cannot observe them, while adding integration tests to pin the “silent Null” failure modes these gates can introduce.

Changes:

  • Added query analysis to detect when #postings must materialize entry, meta, and hidden metadata helper columns based on column references, wildcard expansion, and metadata-function calls.
  • Introduced query_calls_any_function / expr_calls_any_function to detect function-based reachability (e.g., META('k')) across all relevant query clauses (including window OVER clauses).
  • Added an integration test that asserts gated columns are still materialized when reachable via function call, attribute access, or wildcard.

Reviewed changes

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

File Description
crates/rustledger-query/src/executor/system_tables.rs Gates construction of #postings structured entry + metadata columns based on query observability (wildcard, column refs, and metadata-function calls).
crates/rustledger-query/src/executor/mod.rs Adds function-call detection helpers (expr_calls_any_function, query_calls_any_function) to support system-table gating decisions.
crates/rustledger-query/tests/bql_integration_test.rs Adds an integration test to pin reachability paths to gated columns and prevent silent-Null regressions.

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

@github-actions

github-actions Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 47.9ms ± 3.6ms 751.3ms ± 8.6ms 15.7x 55.1 MB / 50.2 MB
investment 72.1ms ± 3.6ms 2937.1ms ± 95.7ms 40.8x 58.9 MB / 58.0 MB
fifo 70.3ms ± 5.5ms 16323.7ms ± 195.1ms 232.2x 61.1 MB / 57.7 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 47.7ms ± 2.6ms 47.9ms ± 3.6ms +0.5% ✅ within noise 55.1 MB → 55.1 MB (-0.0%)
investment 72.0ms ± 2.7ms 72.1ms ± 3.6ms +0.1% ✅ within noise 58.9 MB → 58.9 MB (-0.1%)
fifo 70.0ms ± 2.4ms 70.3ms ± 5.5ms +0.5% ✅ 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.0ms, investment 2.0ms, fifo 2.7ms), 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

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.
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.
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
robcohen merged commit 82b5a9d into main Aug 28, 2026
60 of 61 checks passed
@robcohen
robcohen deleted the perf/postings-column-projection branch August 28, 2026 19: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.

perf: #postings builds all 31 columns per row regardless of projection (~600ms for 40k postings)

2 participants