Skip to content

fix(booking)!: a lot keeps its exact total, and its sales add up to it - #2427

Merged
robcohen merged 4 commits into
mainfrom
fix/lot-exact-total-2425
Sep 25, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/lot-exact-total-2425

Conversation

@robcohen

@robcohen robcohen commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Part of #2425. BQL cost(position) is left for a follow-up, explained below.

Problem

3 X {{500 USD}} resolves to a per-unit cost of 500/3, which Decimal rounds to 166.6666666666666666666666667. The inventory kept only that per-unit cost:

  • Selling the whole lot: a sale for 500 USD was booked at 3 × 166.66…67 = 500.0000000000000000000000001 and failed with residual -1E-26 USD. Beancount 3.2.0 fails the same way, and it also interpolates the purchase's cash as -500.0000000000000000000000001.
  • Selling in parts, lots or pools: a sell-down drifted, and so did an AVERAGE or {*} pool sold in more than one posting. In 600 generated sell-downs on main, 269 accounts missed their total, by up to 7E-23.

Design

These are the choices made in the issue discussion:

  • Where the total lives: inside Inventory, in a vector parallel to the position store's slots. Tombstones, compaction, dense_copy and the undo log carry it with the lot, so a rolled-back transaction restores it. Cost is the lot's identity (Eq/Hash) and is untouched, so lot matching and merging, directives, meta.hash for ordinary sales, the caches and the FFI types are unchanged. BQL's shared snapshot backing never books and keeps no totals.
  • Recording it: the engine records a lot's total when it adds a {{T}} or compound-cost lot (Inventory::add_with_total). Identical lots merging ([Compat]: rustledger keeps a slot per acquisition where beancount pools identical lots — FIFO/LIFO consume in different orders #2118) sum their totals. A total is kept even when units × per-unit rounds to it: 19 × 2921.3157…895 rounds to exactly 55505, yet 18 and 1 sold separately still drift.
  • Selling:
    • A take that empties a lot or pool books what is left of its total.
    • A partial take of such a lot or pool books take × per-unit rounded to the total's precision (28 digits less the total's integer digits), and the lot keeps total − that.
    • Without that rounding, a remainder like 52583.6842105263157894736842105 needs 30 digits, and the sell-down drifts again (79 of 600). You chose rounding over leaving that drift.
    • Partial sales of ordinary per-unit lots are unchanged.
  • Booking: booked_cost_number writes PerUnitFromTotal wherever a lot's basis is not |units| × per-unit, so the balance weighs the exact basis. That covers single lots and each posting of a multi-lot expansion. Realized gains use the same per-lot bases (BookingResult::matched_basis). This replaces fix(booking): sell a whole AVERAGE or {*} pool at its exact cost #2424's pool-only condition.
600 generated sell-downs (lots and pools, long and short, FIFO / AVERAGE / STRICT, totals up to 999,999) accounts not netting to 0 largest drift
main 269 7E-23
this PR 0 0

Breaking

  • Booked costs change for these sales. They now book PerUnitFromTotal, so their meta.hash moves: the sale that empties a {{T}} lot, and a partial sale whose fitted basis differs from units × per-unit.
    • Fitting applies to partial sales of {{T}} lots and to every partial sale from an AVERAGE or {*} pool, including pools of lots bought at a per-unit cost. A pool sold down in parts is only exact if each part is fitted.
    • It rounds whenever the sale's basis has fewer integer digits than the pool's total, which is common. For example, 1 of 17 X pooled at 19338.6 USD books 1137.56470588235294117647059 where main books 1137.5647058823529411764705882, under 5E-24 apart.
    • Sales of lots under FIFO, LIFO, HIFO and STRICT bought at a per-unit cost are unchanged.
  • rustledger_core::BookingResult gained matched_basis. It isn't #[non_exhaustive], so code that builds one with a struct literal must set it.
  • Inventory::add_with_total is new.
  • Wasm cache v32. The loader cache holds parsed directives only, so it is unaffected.

Not in this PR: BQL cost(position)

By the time COST() runs, it gets a bare Position (units plus per-unit Cost). The posting's total is already gone, so it still returns units × per-unit, while weight is now exact. Carrying the total there means a Position value that holds it, which is a change to the query layer. I'd do it as a separate PR.

Tests

  • Core (inventory::booking::reduction_tests):
    • a whole {{T}} lot under all six methods;
    • sell-downs, including 1 + 1 + 17 of 19 units for 55505;
    • a short lot;
    • merged identical lots, and an exact lot merged into a plain one;
    • rollback restoring a total;
    • pools sold down, long and short, AVERAGE and {*};
    • merge_average carrying totals.
  • Booking (lot_exact_total_booking_test): a whole lot, a short cover, a short covered in parts, a multi-lot expansion, and a per-unit lot booking unchanged.
  • Loader (lot_exact_total_test):
    • the issue's ledger;
    • 200 generated whole sales at magnitudes up to 999,999;
    • 200 generated sell-downs. Every account nets to exactly zero and realizes exactly its total. The sums are exact i128s, since Decimal sums round.
  • Mutation testing on the core and booking diff: 67 mutants, 45 caught, 15 didn't compile.
    • The first run's real gaps now have tests: the merge ||, merge_average's filter, the {*} remainder sign, FromIterator, and the short-sign branch. A pool test's fixture had a terminating average and couldn't detect anything; it's fixed.
    • 4 survivors are equivalent: × signum vs ÷ signum three times, and a units sign handed to BookedCost, which reads only the magnitude.
    • 1 is the replay's account_snapshot, which only the query crate calls and tests.
  • Workspace: 175 test binaries, 0 failures. cargo clippy --workspace --all-features --all-targets -D warnings and cargo doc -D warnings are clean.
  • Fuzzing: CI's fuzz_booking replay found a panic.
    • BookedCost::try_new's invariant check subtracted with a bare -, which panics for opposite-signed values near the range. It's the typed-error path, so it must never panic; it now reports overflow: true, as it already did for the product.
    • The crash input is committed under fuzz/regressions/fuzz_booking/. It replays clean, and panics with only that fix reverted.
    • A further 120 s local run, 602k inputs, found nothing.
  • Performance: this touches the inventory's hot paths (one Option<Decimal> per slot, one lookup per take).
    • The first PR Benchmark run flagged simple at +5.1%, just over the 5% bar, with a noisy ±2.1 ms PR measurement.
    • A rerun put every shape within noise: simple +2.4%, investment +1.4%, fifo +2.4%, RSS flat.
    • Both runs lean positive, so a real cost of about 1–2% is plausible.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`3 X {{500 USD}}` resolves to a per-unit cost of 500/3, rounded to
166.6666666666666666666666667, and the inventory kept only that: sold
whole for `500 USD` it booked `3 x` that, 500.0000000000000000000000001,
and failed by -1E-26 (beancount 3.2.0 fails the same way). Sold down in
parts it drifted, and so did an AVERAGE or {*} pool sold in more than
one posting: 269 of 600 generated sell-downs missed by up to 7E-23.

The inventory now keeps each lot's exact total in a vector parallel to
its slots, so tombstones, compaction and the undo log carry it, and
Cost (the lot's identity) is untouched. The engine records it when it
adds a {{T}} or compound-cost lot. The sale that empties a lot or pool
takes what is left of its total; a partial sale takes units x per-unit,
rounded to the total's precision (28 digits less its integer digits) so
every remainder stays exact. Booking writes PerUnitFromTotal wherever a
basis is not units x per-unit, and gains use the same per-lot bases
(BookingResult::matched_basis). Every generated whole sale and
sell-down now nets to exactly zero. Wasm cache v32.

Part of #2425; BQL cost(position) is left for a follow-up.

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 15:30
@codecov

codecov Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.74775% with 10 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/book.rs 89.09% 6 Missing ⚠️
crates/rustledger-core/src/inventory/booking.rs 98.65% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: simple

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 45.8ms ± 2.2ms 822.5ms ± 10.3ms 18.0x 50.9 MB / 50.0 MB
investment 70.3ms ± 1.2ms 3101.0ms ± 65.3ms 44.1x 55.2 MB / 58.1 MB
fifo 68.2ms ± 0.9ms 15468.7ms ± 141.7ms 226.7x 59.3 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 43.4ms ± 0.3ms 45.8ms ± 2.2ms +5.4% 🟡 slower 50.8 MB → 50.9 MB (+0.2%)
investment 69.9ms ± 0.7ms 70.3ms ± 1.2ms +0.6% ✅ within noise 55.0 MB → 55.2 MB (+0.4%)
fifo 67.7ms ± 0.7ms 68.2ms ± 0.9ms +0.8% ✅ within noise 56.9 MB → 59.3 MB (+4.1%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 1.0ms, investment 0.6ms, fifo 0.5ms), 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 and others added 2 commits September 25, 2026 15:52
`check_invariant` checked the `per_unit x units` product for overflow
but subtracted the total from it with a bare `-`, which panics when the
two have opposite signs near Decimal's range. `try_new` is the typed
error path for trust boundaries, so it must not panic; it now reports
`overflow: true` as it does for the product. fuzz_booking reached it
through this PR's exact-total bookings; the crash input is committed as
a regression and replays clean, and panics with this change reverted.

Also checks `old - new` in `retotal_after_take`, the one unchecked
subtraction the exact-total change added.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…ons drops totals

The CHANGELOG said sales of ordinary per-unit lots were unchanged. That
holds for FIFO, LIFO, HIFO and STRICT lots, but every partial sale from
an AVERAGE or `{*}` pool is fitted to the pool's total, per-unit lots or
not, and the fit rounds whenever the sale's basis has fewer integer
digits than the pool total: 1 of 17 X pooled at 19338.6 USD now books
1137.56470588235294117647059 where main booked ...4705882. Say so. Also
document that `modify_positions` drops exact totals.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

robcohen commented Sep 25, 2026 •

Copy link
Copy Markdown
Member Author

Deep review (two passes)

Fixed in pass 2 (7948136): a negative cost's gain came out with the wrong sign. The exact-total code treated a basis as a magnitude:

  • an emptying take returned |lot total|;
  • a whole pool took |pool total|;
  • the engine stored a {{T}} lot's total as |T| × sign(units).

For a negative cost (E4005, but still booked and reported), 3 X {{-500 USD}} sold whole realized:

cost basis gain
main -500.00000000000000000000000001 530.00000000000000000000000001
this PR before the fix +500 -470
this PR now -500 530

A basis is now signed like the per-unit cost, as take × per-unit always was, and the stored total is the written total times the units' sign. New tests cover whole and sold-down lots under FIFO and AVERAGE (core), and the booked total through the engine (booking). Both fail with abs restored.

Fixed in pass 1, 9ce2dd8 (docs only): the CHANGELOG overstated what stays unchanged. It said sales of ordinary per-unit lots are unchanged. That holds under FIFO, LIFO, HIFO and STRICT. But every partial sale from an AVERAGE or {*} pool is fitted to the pool's total, plain per-unit lots or not, and that fitting is what makes a pool sold down in parts exact.

The fit rounds whenever the sale's basis has fewer integer digits than the pool's total, which is common:

1 of 17 X, pooled at 19338.6 USD booked weight
main -1137.5647058823529411764705882
this PR -1137.56470588235294117647059

So those postings' meta.hash moves too, by under 5E-24 in value. The CHANGELOG and PR body now say so. The same commit documents that modify_positions drops exact totals. It rewrites lots wholesale, so there's no telling which total belongs to which; nothing on the booking path calls it.

Checked, no change needed

  • Where a lot's total could be lost:
    • Clone (derived) and dense_copy (used by detached_snapshot, i.e. BQL's per-row account_balance) carry it.
    • Compaction and the undo log carry it too.
    • make_owned from BQL's shared backing has none to carry, since that backing never books.
    • Nothing in production deserializes an Inventory.
    • modify_positions is the one path that drops totals, and it has no production callers.
  • Every booking entry point records totals:
    • the loader's book_interpolate_apply and the LSP's book_and_interpolate + apply, both through augment_posting;
    • the replay's deferred adds.
  • Expansion order: STRICT's sell_undated_lots_after_their_dated_twins reorders expanded postings after each one gets its own lot's cost, so each basis travels with its posting.
  • BookedCost::try_new's tolerance (max(1e-20, |total| × 1e-24)) covers both the fitted bases (under 5E-24) and the remainder-vs-per-unit gap. That gap is relative to the total, and a rounded per-unit cost is off by about 1e-28 relative, so the check holds however many units a lot has.
  • CI: fuzz_booking passes on d491a93 after the try_new fix. The advisory rustfava check fails on the same five stale snapshots. PR Benchmark: every shape within noise on the rerun, with a possible real cost of 1–2%.

A basis was taken as a magnitude: an emptying take returned
`|lot total|`, a whole pool `|pool total|`, and the engine stored a
`{{T}}` lot's total as `|T|` times the units' sign. For a negative cost
(E4005, but still booked and reported) that flipped the sign: `3 X
{{-500 USD}}` sold whole realized a basis of +500 and a gain of -470,
where main reported -500 and 530. A basis is now signed like the
per-unit cost, as `take x per-unit` always was, and the stored total is
the written total times the units' sign.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit 2a79525 into main Sep 25, 2026
68 of 69 checks passed
@robcohen
robcohen deleted the fix/lot-exact-total-2425 branch September 25, 2026 18:01
robcohen added a commit that referenced this pull request Sep 25, 2026
`Inventory::at_cost` multiplied each lot's per-unit cost back out, so a
held `{{500 USD}}` lot of 3 showed 500.0000000000000000000000001 under
`BALANCES AT COST`. It now reads the lot's total where the inventory
keeps one (#2427). BQL's balances come from the booking engine's
replay, whose inventories keep those totals; an inventory built without
them values its lots as before.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen added a commit that referenced this pull request Sep 26, 2026
* fix(query): cost(position) reads the posting's booked cost

`cost(position)` multiplied the Position value's per-unit cost back out,
and a lot bought as `3 X {{500 USD}}` has a per-unit cost of 500/3,
rounded: it gave 500.0000000000000000000000001 where `weight` gives 500,
and so did the sale that empties such a lot, so an emptied account's
`sum(cost(position))` printed `-0 USD`.

Over the position column it now takes the posting's booked cost through
the canonical `cost_number_weight`, the route `weight(position)` already
takes (#1966): exact for a total-carrying cost, and the same
`units x per-unit` for every per-unit one. The posting table's `cost`
column did the same multiplication with an unchecked `*`; it uses the
same rule now, unsigned as before. `cost()` of any other argument still
works from the per-unit cost.

Closes #2425

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

* test(query): only the position column takes COST's posting route

Mutation testing left the route's guard unpinned: forcing it true, or
`&&` to `||`, sent every `COST(x)` to the posting's cost, and the only
non-column case tested was `cost(sum(position))`, which is aggregated
elsewhere. `cost(units(position))` per row is the units themselves.

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

* docs(bql): describe the total-cost lot in words, not {{ }}

VitePress parses `{{ ... }}` as a Vue expression even inside inline code,
so the docs build failed on `3 X {{500 USD}}`. No other docs page writes
the syntax; say it in words instead.

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

* fix(core): BALANCES AT COST values a lot at its exact total

`Inventory::at_cost` multiplied each lot's per-unit cost back out, so a
held `{{500 USD}}` lot of 3 showed 500.0000000000000000000000001 under
`BALANCES AT COST`. It now reads the lot's total where the inventory
keeps one (#2427). BQL's balances come from the booking engine's
replay, whose inventories keep those totals; an inventory built without
them values its lots as before.

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

* fix(query): JOURNAL AT COST shows each row's exact cost

Each row's position AT COST was `units x per-unit` (with a bare `*`),
and its balance was `at_cost` of the running balance, which multiplies
the rounded per-unit cost back out: a `{{500 USD}}` lot showed
500.0000000000000000000000001 on its row and in the balance. The
running balance uses the shared backing (#1086), which keeps no lot
totals, so `at_cost` cannot be made exact there.

The row now shows the posting's booked cost (`compute_posting_cost`, as
`cost(position)` gives it), and the balance is the running sum of those
row costs, which is what `at_cost` of the cumulative balance is: a
sale's cost nets its buy's, and cost-less amounts pass as units.
Unchanged for per-unit lots, including a sale that spans lots.

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

* refactor(query): compute COST(position)'s posting cost once per row

The arm's guard called `compute_posting_cost` and the body called it
again, so every `cost(position)` row paid for the canonical weight
twice. The arm now matches on one call and falls back to the value
path, which moves into `evaluate_on_argument_values` so the default arm
and the fallback share it. JOURNAL AT COST also stops building the
running balance it no longer reads; its balance is `cost_balance`.

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

* docs(changelog): cost(position)'s raw value now carries the weight's scale

Running the BQL compat corpus's 29 total/compound-cost ledgers through
both builds: all 551 (file, query) pairs keep their status, and the
rendered text of `JOURNAL ... AT cost` is identical, but the raw JSON
changes on 19 pairs. `cost(position)` now carries the booked total's
scale, the weight column's: 300.00 where it was
300.00000000000000000000000000, and 305 for `2 HOOL {150 # 5 USD}`
where the re-multiplied per-unit gave 305.00. Say so for JSON and
embedder consumers.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
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.

1 participant