Repository navigation
fix(query): JOURNAL AT cost/units collapses balance column (closes #957) - #960
Merged
Merged
Conversation
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]>
Contributor
There was a problem hiding this comment.
Pull request overview
This PR fixes a BQL compatibility gap where JOURNAL ... AT cost / AT units previously applied the AT-mode projection only to the position column, leaving the balance column as the unprojected cumulative inventory (including lot annotations). The change makes JOURNAL mirror bean-query’s summary_func(balance) behavior.
Changes:
- Apply
Inventory::at_cost()/Inventory::at_units()to the per-row JOURNAL balance whenAT cost/AT unitsis specified. - Add 4 integration regression tests covering AT-mode balance projection and edge cases (no-cost positions; mixed cost currencies).
- Add 2 compatibility-suite queries to keep the behavior regression-protected against
bean-query.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
crates/rustledger-query/src/executor/execution.rs |
Projects JOURNAL’s balance column via at_cost() / at_units() when AT is used, matching bean-query. |
crates/rustledger-query/tests/bql_integration_test.rs |
Adds regression tests validating AT-mode balance behavior and edge cases. |
tests/compatibility/bql-queries.toml |
Extends the compat suite with JOURNAL 'Assets' AT cost/units queries to prevent future regressions. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Codecov Report❌ Patch coverage is
📢 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 | 91% |
| 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
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]>
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]>
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
JOURNAL ... AT costandJOURNAL ... AT unitsonly applied the AT-mode transformation to the position column, leaving the balance column as the full cumulative inventory with{ lot }annotations. Pythonbean-querytranslatesJOURNAL ... AT <mode>into a SELECT where both the position and balance columns are wrapped insummary_func(...), so AT cost collapses both to cost-currency totals; AT units strips lots from both. This PR makes our JOURNAL match.Reproducer
10 AAPL { 150 USD }(full lot detail).1500 USD(cost-currency total, matchingbean-query).Fix
In
execute_journal, after building the row'scumulative_balanceview, applyInventory::at_cost()/at_units()symmetrically toquery.at_function. Reuses the existing methods thatexecute_balancesalready uses correctly. Five lines added:Edge cases preserved
Inventory::at_cost()already has the right semantics (verified againstcrates/rustledger-core/src/inventory/mod.rs:554):10 AAPL { 150 USD }becomes1500 USD).1500 USD 650 EUR), not collapsed across cost currencies. Matchesbean-query'scost(balance).Tests
Four new regression tests in
crates/rustledger-query/tests/bql_integration_test.rs:test_journal_at_cost_collapses_balance_to_cost_currency— primary case:10 AAPL { 150 USD }→ balance1500 USD, no lot annotation.test_journal_at_units_strips_cost_from_balance—AAPL { 150 USD }→ balance10 AAPL, no lot annotation.test_journal_at_cost_balance_preserves_no_cost_positions— USD-only ledger under AT cost: USD passes through unchanged. Locks in the no-cost-fallback behavior.test_journal_at_cost_balance_keeps_mixed_cost_currencies— USD lot + EUR lot of same commodity: balance retains both1500 USDand650 EUR, not collapsed across currencies.Compat suite
Two new queries in
tests/compatibility/bql-queries.toml:These exercise the new code path against
bean-queryso future regressions are caught by the compat run.Verification
cargo test -p rustledger-query: 497 tests pass (was 493, +4 new)cargo clippy --all-features --all-targets -- -D warnings: cleancargo fmt --check: cleanCompat impact
Closes a known divergence from
bean-query. Should move the BQL match rate up on the next compat run once the new queries land in the suite.Test plan
journal-assets-at-cost/journal-assets-at-unitsqueries should pass byte-for-byte againstbean-query(modulo whitespace) on relevant fixtures1500 USDin the balance columnOut of scope
Stacks cleanly with PR #959 (which fixes
BALANCESnon-idempotency). The two PRs touch different functions and merge in any order.Closes #957
🤖 Generated with Claude Code