Skip to content

feat(core): exceed Beancount decimal precision via a zero-cost side channel - #1613

Closed
robcohen wants to merge 3 commits into
mainfrom
spike/decimal-exact-sidechannel
Closed

robcohen wants to merge 3 commits into
mainfrom
spike/decimal-exact-sidechannel

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Match-or-exceed Beancount's decimal precision at zero hot-path cost, without migrating off rust_decimal.

Decimal stays rust_decimal::Decimal (16 bytes, Copy, untouched). rust_decimal holds ~29 significant digits; Beancount (Python's arbitrary-precision Decimal) keeps more, so a literal beyond ~29 digits is rounded on parse and a balance residual that depends on those digits can read zero — the transaction looks balanced — where Beancount flags an imbalance.

The exact value of the (vanishingly rare) over-precise literal is stashed in a side table (rustledger_core::decimal_exact), consulted only in cold paths:

  • parse records the exact BigDecimal, gated by a digit count so ≤29-digit literals (every real amount) cost nothing — no lock, no allocation;
  • balance residual (booking::to_big) uses the exact value when present;
  • display (Amount) shows the exact value;
  • the validator escalates to the precise BigDecimal residual when the fast rust_decimal residual is non-zero or any over-precise literal exists (any_overprecise() is one relaxed atomic load).

Why not change the number type

Three full migrations were prototyped and benchmarked (fastnum D512/D256/D128, and a bigdecimal hybrid). All regressed the hot paths +22–35% (e.g. validate +35%) because a hybrid enum taxes every operation of every ledger — match dispatch plus a larger Decimal inflating Amount/Posting — to serve a case that occurs in essentially none. The side channel inverts that: the 99.999% pay nothing.

Result

this PR (side channel) best hybrid
validate vs main ~0% (31.2µs vs 31.1µs) +35%
precision ceiling unbounded (BigDecimal) fixed/unbounded
Decimal rust_decimal, 16 B, unchanged enum, 32–48 B
over-precise residual ✅ flags 1e-30, matches Beancount ✅

Verified end-to-end: a transaction with 1.000000000000000000000000000001 USD and -1 USD (a 1e-30 residual rust_decimal rounds to zero) is now flagged Transaction does not balance: residual 1E-30 USD — byte-identical to Beancount. The existing 28-digit some_fund compat fixture is unaffected (already handled by the two-tier validator).

Soundness

  • Thread-safe — the loader parses includes in parallel (rayon); the table is an RwLock, lookups take a shared read lock.
  • Collision-safe — two distinct literals rounding to the same Decimal poison the key and both fall back to plain rust_decimal behaviour: a collision can only lose the precision bonus, never produce a wrong value.
  • Append-only — over-precise literals are so rare that not auto-clearing is cheaper than risking a clear racing a concurrent load; clear() is exposed for explicit reset.
  • Cache-aware — a parse-cache hit would bypass the side channel, so the loader doesn't write the on-disk cache for an over-precise load (those files re-parse every time).

Tests

  • decimal_exact::side_channel_behaviour — record/skip/preserve/collision-fallback.
  • loader_test::over_precise_literal_residual_detected_beyond_rust_decimal — full parse→validate detecting the 1e-30 imbalance.

Follow-ups (documented inline)

  • Wire exact values through the aligned display_context formatter (this PR wires Amount::Display).
  • Optionally cache the exact values (rkyv) instead of skipping the cache, if over-precise files ever become common.

🤖 Generated with Claude Code

…hannel

rust_decimal (Decimal) holds ~29 significant digits; Beancount, on Python's
arbitrary-precision Decimal, keeps more. A literal beyond ~29 digits is rounded
on parse, so a balance residual that depends on those digits can read zero (the
transaction looks balanced) when Beancount flags an imbalance.

Rather than swap the number type (every hybrid measured +22-35% on the hot
paths, because the per-op enum dispatch + larger Decimal taxes ALL ledgers),
keep Decimal = rust_decimal (16 B, Copy, untouched) and stash only the rare
over-precise literal's exact value in a side table (decimal_exact), consulted
solely in cold paths:
  - parse: record the exact BigDecimal, gated by a digit count so ≤29-digit
    literals (every real amount) cost nothing;
  - balance residual: to_big() uses the exact value when present;
  - display: Amount shows the exact value;
  - validator: escalates to the precise BigDecimal residual when a fast
    rust_decimal residual is non-zero OR any over-precise literal exists
    (any_overprecise() is one relaxed atomic load).

Soundness: thread-safe (RwLock; loader parses includes in parallel), collision-
safe (distinct literals rounding to the same Decimal poison the key and fall
back to rust_decimal — never wrong), append-only (over-precise literals are
vanishingly rare). The on-disk parse cache is skipped for over-precise loads
(a cache hit would bypass parse and the side channel).

Result: full rust_decimal speed (validate ~0% vs main) AND exceeds Beancount —
verified to flag a 1e-30 residual matching Beancount that rust_decimal alone
rounds away. The some_fund 28-digit fixture is unaffected (already handled by
the two-tier validator).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner June 26, 2026 20:18
Copilot AI review requested due to automatic review settings June 26, 2026 20:18
@github-actions

github-actions Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.9ms ± 0.8ms 23.6 MB
beancount 746ms ± 5.4ms 50.7 MB
Comparison 21.4x faster 2.1x less

vs main branch (2026-06-26)

Metric main this PR Change
Time 40ms 34.9ms -12.8% 🟢
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

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

Introduces a rustledger_core::decimal_exact side-channel to preserve exact values of over-precise decimal literals (beyond rust_decimal’s ~29 digits) so cold paths (precise balance residual + display) can match Beancount’s arbitrary-precision behavior without changing the hot-path Decimal type.

Changes:

  • Add decimal_exact side table keyed by rounded Decimal, plus any_overprecise() fast gate and collision fallback.
  • Record exact literals during parsing and consult the side-channel in precise residual computation and Amount display.
  • Skip parse-cache writes when over-precise literals are present; add end-to-end fixture + validation test.

Reviewed changes

Copilot reviewed 11 out of 12 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
crates/rustledger/src/cmd/loadcache.rs Skip writing parse cache when any_overprecise() is true.
crates/rustledger-validate/src/validators/transaction.rs Gate slow BigDecimal residual pass on any_overprecise() even when fast residual is zero.
crates/rustledger-parser/src/cst/convert.rs Record over-precise decimal literals at parse time into the side-channel.
crates/rustledger-loader/tests/loader_test.rs Add an end-to-end test covering an over-precise residual.
crates/rustledger-loader/tests/fixtures/over_precise_residual.beancount New fixture containing an over-precise literal that rounds to zero residual in rust_decimal.
crates/rustledger-loader/src/lib.rs Add note about side-channel clearing (currently not performed).
crates/rustledger-core/src/lib.rs Export new decimal_exact module.
crates/rustledger-core/src/decimal_exact.rs New side-channel implementation + tests.
crates/rustledger-core/src/amount.rs Display exact BigDecimal when present for an over-precise literal.
crates/rustledger-core/Cargo.toml Add bigdecimal dependency.
crates/rustledger-booking/src/lib.rs Use exact value from side-channel in precise residual conversion path.
Cargo.lock Lockfile update for new dependency linkage.

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

Comment thread crates/rustledger-loader/src/lib.rs Outdated
Comment on lines +363 to +366
// NOTE: side-channel clear() intentionally NOT here — this method
// re-enters for includes, which would wipe earlier files' recordings.
// (Debugging the right chokepoint.)

Comment on lines +71 to +75
// Only stash if rust_decimal actually lost precision.
let rounded_big = BigDecimal::from_str(&rounded.to_string()).unwrap_or_default();
if exact == rounded_big {
return;
}
Comment on lines +55 to +63
/// Number of significant digits beyond which a literal *might* exceed
/// rust_decimal and is worth the precise round-trip check. rust_decimal holds a
/// 96-bit coefficient (~29 digits), so anything with ≤29 digits is exact.
const MAX_EXACT_DIGITS: usize = 29;

/// If `literal` carries more precision than `rounded` (its rust_decimal parse)
/// can hold, record the exact value. Cheap-gated on digit count, so the common
/// case (≤29 digits — every real amount) returns immediately with no lock, no
/// allocation, no `BigDecimal`.
Comment thread crates/rustledger/src/cmd/loadcache.rs Outdated
Comment on lines +79 to +88
//
// Also skip caching when the load contained an over-precise literal: its
// exact value lives in a parse-time side channel (`decimal_exact`), which a
// cache hit would bypass — so such (extremely rare) files re-parse every
// time, keeping the side channel correct. See `rustledger_core::decimal_exact`.
if !cache_disabled
&& result.errors.is_empty()
&& result.options.warnings.is_empty()
&& !rustledger_core::decimal_exact::any_overprecise()
{
Comment on lines +2172 to +2174
#[test]
fn over_precise_literal_residual_detected_beyond_rust_decimal() {
let path = fixtures_path("over_precise_residual.beancount");
@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 792
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 and others added 2 commits June 26, 2026 20:30
Mark decimal precision RESOLVED via the decimal_exact side channel (not a
type migration): document the two mechanisms (two-tier validator for 28-digit
residuals, side channel for >29-digit literals), why the fastnum/bigdecimal
hybrids were rejected (+22-35% hot-path tax), and the soundness properties.
Reclassify the rust_decimal ceiling from 'not fixable locally' to 'fixable —
we exceed Python' in the compatibility policy.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…leak)

A deep review found the value-keyed global side table was unsound: keyed by the
rounded Decimal value, an over-precise literal's exact value leaked onto ANY
unrelated amount equal to its rounded value, so a genuinely-balanced `1 - 1 = 0`
transaction was falsely flagged when the ledger also contained an over-precise
`1.000…001`. The global state also (a) never reset -> contaminated later loads
in long-lived embedders, (b) forced every transaction onto the slow path after
one over-precise literal, (c) keyed sub-1 literals under Decimal ZERO, (d)
recorded for every token (metadata/cost/price), and (e) mis-signed negatives.

Replace the whole approach with identity-keying. `decimal_exact` is now
STATELESS — it only detects over-precision and reconstitutes a value. The exact
literal is carried on the specific posting that owns it, in posting metadata
(`EXACT_NUMBER_META_KEY`, an internal `__`-key filtered from formatted output),
so it can't leak, it travels through booking and the rkyv parse cache for free,
and the validator escalates per-transaction (no global flag). Wired in BOTH
parser converters (red `convert.rs` and green `green.rs` — the green path is why
a txn directly after an `open` initially went undetected). `CACHE_VERSION` 12->13
so pre-fix caches (lacking the key) re-parse.

Regression test pins the no-leak property (exactly one imbalance in a fixture
mixing an over-precise txn with a plain balanced one). All 3789 tests pass; hot
path unchanged (Decimal is still rust_decimal); the per-txn probe short-circuits
on all_zero and skips empty metadata.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@robcohen

Copy link
Copy Markdown
Member Author

Deep review found the side channel unsound — fixed with identity-keying

A high-effort architecture/correctness review (manual + the multi-agent workflow, which agreed) found the original value-keyed global side table was unsound. Confirmed, with a reproducer:

over-precise  Assets:A 1.000…001 USD   (rounds to 1)  → SHOULD be flagged
plain         Assets:C 1 USD / Assets:D -1 USD         → genuinely balanced

rledger flagged both (Beancount flags one): the plain 1 absorbed the exact value 1.000…001 keyed under 1. Using the feature corrupted the rest of the ledger. Related defects from the same two root causes (value-keying + global state): sign bug (negatives keyed positive), sub-1 literals keyed under Decimal 0 (corrupting zero amounts), recording on every token (metadata/cost/price), never-reset global flag (cross-load contamination + permanent slow-path), and a stale-cache bypass.

Fix: identity-keying

  • decimal_exact is now stateless — it only detects over-precision and reconstitutes a value.
  • The exact literal is carried on the specific posting that owns it, in posting metadata (__exact_number__, an internal key filtered from output) — so it can't leak, it rides through booking and the rkyv cache for free, and the validator escalates per-transaction (no global flag).
  • Wired in both parser converters — convert.rs (red) and green.rs (green). The green path was why a txn placed directly after an open (no blank line) initially went undetected.
  • CACHE_VERSION 12→13 so pre-fix caches re-parse.

Verification

  • Reproducer now flags exactly one imbalance; pinned by a regression test (over_precise_literal_residual_detected_without_value_leak) in a fixture mixing an over-precise txn with a plain balanced one.
  • Positive / negative / green-path / red-path all detect; 3789 tests pass.
  • Hot path unchanged (Decimal is still rust_decimal); the per-txn escalation probe short-circuits on all_zero and skips empty-metadata postings.

Remaining scope (documented, not a correctness gap)

Only over-precise units literals are carried; cost/price/metadata over-precision rounds like plain rust_decimal — sound (never wrong), just not extended to exceed Beancount there.

@codecov

codecov Bot commented Jun 26, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.74074% with 10 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/green.rs 66.66% 8 Missing ⚠️
crates/rustledger-core/src/decimal_exact.rs 97.67% 1 Missing ⚠️
crates/rustledger-core/src/format/directives.rs 66.66% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@robcohen

Copy link
Copy Markdown
Member Author

Closing: the side channel isn't the right vehicle

This PR set out to recover over-precise (>28-digit) units literals that rust_decimal rounds away, so a balance residual that depends on those digits matches Beancount. Two deep architecture/correctness reviews later, the evidence is consistent: even done correctly, the side channel doesn't deliver enough to justify its surface area.

What we learned

  • Review ci: add merge_group trigger for GitHub Merge Queue #1 found the original value-keyed global table was unsound — an over-precise literal's exact value leaked onto any unrelated amount equal to its rounded value, falsely flagging genuinely-balanced transactions. Fixed with identity-keying (per-posting metadata, stateless helper). The leak is gone and stays gone.
  • Review chore: update dependencies and fix deny.toml for cargo-deny v0.18 #2 (post-fix) found the design still falls short, decisively:
    • 🔴 Tolerance gap (defeats the feature). The escalated exact residual is still compared against a tolerance derived from the rounded scale. For any over-precise literal that rounds to a value with a multi-digit integer part, the tolerance is too coarse and masks the residual. 100.000…001 − 100 → exact residual 1e-30 → rledger: balanced; Beancount: imbalanced. The shipped fixture only passes because its scale-28 tolerance underflows to 0 in rust_decimal. The side channel does nothing in most of the regime it exists for.
    • 🟠 Egress leak. __exact_number__ leaks into BQL meta() results and wasm JSON — putting internal data in the shared user-facing meta map means every egress needs a filter, and only the text formatter had one.
    • 🟠 Cost/price uncovered. Residual is exact-aware only in the simple-units branch; cost/price postings and cost/price literals drop precision.
    • 🟡 Sign bug in overprecise_literal (negative >28-char literals that fit are falsely escalated), plus doc/alloc/dup cleanups.

Why shelve rather than keep fixing

Fully delivering this needs exact-aware tolerance, exact-aware cost/price weights, and __-filtering at every egress — substantial, fragile plumbing — for literals beyond ~28 digits that do not occur in real ledgers. Meanwhile main's two-tier validator (calculate_residual → calculate_residual_precise) already catches every realistic (≤28–29 digit) over-precision case, including the original #1240 some_fund residual, at full rust_decimal hot-path speed.

The pragmatic call: keep Decimal = rust_decimal + main's two-tier validator; do not merge the side channel. Closing. The branch stays for reference; the identity-keying approach is the correct shape if unbounded-precision balance ever becomes a real requirement (it would still need the tolerance + cost/price + egress work above).

@robcohen robcohen closed this Jun 27, 2026
robcohen added a commit that referenced this pull request Jun 27, 2026
* docs: correct stale Decimal Precision section (#1240 resolved)

CLAUDE.md still described rust_decimal's 28-digit ceiling as an open compat
failure with a TODO to migrate to bigdecimal. That's stale: `main` already
resolves #1240 with a two-tier balance validator (calculate_residual ->
calculate_residual_precise), and `rledger check` now reports the some_fund
2.1875E-25 USD residual. Decimal stays rust_decimal.

Rewrite the section to describe the two-tier validator, move the over-precise
residual case into the 'Fixable' compat bucket, narrow the 'Not fixable' note to
over-precise *literals* (a non-issue, no real ledger has them), and record that
the literal-recovery side channel was prototyped and rejected (PR #1613) so it
isn't re-attempted.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs: address review — correct validator crate + align ceiling wording

Per Copilot review: the two-tier escalation logic lives in
rustledger-validate (validate_transaction_balance), not rustledger-booking
(which only provides calculate_residual / calculate_residual_precise); and align
the '28-digit ceiling' wording with the '~28-29 significant digits' phrasing
used in the section below.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
@robcohen
robcohen deleted the spike/decimal-exact-sidechannel branch June 27, 2026 14:55
robcohen added a commit that referenced this pull request Aug 3, 2026
… 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.
robcohen added a commit that referenced this pull request Aug 3, 2026
…cle (#1940)

* feat(compat): compare per-posting cost, price and lot date in the oracle

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.

* docs(compat): _dec is format-neutral now, say so

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.

* feat(compat): add a pin registry for the per-posting axis, and triage 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.

* fix(compat): make the posting sort token lossless and context-free

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