Skip to content

fix(query): give #entries the five columns bean-query exposes - #2157

Merged
robcohen merged 4 commits into
mainfrom
fix/bql-entries-columns
Aug 26, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/bql-entries-columns

Conversation

@robcohen

@robcohen robcohen commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

Partially closes #2154.

The gap

SELECT * FROM #entries returned 11 columns where bean-query returns 16.

rl (11): id type filename lineno date           flag payee narration             tags links      accounts
bc (16): id type filename lineno date year month day flag payee narration description tags links meta accounts

None of the five needed building. Every name already resolved against #postings, and description is the same "payee | narration" shape that table already produces. The #entries schema just did not list them, so SELECT year FROM #entries -- a query that runs fine under bean-query -- failed here with column 'year' not found.

Verified row by row

Against bean-query 3.2.3 on a ledger mixing opens, a payee transaction, a narration-only transaction, and a note:

bean-query rustledger
open ('open', 2024, 1, 1, None) same
txn with payee ('transaction', 2024, 2, 15, 'Acme Corp | monthly invoice') same
txn without payee ('transaction', 2024, 3, 20, 'narration only') same
note ('note', 2024, 4, 10, None) same

Two behaviours worth calling out, both matching bean-query:

  • Date parts come from the entry's own date, not from a transaction, so they populate for every directive type. bean-query reports year on an open; so do we.
  • description is Null on a non-transaction, consistent with how payee and narration already behave there.

Column order is asserted, not just membership. SELECT * is positional for anyone consuming rows as tuples, so right set / wrong order would still break them.

meta and _entry_meta coexist on purpose

The underscore copy cannot simply be renamed. ENTRY_META resolves through it (execution.rs), and wildcard_hidden uses the underscore prefix to keep helper columns out of SELECT *. So the visible meta is added beside it.

Regression-checked all four halves of that: _entry_meta still answers by name, ENTRY_META / ANY_META still work, meta now resolves, and _entry_meta still does not leak into the wildcard now that a visible meta sits next to it.

The census in #2154 was wrong, and is now corrected

Reviewing this PR turned up a flaw in the measurement that produced #2154. It reported 6 missing columns across 87; the real number was 16.

The fixture used for that census contained only open and transaction directives, so six of the ten tables had zero rows. Selecting a non-existent column from an empty table returns no rows without ever evaluating the column, so it comes back clean. The census tested four tables and reported on ten.

Re-run against a fixture that populates every table, with row counts asserted non-empty first, the remaining gaps after this PR are:

table missing
#balances discrepancy, meta, tolerance
#notes links, meta, tags
#transactions, #prices, #events, #documents, #commodities meta

Each confirmed working under beanquery. #2154 has been updated with the corrected figures.

meta is absent from seven of ten tables, which suggests one cause rather than seven, and it is the same shape this PR handled for #entries. That is worth doing as its own change rather than growing this one.

What is deliberately left

#transactions.meta, the sixth column in #2154, is not in this PR. bean-query carries it as a column but excludes it from SELECT * (7 columns there, not 8). wildcard_hidden keys on the column name alone with no table context, and both call sites take a bare column list, so matching that needs table-aware hiding threaded through the subquery paths.

Adding it visibly would trade a missing column for a wildcard returning 8 where bean-query returns 7 -- a worse bug than the one being fixed. #2154 stays open for it.

Checks

  • New test asserts the full 16-column list in order, that _entry_meta stays out of the wildcard, that date parts populate on an open, and that description is Null there and "payee | narration" on a transaction.
  • Confirmed the test fails before trusting it: deleting the year column produces wildcard must match bean-query's #entries columns and their order.
  • cargo test -p rustledger-query: 178 passed, 0 failed.
  • Clippy clean on local 1.96 and CI's 1.97; workspace builds clean.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`SELECT * FROM #entries` returned 11 columns against bean-query's 16.
Missing: `year`, `month`, `day`, `description`, `meta`.

None of them needed building. Every name already resolved against
`#postings`, and `description` is the same "payee | narration" shape that
table already produces. The `#entries` schema simply did not list them, so
`SELECT year FROM #entries` -- a query that runs under bean-query -- failed
here with `column 'year' not found`.

Column order now matches bean-query position for position, not just as a set.
`SELECT *` is positional for anyone reading rows as tuples, so getting the
membership right and the order wrong would still break them.

Date parts come from the entry's own date rather than from a transaction, so
they are populated for every directive type: bean-query reports `year` on an
`open`, and now so do we. `description` is Null on a non-transaction, matching
how `payee` and `narration` already behave there.

`meta` and `_entry_meta` deliberately hold the same value. The underscore copy
cannot be renamed: `ENTRY_META` resolves through it, and `wildcard_hidden`
uses the underscore prefix to keep helpers out of `SELECT *`. Verified the
hidden spelling still answers, that `ENTRY_META` / `ANY_META` still work, and
that `_entry_meta` still does not leak into the wildcard now that a visible
`meta` sits beside it.

Values checked row by row against bean-query 3.2.3 on a ledger mixing opens,
a payee transaction, a narration-only transaction and a note: identical on
all five columns. The test asserts order and was confirmed to fail with
`year` removed before being trusted.

`#transactions.meta` is left for #2154. bean-query carries it as a column but
excludes it from `SELECT *`, and `wildcard_hidden` keys on the name alone
with no table context. Adding it visibly would trade a missing column for a
wildcard that returns 8 where bean-query returns 7, which is a worse bug than
the one being fixed.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Copilot AI lite review requested due to automatic review settings August 26, 2026 03:42
@robcohen
robcohen requested a review from a team as a code owner August 26, 2026 03:42
@codecov

codecov Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.66667% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...tes/rustledger-query/src/executor/system_tables.rs 96.29% 1 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 updates the #entries system table schema in rustledger-query to match bean-query’s SELECT * FROM #entries output (16 columns, correct order), fixing queries like SELECT year FROM #entries that previously failed due to missing registered columns.

Changes:

  • Expands #entries column list to include year, month, day, description, and visible meta, matching bean-query column order.
  • Populates the new date-part and description fields when building #entries rows, while keeping _entry_meta as a hidden helper column.
  • Adds a regression test asserting the exact wildcard column list/order and validating date parts + description behavior.

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/system_tables.rs Extends and reorders #entries columns to match bean-query; adds row population for year/month/day/description/meta while preserving hidden _entry_meta.
crates/rustledger-query/src/executor/tests.rs Adds a test that pins SELECT * FROM #entries column order and checks date-part + description semantics and wildcard hiding for _entry_meta.

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

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 51.6ms ± 6.3ms 852.6ms ± 3.5ms 16.5x 55.1 MB / 50.0 MB
investment 71.8ms ± 4.8ms 3157.5ms ± 75.6ms 44.0x 59.1 MB / 58.1 MB
fifo 70.4ms ± 3.9ms 15760.0ms ± 378.3ms 223.9x 61.0 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 49.7ms ± 4.9ms 51.6ms ± 6.3ms +3.8% ✅ within noise 55.1 MB → 55.1 MB (+0.2%)
investment 71.3ms ± 2.5ms 71.8ms ± 4.8ms +0.6% ✅ within noise 58.9 MB → 59.1 MB (+0.3%)
fifo 70.5ms ± 3.8ms 70.4ms ± 3.9ms -0.1% ✅ within noise 59.1 MB → 61.0 MB (+3.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 3.6ms, investment 2.4ms, fifo 2.5ms), 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

…ata twice

Review follow-ups on #2157.

`"payee | narration"` was written out twice, once for `#entries` and once for
`#postings`. Both describe the same transaction, so a change to the separator
or the no-payee case on one side would have produced two tables disagreeing
about the same row. Now one `transaction_description`.

`#entries` stored its metadata in two columns, `meta` and `_entry_meta`,
holding the same map. That cost a deep clone per entry on every query that
touches the table, projected or not. The table now carries it once, and
`eval_meta_on_table_row` falls back to the visible `meta` when the helper
column is absent.

The fallback cannot misfire on `#postings`, which is the case that matters:
that table carries `meta`, `_entry_meta` and `_posting_meta` as three
DISTINCT values, so the helper column is present and the fallback is never
reached. Confirmed by comparing against main rather than by reading the code
-- `ANY_META("postkey")` returns `postval` on both, and `META` / `ENTRY_META`
still separate posting metadata from entry metadata on the same row.

`ENTRY_META` and `ANY_META` now resolve on `#entries` too, returning the
transaction's value and Null on directives that carry none.

The test previously asserted `_entry_meta` was addressable on `#entries`.
That was pinning the duplicate storage, so it now asserts the opposite, plus
the part a user actually depends on: the functions that used to read it still
answer.

`SELECT *` unchanged at 31 columns for `#postings` and 16 for `#entries`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…alone

Coverage showed the untested half of the fallback was the branch that takes
the helper column when it IS present. That is the branch the safety argument
rests on, so the claim "cannot misfire on #postings" was the part with no
test behind it.

`#postings` is where a wrong answer would be silent rather than loud: `meta`
there is the POSTING's metadata and `_entry_meta` is the TRANSACTION's, two
different maps on one row. Resolving `ENTRY_META` through `meta` would return
posting metadata and look plausible.

The fixture sets the same key at both levels with different values, so an
accessor reading the wrong column returns the wrong string rather than Null,
and all three of `META`, `ENTRY_META` and `ANY_META` are pinned on the same
row.

Confirmed it bites before trusting it: making the fallback unconditional
fails with `ENTRY_META on #postings must read the transaction's metadata, not
the posting's`.

The one remaining uncovered line is the `_ => (Null, Null, Null)` arm for
date parts. Every directive variant maps to `Value::Date`, so it is
defensive rather than reachable; the alternative is an unwrap, which is
worse.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

Copy link
Copy Markdown
Member Author

On the benchmark flag

The bot marks investment +7.9% 🟡 slower. It is runner noise, and here is the measurement rather than the argument.

Same workload (scripts/gen-profile-workload.py investment, 33k lines), same command the bot runs (rledger check), base and PR binaries built from this branch and main, hyperfine 20 runs / 3 warmup:

base   51.6 ms ±  3.6 ms
pr     50.8 ms ±  3.1 ms

pr ran 1.02 ± 0.09 times faster than base

The PR is marginally faster, and the difference is inside the spread either way.

Two things make the CI figure hard to credit on its own:

  • The PR run's own spread was ±6.5 ms, larger than the 3.1 ms threshold the footer says a difference must clear. The base run's was ±2.4 ms. That is a noisy pair, not a shifted one.
  • Absolute times move more between CI runs than the claimed delta: feat(query): add six missing beanquery BQL functions #2155 measured this shape at 80.6 / 83.9 ms, this run at 72.1 / 77.8 ms. A ~10 ms run-to-run swing is bigger than the 5.7 ms being flagged.

There is also no path for this change to touch that number. The benchmark runs rledger check; every line this PR changes lives in the BQL executor's system-table builders (build_entries_table, directive_to_entry_row, eval_meta_on_table_row, transaction_description), none of which execute during a check.

Refactor is behaviour-preserving

The description extraction touched #postings, so that table was diffed rather than eyeballed. SELECT * FROM #postings is byte-identical between base and PR, and description still renders Acme Corp | monthly invoice and the bare narration in the no-payee case.

Compatibility

Check Compatibility 100%, BQL Compatibility 100%, Full AST Match 100% across 811 files, unchanged.

…low-up

Reading the finished diff end to end turned up a doc describing a design
this branch had already replaced.

`build_entries_table` still explained that `meta` and `_entry_meta` carry the
same value and that the underscore copy cannot be renamed. Both sentences
were true when written and false two commits later: the duplicate column was
removed precisely because storing the map twice cost a deep clone per entry.
A reader would have gone looking for `_entry_meta` in that table's column
list and not found it.

Now describes what is there: metadata in one column, `ENTRY_META` resolving
through the fallback, and why `#postings` still needs its own `_entry_meta`
(there `meta` is the POSTING's metadata and `_entry_meta` the TRANSACTION's,
two different maps on one row).

This is the same defect an automated reviewer caught on #2155, where a
comment justified an argument type using a premise that no longer held. A
stale comment that merely repeats the code is noise; one that explains why
something must be a certain way, after that stopped being true, actively
misleads.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit 398766c into main Aug 26, 2026
66 checks passed
@robcohen
robcohen deleted the fix/bql-entries-columns branch August 26, 2026 13:50
robcohen added a commit that referenced this pull request Aug 26, 2026
Reading the finished diff turned up a doc describing a design this branch
tried and abandoned.

`lookup_dated_at` said the chained lookup needs the rate's date "so it can
value the second leg as of that same moment". That was true of the anchoring
attempt and false once it was backed out: both legs are dated the caller's
way now, and the date is used for RANKING paths rather than for pinning one
leg to the other. A reader would have gone looking for anchoring logic that
is not there.

Same defect as the one an automated reviewer caught on #2155 and I caught on
#2157: a comment that merely restates code is noise, but one explaining why
something must be a certain way, after that stopped being true, actively
misleads.

Also folds two near-verbatim copies of the ranking rationale into one.
`get_chained_price` and `best_chain` each carried the full explanation of
path selection and the stale-chain policy; the caller now points at the
function that owns the logic. Two copies of an argument drift the same way
two copies of a sort do, which is what this branch already fixed in the code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen added a commit that referenced this pull request Aug 26, 2026
)

* test(query): pin the chained-price tie-break, and say what it is

Two of the three items in #2152. The third is left deliberately, below.

`get_chained_price` documents that "intermediates are tried in sorted order
so the result is deterministic when several paths exist". Nothing tested it.
The three existing chained-price tests each build a single chain, so the sort
could have been dropped in a refactor and all three would still pass. Both
`get_chained_price` and `get_chained_latest_price` carry their own copy of
the sort line, so both were unheld.

The new test builds two complete same-dated paths worth deliberately
different amounts, 20.00 via AAA and 50.00 via MMM, and asserts the
alphabetically first wins in both functions. Equal-valued paths would have
passed whichever way iteration went, which is the property being detected.
It also rebuilds the database eight times, because the underlying map is a
hash map and insertion-order luck shows up across constructions rather than
within one run.

Confirmed it bites, once per function: removing the sort from
`get_chained_price` fails it, and so does removing the sort from
`get_chained_latest_price`. Two copies, two independent proofs.

The doc now says what the guarantee is worth. Deterministic is not
principled: 20.00 wins because `AAA` sorts before `MMM`, and nothing in the
output mentions that 50.00 was equally available. A reader of the old
sentence could reasonably assume the choice meant something. It also records
that legs are dated independently, so a 2010 leg times a 2024 leg yields a
current valuation with no diagnostic.

NOT fixing the staleness half. There is no precedent to align with: the only
age concept in the tree is the price-FETCH cache, which governs how long a
downloaded quote is reused rather than whether a rate is too old to value
with. A bound would be new user-facing policy -- someone has to choose a
window, choose error versus warn, and choose whether reports differ -- and
that is a decision to make deliberately, not to smuggle in as a bug fix.
#2152 stays open for it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

* fix(query): rank chained price paths by evidence, not by spelling

Replaces the alphabetical tie-break in chained lookups. When several one-hop
routes exist, the winner is now the one whose OLDEST leg is most recent, then
the one whose legs sit closest together, then the currency name so the order
stays total and independent of hash iteration.

A chain is only as current as its oldest leg. Multiplying a 2010 `A -> B` by
a 2024 `B -> C` yields a figure that looks 2024-dated and rests on 2010 data,
so ranking by that date is what makes the chosen path the best-supported one
rather than the alphabetically luckiest.

The corpus made the case. Chaining is needed in 54 of 761 files across 1152
pairs, and multi-path ambiguity reaches only 2 of them -- but the real one is
`ledger_prices.beancount`, BTC to CNY via USD or USDT, where the answers are
125,856 and 74,763 CNY. A 68% spread, and the paths do not disagree about
BTC: one route's quotes stop 16 months earlier. We returned the right number
because `USD` sorts before `USDT`. A currency named `AUSDT` would have flipped
it.

Both lookups now share one ranking through `best_chain`; the latest-rate
variant used to carry its own copy of the sort and could drift from the
as-of one.

NOT refusing stale chains, after trying it. beancount's `prices.project()`
anchors its second leg to the first leg's date and declines when no rate
existed then, and porting that rule here was wrong for two reasons. It is
built for a different question -- `project` synthesizes a price SERIES at the
base commodity's own dates, while this answers "value as of D" -- and it
refuses when the second leg is merely NEWER, which broke
`test_chained_lookup_uses_newest_rate_per_leg`: valuing an 07-10 close with
an 07-11 rate is ordinary, not suspect. More decisively, a stale DIRECT price
is returned here without complaint, so refusing only the chained case would
be an inconsistent rule rather than a stricter one.

Verified: the era-mixing fixture from #2152 is unchanged in value, the
freshness case now picks the 2020 route over the alphabetically-first 2019
one, and the booked-value gate against beancount reports `known 34, found 34,
new 0` across 761 files, so no divergence moved.

Both properties are pinned and both proofs are real: ranking the name ahead
of freshness fails with `left: 74763, right: 125856`, and removing the name
tie-break fails the stability assertions.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

* docs(query): correct the note left stale by backing out anchoring

Reading the finished diff turned up a doc describing a design this branch
tried and abandoned.

`lookup_dated_at` said the chained lookup needs the rate's date "so it can
value the second leg as of that same moment". That was true of the anchoring
attempt and false once it was backed out: both legs are dated the caller's
way now, and the date is used for RANKING paths rather than for pinning one
leg to the other. A reader would have gone looking for anchoring logic that
is not there.

Same defect as the one an automated reviewer caught on #2155 and I caught on
#2157: a comment that merely restates code is noise, but one explaining why
something must be a certain way, after that stopped being true, actively
misleads.

Also folds two near-verbatim copies of the ranking rationale into one.
`get_chained_price` and `best_chain` each carried the full explanation of
path selection and the stale-chain policy; the caller now points at the
function that owns the logic. Two copies of an argument drift the same way
two copies of a sort do, which is what this branch already fixed in the code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

---------

Co-authored-by: Claude Opus 5 <[email protected]>
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.

meta is missing from seven BQL tables, plus discrepancy/tolerance on #balances and links/tags on #notes

2 participants