Repository navigation
fix(query): summarize the ledger before FROM ... OPEN ON, as beanquery does - #2410
Merged
Merged
Conversation
…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
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Contributor
📊 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?
|
Contributor
✅ Compatibility Test Results
What's tested
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
Member
Author
Deep review (head
|
This was referenced Sep 24, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.SELECT account, sum(position) FROM OPEN ON 2024-02-01 GROUP BY accountAssets:BankEquity:OpeningEquity:Opening-BalancesExpenses:FoodHow
beanquery applies
OPEN ONwith beancount'ssummarize.open(sources/beancount.py,_BeancountTable.prepare). The newexecutor/summarize.rsreproduces it, in beancount's order.@conversion), the residual goes toaccount_previous_conversions.account_previous_earnings, at cost.S, narratedOpening balance for '<account>' (Summarization). Each lot gets a posting at its cost, date and label, balanced by its cost againstaccount_previous_balances.Executor::window_transactionsis the one definition of the date window:OPEN ON's summaries, then the ledger's transactions in[open, close).scan_postings(SELECT,BALANCES) andJOURNALboth iterate it.JOURNALused to walk the ledger itself and applied only theFROMfilter expression, ignoringOPEN ONandCLOSE ONaltogether. ACLOSE ONbefore theOPEN ONis refused, as beanquery refuses it. The summaries go through the sameFROM/CLOSE ON/WHEREfilters and the same booking-engine replay as any other transaction, so the rows, the runningbalance,account_balanceandBALANCESall start from them. The old code replayed pre-date transactions only intoaccount_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
BALANCESandreport balancesrealize 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::transactionbecomesTransactionRef<'a>(breaking; in the CHANGELOG). It isLedger(&'a Transaction)orSynthesized(Arc<Transaction>)and derefs toTransaction. 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,LedgerincludingfromCache; 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, asget_previous_accountsbuilds it. The raw defaultEquity:Opening-Balancesnamed a root that a ledger withoption "name_equity" "Eigenkapital"doesn't have. The component's exported options use it too, sosession.clampand hosts also get the right names on such ledgers. On default-root ledgers the names are byte-identical.run_interactivetakes the caller'sShellSettings. 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_totalsis rewritten. It asserted thatOPEN ONleft everyBALANCEStotal 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, andEquity:Earnings:Previousholds the rest.Verification
@conversions, a closed account), severalOPEN ONdates each, seven query shapes:SELECTwithbalance, summary rows with narration,sum(position),sum(cost(position)),BALANCES, andOPEN ON+CLOSE ON.balanceand total agrees.BALANCESrow order (BQLBALANCESorders rows by account name, beanquery by account_sortkey #2409),CLOSE ON's conversions entry (BQL:FROM ... CLEARis ignored, andCLOSE ONomits the conversions entry #2406), andFROM <expr> OPEN ONnot parsing (BQL:FROM <expr> OPEN ON / CLOSE ON / CLEARfails to parse #2407).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 tomain.beancount.name_equityfails the renamed-root test.-D warningsare clean.OPEN ON: byte-identical to main (d148fdba62) on fifo, avg and investment 20k forBALANCES,sum(position), abalanceSELECTandJOURNAL. Callgrind onBALANCESfifo-20000: +0.02%.OPEN ONcost: the same wall time as main within ±0.02 s, and RSS within 4 MB.Behavior change
BALANCES FROM OPEN ONon income-statement accounts. On the #2401 differential's earnings ledger:Income:SalaryExpenses:RentEquity:Earnings:PreviousFollow-ups filed
FROM ... CLEARis ignored, andCLOSE ONomits the conversions entry #2406:CLEARis ignored andCLOSE ONomits its conversions entry. Both are the same machinery, now in place.FROM <expr> OPEN ON / CLOSE ON / CLEARfails to parse #2407:FROM <expr> OPEN ONdoes not parse.account_previous_*option values are relative to the equity root in beancount, and rledger rejects that form with E7002. Needs a decision.BALANCESorders rows by account name, beanquery by account_sortkey #2409:BALANCESrow order.PRINTignoresFROM ... OPEN ON/CLOSE ON#2411:PRINTignoresOPEN ON/CLOSE ON. It prints entries, not postings, so it needs the full summarized entry stream (active Opens, last Prices).Closes #2401
🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr