Skip to content

feat(query): #balances exposes the checker's discrepancy - #2238

Merged
robcohen merged 2 commits into
mainfrom
feat/balances-discrepancy-column
Sep 2, 2026
Merged

robcohen merged 2 commits into
mainfrom
feat/balances-discrepancy-column

Conversation

@robcohen

@robcohen robcohen commented Sep 2, 2026

Copy link
Copy Markdown
Member

SELECT * FROM #balances now returns bean-query's fifth column. Closes #2180.

discrepancy is computed − asserted for a failing assertion and NULL otherwise. Verified against beanquery 0.2.0:

asserted accumulated tolerance discrepancy
90.00 100.00 — 10.00 USD
120.00 100.00 — -20.00 USD
100.01 100.00 0.05 (null)

That 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.py sets diff_amount only when abs(diff) > tolerance, leaving it None otherwise.

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, beside capital_gains and for the same stated reason — a consumer that re-derives either would drift from rledger check.

rustledger-query can't depend on rustledger-validate (checked: it's an optional dep of the loader only), so the executor receives the differences from its host via set_balance_discrepancies 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 validates

That's what computes them. Two things I measured rather than assumed:

  • Cost: a query on the largest corpus file (18.6k lines) runs in ~0.09s with validation and ~0.12s without — load dominates, and the difference is noise.
  • Output: diagnostics go to stderr, so stdout is byte-identical. bean-query likewise prints a failing assertion before returning its rows, so this moves us toward it in behavior as well as schema.

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/.links went with #2160). So select_star_matches_bean_query_per_table loses its per-table gap field — 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 last Some(...) 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: false fails 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.

`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.
@robcohen
robcohen requested a review from a team as a code owner September 2, 2026 18:42
Copilot AI lite review requested due to automatic review settings September 2, 2026 18:42
@codecov

codecov Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.58559% with 16 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/query/interactive.rs 0.00% 15 Missing ⚠️
crates/rustledger/src/cmd/query/mod.rs 97.05% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

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.

🟡 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-query executor, surfacing them as #balances.discrepancy (NULL when not available / not failing).
  • Enables validation for rledger query to 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.

@github-actions

github-actions Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 49.9ms ± 5.6ms 814.7ms ± 3.8ms 16.3x 55.1 MB / 50.1 MB
investment 70.9ms ± 4.7ms 3083.3ms ± 67.5ms 43.5x 58.9 MB / 57.9 MB
fifo 68.0ms ± 3.4ms 15491.3ms ± 92.2ms 227.8x 61.1 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 47.7ms ± 4.8ms 49.9ms ± 5.6ms +4.7% ✅ within noise 55.0 MB → 55.1 MB (+0.2%)
investment 70.2ms ± 3.5ms 70.9ms ± 4.7ms +1.1% ✅ within noise 59.0 MB → 58.9 MB (-0.2%)
fifo 69.1ms ± 3.7ms 68.0ms ± 3.4ms -1.6% ✅ within noise 61.1 MB → 61.1 MB (-0.0%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 3.3ms, investment 2.6ms, fifo 2.2ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@github-actions

github-actions Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 99% (raw 93%, 169 masked)
Full AST Match 100%
Total Files 812
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

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.
@robcohen

robcohen commented Sep 2, 2026

Copy link
Copy Markdown
Member Author

Real bug — reproduced and fixed in 10adaf6.

(date, account, currency) does not identify an assertion. Two on one date for the same account and currency can assert different amounts and fail differently, and both rows took 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
after        10.00 USD, -20.00 USD

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 same_date_assertions_do_not_share_a_discrepancy, which fails if the lookup ignores the asserted amount.

I checked whether the same keying appears elsewhere: attach_balance_diffs in the FFI (#1663) builds a (date, account, currency) map for the same data. It has the identical collision, and it predates this PR. Filing separately rather than widening the scope here — the FFI's contract also differs (it attaches a diff for passing assertions too), so the fix is not a copy of this one.

@robcohen
robcohen merged commit 82f8359 into main Sep 2, 2026
62 of 65 checks passed
@robcohen
robcohen deleted the feat/balances-discrepancy-column branch September 2, 2026 19:51
robcohen added a commit that referenced this pull request Sep 3, 2026
`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.
robcohen added a commit that referenced this pull request Sep 3, 2026
* 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.
robcohen added a commit that referenced this pull request Oct 9, 2026
…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]>
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.

BQL: #balances.discrepancy needs the checker's computed difference, not a schema entry

2 participants