Skip to content

fix(booking): stop small lots booking at a zero cost basis - #2352

Merged
robcohen merged 3 commits into
mainfrom
fix/intermediate-product-zero-cost-2351
Sep 20, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/intermediate-product-zero-cost-2351

Conversation

@robcohen

@robcohen robcohen commented Sep 19, 2026 •

Copy link
Copy Markdown
Member

Closes #2351.

Small lots booked at a zero cost basis

Two booking sites computed a cost from an intermediate product that
checked_mul rounds to 28 decimal places without failing. For a small
lot 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 later
sale of it reads as pure gain.

site reproducer before after
compound {a # b} 1e-11 units at {1e-18 # 0} per-unit 0 1e-18
AVERAGE booking two 1e-11 lots at 1e-18, 3e-18 average 0 2e-18

Compound: a copy that drifted from the canonical

The booker computed (N·a + b) / N. CostSpec::resolve — the canonical CLAUDE.md
names for cost resolution — and the implicit-price extractor already computed
a + b / N: the same value, no intermediate product. All three now call one
function, CostNumber::compound_per_unit, and a test asserts the booker and
resolve agree; reverting the booker fails that test as well as the
reproducer. (resolve's comment described the unsafe form while its code used
the 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 BigDecimal reference
over 256,574 random pools:

fallback rule worse than main fabricated zeros
main as-is — 145
ratio form for every inexact product 178,500 (70%) 0
sum < 1e-10 1,066 0
sum < 1e-20 9 0
sum is zero AND a product vanished 0 0

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 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-core deliberately has no bigdecimal
dependency — the published rustledger-parser uses it standalone. If you want
correctly-rounded averages, that dependency is the decision.

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. 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 doc clean at 1.98.1. Changelog
entries 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 used
to book. Over 362,103 random {a # b} inputs: 0 such cases. 186 zero
per-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:

lots (6e-14 at 4e-16), (9e-14 at 5e-16), (9e-14 at 5e-16), (3e-14 at 1e-16)
sum 1e-28 (one product rounds up, the rest vanish) -> not zero -> no repair
booked 3.7037e-16   correct 4.3333e-16

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 BigDecimal dominates both and needs the
rustledger-core dependency decision — also in #2353.

Two of my own measurement errors, caught: the first accuracy reading
compared against the unrounded exact value, counting Decimal's own
resolution 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-18 for an exact 2e-18, sign
and value right. The property now draws both directions.

Extending it failed twice, both times because of the test, not the code:

  1. The 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. Baseline and
    reference now read the pool back out of the inventory.
  2. Bit-for-bit comparison failed by one digit (…7719 vs …7727): the
    function 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 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.

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, and
sums 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

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
@robcohen
robcohen requested a review from a team as a code owner September 19, 2026 19:15
@codecov

codecov Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.45455% with 8 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/booking.rs 87.17% 5 Missing ⚠️
crates/rustledger-core/src/implicit_prices.rs 0.00% 2 Missing ⚠️
crates/rustledger-core/src/cost.rs 85.71% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 34.4ms ± 0.7ms 580.5ms ± 8.1ms 16.9x 51.1 MB / 49.9 MB
investment 53.3ms ± 1.2ms 2182.6ms ± 17.6ms 40.9x 57.1 MB / 58.1 MB
fifo 50.9ms ± 1.0ms 12268.6ms ± 109.5ms 241.1x 57.2 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 34.5ms ± 1.1ms 34.4ms ± 0.7ms -0.2% ✅ within noise 51.2 MB → 51.1 MB (-0.2%)
investment 52.9ms ± 0.9ms 53.3ms ± 1.2ms +0.8% ✅ within noise 57.0 MB → 57.1 MB (+0.0%)
fifo 50.4ms ± 0.8ms 50.9ms ± 1.0ms +1.0% ✅ within noise 57.1 MB → 57.2 MB (+0.2%)

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

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
robcohen merged commit 5bd08dc into main Sep 20, 2026
70 of 71 checks passed
@robcohen
robcohen deleted the fix/intermediate-product-zero-cost-2351 branch September 20, 2026 03:08
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>
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.

Average-cost and compound-cost booking record a zero cost basis for small lots (intermediate product rounded before a division)

1 participant