Skip to content

fix(query): JOURNAL AT cost/units collapses balance column (closes #957) - #960

Merged
robcohen merged 5 commits into
mainfrom
fix/journal-at-mode-balance
May 1, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/journal-at-mode-balance

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

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 ... AT <mode> into a SELECT where both the position and balance columns are wrapped in summary_func(...), so AT cost collapses both to cost-currency totals; AT units strips lots from both. This PR makes our JOURNAL match.

Reproducer

cat > /tmp/x.bean <<'BEAN'
2024-01-01 open Assets:Brokerage
2024-01-01 open Equity:Opening
2024-02-01 * "Buy AAPL"
  Assets:Brokerage  10 AAPL { 150 USD }
  Equity:Opening   -1500 USD
BEAN
rledger query "JOURNAL 'Assets:Brokerage' AT cost" /tmp/x.bean
  • Before: balance column shows 10 AAPL { 150 USD } (full lot detail).
  • After: balance column shows 1500 USD (cost-currency total, matching bean-query).

Fix

In execute_journal, after building the row's cumulative_balance view, apply Inventory::at_cost() / at_units() symmetrically to query.at_function. Reuses the existing methods that execute_balances already uses correctly. Five lines added:

let balance_for_row = if let Some(at_func) = &query.at_function {
    match at_func.to_uppercase().as_str() {
        "COST" => cumulative_balance.at_cost(),
        "UNITS" => cumulative_balance.at_units(),
        _ => cumulative_balance.clone(),
    }
} else {
    cumulative_balance.clone()
};

Edge cases preserved

Inventory::at_cost() already has the right semantics (verified against crates/rustledger-core/src/inventory/mod.rs:554):

  • Positions with cost → collapsed to cost-currency total (10 AAPL { 150 USD } becomes 1500 USD).
  • Positions without cost → returned as-is. Matches the AT-cost position-side fallback Copilot flagged in PR fix(query): JOURNAL position with cost + cumulative balance (closes #955) #956: when no cost is resolvable, fall back to the original units, don't error.
  • Mixed cost currencies → multi-currency inventory preserved (1500 USD 650 EUR), not collapsed across cost currencies. Matches bean-query's cost(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 } → balance 1500 USD, no lot annotation.
  • test_journal_at_units_strips_cost_from_balance — AAPL { 150 USD } → balance 10 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 both 1500 USD and 650 EUR, not collapsed across currencies.

Compat suite

Two new queries in tests/compatibility/bql-queries.toml:

[[query]]
name = "journal-assets-at-cost"
query = "JOURNAL 'Assets' AT cost"
preserve_order = true

[[query]]
name = "journal-assets-at-units"
query = "JOURNAL 'Assets' AT units"
preserve_order = true

These exercise the new code path against bean-query so 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: clean
  • cargo fmt --check: clean

Compat 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

  • CI: Test, Clippy, Doctests, Format, Compatibility
  • Compat run: new journal-assets-at-cost / journal-assets-at-units queries should pass byte-for-byte against bean-query (modulo whitespace) on relevant fixtures
  • Manual: reproducer above produces 1500 USD in the balance column

Out of scope

Stacks cleanly with PR #959 (which fixes BALANCES non-idempotency). The two PRs touch different functions and merge in any order.

Closes #957

🤖 Generated with Claude Code

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]>
@robcohen
robcohen requested a review from a team as a code owner April 30, 2026 04:42
Copilot AI review requested due to automatic review settings April 30, 2026 04:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 when AT cost / AT units is 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

codecov Bot commented Apr 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.85714% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-query/src/executor/execution.rs 92.85% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.4ms ± 0.9ms 21.8 MB
beancount 817.7ms ± 5.7ms 50.5 MB
Comparison 23.8x faster 2.3x less

vs main branch (2026-04-30)

Metric main this PR Change
Time 35.9ms 34.4ms -4.2% ✅
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@github-actions

github-actions Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

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

robcohen and others added 4 commits April 29, 2026 23:33
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]>
@robcohen
robcohen enabled auto-merge (squash) May 1, 2026 02:35
@robcohen
robcohen merged commit f50fb05 into main May 1, 2026
32 of 34 checks passed
@robcohen
robcohen deleted the fix/journal-at-mode-balance branch May 1, 2026 02:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JOURNAL AT cost / AT units doesn't collapse the balance column to cost-currency totals

2 participants