Skip to content

fix(query): build_balances_with_filter returns fresh map (closes #958) - #959

Merged
robcohen merged 2 commits into
mainfrom
fix/balance-builder-fresh-hashmap
Apr 30, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/balance-builder-fresh-hashmap

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

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 implementation contradicted that intent.

Fix

Change build_balances_with_filter to return a fresh FxHashMap<InternedStr, Inventory> rather than mutating self.balances. execute_balances consumes the return value directly.

// Before:
fn build_balances_with_filter(&mut self, from: Option<&FromClause>) -> Result<(), QueryError> {
    for ... { self.balances.entry(...).or_default().add(pos); }
    Ok(())
}

// After:
fn build_balances_with_filter(
    &self,
    from: Option<&FromClause>,
) -> Result<FxHashMap<InternedStr, Inventory>, QueryError> {
    let mut balances: FxHashMap<...> = FxHashMap::default();
    for ... { balances.entry(...).or_default().add(pos); }
    Ok(balances)
}

Both build_balances_with_filter and execute_balances 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 was 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.

Why structural over a one-line clear()

A self.balances.clear() at function entry would have fixed today's symptom in one line, but left a footgun: a field whose contract is "fresh per call" still living on a struct that allows arbitrary cross-call use. The next person to write a method touching self.balances either remembers the clear-on-entry rule or recreates this bug. Removing the field eliminates the failure mode permanently.

This change also finishes the cleanup arc started in #956 — that PR removed execute_journal's mutation of self.balances and made it &self. With this PR, the field is gone entirely.

Tests

Two new regression tests in bql_integration_test.rs:

  • test_balances_idempotent_across_sequential_runs — BALANCES then BALANCES on the same Executor returns identical rows. Locks in the basic idempotency.
  • 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 (500 USD, not 600 USD which would be the union of both years). This is the worse-than-doubling case noted in build_balances_with_filter doesn't clear self.balances; sequential BALANCES queries can double-count #958.

Verification

  • cargo test -p rustledger-query: 495 tests pass (was 493, +2 new)
  • cargo clippy --all-features --all-targets -- -D warnings: clean
  • cargo fmt --check: clean

Behavior change / migration

This is a strict improvement for any consumer that reuses an Executor:

  • CLI (rledger query): unchanged — creates a fresh Executor per invocation.
  • WASM API and other library consumers: unchanged for current call sites (all single-query). Future programmatic users get correct behavior automatically.
  • The Executor::balances field was pub(crate); no external API surface affected.

Test plan

  • CI: Test, Clippy, Doctests, Format, Compatibility
  • Compat suite: BALANCES queries should be unaffected (no current call site reused an Executor in a way that triggered the bug)
  • Manual: programmatic Executor::execute(BALANCES) × 2 returns identical results

Closes #958

🤖 Generated with Claude Code

`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]>
Copilot AI review requested due to automatic review settings April 30, 2026 04:24
@robcohen
robcohen requested a review from a team as a code owner April 30, 2026 04:24
@robcohen
robcohen enabled auto-merge (squash) April 30, 2026 04:26
@codecov

codecov Bot commented Apr 30, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 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 29.3ms ± 0.3ms 21.7 MB
beancount 906.9ms ± 6.4ms 50.3 MB
Comparison 31x faster 2.3x less

vs main branch (2026-04-30)

Metric main this PR Change
Time 35.9ms 29.3ms -18.4% 🟢
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

@robcohen
robcohen disabled auto-merge April 30, 2026 04:29

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

Fixes a correctness bug in BALANCES execution where per-account balances were accumulated into Executor state across runs, causing sequential queries on the same Executor to double-count or union results across different FROM filters.

Changes:

  • Remove Executor::balances and refactor build_balances_with_filter to return a fresh per-call FxHashMap<InternedStr, Inventory>.
  • Update execute_balances to consume the returned map and drop its &mut self requirement.
  • Add regression tests ensuring sequential BALANCES runs are idempotent and independent across different FROM filters.

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/mod.rs Removes struct-level balances state; refactors balance-building to return a fresh map per call.
crates/rustledger-query/src/executor/execution.rs Updates BALANCES execution to use the returned per-call balances map and take &self.
crates/rustledger-query/tests/bql_integration_test.rs Adds regression tests covering sequential-run idempotency and FROM-filter independence for BALANCES.
Comments suppressed due to low confidence (1)

crates/rustledger-query/src/executor/mod.rs:285

  • The FROM handling in build_balances_with_filter only applies from_clause.filter and ignores other FromClause modifiers like open_on / close_on (and clear). This means queries like BALANCES FROM OPEN ON ... parse but won't actually restrict the time window. Consider applying the same OPEN/CLOSE checks used in collect_postings so BALANCES FROM semantics match the FromClause contract/spec.
                // Apply FROM filter if present
                if let Some(from_clause) = from
                    && let Some(filter) = &from_clause.filter
                    && !self.evaluate_from_filter(filter, txn)?
                {
                    continue;
                }

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

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

…utor (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]>
@robcohen
robcohen enabled auto-merge (squash) April 30, 2026 04:46
@robcohen
robcohen merged commit 8a27dd4 into main Apr 30, 2026
34 checks passed
@robcohen
robcohen deleted the fix/balance-builder-fresh-hashmap branch April 30, 2026 04:53
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.

build_balances_with_filter doesn't clear self.balances; sequential BALANCES queries can double-count

2 participants