Repository navigation
fix(core): bound every lot an add can merge into, not just the cost-less one - #2347
Merged
Merged
Conversation
…ess one
`add_headroom_for` proves that a sequence of adds cannot overflow, and `apply`
relies on it to decide whether to snapshot the accounts a transaction touches.
When it is wrong in the `true` direction, `apply` skips the snapshot and then
hits its own guard:
rollback_needed() returned false but posting application failed
(Assets:Stock: CORP amount exceeds the representable range (±7.9e28)):
the guard is unsound and the earlier postings of this transaction cannot
be rolled back
That is a plain `assert!`, not a `debug_assert!`, so it is a process abort in
release.
The predicate's own doc described `add` as overflowing at two places: the
per-currency running total, and the single cost-less lot `simple_index` names.
That was true when it was written. #2118 made cost-bearing lots merge as well
-- `cost_index` finds a lot agreeing on cost, date and label -- which gave
`add` a second merge target this predicate was never taught about.
`stats.total` bounds the individual lots only when they all share a sign,
because then it is the sum of their magnitudes. With mixed signs it is not:
`+MAX` and `-MAX` net to zero and a lot at the ceiling leaves no trace in it.
Measured, with no booking engine in the picture:
add_headroom_for("CORP", 1) -> true
add(1 CORP {0.01 USD}) -> Err(OverflowError { currency: CORP })
There is no O(1) bound on the largest lot in the mixed case -- a cached
maximum cannot survive removals without a rescan, and this runs twice per
posting -- so it now answers "cannot prove it", which is the direction the
method is allowed to be wrong in. Rare in practice: a cost-less currency has
exactly one lot and so can never be mixed; it takes a long and a short of the
same commodity in one account, and the cost of the conservative answer is an
`imbl` snapshot with O(1) structural sharing.
Two tests. One pins the ceiling case and checks the add it asks about really
does fail; the other pins that same-sign lots still prove room, so a predicate
that quietly became `false` for everything would not pass. Removing the guard
fails the first and leaves the second passing.
Also fixes the generator defect that hid this. `fuzz_booking`'s "anywhere in
the domain" arm handed a raw uniform `i128` to
`Decimal::try_from_i128_with_scale`, which is representable about one time in
2^31 -- measured at 0 of 200,000 draws, so the arm produced `ZERO` on every
draw and one draw in eight was dead. Masking the mantissa to the 96 bits
`Decimal` has makes it work, and it found this panic within 150 seconds.
Verified two-sided through `cargo fuzz` rather than a hand-rolled release
build, which compiles the assert's neighbors out: the input panics without
the fix and passes with it. 9.4M runs over six minutes on the fixed build
found nothing further.
Closes #2345
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Contributor
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
…he fuzzer
Review pass over this PR's own diff.
The panic being fixed lived at `apply`'s `assert!`, and nothing here reached
it from `cargo test`. The crash input is in the fuzz regressions directory,
but no test in this crate replays that corpus -- the parser has
`tests/fuzz_regressions.rs` for exactly this reason and booking has no
equivalent -- so the abort path was covered only while the fuzz job ran.
Every test added so far was against `add_headroom_for` directly, one layer
below the thing that aborts.
The new test drives `BookingEngine::apply`. Reproducing it turned up the
detail that matters and that the issue did not record: merging needs agreement
on cost, currency, date AND label, so the third buy has to carry the same
acquisition date as the first. With a different date it opens a third lot,
nothing merges, and the overflow never happens -- the first draft of this test
passed for that reason while the bug was fully present.
It also asserts what the guard is actually for, which the unit tests cannot
see: the running balance is unchanged after the failed apply. Verified two-
sided -- removing the guard makes it fail with the exact assertion text.
Two corrections to my own work in this PR:
The account assertion first read `format!("{err}").contains(...)`, which is
the substring shape that a message match satisfies by accident. Now on the
typed fields.
The comment justifying the conservative answer said it takes two cost-bearing
lots of opposite sign. A cost-less lot beside an opposite cost-bearing one
qualifies too; only cost-less-ONLY is safe, because those always merge and so
a currency holds at most one.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #2345.
A release-mode abort, not a debug assert
applyasksadd_headroom_forwhether a transaction can overflow, and skipsits rollback snapshot when the answer is no. When that answer is wrong it hits
its own guard:
That is a plain
assert!. It is live in release, so this is a process abortout of
rledger check, which is the outcome the #1987 / #2067 work on thisguard exists to prevent.
The predicate went stale under a change to
addIts own doc said
addoverflows at twochecked_adds: the per-currencyrunning total, and the single cost-less lot
simple_indexnames. That wasaccurate when written.
#2118 made cost-bearing lots merge as well —
cost_indexfinds a lot agreeingon cost, date and label — which gave
adda second merge target. The predicatewas not updated with it, so the lot a cost-bearing add joins was never bounded.
stats.totalbounds the individual lots only when they all share a sign,because then it is the sum of their magnitudes. With mixed signs it is not:
+MAXand-MAXnet to zero, and a lot at the ceiling leaves no trace in thenet. Measured directly against
Inventory, no booking engine involved:The fix, and why it is the conservative one
A cached maximum lot cannot survive removals without a rescan, and this method
runs twice per posting — so there is no O(1) bound available in the mixed case.
It now answers "cannot prove it", which is the one direction the method is
allowed to be wrong in. The doc is corrected to match what
addactually does.This is rare enough to cost nothing in practice: a cost-less currency has
exactly one lot and so can never be mixed, it takes a long and a short of the
same commodity in one account, and a
falsecosts animblsnapshot with O(1)structural sharing.
The generator defect that hid it
fuzz_booking's "anywhere in the domain" arm handed a raw uniformi128toDecimal::try_from_i128_with_scale, representable about one time in2^31.Measured at 0 of 200,000 draws — the arm produced
Decimal::ZEROeverytime, so one draw in eight was dead and #2344's "values now come from
Decimal's actual domain" was only ever true of the edge arm. Masking themantissa to the 96 bits
Decimalhas makes it work, and it found this panicwithin 150 seconds.
Review pass over this PR
The abort path was not covered by
cargo test. Every test here was againstadd_headroom_fordirectly -- one layer below the thing that actually aborts.The crash input sits in the fuzz regressions directory, but no test in this
crate replays that corpus (the parser has
tests/fuzz_regressions.rsforexactly this; booking has no equivalent), so
apply's assertion was coveredonly while the fuzz job ran. Added
tests/apply_rollback_guard.rs, whichdrives
BookingEngine::applyand fails with the exact assertion text when theguard is removed.
Writing it surfaced a detail the issue did not record: merging needs
agreement on cost, currency, date AND label, so the third buy has to carry
the same acquisition date as the first. With a different date it opens a third
lot, nothing merges, and no overflow occurs -- the first draft of that test
passed for that reason while the bug was fully present. Worth knowing for
anyone reading the reproducer.
The test also asserts what the guard exists for and the unit tests cannot see:
the running balance is unchanged after the failed apply.
Two corrections to my own work here. The account assertion first read
format!("{err}").contains(...)-- the substring shape a message matchsatisfies by accident; now on the typed fields. And the comment justifying the
conservative answer claimed it takes two cost-BEARING lots of opposite sign: a
cost-less lot beside an opposite cost-bearing one qualifies too. Only
cost-less-only is safe, because those always merge, so a currency holds at
most one.
Audited, and holds. The guard's soundness rests entirely on
stats.countsbeing accurate, so I traced every path that can change a lot'ssign. Both reduction paths in
inventory/booking.rsbump the sign bucket downbefore overwriting and up afterwards (a reduction can take a lot through
zero), with a further decrement on removal, and
compactrebuilds the cachesoutright. Nothing mutates a position's units outside those paths.
Verification
cargo fuzz, not a hand-rolledcargo build --release— that compiles the assert's neighbors out andreports a clean replay for a live bug.
leaves the same-sign test passing, so the second one really does
distinguish. A predicate that quietly became
falsefor everything wouldnot survive it.
rustledger-core,rustledger-booking,rustledger-loader,rustledger-query,rustledger-validateall pass. Clippy, fmt andcargo docclean at 1.98.1.The crash input is kept at
fuzz/regressions/fuzz_booking/headroom-net-hides-ceiling-lot-2345.🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr