Skip to content

fix(query): apply CLEAR and CLOSE's conversions entry, as beanquery does - #2412

Merged
robcohen merged 2 commits into
mainfrom
fix/bql-close-clear-summarize-2406
Sep 24, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/bql-close-clear-summarize-2406

Conversation

@robcohen

@robcohen robcohen commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

What

The rest of beancount's summarize family in BQL's FROM clause, after #2401's OPEN ON.

CLEAR was parsed and ignored, and FROM CLEAR on its own failed as a table name.

SELECT account, sum(position) FROM CLOSE ON 2024-03-01 CLEAR GROUP BY account (the #2406 repro):

account main this PR bean-query 0.2.0
Assets:Bank 4800.00 USD 4800.00 USD 4800.00 USD
Equity:Earnings:Current (no row) -4674.25 USD -4674.25 USD
Expenses:Food 125.75 USD (empty) (empty)
Expenses:Rent 1200.00 USD (empty) (empty)
Income:Salary -6000.00 USD (empty) (empty)
Liabilities:Card -125.75 USD -125.75 USD -125.75 USD

CLOSE only truncated. It was missing the conversions entry beancount books when @ price conversions leave the balances unequal at cost.

How

Both follow beancount's summarize, applied after OPEN ON in beanquery's order (_BeancountTable.prepare), inside #2401's single date window, Executor::window_transactions. SELECT, BALANCES and JOURNAL therefore all see them.

  • CLOSE [ON <date>] is summarize.close. After truncating, it adds a C entry that books the period's residual at cost, negated, to account_current_conversions.
    • Date: the day before the close date, or the last entry's date for a bare CLOSE.
    • Price: each posting is priced at zero in conversion_currency (NOTHING by default), as beancount prices it.
    • Posting order: the running balance uses beancount's Inventory ordering. Keys go in first-appearance order, a key is dropped when it reaches zero, and it comes back at the end. So the postings come out in bean-query's order, which is not the obvious one: EUR then USD without OPEN ON, USD then EUR with it.
    • Narration: Conversion for (<balance>) renders the balance sorted by beancount's Position.sortkey. That is a currency rank (USD, EUR, JPY, … first), then cost, then units.
  • CLEAR is summarize.clear with no date: one T transfer per income-statement account with a balance, in account order, moving the balance at cost to account_current_earnings. They are dated entries[-1].date, the last entry of any type left after OPEN and CLOSE, so a later price or balance directive counts. Balances are realized through the booking engine, as BQL FROM OPEN ON drops the opening balance from posting rows, balance and sum(position) #2401's summaries are.
  • Account names: Options::current_{earnings,conversions}_account and conversion_currency_or_default resolve unset options under the ledger's own equity root, like BQL FROM OPEN ON drops the opening balance from posting rows, balance and sum(position) #2401's previous_*. SummaryAccounts carries them (wasm cache v27). The component resolves an unset account_current_conversions without changing its exported None, so hosts see the same options as before.

Parser

  • Modifiers are keywords: OPEN, CLOSE and CLEAR are FROM modifiers, not table names, as in beanquery's grammar. FROM CLEAR, FROM CLOSE and FROM CLOSE CLEAR now parse. FROM #postings and user tables still parse as tables (tested).
  • Bare CLOSE: FromClause::close marks it; close_on stays the date.
  • The dated form is one all-or-nothing unit: separator, optional ON, then the date. My first cut left the separator outside it. That silently turned CLOSE 2024-02-01, a parse error on main, into a bare CLOSE with the date read as a filter, which returned the whole ledger. Found while testing, fixed, and pinned in the parser test. CLOSE <date> without ON is now a dated close; beanquery requires ON, and the old parser meant to accept both but never could.

Verification

  • Differential against bean-query: the BQL FROM OPEN ON drops the opening balance from posting rows, balance and sum(position) #2401 ledgers plus the new CLOSE / CLEAR / CLOSE CLEAR / OPEN … CLOSE … CLEAR / sum(weight) / JOURNAL … CLEAR shapes give 140/153 identical.
  • Tests:
    • open_on_summarize_test.rs: three new tests (CLEAR transfers and totals, conversions residual with a bare and an OPEN ON variant, renamed root with conversion_currency), 14 in the file.
    • A parser test covers standalone modifiers, bare CLOSE, CLOSE <date>, and table names still being tables.
    • Values are bean-query's.
  • Dirty-checked: ignoring CLEAR, dropping the conversions entry, leaving the narration unsorted, and removing the keyword guard each fail their tests.
  • Suites: workspace 170 test binaries after the cache-test fix, 0 failures. Clippy and rustdoc -D warnings are clean.
  • Queries without CLOSE / CLEAR: byte-identical to merged main on the fifo, avg and investment 20k benches (BALANCES, sum(position), a balance SELECT, JOURNAL). Callgrind on BALANCES fifo-20000: +0.01%.

Upstream crash

bean-query 0.2.0 crashes on OPEN ON <date> together with a bare CLOSE: its compiler evaluates node.open > node.close with close being True, a TypeError. rledger answers it, and its rows equal beancount's own summarize.open_opt → close_opt(None) → clear_opt run directly (pinned in a test).

Reserved words

OPEN, CLOSE and CLEAR are FROM keywords now, as in beanquery's grammar, so a user table with one of those names cannot be selected with FROM <name>.

Known, not this PR

A zero-price posting's weight renders 0 NOTHING where Python keeps the product's sign and scale (-0.00 NOTHING). That is rledger's rendering of zero products on main too, for any @ 0 posting (0 USD against -0 USD); the value is equal.

API

Breaking (in the CHANGELOG): FromClause::close and three SummaryAccounts fields, both exhaustive structs. FromClause::close() is a new builder.

Closes #2406

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`FROM ... CLEAR` was parsed and ignored: the income statement stayed in the
income and expense accounts where bean-query moves it to
`account_current_earnings`, and `FROM CLEAR` alone failed as a table name.
`CLOSE` only truncated, missing beancount's conversions entry.

Both now follow beancount's `summarize`, after OPEN ON in beanquery's order:

- CLOSE (`summarize.close`): a `C` entry dated the day before the close
  date, or at the last entry for a bare CLOSE, booking the period's
  residual at cost to `account_current_conversions`, priced at zero in
  `conversion_currency`, narrated with the balance sorted as beancount
  sorts an inventory. The balance keeps beancount's insertion order with
  zero-crossing keys dropped, so postings come out in its order.
- CLEAR (`summarize.clear`): one `T` transfer per income-statement account,
  dated the last entry of any type, to `account_current_earnings`.

The parser now reads OPEN/CLOSE/CLEAR as FROM modifiers rather than table
names, takes a bare CLOSE (`FromClause::close`), and parses the separator,
optional ON and date of `CLOSE ON <date>` as one unit, so `CLOSE <date>` can
no longer leave the date to be read as a filter expression.

`Options::current_{earnings,conversions}_account` resolve an unset account
under the ledger's equity root; `SummaryAccounts` carries them and the
conversion currency (wasm cache v27).

Closes #2406

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 21:40
@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.05298% with 24 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-query/src/executor/summarize.rs 89.94% 17 Missing ⚠️
crates/rustledger-query/src/ast.rs 25.00% 6 Missing ⚠️
crates/rustledger-query/src/parser.rs 97.05% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 44.4ms ± 1.6ms 804.9ms ± 12.3ms 18.1x 50.8 MB / 49.9 MB
investment 67.0ms ± 0.7ms 3005.6ms ± 24.4ms 44.9x 57.1 MB / 58.0 MB
fifo 64.1ms ± 0.7ms 15337.8ms ± 178.8ms 239.2x 57.2 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 43.8ms ± 0.5ms 44.4ms ± 1.6ms +1.5% ✅ within noise 51.1 MB → 50.8 MB (-0.6%)
investment 67.6ms ± 0.8ms 67.0ms ± 0.7ms -0.9% ✅ within noise 56.8 MB → 57.1 MB (+0.5%)
fifo 65.9ms ± 1.3ms 64.1ms ± 0.7ms -2.8% ✅ within noise 55.3 MB → 57.2 MB (+3.5%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.8ms, investment 0.5ms, fifo 0.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%, 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 #2412.

- `cargo mutants --in-diff` found the new loader methods
  (`current_*_account`, `conversion_currency_or_default`) untested in
  their crate, and two `OrderedBalance` rules unpinned: a zero position
  never enters (Python's `Inventory` behavior) and non-major currencies
  rank by code length. Tests now cover all three.
- Four window mutants survived because the code was unobservable: seeding
  `CLEAR`'s and a bare `CLOSE`'s date from the summaries and pre-open
  Opens/Prices. A conversions entry or transfer needs a balance from the
  window's own transactions, which are dated on or after the open date,
  so an in-window date always wins. Removed, with the argument in a
  comment. `current_conversions_account`'s guard was redundant the same
  way (`Some` only when set) and is gone too.
- bean-query 0.2.0 crashes on `OPEN ON <date>` with a bare `CLOSE` (its
  compiler compares the date with `True`); rledger's rows equal
  beancount's own `summarize` for it, now pinned.

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 2151c1fab0)

Verdict: correct and complete. No wrong answers found. The review added tests for five unpinned rules, removed code no test could observe, and pinned an answer bean-query itself can't give (2151c1fab0).

Probed against bean-query

  • Where the date could be wrong:

    • the last entry is a price or balance directive after the last transaction, which CLEAR must date its transfers by;
    • CLOSE ON before every entry;
    • OPEN ON after the ledger ends;
    • OPEN ON + CLEAR, OPEN + CLOSE ON + CLEAR on lots, and CLOSE CLEAR on a closed account.

    All agree. The only differences are bean-query's in-cell alignment and BQL BALANCES orders rows by account name, beanquery by account_sortkey #2409's BALANCES order.

  • bean-query crashes on OPEN ON <date> + bare CLOSE. Its compiler compares the date with True. For that form I ran beancount's summarize.open_opt → close_opt(None) → clear_opt directly: rledger's 14 rows are identical, and a test now pins them.

  • Every BQL column on C / T rows: all 24 evaluate with no panic. account_balance reads sensibly on them (rledger-only column).

  • Cost: CLOSE, CLEAR and OPEN … CLOSE ON … CLEAR on investment-20000 run in the same 0.49–0.61 s as a plain count(*). The second realization pass is negligible.

Mutation testing: 51 mutants, 28 caught, 7 unviable, 16 missed

Fixed in 2151c1fab0 (a targeted re-run gives 34 caught, 2 missed, both below):

  1. Eight Options::current_*_account / conversion_currency_or_default mutants: the new loader methods had no test in their crate, the gap previous_* had in fix(query): summarize the ledger before FROM ... OPEN ON, as beanquery does #2410. A loader unit test now covers unset, renamed-root and set values.
  2. OrderedBalance's zero rule: a position that first appears at zero never enters, as in Python's Inventory. Now tested.
  3. render's rank for non-major currencies, 8 + len(code), + → -: now tested with ABCD / XYZ / CHF.
  4. Four window_transactions mutants were unobservable: the code seeded CLEAR's and a bare CLOSE's date from the summaries and pre-open Opens/Prices. A conversions entry or transfer only exists for a balance the window's own transactions produced: summaries sum to zero at cost and hold no income-statement account. So an in-window date, on or after the open date, always wins the max. Removed, with that argument in a comment; the differential is unchanged at 140/153.
  5. current_conversions_account's set_options guard was redundant: the field is Some only when set, because includes cannot set options. Removed.

Remaining survivors, both equivalent:

  • render's + → *: 8 × len and 8 + len order codes identically.
  • The guard mutant, now moot since the guard is gone.

After the changes

CI

At 5e5a829deb, the only red check was rustfava: the stale test_api_errors snapshot main has had since 2026-09-01 (1 failed, 678 passed).

@robcohen
robcohen merged commit ef5042d into main Sep 24, 2026
67 of 68 checks passed
@robcohen
robcohen deleted the fix/bql-close-clear-summarize-2406 branch September 24, 2026 11:07
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 ... CLEAR is ignored, and CLOSE ON omits the conversions entry

1 participant