Skip to content

fix(query): summarize the ledger before FROM ... OPEN ON, as beanquery does - #2410

Merged
robcohen merged 2 commits into
mainfrom
fix/bql-open-on-summarize-2401
Sep 23, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/bql-open-on-summarize-2401

Conversation

@robcohen

@robcohen robcohen commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

What

FROM ... OPEN ON <date> now summarizes the ledger before the date, as beanquery does, where rledger dropped those postings and started every balance at zero.

2024-01-05 * "opening"
  Assets:Bank      1000.00 USD
  Equity:Opening  -1000.00 USD
2024-02-10 * "lunch"
  Expenses:Food      20.00 USD
  Assets:Bank       -20.00 USD

SELECT account, sum(position) FROM OPEN ON 2024-02-01 GROUP BY account

account main this PR bean-query 0.2.0
Assets:Bank -20.00 USD 980.00 USD 980.00 USD
Equity:Opening (no row) -1000.00 USD -1000.00 USD
Equity:Opening-Balances (no row) (empty) (empty)
Expenses:Food 20.00 USD 20.00 USD 20.00 USD

How

beanquery applies OPEN ON with beancount's summarize.open (sources/beancount.py, _BeancountTable.prepare). The new executor/summarize.rs reproduces it, in beancount's order.

  1. Conversions: if the pre-date balances don't sum to zero at cost (an @ conversion), the residual goes to account_previous_conversions.
  2. Clear: income and expenses before the date move to account_previous_earnings, at cost.
  3. Summarize: one transaction per account, in account order, dated the day before, flagged S, narrated Opening balance for '<account>' (Summarization). Each lot gets a posting at its cost, date and label, balanced by its cost against account_previous_balances.

Executor::window_transactions is the one definition of the date window: OPEN ON's summaries, then the ledger's transactions in [open, close). scan_postings (SELECT, BALANCES) and JOURNAL both iterate it. JOURNAL used to walk the ledger itself and applied only the FROM filter expression, ignoring OPEN ON and CLOSE ON altogether. A CLOSE ON before the OPEN ON is refused, as beanquery refuses it. The summaries go through the same FROM / CLOSE ON / WHERE filters and the same booking-engine replay as any other transaction, so the rows, the running balance, account_balance and BALANCES all start from them. The old code replayed pre-date transactions only into account_balance, and only when the query asked for it; that branch is gone.

Deliberately not beancount's method. beancount totals each account by plain inventory addition. Here the balances are realized through the booking engine, as BALANCES and report balances realize them. The two agree for every method beancount has. For AVERAGE, which beancount lacks, plain addition leaves the sale booked at the pooled cost as a third, negative lot (#1985); this summarizes the pool the account holds.

Changes beyond the executor

  • PostingContext::transaction becomes TransactionRef<'a> (breaking; in the CHANGELOG). It is Ledger(&'a Transaction) or Synthesized(Arc<Transaction>) and derefs to Transaction. A row can't borrow a summary from the ledger, and a child executor over a cloned stream would have copied the post-date ledger per query. Field access is unchanged; the other seven construction and use sites changed by one token each.
  • SummaryAccounts / Executor::set_summary_accounts, set from the ledger's options by the CLI, wasm (query, queryMultiFile, ParsedLedger, Ledger including fromCache; wasm cache v26) and component (query, batch, session.query) paths.
  • Options::previous_{balances,earnings,conversions}_account(), a new loader canonical. Unset, it is beancount's default leaf under the ledger's equity root, as get_previous_accounts builds it. The raw default Equity:Opening-Balances named a root that a ledger with option "name_equity" "Eigenkapital" doesn't have. The component's exported options use it too, so session.clamp and hosts also get the right names on such ledgers. On default-root ledgers the names are byte-identical.
  • run_interactive takes the caller's ShellSettings. Threading one more setting through it hit clippy's argument limit, and building the settings once is simpler anyway.
  • test_balances_open_on_is_noop_for_totals is rewritten. It asserted that OPEN ON left every BALANCES total unchanged, "matching bean-query". It did not match: bean-query clears the pre-date income statement. The test now pins that balance-sheet totals are unchanged, income-statement accounts show the period only, and Equity:Earnings:Previous holds the rest.

Verification

  • Differential against bean-query 0.2.0 / beancount 3.2.3. Five ledgers (plain, earnings, lots with labels and a gain, @ conversions, a closed account), several OPEN ON dates each, seven query shapes: SELECT with balance, summary rows with narration, sum(position), sum(cost(position)), BALANCES, and OPEN ON + CLOSE ON.
  • open_on_summarize_test.rs, 9 tests. Expected values are bean-query's output, except three rledger-specific cases, each labeled: AVERAGE, account_balance, and set option values. The tests use the CLI's source-aware executor, so the "summary rows have no location" assertion is not vacuous; a ledger row resolves to main.beancount.
  • Dirty-checked: dropping the summaries fails 8 of 9 tests, dropping the clear step fails 6, dropping the conversions step fails the conversions test, and ignoring name_equity fails the renamed-root test.
  • Suites: workspace 170 test binaries, then query, CLI and loader again (73) after the last edits, 0 failures. Clippy and rustdoc -D warnings are clean.
  • Queries without OPEN ON: byte-identical to main (d148fdba62) on fifo, avg and investment 20k for BALANCES, sum(position), a balance SELECT and JOURNAL. Callgrind on BALANCES fifo-20000: +0.02%.
  • OPEN ON cost: the same wall time as main within ±0.02 s, and RSS within 4 MB.

Behavior change

BALANCES FROM OPEN ON on income-statement accounts. On the #2401 differential's earnings ledger:

main this PR (= bean-query)
Income:Salary -6000.00 USD (both months) -3000.00 USD (the period)
Expenses:Rent 1200.00 USD (none; all before the date)
Equity:Earnings:Previous (no row) -1754.50 USD

Follow-ups filed

Closes #2401

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

…y does

`FROM ... OPEN ON <date>` dropped every posting before the date from the
rows and started the running `balance` at zero, so a balance-sheet account's
total over the period was wrong: holding 1000 USD and spending 20 in the
period, `sum(position)` gave -20.00 USD where bean-query gives 980.00 USD.

`OPEN ON` now applies beancount's `summarize.open`, which beanquery uses:
every transaction before the date is replaced by one opening-balance
transaction per account, dated the day before, flagged `S`, a posting per
lot at its cost balanced against `account_previous_balances`. Income and
expenses before the date are first cleared to `account_previous_earnings`,
and a residual left by `@` conversions goes to
`account_previous_conversions`. Rows, `balance`, `account_balance` and
`BALANCES` all start from the summaries.

Balances are realized through the booking engine, as `BALANCES` does, not
by beancount's plain inventory addition; the two agree for every method
beancount has, and for AVERAGE the summary is the pool the account holds.

- `PostingContext::transaction` becomes a `TransactionRef` (ledger or
  synthesized, deref to `Transaction`), so rows can hold the summaries.
- `SummaryAccounts` / `Executor::set_summary_accounts`, set by the CLI,
  wasm (cache v26) and component query paths.
- `Options::previous_*_account` resolves an unset summary account under the
  ledger's own equity root; BQL and the component's exported options use it.
- `run_interactive` takes the caller's `ShellSettings`.

Follow-ups filed: #2406 (CLEAR, CLOSE ON conversions), #2407 (FROM <expr>
OPEN ON parse), #2408 (relative account_previous_* values), #2409
(BALANCES order).

Closes #2401

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 September 23, 2026 18:29
@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 45.5ms ± 3.3ms 812.4ms ± 8.7ms 17.8x 50.9 MB / 50.1 MB
investment 67.9ms ± 0.6ms 3068.9ms ± 48.8ms 45.2x 55.2 MB / 58.2 MB
fifo 65.5ms ± 1.0ms 15625.4ms ± 137.6ms 238.6x 53.3 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 44.1ms ± 0.4ms 45.5ms ± 3.3ms +3.1% ✅ within noise 51.0 MB → 50.9 MB (-0.3%)
investment 68.1ms ± 1.1ms 67.9ms ± 0.6ms -0.3% ✅ within noise 55.1 MB → 55.2 MB (+0.1%)
fifo 66.4ms ± 1.6ms 65.5ms ± 1.0ms -1.3% ✅ within noise 55.0 MB → 53.3 MB (-3.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 1.5ms, investment 0.6ms, fifo 0.9ms), 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%, 178 masked)
Full AST Match 100%
Total Files 813
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 of #2410. JOURNAL walked the ledger itself and applied only the FROM
filter expression, so `JOURNAL ... FROM OPEN ON` still showed the posting
before the date as itself, and `CLOSE ON` was ignored too (on main as well).
The date window is now one helper, `Executor::window_transactions`: OPEN ON's
summaries, then the transactions in [open, close). `scan_postings` and
JOURNAL both iterate it, so they cannot drift again.

A CLOSE ON before the OPEN ON is refused ("CLOSE date must follow OPEN
date"), as beanquery refuses it, where the window was silently empty.

`cargo mutants --in-diff` found `Options::previous_*_account` untested in
its own crate (8 mutants caught only through the query crate); a loader
unit test now covers unset, renamed-root and set values (8/8 caught).

PRINT, which prints entries rather than postings, is filed as #2411.

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

Copy link
Copy Markdown
Member Author

Deep review (head 615e987435)

Verdict: correct and complete. One real gap found and fixed (JOURNAL), plus a test gap and a missing validation.

Found and fixed in 615e987435

  1. JOURNAL ignored the FROM date window, on main too. It walked the ledger itself and applied only the filter expression, so JOURNAL … FROM OPEN ON still showed the pre-date posting as itself, and CLOSE ON did nothing. JOURNAL is posting rows with a running balance, which is squarely BQL FROM OPEN ON drops the opening balance from posting rows, balance and sum(position) #2401. The window is now one helper, Executor::window_transactions, that scan_postings and JOURNAL both iterate, so they can't drift again.
    • Verified against bean-query on 3 ledgers × OPEN ON, CLOSE ON and both: 9/9 agree, including balance and narration. The same comparison against main shows the differences, so the check is not vacuous.
    • Output without FROM is byte-identical to main on the 20k benches: JOURNAL, JOURNAL … AT COST, SELECT, BALANCES. Callgrind on JOURNAL (fifo-2000): +0.1%.
  2. CLOSE ON before OPEN ON silently answered with nothing. It is now refused ("CLOSE date must follow OPEN date") for SELECT, BALANCES and JOURNAL, as beanquery refuses it. Equal dates remain an empty period.
  3. The loader's Options::previous_*_account had no test in its own crate. cargo mutants --in-diff found 8 of its mutants surviving the loader's tests. A loader unit test now covers unset, renamed-root and set values, and a re-run catches 8/8.

Both new open_on_summarize_test cases fail when their fix is reverted.

Checked, no change needed

  • Every BQL column on a summary row: all 24 SELECT columns evaluate on synthesized rows, with no panic. A summary row has no directive index and no posting spans, so the location columns resolve to NULL, as in bean-query.
  • rustfava: the one red check is the same test_api_errors stale snapshot main has (1 failed, 678 passed). No rustfava test moved from the component's now-resolved account_previous_* names.
  • The other mutation survivors:
    • run_interactive → Ok(()): the REPL, which has no harness.
    • Two scan_postings performance gates (the pre-WHERE account_balance snapshot and the large-inventory detach): no output depends on either, so they are equivalent. They appear in the diff only through re-indentation.
    • Two evaluate_from_filter fast-path arms: the generic evaluation gives the same answer. The only change there is one token.
  • Differential re-run with the JOURNAL queries added: 66/81 identical. Every remaining line is a filed, pre-existing category: BQL: FROM <expr> OPEN ON / CLOSE ON / CLEAR fails to parse #2407 (FROM <expr> OPEN ON parse), BQL BALANCES orders rows by account name, beanquery by account_sortkey #2409 (BALANCES order), BQL: FROM ... CLEAR is ignored, and CLOSE ON omits the conversions entry #2406 (CLOSE ON conversions, including the C rows in JOURNAL 'Equity').

Filed

  • BQL PRINT ignores FROM ... OPEN ON / CLOSE ON #2411: PRINT ignores OPEN ON / CLOSE ON too. It prints entries, not postings, so it needs beancount's full summarized entry stream (active Opens, last Prices, then the summaries), which the posting sources don't.

Verification after the fixes

Query, CLI, loader, wasm and component: 80 test binaries, 0 failures. Clippy and rustdoc -D warnings are clean.

@robcohen
robcohen merged commit 1324bc2 into main Sep 23, 2026
67 of 68 checks passed
@robcohen
robcohen deleted the fix/bql-open-on-summarize-2401 branch September 23, 2026 20:34
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 OPEN ON drops the opening balance from posting rows, balance and sum(position)

1 participant