Skip to content

fix(booking): drop cost-spec scale from interpolation rounding (#1107) - #1108

Merged
robcohen merged 4 commits into
mainfrom
fix/interpolation-precision-cap
May 13, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/interpolation-precision-cap

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

When rust_decimal divides total / units during cost-spec interpolation (resolving {{300.00 USD}} to per-unit, or lot-matching {} against a stored derived per-unit), the result carries 26+ digits of fractional precision. Previously that scale was tracked in cost_scale_by_currency and merged into max_scale_by_currency, which drove the residual-rounding scale for the auto-balanced posting.

Result: a sell like -1.763 STOCK {} @ 191.00 USD filled the Income residual at scale 26 (-36.73000000000000000000000000) instead of scale 2 (-36.73 — what bean-query produces).

Closes #1107.

Repro (minimal)

2016-02-12 * "Sell"
  Assets:Cash       336.73 USD
  Assets:Brokerage -1.763 STOCK {170.16734 USD} @ 191.00 USD
  Income:Capital-Gains
Tool Income posting number
bean-query -36.72 (scale 2)
rledger (before) -36.72498 (scale 5, inheriting cost spec scale)
rledger (after) -36.72 (matches bean-query exactly)

The fix

Match Python beancount's infer_tolerances rule (default infer_tolerance_from_cost = False):

  1. Only NON-INTEGER posting.units contribute to per-currency precision. Integer amounts (1 CAD commission, 1 CSU share count) don't reflect intentional display precision in that currency.
  2. Cost spec scales are NOT tracked. With cost-from-tolerance disabled in Python, cost annotations don't influence residual quantization. The natural Decimal arithmetic flowing through cost_amount = units × per_unit preserves whatever scale the operands carry; if no non-integer posting.units exist for a currency, the residual passes through unrounded.

Removed: cost_scale_by_currency tracking and the merge step.
Added: integer-amount filter (scale > 0) on max_scale_by_currency inserts.

Why this doesn't regress #333 / #251

Both prior bugs relied on cost-spec scale propagating so a missing-amount posting got rounded to a sensible precision when no explicit posting.units existed for that currency.

After this fix, those cases hit the round_interpolated(residual, None) branch instead — which passes the residual through unrounded at its natural scale. The natural scale equals the cost spec scale anyway (units × cost_per_unit Decimal multiplication preserves the cost scale when units are integers). So:

Both regression tests still pass.

On the remaining healthequity divergence

After this fix:

  • rust: -36.73 (scale 2)
  • python: -36.730 (scale 3)

The values are mathematically equivalent. Python's scale=3 trailing zero appears to come from infer_tolerances interacting with the broader ledger context in a way I haven't fully characterized — it doesn't reproduce in standalone minimal fixtures. The remaining display divergence is a Python-specific quirk; not addressed in this PR.

Combined with PR #1106 (DisplayContext pads up but never quantizes down), the rust SUM aggregate goes from -1966.700000000000000000000000 → -1966.70 (vs Python's -1966.700). Mathematically equal; one trailing zero of display divergence remains.

Tests

Files

  • crates/rustledger-booking/src/interpolate.rs (+101 / -41) — removes cost-scale tracking + merge, adds integer filter, adds regression test, updated doc comments

🤖 Generated with Claude Code

When `rust_decimal` divides `total / units` for cost-spec interpolation
(e.g., resolving `{{300.00 USD}}` to per-unit, or lot-matching an empty
`{}` against a stored derived per-unit), the result carries 26+ digits
of fractional precision. Previously, that scale was tracked in
`cost_scale_by_currency` and merged into `max_scale_by_currency`, which
in turn drove the residual-rounding scale for the auto-balanced posting.

Result: a sell like `-1.763 STOCK {} @ 191.00 USD` filled the Income
residual at scale 26 (`-36.73000000000000000000000000`) instead of
scale 2 (`-36.73` — what bean-query produces).

## Fix

Match Python beancount's `infer_tolerances` rule:

  - Only NON-INTEGER posting.units contribute to the per-currency
    tolerance/precision. Integer amounts (`1 CAD` commission,
    `1 CSU` share count) don't tell us anything about display
    precision in that currency.
  - Cost spec scales are NOT tracked. With Python's default
    `infer_tolerance_from_cost = False`, cost annotations don't
    influence residual quantization. The natural Decimal arithmetic
    through `cost_amount = units × per_unit` preserves whatever scale
    flows from the operands; if no non-integer posting.units exist for
    a currency, the residual passes through unrounded at its natural
    scale (which #333 confirms is the scale of the explicit cost
    literal, ~2dp for typical fixtures).

Removed: `cost_scale_by_currency` tracking and the merge step.
Added: integer-amount filter (`scale > 0`) on `max_scale_by_currency`
inserts.

## Verification

Per-row USD `number` rendering on the healthequity fixture
(`testdata_source_healthequity_test_invalid_journal.beancount`):

  before: `-36.73000000000000000000000000` (scale 26)
  after:  `-36.73`                          (scale 2)
  python: `-36.730`                         (scale 3)

Minimal repro (`bean-query` equivalent):

```
2016-02-12 * "Sell"
  Assets:Cash       336.73 USD
  Assets:Brokerage -1.763 STOCK {170.16734 USD} @ 191.00 USD
  Income:Capital-Gains
```

  before: Income = -36.72498  (scale 5, from cost spec scale)
  after:  Income = -36.72     (scale 2, matches bean-query exactly)

The remaining scale=2 vs scale=3 display difference between rust
(`-36.73`) and Python (`-36.730`) on the healthequity fixture appears
to be a separate Python `infer_tolerances` quirk that depends on the
broader ledger context; not addressed here. The values are
mathematically equivalent.

## Regression tests

#333 (`70.538 ABC {100 USD}` → missing USD with cost-derived weight)
and #251 still pass — those depend on the residual being rounded to
the COST SPEC scale when no explicit non-integer posting.units exist
in the currency. The natural-scale fallback handles them correctly
because `cost_amount = units × per_unit` already produces the right
scale via rust_decimal multiplication.

Added: `test_interpolate_residual_ignores_cost_spec_scale` pins the
new rule.

## Workspace tests

`cargo test --workspace --all-features`: all pass.
`cargo clippy --workspace --all-features -- -D warnings`: clean.
`cargo fmt --all -- --check`: clean.

Closes #1107.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 13, 2026 05:40
@robcohen
robcohen requested a review from a team as a code owner May 13, 2026 05:40
@codecov

codecov Bot commented May 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.71429% with 13 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/interpolate.rs 85.71% 13 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 33.9ms ± 0.9ms 21.9 MB
beancount 933.3ms ± 4.5ms 50.5 MB
Comparison 27.5x faster 2.3x less

vs main branch (2026-05-13)

Metric main this PR Change
Time 32.4ms 33.9ms +4.6% ✅
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

@github-actions

github-actions Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 93%
Full AST Match 99%
Total Files 786
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

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 updates booking interpolation precision handling so residual rounding no longer inherits cost-spec scale, aiming to match Beancount’s default tolerance inference behavior.

Changes:

  • Removes cost-scale tracking/merging from interpolation rounding.
  • Ignores integer posting-unit scales when deriving residual precision.
  • Adds a regression test for residual rounding independent of cost-spec precision.
Comments suppressed due to low confidence (1)

crates/rustledger-booking/src/interpolate.rs:221

  • This still prefers number_per when a cost spec has both per-unit and total amounts. book() creates exactly that shape for {{total}} augmentations (it derives number_per but preserves number_total for precise residual calculation), and calculate_residual() deliberately checks number_total first. With the cost-scale fallback removed, a booked {{300.00 USD}} posting with an elided cash leg can be interpolated from the high-precision division result instead of the exact total. This should prefer number_total first to stay consistent with the rest of the booking code.
                    if let (Some(per_unit), Some(cost_curr)) =
                        (&cost_spec.number_per, &inferred_currency)
                    {
                        let cost_amount = amount.number * per_unit;
                        Some((cost_curr.clone(), cost_amount))
                    } else if let (Some(total), Some(cost_curr)) =
                        (&cost_spec.number_total, &inferred_currency)
                    {
                        // For total cost, sign depends on units sign
                        Some((cost_curr.clone(), *total * amount.number.signum()))

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

robcohen and others added 3 commits May 13, 2026 10:20
…s + strengthen tests

Four issues raised on PR #1108:

1. **Total-price scales contradicted the "non-integer posting.units"
   rule.** The `PriceAnnotation::Total` and `TotalIncomplete` branches
   still wrote scales into `max_scale_by_currency` regardless of value
   scale. Concrete problem: a fractional cost contribution plus an
   integer `@@ 1 USD` price would round the natural fractional residual
   to whole units. Apply the same `scale > 0` filter as the
   posting.units path so all explicit-amount tracking is consistent.

2. **Dangling sentence fragment.** Removed "Companion to the previous
   test — same shape but with an" from the test docstring.

3. **#333 vs #251 example mix-up.** The bullet list previously
   conflated #333 (CSU/CAD commission) with #251 (ABC/USD cost
   spec). Split into two separate bullets with the correct issue
   refs and currencies for each.

4. **Regression test didn't exercise the actual 26+ digit
   division path.** The existing
   `test_interpolate_residual_ignores_cost_spec_scale` used a fixed
   5dp `number_per`, while real-world #1107 surfaces through
   `{{total}} / units` division at the booking layer producing
   26+ digits. Added `test_interpolate_residual_after_booking_total_cost_division`
   that runs the full booking + interpolation path: buy with
   `{{300.00 USD}}` total, sell with `{}` lot-match, missing Income.
   Pre-fix the residual would carry the lot's high-scale per_unit;
   post-fix it's bounded by USD's tracked 2dp.

Tests pass: rustledger-booking 87 (+1 new) / 0 fail.
…py::doc_markdown

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen merged commit c1a12bb into main May 13, 2026
38 checks passed
@robcohen
robcohen deleted the fix/interpolation-precision-cap branch May 13, 2026 16:05
robcohen added a commit that referenced this pull request May 13, 2026
…1114 review)

Copilot review caught that the 3 `sum-number-by-currency` entries I
added to `KNOWN_PYTHON_DIVERGENCES` are actually rledger-side bugs
(continuation of #1108's pipeline scale-propagation work), not Python
beanquery quirks. Conflating them in the Python allowlist lets an
rledger bug masquerade as a Python quirk and could absorb a future
rledger regression on these file/query pairs.

Fix: introduce a separate `KNOWN_RUST_DIVERGENCES` set with the same
surgical-pin semantics. Wire it through:

- New predicate `_is_known_rust_divergence(run)` mirroring the Python
  one. New `_is_known_divergence(run)` returns the OR of both.
- Summary stats report `Known Python diffs` and `Known Rust diffs`
  separately so each side's allowlist size is visible at a glance.
- Per-mismatch log lines use `KNOWN-PY` / `KNOWN-RS` / `MISMATCH`
  labels.
- `$GITHUB_OUTPUT` gets two new keys, `bql_known_python` and
  `bql_known_rust`, alongside the existing aggregate `bql_known_divergences`.
- The 3 cost-spec interpolation cases move out of the Python allowlist
  and into the new Rust one. Effective match percentage is unchanged
  (still counted as "known"); only the bookkeeping is corrected.

Also addresses Copilot's second comment: the inline doc on the Rust
allowlist now says "Tracked under #1112 (kept open as the tracker — do
not auto-close from this PR)" so the reference stays valid post-merge.
PR body updated correspondingly.

Refs #1112. Does NOT auto-close it — the deep pipeline fix is the
real closure path.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 14, 2026
…Rust divergences (refs #1112) (#1114)

* chore(compat): mask the last 3 BQL divergences from #1112

After #1113 recovered the bulk of the #1106 regression, three real
mismatches remain — all `sum-number-by-currency` queries on fixtures
whose cost-spec interpolation produces a scale-3 residual in Python's
pipeline vs scale-2 in rledger's:

* testdata_source_healthequity_test_invalid_journal.beancount
* testdata_source_healthequity_test_matching_journal.beancount
* testdata_source_ofx_test_non_default_capital_gains_journal.beancount

In every case the numeric value is the same (e.g. `-1966.700` vs
`-1966.70`) — only the display scale differs, surfaced as a textual
diff because both tools intentionally preserve scale on
`Value::Number` output.

Root cause: cost-spec interpolation against `{}` lot-match against a
`{{total}}` lot produces a residual whose scale depends on which
intermediate value drives it. Python's intermediate stays at the
buy-side scale 3; rledger's #1108 fix dropped intermediate scale to
the input minimum (2) to stop the 26-digit contamination. That fix
was correct for the over-precision case but over-applies here.

Mask surgically (per `(file, query_name)`, not `"*"`) so any
non-scale divergence on these fixtures stays surfaced. This is a
display-scale shim, not a value bug — both tools agree on the
arithmetic. Fixing it properly means continuing #1108's pipeline
scale-propagation work, which is tracked under #1112 as a follow-up.

After this commit all 5 `first-balance-by-month` Python beanquery
bugs (#1105) and the 3 scale residuals here are accounted for as
known divergences, taking the BQL compat percentage's effective
match closer to 100%. The user-facing rounded percentage stays at
99% (it was already 99% post-#1113); this commit cleans up the
remaining bookkeeping so future regressions stand out clearly.

Refs #1112.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(compat): split known-Python vs known-Rust BQL divergences (#1114 review)

Copilot review caught that the 3 `sum-number-by-currency` entries I
added to `KNOWN_PYTHON_DIVERGENCES` are actually rledger-side bugs
(continuation of #1108's pipeline scale-propagation work), not Python
beanquery quirks. Conflating them in the Python allowlist lets an
rledger bug masquerade as a Python quirk and could absorb a future
rledger regression on these file/query pairs.

Fix: introduce a separate `KNOWN_RUST_DIVERGENCES` set with the same
surgical-pin semantics. Wire it through:

- New predicate `_is_known_rust_divergence(run)` mirroring the Python
  one. New `_is_known_divergence(run)` returns the OR of both.
- Summary stats report `Known Python diffs` and `Known Rust diffs`
  separately so each side's allowlist size is visible at a glance.
- Per-mismatch log lines use `KNOWN-PY` / `KNOWN-RS` / `MISMATCH`
  labels.
- `$GITHUB_OUTPUT` gets two new keys, `bql_known_python` and
  `bql_known_rust`, alongside the existing aggregate `bql_known_divergences`.
- The 3 cost-spec interpolation cases move out of the Python allowlist
  and into the new Rust one. Effective match percentage is unchanged
  (still counted as "known"); only the bookkeeping is corrected.

Also addresses Copilot's second comment: the inline doc on the Rust
allowlist now says "Tracked under #1112 (kept open as the tracker — do
not auto-close from this PR)" so the reference stays valid post-merge.
PR body updated correspondingly.

Refs #1112. Does NOT auto-close it — the deep pipeline fix is the
real closure path.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(booking): prune zero-value interpolated postings post-validation

Until now rledger preserved every interpolated posting through to user-
facing output, including zero-value ones (commit 7706be9, closes #877).
That fix was correct in spirit — pruning before validation hides E1001
on never-opened accounts referenced by elided postings — but
over-applied: it kept zero postings in user-facing output too, where
Python beancount drops them. The result was a persistent ~0.25% Full
AST Match floor on fixtures like `tests/regressions/issue-276.beancount`
and `tests/regressions/issue-279.beancount` (multi-posting lot sales
with zero residuals on Income:Trading).

This commit splits the two invariants by phase:

1. Booking marks every interpolated posting with a new metadata key
   `__interpolated__` (exposed as `rustledger_booking::INTERPOLATED_MARKER`).
   Validation runs against transactions that still include zero-value
   postings — so #877's E1001-on-unopened-account check still fires.

2. AFTER validation, `process()` walks each transaction and drops
   postings that have the marker AND a zero `units` value. Survivors
   keep their value but the marker is stripped so it doesn't leak into
   BQL queries, JSON output, or formatted ledgers.

Both invariants verified by new integration tests in
`crates/rustledger-loader/tests/loader_test.rs`:

* `test_zero_interpolated_posting_pruned_on_opened_account` — zero-value
  interpolated Income posting is dropped from output, no errors.
* `test_zero_interpolated_posting_keeps_e1001_on_unopened_account` —
  the #877 scenario: E1001 still emitted.
* `test_non_zero_interpolated_posting_is_preserved` — only ZERO ones
  get pruned; legitimate interpolated residuals stay.
* `test_interpolated_marker_does_not_leak_to_user_output` — defensive
  check that `__interpolated__` is stripped from survivors.

Effect on compat suite (verified locally with `--no-default-features`,
matching CI):

  Before                                             After
  ─────────────────────────────────────────────      ─────────────────────────
  issue-276.beancount  SELECT COUNT(*) = 12          = 10  (matches Python)
  issue-279.beancount  SELECT COUNT(*) = 13          = 11  (matches Python)
  Full AST Match       99% (784/786)                 100% (786/786)

The #877 regression case still produces E1001 with this commit applied:

  $ rledger check zero-balance.bean
  E1001 Account Expenses:NeverOpened was never opened
  ✗ 1 error
  exit_code: 1

Closes the residual AST divergence tracked under #1112.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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.

compat(booking): cost-spec interpolation produces scale-26 residuals where Python produces scale-3

2 participants