Repository navigation
Conversation
…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]>
📊 Benchmark Results
vs main branch (2026-06-26)
What do these numbers mean?
|
There was a problem hiding this comment.
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_exactside table keyed by roundedDecimal, plusany_overprecise()fast gate and collision fallback. - Record exact literals during parsing and consult the side-channel in precise residual computation and
Amountdisplay. - 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.
| // NOTE: side-channel clear() intentionally NOT here — this method | ||
| // re-enters for includes, which would wipe earlier files' recordings. | ||
| // (Debugging the right chokepoint.) | ||
|
|
| // 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; | ||
| } |
| /// 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`. |
| // | ||
| // 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() | ||
| { |
| #[test] | ||
| fn over_precise_literal_residual_detected_beyond_rust_decimal() { | ||
| let path = fixtures_path("over_precise_residual.beancount"); |
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
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]>
Deep review found the side channel unsound — fixed with identity-keyingA 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: rledger flagged both (Beancount flags one): the plain Fix: identity-keying
Verification
Remaining scope (documented, not a correctness gap)Only over-precise units literals are carried; cost/price/metadata over-precision rounds like plain |
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Closing: the side channel isn't the right vehicleThis PR set out to recover over-precise (>28-digit) units literals that What we learned
Why shelve rather than keep fixingFully delivering this needs exact-aware tolerance, exact-aware cost/price weights, and The pragmatic call: keep |
* 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]>
… 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.
…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.
Summary
Match-or-exceed Beancount's decimal precision at zero hot-path cost, without migrating off
rust_decimal.Decimalstaysrust_decimal::Decimal(16 bytes,Copy, untouched). rust_decimal holds ~29 significant digits; Beancount (Python's arbitrary-precisionDecimal) 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:BigDecimal, gated by a digit count so ≤29-digit literals (every real amount) cost nothing — no lock, no allocation;booking::to_big) uses the exact value when present;Amount) shows the exact value;BigDecimalresidual 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 abigdecimalhybrid). All regressed the hot paths +22–35% (e.g. validate +35%) because a hybrid enum taxes every operation of every ledger —matchdispatch plus a largerDecimalinflatingAmount/Posting— to serve a case that occurs in essentially none. The side channel inverts that: the 99.999% pay nothing.Result
validatevs mainDecimal1e-30, matches BeancountVerified end-to-end: a transaction with
1.000000000000000000000000000001 USDand-1 USD(a1e-30residual rust_decimal rounds to zero) is now flaggedTransaction does not balance: residual 1E-30 USD— byte-identical to Beancount. The existing 28-digitsome_fundcompat fixture is unaffected (already handled by the two-tier validator).Soundness
RwLock, lookups take a shared read lock.Decimalpoison the key and both fall back to plain rust_decimal behaviour: a collision can only lose the precision bonus, never produce a wrong value.clearracing a concurrent load;clear()is exposed for explicit reset.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 the1e-30imbalance.Follow-ups (documented inline)
display_contextformatter (this PR wiresAmount::Display).🤖 Generated with Claude Code