Repository navigation
fix(query): PRINT prints the FROM entry stream through the canonical formatter - #2530
Conversation
… 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
…formatter PRINT printed every directive whatever OPEN ON / CLOSE / CLEAR said, filtered transactions only, and rendered with a formatter of its own that dropped costs, prices, metadata and the booking method and did not escape strings. The CLI showed it as a padded one-column table. - window_entries is the stream FROM leaves, beanquery's prepare: for OPEN ON, the active opens, the last price per pair and the summaries, then every entry from the date (minus balances on accounts the summary cleared); CLOSE ON truncates; CLOSE and CLEAR append their entries. window_transactions is now its transactions. - PRINT evaluates its filter on each entry as an #entries row, and has_account() works on #entries rows. - Each entry is rendered by rustledger_core::format, separated as beancount's printer separates them, and rledger query writes PRINT as raw text. Closes #2411 Closes #2426 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
✅ Compatibility Test Results
What's tested
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
PRINT called `rustledger_core::format` directly. Its text is only the intermediate that `rustledger_parser::format::canonicalize_directives` reparses into `rledger format`'s canonical form, so a price came out as `price X 110 USD` and a balance as `balance A -300 USD`, which `rledger format` rewrites to a single space. PRINT now goes through `canonicalize_directives`, which `rledger add`, `rledger extract` and the FFI `format.entry` already use. Every printed entry is a fixed point of `format_source`. Transactions are unchanged. compatibility.md gets a section on PRINT layout versus bean-query: beancount pads open/price/balance lines to fixed columns and applies `render_commas`, and rledger does neither. Posting alignment is per entry in both. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…o fix/bql-print-entry-stream
Review passThe review looked at PRINT rendering consistency, performance at two ledger sizes, and the stacking. Fixed here (fbef27b). PRINT called A new test asserts that every printed entry, for plain PRINT, OPEN ON and CLOSE ON + CLEAR, is a fixed point of Compat. Performance. Callgrind instruction counts, release builds, cache off, above the load floor:
Stacking. This now contains #2523's head (8901bcf) through a merge. After #2523 merges, main has to be merged into this branch so the diff shrinks to this PR's own commits. Review pass 2
Review pass 3Checked the §16 text only. I reproduced every row of the table with one ledger, rledger vs bean-query 0.2.0 PRINT:
One overclaim, fixed (f234fef): the lead sentence said "the entries are the same". It now says the table lists layout only and that the loader differences elsewhere on the page show up in PRINT too. Review pass 4Re-read the §16 lead sentence against the rest of One sentence did disagree with the PRINT decision: it called separators something PRINT "does not have yet". It now says PRINT writes none, as plain Merge after #2523 (3690b9f)#2523 was squash-merged as a2d984d, so main now carries its code. Merged main in.
|
…column # Conflicts: # CHANGELOG.md
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
Ran PRINT over the 742-file downloaded compatibility corpus, comparing against bean-query 0.2.0. 615 files print in both tools. Of those, 342 are identical or differ only in spacing. The rest differ in ways §16 now lists: - a failing balance gets `; Diff:` in bean-query only; - comments inside a transaction are kept; - an empty payee or narration is kept as `""`; - metadata keys are sorted, since rledger stores metadata unordered; - tags and links stay in source order, where bean-query sorts them; - `\n` is escaped in strings; or in loader differences that `SELECT` shows too. The previous text said transactions are laid out the same way in both; that held for example.beancount, not for the corpus. Compared with this PR's previous head, canonicalize_directives changed three things: price/balance spacing, the trailing space after an empty metadata value, and a balance tolerance written as `200 ~ 0.002 USD`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…column # Conflicts: # CHANGELOG.md
#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
…column # Conflicts: # CHANGELOG.md
That sentence was the one claim in §16 that is not true: the loader differences listed elsewhere on the page (decimal precision, booking, plugins) show up in PRINT too. I reproduced every row of the table with one ledger, comparing rledger and bean-query 0.2.0 PRINT: open, price and balance padding, `; Diff:` on a failing balance, per-entry posting alignment, `render_commas`, the comment kept, `""` for an empty payee and an empty narration, sorted metadata, tag and link order, and the `\n` escape. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…tream # Conflicts: # CHANGELOG.md
The old sentence called thousands separators something PRINT "does not have yet". robcohen decided PRINT matches `rledger format`'s canonical output, so the sentence now says it plainly: plain `rledger format` writes no separators, and only `rledger format --ledger` adds the ones `render_commas` declares. Checked on a render_commas ledger: `1234.50 USD` without --ledger, `1,234.50 USD` with it. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…tream # Conflicts: # CHANGELOG.md
…tream # Conflicts: # CHANGELOG.md # crates/rustledger-query/src/executor/execution.rs
…tream # Conflicts: # CHANGELOG.md
What
BQL
PRINTnow prints the entry stream theFROMclause leaves (#2411). Each entry is rendered inrledger format's canonical form throughcanonicalize_directives(#2426), andrledger querywrites the result as raw ledger text.Previously stacked on #2523. #2523 has merged (a2d984d), and main is merged in here (3690b9f), so the diff against main is now this PR's own changes only.
Before / after
On the #2426 ledger (costs with a label, a sale, a price, metadata on the transaction, a posting and a commodity, a
"FIFO"booking method, a quoted narration):3 X {100 USD, 2024-01-02, "lot-a"}3 X-1 X {100 USD, 2024-01-02, "lot-a"} @ 120 USD-1 Xopen ... "FIFO""buy \"quoted\""N row(s)footerPRINT FROM OPEN ON 2024-02-01Ssummaries, then entries from the datePRINT FROM narration ~ 'lunch'open/price/note... tooPRINT FROM has_account('Assets:C')open,balance,noteand transactions naming itHow
One stream (BQL
PRINTignoresFROM ... OPEN ON/CLOSE ON#2411). The newwindow_entriesis beanquery'sprepare, i.e. beancount'ssummarize.open_opt/close_opt/clear_opt, over every directive type:OPEN ON: theopens still active at the date (get_open_entries: the earliest open per account, dropped if closed before the date), the lastpriceper (base, quote) before it, and the summaries, sorted by beancount'sentry_sortkey. Then every entry from the date on, except abalanceon an income/expense account that the summary cleared (beancount'stransfer_balancesdrops those).CLOSE ONtruncates.CLOSEandCLEARappend their entries, as before.window_transactions, which SELECT / BALANCES / JOURNAL iterate, is nowwindow_entriesfiltered to transactions. So PRINT and the posting sources read one definition, andclose_conversions/clear_transferstake that stream.Filter. PRINT evaluates its FROM expression on each entry as a row of
#entries(sharedENTRY_TABLE_COLUMNS+directive_to_entry_row), as beanquery evaluates it on itsentriestable.narrationis NULL on anopen, andmetais the entry's.has_account(regex)on a table with anaccountscolumn is beanquery'sregex ~? any(accounts). Before this PR,SELECT ... FROM #entries WHERE has_account(...)failed withno function matches "HAS_ACCOUNT". A posting column in PRINT's FROM is still the fix(query): a posting column in FROM filters rows, and is an error in PRINT #2523 error.Rendering (BQL PRINT drops costs, prices, metadata and the booking method: it re-derives the formatter instead of using rustledger_core::format #2426). Each entry goes through
rustledger_parser::format::canonicalize_directives, the one function that turns a typed directive intorledger format's canonical form (rledger add,extractand the FFIformat.entryuse it too), so the hand-writtenformat_directiveis gone. A test asserts that every printed entry is a fixed point offormat_source. The first version of this PR calledrustledger_core::formatdirectly, which printed that emitter's intermediate text (price X 110 USD, with two spaces, whichrledger formatrewrites to one); fixed in fbef27b. Layout differences from bean-query (fixed-column padding ofopen/price/balancelines,render_commas) are documented indocs/reference/compatibility.md§16. Beancount'sprint_entriesputs a blank line before each transaction and commodity, and wherever the directive type changes. Each row's text starts with that blank line where needed, so the rows concatenated are bean-query's layout.CLI. For
PRINT, the text and beancount output formats write the rows as they are. CSV and JSON keep the one-column rows as data.Verification
Compared against bean-query 0.2.0 (
uv run --with beancount --with beanquery bean-query F "PRINT ..."):t2, now the test fixture):PRINT,FROM OPEN ON 2024-02-01,FROM CLOSE ON 2024-02-02 CLEAR,FROM narration ~ 'lunch',FROM has_account('Assets:C'),FROM type = 'price' OR type = 'commodity'. The filtered transaction-only output is byte-identical. Every other output differs from bean-query only in the column padding ofopen,priceandbalancelines (beancount's printer pads them to fixed columns; the canonical formatter does not).{{500 USD}}lot, an@conversion,document,custom,notewith tags, a closed account, and abalanceon an income account cleared by OPEN ON. All filter, OPEN/CLOSE/CLEAR combinations agree except:{{500 USD}}interpolation, where rledger keeps the exact-500 USD(validate: rledger accepts sale of non-existent inventory + unsolvable interpolation #1026, the difference BQL PRINT drops costs, prices, metadata and the booking method: it re-derives the formatter instead of using rustledger_core::format #2426 says to keep);example.beancount:PRINT,OPEN ON 2015-01-01,OPEN ON ... CLOSE ON ... CLEAR,CLOSE,has_account('Vanguard'). Agreement modulo padding, except:render_commas: beanquery's PRINT renders1,350.60, and PRINT does not (see Decision: thousands separators below);PRINToutput of the fixture and ofexample.beancountloads back clean inrledger checkandbean-check. The fixture is pinned byprinted_text_loads_back_clean.crates/rustledger-query/tests/print_entry_stream.rs(6 tests, expected texts from bean-query) plus an exact-output assertion in the CLI testtest_query_print_outputs_directives. All 7 fail with this commit's source changes reverted. The twohas_accounttests also fail with only the tablehas_accountarm disabled.cargo test -p rustledger-query --all-features: 824 passed.cargo test -p rustledger --all-features: 912 passed.cargo clippy --workspace --all-features --all-targets -D warningsandcargo doc -D warnings(both crates) are clean.scripts/compat-bql-test.pyruns no PRINT queries, so no registry entries are affected.Corpus sweep (742 files, downloaded compatibility corpus)
PRINT at this head vs bean-query 0.2.0
PRINT, plus a round trip of the printed text throughrledger checkandbean-check:; Diff:on a failing balance, comments kept inside transactions, an empty payee or narration kept as"", metadata keys sorted (rledger stores metadata unordered), tags in source order,\nescapes, separators. All of these are now incompatibility.md§16.SELECTshows these too.canonicalize_directiveschanged only price/balance spacing, the trailing space after an empty metadata value, and the balance tolerance syntax (200 ~ 0.002 USD). No blank-line or entry changes.reds-plugins/..._effective_date_examples.beancount. The nativeeffective_dateplugin emits its synthesizedopens inHashSetorder. The upstream Python plugin sorts them. Fixed separately in feat(plugin)!: effective_date moves a marked posting correctly or reports it #2536.Decision: thousands separators (
render_commas) in PRINT — for @robcohenPRINT writes no separators even when the ledger sets
render_commas. bean-query writes them, and so doesrledger format --ledger. Values are identical and the text loads back the same either way.DisplayContext, and thread it from every PRINT surface: CLIquery,ag-rledger, the wasm and component query APIs. These are the policy-threading sites where a missed one silently disagrees.canonicalize_directives. Today its only lever isFormatConfig.number_display, which also rounds and pads numbers to display precision. That would change5 VACHR,-25.61and similar values, away from both bean-query andrledger format.rledger formatwrites. It is documented in §16. The work above becomes its own PR, with a parser-crate API change, and it only affectsrender_commasledgers.Differences that remain (pre-existing, not PRINT's)
IRAUSDlegs ofexample.beancount's payroll. rledger keeps source order.eventsorts differently among same-dayopens (loader sort).documentpaths. beancount makes them absolute; rledger keeps the path as written.OPEN ONsummary holding two currencies (theEquity:Conversions:Previoussummary), beancount lists EUR before USD and rledger lists USD first. This comes fromopen_summaries(BQLFROM OPEN ONdrops the opening balance from posting rows,balanceandsum(position)#2401) and shows inSELECTtoo.querystrings. These print with\nescapes, which is the canonical formatter'sescape_string.{{T}}round trip. A{{T}}lot with a non-terminating per-unit cost prints per-unit ({166.666…67 USD}), as beancount does. With rledger's exact-500 USDleg,rledger checkof the printed text then reports a 1E-26 residual. This is the canonical formatter'sPerUnitFromTotalrendering.Closes #2411
Closes #2426
🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr