Skip to content

fix(fuzz): let the booking fuzzer reach the overflows it exists to find - #2344

Merged
robcohen merged 5 commits into
mainfrom
fix/fuzz-booking-reaches-extremes
Sep 17, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/fuzz-booking-reaches-extremes

Conversation

@robcohen

@robcohen robcohen commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

Closes #2340.

The target could not reach what it was named for

fuzz_booking says it looks for "panics, overflows, or other crashes in the booking and interpolation logic". Every money value came from i32 cents — totals capped near 2.1e7 — and every unit count was a u16, so fractional units were unreachable outright. The panic in #2327 needs a quotient above 7.9e28: roughly 22 orders of magnitude beyond the target's input space.

Values now come from Decimal's actual domain: about one draw in eight from the edges (MAX, its negation, the smallest magnitude, the integers that divide badly), one in eight from a full-width mantissa at any scale, and the rest ordinary money — a corpus of nothing but extremes explores lot matching and interpolation badly. Units are a Decimal, so fractional lots like 1.763 VIIIX get generated at all.

The harness multiplication is checked, which matters more than it looks: widening the generator without it would panic in the harness and report a false finding against the engine.

It works, and it found a bug in the fix it was written to validate

With #2327's checked_div reverted, the widened generator finds Division overflowed minutes into its first run. Months of nightly runs of the old one never did.

Then, with the fix in place, it still crashed — at interpolate.rs:1551, solving a cost from a residual:

thread '<unnamed>' panicked at rust_decimal/src/arithmetic_impls.rs:218:
Division overflowed
   at crates/rustledger-booking/src/interpolate.rs:1551
   at crates/rustledger-booking/src/book.rs:1499

#2327 claimed it had fixed every per-unit division. That claim was wrong. Its sweep grepped book.rs and cost.rs for / units...abs(); this site is in a third file, so the pattern could not have matched it. The claim was as wide as one grep, not as wide as the engine.

Auditing properly turned up six more

site what was unchecked
booking/src/lib.rs normalizing an @@ price to per-unit
core/src/implicit_prices.rs ×3 the @@ annotation, a {{total}} cost, and a compound cost whose addition can leave the range even when its quotient fits
core/src/inventory/booking.rs #1863 made the multiplication checked and left the division beside it bare — the same miss, twice
book.rs capital gains ×2 two multiplications, which a division-only grep was structurally incapable of finding

Each takes the failure its own contract already uses: None where the caller reads an Option and already falls through on zero units; BookingError::Overflow where one is returned; InterpolationError::Unrepresentable for the interpolation path. checked_div also covers a zero divisor, which panics too.

Then it found a third one, and checked arithmetic was not the answer

Same generator, next run:

BookedCost invariant violated: per_unit (0) * |units|
(79228162514264337593543950335) = 0 != total (-2.55)
  at crates/rustledger-core/src/cost.rs:494
  at crates/rustledger-booking/src/interpolate.rs:1574

This one is not an unchecked division. It is a checked division that
succeeded.
-2.55 / 7.9e28 is about -3.2e-29, below rust_decimal's
1e-28 minimum, so the quotient underflows: checked_div sees no overflow
and returns Some(0). Zero cannot reproduce a total of -2.55, so
BookedCost::new's debug assert fires.

Checked arithmetic guards the top of Decimal's range. Nothing guarded the
bottom, and the sweep above was framed entirely around the top — which is the
same shape of mistake as #2327's grep, one layer up: a fix as wide as its
stated failure mode rather than as wide as the operation.

The constructor already prescribes the remedy in its own docs — "trust-boundary
callers should use try_new for runtime validation in release too". The engine
is such a caller: the per-unit it passes is derived, not supplied. All four
engine sites now go through try_new:

site path rejection reported as
interpolate.rs:1574 cost solved from a residual InterpolationError::Unrepresentable
book.rs augmentation {{total}} on a new lot BookingError::Overflow
book.rs reduction filter {{total}} turned into a lot-match filter BookingError::Overflow
book.rs compound {per # total} combined BookingError::Overflow

The interpolation site computes the BookedCost before touching the
posting, so a rejected transaction still reads exactly as its author wrote it —
the property Rollback exists for, and one run_booking depends on because it
sets failed transactions aside rather than discarding them.

Two tests, each verified to fail with the change reverted and to print the
exact assert above:

  • an_inferred_cost_that_underflows_to_zero_is_reported_not_asserted
  • an_augmenting_total_cost_that_underflows_to_zero_is_reported

The crash input is kept at
fuzz/regressions/fuzz_booking/booked-cost-underflow-2344, replayed under
cargo fuzz both ways.

Also: the compat harness stopped seeing booking errors at all

Unrelated to the fuzzer, and currently reddening Compatibility on every PR.
Giving booking errors a source span (#2342) moved them onto miette's graphical
renderer, which prints the code bare on its own line:

BOOK

  x No matching lot for SHARES in Assets:Shares
   ,-[ledger.beancount:8:1]

scripts/compat-values.py matched \b[A-Z]\d{4}\b and
(?:error|warning)\[([A-Z][A-Z_]+)\]. A bare BOOK matches neither, so
every booking diagnostic became invisible to the harness. Numbered codes
survived by luck: E2001 alone on a line still matches the first pattern,
which is why only the booking family broke.

The extractor now also collects that shape, anchored on the x <message>
marker that follows it rather than on "a line that looks shouty", so a bare
uppercase word elsewhere in the output cannot be mistaken for a code. Measured
both ways on a file that fails booking: set() before, {'BOOK'} after.
--self-test passes.

A deep review of this PR found two more things, one of them not mine

The rollback erased a cost the author wrote. Rollback::touch clones the
posting as it finds it and the first touch for an index wins. The inferred-cost
write called it AFTER .cost.take() had emptied the posting, so the snapshot
recorded a posting with no cost and restore handed back 10 SHARES where the
author wrote 10 SHARES {EUR}. Failed transactions are not discarded --
run_booking sets them aside and finalize merges them back -- so that
erasure is displayed. Measured: posting 0 went in as
Some(CostSpec { currency: EUR }) and came back None.

It is the invariant
a_failure_after_a_write_leaves_the_transaction_untouched exists for, on a
path that test does not reach, and the underflow rejection added above is what
makes it easy to trigger. One line, plus a test.

The compat matcher was anchored on one miette theme. The bare-code shape
appears under GraphicalTheme::none(), which the CLI picks when stdout is not
a terminal -- always true under the harness. Accepting the unicode marker too
costs nothing and stops a theme change from silently blinding the harness the
way the original two patterns did.

And one finding held back deliberately: #2345

The generator has a second defect. Its "anywhere in the domain" arm hands a raw
uniform i128 to Decimal::try_from_i128_with_scale, which is representable
with probability about 2^-31. Measured at 0 of 200,000 draws -- the arm
produced Decimal::ZERO every single time, so one draw in eight was dead and
the "whole domain" claim above was only ever true of the edge arm.

Masking the mantissa to the 96 bits Decimal has makes it work, and it finds a
live release-mode panic within 150 seconds: add_headroom_for tests the signed
net for a currency, so two opposite cost-bearing lots net to zero and a lot
sitting at Decimal::MAX is invisible to rollback_needed. apply's
assert! -- a real assert, not a debug one -- then fires. Verified directly
against Inventory, no booking engine involved.

That is a separate bug in separate code, and landing the mask here would take
this PR red for it. Both are filed as #2345 with the crash input.

A second review pass, over this PR's own diff

The new tests matched a word in the message. format!("{err}").contains("range")
is the guard shape CLAUDE.md singles out: satisfied by any error that happens
to use the word. Now matched on the variant,
BookingError::Inventory(e) if e.error is Overflow. Verified the tightening
bites by pointing it at MergeMismatch -- all three then fail.

average_cost_from_positions disagreed with itself. The new error path read
cost_currency.clone().unwrap_or_default() while the line below it read
cost_currency.unwrap(). The same impossible state would panic on one path and
report an overflow in the EMPTY currency on the other, printing a blank where
the commodity belongs. Bound once instead.

One finding raised and filed separately, as #2346 -- not addressed here. The @@ pro-rata gain is
computed multiply-first, which is correct and deliberate, but total x units
can leave the range while total x units / total_units fits. Until this PR
that site was a bare * and PANICKED, so reporting it is strictly better and
this PR should not wait for it -- but an error is still the wrong answer for a
figure that is perfectly representable. A divide-first fallback fixes it
without touching the exactness property.

Kept

The 19-byte crash input lives at fuzz/regressions/fuzz_booking/interpolated-cost-division-overflow-2340, which is where CLAUDE.md says crash inputs belong — beside their fix, so losing the corpus branch cannot resurrect a closed bug. A crate-level test pins the same case without the fuzzer; reverting the fix makes it fail with Division overflowed.

Verification

  • Two-sided on the fuzzer, for both crash inputs: each finds its panic when the fix is reverted and passes when it is present.
  • Sabotage on all three new tests: reverting the change makes each fail with the panic it was written for.
  • One vacuous result caught and redone: the first replay of the underflow input used a plain cargo build --release, which compiles the debug_assert out. It "passed" without the fix. Re-run through cargo fuzz, which sets -C debug-assertions, it panics.
  • rustledger-core 567, rustledger-booking 207, rustledger-loader 230, rustledger-query 720, plus rustledger. Clippy and fmt clean at 1.98.1.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

The target says it looks for "panics, overflows, or other crashes in the
booking and interpolation logic" and could not reach an overflow. Every money
value came from `i32` cents, so totals stopped at about 2.1e7; every unit count
was a `u16`, so fractional units were unreachable outright. The panic in #2327
needs a quotient above 7.9e28 -- some 22 orders of magnitude further out
(#2340).

Values are drawn from `Decimal`'s actual domain now: roughly one draw in eight
from the edges (`MAX`, its negation, the smallest magnitude, the integers that
divide badly), one in eight from a full-width mantissa at any scale, and the
rest ordinary money, because a corpus of nothing but extremes explores lot
matching and interpolation badly. Units are a `Decimal`, so fractional lots
like `1.763 VIIIX` are generated at all. The harness multiplication is checked:
widening the generator without that would panic in the HARNESS and report a
false finding against the engine, which is this target's worst outcome.

It works. With #2327's `checked_div` reverted, the widened generator finds
`Division overflowed` minutes into its first run, where months of nightly runs
of the old one never did.

AND IT IMMEDIATELY FOUND A SEVENTH SITE #2327 MISSED. `interpolate.rs:1551`
solves a cost from a residual and divides bare. That PR claimed to have fixed
every per-unit division; its sweep grepped `book.rs` and `cost.rs` for
`/ units...abs()`, and this lives in a third file, so the pattern could not have
matched it. The claim was as wide as one grep, not as wide as the engine.

Auditing properly -- every division AND multiplication on user-supplied
decimals across both crates -- turned up six more:

- `booking/src/lib.rs`, normalizing an `@@` price to per-unit;
- `core/src/implicit_prices.rs`, three: the `@@` annotation, a `{{total}}` cost,
  and a compound cost whose ADDITION can leave the range even when its quotient
  fits;
- `core/src/inventory/booking.rs`, where #1863 made the multiplication checked
  and left the division beside it bare -- the same miss, twice;
- `book.rs`'s capital-gains block, two multiplications my division-only grep
  never looked at.

Each takes the failure its own contract already uses: `None` where the caller
reads an `Option` and already falls through on zero units, `BookingError::
Overflow` where one is returned, `InterpolationError::Unrepresentable` for the
interpolation path.

The crash input is kept at
`fuzz/regressions/fuzz_booking/interpolated-cost-division-overflow-2340`, which
is where CLAUDE.md says crash inputs belong -- beside their fix, so losing the
corpus branch cannot resurrect a closed bug. A crate-level test pins the same
case without needing the fuzzer; reverting the fix makes it fail with
`Division overflowed`.

core 567, booking 205, loader 230 and query 720 tests pass.

Closes #2340

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner September 17, 2026 16:32
@codecov

codecov Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.53488% with 18 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/book.rs 91.39% 8 Missing ⚠️
crates/rustledger-core/src/implicit_prices.rs 45.45% 6 Missing ⚠️
crates/rustledger-core/src/inventory/booking.rs 42.85% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 29.1ms ± 0.7ms 394.5ms ± 4.0ms 13.6x 51.1 MB / 50.1 MB
investment 42.4ms ± 1.3ms 1500.4ms ± 5.1ms 35.4x 57.0 MB / 58.0 MB
fifo 40.7ms ± 1.4ms 8273.8ms ± 205.0ms 203.4x 57.2 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 28.2ms ± 1.2ms 29.1ms ± 0.7ms +3.1% ✅ within noise 51.1 MB → 51.1 MB (-0.1%)
investment 44.3ms ± 7.5ms 42.4ms ± 1.3ms -4.2% ✅ within noise 57.2 MB → 57.0 MB (-0.3%)
fifo 42.0ms ± 5.8ms 40.7ms ± 1.4ms -3.2% ✅ within noise 57.0 MB → 57.2 MB (+0.3%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.6ms, investment 3.4ms, fifo 2.7ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

… sites

The widened fuzzer (#2340) found a second failure the same afternoon, and it
is not another unchecked division. It is the checked division being
insufficient.

    BookedCost invariant violated: per_unit (0) * |units|
    (79228162514264337593543950335) = 0 != total (-2.55)

`total / |units|` with units at Decimal::MAX gives a quotient of about
-3.2e-29, below rust_decimal's 1e-28 minimum. It UNDERFLOWS. checked_div
reports no overflow and hands back Some(0), and zero cannot reproduce a total
of -2.55, so BookedCost::new's debug assert fires. Checked arithmetic guards
the top of the range; nothing guarded the bottom.

The constructor already documents the answer: "trust-boundary callers should
use try_new for runtime validation in release too". The engine is such a
caller, because the per-unit it passes is derived rather than supplied. All
four sites now construct through try_new and map the rejection to the error
each path already reports (Unrepresentable for interpolation, Overflow for
booking). The interpolation site computes the BookedCost before touching the
posting, so a rejected transaction still reads exactly as its author wrote it.

Two tests, each verified to fail with the change reverted and to report the
exact panic above:

  an_inferred_cost_that_underflows_to_zero_is_reported_not_asserted
  an_augmenting_total_cost_that_underflows_to_zero_is_reported

The crash input is kept in tree as
fuzz/regressions/fuzz_booking/booked-cost-underflow-2344, replayed under
cargo fuzz both ways: it panics without the fix, passes with it.

Also fixes scripts/compat-values.py, which reds Compatibility on every PR
right now. Giving booking errors a source span (#2342) moved them onto the
graphical renderer, which prints the code bare on its own line instead of
error[BOOK]. Neither of the script's two patterns matches a bare BOOK, so
every booking diagnostic became invisible to the harness. Numbered codes
survived by luck, since E2001 alone on a line still matches the first
pattern.

Part of #2340. The PR body carries the closing keyword; this commit does not
add a second one.
The previous commit converted four construction sites and tested two of them.
The reduction filter and the compound arm were left defensive, which is the
half-measure this PR already criticized #2327 for: a fix as wide as the
operation, verified only as wide as the reproducer.

Both are reachable without any inventory state, because both derive the
per-unit BEFORE a lot is looked at:

  {0 # 2.55 USD} over Decimal::MAX units  -> compound: |units|*0 + 2.55, / |units|
  -Decimal::MAX SHARES {{2.55 USD}}       -> the sale's lot-match filter

All four tests were run with the conversion reverted and all four fail with
the same assert, so none of them is decoration.
Found reviewing this PR's own change, in the code beside it.

`Rollback::touch` clones the posting as it finds it, and the first touch for
an index wins. The inferred-cost write called it AFTER `.cost.take()` had
already emptied the posting, so the snapshot recorded a posting with no cost
and `restore` handed back `10 SHARES` where the author wrote
`10 SHARES {EUR}`.

Failed transactions are not discarded. `run_booking` sets them aside and
`finalize` merges them back into `Ledger.directives`, so the erased cost is
shown to the user as if they had written it that way. That is the exact
failure mode `a_failure_after_a_write_leaves_the_transaction_untouched`
exists to prevent; it just never reached this path.

Reachable whenever one inferred cost succeeds and a later one fails, which
the underflow rejection added earlier in this PR makes easy to demonstrate:

  Assets:Shares   10 SHARES {EUR}      <- inferred fine, then erased
  Assets:CashE  -900 EUR
  Assets:Bonds    <Decimal::MAX> BONDS {USD}
  Assets:CashU   -2.55 USD             <- underflows, whole txn rolls back

Measured before the fix: posting 0 went in as `Some(CostSpec { currency: EUR
})` and came back `None`.

Also hardens scripts/compat-values.py against the same class of coupling it
was just fixed for: the bare-code matcher anchors on miette's `x <message>`
marker, which is the ASCII theme's spelling. The CLI picks that theme when
stdout is not a terminal, which is always true under this harness, but
accepting the unicode marker too costs nothing and keeps a theme change from
silently blinding the harness a second time.
@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

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

Second review pass over this PR's own diff.

The three underflow tests matched `format!("{err}").contains("range")`. That
is the guard shape CLAUDE.md singles out: a substring is satisfied by any
error that happens to use the word, so the test cannot tell an overflow from
an unrelated failure whose message also says "range". Now matched on
`BookingError::Inventory(e) if e.error is Overflow`.

Checked that the tightening bites rather than assuming it: pointing the
matcher at `MergeMismatch` instead fails all three.

Two more from the same pass, both in code this PR already touched:

`average_cost_from_positions` read `cost_currency.clone().unwrap_or_default()`
in the new error path and `cost_currency.unwrap()` on the line below it. The
same impossible state would panic on one path and report an overflow in the
EMPTY currency on the other, printing a message with a blank where the
commodity belongs. Bound once instead, so both paths rest on the guard that
actually settles it.

`extract_per_unit_price` grew a second comment saying what the comment under
it already said. Merged.
@robcohen
robcohen merged commit 9699b3e into main Sep 17, 2026
70 of 71 checks passed
@robcohen
robcohen deleted the fix/fuzz-booking-reaches-extremes branch September 17, 2026 18:37
robcohen added a commit that referenced this pull request Sep 18, 2026
Review pass over this PR's own diff, which shipped a wrong-answer bug.

The fallback for an overflowing product divided first. Every reordering
underflows on some input, and an underflow does not fail -- it returns a
number:

    prorate(2, MAX, MAX)   -> Some(0)    true share: 2

`2 / MAX` is about 2.5e-29, below Decimal's 1e-28 floor, so it rounds to zero,
and zero times MAX is zero. Not an error: a fabricated share presented as
valid, which the function's own doc said it never produces. The code this PR
replaced returned an honest error for that input, so for it the PR made
things worse. Dividing the other operand first fails the same way on
`prorate(MAX, 2, MAX)`.

It is the underflow class #2344 fixed -- a checked operation that SUCCEEDS and
hands back a zero that cannot be right -- reintroduced one PR later, and then
promoted into a shared function so that both callers inherited it. The budget
crate's original inline copy had carried it all along.

Choosing the larger numerator avoids the outright zero (both quotients cannot
underflow while the product overflows), but still keeps as few as ~14
significant digits in the worst case. So the slow path now forms the product
in BigDecimal, divides there, and rounds once into Decimal: correctly rounded,
every digit kept. It runs only when the fast path could not.

That needs the precise tier, which lives in rustledger-booking, not core. So
`prorate` moves there; rustledger-core is now untouched by this PR. Nothing
breaks: `prorate` was added by this PR and never released, and the budget
crate already depends on booking.

The first version also invented scale: `500000000000000.00`, two trailing
zeros a capital-gains report would print. The tests could not see either
problem, because `Decimal` equality ignores scale and none of them probed the
bottom of the range. Both are now pinned, and reinstating the old
divide-first fallback fails exactly those two tests.

`to_plain_string`, not `Display`, for the conversion: `Display` emits
exponent form (`5e+20`), which `Decimal::from_str` accepts today only by
coincidence.
robcohen added a commit that referenced this pull request Sep 18, 2026
…ver refused (#2348)

* fix(core): share one prorate, so a representable split is never refused

The per-lot share of a `@@` total price was computed multiply-before-divide.
That order is deliberate and correct -- it is what makes a set of shares cover
the whole sum back to exactly the total, and it is what beancount does -- but
the intermediate product leaves `Decimal`'s range long before the answer does.
A total price of 5e14 over 1e15 of 1e15 units has an ordinary share of 5e14
and a product of 5e29, so the whole reduction was reported unrepresentable.

Until #2344 that site was a bare `*` and PANICKED, so an error was already an
improvement. It is still the wrong answer for a figure this ordinary.

Sweeping for the pattern rather than fixing the one site the issue named
turned up that `rustledger-budget` had already solved it, independently, with
the same fallback and the same reasoning in its comment ("a slightly inexact
number beats an abort"). Two derivations of one rule with nothing asserting
they agree is the anti-pattern CLAUDE.md's canonical-function discipline is
about, so this adds `rustledger_core::prorate` and points both at it:

    value.checked_mul(num).and_then(|p| p.checked_div(den))
        .or_else(|| value.checked_div(den)?.checked_mul(num))

Exact where `Decimal` allows, approximate where it does not, `None` where
neither order can represent the result. Nothing clamps or saturates: a
fabricated share presented as the user's own money is the failure this area
exists to avoid.

Tests, each verified two-sided:

- `prorate(1, 3, 3)` is exactly 1. Divide-first gives 0.999...9, so this test
  fails if the primary order is ever dropped -- the exactness property has a
  guard rather than a comment.
- The 5e14 case asserts its own premise (the product really does overflow)
  before asserting the share is computed.
- An engine-level test books a whole-holding sale at those magnitudes and
  checks the gain. Removing the fallback makes it fail with the spurious
  `Overflow` this fixes.

`rustledger-budget`'s 58 tests pass unchanged against the shared function.

Closes #2346

* fix(booking): round prorate once, exactly, instead of dividing first

Review pass over this PR's own diff, which shipped a wrong-answer bug.

The fallback for an overflowing product divided first. Every reordering
underflows on some input, and an underflow does not fail -- it returns a
number:

    prorate(2, MAX, MAX)   -> Some(0)    true share: 2

`2 / MAX` is about 2.5e-29, below Decimal's 1e-28 floor, so it rounds to zero,
and zero times MAX is zero. Not an error: a fabricated share presented as
valid, which the function's own doc said it never produces. The code this PR
replaced returned an honest error for that input, so for it the PR made
things worse. Dividing the other operand first fails the same way on
`prorate(MAX, 2, MAX)`.

It is the underflow class #2344 fixed -- a checked operation that SUCCEEDS and
hands back a zero that cannot be right -- reintroduced one PR later, and then
promoted into a shared function so that both callers inherited it. The budget
crate's original inline copy had carried it all along.

Choosing the larger numerator avoids the outright zero (both quotients cannot
underflow while the product overflows), but still keeps as few as ~14
significant digits in the worst case. So the slow path now forms the product
in BigDecimal, divides there, and rounds once into Decimal: correctly rounded,
every digit kept. It runs only when the fast path could not.

That needs the precise tier, which lives in rustledger-booking, not core. So
`prorate` moves there; rustledger-core is now untouched by this PR. Nothing
breaks: `prorate` was added by this PR and never released, and the budget
crate already depends on booking.

The first version also invented scale: `500000000000000.00`, two trailing
zeros a capital-gains report would print. The tests could not see either
problem, because `Decimal` equality ignores scale and none of them probed the
bottom of the range. Both are now pinned, and reinstating the old
divide-first fallback fails exactly those two tests.

`to_plain_string`, not `Display`, for the conversion: `Display` emits
exponent form (`5e+20`), which `Decimal::from_str` accepts today only by
coincidence.

* docs(booking): stop claiming prorate fixed invented scale everywhere

Second review pass. The previous commit said the first version "invented
scale" and that this was fixed. Only half true, and the half matters:

- The SLOW path now gives minimal scale (`500000000000000`, not `.00`).
- The FAST path -- every ordinary share -- is unchanged, and follows
  rust_decimal, not Python's ideal exponent: `900 * 1 / 1000` gives `0.90`
  where Python gives `0.9`, and `10 * 3 / 4` gives `7.50` against `7.5`.

That fast-path divergence predates `prorate`; it is what both callers already
computed. Fixing it means calling `checked_div_python_scale`, which changes
capgains CSV/JSON output for ordinary ledgers, so it is filed separately as
#2349 rather than folded into an overflow fix.

The test comment also claimed "a capital-gains report would print" the extra
zeros without anyone having looked. Checked: CSV and JSON emit the `Decimal`
verbatim and would; TEXT renders through `DisplayContext` at display precision
and would not.

Also documents the tie rule: the slow path rounds ties away from zero (what
`Decimal::from_str` does) while rust_decimal arithmetic breaks ties to even.
They can disagree only on an exact tie at the 29th significant digit.
robcohen added a commit that referenced this pull request Sep 19, 2026
Ninth review pass, on the one thing no earlier pass looked at: the user-facing
record. CHANGELOG.md is hand-written and every user-visible PR adds its own
entry -- #2342, #2331, #2306, #2326 and #2322 all did. This PR changes exported
strings, booking results and speed, and added none.

Three Fixed entries and one Performance entry, in the file's style:

- a tiny `@@` share is no longer booked as zero;
- an uneven `@@` split keeps Python's scale in the capgains exports, with the
  exact surfaces named -- CSV and JSON change, TEXT and the budget report do
  not, `session.budget` does -- and the two pinned deviations stated;
- a `@@` share is computed when its intermediate product overflows, which is
  #2348's work: this PR rewrites the function that PR introduced, and an
  entry for one without the other would not read.

Output changes go under Fixed, not Breaking, following the precedent of the
`--format json` column change in #2342. The entry says in bold that exported
strings change and values do not.

The Performance entry is a cost disclosure, not an improvement. Against the
last release the net effect on the worst case is 4.8% slower; the string-free
conversion only recovered most of a regression this same PR introduced, and
the first draft of the entry read as a speedup. It also implied the #1240
precise tier got faster, which was never measured; it now says only that the
tier shares the conversion.

Not addressed here: #2344 and #2347, both merged, also shipped user-visible
fixes without entries -- #2347 fixed a release-mode abort.
robcohen added a commit that referenced this pull request Sep 19, 2026
…hares (#2350)

* fix(booking): give prorate's shares Python's ideal-exponent scale

`rust_decimal`'s division keeps a non-minimal scale for an exact quotient:
`900 / 1000` is `0.90`. Python's `decimal` reduces to the ideal exponent and
gives `0.9`. So an uneven `@@` split read `0.90` and `899.10` in the capgains
CSV and JSON exports, trailing zeros no input carried. The summary, which sums
the shares, read `900.00`.

The fast path now divides with `checked_div_python_scale`, which core already
has and BQL already uses. The product's scale is the sum of its factors', so
this lands on Python's scale for the whole of `value * num / den`. Measured
against Python on the stripping cases (`0.9`, `7.5`) and on the cases that
must NOT change (`100.00` keeps its places, `1.00` stays `1.00`).

The exact slow path is left alone, deliberately. The first draft of this fix
extracted a scale-padding helper into core and applied it there too, on the
assumption that `BigDecimal` would not produce Python's scale. It does:
measured on nine cases covering both padding and stripping, all agree. The
helper was a no-op on every exact case, and worse than a no-op on an inexact
one, where normalizing strips trailing digits Python keeps. It was caught
because sabotaging it changed nothing, and it is gone. Core is untouched.

User-visible, and only in the verbatim exports:

    before   0.90,  899.10,  summary 900.00
    after    0.9,   899.1,   summary 900.0     (= Python's 0.9 + 899.1)

TEXT renders through DisplayContext and is unchanged. The budget report is the
other caller and changes the same way, in its CSV/JSON and in
`session.budget`'s decimal strings. rustfava is unaffected: it computes budgets
in its own Python and never calls `session.budget`, and capgains is not exposed
through the FFI at all.

No test pinned any of this, which is why the change broke nothing. The capgains
CLI fixture splits `@@ 700` into `350 + 350`, an even split with no fraction to
show. Added:

- a prorate test over Python's measured outputs, including the cases that
  must keep their scale, failing if the fast path goes back to `checked_div`;
- a slow-path test that pins `BigDecimal`'s scale behavior, since it is now a
  property of a dependency; it fails if the result is normalized;
- a CLI test with an uneven split, asserting exact CSV rows and JSON fields.
  Confirmed it runs rather than skips (`require_rledger!` skips silently), and
  that it fails against a genuinely rebuilt binary with the old division.

Closes #2349

* docs(booking): scope prorate's Python-scale claim to exact quotients

Review pass. The doc, commit and PR said an ideal-exponent division makes a
share land on Python's scale "for the whole of value * num / den". Measured,
that holds only for an EXACT quotient.

For an inexact one Python rounds to its 28-significant-digit context and
rust_decimal keeps up to 29:

    100 / 3    Python 33.33333333333333333333333333
               rledger 33.333333333333333333333333333

Identical before and after this PR, so no regression -- but a divergence the
PR's own wording denied. It is more precision rather than less, so it stays,
and per CLAUDE.md's checklist for a deliberate Python deviation it is now named
in the doc and pinned by a test that asserts the rledger digits AND that they
differ from Python's. Switching to 28-digit rounding fails it, so that change
would have to be made on purpose.

Also checked the one way this PR could have changed an inexact result: the
ideal-exponent step normalizes, which would strip a trailing zero. rust_decimal
never emits one on an inexact quotient -- none in 210,563 measured. The first
search for that reported zero cases vacuously: its inexactness test
(`scale >= 27`) silently excluded every quotient with a larger integer part.
Rerun with a correct test (the quotient does not multiply back), which is the
number above.

* test(booking): pin the negative-scale case and correct the blast radius

Third review pass. Two claims in this PR were wrong, found by measuring
things that had only been asserted.

The budget blast radius. The PR said the budget report "changes the same way"
as capgains. Run against the CLI, it does not change at all: `7 * 15 / 30`
comes out `"budgeted": "4"` before and after, because the report rounds to
display precision before emitting CSV or JSON. The real exposure is the FFI:
`session.budget` serializes the accrued `Decimal` with a plain `to_string()`,
so an embedder does see `3.50` become `3.5`. rustfava never calls it. Pinned
at the budget crate, where the value is shaped and nothing rounds it before
the FFI boundary; reverting the fast path fails it with exactly "3.50" vs
"3.5".

A negative ideal scale. The doc said an exact quotient gets Python's scale.
Not when the divisor is finer than the dividend, which is what a whole-number
`@@` total split across lots of 1 and 0.5 units produces: Python switches to
exponent form (`900 * 1 / 1.5` is `6.0E+2`), and rust_decimal, which has no
negative scale, writes `600`. Same value, unmatched representation, and `600`
is what a CSV consumer wants. Named in the doc and pinned as a deviation.

Also widened the evidence for "rust_decimal never emits a trailing zero on an
inexact quotient": the 210,563 cases were all integer operands. 103,207 more
with fractional operands at scales 1-4, also none.

* fix(booking): take prorate's fast path only when the product is exact

Fourth review pass, applying the lesson this function's own history taught
("probe the BOTTOM of the range") to the one place it had not been applied:
the fast path's product.

`checked_mul` does not fail when a product needs more than 28 decimal places
or more than 96 bits. It rounds and returns Some, and for a small product the
rounding is to ZERO:

    prorate(1e-16, 1e-13, 1e-10)    -> Some(0)    true share: 1e-19
    18-decimal token dust
    prorate(1e-18, 1e-11, 1e-11)    -> Some(0)    true share: 1e-18

A representable share presented as nothing -- the wrong-answer class #2348
fixed for the overflow fallback, sitting in the fast path the whole time. It
predates this PR (the gains site multiplied then divided the same way before
prorate existed), but this PR ASSERTED the premise it breaks: a comment here
said "the product's scale is already the sum of its factors'". Not when the
sum exceeds 28.

So the fast path now runs only when that premise holds. rust_decimal does not
normalize products, so an exact product keeps the sum of its factors' scales
and a rounded one has a smaller scale. The check never passes an inexact
product; it can reject an exact one whose trailing zeros were dropped to fit,
which only costs the exact path's time.

Routing more inputs to the exact path exposed a second false claim. The
previous commit said BigDecimal division already lands on Python's ideal
exponent, from nine measured cases. All nine were small-scale. An ordinary
18-decimal token split, 0.500000000000000000 * 1.000000000000000000 /
2.000000000000000000, comes out 0.25 where Python gives 0.250000000000000000.
So `with_ideal_scale` is back in core -- one implementation, shared with
`checked_div_python_scale` -- and applied to an exact slow-path share.

Only to an exact one. An inexact share's trailing zeros are rounding, not
padding; normalizing and re-padding would claim precision the computation
never had. That gate was untested decoration until a search found it guards
real inputs: 1,978 of 19,997 inexact exact-path shares on one shape end in
zero. Now pinned; removing the gate fails it.

Every new test verified two-sided, each sabotage confirmed applied. Two of
this pass's own mistakes caught on the way: a test replace that silently
matched nothing (cargo fmt had reflowed the text) and so "passed" against the
old file, and a test doc that predicted the ungated output wrongly.

* perf(booking): build BigDecimal from mantissa and scale, not a string

Fifth review pass. The previous commit made prorate correct at the bottom of
the range by sending any product that was not exact to the BigDecimal path.
That was measured this time rather than assumed, and it cost a whole class of
ledgers.

`book()` computes gains for every reduction carrying a price, whether or not
anything reads them, so prorate runs on every `rledger check`. Per call, the
fast path is 52-88 ns and the BigDecimal path 1.2-3.0 us. On main only an
overflowing product reached that path; now every 18-decimal-token `@@`
reduction does, since an 18 x 18 product needs 36 places.

Release builds, `rledger check --no-cache`, median of 7-9 interleaved runs:

                        main       exact check     + this commit
    2-dp money (control) 479 ms    474 ms (-1.0%)   483 ms (-1.8%)
    18-dp ERC-20         555 ms    630 ms (+13.6%)  575 ms (+4.8%)

Both ledgers: 30,000 transactions, 20,000 two-lot `@@` disposals, loading
clean. The ERC-20 one is a worst case -- a third of its transactions are those
sales.

Most of the path's cost was `to_big` formatting each Decimal to a string and
parsing it back, four times per call. A Decimal IS mantissa * 10^-scale and
`BigDecimal::new` takes exactly that, so it is now built from the parts:
identical in value AND scale on 500,010 decimals including MAX, MIN, -0.00 and
trailing-zero-padded 18-place values. `to_big` is the crate's canonical
conversion, so `calculate_residual_precise` -- the #1240 balance tier -- gets
the same speedup; rustledger-validate's 154 tests pass through it.

The remaining +4.8% sits inside the run-to-run spread (old 507-609 ms, new
526-613 ms) and is the conversion back, `to_plain_string` + `from_str`.
Removing it would mean re-implementing Decimal's rounding, a correctness risk
for a borderline cost on a worst-case ledger. Not taken.

Also verified the premise the exact-check commit rests on with a randomized
sweep across the full scale and magnitude space: of ~956,000 products, zero
passed the check while inexact. The sweep is not vacuous -- it saw 665,757
inexact products and rejected every one. It also counted 31,701 exact
products rejected (trailing zeros dropped to fit): correct, only slower, and
the reason the exact path's speed mattered.

* fix(core): cap with_ideal_scale at Decimal::MAX_SCALE

Sixth review pass, looking only at paths no earlier pass had executed. One
was an ideal scale above 28.

`with_ideal_scale` pads a quotient up to its ideal scale with `rescale`.
`rescale` clamps to MAX_SCALE only when the value is ZERO; a nonzero value
scales up until its 96-bit mantissa is full, straight past 28:

    with_ideal_scale(0.5, 36)  ->  0.50000000000000000000000000000   scale 29

That is not a Decimal rust_decimal will make itself. `from_parts` rebuilding
it from its own parts PANICS (`assert!(scale <= Self::MAX_SCALE)`), and a
`serialize` / `deserialize` round trip silently turns it into scale 28.

`checked_div_python_scale` cannot reach this -- its ideal is the difference of
two scales, so at most 28. `prorate`'s `a * b / c` can ask for up to 56, and
did so through a realistic ledger: 18-decimal lots sold by a posting written
with one place (`-2.5 TKN`) give 18 + 18 - 1 = 35. It takes a share below 1 to
land on 29 -- one with an integer digit fills the mantissa at 28 -- and ETH
totals under 1 are ordinary.

Capped in the shared helper, so no caller can get an out-of-range scale. Two
tests rebuild the result from its own parts, the operation that would panic
downstream: one on the helper, one end to end through `prorate` on that
ledger shape. Removing the cap fails both.

Python's digit count for an ideal above 28 comes from its 28-digit context
rounding the product before dividing, so the trailing-zero count can differ
from rledger's. Documented; the value never differs.

Also probed this pass, and fine: a tiny NEGATIVE share that rounds to zero
comes back as plain zero, not `-0.000...`, so no signed-zero artifact reaches
a CSV.

* test(booking): check prorate against an exact reference, across all inputs

Seventh review pass. Six passes found bugs in prorate by picking inputs by
hand, and several of those samples were narrower than the conclusions drawn
from them. This asks the question for arbitrary inputs instead.

The reference forms `value * num / den` exactly in BigDecimal and rounds once.
Inputs are drawn with the mantissa's WIDTH chosen first (1 to 96 bits), then
every scale from 0 to 28 and both signs, so tiny and huge magnitudes are
equally likely. It asserts: the value matches to within one unit in the last
place (the fast path breaks ties to even, the conversion away from zero);
`None` exactly when the share cannot be represented; the scale is valid; and
no fabricated zero.

As an exploratory sweep over 1.5 million triples it found nothing on this
code: 1,364,865 exactly equal, 48 within one ulp, zero wrong. It reports dirty
when it should -- with the exactness guard removed it flagged fabricated zeros
AND wrong nonzero shares, one off from the 13th significant digit:

    got  0.0000444905880782270215971873
    want 0.0000444905880781070147260043

which is worth stating plainly: that guard fixed more than dust. Any product
small enough that 28 decimal places leave few significant digits came out
wrong in proportion, not only as zero.

As a proptest it runs 20,000 cases, 0.35 s release and 0.5 s debug, and failed
on 5 of 5 sabotaged runs with fresh seeds. The committed regression file is
proptest's own shrink of the first failure, `v = 1e-20, n = 1e-9, d = 0.1`:
a product below the floor and a true share of exactly 1e-28, on it. The repo
already commits five such files, three beside this one.

Limitation, stated in the file: the reference shares the slow path's final
string conversion, so it cannot catch an error in that single step, which
was checked separately.

* docs(changelog): record the prorate fixes and their cost

Ninth review pass, on the one thing no earlier pass looked at: the user-facing
record. CHANGELOG.md is hand-written and every user-visible PR adds its own
entry -- #2342, #2331, #2306, #2326 and #2322 all did. This PR changes exported
strings, booking results and speed, and added none.

Three Fixed entries and one Performance entry, in the file's style:

- a tiny `@@` share is no longer booked as zero;
- an uneven `@@` split keeps Python's scale in the capgains exports, with the
  exact surfaces named -- CSV and JSON change, TEXT and the budget report do
  not, `session.budget` does -- and the two pinned deviations stated;
- a `@@` share is computed when its intermediate product overflows, which is
  #2348's work: this PR rewrites the function that PR introduced, and an
  entry for one without the other would not read.

Output changes go under Fixed, not Breaking, following the precedent of the
`--format json` column change in #2342. The entry says in bold that exported
strings change and values do not.

The Performance entry is a cost disclosure, not an improvement. Against the
last release the net effect on the worst case is 4.8% slower; the string-free
conversion only recovered most of a regression this same PR introduced, and
the first draft of the entry read as a speedup. It also implied the #1240
precise tier got faster, which was never measured; it now says only that the
tier shares the conversion.

Not addressed here: #2344 and #2347, both merged, also shipped user-visible
fixes without entries -- #2347 fixed a release-mode abort.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Testing]: fuzz_booking cannot generate the overflows it exists to find

1 participant