Repository navigation
feat(compat): compare per-posting cost, price and lot date in the oracle - #1940
Conversation
The oracle summed units per (account, currency). That cancels compensating per-posting errors, and it never looked at cost or price at all. #1915 is the case in point: `100.00 USD @` was read as "no price", and the UNITS were identical before and after the fix, so no sum could ever have shown it. This adds a third axis comparing each posting on date, account, number, currency, cost_number, cost_currency, cost_date and price, as an ordered multiset. FIRST CORPUS RUN FOUND A REAL BUG #1939: an arithmetic expression in a COST SPEC is truncated to its first operand, while the same expression in a PRICE annotation evaluates correctly. Assets:Something 2 HOOL {10.00 * 3 USD} @ 20.00 * 2 USD beancount cost 30.00 price 40.00 rledger cost 10.00 price 40.00 Consequences are a wrong cost basis, and then a FALSE E3001 rejecting a file beancount accepts, because the weight follows the truncated cost. DESIGN DECISIONS, AND WHY Reference side is the beancount PYTHON API, not bean-query. beanquery has bugs of its own (beanquery#279 is pinned in the BQL suite for exactly that reason) and an oracle that inherits the reference implementation's query-layer bugs is not an oracle. Our side is read as JSON, NOT CSV. This is the whole ballgame and it cost a full corpus run to learn: CSV renders every number through DisplayContext, so a price written `56.0763 USD` in a ledger whose USD is mostly 2-decimal comes back as `56.08`. The first run reported 32 files diverging on price_number, and every single one was the harness comparing beancount's STORED value against rledger's RENDERED one. None was a defect. JSON carries the stored value. Generalized: a differential oracle must not read the other side through a presentation layer. Lot dates and currencies compare EXACTLY. A lot date is either the right lot or it is not, and softening that would defeat the reason the axis exists. Only the three money fields get the precision tolerance, and it is the same one `compare()` already uses for units after #1909 - quantize to beancount's own exponent, because beancount rounds when it books and rledger rounds when it displays. TWO HARNESS BUGS THE RUN EXPOSED, BOTH FIXED HERE - CSV vs JSON, above: 32 false findings. - Signed zero. Decimal keeps the sign of zero and the tools do not always agree on it, so `-0.00` and `0.00` sorted differently, every row after the first signed zero was compared against the wrong partner, and one file reported five bogus `number` differences that were really one misalignment. SELF-TEST Extended to the new comparator, on synthetic rows rather than fixtures because the interesting cases are ones no ledger we have produces on demand: a wrong cost, a wrong lot date, a one-sided price, a row-count mismatch, and - the one that matters most - a difference that is REPRESENTATION and must NOT be reported, paired with one AT beancount's precision that must be. Verified by sabotage, twice: gutting the comparator, and widening the tolerance to always agree. Both are caught, the second reporting exactly the two checks that distinguish a real difference from a representational one. REMAINING FINDINGS, NOT YET TRIAGED 12 files diverge. Beyond #1939 they include two known rust_decimal ceiling cases (30 significant digits, documented in CLAUDE.md as not fixable locally), a `{# 2000 USD}` total-cost reading where we say 200 and beancount says 2000, and several IncompleteInputs fixtures where beancount computes a price we leave unset. None is pinned: an untriaged finding should stay surfaced. Refs #1902.
There was a problem hiding this comment.
Pull request overview
This PR strengthens the scripts/compat-values.py “oracle” by adding a third comparison axis that checks per-posting attributes (cost, price, lot date) as an ordered multiset rather than relying only on per-(account, currency) unit sums, which can cancel compensating per-posting errors and miss cost/price divergences.
Changes:
- Added a per-posting query (
POSTING_QUERY) and two extractors (beancount_postings,rledger_postings) to compare(date, account, units, cost, lot date, price)per posting. - Switched rledger-side posting extraction to JSON output to avoid CSV/display quantization artifacts.
- Added comparator helpers (
_row_sort_key,_num_agrees,compare_postings) plus self-test coverage for the new axis.
Suppressed comments (3)
scripts/compat-values.py:384
- In
compare_postings, non-numeric fields are compared via(x or None) == (y or None), which treats empty strings as equal toNone. That can hide missing/empty required fields (date/account/currency) and contradicts the function doc that these compare exactly. Prefer strict equality for non-numeric fields and let missing values surface as divergences.
ok = _num_agrees(x, y) if name in numeric else (x or None) == (y or None)
scripts/compat-values.py:345
_row_sort_keyformats allDecimalvalues asf"{+v:+040.10f}", which rounds everything to 10 decimal places for ordering. That can cause distinct values to sort as equal (e.g., more-than-10dp costs/prices), reintroducing the misalignment issue this sort key is meant to prevent. Use an order key that preserves full precision (e.g., normalized sign-collapsed string viaformat(+v, 'f')+ explicit exponent) rather than a fixed 10dp format.
elif isinstance(v, Decimal):
# `+v` collapses -0.00 to 0.00. Decimal keeps the sign of zero, and
# the two tools do not always agree on it, so without this the two
# sides sort differently and every row after the first signed zero
# is compared against the wrong partner. That showed up as a file
# reporting five bogus `number` differences that were really one
# misalignment.
out.append((0, f"{+v:+040.10f}"))
else:
out.append((0, str(v)))
scripts/compat-values.py:308
- In
rledger_postings, a non-dictpricevalue is treated as(None, None), which will make the harness silently accept a shape mismatch in the JSON contract (e.g., ifpricestarts being emitted as a string). Since this is a machine-contract oracle, it’s better to fail comparison on unexpected shapes so the contract drift is visible.
def amount(v):
"""(number, currency) from a JSON amount, or (None, None)."""
if not isinstance(v, dict):
return None, None
return _dec(v.get("number")), v.get("currency") or None
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
| Metric | Result |
|---|---|
| Check Compatibility | 100% |
| BQL Compatibility | 95% (raw 89%, 162 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
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
It parses JSON amount strings as well as CSV cells since the axis switched to --format json. The docstring still said "CSV cell", which invites misuse. Also states the trade the None return makes: unparsable reads as absent rather than crashing, which is right for a corpus sweep (one bad file must not abort the other 700) but relabels a garbled field as present/absent. It is still reported either way.
… its findings The axis shipped without a way to record a deliberate deviation, so every settled divergence stayed in the report forever. That is how a signal gets muted, which is the failure #1902 exists to prevent. `KNOWN_POSTING_DIVERGENCES` is keyed by (basename, FIELD), not by file. A whole-file mask would also swallow a DIFFERENT field diverging on that file later - exactly the regression a registry is supposed to keep visible. Every entry carries its reason; an entry without one is indistinguishable from one added to make a run look clean. TRIAGE OF THE 10 FINDINGS Pinned, 10 fields across 5 files: rust_decimal 28-29 digit ceiling (2 files). The price needs 30 digits to round-trip. CLAUDE.md records this as not fixable locally; the recovery side channel was prototyped and rejected in PR #1613. Negative inferred price (2 files). `100.00 USD @` against `120.00 CAD` has both postings positive, so the price would have to be -1.20 CAD. beancount takes the magnitude; #1919 decided to refuse it and say so, because silently flipping the sign hides a sign error in the user's own ledger. issue-520 (1 file), the tracked regression fixture compat.yml names. Left surfaced on purpose, 5 files: The `{# total}` / `{per # }` compound-cost divergence, now filed as #1943. beancount treats a `#` spec as incomplete and SOLVES it from the residual, discarding what the author wrote: `{# 9.95}` against -19.90 cash books 1.990, not 0.995. We honor the written number and report E3001. Real, undecided, and it should stay in anyone's face until it is decided. `UnitsMissingNumberWithCost` cost_date and `Transactions.ZeroPrices` - triaged only far enough to know what they are. Pinning them would assert a conclusion nobody has reached. A LIMITATION #1943 EXPOSED IN THE ERROR AXIS Those compound-cost files were NOT flagged by axis 2. beancount emits ValidationError (unknown account) on the corpus copies while rledger emits E3001, so both "error" and the axis scores agreement. Not comparing error taxonomies is still the right call - there is no honest mapping between Python exception classes and our codes - but the cost is that a genuine semantic divergence can hide behind incidental agreement on WHETHER a file errs. Noted in the issue so a future clean error report is not over-read. SELF-TEST Extended with the property that matters for a field-keyed registry: a pin suppresses the field it names, and a pin on a DIFFERENT field leaves the finding visible. Verified by sabotage - rewriting the lookup to match on filename alone fails exactly that check.
|
Pushed 5415c1c — the axis shipped without a way to record a deliberate deviation, so every settled divergence would have stayed in the report forever. That's how a signal gets muted, which is the failure #1902 exists to prevent.
Triage of all 10 findingsPinned — 10 fields across 5 files:
Left surfaced on purpose — 5 files:
Report now reads: A limitation #1943 exposed in the error axisThose compound-cost files were not flagged by axis 2. beancount emits Self-testExtended with the property that matters for a field-keyed registry: a pin suppresses the field it names, and a pin on a different field leaves the finding visible. Verified by sabotage — rewriting the lookup to match on filename alone fails exactly that check: |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 1 out of 1 changed files in this pull request and generated no new comments.
Suppressed comments (1)
scripts/compat-values.py:405
_row_sort_key()rounds allDecimalfields to 10 fractional digits viaf"{+v:+040.10f}". That can collapse distinct values to the same sort key (e.g., values that only differ beyond 10dp, or cases where beancount preserves >10dp), making the sort order depend on input/stable-tie behavior and reintroducing the misalignment/cascade problem the key is trying to avoid. It also bakes in an arbitrary 10dp threshold that doesn’t match the comparator’s tolerance (which is based on beancount’s exponent). Use a canonicalized full-precision representation for sorting (collapse signed zero + strip trailing zeros) without rounding.
elif isinstance(v, Decimal):
# `+v` collapses -0.00 to 0.00. Decimal keeps the sign of zero, and
# the two tools do not always agree on it, so without this the two
# sides sort differently and every row after the first signed zero
# is compared against the wrong partner. That showed up as a file
# reporting five bogus `number` differences that were really one
# misalignment.
out.append((0, f"{+v:+040.10f}"))
else:
Copilot caught a real defect. `_row_sort_key` canonicalized Decimals with
`f"{+v:+040.10f}"`, which has two problems:
- `:.10f` rounds to 10 FRACTIONAL digits, and the values this comparison most
cares about are exactly the ones that do not survive that. The rust_decimal
ceiling cases carry ~30 fractional digits, so two genuinely different prices
flattened to the same key.
- unary `+` applies the active decimal context, so the token depended on
ambient state no caller sets deliberately.
The sort key exists to PAIR corresponding rows. Colliding keys mean distinct
rows pair arbitrarily, which can invent differences or hide them - and it
would have been at its worst on the high-precision entries the registry
pins, i.e. the ones nobody looks at twice.
Rebuilt from `as_tuple()`, which is context-free. Trailing zeros are stripped
by hand rather than via `normalize()` (which also consults the context), so
0.10 and 0.1 agree; an all-zero coefficient drops its sign, so -0.00 and 0.00
agree, which is the signed-zero misalignment fixed earlier.
Ordering only has to be TOTAL and identical on both sides. It does not have to
be numeric, and pretending it did is what invited the rounding in the first
place.
Self-test now pins both directions, including the two cases the old token got
wrong. Verified by putting the old token back:
SELF-TEST FAILED: sort token for 0.0096938775510204081632653061 22 vs
0.0096938775510204081632653061: same=True, expected False
SELF-TEST FAILED: sort token for 1.00000000001 vs 1.00000000002:
same=True, expected False
Corpus result is unchanged - 10 fields pinned, 5 files surfaced - so this
fixes a latent hazard rather than a live miscount.
The oracle summed units per
(account, currency). That cancels compensating per-posting errors, and it never looked at cost or price at all. #1915 is the case in point:100.00 USD @was read as "no price", and the units were identical before and after the fix, so no sum could ever have shown it.This adds a third axis comparing each posting on
date, account, number, currency, cost_number, cost_currency, cost_date, price, as an ordered multiset.It found a real bug on the first corpus run
#1939 — an arithmetic expression in a cost spec is truncated to its first operand, while the same expression in a price annotation evaluates correctly:
Consequences: a wrong cost basis, and then a false E3001 rejecting a file beancount accepts, because the weight follows the truncated cost.
Design decisions
Reference side is the beancount Python API, not
bean-query. beanquery has bugs of its own — beanquery#279 is pinned in the BQL suite for exactly that reason — and an oracle that inherits the reference implementation's query-layer bugs is not an oracle.Our side is read as JSON, not CSV. This is the whole ballgame, and it cost a full corpus run to learn. CSV renders every number through
DisplayContext, so a price written56.0763 USDin a ledger whose USD is mostly 2-decimal comes back as56.08. The first run reported 32 files diverging onprice_numberand every single one was the harness comparing beancount's stored value against rledger's rendered one. None was a defect. Generalized: a differential oracle must not read the other side through a presentation layer.Lot dates and currencies compare exactly. A lot date is either the right lot or it is not; softening that would defeat the reason the axis exists. Only the three money fields get the precision tolerance — the same one
compare()already uses for units after #1909.Two harness bugs the run exposed, both fixed here
Decimalkeeps the sign of zero and the tools don't always agree on it, so-0.00and0.00sorted differently, every row after the first signed zero was compared against the wrong partner, and one file reported five bogusnumberdifferences that were really one misalignment.Self-test
Extended to the new comparator, on synthetic rows rather than fixtures because the interesting cases are ones no ledger we have produces on demand: wrong cost, wrong lot date, one-sided price, row-count mismatch, and — the one that matters most — a difference that is representation and must not be reported, paired with one at beancount's own precision that must be.
Verified by sabotage twice. Gutting the comparator, and widening the tolerance to always agree:
Remaining findings, not yet triaged
12 files diverge. Beyond #1939 they include two known
rust_decimalceiling cases (30 significant digits — documented in CLAUDE.md as not fixable locally), a{# 2000 USD}total-cost reading where we say200and beancount says2000, and severalIncompleteInputsfixtures where beancount computes a price we leave unset.None is pinned. An untriaged finding should stay surfaced — the same rule that kept 8 files unpinned in #1927.
Refs #1902.