Repository navigation
fix(booking)!: a lot keeps its exact total, and its sales add up to it - #2427
Conversation
`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
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
📊 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?
|
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
`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
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:
For a negative cost (E4005, but still booked and reported),
A basis is now signed like the per-unit cost, as 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 The fit rounds whenever the sale's basis has fewer integer digits than the pool's total, which is common:
So those postings' Checked, no change needed
|
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
`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): 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]>
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, whichDecimalrounds to 166.6666666666666666666666667. The inventory kept only that per-unit cost:500 USDwas booked at3 × 166.66…67= 500.0000000000000000000000001 and failed withresidual -1E-26 USD. Beancount 3.2.0 fails the same way, and it also interpolates the purchase's cash as-500.0000000000000000000000001.{*}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:
Inventory, in a vector parallel to the position store's slots. Tombstones, compaction,dense_copyand the undo log carry it with the lot, so a rolled-back transaction restores it.Costis the lot's identity (Eq/Hash) and is untouched, so lot matching and merging, directives,meta.hashfor ordinary sales, the caches and the FFI types are unchanged. BQL's shared snapshot backing never books and keeps no totals.{{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 whenunits × per-unitrounds to it:19 × 2921.3157…895rounds to exactly 55505, yet 18 and 1 sold separately still drift.take × per-unitrounded to the total's precision (28 digits less the total's integer digits), and the lot keepstotal − that.booked_cost_numberwritesPerUnitFromTotalwherever 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.Breaking
PerUnitFromTotal, so theirmeta.hashmoves: the sale that empties a{{T}}lot, and a partial sale whose fitted basis differs fromunits × per-unit.{{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.rustledger_core::BookingResultgainedmatched_basis. It isn't#[non_exhaustive], so code that builds one with a struct literal must set it.Inventory::add_with_totalis new.Not in this PR: BQL
cost(position)By the time
COST()runs, it gets a barePosition(units plus per-unitCost). The posting's total is already gone, so it still returnsunits × per-unit, whileweightis now exact. Carrying the total there means aPositionvalue that holds it, which is a change to the query layer. I'd do it as a separate PR.Tests
inventory::booking::reduction_tests):{{T}}lot under all six methods;1 + 1 + 17of 19 units for 55505;{*};merge_averagecarrying totals.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.lot_exact_total_test):i128s, sinceDecimalsums round.||,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.× signumvs÷ signumthree times, and a units sign handed toBookedCost, which reads only the magnitude.account_snapshot, which only the query crate calls and tests.cargo clippy --workspace --all-features --all-targets -D warningsandcargo doc -D warningsare clean.fuzz_bookingreplay 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 reportsoverflow: true, as it already did for the product.fuzz/regressions/fuzz_booking/. It replays clean, and panics with only that fix reverted.Option<Decimal>per slot, one lookup per take).simpleat +5.1%, just over the 5% bar, with a noisy ±2.1 ms PR measurement.simple+2.4%,investment+1.4%,fifo+2.4%, RSS flat.🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr