Skip to content

fix(booking): give prorate Python's scale, and stop it zeroing dust shares - #2350

Merged
robcohen merged 8 commits into
mainfrom
fix/prorate-python-scale-2349
Sep 19, 2026
Merged

robcohen merged 8 commits into
mainfrom
fix/prorate-python-scale-2349

Conversation

@robcohen

@robcohen robcohen commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

Closes #2349.

What changes for a user

Only the verbatim exports, and only for an uneven split. @@ 900 USD over lots
of 1 and 999 units:

per-lot proceeds summary
before 0.90, 899.10 900.00
after 0.9, 899.1 900.0
Python decimal 0.9, 899.1 900.0

The summary moves too because it sums the shares, and 0.9 + 899.1 = 900.0 is
exactly Python's answer. TEXT is unchanged — it renders through
DisplayContext at display precision.

Why

rust_decimal's division keeps a non-minimal scale for an exact quotient
(900 / 1000 → 0.90); Python reduces to the ideal exponent (0.9). 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 an
exact share lands on Python's scale for all of value * num / den.

Measured against Python on the cases that must change (0.9, 7.5) and on
the ones that must not
— 100.00 * 1 / 1 keeps its places, 1.50 * 2 / 3
stays 1.00. A fix for the first pair that stripped scale the user actually
wrote would be a regression, so both kinds are pinned.

The slow path's scale — got wrong twice, now settled

First draft: added a scale-padding helper (with_ideal_scale) to core and
applied it to the exact BigDecimal path. Sabotaging it changed nothing, so I
concluded BigDecimal division follows Python's ideal exponent on its own,
from nine measured cases, removed the helper, and wrote here that core was
untouched.

That conclusion was wrong (fourth review pass). All nine cases were
small-scale. An ordinary 18-decimal token split,
0.500000000000000000 × 1.000000000000000000 / 2.000000000000000000, comes out
0.25 from BigDecimal where Python gives 0.250000000000000000. So
with_ideal_scale is back in core — split out of checked_div_python_scale
so there is one implementation of "ideal" — and rustledger-core is changed
by this PR
after all.

It is applied only to an exact share. An inexact share's trailing zeros are
the rounding, not padding, and normalizing then re-padding would claim precision
the computation never had. That gate was itself untested decoration until a
search showed it guards real inputs — 1,978 of 19,997 inexact exact-path shares
on one shape end in zero — and it is now pinned.

A wrong-answer bug in the fast path (fourth pass)

checked_mul does not fail when a product needs more than 28 decimal places;
it rounds and returns Some, and for a small product the rounding is to zero:

true share before
1e-16 × 1e-13 / 1e-10 1e-19 Some(0)
18-dp token dust, 1e-18 × 1e-11 / 1e-11 1e-18 Some(0)

It predates this PR — the gains site multiplied then divided the same way
before prorate existed — but this PR asserted the premise it breaks, in a
comment saying "the product's scale is already the sum of its factors'". So the
fast path now runs only when that holds. rust_decimal doesn't normalize
products, so an exact product keeps the sum of its factors' scales and a rounded
one doesn't. The check never passes an inexact product; rejecting an exact one
only costs time.

What this does not make Python-identical

A review pass caught the PR overclaiming. The above holds for exact
quotients only. For an inexact one, Python rounds to its 28-significant-digit
context while rust_decimal keeps up to 29:

rledger Python
100 / 3 33.333333333333333333333333333 33.33333333333333333333333333
900 / 7 128.57142857142857142857142857 128.5714285714285714285714286

Identical before and after this PR — no regression — but a divergence the
wording denied. It is more precision, not less, so it stays; per CLAUDE.md's
checklist for a deliberate Python deviation it is now named in the doc and
pinned by a test asserting 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.

I also checked the one way this PR could change 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
. My first search for that reported zero cases vacuously: its
inexactness test silently excluded every quotient with a larger integer part.
The number above is from the rerun with a correct test.

And the blast-radius claim, which I had stated from one narrow grep, now rests
on a wider one: the only gains-shaped thing in the WIT is
account-unrealized-gains (market vs cost, never through prorate), and
Ledger::capital_gains is opt-in with exactly one reader, the capgains report.

Blast radius

  • capgains CSV/JSON: as above.
  • budget CLI report: does NOT change. I originally claimed it did, by
    inference from the shared function. Measured, it rounds to display precision
    before emitting any format: 7 × 15 / 30 reads "budgeted": "4" before and
    after.
  • session.budget (FFI): changes. It serializes the accrued Decimal with
    a plain to_string(), so an embedder sees 3.50 become 3.5. Pinned at the
    budget crate, where the value is shaped.
  • rustfava: unaffected. I checked rather than assumed, since I flagged it as
    the risk when filing Pro-rata shares follow rust_decimal's scale, not Python's ideal exponent, in capgains CSV/JSON #2349: rustfava computes budgets in its own Python
    (core/budgets.py, Fava's BudgetModule) and never calls session.budget;
    its only custom "budget" tests exercise how the directive's own arguments
    marshal, not computed accruals. Capgains is not exposed through the FFI.

Third review pass: two more wrong claims, now measured

Budget blast radius — see above. The CLI report is unaffected; only the FFI
sees the change, and rustfava does not call it.

A negative ideal scale. The "exact quotients match Python" claim fails when
the divisor is finer than the dividend — e.g. a whole-number @@ total split
across lots of 1 and 0.5 units:

Python rledger
900 × 1 / 1.5 6.0E+2 600
900 × 1 / 0.5 1.80E+3 1800

rust_decimal has no negative scale, so it cannot follow Python into exponent
form. Same value, and 600 is what a CSV consumer wants. Named in the doc and
pinned as a deliberate deviation.

The trailing-zero evidence was integer-only. The 210,563 cases above had
integer operands; real shares have fractional ones. 103,207 more with
fractional operands at scales 1–4: also none ending in 0.

Fifth pass: the exact check cost 13.6% on 18-decimal ledgers — now ~5%

Measured rather than assumed. book() computes gains for every reduction
carrying a price, so prorate runs on every rledger check. The fourth pass
sent every non-exact product to the BigDecimal path (52–88 ns → 1.2–3.0 µs
per call), and an 18 × 18-decimal product always needs 36 places.

Release builds, rledger check --no-cache, median of interleaved runs, 30,000
transactions with 20,000 two-lot @@ disposals each:

ledger main exact check + string-free to_big
2-dp money (control) 479 ms −1.0% −1.8%
18-dp ERC-20 (worst case) 555 ms +13.6% +4.8%

Most of the cost was to_big formatting each Decimal to a string and parsing
it back, four times per call. It now builds BigDecimal::new(mantissa, scale)
directly — identical value and scale on 500,010 decimals, including MAX,
MIN, -0.00 and padded 18-place values. to_big is the crate's canonical
conversion, so the #1240 precise-residual tier gets faster too.

The remaining +4.8% is inside the run-to-run spread and is the conversion back.
Removing it would mean re-implementing Decimal's rounding — a correctness risk
for a borderline cost on a worst-case ledger — so it is left.

Also swept the fourth pass's premise across the full scale/magnitude space:
of ~956,000 products, zero passed the exactness check while inexact. The
sweep saw 665,757 inexact products and rejected every one, so the zero is not
vacuous.

Sixth pass: with_ideal_scale could build an invalid Decimal

Aimed only at paths no earlier pass had run. with_ideal_scale pads with
rescale, and rescale clamps to MAX_SCALE (28) only for zero — a
nonzero value scales up until its mantissa is full:

with_ideal_scale(0.5, 36)  ->  0.50000000000000000000000000000   (scale 29)

rust_decimal will not build that itself: from_parts rebuilding it from
its own parts panics
, and a serialize/deserialize round trip silently
turns it into scale 28. BQL's checked_div_python_scale cannot reach it (ideal
≤ 28), but prorate can, from a realistic ledger — 18-decimal lots sold by a
posting written as -2.5 TKN ask for scale 18 + 18 − 1 = 35, and a share
under 1 lands on 29. Now capped in the shared helper; two tests rebuild the
result from its parts (the operation that would panic), and removing the cap
fails both.

Also probed, and fine: a tiny negative share rounding to zero comes back as
plain 0, not -0.000….

Seventh pass: a differential test over the whole input space

Six passes found bugs by hand-picking inputs, and several of those samples
were narrower than their conclusions. tests/prorate_differential.rs now
checks prorate against an exact BigDecimal reference for arbitrary inputs
— mantissa width drawn first (1–96 bits), every scale 0–28, both signs — and
asserts value (to one ulp), None exactly when unrepresentable, a valid scale,
and no fabricated zero.

result
exploratory sweep, 1.5M triples 1,364,865 equal · 48 within 1 ulp · 0 wrong
same sweep, exactness guard removed fabricated zeros and wrong nonzero shares
as a proptest, 20,000 cases 0.35 s release / 0.5 s debug
sabotaged, fresh seeds failed 5 of 5 runs

The sabotaged run is worth stating plainly: the fourth pass's 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 —

got  0.0000444905880782270215971873
want 0.0000444905880781070147260043    (off from the 13th significant digit)

The committed regression file is proptest's own shrink of the first failure,
v = 1e-20, n = 1e-9, d = 0.1: a true share of exactly 1e-28, on the floor.
The repo already commits five such files. Limitation, stated in the test: the
reference shares the slow path's final string conversion, which was checked
separately.

Ninth pass: the changelog

CHANGELOG.md is hand-written and every user-visible PR adds its own entry —
#2342, #2331, #2306, #2326 and #2322 all did. This PR had none, so it now adds
three Fixed entries (tiny shares no longer zero; Python scale in the exports,
naming exactly which surfaces change; and #2348's overflow fix, since this PR
rewrites that function) and one Performance entry.

The Performance entry is a cost disclosure, not an improvement: against the
last release the worst case is 4.8% slower. The first draft read as a speedup
and implied the #1240 precise tier got faster, which was never measured; both
are corrected. Output changes are filed under Fixed, following #2342's
--format json precedent, with the string change stated in bold.

Out of scope here but worth knowing: the merged #2344 and #2347 also shipped
user-visible fixes without entries — #2347 fixed a release-mode abort.

Why nothing broke — and the tests that should have existed

No test pinned the scale of a share. The capgains CLI fixture splits @@ 700
into 350 + 350 — even, no fraction — so it could not see this. Added:

test fails when
prorate over Python's measured outputs, incl. must-not-change cases the fast path goes back to checked_div
slow-path scale the exact path's result is normalized
CLI: uneven @@ split, exact CSV rows + JSON fields the fast path goes back to checked_div

Each sabotage was confirmed to have applied before its result was read. The
CLI one was run against a genuinely rebuilt binary (timestamp checked) —
otherwise it tests the stale fixed binary and passes vacuously. And since
require_rledger! skips silently when the binary is missing, I confirmed the
CLI tests ran: zero skip markers across the crate.

rustledger-core, -booking, -budget, -loader, -query and the CLI all
pass; clippy, fmt and cargo doc clean at 1.98.1.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`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
@robcohen
robcohen requested a review from a team as a code owner September 18, 2026 21:51
@github-actions

github-actions Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 45.3ms ± 3.1ms 788.5ms ± 7.9ms 17.4x 50.9 MB / 50.0 MB
investment 66.2ms ± 0.6ms 3008.0ms ± 8.4ms 45.5x 55.0 MB / 58.2 MB
fifo 63.4ms ± 0.3ms 15309.0ms ± 172.8ms 241.5x 55.1 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 43.5ms ± 0.3ms 45.3ms ± 3.1ms +4.1% ✅ within noise 51.1 MB → 50.9 MB (-0.4%)
investment 65.9ms ± 0.5ms 66.2ms ± 0.6ms +0.4% ✅ within noise 56.8 MB → 55.0 MB (-3.2%)
fifo 63.4ms ± 0.5ms 63.4ms ± 0.3ms +0.0% ✅ within noise 55.0 MB → 55.1 MB (+0.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 1.4ms, investment 0.3ms, fifo 0.3ms), 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

@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

@codecov

codecov Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.22222% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/decimal.rs 95.45% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

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.
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.
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.
@robcohen robcohen changed the title fix(booking): give prorate's shares Python's ideal-exponent scale fix(booking): give prorate Python's scale, and stop it zeroing dust shares Sep 19, 2026
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.
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.
…nputs

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.
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
robcohen merged commit cc37338 into main Sep 19, 2026
70 of 71 checks passed
@robcohen
robcohen deleted the fix/prorate-python-scale-2349 branch September 19, 2026 18:39
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.

Pro-rata shares follow rust_decimal's scale, not Python's ideal exponent, in capgains CSV/JSON

1 participant