Repository navigation
fix(booking): apply a transaction in the order booking read it - #2379
Merged
Merged
Conversation
`book` classifies each posting against the inventory as it stood before the transaction, threaded with that transaction's earlier REDUCTIONS only. An augmentation is never visible to a later posting of the same transaction. `apply` classified every posting against the untouched pre-transaction inventory to order them, reductions first, then let each posting ask live state again. Its justification, that threading can only make a posting look less like a reduction, is false once a sale exhausts a lot and the next opens a short: a later posting then reads as a reduction of a short `book` never saw. Holding 2 @ 100, `+9 @101, -2 @100, -2 @100` booked and then failed to apply. `apply` now walks in textual order, applying each reduction as found and holding augmentations back until the walk ends, so live state during the walk is `book`'s view and every classification matches by construction. A cost-less posting met before anything is held back is added at once: it cannot change any classification or a `{*}` pool, and this keeps the common case off the second pass. The validator's inventory pass (`update_inventories`) made the same mistake independently, so `rledger check` still rejected these ledgers after `apply` was fixed. It walks the same way now, and each site names the other. Beancount accepts both shapes, and the holdings now match it. On 2000 generated ledgers of this shape (lots of 1 to 5 units, several sells per transaction), main disagreed with beancount on 30 and this change on none; acceptance agreed on all 1713 that beancount rejects. Callgrind on the benchmark ledgers ranges from -1.4% to +0.04%, and `check` output is byte-identical on all seven. Tests: - A regression table of three shapes under Strict, Fifo, Lifo and Average, every case failing on main, plus the original seed. - A focused agreement property with small lots, committed ignored: it still finds two older disagreements, filed as #2378. - Loader tests driving both ledgers through the whole pipeline, checked to fail with the validator change reverted. - `apply_precondition_test` pinned `+10`/`-20` as an error. That was the bug; it now expects the short, and a new test keeps the rollback guarantee with a reduction that fails after an earlier one changed state. Closes #2368 Refs #2378 Co-Authored-By: Claude Opus 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! |
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 of #2379 found the cost-less fast path wrong. It added a cost-less posting at once, before later reductions in the same transaction, on the argument that a cost-less position is invisible to them. It is invisible to the classification, but not to execution: `AVERAGE` pools every position of the currency, cost-less ones included. Holding 10 X {100}, a transaction of `+10 X` then `-4 X {}` left the engine at 16 @ 50 where `book` (and main) have 6 @ 100 beside 10 cost-less, and the next sale booked at 50 instead of 37.50. The shortcut now applies only when no posting in the transaction carries a cost spec. Then nothing can reduce and textual order is `book`'s order. The validator's pass takes the same narrower shortcut. A loader test reads the pool back through a later sale, and fails on the previous head (50 vs 37.50). Also restores the comment explaining where commit and compaction happen, which the rewrite dropped, and renames the validator helper to `add_posting`. Callgrind against main: simple -1.28%, money +0.42%, erc20 +0.34%, fifo +0.46%, investment +0.05%; `check` output byte-identical on seven ledgers. Refs #2368, #2380 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Member
Author
Deep review (head 3a809a2)Verdict: ready once CI is green. Review found one real bug, which is fixed in 3a809a2, and one pre-existing gap, now filed as #2380. Fixed in this PR
Pre-existing, not in scope
Checked and fine
Evidence at this head
|
This was referenced Sep 21, 2026
robcohen
added a commit
that referenced
this pull request
Sep 22, 2026
…#2385) * fix(booking): drop lots netted to zero, and sell an undated pool last Two ways `book` and `apply` still disagreed after #2368, both found by the small-lot agreement property committed ignored in #2379. 1. A short and a buy-back of the same lot in one transaction netted the lot to zero units, and the lot stayed. The sign counts put zero in the positive bucket, so it still counted as a holding: the next sale read as reducing it and failed with `No matching lot`. This was not AVERAGE-only; plain STRICT and FIFO ledgers that beancount accepts failed (`-5 X {100}`, `+5 X {100}`, then `-1 X {100}`, where beancount holds -1 X {100}), and `report balances` listed an empty `0 X {100 USD}` lot. A zero-unit lot is now in no sign bucket, in the counts and in the scan they are checked against. `add` also removes a cost-bearing lot it nets to zero, as beancount does, on the owned backing only: a cost-less position has always stayed at zero and been hidden by consumers, and BQL's shared running `balance` nets a lot to zero on every full-lot sale, where removal would shift every later slot. Two core tests that pinned "left at zero rather than removed" now expect removal. 2. A `{*}` merge leaves its pool undated, which `report capgains` documents as an unknown holding period. When STRICT later sells every lot at that cost, `book` splits the sale per lot, and the pool's spec carries no date, which as a filter matches any date, so `apply` saw two candidates and refused with `AmbiguousMatch`. STRICT expansions now put an undated lot's posting last; by then the dated lots at that cost are gone. The other methods re-select with the ordering `book` used and keep their order. The property now runs un-ignored, and a regression test replays both cases; each fails with its own fix reverted. The BALANCES-vs-report drift guard gains the net-to-zero ledger. `check`, `BALANCES` and `report balances` output is byte-identical to main on seven benchmark ledgers; `compat-booking-fuzz` agrees 300/300; callgrind on `check` is +0.01% to +0.31%. A third divergence surfaced by the same differential run is pre-existing and separate: #2384. Closes #2378 Refs #2384 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * test(core): pin that a shared store keeps a zero-netted lot Review of #2385: the one mutant the core gate missed in this PR's lines was `PositionStore::is_owned -> true`, i.e. nothing noticed if a zero-netted lot were also removed from a `Shared` store. That exclusion is load-bearing: removing from an imbl `Vector` shifts every later slot while `cost_index` still names the old ones, so the next buy of the lot that moved misses it and opens a second lot. The new test fails under that mutant. Refs #2378 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * fix(booking): move an undated lot only past a dated lot at its cost Second review of #2385. Putting every undated lot last in a STRICT expansion also reordered sales that never collided: with a `{*}` pool at 110 and a lot at 130, a STRICT `{}` sale of both applied on main, and the PR moved the pool's posting after the 130 lot, changing the booked posting order (and so `print` output and any pinned `meta.hash`) of a ledger that was already valid. The undated lot now moves only when a dated lot shares its cost, and only to just after the last one: the only lots its wildcard date can collide with. Every expansion main could apply keeps its exact order. Unit test covers the three shapes; the #2378 regression still fails with the call disabled. Also checked in this pass: 12 report subcommands on 7 ledgers are identical to main except the ledger main refuses; `CapitalGain` carries no posting index, so posting order cannot attach a gain to the wrong posting. Refs #2378 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * test(booking): pin that FIFO keeps an undated pool where it consumed it Third review of #2385. The CI mutation gate covers rustledger-core only, so the new booking helper was mutation-tested locally: 10 of 11 mutants caught, 1 timeout (an infinite loop, caught), and the one miss, `i + 1` -> `i * 1`, is equivalent (the search then includes `i`, which the undated check excludes). The STRICT gate at the call site had no test: widening it to every method passed the suite, although it reorders FIFO's booked postings (FIFO sells the pool first). The new test fails under that change. Refs #2378 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This was referenced Sep 22, 2026
robcohen
added a commit
that referenced
this pull request
Sep 23, 2026
* fix(core): a cost spec, even {}, matches only lots held at cost
`Position::matches_cost_spec` let an empty spec match a position held
without a cost (`(None, true) => true`), a rule from the initial release
with no recorded reason. So on an account holding a commodity both at cost
and without one, a `{}` sale treated the cost-less units as sellable. Holding
10 X at 100 and 10 X that arrived with no cost, `-4 X {}` booked under
AVERAGE at 50 (the pool counted the cost-less units in its total but not its
cost; a gain of 240 instead of 40, and the remainder gave those units a cost
of 50), FIFO failed in interpolation, and STRICT reported an ambiguous match.
Beancount's reduction matching skips positions not held at cost and books
4 of the 100 lot.
- `matches_cost_spec`: a cost-less position never matches.
- `reduce_average`: the pool and the lots it replaces are cost-held lots on
the reduced side; cost-less units stay as they are.
- NONE booking still drains cost-less positions. It did so through `{}`
inside ordered selection; it now asks for them explicitly with a new
`LotScope::Any`, while every booking method uses `LotScope::CostHeld`.
`plan_ordered`/`reduce_ordered` keep their signatures as wrappers.
Tests that encoded the old rule:
- `removing_a_cost_less_lot_drops_its_index_entry` drained a cost-less lot
with STRICT `{}`; it now uses NONE, which reaches the same index path.
- The TLA+ `MultiCurrency` replay models cost-free units and reduced them
FIFO; the replayed lots now carry a nominal cost, which leaves the
per-currency unit invariant unchanged (10116 behaviors still replay).
- #2379's same-transaction AVERAGE test pinned the diluted 37.50; it is 100.
Five comments stated the old rule as the reason for code that remains (the
ordered index keeps cost-less lots and the slot-map clears stay, both for
NONE's drain); they now say so.
New: `costless_units_test` loads the issue's ledger under AVERAGE, FIFO,
LIFO, HIFO and STRICT and pins a sale of 4 at 100 with the cost-less units
untouched; it fails with the change reverted.
Verified: workspace suite green (168 binaries, all eight TLA+ replays run);
compat-booking-fuzz clean; the same-transaction beancount differential
unchanged; agreement properties clean over 100 runs; `check`, `BALANCES`
and `report capgains` byte-identical to main on eight benchmark ledgers
including an AVERAGE one; callgrind on `check` +0.00% to +0.08%. One
surviving in-diff mutant is equivalent (`* sign` vs `/ sign`, sign = +/-1).
Closes #2396
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
* fix(core): {*} merges only lots held at cost
Review of #2397. `plan_merge` builds its own candidate list rather than
calling `matches_cost_spec`, so `{*}` still merged cost-less units into its
pool: holding 10 X at 100 and 10 X with no cost, `-4 X {*}` merged to 20 at
50, realized 240, and left `16 X {50}`, on main and on the first head of
this PR. It now merges only cost-held lots, like every other method.
Every caller of `weighted_average_cost` now passes only cost-held lots:
`reduce_average`, `plan_merge`, and `merge_average` (which already
filtered). `book`'s `{*}` preview, `apply`'s precondition and the merge all
use `plan_merge`, so they agree.
`costless_units_test` gains the `{*}` case. Its first version wrote `{}`
for every case (an unused `spec` variable, caught by the compiler warning),
so it was fixed before it counted; the `{*}` case now fails with the filter
removed.
Refs #2396
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
* test(loader): a sale larger than the cost-held lots is refused
Second review of #2397. The one change that can make a previously loading
ledger fail was untested and undocumented: holding 10 X at 100 and 10 X
with no cost, `-15 X {}` under AVERAGE loaded on main (15 sold from a pool
of 20 at 50) and is now refused as insufficient, because 5 of those units
have no basis. Beancount refuses it (`Not enough lots to reduce`). FIFO,
LIFO and STRICT already refused it on main, but as an interpolation failure
or an ambiguous match; the reason is now the right one.
`a_sale_larger_than_the_cost_held_lots_is_refused` pins it for AVERAGE,
FIFO, LIFO and STRICT and fails with the core change reverted (AVERAGE
accepts). The CHANGELOG entry now names it.
Also mapped on the issue's ledger: LIFO and HIFO are unchanged (the
cost-held lot already sorted first); STRICT_WITH_SIZE, refused on main as
ambiguous, now books 4 at 100.
Refs #2396
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]>
robcohen
added a commit
that referenced
this pull request
Sep 23, 2026
…#2399) * fix(parser): a `*` that begins any cost component is the merge marker Beancount's grammar takes a cost as a comma-separated list of components (number, currency, date, label, `*`), and `*` may be any of them: `{100.00 USD, *}`, `{2020-01-01, *}` and `{*, 100.00 USD}` all set merge (checked against beancount 3.2.3's parser, which reaches its "Cost merging is not supported yet" action for each). `MergeFlag` decided the flag from the first token after the opener only, so a trailing `*` parsed as a plain per-unit spec, with no diagnostic: `-5 X {110.00 USD, *}` failed with `No matching lot`, and `-5 X {100.00 USD, *}` silently sold from the lot at 100 instead of the merged pool. The rule is now: a `*` is the merge marker when the previous non-whitespace token is the opener or a comma, i.e. when it begins a component. A `*` after a number or `)` is still multiplication (`{500 * 2 USD}`). `MergeFlag` is the one machine both the green and red walkers feed, so both change together; the test that pinned `{2 USD, *}` as not-merge now pins it as a merge, with rows for the other positions, and the red-tree accessor test gains the trailing form. `rledger format` round-trips every form unchanged. Caches: parser output changes, so loader CACHE_VERSION goes to 36 and the wasm cache to 24 (with its loader pin). The wasm cache archives BOOKED directives and errors, and the booking fixes merged since v23 (#2379, #2385, #2391, #2395, #2397) each changed those without a bump, so a v23 blob could serve their pre-fix answers; v24 covers them too. The CostNumber and MetaValue byte-layout tripwires still compare their bytes; only their FIXTURE_VERSION moves. Not changed: a number in a merge spec is ignored, for the leading form as it always was and now for the trailing one (#2398). Tests: the MergeFlag row test and the ast accessor test; a loader test that `{*}`, `{110.00 USD, *}` and `{100.00 USD, *}` all book from the merged pool at 110, which fails on main's parser. Workspace suite green (169 binaries); `check` byte-identical to main on four benchmarks; callgrind -0.03% to +0.004%. Closes #2329 Refs #2398 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * test(parser): pin that MergeFlag ignores a comma before, or a brace after, the opener Review of #2399. `cargo mutants --in-diff` (the CI mutation gate covers rustledger-core only, not the parser) left the two `past_opener` guards alive: flipping either let a comma before the opener, or a second `{` on malformed input, arm a component start, so `, * {...` or `{2 USD {*` would read as a merge. Both are malformed-input paths the doc comment promises to ignore; two direct-feed assertions now pin them, and all 11 in-diff mutants are caught. Also checked in review: - Only `merge` changes. Parsing 18 shapes with main's and this branch's parser gives identical number, currency, date and label for every one (compound `#` and total `{{}}` included); a missing comma (`{100 USD *}`) is still a parse error, as in beancount. - No other code re-derives the merge flag; `Amount::is_arithmetic` sees the posting's amount node, never a cost spec's tokens. - A trailing `*` on a buy books the same lot as before, as the leading form always has. Refs #2329 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]>
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.
What
BookingEngine::applyand the validator's inventory pass now walk a transaction the waybookread it: each reduction applied as it is reached, every augmentation after the walk.Why
bookclassifies each posting against the pre-transaction inventory threaded with that transaction's earlier reductions only.applyordered postings by a pre-transaction classification and then let each re-ask live state; the validator added each posting as it went. Once a sale exhausts a lot and opens a short, a later posting reads as a reductionbooknever made:+10 X {100},-20 X {100}in one txnNot enough units+9 {101},-2 {100},-2 {100}No matching lotFixing only
applystill leftrledger checkrejecting both, becauseupdate_inventorieshad the same bug independently. Both sites now name each other.When no posting in a transaction carries a cost spec, nothing can reduce, so postings are added as they come and the second pass is skipped. The shortcut is deliberately no wider: a cost-less position does not affect classification, but
AVERAGEpools it, so a cost-less buy ahead of anAVERAGEsale must still wait (review found the wider version wrong;a_cost_less_buy_does_not_join_an_average_sale_in_its_own_transactionpins it).Evidence
compat-booking-fuzz.pyagrees 400/400 on both (it does not generate this shape).checkoutput byte-identical on seven benchmark ledgers.cargo test --all-featuresgreen; clippy andcargo doc -D warningsclean.Tests
a_transaction_that_sells_past_a_lot_applies_as_it_booked: 3 shapes × Strict/Fifo/Lifo/Average; all 12 fail on main. Plus the [Booking]: book accepts transactions apply refuses (intermittent book_apply_agreement failure; deterministic seed) #2368 seed.same_transaction_short_test.rs(loader): both ledgers through the full pipeline, holdings asserted (fails with the validator change reverted); plus the AVERAGE cost-less case, read back through a later sale's booked cost (fails on the first head, 50 vs 37.50).the_engine_agrees_when_a_transaction_exhausts_a_lot: the agreement property with small lots, committed#[ignore]. It still finds two older disagreements, filed as [Booking]: two more book/apply disagreements behind #2368: an undated merged lot, and AVERAGE zero/cost-less lots #2378 (still reproduced on its seed with this PR).apply_precondition_test: the old test asserted+10/-20is an error, which was this bug. It now expects the short; a new test keeps the rollback guarantee with a second reduction failing after the first changed state.Not in this PR
The BQL executor replays postings one at a time too, so
BALANCESstill fails on both ledgers above (as on main). Fixing it needs a decision about what the per-postingaccount_balancecolumn shows partway through a transaction: #2380.Closes #2368
Refs #2378, #2380
🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr