Skip to content

fix(query): expose meta on five system tables without breaking SELECT * - #2161

Merged
robcohen merged 3 commits into
mainfrom
fix/bql-meta-columns
Aug 27, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/bql-meta-columns

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

SELECT meta FROM #balances — and #notes, #events, #documents,
#commodities — failed, because the column did not exist. bean-query answers
all five. This adds them.

Why it isn't a one-line column addition

bean-query's wildcard is not uniform about meta. Measured against
bean-query 3.x on a fixture where every table has rows:

table bean-query SELECT * meta in wildcard?
#balances date, account, amount, tolerance, discrepancy no
#notes date, account, comment, tags, links no
#events date, type, description no
#documents date, account, filename, tags, links no
#commodities meta, date, name yes, first

Registering meta as an ordinary column everywhere — the obvious
implementation — trades one missing column for four wildcards that return a
column more than bean-query. That is the worse bug, and it is what the first
cut of this change did; test_balances_table_select_all caught it.

The split looks arbitrary because it is. beanquery derives #commodities'
columns from the Commodity namedtuple, whose first field is meta, while
the other tables carry hand-written column lists. Every set in the table
above was read off bean-query rather than reasoned about, precisely because
no rule predicts it.

How

Table gains a per-table hidden list: columns omitted from SELECT * but
still addressable by name. That is not a workaround — it is bean-query's own
behavior, which answers SELECT meta FROM #notes while omitting meta from
SELECT * on that same table (verified, with a negative control confirming a
genuinely absent column raises instead).

Executor::wildcard_hidden now combines that per-table list with the
existing name-based rule (_-prefixed helpers and entry). A name-only rule
cannot express the split above.

Also: #entries disagreed with #documents

#entries emptied tags/links for every non-transaction. A document's tags
do survive into our model — SELECT tags FROM #documents returned them — so
the two tables reported different tags for the same directive.

A column-presence census cannot see this class of bug: tags is
registered on #entries; it was just wrong for every directive except
transactions.

Result

SELECT * parity, same fixture: 6 of 10 tables match, up from 5.
#commodities goes from mismatched to exact; #events and #documents are
preserved rather than regressed.

The four that still differ are all pre-existing and none are touched here:
#postings (31 columns vs 5) and #accounts (extra currencies, booking),
plus the two gaps below.

Deliberately left open

Neither is reachable from directive data, so neither belongs in this PR:

Both are documented at the point where a reader would otherwise assume an
oversight.

Verification

Refs #2154

`SELECT meta FROM #balances` (and #notes, #events, #documents,
#commodities) failed: the column simply did not exist. bean-query
answers all five.

Adding the column naively regresses something worse, though. bean-query's
wildcard is not uniform about `meta` -- it OMITS the column from
`SELECT *` on #balances/#notes/#events/#documents, and INCLUDES it, in
first position, on #commodities. Registering `meta` as an ordinary column
everywhere would trade a missing column for four wildcards that return
one column more than bean-query, which is the worse bug.

The split looks arbitrary because it is: beanquery derives #commodities'
columns from the `Commodity` namedtuple, whose first field is `meta`,
while the other tables carry hand-written column lists. Every set here
was read off bean-query 3.x rather than reasoned about.

So `Table` gains a per-table `hidden` list -- columns omitted from
`SELECT *` but still addressable by name, which is exactly bean-query's
own behavior. `Executor::wildcard_hidden` now combines that list with
the existing name-based rule (`_`-prefixed helpers and `entry`).

Also fixes #entries, which emptied tags/links for every non-transaction.
A document's tags survive into our model and `SELECT tags FROM #documents`
returned them, so #entries and #documents disagreed about the same
directive. A column-presence census cannot see this: `tags` IS registered
on #entries, it was just wrong for all but transactions.

#commodities' wildcard goes from mismatched to exact; #events and
#documents are preserved rather than regressed. Verified against
bean-query on a fixture where every table has rows -- a wildcard against a
zero-row table still reports its header, which is how an earlier column
census under-reported by ten columns.

Both new tests were confirmed to fail on a mutation of the behavior they
pin before being trusted.

Two gaps stay open, neither reachable from directive data:
`#balances.discrepancy` is computed by the balance checker, not stored;
`#notes` tags/links are dropped by our `Note` model (#2160).

Refs #2154
@robcohen
robcohen requested a review from a team as a code owner August 27, 2026 03:38
Copilot AI lite review requested due to automatic review settings August 27, 2026 03:38
@codecov

codecov Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.18072% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...tes/rustledger-query/src/executor/system_tables.rs 91.83% 4 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

This PR improves BQL system-table compatibility with upstream bean-query by making the meta column selectable on five system tables while preserving bean-query’s per-table SELECT * wildcard behavior (i.e., meta is still omitted from the wildcard on some tables, but included on #commodities).

Changes:

  • Added a per-table hidden column list to support columns that are selectable by name but omitted from SELECT *.
  • Exposed meta on #balances, #notes, #events, #documents, and #commodities, and ensured wildcard expansion matches the intended per-table behavior.
  • Fixed #entries to retain tags/links for document directives (so #entries doesn’t disagree with #documents for the same directive).

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
crates/rustledger-query/tests/bql_integration_test.rs Updates/extends integration coverage for per-table wildcard behavior and explicit meta selection.
crates/rustledger-query/src/executor/types.rs Extends Table with a hidden column list and builder helper to omit columns from SELECT *.
crates/rustledger-query/src/executor/system_tables.rs Adds meta (and tolerance on #balances) to relevant system tables; ensures meta is hidden from wildcard where required; fixes #entries document tags/links.
crates/rustledger-query/src/executor/execution.rs Threads per-table hidden-column behavior through wildcard expansion for both column-name resolution and row evaluation.
Suppressed comments (1)

crates/rustledger-query/tests/bql_integration_test.rs:6571

  • This assertion failure message says the wildcard "drifted from bean-query", but the expected column lists in this test aren’t full bean-query parity (they exclude known gaps like discrepancy / note tags+links). Consider updating the message so it accurately describes what’s being pinned (meta visibility / current expected wildcard).
        assert_eq!(
            result.columns, expected,
            "SELECT * FROM {table} drifted from bean-query"
        );

💡 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 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 48.2ms ± 5.5ms 736.7ms ± 15.0ms 15.3x 55.1 MB / 50.1 MB
investment 71.4ms ± 2.7ms 2919.6ms ± 21.9ms 40.9x 59.0 MB / 58.0 MB
fifo 71.6ms ± 3.8ms 17299.0ms ± 1011.4ms 241.7x 63.2 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 46.1ms ± 1.1ms 48.2ms ± 5.5ms +4.5% ✅ within noise 55.2 MB → 55.1 MB (-0.1%)
investment 72.4ms ± 2.4ms 71.4ms ± 2.7ms -1.4% ✅ within noise 59.1 MB → 59.0 MB (-0.1%)
fifo 73.9ms ± 4.5ms 71.6ms ± 3.8ms -3.2% ✅ within noise 61.0 MB → 63.2 MB (+3.5%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 2.5ms, investment 1.6ms, 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 catch (#2161). The test comment said every expected `SELECT *`
set "was read off bean-query 3.x", but two of the five are not
bean-query's sets: #balances omits `discrepancy` and #notes omits
tags/links, because our model cannot produce either yet.

The failure message made it worse. Adding `discrepancy` -- the obvious
next step on #2154 -- would have failed this test with "drifted from
bean-query" while the table moved TOWARD bean-query. A tripwire pointed
at the follow-up work, phrased to make the implementer think they broke
something.

The known gap is now data, so the message can distinguish the two cases:
an exact-parity table still reports drift, while a table with a recorded
gap says what bean-query also returns and to update the expectation.
Both branches were rendered by mutation before being trusted.

Widen the fixture to two directives per kind as well. Each of these
tables sorts its rows, and a one-row table never runs the comparison
closure -- so the comparators this PR edited were never actually
executed.
Self-review catch (#2161). `with_hidden` accepted any string. Hiding a
name the table does not have is a silent no-op, so a typo would leave the
column in `SELECT *` -- precisely the failure this mechanism exists to
prevent, and invisible unless a test asserts the full wildcard set of
that exact table.

A debug assertion turns it into a panic naming both the bad entry and the
available columns. Confirmed to fire by misspelling #notes' entry as
"metaa" before being trusted.
@robcohen
robcohen enabled auto-merge (squash) August 27, 2026 13:00
@robcohen
robcohen merged commit bd71b1c into main Aug 27, 2026
60 checks passed
@robcohen
robcohen deleted the fix/bql-meta-columns branch August 27, 2026 13:23
robcohen added a commit that referenced this pull request Aug 27, 2026
Self-review catch (#2165). The comment claimed sorting by date alone
"reproduces beancount's (date, lineno) entry order". That holds within
one file and breaks across an `include`: beancount compares the raw line
number without regard to which file it came from, so line 1 of an
included file sorts ahead of line 3 of its parent, while we keep each
file's directives together.

Verified against `main`, which orders these the same way -- the gap is
pre-existing and neither caused nor fixed here. Tracked as #2166.

The comment also still said `sort_by` after clippy moved the code to
`sort_by_key`.

Same defect class Copilot caught on #2161: a comment claiming more
bean-query parity than the code delivers.
robcohen added a commit that referenced this pull request Aug 27, 2026
…es (#2165)

* fix(query): keep source order in five system tables, as bean-query does

`#balances`, `#commodities`, `#events`, `#notes` and `#documents` sorted
by `(date, account|type|name)`. beancount orders entries by
`(date, lineno)`, so bean-query returns rows sharing a date in the order
they were written, and ours came back reordered:

    2020-02-05 event "zeta" "z"
    2020-02-05 event "beta" "b"

    bean-query:  zeta, beta      rledger (before):  beta, zeta

Sorting by date alone fixes it. `sort_by_key` is stable and
`resolved_directives` yields source order, so the result is exactly
`(date, lineno)` -- which is why `#entries` and `#transactions`, which
never applied a secondary key, already agreed.

`#prices` is deliberately NOT changed, though it has the same shape. Its
rows come from `price_db`, whose outer map is an `FxHashMap` keyed by
base currency: iteration is grouped by currency in arbitrary order and no
source position survives. The secondary key is the only thing making that
table deterministic, so dropping it would trade a wrong-but-stable order
for an unstable one. `test_prices_table_deterministic_ordering` caught
this after I had already changed it, and an empirical check against
bean-query had passed by coincidence on a two-currency fixture.

`#accounts` is also unchanged and is a separate problem: it is built from
an `FxHashMap`, so it has no source order to restore, and it diverges
from bean-query more deeply than ordering (bean-query's `open` column is
a full `Open(...)` repr; ours is a date, plus we carry two extra
columns).

The two ordering tests that pinned the old behavior now pin the new one.
They still test determinism -- just anchored to the source rather than to
the name.

Closes #2163

* docs(query): scope the source-order claim to a single file

Self-review catch (#2165). The comment claimed sorting by date alone
"reproduces beancount's (date, lineno) entry order". That holds within
one file and breaks across an `include`: beancount compares the raw line
number without regard to which file it came from, so line 1 of an
included file sorts ahead of line 3 of its parent, while we keep each
file's directives together.

Verified against `main`, which orders these the same way -- the gap is
pre-existing and neither caused nor fixed here. Tracked as #2166.

The comment also still said `sort_by` after clippy moved the code to
`sort_by_key`.

Same defect class Copilot caught on #2161: a comment claiming more
bean-query parity than the code delivers.

* test(query): cover the date sort's one real path, and describe it correctly

Self-review catch (#2165). Two related problems.

The comments explained the fix as "we sort by date, stability preserves
source order". That is not the mechanism. The loader already delivers
directives in beancount's (date, SORT_ORDER, lineno) order -- `#entries`
never sorts and still comes back ordered, and a file declaring five kinds
on one date in reverse order still queries back in SORT_ORDER. So on the
loader path the sort is a no-op. The bug was never a missing sort; it was
an extra one, a secondary key re-ordering rows that were already right.

The sort does real work only when an `Executor` is built directly from a
caller-supplied slice, as the tests do. Nothing covered that: deleting
the `#notes` sort outright passed the entire suite. The new test builds
out-of-date-order directives by hand and is confirmed to fail when the
sort is removed from #notes, #commodities and #events.

Verified against bean-query that mixed directive kinds sharing a date
already agree, which the PR asserted but had not checked.

* test(query): cover all five sorts, not three

Self-review catch (#2165). The test added in the previous commit to close
a coverage gap closed it only partially: it exercised #notes,
#commodities and #events, so deleting the #balances or #documents sort
still passed all 407 tests.

Each of the five is now confirmed individually -- removing any one sort
fails this test, checked one at a time.

* docs(query): record the include-order divergence as a choice, not a gap

#2166 investigated and closed as working-as-intended. The comment said
the cross-file gap was "tracked separately", which reads as pending work.
It is a deliberate divergence.

beancount sorts by raw `lineno` with no record of which file it came
from, so adding two comment lines to an included file reorders query
results. Measured across 0, 1 and 2 comment lines: bean-query flips at
two, ours is stable at all three. Replicating that would make row order
depend on incidental formatting of a file the query does not name.

Within a single file `lineno` is meaningful, which is why #2163 matched
bean-query and this does not.
robcohen added a commit that referenced this pull request Aug 27, 2026
…2167)

* fix(query): give #entries.meta its source keys, and empty meta a map

Two divergences from bean-query, both in how metadata reaches a query.

`#entries.meta` dropped `filename` and `lineno`. bean-query carries them
alongside the user's keys there. `#postings` already did this via
`augmented_meta`; `#entries` had the same source location in scope and
did not use it.

The augmentation belongs on `#entries` specifically. bean-query's
per-table `meta` columns -- #notes, #balances, #events, #documents,
#commodities -- exclude `filename`/`lineno`, which is verified here, so
moving this into the shared conversion would break the five tables #2161
brought into agreement. A regression check confirms those five still
match bean-query without the source keys while #entries has them.

Second, an absent metadata block produced `Null` where bean-query
produces `{}`. Those are distinguishable in bean-query -- it renders Null
as an empty CSV field -- so `meta IS NULL` answered true where
bean-query answers false.

Not replicated: bean-query also injects `__tolerances__` into
`#entries.meta`, its internal per-currency inference cache. That is an
implementation detail rather than ledger content, and exposing it would
put beancount's internals in user query results.

Neither fix was covered: reverting either passed the whole suite before
these tests. Both are confirmed to fail against their unfixed code.

* test(query): pin the meta scoping from both sides

Review catch on #2167. The empty-metadata test asserted only that the
value was not Null. That would still pass if per-table `meta` picked up
the synthetic `filename` / `lineno` keys -- the exact regression this
change's scoping exists to prevent. It now asserts the value IS an empty
map, and the #entries test inspects the map rather than a Debug string.

Adds the missing test for the split itself: the same directive, through
the same executor, must carry the source keys in `#entries.meta` and must
not carry them in `#notes.meta`.

Both directions confirmed by mutation. The first attempt at the
per-table direction passed `None` as the location, which `augmented_meta`
early-returns on, so it changed nothing and proved nothing; injecting the
keys inside the shared `metadata_to_value` is the realistic regression
shape and does fire the assertion.
robcohen added a commit that referenced this pull request Aug 29, 2026
…data

Third review pass on #2181 found no defect; this locks in what it
checked.

The same transaction is visible through `#transactions.meta`,
`#entries.meta` and `#postings._entry_meta`. `#entries` adds
`filename`/`lineno` and the other two do not -- that split is
bean-query's and is already asserted -- but the user's own keys are one
fact and must not differ by which table you ask.

Nothing tested that. A per-table census cannot see it either: every
column involved is present in every table, so the disagreement is in the
values. That is exactly how #entries and #documents came to report
different tags for one directive (#2161).

Confirmed the assertion fails when `#entries.meta` is made to drop the
user's keys.
robcohen added a commit that referenced this pull request Aug 29, 2026
* feat(query): make meta selectable on #transactions

The last of #2154's eleven columns. bean-query answers
`SELECT meta FROM #transactions`; we returned nothing. Its `SELECT *`
stays at seven columns, so this is wildcard-hidden -- the same split
#2161 established for the other five per-table `meta` columns, and it
means no existing output changes.

User keys only. bean-query's per-table `meta` excludes `filename` and
`lineno`; only `#entries` carries them (#2162), so this must not route
through `augmented_meta`.

A census of all 55 columns bean-query exposes across its ten system
tables now finds three unselectable here, and all three need model
changes rather than schema entries:

  #notes.tags, #notes.links   Note drops them at parse time (#2160)
  #balances.discrepancy       the balance checker computes it and does
                              not store it on the directive (#2180)

#2180 is filed as part of this, and the comment in `build_balances_table`
that pointed at #2154 for `discrepancy` now points there instead, so the
reference survives #2154 closing.

The test asserts both halves -- selectable by name, absent from the
wildcard -- and that the map carries no source keys. That last assertion
needed a source-mapped executor to mean anything: with a plain
`Executor::new` the location is None, `augmented_meta` returns its input
unchanged, and routing this column through it passed the test. It fails
now.

Closes #2154

* test(query): cover the plain executor path too

Self-review catch on #2181. The test was switched to `new_with_sources`
so the "no source keys" assertion could actually fail -- with a plain
`Executor::new` the location is None and `augmented_meta` is a no-op.
That fixed one gap and opened another: the plain path is what wasm and
the FFI use, and it was then covered by nothing.

Both are asserted now. All four ways to get the column wrong -- dropping
it, making it wildcard-visible, routing it through `augmented_meta`,
nulling the value -- fail the test, checked one at a time.

* docs(query): record what the unconditional meta column costs

* test(query): pin that three tables agree about one transaction's metadata

Third review pass on #2181 found no defect; this locks in what it
checked.

The same transaction is visible through `#transactions.meta`,
`#entries.meta` and `#postings._entry_meta`. `#entries` adds
`filename`/`lineno` and the other two do not -- that split is
bean-query's and is already asserted -- but the user's own keys are one
fact and must not differ by which table you ask.

Nothing tested that. A per-table census cannot see it either: every
column involved is present in every table, so the disagreement is in the
values. That is exactly how #entries and #documents came to report
different tags for one directive (#2161).

Confirmed the assertion fails when `#entries.meta` is made to drop the
user's keys.
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