Repository navigation
fix(booking): stop small lots booking at a zero cost basis - #2352
Merged
Merged
Conversation
Two sites computed a cost from an intermediate product that `checked_mul`
rounds to 28 decimal places without failing. For a small lot the product
rounds to zero and the cost it was headed for -- perfectly representable --
came out 0: a zero cost basis on a real holding, every later sale of it
reading as pure gain.
Compound `{a # b}`. The booker computed the per-unit as (N*a + b) / N;
`CostSpec::resolve` and the implicit-price extractor computed a + b / N, the
same value with no intermediate product. The booker was a copy that had
drifted, which is how `1e-11` units at `{1e-18 # 0}` booked a per-unit of 0.
All three now call one function, `CostNumber::compound_per_unit`, and a test
asserts the booker and `resolve` agree -- reverting the booker fails it along
with the reproducer. `resolve`'s own comment described the unsafe form while
its code used the safe one; it now says which is evaluated and why.
AVERAGE. The pool's cost was sum(units * cost) / sum(units). Two lots of 1e-11
units at 1e-18 and 3e-18 have products 1e-29 and 3e-29, below the floor, so the
pool booked at 0 where it is 2e-18.
The first fix was wrong, and measurement caught it before it shipped. It took
the ratio form, sum(cost * units / total), for every inexact product,
reasoning that it could only be better. Against an exact BigDecimal reference
over 256,574 random pools it was WORSE than the old formula in 70% of them:
rust_decimal keeps 28 decimal places, not 28 significant digits, so a small
ratio keeps few digits and a large cost magnifies the loss.
The fix that ships changes exactly one signature: the sum of products is zero
AND a product vanished from two nonzero factors. Measured, it altered exactly
the 145 fabricated zeros in those pools and left 256,429 bit-for-bit
unchanged. Widening the trigger to "the sum is merely small" rescued more
imprecise pools but made others worse (9 at < 1e-20, 1,066 at < 1e-10).
A zero sum from products that genuinely cancel keeps its exact zero.
Not fixed, and said so in the doc and the changelog: a sum that loses digits
without reaching zero stays imprecise in proportion, as before. That needs
exact arithmetic, and rustledger-core deliberately has no bigdecimal
dependency -- the published rustledger-parser uses it standalone.
Tests:
- both reproducers, and the booker/resolve agreement, each failing when its
fix is reverted;
- a 20,000-case property test over the whole magnitude range asserting no
fabricated zero AND bit-for-bit agreement with the old formula outside the
repair. It failed 5 of 5 runs with the repair disabled, and 5 of 5 with the
trigger widened to the measured-worse variant. Its committed seed is
proptest's shrink of a real pool that booked at zero.
Found while reviewing, and deliberately left alone: the booker divides a
summed cost basis for a reduction whose first matched lot has no cost. Same
class by construction, but it signs and currency-checks differently from the
weighted average, and a mixed cost-less/costed pool did not reach it in
testing. Documented at the function.
Closes #2351
Codecov Report❌ Patch coverage is 📢 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 |
Review pass over this PR. Two claims in it rested on reasoning, and measuring
them changed what the PR says.
The compound change was the regression risk: the per-unit is now computed
independently of the total, where it used to be derived from it, so the pair
could fall outside `BookedCost::try_new`'s tolerance and start erroring on
input that used to book. Measured over 362,103 random `{a # b}` inputs: 0 such
cases. 186 had a zero per-unit that is now nonzero, and the 24,035 that fail
the invariant failed it before as well.
The average-cost limitation was stated but not quantified, and the figure I
first wrote came from the wrong sample. Measured against an exact reference:
of 400,000 random pools of COMPARABLE small lots -- the realistic shape --
37,914 are off by more than 100 units in the last place, unchanged by this PR
(11,842 of 341,915 when magnitudes span the whole range). The cause is a sum
that keeps one or two digits instead of vanishing, so the zero-only trigger
does not fire.
Two corrections to my own measurements on the way:
The first reading of the fallback's accuracy compared against the unrounded
exact value, which counts `Decimal`'s own resolution as error and made a
correctly rounded result look 96% wrong. Against the exact value ROUNDED to
`Decimal` -- the best any implementation can return -- the fallback is exact
in 137,704 of 178,474 triggered pools and within one unit in the last place in
36,859 more.
A targeted generator for realistic pools first produced zero triggered cases,
because mantissas up to 1000 kept every product above the floor. The figures
above are from the corrected one.
The wider trigger those measurements point to -- a product vanished AND every
ratio well-conditioned -- is better than the old formula on both populations
and takes the realistic figure from 37,914 to 326, at the price of 519 in
742,000 coming out slightly worse. This PR keeps the never-worse trigger:
trading that property for accuracy is a deliberate call, not something to
fold into a bug fix. Filed with the full table as #2353, alongside the exact
arithmetic that dominates both.
Second review pass, on the coverage the property test did not have. It drew positive units only, so the repair had never run on a SHORT pool. The sign arrives by a different route on each path -- the ratio form divides two negatives where the product form multiplies them -- so this was luck rather than coverage. Checked directly first: a short dust pool books 2.00e-18 for an exact 2e-18, sign and value right. The property now draws both directions. Extending it failed immediately, twice, both times because of the test: Its baseline read the drawn lots, but `Inventory::add` MERGES positions whose costs are equal in value and differ only in scale (`...0010` and `...001`), so the function sees summed units where the draw had two lots and the products round differently. The baseline and the exact reference now read the pool back out of the inventory. Then the bit-for-bit comparison failed by one digit in the last place (...7719 against ...7727). The function accumulates over the lots it matched in its own order, and the order a sum is built in decides that digit, so the assertion was pinning an internal detail as though it were behavior. It is one unit in the last place now, which still catches a change of FORM: both sabotages -- repair disabled, and trigger widened to `vanished` alone -- fail 3 of 3 runs with fresh seeds. Also verified this pass, and unchanged: the rewritten loop checks each lot's currency before computing that lot's product, which is how the old code interleaved them, so the same input yields the same error. Worth knowing, and correct: the reduction's cost BASIS for such a dust sale is still 0. It is `reduction * average`, a final product whose true value is below `Decimal`'s floor, so 0 is its correct rounding. The repair fixes the pool's per-unit cost, which is what later reductions and the holdings view read.
robcohen
added a commit
that referenced
this pull request
Sep 20, 2026
…Decimal (#2354) * fix(core): compute the pooled average cost exactly, escalating to BigDecimal #2352 stopped AVERAGE booking pooling small lots at a ZERO cost, and left the rest: a sum that loses digits without reaching zero is still divided as-is, so the average is wrong in proportion. The issue offered a cheaper trigger or exact arithmetic. Measured, only exact arithmetic is right. Three Decimal-only forms, against an exact reference, counting results more than 100 units in the last place from correct: comparable small lots whole range products, divided (main) 28,146 8,894 ratio form when a product vanished, if the ratios are well-conditioned 215 8,348 incremental weighted mean 0 123,365 exact escalation (this) 0 0 Each Decimal-only form wins one population and loses the other, because rust_decimal keeps 28 decimal PLACES, not 28 significant digits: a small product loses digits to the floor and a small ratio loses them just the same. The incremental mean is the best of them on realistic pools and the worst of them on wide ones. So the average is computed in two tiers, the shape the balance validator already uses for an over-precise residual (#1240): the Decimal sum of products while every step is exact, otherwise the same expression in BigDecimal, rounded once. Ordinary pools stay on the Decimal path, unchanged to the last digit. Writing the property test as "correctly rounded" immediately found that tracking exactness per PRODUCT is not enough. Summing exact products rounds too, once their magnitudes fill the 96-bit mantissa, and that left one class two units in the last place from correct. An exact addition keeps the larger of the two scales, so the accumulation is checked the same way the products are. The seed is committed; removing that check fails it deterministically. This makes bigdecimal a dependency of rustledger-core, which had avoided one. Nothing new enters the workspace -- it is already here for #1240 -- and the cost falls on a rustledger-parser-only consumer, which gains four crates on 65. `to_bigdecimal` is now core's canonical conversion, and rustledger-booking's precise residual delegates to it so the two cannot drift. Measured on `check --no-cache`, 24,000 transactions with 8,000 AVERAGE reductions, release, median of 7 interleaved runs: -1.2% on 18-decimal amounts and -1.9% on ordinary money, both inside the run-to-run spread. Every reduction in the 18-decimal ledger escalates -- its products need 36 decimal places and come back with 28 -- so that figure is the escalation's real cost, not a measurement of a path that never ran. The first attempt at that benchmark was invalid (Python wrote the cash amounts in exponent notation, which the grammar rejects); the assertion that the ledger loads clean is what caught it. The property test now asserts correct rounding outright, where it could only assert "no fabricated zero, and otherwise the old formula" while the fix was a heuristic. Closes #2353 * test(booking): cover a mixed-sign pool through the exact escalation Review pass over this PR, on perf and on coverage. Perf, which the last pass measured only on pools of two or three lots. A real AVERAGE account accumulates lots for years before a sale, and the escalation does a BigInt multiply per lot, so the question was the curve rather than the constant. Timing `Inventory::reduce` directly, best of five, release: lots escalated fast path ratio 500 0.100 ms 0.033 ms 3.0x 2000 0.408 ms 0.139 ms 2.9x 8000 1.498 ms 0.652 ms 2.3x Linear -- 4x the lots costs 3.7-4.1x the time -- so a single pool of 8,000 lots reduces in 1.5 ms against 0.65 ms. No quadratic hiding in the escalation. Coverage: the property test draws pools whose lots all share a sign, so a pool holding BOTH directions of one commodity had none, and it is where a weighted average is least intuitive -- the numerator is a difference of products rather than a sum of like terms. Checked first that the regime is reachable at all: a pool of +10 {2.5} and -4 {3.5} reduces at 11/6, correctly rounded. That one takes the fast path, so the test uses 18-decimal costs to force the escalation, and asserts its own premise. Disabling the escalation fails it. Also verified this pass, both claims this PR makes: The dependency cost. `rustledger-parser`, the published crate that uses core standalone, goes from 65 dependency crates to 69 -- bigdecimal, libm, num-bigint and num-integer; num-traits was already there. That is the "+4 on 65" the PR body states, now measured after the change rather than predicted before it. The `Update Exemptions` failure is not transient. Re-running the job reproduces it exactly: `cargo vet regenerate exemptions` cannot parse supply-chain/audits.toml, where three entries use a `trusted-publisher` key no released cargo-vet understands. Pre-existing since #2323, path-gated on Cargo.lock, and tracked in #2355; this branch does not touch supply-chain/. * chore: regenerate cargo-vet exemptions --------- Co-authored-by: rustledger-bot[bot] <257329324+rustledger-bot[bot]@users.noreply.github.com>
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 #2351.
Small lots booked at a zero cost basis
Two booking sites computed a cost from an intermediate product that
checked_mulrounds to 28 decimal places without failing. For a smalllot the product becomes zero, and the cost it was headed for — perfectly
representable — came out
0. A zero cost basis on a real holding: every latersale of it reads as pure gain.
{a # b}1e-11units at{1e-18 # 0}01e-181e-11lots at1e-18,3e-1802e-18Compound: a copy that drifted from the canonical
The booker computed
(N·a + b) / N.CostSpec::resolve— the canonical CLAUDE.mdnames for cost resolution — and the implicit-price extractor already computed
a + b / N: the same value, no intermediate product. All three now call onefunction,
CostNumber::compound_per_unit, and a test asserts the booker andresolveagree; reverting the booker fails that test as well as thereproducer. (
resolve's comment described the unsafe form while its code usedthe safe one — the form someone copied.)
Average: my first fix was wrong, and measurement caught it
It took the ratio form,
Σ cost × (units / total), for every inexact product,reasoning it could only be better. Against an exact
BigDecimalreferenceover 256,574 random pools:
mainmainas-is< 1e-10< 1e-20rust_decimalkeeps 28 decimal places, not 28 significant digits, so a smallratio keeps few digits and a large cost magnifies the loss. The shipped rule
changed exactly the 145 fabricated zeros and left 256,429 pools bit-for-bit
unchanged. A zero sum from products that genuinely cancel keeps its exact zero.
Not fixed, and stated in the doc and the changelog: a sum that loses digits
without reaching zero stays imprecise in proportion, as it was. That needs
exact arithmetic, and
rustledger-coredeliberately has nobigdecimaldependency — the published
rustledger-parseruses it standalone. If you wantcorrectly-rounded averages, that dependency is the decision.
Tests
resolveagreement, each failing when itsfix is reverted.
fabricated zero AND bit-for-bit agreement with the old formula outside
the repair. Failed 5 of 5 runs with the repair disabled, and 5 of 5
with the trigger widened to the measured-worse variant — so a future
"improvement" of that kind cannot slip through. The committed seed is
proptest's shrink of a real pool that booked at zero:
[(1e-8, 1e-21), (1e-14, 1e-15)].3,206 tests pass across eight suites (core, booking, budget, validate, loader,
query, CLI, plugin); clippy, fmt and
cargo docclean at 1.98.1. Changelogentries added in this PR.
Review pass: both claims measured
The compound change's regression risk: none. The per-unit is now computed
independently of the total, where it was derived from it, so the pair could fall
outside
BookedCost::try_new's tolerance and start erroring on input that usedto book. Over 362,103 random
{a # b}inputs: 0 such cases. 186 zeroper-units became nonzero; the 24,035 that fail the invariant failed before too.
The average-cost limitation, quantified — and my first figure was from the
wrong sample. Of 400,000 random pools of comparable small lots (the
realistic shape), 37,914 are off by more than 100 ulps, unchanged by this
PR; 11,842 of 341,915 when magnitudes span the whole range. The cause is a sum
that keeps one or two digits instead of vanishing, so the zero-only trigger does
not fire:
A better trigger exists, and is filed rather than taken: #2353. Requiring a
vanished product AND every ratio well-conditioned beats the old formula on both
populations and takes 37,914 → 326, at the price of 519 in 742,000 coming out
slightly worse than the old formula. This PR keeps the never-worse trigger;
trading that property for accuracy is a deliberate call, not something to fold
into a bug fix. Exact arithmetic in
BigDecimaldominates both and needs therustledger-coredependency decision — also in #2353.Two of my own measurement errors, caught: the first accuracy reading
compared against the unrounded exact value, counting
Decimal's ownresolution as error and making a correctly rounded result look 96% wrong
(against the correctly rounded value the fallback is exact in 137,704 of 178,474
triggered pools, within 1 ulp in 36,859 more); and a targeted generator for
realistic pools first produced zero triggered cases because its mantissas
kept every product above the floor.
Second review pass: the property test's own gaps
Short pools were untested. The test drew positive units only, so the repair
had never run on a short pool — where the sign arrives by a different route
(the ratio form divides two negatives where the product form multiplies them).
Checked directly: a short dust pool books
2.00e-18for an exact2e-18, signand value right. The property now draws both directions.
Extending it failed twice, both times because of the test, not the code:
Inventory::addmerges positionswhose costs are equal in value and differ only in scale (
…0010and…001),so the function sees summed units where the draw had two lots. Baseline and
reference now read the pool back out of the inventory.
…7719vs…7727): thefunction accumulates over the lots it matched in its own order, and that
order decides the last digit. The assertion was pinning an internal detail as
behavior. It is one ulp now, and both sabotages — repair disabled, trigger
widened — still fail 3 of 3 runs on fresh seeds.
Verified unchanged: the rewritten loop checks each lot's currency before
computing that lot's product, exactly as the old code interleaved them, so the
same input yields the same error.
Worth knowing, and correct: the reduction's cost basis for such a dust
sale is still
0. It isreduction × average, a final product whose true valueis below
Decimal's floor, so0is its correct rounding. The repair fixes thepool's per-unit cost, which is what later reductions and the holdings view read.
Found, deliberately left alone
The booker divides a summed cost basis for a reduction whose first matched
lot has no cost — the same class by construction. But that branch divides an
unsigned basis by
|units|while matched lots carry the inventory's sign, andsums across cost currencies where the weighted average reports a mismatch;
routing it through here is a semantic change of its own. A mixed
cost-less/costed pool did not reach it in testing (the cost was left unfilled
instead). Documented at the function.
🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr