Skip to content

test(compat): pin the 51 verified beanquery#279 fixtures, and say so in the code - #1927

Merged
robcohen merged 1 commit into
mainfrom
fix/register-first-balance-divergence
Aug 3, 2026
Merged

robcohen merged 1 commit into
mainfrom
fix/register-first-balance-divergence

Conversation

@robcohen

@robcohen robcohen commented Aug 3, 2026 •

Copy link
Copy Markdown
Member

first-balance-by-month accounted for 62 of the 160 mismatches in the BQL compat run: 39% of the entire reported gap, and every one with a proven cause is the same upstream bug, filed as beanquery#279.

The registry had five fixtures pinned. The corpus has grown to 812 files since, and newer ones hit the same bug uncounted, so the metric was attributing beanquery's defect to us.

Why this is upstream's bug, re-established from source

beanquery's balance column mutates a shared accumulator every time it is evaluated (sources/beancount.py; the @cache(maxsize=1) on it is an admission the function is impure). Its FIRST.update evaluates the operand only on a group's first row, so later postings never reach the accumulator and every subsequent group reads a stale balance.

The symptom is decisive and needs no judgment call: the same FIRST(balance) returns different numbers depending on what else is in the SELECT list, because adding LAST(balance) forces evaluation on every row. No engine may let one selected column change another's value.

And when beanquery is forced to evaluate completely, it agrees with us exactly, byte-identical on every row of the fixture I drilled into.

rledger cannot have the bug by construction: the running balance is materialized onto each row during the scan (execution.rs, track_balance), so column reads are pure and no aggregate can change what another sees.

Verified, not assumed

scripts/verify-first-balance-divergence.py (added) checks each candidate by that same test. 51 of 59 proved same-cause and are pinned.

The other eight are deliberately not pinned. Seven load third-party plugins the verifier could not import, and beancount reports that as a load error and then exits 0 with a partially-loaded ledger, so the comparison silently degrades to rledger-full against beancount-partial and proves nothing. Three of those seven produced matching rows anyway; matching output from a ledger missing directives is not evidence, so they are not pinned either. The eighth genuinely disagrees.

Checking only the exit status would have missed all seven, so the script greps stderr for the load-error line too. Credit to the Copilot review comment that prompted this: the first version of the registration pinned 54, three of them on a compromised comparison.

Pinning the remainder on the strength of a shared query name would be the too-broad mask this registry's surgical-pin rule exists to prevent, and would bury a real regression among dozens of known-bad pairs. Install the plugins and re-run the verifier to settle them.

The script exists because this will drift again: the registry pins per file and the corpus keeps growing. Re-run it after a corpus refresh instead of eyeballing the mismatch list. It needs a checkout with the corpus fetched (fixtures are downloaded, not committed); set RLEDGER to point at a binary built elsewhere.

Also: the inline comment CLAUDE.md asks for

The deviation checklist requires a code comment naming the Python issue. grep 279 across the query crate returned nothing, so the reason a reader would find for min_by_key(transaction.date) was a one-line note about chronology. It now explains the upstream bug, why our architecture is immune, and where the evidence lives.

It also records the one genuine semantic difference, separate from the bug: our FIRST means the chronologically earliest posting, beanquery's means the first row scanned. Reordering entries with different dates cannot change our answer but can change theirs. Same-date ties are not broken (min_by_key keeps the earliest-scanned), which is deterministic per input and matches Python; inventing a tie-break here would be a divergence with no upstream behavior to compare against.

Gates

  • verifier re-run end to end after the rewrite: 51 same-cause / 1 differ / 7 load-error, totalling 59
  • cargo test -p rustledger-query: 631 passed, 0 failed
  • cargo +1.97.0 clippy -p rustledger-query --all-features --all-targets -D warnings: clean
  • cargo fmt --check: clean
  • compat-bql-test.py --self-test: OK (stale/dangling pin detection still behaves)
  • cross-check: every pin has a proof entry and every proof entry has a pin (0 unmatched either way)

@robcohen
robcohen requested a review from a team as a code owner August 3, 2026 02:47
Copilot AI review requested due to automatic review settings August 3, 2026 02:47
@robcohen
robcohen enabled auto-merge (squash) August 3, 2026 02:47

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 to accurately attribute first-balance-by-month mismatches to the already-known upstream beanquery bug (beanquery#279), preventing the compat metric from being skewed as the fixture corpus grows.

Changes:

  • Add a verifier script to confirm whether a fixture’s divergence is the specific beanquery#279 FIRST(balance)/stateful-balance issue.
  • Expand KNOWN_PYTHON_DIVERGENCES to pin the newly verified fixtures for first-balance-by-month, with an explicit verification note.
  • Add an inline rationale comment in the query executor explaining the upstream bug and why rledger’s architecture avoids it.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
scripts/verify-first-balance-divergence.py New script to verify the beanquery#279 divergence mechanism per fixture before pinning.
scripts/compat-bql-test.py Pins the 54 verified fixtures for first-balance-by-month and documents the verification rationale.
crates/rustledger-query/src/executor/aggregation.rs Adds an inline comment explaining the upstream bug and rledger’s differing/stricter behavior for FIRST.
Suppressed comments (2)

scripts/verify-first-balance-divergence.py:54

  • This script errors with an IndexError when no argument is provided, and it leaves the input file handle unclosed. A small usage guard plus a with open(...) makes failures clearer and avoids leaking descriptors.
files = [l.strip() for l in open(sys.argv[1]) if l.strip()]

scripts/verify-first-balance-divergence.py:51

  • find() returns the first rglob() hit without ordering, which can be nondeterministic if the same fixture name exists in multiple places. Sorting the hits makes the verifier stable and easier to reproduce.
    for d in ("tests/compatibility/files", "tests/regressions"):
        hits = list(pathlib.Path(d).rglob(name))
        if hits: return str(hits[0])

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

@codecov

codecov Bot commented Aug 3, 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 Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 33.9ms ± 0.2ms 24 MB
beancount 901.2ms ± 5.2ms 50.5 MB
Comparison 26.6x faster 2.1x less

vs main branch (2026-08-02)

Metric main this PR Change
Time 37.3ms 33.9ms -9.1% 🟢
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

@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 95%
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
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

…in the code

`first-balance-by-month` accounted for 62 of the 160 mismatches in the BQL
compat run - 39% of the entire reported gap - and the ones with a proven
cause are all the same upstream bug, filed as beanquery#279.

The registry had five fixtures pinned. The corpus has grown to 812 files
since, and the newer ones hit the same bug uncounted, so the metric was
attributing beanquery's defect to us.

WHY THIS IS UPSTREAM'S BUG, RE-ESTABLISHED FROM SOURCE

beanquery's `balance` column mutates a shared accumulator every time it is
evaluated (`sources/beancount.py`; the `@cache(maxsize=1)` on it is an
admission that the function is impure). Its `FIRST.update` evaluates the
operand only on a group's first row, so later postings never reach the
accumulator and every subsequent group reads a stale balance.

The symptom is decisive and needs no judgment call: the same
`FIRST(balance)` returns different numbers depending on what ELSE is in the
SELECT list, because adding `LAST(balance)` forces evaluation on every row.
No engine may let one selected column change another's value.

And when beanquery is forced to evaluate completely, it agrees with us
exactly - byte-identical on every row of the fixture I drilled into.

rledger cannot have the bug by construction: the running balance is
materialized onto each row during the scan (`execution.rs`, `track_balance`),
so column reads are pure and no aggregate can change what another sees.

VERIFIED, NOT ASSUMED

`scripts/verify-first-balance-divergence.py` (added) checks each candidate
by that same test. 51 of 59 proved same-cause and are pinned.

The other eight are deliberately NOT pinned. Seven load third-party plugins
the verifier could not import - and beancount reports that as a load error
then EXITS 0 with a partially-loaded ledger, so the comparison silently
degrades to rledger-full against beancount-partial and proves nothing. Three
of those seven produced matching rows anyway; matching output from a ledger
that is missing directives is not evidence, so they are not pinned either.
The eighth genuinely disagrees.

Checking only the exit status would have missed all seven. The script greps
stderr for the load-error line as well.

Pinning the remainder on the strength of a shared query name would be the
too-broad mask this registry's surgical-pin rule exists to prevent, and
would bury any real regression among dozens of known-bad pairs. Install the
plugins and re-run the verifier to settle them.

The script exists because this WILL drift again: the registry pins per
file and the corpus keeps growing. Re-run it after a corpus refresh instead
of eyeballing the mismatch list. It needs a checkout with the corpus fetched
(the fixtures are downloaded, not committed); set RLEDGER to point at a
binary built elsewhere.

ALSO: the inline comment CLAUDE.md asks for

The deviation checklist requires a code comment naming the Python issue.
`grep 279` across the query crate returned nothing, so the reason a reader
would find for `min_by_key(transaction.date)` was a one-line note about
chronology. It now explains the upstream bug, why our architecture is immune,
and where the evidence lives.

It also records the one genuine semantic difference, separate from the bug:
our FIRST means the chronologically earliest posting, beanquery's means the
first row scanned. Reordering entries with DIFFERENT dates cannot change our
answer but can change theirs. Same-date ties are not broken - `min_by_key`
keeps the earliest-scanned - which is deterministic per input and matches
Python, and inventing a tie-break here would be a divergence with no upstream
behavior to compare against.
Copilot AI review requested due to automatic review settings August 3, 2026 03:00
@robcohen
robcohen force-pushed the fix/register-first-balance-divergence branch from 7dd4500 to 10f5f5d Compare August 3, 2026 03:00
@robcohen robcohen changed the title test(compat): pin the 54 verified beanquery#279 fixtures, and say so in the code test(compat): pin the 51 verified beanquery#279 fixtures, and say so in the code Aug 3, 2026

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

Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.

Suppressed comments (2)

scripts/verify-first-balance-divergence.py:83

  • The script assumes a positional CLI argument and will crash with an IndexError if invoked without it. Since this is intended to be rerun manually, it should validate argv length and print a clear usage message (to stderr) with a non-zero exit code.
with open(sys.argv[1]) as fh:
    files = [l.strip() for l in fh if l.strip()]

scripts/verify-first-balance-divergence.py:45

  • rows() takes a cols parameter that is never used, and no caller passes it. Keeping an unused parameter makes the parsing contract unclear (it suggests variable-width parsing that doesn't exist).
def rows(text, cols=3):

@robcohen
robcohen merged commit 55f461c into main Aug 3, 2026
82 of 83 checks passed
@robcohen
robcohen deleted the fix/register-first-balance-divergence branch August 3, 2026 03:20
robcohen added a commit that referenced this pull request Aug 3, 2026
…1929)

The compat run reports "BQL match: 93%". That is the EFFECTIVE rate, after
KNOWN_PYTHON_DIVERGENCES and KNOWN_RUST_DIVERGENCES absorb pairs where the
upstream tool is the one that is wrong. The raw count was printed, but only
the effective figure carried a percentage - and the percentage is what gets
quoted, in release notes, in the badge, and in the job summary.

That is the exact doubt #1902 raised about this metric: is the headline real,
or is the registry doing the work? A reader could not answer it without
opening the script.

The gap also moves, and just moved a lot. #1927 pinned 51 more pairs, every
one a proven beanquery#279 case, taking masked pairs from 108 to about 159
and widening the difference between raw and effective by roughly 2 points in
a single PR. Nothing in the output would have shown that.

So the summary now prints both, plus the size of the masking:

  Raw match:           2282/2550 (89%)  [nothing masked]
  Effective match:     2441/2550 (95%)  [+159 masked, 6 pts over raw]

Same treatment where the number is actually read:

- GITHUB_OUTPUT gains `bql_raw_pct` alongside `bql_pct`
- the step-summary table gains "BQL match (raw, nothing masked)" and
  "BQL known divergences masked" rows under the existing "BQL match"
- compat-results.yaml gains `raw_match_pct` and `known_divergences`
- the console recap prints "93% (raw 89%, 4 pts masked)"

This changes reporting only. No pin is added or removed, the stale-mask gate
is untouched, and `bql_pct` keeps its meaning so the history series and badge
stay comparable across runs.

VERIFIED by running the harness, not by reading the diff:

  Runs tested:         68
  Raw match:           0/68 (0%)  [nothing masked]
  Known Python diffs:  4
  Effective match:     4/68 (5%)  [+4 masked, 5 pts over raw]

on a file set chosen because it carries known-divergence pins, so the
masked-vs-raw split is actually exercised rather than both reading zero.
`bql_raw_pct=0` and `bql_pct=5` were written to GITHUB_OUTPUT in the same run.
Self-test still passes; compat.yml still parses.
robcohen added a commit that referenced this pull request Aug 3, 2026
#1929 added the raw rate to the step summary, compat-results.yaml,
GITHUB_OUTPUT and the console recap - but not to the PR comment, which is the
most-read surface in the repo and the one that produced the "BQL
Compatibility 93%" that prompted the change.

The gap this closes is not hypothetical. #1927 pinned 51 proven-upstream
pairs in a single PR and moved the effective figure from 93% to 95% with raw
unchanged underneath. Anyone reading only the headline saw compatibility
improve when nothing about rledger had.

The cell now reads: 95% (raw 89%, 159 masked)

Raw goes INSIDE the existing cell rather than in a new row, so the headline
cannot be quoted without it.

Degrades to the old single-figure cell when the raw key is absent, which is
what a re-run against a pre-#1929 artifact produces - an N/A would be noise.

Verified by running the script logic in node against both shapes: current YAML
gives "95% (raw 89%, 159 masked)", a pre-#1929 one gives "93%", and the
effective key is not shadowed by the raw key (bql_raw_match_pct does not
contain the substring bql_match_pct).

Refs #1902.
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.

2 participants