Skip to content

fix(core): a cost spec, even {}, matches only lots held at cost - #2397

Merged
robcohen merged 3 commits into
mainfrom
fix/costless-lots-not-reduced-2396
Sep 23, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/costless-lots-not-reduced-2396

Conversation

@robcohen

@robcohen robcohen commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

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_spec let {} 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:

2020-01-02 * "buy 10 at 100"
  Assets:Stock  10 X {100 USD}
  Assets:Cash  -1000 USD
2020-01-03 * "10 units arrive with no cost stated"
  Assets:Stock   10 X
  Equity:Transfer
2020-01-04 * "sell 4 at 110"
  Assets:Stock  -4 X {} @ 110 USD
  ...
method main beancount this PR
AVERAGE sale at 50, gain 240, holdings 16 X {50} (the cost-less units given a cost of 50) (no AVERAGE) sale at 100, gain 40, holdings 6 X {100} + 10 X
FIFO refused: interpolation failed -4 X {100} -4 X {100}
STRICT refused: ambiguous match -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).
  • NONE booking still drains cost-less positions. That is its job: no lot matching at all. It used to reach them through {}; it now asks explicitly via a new LotScope::Any in ordered selection, 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.
  • TLA+ MultiCurrency replay: 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.
  • fix(booking): apply a transaction in the order booking read it #2379's same-transaction AVERAGE test pinned the diluted 37.50. The correct value is 100.
  • Comments: five stated the old rule as the reason for code that stays (the ordered index keeps cost-less lots and the slot-map clears remain, both for NONE's drain); they now say so.

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.
  • Workspace suite green (168 binaries; all eight TLA+ replays run); clippy and rustdoc clean.
  • compat-booking-fuzz clean. The same-transaction beancount differential is unchanged (0 units-or-cost differences). Agreement properties clean over 100 runs.
  • Output identity: 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%.
  • 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):

  • AVERAGE cost basis and realized gains change for any account that also holds cost-less units of the commodity. Those numbers were wrong.
  • A sale larger than the lots held at cost is now refused (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 by a_sale_larger_than_the_cost_held_lots_is_refused.
  • LIFO and HIFO results on the issue's ledger are unchanged (the cost-held lot already sorted first); STRICT_WITH_SIZE, refused on main as ambiguous, now books.

Closes #2396

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`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
@robcohen
robcohen requested a review from a team as a code owner September 22, 2026 21:21
@codecov

codecov Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.05882% with 1 line in your changes missing coverage. Please review.

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

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: simple

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 30.0ms ± 4.9ms 400.3ms ± 5.2ms 13.4x 51.2 MB / 50.1 MB
investment 42.8ms ± 2.1ms 1554.6ms ± 27.8ms 36.3x 57.1 MB / 57.9 MB
fifo 40.4ms ± 1.0ms 8076.2ms ± 60.0ms 199.8x 57.1 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 27.6ms ± 0.3ms 30.0ms ± 4.9ms +8.5% 🟡 slower 51.2 MB → 51.2 MB (+0.1%)
investment 43.8ms ± 0.7ms 42.8ms ± 2.1ms -2.2% ✅ within noise 57.2 MB → 57.1 MB (-0.3%)
fifo 40.9ms ± 0.5ms 40.4ms ± 1.0ms -1.2% ✅ within noise 57.3 MB → 57.1 MB (-0.3%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 2.2ms, investment 1.0ms, 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

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
@robcohen

robcohen commented Sep 22, 2026 •

Copy link
Copy Markdown
Member Author

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: {*} still merged cost-less units (fixed)

plan_merge builds its own candidate list (currency, non-empty, opposite sign) instead of calling matches_cost_spec, so flipping that rule didn't reach it. 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}, identically on main and on the first head of this PR. It now merges only cost-held lots. costless_units_test gained the {*} case, which fails with the filter removed.

The test's first version of that case was vacuous. It wrote {} for every case (a spec variable left unused, flagged by the compiler warning), and was fixed before being counted.

Every path that pools or matches lots

  • matches_cost_spec is used by STRICT, STRICT_WITH_SIZE, and FIFO/LIFO/HIFO ordered selection. A cost-less position never matches.
  • weighted_average_cost callers: reduce_average and plan_merge now pass cost-held lots only; merge_average (the sum(position) view) already did.
  • Classification (is_reduced_by(.., CostBearingOnly)) and the fix(booking): a cost matching only its own side adds to that side #2391 own-side check already ignored cost-less lots, so a posting is now classified and executed on the same set.
  • book's {*} preview, apply's precondition (merged_pool_cost) and the merge itself all go through plan_merge, so they agree.
  • NONE's drain asks for cost-less lots explicitly (LotScope::Any); it's the only thing that does.

{*}'s cost-less fallback

When plan_merge finds no pool cost it falls back to reduce_average. With cost-held matching, that fallback is unreachable through booking, because a reduction requires an opposite lot held at cost. It stays in place for direct API callers of Inventory::reduce.

Second pass: what changes for existing ledgers

Mapped on the issue's ledger (10 X at 100 plus 10 X with no cost), main vs this PR:

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 → / sign in reduce_none, where sign is ±1.
  • From the first head, unaffected by this change: beancount fuzz and differential clean; check, BALANCES and report capgains byte-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
@robcohen
robcohen merged commit 5f7b026 into main Sep 23, 2026
70 of 71 checks passed
@robcohen
robcohen deleted the fix/costless-lots-not-reduced-2396 branch September 23, 2026 02:31
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]>
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.

A {} reduction draws on cost-less units of a cost-held commodity: AVERAGE dilutes the basis, FIFO and STRICT refuse

1 participant