Repository navigation
feat(query): #balances exposes the checker's discrepancy - #2238
Conversation
`SELECT * FROM #balances` now returns bean-query's fifth column. Closes #2180. `discrepancy` is `computed - asserted` for a FAILING assertion and NULL otherwise. It cannot be derived from the directive: a small non-zero difference INSIDE the tolerance is a pass and reports nothing, so the value depends on the tolerance rule as much as on the arithmetic. beancount agrees -- its checker sets `diff_amount` only on a failing entry -- and both halves are verified against beanquery 0.2.0: asserted 90.00 vs accumulated 100.00 -> 10.00 USD asserted 120.00 vs accumulated 100.00 -> -20.00 USD asserted 100.01 within a 0.05 tolerance -> (null) Plumbed rather than recomputed. The validator already recorded the signed difference per assertion (#1663); it now also records whether that difference exceeded the tolerance, taken from the same comparison that raises the error. The loader carries the failing ones onto `Ledger`, beside `capital_gains` and for the same reason: a consumer that re-derived either would be a second implementation, and would disagree with `rledger check` the moment either changed. `rustledger-query` cannot depend on `rustledger-validate`, so the executor receives the differences from its host and reports NULL without them. The column exists either way, so a host that skips validation gets bean-query's SCHEMA rather than a missing column. The query command now loads with validation on, which is what computes them. Measured: a query on the largest corpus file runs in the same ~0.1s either way, load cost dominates, and diagnostics go to stderr so stdout stays byte-identical. bean-query likewise reports a failing assertion before returning its rows. This was the last gap from the #2154 census of all 55 columns bean-query exposes across its ten tables, so `select_star_matches_bean_query_per_table` loses its per-table `gap` field: every expectation is now bean-query's set, and a difference means drift rather than progress.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
🟡 Changes recommended
Discrepancies are keyed and stored in a way that can silently drop/alias results when multiple balance directives share the same (date, account, currency), which can lead to incorrect #balances.discrepancy values in those cases.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds bean-query parity for #balances by exposing a new discrepancy column sourced from the balance checker’s own computed result (rather than being re-derived in the query layer), and enables validation in the CLI query path so those discrepancies are available end-to-end.
Changes:
- Plumbs failing balance-assertion differences from validation → loader
Ledger→ CLI query settings →rustledger-queryexecutor, surfacing them as#balances.discrepancy(NULL when not available / not failing). - Enables validation for
rledger queryto compute discrepancies while keeping diagnostics on stderr. - Adds CLI- and integration-level tests to pin schema/order and tolerance behavior.
File summaries
| File | Description |
|---|---|
| crates/rustledger/tests/query_balances_discrepancy_test.rs | New CLI-level tests asserting #balances.discrepancy semantics, wildcard ordering, and stderr-only diagnostics. |
| crates/rustledger/src/cmd/query/output.rs | Passes host-provided balance discrepancies into the query executor. |
| crates/rustledger/src/cmd/query/mod.rs | Turns validation on for query and flattens loader discrepancies into executor settings (batch + REPL). |
| crates/rustledger/src/cmd/query/interactive.rs | Threads balance discrepancies into interactive query settings. |
| crates/rustledger-validate/src/validators/balance.rs | Records exceeds_tolerance from the same tolerance comparison used to raise balance errors. |
| crates/rustledger-validate/src/lib.rs | Extends BalanceActual with exceeds_tolerance so consumers can distinguish fail vs pass without re-deriving tolerance logic. |
| crates/rustledger-query/tests/bql_integration_test.rs | Updates schema expectations for #balances wildcard and removes the previous “gap” mechanism now that parity is claimed. |
| crates/rustledger-query/src/executor/system_tables.rs | Adds discrepancy column to #balances and renders it from host-supplied discrepancies. |
| crates/rustledger-query/src/executor/mod.rs | Adds executor storage + setter for balance discrepancies supplied by the host. |
| crates/rustledger-loader/src/process.rs | Introduces Ledger::balance_discrepancies and harvests failing assertion diffs from the validation session. |
Review details
- Files reviewed: 10/10 changed files
- Comments generated: 1
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
`(date, account, currency)` does not identify a balance assertion. A
ledger may assert the same account and currency twice on one date, and
those can assert different amounts and so fail differently. Keying the
lookup on those three collapsed them, and both rows reported whichever
difference was inserted last:
2024-03-01 balance Assets:Cash 90.00 USD
2024-03-01 balance Assets:Cash 120.00 USD
bean-query 10.00 USD, -20.00 USD
before -20.00 USD, -20.00 USD
The asserted number is now part of the key, recorded by the validator
alongside the difference. Two assertions that agree on all four are the
same assertion, so collapsing those is harmless -- they see the same
accumulated balance and compute the same difference.
Caught in review of #2238.
|
Real bug — reproduced and fixed in 10adaf6.
The asserted number is now part of the key, recorded by the validator beside the difference. Two assertions agreeing on all four are the same assertion — same date, account, currency and amount means the same accumulated balance and the same computed difference — so collapsing those is harmless. Pinned by I checked whether the same keying appears elsewhere: |
`attach_balance_diffs` keyed the validator's results by `(date, account, currency)`. Those three do not identify a balance assertion: a ledger may assert the same account and currency twice on one date with different amounts, and so different differences. Building a map collapsed them, and one directive received the other's diff. Closes #2239. 2024-03-01 balance Assets:Cash 90.00 USD 2024-03-01 balance Assets:Cash 120.00 USD before both carry -20.00 after 90.00 carries 10.00, 120.00 carries -20.00 bean-query reports 10.00 and -20.00 here. The query layer had the same collision, fixed in #2238, which is also what added `BalanceActual::asserted` -- so the fix here is the key, not the semantics. This surface deliberately attaches a diff for EVERY assertion including passing ones, where it is zero; that is its contract (#1663) and is unchanged. The asserted number is compared as the STRING the WIT directive carries. Both sides come from `Decimal::to_string()` on the same value -- `amount_from_core` for the directive, the validator's record for the map -- so they agree by construction rather than by luck. Tested at the WIT level, because the collision is in the map the component builds and a validator unit test cannot see it. The component wasm was REBUILT for both runs: the checked-in one was three days stale, and testing against it would have measured old code either way. The test fails against a freshly built unfixed component (both diffs -20.00) and passes against a freshly built fixed one. No WIT change; the wire contract is untouched.
* fix(ffi): a balance diff belongs to its own assertion `attach_balance_diffs` keyed the validator's results by `(date, account, currency)`. Those three do not identify a balance assertion: a ledger may assert the same account and currency twice on one date with different amounts, and so different differences. Building a map collapsed them, and one directive received the other's diff. Closes #2239. 2024-03-01 balance Assets:Cash 90.00 USD 2024-03-01 balance Assets:Cash 120.00 USD before both carry -20.00 after 90.00 carries 10.00, 120.00 carries -20.00 bean-query reports 10.00 and -20.00 here. The query layer had the same collision, fixed in #2238, which is also what added `BalanceActual::asserted` -- so the fix here is the key, not the semantics. This surface deliberately attaches a diff for EVERY assertion including passing ones, where it is zero; that is its contract (#1663) and is unchanged. The asserted number is compared as the STRING the WIT directive carries. Both sides come from `Decimal::to_string()` on the same value -- `amount_from_core` for the directive, the validator's record for the map -- so they agree by construction rather than by luck. Tested at the WIT level, because the collision is in the map the component builds and a validator unit test cannot see it. The component wasm was REBUILT for both runs: the checked-in one was three days stale, and testing against it would have measured old code either way. The test fails against a freshly built unfixed component (both diffs -20.00) and passes against a freshly built fixed one. No WIT change; the wire contract is untouched. * docs(ffi): the attached balance diff is raw, not a pass/fail zero The comment claimed a passing assertion carries a diff of zero. It does not: `BalanceActual::diff` is the raw signed `computed - asserted`, recorded before the tolerance is consulted, so an assertion that passes WITHIN tolerance carries its real difference. Measured through the component: `100.01` asserted against an accumulated `100.00` under a `0.05` tolerance carries `-0.01`, and only an exact match carries `0.00`. That distinction is the reason `#balances.discrepancy` could not reuse this value directly -- it reports a difference only for failures -- so the comment was wrong about the very thing it existed to explain. Caught in review of #2242. No behavior change.
…2534) * fix(query): skip advisory-only diagnostics on stderr, as check does Closing an account that still holds a balance is E1004, which is advisory-only: beancount does not flag it, so bean-check and bean-query print nothing, and `rledger check` already skips it (#1446). #2238 turned validation on in `query` (for `#balances.discrepancy`) without that skip, so `rledger query` printed "E1004: Cannot close account ... with non-zero balance" on ledgers `rledger check` called clean. `query` now filters with the same `is_advisory_only_code` predicate as `check`. Other diagnostics on the same load are still printed. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * fix(query): print option diagnostics, as check and bean-query do `query` printed `ledger.errors` only. Option diagnostics (E7001 unknown option, E7002 invalid value, the rest of E7xxx) are kept on `options.warnings`, so a misspelled option was reported by `rledger check` and bean-query and went unreported here. They are now printed first, as bean-query does, ahead of the validation errors, through the same `--no-errors` switch. Neither kind of diagnostic changes query's exit status (bean-query also exits 0). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
SELECT * FROM #balancesnow returns bean-query's fifth column. Closes #2180.discrepancyiscomputed − assertedfor a failing assertion and NULL otherwise. Verified against beanquery 0.2.0:10.00 USD-20.00 USDThat last row is the reason this couldn't be faked from the directive: a small non-zero difference inside the tolerance is a pass and reports nothing, so the value depends on the tolerance rule as much as on the arithmetic. beancount does the same —
ops/balance.pysetsdiff_amountonly whenabs(diff) > tolerance, leaving itNoneotherwise.Plumbed, not recomputed
The issue's constraint was that re-deriving this in the query layer means a second implementation of balance accumulation. It's worse than that — it also means a second implementation of the tolerance rule.
So: the validator already recorded the signed difference per assertion (#1663). It now also records whether that difference exceeded the tolerance, taken from the same comparison that raises the error. The loader carries the failing ones onto
Ledger, besidecapital_gainsand for the same stated reason — a consumer that re-derives either would drift fromrledger check.rustledger-querycan't depend onrustledger-validate(checked: it's an optional dep of the loader only), so the executor receives the differences from its host viaset_balance_discrepanciesand reports NULL without them. The column exists either way, so a host that skips validation gets bean-query's schema rather than a missing column.The query command now validates
That's what computes them. Two things I measured rather than assumed:
Last gap in the census
This was the final item from #2154's census of all 55 columns bean-query exposes across its ten tables (
#notes.tags/.linkswent with #2160). Soselect_star_matches_bean_query_per_tableloses its per-tablegapfield — every expectation is now bean-query's set exactly, and a difference means drift rather than progress. That also fixes the type-inference break that removing the lastSome(...)would otherwise have caused.Verification
Four CLI-level tests, because that's where the whole path runs — loader → checker → executor. Two negative controls, each failing a distinct set: reverting the query path to
validate: falsefails 3, and reporting the difference for passing assertions too fails the tolerance case.One test pins that stdout stays free of diagnostics, since every consumer parses it.
4718 workspace tests green, clippy clean on 1.97.0, typos clean on all changed files. BQL compat harness over 71 files / 1349 runs: no regression against baseline.