Repository navigation
fix(query): JOURNAL position with cost + cumulative balance (closes #955) - #956
Merged
Merged
Conversation
#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]>
Contributor
There was a problem hiding this comment.
Pull request overview
Fixes JOURNAL <pattern> so the position column preserves cost annotations by emitting a cost-aware Value::Position (instead of a cost-stripping Value::Amount) in the default/no-AT case, aligning output with bean-query.
Changes:
- Resolve each posting into a
Positiononce and reuse it for both the running balance accumulator and the default position column value. - Emit
Value::Positionfor the default position column so{ cost }is retained. - Add an integration regression test covering a cost-bearing posting in
JOURNAL.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
crates/rustledger-query/src/executor/execution.rs |
Builds the JOURNAL position column from a resolved Position (preserving cost) while keeping AT-function behavior as Amount. |
crates/rustledger-query/tests/bql_integration_test.rs |
Adds a regression test asserting the position column returns Value::Position with cost intact. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Contributor
📊 Benchmark Results
vs main branch (2026-04-30)
What do these numbers mean?
|
Contributor
|
| Metric | Result |
|---|---|
| Check Compatibility | 99% |
| BQL Compatibility | 89% |
| 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
… 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]>
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]>
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]>
robcohen
enabled auto-merge (squash)
April 30, 2026 04:00
This was referenced Apr 30, 2026
robcohen
added a commit
that referenced
this pull request
Apr 30, 2026
#959) * fix(query): build_balances_with_filter returns fresh map (closes #958) `Executor::build_balances_with_filter` accumulated into the `self.balances` field without clearing it first. Sequential `BALANCES` queries on the same Executor produced wrong results: - Identical sequential calls: every balance doubled. - Different FROM filters: the second result was a union of both filters, matching no single query. The field's own doc comment described the intended semantic ("Account balances (built up during query)") — fresh-per-query, not cumulative across runs. The current behavior contradicted that intent. Fix: change the function to return a fresh `HashMap<InternedStr, Inventory>` rather than mutating `self.balances`. `execute_balances` consumes the return value directly. Both functions drop their `&mut self` requirement; `&self` suffices now. The `balances` field on `Executor` is removed entirely. After PR #956 (which removed JOURNAL's pollution of this field), `execute_balances` was the only remaining reader. The field is function-local working memory that had escaped to struct level; eliminating it makes sequential-query correctness a property of the type rather than a discipline callers must remember. Two regression tests: - `test_balances_idempotent_across_sequential_runs`: BALANCES then BALANCES on the same Executor returns identical rows. - `test_balances_with_different_from_filters_are_independent`: BALANCES FROM year=2024 then BALANCES FROM year=2025 returns only 2025 transactions in the second result, not a union of both years. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(query): build_balances_with_filter handles spanned-directive Executor (Copilot #959) Copilot review on PR #959 caught a pre-existing bug that surfaced clearly once the function was refactored: `build_balances_with_filter` iterated only `self.directives`, but when the `Executor` is built via `new_with_sources` (used when source-location info is needed), directives live in `self.spanned_directives` and `self.directives` is empty. The result was that BALANCES queries on a source-mapped Executor silently returned an empty result set. Fix: iterate whichever source is populated, mirroring `collect_postings` and the system-table builders (`build_balances_table`, `build_commodities_table`, etc.) which already had this pattern. ```rust let all_directives: Vec<&Directive> = if let Some(spanned) = self.spanned_directives { spanned.iter().map(|s| &s.value).collect() } else { self.directives.iter().collect() }; ``` New regression test `test_balances_works_with_spanned_directives_executor` constructs an Executor via `new_with_sources` and asserts BALANCES returns non-empty rows — would have failed silently before this fix. The bug was latent: only the in-file test suite uses `new_with_sources`, and only for SELECT-shaped queries. No production caller ran BALANCES through the spanned-directives path. But fixing it now makes the function consistent with the rest of the file's directive-iteration patterns and prevents future surprise. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
May 1, 2026
…) (#960) * fix(query): JOURNAL AT cost/units collapses balance column (closes #957) Issue #957: `JOURNAL ... AT cost` and `JOURNAL ... AT units` only applied the AT-mode transformation to the position column, leaving the balance column as the full cumulative inventory with `{ lot }` annotations. Python `bean-query` translates JOURNAL into a SELECT where both columns are wrapped in `summary_func(...)`, so AT cost collapses both position AND balance to cost-currency totals; AT units strips lots from both. Fix: in `execute_journal`, after building the row's `cumulative_balance` view, apply `Inventory::at_cost()` / `at_units()` symmetrically based on `query.at_function`. Reuses the same methods that `execute_balances` already uses correctly. Five-line change. Edge cases preserved by `Inventory::at_cost()` (verified against existing implementation): - Positions with cost: collapsed to cost-currency total. - Positions without cost: kept as-is (matches the AT cost position- side fallback Copilot flagged in PR #956). - Mixed cost currencies: stay multi-currency, no collapsing across cost currencies (matches bean-query behavior). Tests in `bql_integration_test.rs`: - `test_journal_at_cost_collapses_balance_to_cost_currency`: 10 AAPL { 150 USD } collapses to 1500 USD in the balance column. - `test_journal_at_units_strips_cost_from_balance`: AAPL with cost becomes bare 10 AAPL units in balance. - `test_journal_at_cost_balance_preserves_no_cost_positions`: USD-only ledger under AT cost — USD passes through unchanged. - `test_journal_at_cost_balance_keeps_mixed_cost_currencies`: USD lot + EUR lot of same commodity — balance has both `1500 USD` and `650 EUR` cost-currency totals, not collapsed. Compat suite: - New `journal-assets-at-cost` and `journal-assets-at-units` queries in `tests/compatibility/bql-queries.toml` so this divergence is regression-protected against `bean-query` going forward. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * perf(query): precompute JOURNAL AT mode once per query (Copilot #960) Copilot review on PR #960 caught a real per-row allocation: each matched posting called `query.at_function.to_uppercase()` twice — once for `position_value`, once for `balance_for_row` — allocating a fresh String every time. For a wildcard JOURNAL over 10K transactions with 2 postings each, that's ~40K String allocations the inner loop didn't need. Fix: precompute the AT mode once per query into a Copy enum. ```rust #[derive(Copy, Clone, PartialEq, Eq)] enum AtMode { None, Cost, Units, Other } impl AtMode { const fn from_query(at_function: Option<&str>) -> Self { match at_function { None => Self::None, Some(s) if s.eq_ignore_ascii_case("COST") => Self::Cost, Some(s) if s.eq_ignore_ascii_case("UNITS") => Self::Units, Some(_) => Self::Other, } } } ``` The inner loop's two AT-mode matches now branch on a `Copy` enum, no allocations, no string comparison per row. `Other` covers any unrecognized AT mode and routes to the same default branch as before, preserving backward-compatible behavior. Same allocation pattern exists in `execute_balances`'s AT-mode handling (lines 880+); leaving that as a follow-up since it's outside this PR's scope and would benefit from the same enum. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * perf(query): precompute JOURNAL AT mode once per query (Copilot #960) Copilot review on PR #960 caught a real per-row allocation: each matched posting called `query.at_function.to_uppercase()` twice — once for `position_value`, once for `balance_for_row` — allocating a fresh String every time. For a wildcard JOURNAL over 10K transactions with 2 postings each, that's ~40K String allocations the inner loop didn't need. Fix: precompute the AT mode once per query into a Copy enum. ```rust #[derive(Copy, Clone, PartialEq, Eq)] enum AtMode { None, Cost, Units, Other } impl AtMode { const fn from_query(at_function: Option<&str>) -> Self { match at_function { None => Self::None, Some(s) if s.eq_ignore_ascii_case("COST") => Self::Cost, Some(s) if s.eq_ignore_ascii_case("UNITS") => Self::Units, Some(_) => Self::Other, } } } ``` The inner loop's two AT-mode matches now branch on a `Copy` enum, no allocations, no string comparison per row. `Other` covers any unrecognized AT mode and routes to the same default branch as before, preserving backward-compatible behavior. Same allocation pattern exists in `execute_balances`'s AT-mode handling (lines 880+); leaving that as a follow-up since it's outside this PR's scope and would benefit from the same enum. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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
Closes both bugs in issue #955.
Behavior change (heads-up for users)
This PR changes JOURNAL output for wildcard patterns like
JOURNAL "Assets". The balance column was previously per-account (each row showed only its own account's running inventory); after this PR, the balance column is the cumulative inventory across every WHERE-filtered posting that matched the pattern. This matches Pythonbean-queryexactly (see investigation below) and aligns with the cumulativebalancesemantic adopted for SELECT in PR #940.For single-account patterns (
JOURNAL "Assets:Cash"), the output is unchanged — per-account is the same as cumulative when only one account matches.Bug 1: position column dropped cost annotations
crates/rustledger-query/src/executor/execution.rs::execute_journalThe builder computed a cost-aware
Positionsolely for the per-account balance accumulator, then builtposition_valueseparately asValue::Amount(units)— which by definition can't carry a cost. So the balance column rendered with{ cost }correctly while the position column dropped it.Fix: lift the
Positionresolution out of the balance-only branch and use it for both the running balance accumulator and the default-case position column. AT-COST and AT-UNITS branches kept onValue::Amountsince they intentionally project away the position shape.Bug 2: balance was per-account, not cumulative
For
JOURNAL "Assets"on a ledger with both IRAUSD (inPreTax401k) and USD (inCash) holdings, Pythonbean-queryrendered the balance as18500.00 IRAUSD 3262.01 USD— the cumulative inventory across all matched accounts. We rendered only this row's account's slice (18500.00 IRAUSD).Investigation: beanquery's
compiler.py::transform_journaltranslates JOURNAL into:The
balancecolumn there is the cumulative running inventory across every WHERE-filtered posting — same semantic we already adopted for SELECT in PR #940. The JOURNAL builder was missed in that change.Fix: replace the per-account
self.balances.entry(...)lookup inexecute_journalwith a single cumulativeInventoryscoped to the JOURNAL run. Each row gets a clone of that inventory at that point.Drive-by:
execute_journalno longer mutatesself— now takes&selfrather than&mut self.Tests
Five new regression tests in
bql_integration_test.rs:test_journal_position_column_preserves_cost— Bug 1: position column carriesValue::Position(...)with the cost annotation intact.test_journal_balance_is_cumulative_across_matched_accounts— Bug 2: two-account scenario where the cumulative balance after row 2 must include both currencies. Per-account semantics would have failed it.test_journal_from_clause_filters_cumulative_balance— locks in thatJOURNAL ... FROM <filter>correctly composes with the cumulative inventory (FROM-non-matching transactions stay out).test_journal_at_cost_position_is_amount_not_position— guardsAT costagainst future regression (still emitsValue::Amountof the cost-currency total).test_journal_at_units_position_is_amount_not_position— same guard forAT units.Verification
cargo test -p rustledger-query: 493 tests pass (was 488, +5 new)cargo test -p rustledger: 392 tests passcargo clippy --all-features --all-targets -- -D warnings: cleancargo fmt --check: cleanCompat impact
Should resolve a substantial portion of the
journal-assetsBQL compatibility failures (~18 tests). Some rows likely tripped on Bug 1, others on Bug 2, and a few on both. We'll see the breakdown on the next compat run after merge.Known limitations / follow-ups
Discovered during deep self-review of this PR:
JOURNAL ... AT costandAT unitsshould also collapse the balance column to cost-currency / units-only totals, matchingbean-query'ssummary_func(balance)translation. We only collapse the position column. Out of scope here.Executor::build_balances_with_filterdoesn't clearself.balancesbefore populating, so sequentialBALANCESqueries on the same Executor double-count. Pre-existing latent bug, surfaced because removing JOURNAL'sself.balancesside effect (this PR) made the underlying issue more visible.Test plan
journal-assetspass count increase from 12 toward the upper boundrledger query "JOURNAL 'Assets'" example.beancountshows cost annotations on cost-bearing positions and cumulative multi-currency balancesCloses #955
🤖 Generated with Claude Code