Skip to content

feat(compat): compare booked values against beancount, not just shapes - #1910

Merged
robcohen merged 3 commits into
mainfrom
feat/compat-compare-values
Jul 31, 2026
Merged

robcohen merged 3 commits into
mainfrom
feat/compat-compare-values

Conversation

@robcohen

Copy link
Copy Markdown
Member

Item 1 of the bug-hunt plan. It found real bugs on the first run.

The gap

The comprehensive compat test compares:

check_match           did check pass/fail agree
accounts_match        same set of account names
posting_count_match   same NUMBER of postings
error_presence_match  did either report any error

No amount is ever compared. A booking or interpolation bug that produces the right number of postings with the wrong numbers in them passes silently — for an accounting tool, the failure that matters most.

What this adds

Sums booked units per (account, currency) per file and compares against Python beancount. Sensitive to interpolation, booking and sign handling; insensitive to directive order and to display scale, since scale is a separate documented divergence (#1112) and not what this is hunting — so the comparison is numeric, not textual.

First run: 259 files compared, 4 divergences, all real

#1908 — query and report exit 0 on a file that failed to parse, emitting data from the partial parse. check correctly exits non-zero on the same file, so the two commands disagree about whether a file is usable. Any automation piping query --format csv gets plausible-looking wrong numbers with a success status.

Surfaced because a unicode account name beancount accepts (Assets:CORP✨) is truncated to Assets:CORP and still reaches a result set — where it would collide with a real Assets:CORP.

#1909 — interpolated postings book the exact residual where beancount quantizes.

file beancount rledger
fidelity, 2012-08-01 0.00 USD 0.000000000005 USD
vanguard, 2013-09-05 -0.00 USD -0.0003183 USD

Both transactions balance in both tools. The damage is downstream: capital-gains accounts carry sub-cent noise, and a file total reads 0.030000000005 instead of 0.03. Both corpus instances share this one root cause.

Advisory, not gating

continue-on-error: true until the known set is triaged to zero. Flip it off then. Shipping it as a gate today would just mean a permanently red job, which is how the miri situation started.

Verification

Two things checked before trusting any of it:

  • Sabotage-tested with a deliberate 0.01 perturbation on the beancount side, to confirm the harness can report a divergence at all.
  • Caught a near-vacuous first run — it compared 36 files and reported clean. The corpus is CI-fetched, so a fresh worktree holds 21 files rather than 732. The real run is 259 comparable files out of 758.

Reproducing locally

uv run --with beancount python3 scripts/compat-values.py \
  --corpus tests/compatibility/files tests/regressions

The comprehensive compat test compares `check_match`, `accounts_match`,
`posting_count_match` and `error_presence_match` — how MANY postings a
file has and WHETHER either tool errored. It never compares an amount.
A booking or interpolation bug that produces the right number of postings
with the wrong numbers in them passes it silently, which for an
accounting tool is the failure that matters most.

This sums booked units per (account, currency) across a file and compares
against Python beancount. That is sensitive to interpolation, booking and
sign handling, while staying insensitive to directive ORDER and to
display scale — scale is a separate documented divergence (#1112) and not
what this is hunting, so the comparison is numeric rather than textual.

First run over 259 comparable corpus files found 4 divergences, and they
are real:

  #1908  `query` and `report` exit 0 on a file that failed to parse and
         emit data from the partial parse. Found because a unicode
         account name (`Assets:CORP✨`, which beancount accepts) is
         truncated to `Assets:CORP` and still reaches a result set.

  #1909  Interpolated postings book the EXACT residual where beancount
         quantizes to the currency's precision: `0.000000000005 USD`
         against beancount's `0.00`, and `-0.0003183` against `-0.00`.
         Sub-cent noise in capital-gains accounts, summing to 0.03 vs
         0.030000000005 across a file. Both corpus instances share this
         one root cause.

Advisory in CI rather than gating, until that known set is triaged to
zero; flip `continue-on-error` off then.

Two things checked before trusting the result. The harness was
sabotage-tested with a deliberate 0.01 perturbation to confirm it can
report a divergence at all. And the first local run compared only 36
files while appearing clean — the corpus is CI-fetched, so a fresh
worktree holds 21 files rather than 732, and the run was very nearly
vacuous.
@robcohen
robcohen requested a review from a team as a code owner July 31, 2026 13:38
Copilot AI review requested due to automatic review settings July 31, 2026 13:38
@robcohen
robcohen enabled auto-merge (squash) July 31, 2026 13:39
@codecov

codecov Bot commented Jul 31, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 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.

Pull request overview

Adds an advisory compatibility check that compares booked numeric values (not just result “shapes”) between rustledger and Python beancount, to surface booking/interpolation/sign bugs that previously passed the compat suite undetected.

Changes:

  • Introduces scripts/compat-values.py to compute per-file totals of booked units grouped by (account, currency) and diff them against beancount.
  • Wires the new value-compare into the compat.yml GitHub Actions workflow as a non-gating (continue-on-error) step with a short Step Summary excerpt.

Reviewed changes

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

File Description
scripts/compat-values.py New Python harness to compare per-file booked totals between beancount and rledger query.
.github/workflows/compat.yml Adds an advisory CI step running the new harness and emitting a brief summary into $GITHUB_STEP_SUMMARY.
Suppressed comments (1)

scripts/compat-values.py:112

  • The summary line says skipped files are due to "errors in either tool", but skipped is only incremented for beancount errors/unbooked postings and for rledger_totals() returning None. With stderr-reported rledger errors (rc==0) surfaced as divergences, this message becomes misleading.
    print(f"compared {compared} files, skipped {skipped} "
          f"(errors in either tool, or unbooked postings)")

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

Comment thread scripts/compat-values.py Resolved
Comment thread .github/workflows/compat.yml Resolved
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 93%
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

The first version skipped any file where beancount reported an error,
which left 499 of 758 unexamined. Measuring why showed 499 of those 500
skips were "beancount reported errors" — and 302 of them are fully
booked, more files than were being compared at all.

The distinction that matters is which errors stop beancount booking. A
file missing an `open` directive still books its postings correctly and
its amounts are exactly as comparable as a clean file.s; a lexer or
parser error means the entry stream is incomplete and a comparison would
be reading two different ledgers. So ValidationError, BalanceError,
DocumentError and PadError are now tolerated and everything else still
skips.

Coverage: 259 -> 560 files, 34% -> 74% of the corpus.

Also guards against #1908 from the other side: `query` exits 0 on a file
that failed to PARSE and emits data from the partial parse, so a parse
complaint on stderr now marks a file not-comparable. Without that, the
unicode-account file was being reported as a value divergence when it is
really a truncated ledger — a wrong diagnosis of a real bug.

The wider run immediately found #1911: rledger cannot interpolate a
missing units number when a cost is present. beancount solves
`600.00 / 300.00 = 2 HOOL`; rledger leaves the posting unfilled and
reports the whole other leg as the residual. The bare case without a
cost works, so it is one missing branch rather than a missing feature.

Known divergences now: #1909 (two files, interpolation quantization),
#1911 (one file), and issue-520.beancount which is a tracked regression
fixture.
Copilot AI review requested due to automatic review settings July 31, 2026 13:48

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 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (3)

.github/workflows/compat.yml:727

  • This step pipes the script through tee without enabling pipefail, so a non-zero exit from compat-values.py can be masked by tee returning 0. That would prevent the step from failing even when the script detects divergences or errors, and makes it easy to miss breakages until someone reads the logs. Capture and re-emit the pipeline status while still writing the step summary.
        run: |
          python3 scripts/compat-values.py \
            --rledger ./target/release/rledger \
            --corpus tests/compatibility/files tests/regressions \
            | tee compat-values.txt

scripts/compat-values.py:119

  • The broad except Exception: bc = None silently treats unexpected beancount loader failures (including harness bugs) as “skipped”, which can make the run look healthy while actually not comparing anything meaningful. It’s safer to at least log the exception (and still skip that file) so CI/local runs don’t go false-green.
        try:
            bc = beancount_totals(path)
        except Exception:
            bc = None
        if bc is None:

scripts/compat-values.py:136

  • main() always returns 0 even when (a) divergences are found or (b) the run is near-vacuous (e.g. compared=0). That makes it hard to flip this from advisory to gating later, and it can hide “didn’t actually run” situations like a missing corpus. Consider returning a non-zero exit code when divergences exist, and a distinct non-zero code when nothing was comparable.
    print(f"compared {compared} files, skipped {skipped} "
          f"(errors in either tool, or unbooked postings)")
    print(f"files with a VALUE divergence: {len(divergent)}\n")
    for path, diffs in divergent[:25]:
        print(f"  {path}")
        for (acct, cur), x, y in diffs[:6]:
            print(f"      {acct} {cur}:  beancount={x}  rledger={y}")
    return 0

…ison

Two review catches, both the vacuous-pass shape.

`subprocess.run(..., timeout=120)` raises `TimeoutExpired`, which aborted
the whole sweep. One pathological file must not discard the other 700-odd
results — that is the entire value of a corpus run. Now counted as
not-comparable.

The CI step piped into `tee` without `set -o pipefail`, so a crashed
comparison would leave an empty compat-values.txt and a GREEN step. This
workflow already uses pipefail for tee elsewhere.
Copilot AI review requested due to automatic review settings July 31, 2026 15:10

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 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (1)

scripts/compat-values.py:142

  • main() always returns 0, even if no files were actually comparable (e.g. corpus fetch/path issue, systemic beancount/load failure, or every rledger run timing out). That creates a vacuous “all good” exit status, and the printed skip summary is also slightly misleading because skipped includes timeouts.

Consider failing non-zero when compared == 0 (so CI can’t go green on a no-op run) and update the skip message to include timeouts.

    print(f"compared {compared} files, skipped {skipped} "
          f"(errors in either tool, or unbooked postings)")

@robcohen
robcohen merged commit 82953ec into main Jul 31, 2026
54 checks passed
@robcohen
robcohen deleted the feat/compat-compare-values branch July 31, 2026 15:18
robcohen added a commit that referenced this pull request Jul 31, 2026
`query` and `report` exited 0 on a file with parse errors and printed
numbers derived from the partial parse. `check` refused the same file, so
the CLI contradicted itself: one command called a file unusable while
another reported on it and claimed success.

This is a DELIBERATE DEVIATION from Python beancount, verified rather
than assumed. bean-query does exactly what rledger did:

  $ bean-query broken.beancount "SELECT account, sum(number) ..."
  account   n
  --------  -
  Assets:A  0
  exit=0

byte-identical output and exit code, and beancount's loader likewise
returns the transactions it managed to parse past a LexerError. The
existing code said so: "matching bean-query behavior / Continue with
successfully parsed directives rather than bailing".

We deviate because the output is not merely incomplete, it is PLAUSIBLE.
`Assets:A 0` looks like an answer, carries a success status, and lands on
stdout that another program is probably consuming. For a tool whose whole
job is producing figures people rely on, confidently wrong is worse than
loudly broken.

Scoped to PARSE errors only. Validation errors — an account never opened,
a failed balance assertion — leave the entry stream complete and the
arithmetic sound, so they still report exactly as beancount does. Real
ledgers are full of those and refusing them would be a real
compatibility loss for no safety gain. A test pins that half of the
contract, because narrowing the deviation is what makes it acceptable.

No `KNOWN_RUST_DIVERGENCES` entry: the BQL suite's `load_valid_files`
already requires `python_ok AND rust_ok`, so a file neither tool parses
never reaches that comparison. An entry would imply a divergence the
metric cannot observe.

Found by comparing booked VALUES against beancount (#1910), which the
shape-only comparison could not see.

Verified the tests fail without the guard.

Closes #1908
@robcohen
robcohen restored the feat/compat-compare-values branch July 31, 2026 15:50
robcohen added a commit that referenced this pull request Aug 1, 2026
fix(compat): compare balances as money, not as raw Decimals

Re-lands the correction from #1910, which was pushed after that PR had
already auto-merged and so never reached main.

The comparison used raw Decimal equality, which reported two divergences
that were representation differences rather than value disagreements. The
two tools quantize at different layers: beancount rounds when it books,
rledger books what the arithmetic implies and rounds when it displays.

`0.035 SPY @ 137.142857143 USD` against an explicit `4.80` leaves 5e-12.
beancount books 0.00 and loses it; rledger books 0.000000000005, keeps
the postings summing to exactly zero, and renders 0.03 on every surface
that knows the currency. Only `sum(number)` - a deliberately
currency-less projection, which is what this harness asks for - shows the
residue, and there the exact sum is the correct answer. #1909 was closed
as working-as-intended on that basis: rledger preserving the value is the
better behavior, since beancount silently discards a tenth of a cent
someone deliberately typed.

Each side is now quantized to beancount's own exponent before comparing:
beancount has already rounded to the currency's precision at booking, so
its exponent IS the precision at which these figures are money. Stated
cost: a genuine divergence smaller than one display unit is invisible,
which is by definition a difference no user could observe in a balance.

Verified against seven cases that this silences only what it should -
both #1909 representation cases go quiet, while a one-cent error, a sign
flip, a missing posting and a magnitude blowup all still report.

Corpus, with #1913 also applied: 4 divergences -> 1, the survivor being
issue-520.beancount, a tracked regression fixture.
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