Skip to content

chore(compat): mask beanquery FIRST(balance) short-circuit quirk (#1102) - #1105

Merged
robcohen merged 3 commits into
mainfrom
chore/mask-first-balance-quirk
May 13, 2026
Merged

robcohen merged 3 commits into
mainfrom
chore/mask-first-balance-quirk

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Adds 5 surgical entries to KNOWN_PYTHON_DIVERGENCES for the first-balance-by-month query against fixtures hitting upstream beancount/beanquery#279 — FIRST(balance) short-circuiting that leaves the stateful balance accumulator stale.

Closes #1102.

The upstream bug (verified)

Same fixture, same WHERE, three SELECT shapes:

SELECT FIRST(balance) for 2024/2
SELECT year, month, FIRST(balance) 10 HOOL {520} 5 HOOL {540} ❌ (missing −5200 USD)
SELECT year, month, FIRST(balance), LAST(balance) 10 HOOL {520} 5 HOOL {540} −5200 USD ✅
SELECT year, month, FIRST(balance), COUNT(*) 10 HOOL {520} 5 HOOL {540} ❌

bean-query's FIRST aggregator short-circuits operand evaluation after the first row in each group. The balance column mutates a shared accumulator on every call (in beanquery/sources/beancount.py). When LAST(balance) is in the SELECT, its presence forces balance to be evaluated on every row, so the accumulator stays current. With ONLY FIRST(balance), later rows never call balance(context), leaving the accumulator stale for downstream groups.

rledger pre-computes ctx.balance per row in posting collection; the column evaluator is a pure read. FIRST and LAST always agree on single-row groups, and the answer is independent of which other aggregators are queried — that's the semantically clean interpretation.

Per-row diagnostic (rledger and bean-query AGREE)

$ bean-query paypal.beancount "SELECT date, account, position, balance WHERE account ~ '^Assets'"
2014-09-09  Assets:Paypal     -70.00 USD   -82.70 USD
2014-09-09  Assets:Checking    70.00 USD   -12.70 USD

$ rledger query paypal.beancount "SELECT date, account, position, balance WHERE account ~ '^Assets'"
# identical output

Per-row balance values are byte-identical. The only divergence is in how FIRST aggregates over those identical row streams.

Why surgical not wildcard

The existing exclusions.toml entry for testdata_source_google_purchases_test_invalid_journal.beancount is file-level (whole file is a deliberately malformed importer test fixture). The 5 fixtures masked here have many correctly-passing queries — wildcarding would silently hide future genuine divergences. The (file, query_name) pin keeps masking surgical to this specific upstream-buggy query shape.

Files affected

  • cost_only.beancount
  • testdata_source_healthequity_test_invalid_journal.beancount
  • testdata_source_healthequity_test_matching_journal.beancount
  • testdata_source_ofx_test_fidelity_ira_journal.beancount
  • testdata_source_paypal_test_matching_journal.beancount

(testdata_source_ofx_test_fidelity_journal.beancount was already wildcarded for an unrelated DisplayContext divergence.)

Impact

BQL compat metric: 92.4% → ~93.4% raw. Badge metric likely 98% → 99% (already excluded some of these via the existing (file, "*") entries).

Test plan

🤖 Generated with Claude Code

Add 5 surgical entries to `KNOWN_PYTHON_DIVERGENCES` for the
`first-balance-by-month` query against fixtures that hit upstream
`beancount/beanquery#279`.

## The upstream bug

Beanquery's `FIRST` aggregator short-circuits operand evaluation after
the first row of a group, but the `balance` column mutates a shared
accumulator on every call. Result: the accumulator is stale for
subsequent groups when ONLY `FIRST(balance)` is in the SELECT list.

Concretely, against the same fixture and WHERE clause:

  SELECT year, month, FIRST(balance)                  -> wrong
  SELECT year, month, FIRST(balance), LAST(balance)   -> correct

LAST's presence forces operand evaluation on every row, which keeps
the accumulator current.

Repro on `cost_only.beancount` 2024/2 row:

  bean-query: 10 HOOL {520} 5 HOOL {540}              (missing -5200 USD)
  rledger:    10 HOOL {520} 5 HOOL {540} -5200 USD    (correct)

Rledger pre-computes `ctx.balance` per row during posting collection;
the column evaluator is a pure read. FIRST and LAST always agree on
single-row groups, and the result is independent of which other
aggregators are queried — the semantically clean interpretation. We
don't want to mirror the upstream bug.

## Why surgical, not wildcard

The existing entry for `testdata_source_google_purchases_test_invalid_journal.beancount`
in `exclusions.toml` is file-level (the whole file is a deliberately
malformed importer test fixture). The 5 fixtures masked here have
many *correctly*-passing queries — wildcarding them would silently
hide any future genuine divergence. The `(file, query_name)` pin keeps
the masking surgical to this specific upstream-buggy query shape.

## Impact

Moves the BQL compat metric from 92.4% → ~93.4% raw (the badge metric
likely moves 98% → 99% since it already excluded some of these).

## Files affected

- cost_only.beancount
- testdata_source_healthequity_test_invalid_journal.beancount
- testdata_source_healthequity_test_matching_journal.beancount
- testdata_source_ofx_test_fidelity_ira_journal.beancount
- testdata_source_paypal_test_matching_journal.beancount

(`testdata_source_ofx_test_fidelity_journal.beancount` was already
wildcarded for an unrelated DisplayContext divergence.)

Closes #1102

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 13, 2026 04:20
@robcohen
robcohen requested a review from a team as a code owner May 13, 2026 04:20

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

Updates the BQL compatibility harness allowlist to ignore a specific upstream beanquery bug where FIRST(balance) short-circuits balance evaluation, causing stale balance state and fixture-specific divergences.

Changes:

  • Add five (fixture, query_name) entries to KNOWN_PYTHON_DIVERGENCES for the first-balance-by-month query.
  • Document the upstream beancount/beanquery#279 root cause inline and justify why the allowlist is pinned per (file, query) rather than wildcarded.

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

Comment thread scripts/compat-bql-test.py Resolved
@codecov

codecov Bot commented May 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

PR #1105 Copilot review caught that "Rledger" was capitalized
mid-sentence in the new explanatory comment, while the rest of the
script consistently refers to the tool as `rledger`. Lowercase
matches the docstring (line 2), the help text (line 17), and the
pre-existing references at lines 71, 114, 120, 138, 149.
@github-actions

github-actions Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 99%
Full AST Match 99%
Total Files 786
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
robcohen merged commit b78ea99 into main May 13, 2026
27 checks passed
@robcohen
robcohen deleted the chore/mask-first-balance-quirk branch May 13, 2026 15:50
robcohen added a commit that referenced this pull request May 14, 2026
…Rust divergences (refs #1112) (#1114)

* chore(compat): mask the last 3 BQL divergences from #1112

After #1113 recovered the bulk of the #1106 regression, three real
mismatches remain — all `sum-number-by-currency` queries on fixtures
whose cost-spec interpolation produces a scale-3 residual in Python's
pipeline vs scale-2 in rledger's:

* testdata_source_healthequity_test_invalid_journal.beancount
* testdata_source_healthequity_test_matching_journal.beancount
* testdata_source_ofx_test_non_default_capital_gains_journal.beancount

In every case the numeric value is the same (e.g. `-1966.700` vs
`-1966.70`) — only the display scale differs, surfaced as a textual
diff because both tools intentionally preserve scale on
`Value::Number` output.

Root cause: cost-spec interpolation against `{}` lot-match against a
`{{total}}` lot produces a residual whose scale depends on which
intermediate value drives it. Python's intermediate stays at the
buy-side scale 3; rledger's #1108 fix dropped intermediate scale to
the input minimum (2) to stop the 26-digit contamination. That fix
was correct for the over-precision case but over-applies here.

Mask surgically (per `(file, query_name)`, not `"*"`) so any
non-scale divergence on these fixtures stays surfaced. This is a
display-scale shim, not a value bug — both tools agree on the
arithmetic. Fixing it properly means continuing #1108's pipeline
scale-propagation work, which is tracked under #1112 as a follow-up.

After this commit all 5 `first-balance-by-month` Python beanquery
bugs (#1105) and the 3 scale residuals here are accounted for as
known divergences, taking the BQL compat percentage's effective
match closer to 100%. The user-facing rounded percentage stays at
99% (it was already 99% post-#1113); this commit cleans up the
remaining bookkeeping so future regressions stand out clearly.

Refs #1112.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(compat): split known-Python vs known-Rust BQL divergences (#1114 review)

Copilot review caught that the 3 `sum-number-by-currency` entries I
added to `KNOWN_PYTHON_DIVERGENCES` are actually rledger-side bugs
(continuation of #1108's pipeline scale-propagation work), not Python
beanquery quirks. Conflating them in the Python allowlist lets an
rledger bug masquerade as a Python quirk and could absorb a future
rledger regression on these file/query pairs.

Fix: introduce a separate `KNOWN_RUST_DIVERGENCES` set with the same
surgical-pin semantics. Wire it through:

- New predicate `_is_known_rust_divergence(run)` mirroring the Python
  one. New `_is_known_divergence(run)` returns the OR of both.
- Summary stats report `Known Python diffs` and `Known Rust diffs`
  separately so each side's allowlist size is visible at a glance.
- Per-mismatch log lines use `KNOWN-PY` / `KNOWN-RS` / `MISMATCH`
  labels.
- `$GITHUB_OUTPUT` gets two new keys, `bql_known_python` and
  `bql_known_rust`, alongside the existing aggregate `bql_known_divergences`.
- The 3 cost-spec interpolation cases move out of the Python allowlist
  and into the new Rust one. Effective match percentage is unchanged
  (still counted as "known"); only the bookkeeping is corrected.

Also addresses Copilot's second comment: the inline doc on the Rust
allowlist now says "Tracked under #1112 (kept open as the tracker — do
not auto-close from this PR)" so the reference stays valid post-merge.
PR body updated correspondingly.

Refs #1112. Does NOT auto-close it — the deep pipeline fix is the
real closure path.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(booking): prune zero-value interpolated postings post-validation

Until now rledger preserved every interpolated posting through to user-
facing output, including zero-value ones (commit 7706be9, closes #877).
That fix was correct in spirit — pruning before validation hides E1001
on never-opened accounts referenced by elided postings — but
over-applied: it kept zero postings in user-facing output too, where
Python beancount drops them. The result was a persistent ~0.25% Full
AST Match floor on fixtures like `tests/regressions/issue-276.beancount`
and `tests/regressions/issue-279.beancount` (multi-posting lot sales
with zero residuals on Income:Trading).

This commit splits the two invariants by phase:

1. Booking marks every interpolated posting with a new metadata key
   `__interpolated__` (exposed as `rustledger_booking::INTERPOLATED_MARKER`).
   Validation runs against transactions that still include zero-value
   postings — so #877's E1001-on-unopened-account check still fires.

2. AFTER validation, `process()` walks each transaction and drops
   postings that have the marker AND a zero `units` value. Survivors
   keep their value but the marker is stripped so it doesn't leak into
   BQL queries, JSON output, or formatted ledgers.

Both invariants verified by new integration tests in
`crates/rustledger-loader/tests/loader_test.rs`:

* `test_zero_interpolated_posting_pruned_on_opened_account` — zero-value
  interpolated Income posting is dropped from output, no errors.
* `test_zero_interpolated_posting_keeps_e1001_on_unopened_account` —
  the #877 scenario: E1001 still emitted.
* `test_non_zero_interpolated_posting_is_preserved` — only ZERO ones
  get pruned; legitimate interpolated residuals stay.
* `test_interpolated_marker_does_not_leak_to_user_output` — defensive
  check that `__interpolated__` is stripped from survivors.

Effect on compat suite (verified locally with `--no-default-features`,
matching CI):

  Before                                             After
  ─────────────────────────────────────────────      ─────────────────────────
  issue-276.beancount  SELECT COUNT(*) = 12          = 10  (matches Python)
  issue-279.beancount  SELECT COUNT(*) = 13          = 11  (matches Python)
  Full AST Match       99% (784/786)                 100% (786/786)

The #877 regression case still produces E1001 with this commit applied:

  $ rledger check zero-balance.bean
  E1001 Account Expenses:NeverOpened was never opened
  ✗ 1 error
  exit_code: 1

Closes the residual AST divergence tracked under #1112.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (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.

compat(bql): FIRST(balance) WHERE-filtered queries diverge from bean-query in 6 files

2 participants