Repository navigation
fix(query): make balance a cumulative WHERE-filtered total (closes #929) - #940
Merged
Merged
Conversation
…929) The `balance` column was returning the per-account running balance, matching what bank statements show but not what bean-query exposes. As a result, queries like SELECT year, month, convert(last(balance), 'USD') WHERE account ~ '^Assets' — the canonical "portfolio value over time" pattern — produced nonsense in rledger while bean-query gave the correct multi-currency end-of-month inventory. Per the BQL spec and Martin Blais's original 2014 design discussion, `balance` is intended as a single Inventory that accumulates across all WHERE-filtered postings in iteration order, regardless of account. This is the semantic that lets a single query language render both journals and balance reports. See: - https://beancount.github.io/docs/beancount_query_language/ - beancount/beanquery#50 This commit: * Adds a separate `account_balance` column for the per-account view that the old `balance` provided. Existing rledger queries that relied on per-account semantics should switch to `account_balance`. * Reworks `PostingContext` to carry both balances and updates the cumulative *after* WHERE passes (so rejected postings don't pollute the running total). * Same dual tracking in `build_postings_table` for queries that go through `#postings` directly. * Four integration tests covering: cumulative across same account, cumulative carrying across different accounts, per-account isolation via `account_balance`, and the WHERE-pollution invariant. Verified end-to-end against bean-query 0.2.0 on a bean-example file: 30 rows, every value matches exactly (only column-header text and whitespace differ). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
📊 Benchmark Results
vs main branch (2026-04-28)
What do these numbers mean?
|
Contributor
|
| Metric | Result |
|---|---|
| Check Compatibility | 99% |
| BQL Compatibility | 84% |
| Full AST Match | 99% |
| Total Files | 782 |
What's tested
- Check: Exit codes and error counts match
bean-check - BQL: Query results match
bean-query - Files: ~800 test files downloaded from 10+ beancount repositories
Full results available in workflow artifacts
2 of 4 tasks
Contributor
There was a problem hiding this comment.
Pull request overview
This PR aligns rledger’s query balance column with bean-query semantics by making it a single cumulative running Inventory over the WHERE-filtered postings stream, and introduces account_balance to preserve the previous per-account running-balance behavior.
Changes:
- Change
balanceto be cumulative across all WHERE-matched postings in iteration order; addaccount_balancefor per-account running totals. - Update posting collection and
#postingssystem table to track both cumulative and per-account balances. - Add integration tests for cumulative vs per-account semantics and WHERE pollution behavior; expose the new column in completions.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/rustledger-query/tests/bql_integration_test.rs | Adds integration coverage for cumulative balance, new account_balance, and WHERE-filter non-pollution. |
| crates/rustledger-query/src/executor/types.rs | Extends PostingContext to carry both cumulative and per-account inventories. |
| crates/rustledger-query/src/executor/mod.rs | Implements dual balance tracking in posting collection and #postings table; adds account_balance column to #postings. |
| crates/rustledger-query/src/executor/evaluation.rs | Adds expression support for account_balance and updates balance semantics in evaluation. |
| crates/rustledger-query/src/completions.rs | Advertises account_balance and updates balance description. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Five fixes from Copilot's review:
* **Preserve cost basis in account/cumulative balances.** The new
accumulators were updating with `Position::simple(units)`, dropping
cost lot information for cost-bearing postings (lots, securities).
This made running balances inconsistent with the `position` column
and with sibling balance code (`build_balances_with_filter`,
`build_postings_table`). Add an inline `resolve_position` closure
that reproduces the cost-aware Position construction those use, and
call it for the OPEN ON fast-path, the per-account update, and the
cumulative update.
* **Skip the wasted clone when WHERE is None.** Previously
`ctx.balance` was set to `Some(cumulative_balance.clone())`
unconditionally, then overwritten after the WHERE check with another
clone. When there's no WHERE clause, nothing reads the pre-update
snapshot. Initialize as `where_clause.map(|_| ...)` instead so the
pre-update clone happens only when WHERE actually evaluates.
* **Locate test rows by account, not row index.** The two new tests
used `result.rows[3]` after `ORDER BY date`, but the executor's
sort isn't stable for equal date keys. Txn 4 has both Savings and
Checking on 2024-01-25, so the index was non-deterministic. Add a
`find_balance_by_account` helper that scans for the right account
match, and update both tests. Also append `, account` to the
ORDER BY so result order is reproducible across implementations.
* **Cover the full set of Checking postings in the per-account test.**
The original assertion was wrong by 80 USD because it forgot txn 5
("More groceries", -80). Updated to assert the post-all-postings
value (3725) and inspect every Checking row in iteration.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This was referenced Apr 28, 2026
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
Apr 30, 2026
… part 2) Issue #955 Bug 2: Python `bean-query` shows multi-currency JOURNAL balances that we were missing — e.g. for `JOURNAL "Assets"` with both IRAUSD and USD held across different `Assets:*` accounts, Python's balance column shows the cumulative total `18500.00 IRAUSD 3262.01 USD` where we showed only this account's slice. Investigation in beanquery's compiler.py: JOURNAL translates to a SELECT where the `balance` column is `summary_func(balance)` — and `balance` in beanquery's environment is the cumulative running inventory across every WHERE-filtered posting, not per-account. We adopted the same cumulative semantic for SELECT in PR #940 but missed the JOURNAL builder, which kept its old per-account behavior. Fix: replace the per-account `self.balances.entry(...)` lookup in `execute_journal` with a single cumulative `Inventory` scoped to the JOURNAL run. Each row gets a clone of that inventory at that point. Drive-by: the function no longer mutates `self`, so it now takes `&self` rather than `&mut self`. New regression test `test_journal_balance_is_cumulative_across_matched_accounts` builds a two-account scenario where the cumulative balance after row 2 must include both currencies. Per-account semantics would have failed it. Closes #955 (combined with the Bug 1 fix in this same PR). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
3 tasks
robcohen
added a commit
that referenced
this pull request
Apr 30, 2026
) (#956) * fix(query): preserve cost annotation in JOURNAL position column (closes #955 part 1) Issue #955 reported that `JOURNAL <pattern>` output dropped cost annotations in the position column. A posting like Assets:Brokerage 10 AAPL { 150 USD } rendered as `10 AAPL` in the position column even though the balance column correctly showed `10 AAPL { 150 USD }`. Initial diagnosis blamed the renderer; turned out the renderer was correct and the bug was in the journal builder. `crates/rustledger-query/src/executor/execution.rs::execute_journal`: The builder computed a cost-aware `Position` solely for feeding into the per-account balance accumulator, then constructed `position_value` separately as `Value::Amount(units)` — a bare amount that by definition cannot carry a cost annotation. So the balance column saw the cost-aware `Position`, and the position column saw a stripped `Amount`. Fixed by: - Lifting the `Position` resolution to the top of the row-builder so it's available for both the balance accumulator and the position column. - Default position column case: emit `Value::Position(pos)` so the renderer at `output.rs::format_value`'s `Value::Position` arm applies its existing `{ cost }` formatting. - AT-COST and AT-UNITS branches kept on `Value::Amount` since they intentionally project away the position shape (AT COST returns cost-currency total; AT UNITS strips cost by definition). New regression test `test_journal_position_column_preserves_cost` asserts the position column carries `Value::Position(...)` with the cost annotation intact. Out of scope for this PR: #955 also describes a multi-currency balance divergence (Python `bean-query` shows other-currency positions in a per-account inventory we don't surface). That sub-issue needs the upstream beancount-v2 example_ledger.beancount to investigate; the file isn't committed locally and our local fixtures don't exhibit the pattern. Left in #955 for follow-up. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(query): JOURNAL balance is cumulative across matched postings (#955 part 2) Issue #955 Bug 2: Python `bean-query` shows multi-currency JOURNAL balances that we were missing — e.g. for `JOURNAL "Assets"` with both IRAUSD and USD held across different `Assets:*` accounts, Python's balance column shows the cumulative total `18500.00 IRAUSD 3262.01 USD` where we showed only this account's slice. Investigation in beanquery's compiler.py: JOURNAL translates to a SELECT where the `balance` column is `summary_func(balance)` — and `balance` in beanquery's environment is the cumulative running inventory across every WHERE-filtered posting, not per-account. We adopted the same cumulative semantic for SELECT in PR #940 but missed the JOURNAL builder, which kept its old per-account behavior. Fix: replace the per-account `self.balances.entry(...)` lookup in `execute_journal` with a single cumulative `Inventory` scoped to the JOURNAL run. Each row gets a clone of that inventory at that point. Drive-by: the function no longer mutates `self`, so it now takes `&self` rather than `&mut self`. New regression test `test_journal_balance_is_cumulative_across_matched_accounts` builds a two-account scenario where the cumulative balance after row 2 must include both currencies. Per-account semantics would have failed it. Closes #955 (combined with the Bug 1 fix in this same PR). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(query): JOURNAL test coverage from #956 self-review Three additional regression tests surfaced by the deep review: 1. `test_journal_from_clause_filters_cumulative_balance` — locks in that `JOURNAL ... FROM <filter>` correctly excludes non-FROM-matching transactions from the cumulative inventory. A wildcard pattern with two transactions where one matches `year = 2024` and one doesn't should produce a single row whose balance is only the matched transaction. 2. `test_journal_at_cost_position_is_amount_not_position` — locks in that `AT cost` keeps emitting `Value::Amount` (cost-currency total, not the cost-bearing Position). Guards against future refactors accidentally extending the Position-emitting default branch into the AT modes. 3. `test_journal_at_units_position_is_amount_not_position` — same guard for `AT units`. Note: the AT cost / AT units balance-column behavior diverges from bean-query (it should also be cost-collapsed) but that's tracked separately in #957, not part of this PR. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(query): note AT COST fallback to bare units (Copilot #956) Copilot review on PR #956 caught that the comment in execute_journal implied AT COST always returns the cost-currency total. The implementation falls back to the original units when the posting has no resolvable cost annotation. Updated the comment to reflect that. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
This was referenced May 11, 2026
Merged
robcohen
added a commit
that referenced
this pull request
May 11, 2026
…e it (closes #1080) (#1085) * fix(query): skip cumulative-balance clone when query doesn't reference it (closes #1080) PR #940 introduced two computed columns to the BQL executor: balance (cumulative WHERE-filtered running total) and account_balance (per-account running total). Each PostingContext built in collect_postings carried snapshot clones of both. For long-running WHERE-filtered scans like SELECT account WHERE account ~ "^Assets" LIMIT 10 on a 22k-posting ledger, the cumulative_balance Inventory grows monotonically — meaning we cloned a thousand-position Inventory ~2-3 times per posting, producing ~12 GB of total allocation churn and ~5.8 GB peak WASM heap (reported on issue #1080). The existing optimization comment at line 477-478 gated the pre-WHERE clone on "is there a WHERE clause at all?". That gate fired for any query with a WHERE, regardless of whether anything actually read the column. The user's query has WHERE but reads neither balance nor account_balance — we were doing the entire clone churn for nothing. Fix: walk the SelectQuery AST once at the top of collect_postings via the new query_references_column helper, checking every relevant query part (SELECT targets, WHERE, GROUP BY, HAVING, PIVOT BY, ORDER BY, FROM filter). Use the result to gate: * The per-posting cumulative_balance.clone() (pre-WHERE + post-WHERE) * The cumulative_balance.add() update (no-op if no one reads balance) * The account_balances.entry().or_default().add() update * The account_balances.get().cloned() snapshot Queries that reference neither column (the common case) skip the entire balance-tracking + clone path. Queries that reference either keep the existing semantics bit-for-bit — existing tests all pass. Added test_query_references_column_covers_all_query_parts: parses SELECT-statements that reference balance in every position (SELECT target, WHERE, ORDER BY, GROUP BY, function arg, BETWEEN bound) and confirms the helper detects each. Plus negative cases for queries that don't reference balance. Closes #1080 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix: address Copilot review on PR #1085 Two valid findings: (1) expr_references_column did not traverse the OVER clause of Expr::Window — partition_by and order_by inside the window spec were ignored. A query like SUM(amount) OVER (PARTITION BY balance) would have produced a false negative and skipped the cumulative balance materialization, breaking the query at runtime. Added recursion through call.over.partition_by and call.over.order_by[].expr. Test: test_expr_references_column_walks_window_over_clause. (2) Pre-WHERE clone of cumulative_balance was unconditional whenever needs_balance was true. Pre-fix the gate was where_clause.is_some() — a query like SELECT balance FROM #postings (no WHERE) did 1 clone per posting, but my first cut did 2. Tightened the pre-WHERE gate to where_reads_balance (does the WHERE clause specifically read balance?). The post-WHERE refresh still fires whenever needs_balance is true. account_balance keeps the unconditional needs_account_balance gate because (unlike balance) it's NOT refreshed post-WHERE — its single slot is always the pre-WHERE update value, so the gate must allow SELECT account_balance to read it even without a WHERE. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
5 of 6 tasks
robcohen
added a commit
that referenced
this pull request
May 11, 2026
… OOM (#1086) (#1087) * perf(core): use im::Vector for Inventory positions to enable O(1) snapshots (#1086) Changes Inventory.positions from Vec<Position> to im::Vector<Position> so cumulative-balance snapshots in JOURNAL/SELECT cost O(1) (Arc bump on the persistent RRB-tree root) instead of O(M) per row. This makes the per-row clone in `execute_journal` and the cumulative-balance context build in `collect_postings` non-load-bearing for memory. ## The problem PR #940 added a cumulative `balance` column to JOURNAL output. The executor materializes every row's `PostingContext` (and the JOURNAL hot loop materializes every row) holding a snapshot of `cumulative_balance` at that point. With Vec backing, each snapshot is a full O(M) clone of the position list. Memory scales as O(N·M) in the worst case, O(N²) when each posting opens a unique lot. Native stress test, JOURNAL on N rows with N unique lots: N=500: 25 MB / 0.2s N=1000: 63 MB / 0.9s N=2000: 206 MB / 3.7s N=5000: 1.2 GB / 12.7s N=10000: 4.7 GB → panic WASM (4 GB linear memory ceiling) dies well before native does. ## The fix `im::Vector` is a persistent RRB-tree. `.clone()` bumps an Arc on the root and shares the entire tree with the source. Subsequent mutations on either side path-copy only the affected nodes. Net effect: holding N snapshots that descend from a single base costs O(base + sum deltas), not O(N * base). After fix, same workload: N=500: 19 MB / 0.2s N=1000: 22 MB / 0.9s N=2000: 31 MB / 3.5s N=5000: 61 MB / 11.6s N=10000: 108 MB / 50s Realistic active-trader workload (alternating buy/sell, FIFO): N=20000 old: 18.8 GB / 3:27 N=20000 new: 196 MB / 3:07 (99% memory reduction) ## Tradeoff `im::Vector` mutations are O(log M) per op, vs O(1) amortized for `Vec`. The constant factor is non-trivial. Booking benchmarks regress: reduce_fifo/10: 3.22 µs → 4.07 µs (+26%, +85 ns/op) reduce_fifo/100: 189 µs → 352 µs (+86%, +1.6 µs/op) reduce_fifo/500: 4.37 ms → 13.87 ms (+217%, +19 µs/op) The per-op overhead scales with inventory size M. The users who feel the booking tax are users with very large inventories — the same users who hit the JOURNAL OOM today. Net positive for them. For typical users (M <= 10), per-op overhead is ~85 ns; total impact on `rledger check` is sub-millisecond per ledger. ## Surface changes - `Inventory::positions()` now returns an iterator (was `&[Position]`) to abstract over the backing type - Added `Inventory::position_list()` returning `Vec<&Position>` for the few call sites that need slice-style access (BQL test fixtures and integration tests) - Internal `self.positions.push(...)` -> `push_back(...)` for `im::Vector` API - `rkyv` derives removed from `Inventory`: `im::Vector` has no rkyv impl, and no code path archives an Inventory (confirmed during the SmallVec experiment for #1069). Serde wire format unchanged (sequence-typed, identical for both backings). ## Why not a hybrid (Vec for booking, im::Vector for JOURNAL only) Considered. A clean implementation requires either generic-over- backing on Inventory (substantial refactor) or a delta-export API on every mutation (new public surface). Either path is reasonable follow-up if the booking regression bites someone in real measurement, but pure-Vec snapshots cannot avoid the O(N*M) memory shape — they would be free of structural sharing. ## Known follow-ups - `rustledger/src/cmd/query/output.rs:154` panics with "Formatting argument out of range" when a single rendered Inventory cell exceeds format-machinery limits (e.g. 5000+ positions in one row). Pre-existing; surfaces in the adversarial unique-lot workload after the memory fix lifts the OOM. Will file separately. Closes #1086 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * chore: regenerate cargo-vet exemptions * fix(query): cap text-output column width at u16::MAX to avoid stdlib panic `std::fmt::rt::Argument::from_usize` panics with "Formatting argument out of range" when a dynamic `{:width$}` width parameter exceeds `u16::MAX = 65,535` — a stdlib internal limit on the format-args encoding for runtime-supplied widths. This was masked by the OOM fixed in the previous commit, but the previously-OOM-ing adversarial JOURNAL workload now reaches the formatter and trips this panic instead. Repro before this commit (post-im::Vector fix): rledger query stress_lots_3000.beancount "JOURNAL 'Assets:Stocks'" -> panic at output.rs:154: "Formatting argument out of range" The threshold is exactly where stdlib's u16 cap bites: N=2700 lots: cell width ~64,797 chars -> ok N=2800 lots: cell width ~67,197 chars -> panic ## Fix Clamp every column width at `u16::MAX` before passing it to `write!`. When the formatted cell content exceeds the cap, `write!` writes the content verbatim — `{:width$}` does not truncate when content is wider than the requested width, it just produces no padding. Padding to >65k chars couldn't align meaningfully in any terminal anyway, so this is the correct fallback behavior. After this commit, the same stress workload completes cleanly: N=3000: 40 MB / 7.8s exit 0 N=5000: 59 MB / 21.2s exit 0 N=10000: 106 MB / 95s exit 0 ## Test Added `test_write_text_does_not_panic_on_cells_wider_than_u16_max`: build a `QueryResult` with a 70,000-char cell and assert `write_text` returns `Ok` and emits the content verbatim. Without the cap, this test panics inside std::fmt; with the cap, it passes. Refs #1086 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(query): drop Vec<&Position> allocations + clarify positions doc Addresses Copilot review feedback on PR #1087: 1. `executor/mod.rs` NUMBER on `Value::Inventory`: was collecting `inv.positions()` into `Vec<&Position>` to check empty/single- currency. Rewritten as a single pass over the iterator that tracks the first currency and running total, bailing to `Null` on any currency mismatch. No allocation in the hot path. 2. `executor/functions/util.rs` CONVERT: was collecting `result.positions()` into `Vec<&Position>` to determine empty/single/many. Rewritten to peek the first two positions; the single-match `Amount` is cloned eagerly (O(1) — `Decimal` + interned `currency`) so the iterator borrow can be dropped before `result` is moved into the boxed `Value::Inventory`. 3. `wasm/convert.rs` `value_to_cell`: was calling `position_list()` (allocates `Vec<&Position>`) just to iterate once. Switched back to iterating `inv.positions()` directly into the `.collect()` for the serializable `CellValue::Inventory`. 4. `inventory/mod.rs` `positions` field doc: previously claimed "no measurable regression at realistic inventory sizes" — stale, copied from the prior `SmallVec` experiment. Rewritten to state the actual measured trade-off (+85 ns/op at M=10, +1.6 µs/op at M=100, +19 µs/op at M=500) and acknowledge the pre-1.0 break of dropping `rkyv` derives from `Inventory`. No behavior change; all 1046 tests on touched crates still pass. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> Co-authored-by: rustledger-bot[bot] <257329324+rustledger-bot[bot]@users.noreply.github.com>
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.
Summary
The
balancecolumn was returning the per-account running balance — bank-statement-style — but bean-query'sbalanceis a single cumulative Inventory across all WHERE-filtered postings in iteration order. As a result, the canonical "portfolio value over time" queryproduced nonsense in rledger (different value every row, often a single account's balance happened to come last). Reproduced against bean-query 0.2.0 on a
bean-examplefile: every one of 30 rows disagreed.This is by design in beanquery and is documented in the BQL spec — the cumulative semantic is what unifies "journal" and "balance" reports under one query language. See also beanquery/issues/50 for known caveats.
Changes
balanceis now cumulative — matches bean-query exactly, verified row-for-row.account_balanceis new — the per-account running balance the oldbalanceexposed, kept for queries that explicitly want that view.PostingContextcarries both. Cumulative is updated after WHERE passes (so rejected postings don't pollute the running total). Per-account is updated unconditionally (always reflects ledger truth).build_postings_table(the#postingstable) gets the same dual tracking.Migration impact
Existing rledger queries that depend on
balancereturning the per-account view will silently change behavior. The migration is mechanical: renamebalance→account_balancewherever the bank-statement view was the intent. We're 0.x and this is the only cleanly compat-correct path; postponing it bakes in a divergence forever.Tests
bql_integration_test.rscovering: same-account cumulative, cross-account cumulative carrying, per-account isolation viaaccount_balance, and WHERE-pollution invariance.bean-exampleoutput — every value matches.Closes #929
🤖 Generated with Claude Code