Skip to content

fix(booking): sell a whole AVERAGE or {*} pool at its exact cost - #2424

Merged
robcohen merged 2 commits into
mainfrom
fix/whole-pool-exact-basis-2417
Sep 25, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/whole-pool-exact-basis-2417

Conversation

@robcohen

@robcohen robcohen commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Problem

1 X at 100 and 2 X at 200 average 166.66…, which Decimal rounds. Booking priced a sale of all three at 3 × 166.6666666666666666666666667, which is 500.0000000000000000000000001:

x Transaction does not balance: residual -1E-26 USD

Sold for 500 USD, the transaction failed. Its amounts are whole dollars, so they infer no tolerance (the same rule as beancount), and any residual at all is an error. The lots cost exactly 500, so booking created an imbalance the ledger's author could not remove. It happened for AVERAGE {} and for {*}.

Fix

  • Core: a reduction that takes the whole pool now takes what the pool's lots cost, Σ |units| × cost (pool_total_cost), in both reduce_average and reduce_merge. A partial sale is still priced at the average, the only figure there is.
  • Booking: when a pooled sale's basis isn't |units| × per-unit, booking writes PerUnitFromTotal(per_unit, total) instead of PerUnit, the shape {{T}} costs already use for exact residual math (validate: rledger accepts sale of non-existent inventory + unsolvable interpolation #1026). The balance weighs the total. The realized gain for a single pooled match uses the same basis.
  • apply, the validator and the BQL replay pass AVERAGE and {*} reductions to reduce_average and reduce_merge, which ignore the spec's number, so they cannot disagree with booking. The [Bug]: {*} cost-merge reduction books but cannot apply — E4001 on a lot the account holds #2068 merge check reads per_unit(), which is still the pool's.
before after
AVERAGE {}, sell all 3 for 500 residual -1E-26 balances; posting weight -500, gain basis 500
FIFO {*}, sell all 3 for 500 residual -1E-26 balances
sell 2 of 3 for 333.33 balances balances (still at the average)

Out of scope: a whole single {{T}} lot

A single lot bought as 3 X {{500 USD}} and sold whole with {} fails the same way. The lot stores only its rounded per-unit cost, so the exact total is lost when the lot is added. Beancount 3.2.0 does the same: it refuses that sale by -0.0000000000000000000000001 USD, and it books the purchase's cash at -500.0000000000000000000000001.

Fixing it means a lot remembering its total, which changes the Cost type, the cache format and the meta.hash contract. That's tracked in #2425. So is the related limitation here: a pool sold in more than one posting, even within one transaction, leaves a remainder lot at the rounded average, so only a sale of the whole pool in one posting is exact.

Visible changes

  • For a sale of a whole pool, consumers of the booked posting now see a total-carrying cost (per_unit_from_total) where they saw per_unit. That changes those postings' meta.hash.
  • Wasm cache v31. The loader cache holds parsed directives only, so it is unaffected.

Tests

  • Core a_whole_pool_sale_takes_the_lots_exact_cost: a whole-pool sale is priced at exactly 500, and a partial sale at 2 × the average, under both AVERAGE and {*}.
  • Loader whole_pool_basis_test: the issue's ledger, run through the full pipeline. There are no errors, the booked cost's total is 500, and the realized basis is 500. It fails with either the core half or the booking half of the fix reverted.
  • Mutation testing on the diff: 17 mutants, 13 caught, 4 didn't compile, none survived.
  • Workspace: 173 test binaries, 0 failures. Clippy and cargo doc -D warnings are clean.

Closes #2417

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

1 X at 100 and 2 X at 200 average 166.66..., which Decimal rounds, and a
sale of all three was booked at `3 x 166.6666666666666666666666667`,
500.0000000000000000000000001. Sold for `500 USD` (whole-dollar amounts
infer no tolerance) it failed with `residual -1E-26 USD`, an imbalance
booking created and the author could not remove.

A reduction that takes the whole pool now takes what the pool's lots
cost (`pool_total_cost`, 500 exactly) in `reduce_average` and
`reduce_merge`. Booking carries it as `PerUnitFromTotal`, as a `{{T}}`
cost already is, so the balance weighs the exact basis, and the realized
gain uses the same basis. A partial sale keeps the average, the only
figure there is. Wasm cache v31, since the booked cost changes shape.

Closes #2417

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

codecov Bot commented Sep 25, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.64706% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/inventory/booking.rs 90.47% 4 Missing ⚠️
crates/rustledger-booking/src/book.rs 96.15% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 31.0ms ± 0.4ms 494.5ms ± 8.6ms 15.9x 51.1 MB / 50.0 MB
investment 48.2ms ± 2.5ms 1667.4ms ± 8.7ms 34.6x 55.1 MB / 58.2 MB
fifo 45.5ms ± 1.3ms 8775.9ms ± 90.8ms 193.0x 53.1 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 32.6ms ± 5.4ms 31.0ms ± 0.4ms -4.7% ✅ within noise 51.3 MB → 51.1 MB (-0.5%)
investment 47.3ms ± 1.9ms 48.2ms ± 2.5ms +1.8% ✅ within noise 54.9 MB → 55.1 MB (+0.2%)
fifo 46.9ms ± 1.1ms 45.5ms ± 1.3ms -3.0% ✅ within noise 57.1 MB → 53.1 MB (-7.1%)

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

@robcohen

robcohen commented Sep 25, 2026 •

Copy link
Copy Markdown
Member Author

Deep review (three passes)

No changes to the fix itself. Pass 3 added a generated regression test (9656a2c).

Probed, correct

  • Short pool: covering a whole AVERAGE short pool (-1 X {100}, -2 X {200}, then 3 X {} for -500 USD) balances. pool_total_cost takes |units| × cost, and BookedCost::try_new gets the covering units' sign, so the weight comes out +500.
  • {*} claims on a whole-pool sale still pass: {*, 166.67 USD} and {{*, 500 USD}} both book. check_merge_spec reads the pool's per-unit cost, which this PR doesn't change.
  • Partial sales are untouched: there cost_basis == |units| × average, so booking still writes PerUnit, and their meta.hash doesn't move. Only a whole-pool sale changes shape.
  • The other walks: apply, the validator and the BQL replay pass AVERAGE and {*} reductions to reduce_average and reduce_merge, which ignore the spec's number. The [Bug]: {*} cost-merge reduction books but cannot apply — E4001 on a lot the account holds #2068 check reads per_unit(), which is still the pool's.
  • Rendering: a PerUnitFromTotal cost renders as its per-unit value, the same as before. cost_number shows 166.66…67 and weight shows -500 USD.

Pass 2

  • BQL cost(position) vs weight on a whole-pool sale: weight is now exactly -500. cost(position) is still -500.00000000000000000000000001, so sum(cost(position)) over the emptied account prints -0 USD. That isn't a regression: before this PR both columns were -500.00…01. A {{T}} buy splits the same way today (weight 500, cost(position) 500.00…01), because a position holds only its per-unit cost. That's Selling a whole {{T}} lot whose total doesn't divide evenly fails to balance: a lot keeps only its rounded per-unit cost #2425's root cause, and I've added it to that issue as a symptom.
  • The fix(booking)!: check a {*} merge spec's cost, currency, date and label #2416 claim check still computes units × pool instead of reading the exact basis booking now records. Its allowance already covers the pool's rounding, so it accepts and refuses the same claims either way. I couldn't construct a claim it gets wrong, so I left it.
  • CHANGELOG section: whole-pool sales that already balanced (sold for 500.00 USD) now book per_unit_from_total, which moves their meta.hash. Precedent puts corrections like that under Fixed, for example "A {{total}} reduction books against the lot its total names". Breaking is kept for changes to which lot is taken or to the numbers, and this is neither, so the entry stays under Fixed.

Pass 3: generated sweep

These are 240 generated pools: two to four lots of 1–30 units at 1–999 USD, long and short, AVERAGE and {*}, each sold whole.

check this PR pre-PR
sold for the exact total: errors 0 13 (the 1E-26 residual)
sold for total + 1 USD: refused 240 of 240 n/a
per-account sum(weight), compared as numbers: non-zero 0 13 (1E-24 to 1E-25 off)
realized lot value ≠ the lots' exact total 0 13
partial sales (cash elided): errors 0 n/a
  • Covered shorts: the gain's roles swap. The lot's value is the proceeds, and it carries the exact total there too.
  • A buy and a whole-pool sale in one transaction: booking and apply take the same three prior lots and leave 1 X {300 USD}. This PR balances it; pre-PR it failed by 1E-26.
  • Regression test: the single-ledger test covered one pool, so 9656a2c adds every_generated_whole_pool_sale_balances_and_realizes_its_exact_total, 200 pools from a fixed LCG. It fails with the core half of the fix reverted.

Limitation, recorded in #2425 and the PR description

Pre-existing, unrelated to this PR

…and basis

The single-ledger test covers one pool whose average doesn't terminate.
The review sweep found such pools in about one in twenty generated
ones (13 of 240 failed before the fix). This replays 200 of them, long
and short, AVERAGE and `{*}`: every sale must balance, and every
realized lot value must be the pool's exact total. For a covered short
that is the gain's proceeds, since the roles swap. A fixed LCG keeps
the ledger identical on every run; reverting the core half of the fix
fails it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
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.

Selling a whole AVERAGE or {*} pool at a non-terminating average cost fails to balance (residual -1E-26)

1 participant