Skip to content

test(compat): fail on NEW booked-value divergences against beancount - #2148

Merged
robcohen merged 3 commits into
mainfrom
feat/gate-booked-value-divergences
Aug 25, 2026
Merged

robcohen merged 3 commits into
mainfrom
feat/gate-booked-value-divergences

Conversation

@robcohen

Copy link
Copy Markdown
Member

Closes #2147.

The gap

scripts/compat-values.py compares booked values, per-posting cost/price/lot-date, error kinds and price directives against Python beancount. Its docstring states the case for existing: a bug producing the right number of postings with the wrong numbers in them "passes silently, which for an accounting tool is the failure that matters most."

Nothing failed when it found one. The step was continue-on-error, main() returned 0 unconditionally, and no gate read the result -- it went into compat-values.txt and the step summary. Every other comparison in compat.yml is gated (budget, booking, capgains, returns, check regressions, synthetic differential). This one was not, so a PR could introduce a fresh divergence and stay green.

Why not just fail on any divergence

There are 34 today, and most are rustledger being the more correct side: Python's decimal context rounds an intermediate at 28 significant digits where rustledger carries the exact value.

number:       beancount=-720.0200000000000000000000001  rledger=-720.02
price_number: beancount=54.13684210526315789473684211
              rledger=54.136842105263157894736842105

A gate that went red on those would get switched off within a week, which is plausibly how it ended up ungated to begin with.

Shape

The same recorded-baseline approach the BQL step in this workflow already uses:

  • --write-baseline FILE records the current divergence set
  • --baseline FILE exits 1 on anything outside it
  • a divergence that goes away prints RESOLVED and does not fail, so the file can be trimmed rather than silently accumulating entries that pin nothing

Keys are (basename, field), matching how KNOWN_POSTING_DIVERGENCES is already keyed. The corpus is fetched to different absolute paths in CI and locally; a baseline keyed on full paths would match nothing and pass everything.

Verified in both directions

A gate is worth exactly what its failure case is worth, so both were run:

scenario result
against its own baseline exit 0, known 34, found 34, new 0, no-longer-diverging 0
pre-#2139 binary, ledger exercising #2118 exit 1, naming value:Income:Gains USD and posting:<row count>

The script's own --self-test still passes across all four axes.

actionlint on the modified workflow: 3 findings, identical to main.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`compat-values.py` compares booked values, per-posting cost/price/lot-date,
error kinds and price directives against Python beancount across the corpus.
Its docstring says why it exists: a bug producing the right number of
postings with the wrong numbers in them "passes silently, which for an
accounting tool is the failure that matters most".

Nothing failed when it found one. The step was `continue-on-error`, `main()`
returned 0 unconditionally, and no gate read the output -- it went to
`compat-values.txt` and the step summary. Every other comparison in this
workflow is gated (budget, booking, capgains, returns, check regressions,
synthetic differential); this one was not. A PR introducing a fresh
divergence printed it into a summary and stayed green.

Gating on ANY divergence was never an option, which is presumably how it
ended up this way. There are 34 today, largely rustledger carrying an exact
value where Python's `decimal` context rounds an intermediate at 28
significant digits:

  number:       beancount=-720.0200000000000000000000001  rledger=-720.02
  price_number: beancount=54.13684210526315789473684211
                rledger=54.136842105263157894736842105

rustledger is arguably the better side of those, and a gate that failed on
them would simply be switched off again.

So this takes the shape the BQL step already uses in the same workflow: a
recorded baseline, where only departures fail. `--write-baseline` records the
current set, `--baseline` fails on anything outside it, and a divergence that
GOES AWAY is reported as RESOLVED rather than failing, so the file can be
trimmed instead of silently accumulating entries that pin nothing.

Keys are (basename, field), matching how `KNOWN_POSTING_DIVERGENCES` is
already keyed: the corpus is fetched to different absolute paths in CI and
locally, so a baseline keyed on full paths would match nothing and pass
everything.

Verified in both directions, which is the only way a gate is worth having:

  against its own baseline          exit 0, "known 34, found 34, new 0"
  against a pre-#2139 binary on a
  ledger exercising #2118           exit 1, naming
                                    "value:Income:Gains USD" and
                                    "posting:<row count>"

Closes #2147.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner August 25, 2026 14:08
Copilot AI lite review requested due to automatic review settings August 25, 2026 14:08
@codecov

codecov Bot commented Aug 25, 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

This PR closes #2147 by turning the booked-value compatibility comparison (scripts/compat-values.py) into a CI gate that fails the workflow only when new divergences vs Python beancount appear, while allowing the existing known divergence backlog to remain non-blocking.

Changes:

  • Added --baseline / --write-baseline support to scripts/compat-values.py and exit-nonzero behavior for divergences not present in the recorded baseline.
  • Introduced a committed baseline file (tests/compatibility/known-value-divergences.json) containing the currently accepted divergence keys.
  • Updated .github/workflows/compat.yml to run the comparison in continue-on-error mode, capture its exit status, and fail the job via a dedicated “Gate on booked-value divergences” step when the baseline check fails.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
tests/compatibility/known-value-divergences.json Adds the recorded set of accepted (file, field) divergence keys used as the baseline.
scripts/compat-values.py Implements baseline recording and gating logic using stable (basename, field) divergence keys.
.github/workflows/compat.yml Wires the baseline-gated comparison into CI and adds a follow-up step that fails the job on new divergences.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

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

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 170 masked)
Full AST Match 100%
Total Files 811
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

robcohen and others added 2 commits August 25, 2026 14:33
The baseline is generated, so two PRs that both record divergences collide
in it, and an unresolved conflict marker is the likeliest way it goes bad.
Only FileNotFoundError was handled, so that surfaced as a JSONDecodeError
traceback in a CI log.

Also validates shape, which is the quieter half. `set(map(tuple, raw))`
turns a bare string entry into a tuple of its characters rather than a key,
so a hand-edit leaving `["value:x"]` instead of `[["f.beancount",
"value:x"]]` would match nothing and report every known divergence as new,
with nothing in the output to say why.

Each rejection path was run: a conflict marker, a list of bare strings, and
a pair with a non-string element all give one line and exit 1. The real
baseline still reports known 34, found 34, new 0.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Self-review findings on the new booked-value gate.

The step was inserted between an existing comment block and the step it
documents, so "Mirrors the BQL step's `--baseline`..." -- written about
`Gate on check regressions` -- read as though it described this gate
instead. Moved up beside the other comparison gates, which is where it
belongs anyway.

`steps.booked_values.outputs.failed != '0'` fired on an EMPTY output. When
an earlier step aborts the job, this one is skipped, its outputs are unset,
and `'' != '0'` is true: the gate ran on an already-red build and annotated
it with a booked-value divergence that never happened. Added
`outcome != 'skipped'`. Kept `!= '0'` rather than the `== '1'` the fuzz
gates use, and said why in a comment: those report a boolean, this forwards
the script's exit code, and a usage error exits 2.

`--limit` truncates the corpus, so it silently produced a partial
divergence set. `--write-baseline --limit 5` would have shrunk the recorded
file from 34 entries to whatever the first five files happened to diverge
on, and `--baseline --limit 5` reports every unvisited entry as RESOLVED and
exits 0. Both read as success. Now refused outright.

Dropped a function-local `import os` for `path.name`; `path` is already a
`Path` and the KNOWN_POSTING_DIVERGENCES lookup keys on `path.name` two
hundred lines up.

Documented what the key does not pin: it records WHERE we diverge, not by
how much, so a known-diverging cell whose numbers get worse still passes.
Pinning values was considered and rejected -- CI installs beancount from
master, so its side can move with no change here, and a baseline that churns
on upstream commits gets regenerated reflexively instead of read. Also noted
that KNOWN_POSTING_DIVERGENCES is the better home for a divergence that has
a reason worth writing down.

Re-ran every path: baseline clean (known 34, found 34), pre-#2139 binary
still exits 1 naming both keys, three malformed-baseline shapes and a
missing file each give one line and a non-zero exit, --limit alone is
unchanged, self-test passes, actionlint holds at main's 3.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit ca32527 into main Aug 25, 2026
48 checks passed
@robcohen
robcohen deleted the feat/gate-booked-value-divergences branch August 25, 2026 16:00
robcohen added a commit that referenced this pull request Aug 26, 2026
…recations

Three review findings on #2159, and a regression the third one exposed.

The scope notice reused E7003. That code means "specified twice, last value
wins" and maps downstream to `ErrorCode::DuplicateOption`, but an option
ignored for coming from an included file may be the only one of its name in
the tree. It now has E7009, documented alongside the others.

Giving it a code was not enough, and this is the part worth recording.
`cmd::check` classified severity as `warning.code != "E7003"`, so the new code
was an error, and #1546's own repro started exiting non-zero again -- the
exact complaint that issue was filed about, reintroduced by fixing a
different problem. Every unit test still passed. What caught it was running
that ledger end to end, and there was already a test doing exactly that:
`test_check_multi_entity_include_duplicate_option_ok`. Confirmed by reverting
the classification and watching it fail. That test now also asserts the
resolved title is "Combined", which is what the ledger asked for and what
#2151 makes it get.

The scope check also swallowed more specific diagnostics. `option "plugin"`
is deprecated and raises E7004, which `check` treats as an error; reporting
only the ignore notice would have made an included file the one place a
deprecated option stopped failing the build. Deprecation is now raised first,
from a shared table so the scope branch cannot drift from the three arms that
already had those messages inline.

Also moves `REPEATABLE_OPTIONS`'s doc comment back onto it. The new constant
was inserted between the comment and the item it documented, so the list
about include scoping was introduced as "Options that can be specified
multiple times". Same mistake as the one review caught on #2148.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen added a commit that referenced this pull request Aug 27, 2026
…2159)

* fix(loader): options in an included file no longer govern the ledger

Closes #2151.

An option set in an included sub-ledger applied to the whole tree, last one
included winning. `booking_method` decides which lot a sale consumes and
`inferred_tolerance_default` decides what counts as balanced, so a sub-ledger
silently changed results for every other entity, including the master's own
transactions. An included file could make an unbalanced transaction pass.

Scoped per option, by what the option governs rather than by one blanket
rule. Options describing the file that declares them still accumulate:
`operating_currency`, `documents`, `insert_pythonpath`, `display_precision`,
and plugins, which never routed through here. Everything else now comes from
the top-level ledger.

Note the split is NOT the repeatable-option list. Repeating within one file
and crossing an include are different properties, and conflating them is the
bug: `inferred_tolerance_default` accumulates within a file and must still not
cross an include.

This does not undo #1546 and its implementation was not at fault. #1546 asked
for two things: E7003 should not be a hard error, which is right and stays,
and last-wins extended to include trees, which it requested explicitly. That
second request rested on "beancount permits redefining a scalar option with
last-wins", true inside one file and false across `include`, where beancount
takes the top-level file's options and aggregates only three. The request was
reasonable; the belief behind it was not.

#1546's own repro is the clearest evidence. It has `option "title" "Combined"`
in the master and a title in each sub-ledger. It already exited 0 before this
change, so its actual complaint was fixed by the warning alone, and it
resolved to "Entity B", the last file included. It now resolves to "Combined",
matching bean-check, while still exiting 0.

Deliberately NOT copying beancount wholesale. Its uniform rule also discards
plugins declared in included files, which leaves the user with validation
errors about accounts a plugin they did declare would have opened. We run
them, and that stays.

E7003's wording was wrong in both spellings and is fixed: "can only be
specified once" is false, since bean-check accepts a redefinition and takes
the last value. Within a file it now says the last value wins; across an
include it says the value was ignored and the top-level ledger governs, so a
reader can tell why their setting had no effect.

CACHE_VERSION 29 to 30, with the wasm pin. `Options` is part of the cached
payload, so a v29 cache replays the old resolution and resurrects the leak.
Found the hard way: the verification matrices kept diverging until the stale
caches were cleared. The two archived-layout tripwires advance to fixture
version 30 with their byte arrays untouched, which is the point of them:
this changes which options resolve, not how anything is encoded.

Verified against bean-query on all three rows of both value-changing options,
plus title and the plugin case. Booked-value gate reports `known 34, found
34, new 0` across 761 files. Both proofs are real: reverting the scope flag
brings the leak back end-to-end, and disabling the check fails the unit tests.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

* fix(loader): give the include-scope notice its own code, and keep deprecations

Three review findings on #2159, and a regression the third one exposed.

The scope notice reused E7003. That code means "specified twice, last value
wins" and maps downstream to `ErrorCode::DuplicateOption`, but an option
ignored for coming from an included file may be the only one of its name in
the tree. It now has E7009, documented alongside the others.

Giving it a code was not enough, and this is the part worth recording.
`cmd::check` classified severity as `warning.code != "E7003"`, so the new code
was an error, and #1546's own repro started exiting non-zero again -- the
exact complaint that issue was filed about, reintroduced by fixing a
different problem. Every unit test still passed. What caught it was running
that ledger end to end, and there was already a test doing exactly that:
`test_check_multi_entity_include_duplicate_option_ok`. Confirmed by reverting
the classification and watching it fail. That test now also asserts the
resolved title is "Combined", which is what the ledger asked for and what
#2151 makes it get.

The scope check also swallowed more specific diagnostics. `option "plugin"`
is deprecated and raises E7004, which `check` treats as an error; reporting
only the ignore notice would have made an included file the one place a
deprecated option stopped failing the build. Deprecation is now raised first,
from a shared table so the scope branch cannot drift from the three arms that
already had those messages inline.

Also moves `REPEATABLE_OPTIONS`'s doc comment back onto it. The new constant
was inserted between the comment and the item it documented, so the list
about include scoping was introduced as "Options that can be specified
multiple times". Same mistake as the one review caught on #2148.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

* docs(loader): separate the plugin directive from the deprecated plugin option

The note on `ACCUMULATE_ACROSS_INCLUDES` said plugins are absent from the list
because they "never route through here". True of the `plugin "name"`
DIRECTIVE, which is collected separately and accumulates from any file. Not
true of the deprecated `option "plugin"` form, which is a known option, does
route through `set_scoped`, and is scoped out like everything else.

The distinction is the reason the include-scope branch re-raises E7004 two
screens below, so a reader who believed the old sentence would have found
that code path unexplained. Verified both halves: `option "plugin"` in an
included file now reports E7004 and E7009 together, while a `plugin`
directive in an included file still runs and the ledger still checks clean.

Third PR running where reading the finished diff end to end turned up a
comment whose "why" had stopped being true. The pattern is consistent enough
to be worth naming: comments that restate code age harmlessly, comments that
explain why something must be a certain way go actively wrong.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

* refactor(loader): one place that raises a deprecation warning

Four sites spelled out the E7004 push: the three arms for deprecated options
and the include-scope branch added with #2151. The arms reached it through
`deprecation_message(key).unwrap_or_default()`, which is the shape worth
removing: an entry dropped from the table would have produced an E7004 with
an EMPTY message rather than any visible failure, and an empty diagnostic is
worse than a missing one because it still counts as an error.

`warn_if_deprecated` now owns raising it and reports whether it fired, so the
message can only come from the table and the table is the only thing to keep
in step.

Verified each of the three still reports its own text at top level, and that
a deprecated option inside an include still reports E7004 and E7009 together
with neither message empty.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

* refactor(loader): drop the unused return from warn_if_deprecated

It reported whether it had fired, and none of its four callers looked. A
return value nothing consumes is a standing invitation to assume it matters,
and the doc said "reporting whether it was" as though someone acted on it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

---------

Co-authored-by: Claude Opus 5 <[email protected]>
robcohen added a commit that referenced this pull request Aug 28, 2026
Review catches on #2174, all three from Copilot.

The gated set is FOUR columns -- entry, meta, _entry_meta, _posting_meta
-- not five. I wrote five in the code comment, the commit message and the
PR body.

Inserting expr_calls_any_function above query_references_column detached
that function's doc comment onto the new one, leaving
query_references_column undocumented and the new helper described by
someone else's prose. Third time I have done this exact thing (#2148,
#2159), and the shape is always the same: adding an item directly above
one that already had a doc comment.

The metadata-function test looped over three of the four dispatched
names, omitting POSTING_META, so a gate that forgot it would have passed.
Confirmed the test now fails when POSTING_META alone is dropped from the
detected list.
robcohen added a commit that referenced this pull request Aug 28, 2026
* perf(query): skip #postings columns the query cannot observe

Five of this table's 31 columns hold most of its cost: the structured
`entry` object and the three metadata maps (`meta`, `_entry_meta`,
`_posting_meta`). They are now built only when the query can observe
them.

On a 40k-posting ledger, best of three:

    SELECT count(account) FROM #postings   433ms/227MB -> 240ms/131MB
    SELECT account FROM #postings          484ms/229MB -> 296ms/133MB
    SELECT meta('k') FROM #postings        482ms/228MB -> 290ms/135MB
    SELECT * FROM #postings               1617ms/844MB -> 1419ms/766MB

With #2173 that is 681ms/517MB -> 240ms/131MB for the first, -65% and
-75%.

The other 26 columns were measured and left alone: stubbing both
`StringSet` columns moved 443ms to 437ms. Gating them would cost more in
review surface than it saves.

Three ways to reach a gated column, each of which fails SILENTLY when the
gate is too tight -- a missed one yields Null, not an error:

  * By name, including through an attribute: `entry.narration` reaches
    `entry` because `expr_references_column` recurses into
    `Attribute`/`Subscript` operands.
  * By FUNCTION: `META`, `ENTRY_META`, `ANY_META` and `POSTING_META` are
    dispatched by name and then read `_posting_meta` / `_entry_meta` off
    the row. A query calling `meta('key')` names neither column, so
    gating on column references alone drops the data it needs. Detected
    with a new `query_calls_any_function`, which mirrors
    `query_references_column`'s clause coverage and walks the OVER
    clause -- the case Copilot caught on #1085.
  * By wildcard, which forces on only what `SELECT *` can SHOW. This
    table's wildcard emits `meta` but omits `entry` and the underscore
    helpers, since `wildcard_hidden` drops the structured entry column to
    match beanquery. Forcing all five was the first attempt and left
    `SELECT *` with no improvement at all.

Verified by diffing query output against a main-built binary across 17
shapes, including `SELECT *, entry.narration` and
`SELECT * ORDER BY entry.narration`, and re-run after the clippy
refactor rather than assumed. Each of the three gates is confirmed to
fail its own assertion when removed.

Closes #2169

* fix(query): correct the gated-column count and re-attach a doc comment

Review catches on #2174, all three from Copilot.

The gated set is FOUR columns -- entry, meta, _entry_meta, _posting_meta
-- not five. I wrote five in the code comment, the commit message and the
PR body.

Inserting expr_calls_any_function above query_references_column detached
that function's doc comment onto the new one, leaving
query_references_column undocumented and the new helper described by
someone else's prose. Third time I have done this exact thing (#2148,
#2159), and the shape is always the same: adding an item directly above
one that already had a doc comment.

The metadata-function test looped over three of the four dispatched
names, omitting POSTING_META, so a gate that forgot it would have passed.
Confirmed the test now fails when POSTING_META alone is dropped from the
detected list.

* test(query): cover query_calls_any_function directly

Review addition on #2174. The new walker was only exercised through
#postings queries, and two of its arms cannot be reached that way:
`meta('k') BETWEEN ...` type-errors before the gate matters, and window
functions are rejected outright with an explicit FROM #postings. A direct
unit test now covers every clause and every expression shape, mirroring
the sibling test for query_references_column.

Each arm was confirmed to fail the test when made to return false.
Removing an arm outright does not compile: the match is exhaustive with
no catch-all, so a future Expr variant is a build error rather than a
silent false -- worth having, since a false negative here materializes
nothing and meta('k') returns Null with no error.

Also corrects the claim that walking the OVER clause was load-bearing
here. It mirrors expr_references_column so the two stay
interchangeable; this call site cannot reach it.

* docs(query): record the instruction-count measurement

Review addition on #2174. The wall-clock numbers were the only evidence,
and they move with machine load. Callgrind on the profiling harness puts
the combined #2169 + #2173 effect at 457.4M -> 244.2M instructions, -47%,
which does not.

It also closes the loop on the harness gap #2173 fixed: the system-table
shapes added there are exactly the ones that improved, so the harness now
measures the path it previously could not see.
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.

[Testing]: booked-value divergences against beancount are reported but never fail the build

2 participants