Repository navigation
fix(query): build_balances_with_filter returns fresh map (closes #958) - #959
Merged
Merged
Conversation
`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]>
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
5 tasks
Contributor
📊 Benchmark Results
vs main branch (2026-04-30)
What do these numbers mean?
|
robcohen
disabled auto-merge
April 30, 2026 04:29
Contributor
There was a problem hiding this comment.
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::balancesand refactorbuild_balances_with_filterto return a fresh per-callFxHashMap<InternedStr, Inventory>. - Update
execute_balancesto consume the returned map and drop its&mut selfrequirement. - Add regression tests ensuring sequential
BALANCESruns 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_filteronly appliesfrom_clause.filterand ignores otherFromClausemodifiers likeopen_on/close_on(andclear). This means queries likeBALANCES FROM OPEN ON ...parse but won't actually restrict the time window. Consider applying the same OPEN/CLOSE checks used incollect_postingsso BALANCES FROM semantics match theFromClausecontract/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.
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
3 tasks
…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]>
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
Executor::build_balances_with_filteraccumulated into theself.balancesfield without clearing it first. SequentialBALANCESqueries on the sameExecutorproduced wrong results: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_filterto return a freshFxHashMap<InternedStr, Inventory>rather than mutatingself.balances.execute_balancesconsumes the return value directly.Both
build_balances_with_filterandexecute_balancesdrop their&mut selfrequirement;&selfsuffices now.The
balancesfield onExecutoris removed entirely. After PR #956 (which removedJOURNAL's pollution of this field),execute_balanceswas 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 touchingself.balanceseither 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 ofself.balancesand 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—BALANCESthenBALANCESon the sameExecutorreturns identical rows. Locks in the basic idempotency.test_balances_with_different_from_filters_are_independent—BALANCES FROM year = 2024thenBALANCES FROM year = 2025returns 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: cleancargo fmt --check: cleanBehavior change / migration
This is a strict improvement for any consumer that reuses an
Executor:rledger query): unchanged — creates a freshExecutorper invocation.Executor::balancesfield waspub(crate); no external API surface affected.Test plan
BALANCESqueries should be unaffected (no current call site reused an Executor in a way that triggered the bug)Executor::execute(BALANCES)× 2 returns identical resultsCloses #958
🤖 Generated with Claude Code