Repository navigation
fix(core): a cost spec, even {}, matches only lots held at cost - #2397
Conversation
`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
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 |
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
Deep review (head 97853b6, two passes)Verdict: ready once CI is green. One defect fixed (3225c7c), and one undocumented behavior change pinned and documented (97853b6). Found:
|
| sale | method | main | this PR | beancount |
|---|---|---|---|---|
-4 X {} |
AVERAGE | 4 at 50, gain 240 | 4 at 100, gain 40 | (no AVERAGE) |
-4 X {*} |
STRICT | merged 20 at 50, gain 240 | 4 at 100 | — |
-4 X {} |
FIFO / STRICT / STRICT_WITH_SIZE | refused | 4 at 100 | 4 at 100 |
-4 X {} |
LIFO / HIFO | 4 at 100 | unchanged | 4 at 100 |
-15 X {} |
AVERAGE | accepted, 15 at 50 | refused: requested 15, available 10 | (no AVERAGE) |
-15 X {} |
FIFO / LIFO / STRICT | refused (interpolation / ambiguous) | refused: requested 15, available 10 | Not enough lots to reduce |
The last-but-one row is the only case where a ledger that loaded on main now fails. The refusal is correct: 5 of the 15 units have no basis. It was untested and unmentioned; a_sale_larger_than_the_cost_held_lots_is_refused now pins it (and fails with the core change reverted), and the CHANGELOG and PR body name it. No row goes from right to wrong.
Evidence at this head
- Workspace suite green (169 binaries), clippy clean, agreement properties clean over 100 fresh runs.
cargo mutants --in-diff: 12 caught, 20 unviable, 1 missed. The miss is equivalent:available * sign→/ signinreduce_none, where sign is ±1.- From the first head, unaffected by this change: beancount fuzz and differential clean;
check,BALANCESandreport capgainsbyte-identical to main on eight benchmarks; callgrind +0.00% to +0.08%.
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
…#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]>
What
A cost spec, even
{}, now matches only positions held at cost, and AVERAGE pools only cost-held lots. Units of a commodity held without a cost are never sold by a cost-spec reduction; they stay as they are.Why
matches_cost_speclet{}match a cost-less position ((None, true) => true, a rule from the initial release with no recorded reason). On an account holding a commodity both ways, the same ledger went wrong three different ways:16 X {50}(the cost-less units given a cost of 50)6 X {100}+10 X-4 X {100}-4 X {100}-4 X {100}-4 X {100}A cost-less position has no basis, so selling it at cost, or averaging it in as zero-cost, invents a basis and a gain. This is also beancount's rule: its reduction matching skips positions not held at cost. So the fix is both more correct and closer to beancount.
How
Position::matches_cost_spec: a cost-less position never matches.reduce_average: the pool, and the lots it replaces, are the cost-held lots on the reduced side.plan_merge({*}): the same. It builds its own candidate list, so it needed its own filter. Review caught that{*}still merged cost-less units (20 at 50, gain 240).{}; it now asks explicitly via a newLotScope::Anyin ordered selection, while every booking method usesLotScope::CostHeld.plan_ordered/reduce_orderedkeep their signatures as wrappers.Tests that encoded the old rule
removing_a_cost_less_lot_drops_its_index_entrydrained a cost-less lot with STRICT{}. It now uses NONE, which reaches the same index path.MultiCurrencyreplay: the model's units have no cost, and the replay reduced them FIFO. Replayed lots now carry a nominal cost, and the per-currency unit invariant is unchanged; all 10,116 behaviors still replay.Evidence
costless_units_test: the issue's ledger under AVERAGE, FIFO, LIFO, HIFO, STRICT, and STRICT with{*}. Each sells 4 at 100 and leaves the cost-less units untouched. It fails with the change reverted.compat-booking-fuzzclean. The same-transaction beancount differential is unchanged (0 units-or-cost differences). Agreement properties clean over 100 runs.check,BALANCESandreport capgainsbyte-identical to main on eight benchmark ledgers, including an AVERAGE one.check: +0.00% to +0.08%.cargo mutants --in-diff: 11 caught, 19 unviable, 1 missed. The miss is equivalent:available * sign→/ sign, with sign ±1.Behavior changes (review, second pass):
Not enough units: requested 15, available 10) instead of being filled from units with no basis. Under AVERAGE, main accepted it (15 sold at 50), so an AVERAGE ledger that loaded on main can now fail. Beancount refuses it too (Not enough lots to reduce). FIFO, LIFO and STRICT refused it on main already, but with misleading messages (interpolation failure, ambiguous match). Pinned bya_sale_larger_than_the_cost_held_lots_is_refused.Closes #2396
🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr