Skip to content

fix(query): a posting column in FROM filters rows, and is an error in PRINT - #2523

Merged
robcohen merged 8 commits into
mainfrom
fix/bql-from-posting-column
Oct 9, 2026
Merged

robcohen merged 8 commits into
mainfrom
fix/bql-from-posting-column

Conversation

@robcohen

@robcohen robcohen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

What

A posting column in a BQL FROM filter now filters rows on SELECT, BALANCES and JOURNAL, and is an error in PRINT, per the decision on #2414. Entry-level filters keep or drop whole transactions, as before.

evaluate_from_filter built its context with posting_index: 0, so the filter was evaluated once per transaction against its first posting.

Behavior

On the decision's ledger (the issue repro plus a second rent payment on Liabilities:Card):

Query beanquery 0.2 beancount 2.3.6 main this PR
SELECT date, account, position FROM account ~ 'Bank' 3 Assets:Bank rows error 2 rows, one Income:Salary 3 Assets:Bank rows
SELECT sum(position) FROM account ~ 'Bank' 1674.25 USD error blank 1674.25 USD
BALANCES FROM account ~ 'Bank' Assets:Bank 1674.25 USD error Assets:Bank 3000.00, Income:Salary -3000.00 Assets:Bank 1674.25 USD
PRINT FROM account ~ 'Bank' error: column "account" not found in table "entries" error prints every open and 2 transactions error naming the column and has_account()
JOURNAL 'Bank' FROM account ~ 'Bank' 3 rows, balance to 1674.25 error 1 row 3 rows, balance to 1674.25
FROM account ~ 'Bank' OPEN ON 2024-02-01 summary row + 1 error wrong summary row + 1
FROM has_account('Bank'), narration ~ ... whole entries same same same

How

  • from_filter_reads_postings (allowlist of entry columns) decides up front whether a FROM filter is entry-level. An entry-level filter is evaluated once per transaction, as before. Any other filter is evaluated on each posting, with that posting's index and the directive index. It is joined to WHERE with AND after OPEN/CLOSE/CLEAR have rewritten the stream (beanquery compiler.py, _select: c_where = EvalAnd([c_from_expr, c_where])). The allowlist fails safe: an entry column missing from it only costs one evaluation per posting, with the same answer. A drift-guard test (from_filter_column_lists_match_the_executor) pins both hand-kept lists. It takes the row evaluator's own match arms plus the #postings and #entries schemas, evaluates every column on two postings that differ in everything, and requires two things: a column is on the entry list exactly when its values agree, and POSTING_ONLY_COLUMNS is exactly the posting-row columns that #entries lacks. I mutation-checked it in three directions.
  • scan_postings still replays a transaction through the booking engine when any of its postings passes, so account_balance stays the account's own running balance. Only the passing postings become rows, and only they add to balance.
  • BALANCES is beanquery's SELECT account, SUM(position) ... GROUP BY account. An account whose postings all match keeps its booked total (AVERAGE pools stay realized as booking realizes them, [Bug]: BQL BALANCES shows unmerged lots and a dangling negative for AVERAGE-booked accounts #1985). An account with only some matching sums those postings, as SUM(position) does, AVERAGE merge included. That code now shares account_is_average with SUM. A test pins the two as equal.
  • JOURNAL applies the row filter together with its account match.
  • PRINT rejects a filter that reads a posting-only column (beanquery's postings columns that its entries table lacks, plus rledger's units, cost, account_balance, has_cost). The check runs before anything else, so it also fires on an empty ledger, as beanquery's compiler does.

Found and fixed on the way (same function)

  • FROM year > 2014 / FROM month < 3: the YEAR/MONTH fast arms returned !matches for every operator other than =, so > read as !=. On example.beancount, SELECT count(*) FROM year > 2014 gave 2327; beanquery gives 1193, and so does this PR. The arms now take only = / !=.
  • FROM id counted 0, because the context had no directive index. It now counts every row, as beanquery does.
  • An entry filter on a transaction without postings panicked (index out of bounds) in evaluate_column and META(), e.g. PRINT FROM narration ~ 'empty'. A posting column now reads an empty posting there. Both bean-query versions print the entry.

Verification

  • Sweep of SELECT count(*) FROM <expr> on example.beancount against beanquery 0.2. All of these agree: payee narration date year flag tags account position number cost_number id meta type description, number > 0, currency = 'USD', cost_number > 100, year = 2014, price IS NOT NULL. This closes the fix(query): a table name can end a subquery or a statement #2437 gap: number 3549 → 3513, cost_number 421 → 238, id 0 → 3549. links is the adjudicated empty-aggregate quirk (beanquery#1055).
  • Every row of the decision's table, checked against both oracles (uv run --with beancount --with beanquery bean-query, uv run --python 3.11 --with beancount==2.3.6 bean-query). Also checked: OPEN ON, CLOSE ON ... CLEAR, BALANCES ... OPEN ON (with the summary Equity accounts), BALANCES FROM number < 0, SELECT balance FROM number < 0, meta('pk') as posting metadata, JOURNAL FROM number > 0, bare FROM number, a subquery FROM (SELECT account FROM number), and the empty ledger (SELECT/BALANCES empty, PRINT error).
  • New crates/rustledger-query/tests/from_posting_column_filters_rows.rs, 9 tests with expected values from beanquery. All 9 fail with the source changes reverted.
  • cargo test -p rustledger-query --all-features: 818 passed, 0 failed. cargo clippy --workspace --all-features --all-targets -D warnings: clean. cargo doc -D warnings -p rustledger-query: clean.

Divergences

None registered. beancount 2.3.6 rejects every posting column in FROM, and on SELECT/BALANCES/JOURNAL this PR follows beanquery 0.2, which rledger targets. scripts/compat-bql-test.py has no entries about FROM posting columns or PRINT. The AVERAGE BALANCES test is rledger's own: beancount does not book AVERAGE.

Not in this PR

Closes #2414

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

… PRINT

A FROM filter expression was evaluated once per transaction against its
first posting, so `FROM account ~ 'Bank'` kept the transactions whose
first posting was the bank's, with every posting of them.

- SELECT, BALANCES and JOURNAL: a FROM filter that reads a posting
  column is a row filter, joined to WHERE with AND after OPEN/CLOSE/CLEAR
  rewrote the stream, as beanquery 0.2 compiles it. BALANCES keeps an
  account's booked total when all of its postings match and sums the
  matching ones otherwise, as SUM(position) does.
- PRINT: a posting column in FROM is an error pointing at has_account(),
  as both bean-query versions reject it.
- Entry filters keep or drop whole transactions as before. `FROM year > N`
  and `FROM month < N` no longer read as `!=`, `FROM id` sees the
  directive index, and a transaction without postings no longer panics.

Closes #2414

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner October 8, 2026 16:58
@codecov

codecov Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.87500% with 21 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-query/src/executor/evaluation.rs 71.64% 19 Missing ⚠️
...es/rustledger-query/src/executor/functions/util.rs 75.00% 1 Missing ⚠️
crates/rustledger-query/src/executor/mod.rs 98.14% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 39.5ms ± 2.8ms 569.2ms ± 19.5ms 14.4x 51.1 MB / 50.1 MB
investment 60.3ms ± 0.9ms 2106.1ms ± 12.6ms 35.0x 57.4 MB / 58.2 MB
fifo 59.4ms ± 4.7ms 12033.4ms ± 144.8ms 202.6x 55.2 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 38.8ms ± 0.9ms 39.5ms ± 2.8ms +1.6% ✅ within noise 51.1 MB → 51.1 MB (-0.0%)
investment 59.4ms ± 0.8ms 60.3ms ± 0.9ms +1.5% ✅ within noise 57.2 MB → 57.4 MB (+0.4%)
fifo 58.5ms ± 1.2ms 59.4ms ± 4.7ms +1.5% ✅ within noise 55.3 MB → 55.2 MB (-0.2%)

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

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 819
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

FROM_ENTRY_COLUMNS decides whether a FROM filter is read once per
transaction or per posting, and POSTING_ONLY_COLUMNS which columns
PRINT rejects. Both are kept by hand. A posting column added to the
first list would bring #2414 back.

The new test reads the row evaluator's own match arms (via include_str!)
and the executor's #postings and #entries schemas. It evaluates every
column on both postings of a transaction whose postings differ in
everything, then asserts:

- a column is an entry column exactly when its values agree (one
  exception, `filename`, which is only slower per posting);
- POSTING_ONLY_COLUMNS is exactly the posting-row columns that #entries
  lacks.

Checked by mutation: adding `number` to the entry list, dropping
`payee` from it, or dropping `units` from the posting-only list each
fails the test.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

robcohen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member Author

Review pass

The review looked at the column-list drift hazard, performance at two ledger sizes, and the load-pipeline diagnostics.

Fixed here (8901bcf). The two hand-kept lists, FROM_ENTRY_COLUMNS and POSTING_ONLY_COLUMNS, are now checked against the executor itself. The test reads the row evaluator's match arms (include_str!) plus the #postings and #entries schemas, and evaluates every column on two postings that differ in everything. It requires two things:

  • a column is on the entry list exactly when its values agree. The one exception is filename, which is merely slower per posting.
  • POSTING_ONLY_COLUMNS is exactly the posting-row columns that #entries lacks.

Mutation-checked in three directions: adding number to the entry list, dropping payee from it, and dropping units from the posting-only list each fail the test.

Performance. Callgrind instruction counts, release builds, cache off. Each figure is the query's cost above the load floor (SELECT 1 LIMIT 1). Sizes: example.beancount (1,146 txns) and a bean-example ledger with 11,414 txns.

query main 1x PR 1x main 10x PR 10x
SELECT ... FROM narration ~ 'e' (entry-level) 30.0M 29.3M 260.3M 253.9M
SELECT ... FROM account ~ 'Assets' (posting-level) 43.5M 22.6M 359.3M 176.5M
BALANCES 12.9M 13.0M 498.2M 498.0M
BALANCES FROM account ~ 'Assets' 14.1M 11.3M 498.5M 100.4M
  • The entry-level FROM does not regress.
  • Per-posting evaluation scales linearly (7.8x for 10x the data).
  • BALANCES grows 38x on main and on this PR alike. That growth comes from the output: 78 KB vs 3.4 MB of lot-level inventories, written through fmt::Formatter::pad one character at a time. It is not caused by this change.

Found elsewhere, fixed separately in #2534. rledger query printed E1004 (closed with a balance) on ledgers that rledger check and bean-check pass. It is on main and was introduced by #2238, which turned validation on in query without check's advisory-only skip.

Review pass 2

Review pass 3

Looked at my aggregation.rs conflict resolution as fresh code. Nothing found.

Tested with option "booking_method" "AVERAGE" and the auto_accounts plugin on three accounts:

  • Assets:Fifo opened "FIFO": stays FIFO, lots not pooled;
  • Assets:Glob opened with no method: AVERAGE;
  • Assets:Noopen, which has no open at all: AVERAGE, from the ledger's method, as booking's method_for resolves it.

BALANCES with a partial FROM equals sum(position) for all three. The helper resolves the method exactly as register_account_methods + method_for do. The only theoretical gap is an account opened twice with different methods, which validation rejects anyway.

robcohen and others added 6 commits October 8, 2026 22:08
The guard reads evaluate_column's arms with a pattern on its source. If
the `match` were reshaped (`"a" | "b" =>`, a helper, a table), the
pattern would quietly stop seeing those arms and their columns would go
unchecked. It now requires every #postings schema column and every name
on either list to be among the arms it found, and names the column when
one is missing. Checked by rewriting the `units` arm as
`"units" | "units_alias" =>`, which fails it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
#2529 changed `group_is_single_average_account` in aggregation.rs to
resolve an account's method the way booking does: the `open`'s method,
else the ledger's. This branch had moved that check into
`account_is_average`, which the row-filtered BALANCES path also calls.
The helper now carries #2529's resolution, so the partial-BALANCES path
also sees AVERAGE under a global `option "booking_method"`.

Tests added on top of #2529's:

- sum_position_balances_agreement now also runs the posting-level
  filters `FROM number > 0` and `FROM number < 0`, which select part of
  an account. That is the case where BALANCES sums the selected postings
  instead of reading booking's inventory. 3,000 cases pass.
- a targeted test pins BALANCES and sum(position) to the same lots on a
  partly selected AVERAGE account holding two longs, a short and a sale.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
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.

BQL FROM <expr> on a posting column (account, position, …) tests only each transaction's first posting

1 participant