Skip to content

fix(booking): drop lots netted to zero, and sell an undated pool last - #2385

Merged
robcohen merged 4 commits into
mainfrom
fix/book-apply-agreement-2378
Sep 22, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/book-apply-agreement-2378

Conversation

@robcohen

@robcohen robcohen commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

What

Fixes the two book/apply disagreements in #2378, and turns on the small-lot agreement property that found them (committed #[ignore]d in #2379).

1. A lot netted to zero kept counting as a holding

A short and a buy-back of the same lot in one transaction netted the lot to 0 units, and it stayed in the inventory. The sign counts put zero in the positive bucket, so the next sale read as a reduction of the empty lot and failed. Not AVERAGE-only: plain STRICT and FIFO ledgers beancount accepts were refused.

Ledger beancount main this PR
-5 X {100}, +5 X {100} (one txn), then -1 X {100} -1 X {100 USD} No matching lot -1 X {100 USD}
same, report balances 0 X {100} listed only -1 X {100}

2. An undated {*} pool beside a dated lot: AmbiguousMatch

A {*} merge leaves its pool undated. That is deliberate: report capgains documents a pooled lot's holding period as unknown, so dating the pool was ruled out. When STRICT later sells every lot at that cost, book splits the sale per lot. The pool's posting carries no date, which as a filter means "any date", so apply saw two candidates and refused.

In a STRICT expansion, an undated lot's posting now moves to just after the last dated lot at its cost, the only lots its wildcard date can collide with. By then those lots are gone, so it is the only candidate. This holds because a STRICT multi-lot match consumes every lot its spec matches, and any spec that matches the undated lot matches every lot at its cost. When no dated lot shares its cost, nothing moves, so every sale main could apply keeps its exact posting order (and any pinned meta.hash). FIFO, LIFO and HIFO re-select with the same ordering book used and are untouched.

On main this reaches rledger check: a {*} merge, a later buy at the pool's cost, then a STRICT sale of everything fails with Ambiguous lot match.

Evidence

  • the_engine_agrees_when_a_transaction_exhausts_a_lot is un-ignored (2048 cases): 30/30 fresh runs pass, where main failed 1 in 20.
  • the_disagreements_found_after_2368_apply_as_booked replays both [Booking]: two more book/apply disagreements behind #2368: an undated merged lot, and AVERAGE zero/cost-less lots #2378 cases. Each fails with only its own fix reverted: AmbiguousMatch, and journal -100 engine 0.
  • Drift guard (query_report_realization_parity_test) gains the net-to-zero ledger. Main refuses it.
  • Workspace cargo test --all-features green; clippy and cargo doc -D warnings clean.
  • 12 report subcommands on 7 ledgers are identical to main, except the net-to-zero ledger main refuses.
  • Output identity: check, BALANCES and report balances are byte-identical to main on seven benchmark ledgers.
  • compat-booking-fuzz.py: 300/300 agree with beancount.
  • Callgrind on check (mimalloc, cache off): simple +0.31%, money +0.12%, fifo +0.12%, investment +0.01%.

Not in this PR

A same-transaction differential against beancount (2000 STRICT/FIFO/LIFO ledgers) still disagrees on 3, where main disagrees on 4. All 3 are a separate, pre-existing class: a posting is classed as a reduction by an opposite-sign lot its cost spec cannot match. rledger refuses those ledgers, and beancount accepts them but backdates the new units. Filed as #2384.

Closes #2378
Refs #2384

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

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

codecov Bot commented Sep 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 43.9ms ± 0.8ms 785.8ms ± 7.6ms 17.9x 50.9 MB / 50.0 MB
investment 66.7ms ± 0.3ms 2957.9ms ± 30.5ms 44.4x 57.2 MB / 58.1 MB
fifo 64.0ms ± 0.5ms 15442.7ms ± 155.5ms 241.4x 57.1 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 43.8ms ± 0.4ms 43.9ms ± 0.8ms +0.3% ✅ within noise 51.0 MB → 50.9 MB (-0.3%)
investment 66.3ms ± 0.5ms 66.7ms ± 0.3ms +0.6% ✅ within noise 56.8 MB → 57.2 MB (+0.7%)
fifo 63.8ms ± 0.5ms 64.0ms ± 0.5ms +0.3% ✅ within noise 57.0 MB → 57.1 MB (+0.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.4ms, investment 0.3ms, fifo 0.3ms), 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 #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
@robcohen

robcohen commented Sep 22, 2026 •

Copy link
Copy Markdown
Member Author

Deep review (head b5cfe53, five passes)

Verdict: ready once CI is green. Three findings, all fixed: a core test gap (bcd0f13), an over-broad reorder (d2ce904), and an untested method gate (b5cfe53).

Zero-lot rule (core)

  • Only one production reader. Production reads the sign counts through ReductionScope::CostBearingOnly alone; AllPositions appears only in tests. Leaving zero lots out of the counts changes exactly one question: whether a posting is a reduction. Beancount never holds a zero position, so this matches its is_reduced_by.
  • Counts and scan agree. bump skips zero, is_reduced_by_scan skips zero, and the debug assertion that ties them together passes across the whole workspace suite.
  • Every path that zeroes a lot:
    • A reduction draining a lot now leaves its bucket on the drain (the old "move to positive" became "leave"); removal is then a no-op on the counts.
    • add netting to zero decrements the old bucket, and the zero result joins none.
    • The rebuild path skips zero.
  • Removal in add on the owned store:
    • cost_index_remove runs before remove, and set_dead records to the undo log.
    • rollback_undo rebuilds the indexes, so a rolled-back transaction restores the lot; the debug witness checks this.
    • Ordered selection skips tombstoned slots (positions.get(i) is None) and empty lots.
    • The tombstone can only appear in a transaction with a cost posting, which apply records and so compacts at commit.
  • What is not removed, and why:
    • Cost-less positions keep their long-standing stay-at-zero behavior; consumers hide them, and removing them would tombstone every cash account that passes zero.
    • Shared stores keep zero lots. This exclusion is load-bearing, and it was untested. The core mutation gate missed is_owned -> true on this PR's lines. Removing from an imbl Vector shifts later slots while cost_index still names the old ones, so the next buy of a lot that moved opens a second lot. a_shared_store_keeps_a_zero_lot_so_later_merges_still_land pins it and fails under that mutant. No other missed mutant falls on this PR's lines; the remaining ~200 are the crate's existing baseline.
  • Changed tests. Two core tests pinned "left at zero rather than removed" ([Compat]: rustledger keeps a slot per acquisition where beancount pools identical lots — FIFO/LIFO consume in different orders #2118). They were descriptions of the old behavior, not requirements, and now expect removal plus nothing reducible.

Undated pool (booking)

  • Why last-position is enough. A STRICT multi-lot match takes every lot its spec matches. Any spec that matches the undated pool matches every lot at its cost:

    • a date filter excludes the pool;
    • a label filter excludes it (pools carry none);
    • {{T}} matches on the per-unit cost.

    So once the dated postings have applied, the pool is the only candidate. Identical lots are one position since [Compat]: rustledger keeps a slot per acquisition where beancount pools identical lots — FIFO/LIFO consume in different orders #2118, so two lots can't tie on full identity.

  • Why the other methods don't need it. FIFO, LIFO and HIFO re-select with the ordering book used, so a wildcard date lands on the same lot. They keep their consumption order, so their capital-gains row order and posting order are unchanged.

  • It reaches check, not only the property. A ledger that merges with {*}, later buys at the pool's cost, then sells everything STRICT fails rledger check on main with Ambiguous lot match. With this PR it books, and report capgains shows the pool's units as unknown-term and the dated lot as long-term.

  • Second pass: the first version reordered more than it had to (fixed in d2ce904). Putting every undated lot last also moved postings in sales that could never collide. With a pool at 110 and a lot at 130, a STRICT {} sale of both applied on main, and the first version put the pool's posting after the 130 lot. That changes the booked posting order, and so print output and any pinned meta.hash, of a ledger that was already valid. Now an undated lot moves only when a dated lot shares its cost, and only to just after the last one. That ledger keeps main's order exactly. A unit test covers three shapes: no twin, a twin plus an unrelated lot, and already in order. The [Booking]: two more book/apply disagreements behind #2368: an undated merged lot, and AVERAGE zero/cost-less lots #2378 regression still fails with the call disabled.

  • Capital gains are unaffected by the reorder. CapitalGain carries no posting index, so a gain cannot be paired with the wrong posting.

Other consumers of add (second pass)

add backs every plain-add balance builder, not only booking. 12 report subcommands (balances, balsheet, income, journal, holdings, networth, accounts, commodities, stats, prices, returns, capgains) on 7 ledgers, including a full-lot sale and three benchmark shapes, are byte-identical to main. The one exception is the net-to-zero ledger, which main refuses.

Booking helper mutation-tested (third pass)

The CI mutation gate covers rustledger-core only, so I ran cargo-mutants locally on sell_undated_lots_after_their_dated_twins: 10 of 11 mutants caught, plus 1 timeout (an infinite loop, which counts as caught). The one miss, i + 1 → i * 1, is equivalent: the search then includes i, and the undated check excludes it.

The STRICT gate at the call site was untested. Widening it to every method passed the whole suite, yet it reorders FIFO's booked postings, since FIFO sells the pool first and apply agrees. fifo_keeps_an_undated_pool_where_it_consumed_it pins the order and fails under that change. LIFO and FIFO on the pool ledger book identically to main.

Remaining booking methods and the cache (fourth pass, no change needed)

  • STRICT_WITH_SIZE and HIFO: the pool ledger books identically to main. On the net-to-zero ledger, main refuses and this PR gives beancount's -1 X {100}, as it does for STRICT and FIFO.
  • NONE: on the net-to-zero ledger, main's check passed while BALANCES failed. It works here, but only incidentally.
  • Pre-existing, not addressed, and filed as Global option booking_method NONE is ignored when realizing balances: report balances and BALANCES fail on ledgers check accepts #2386. Realizing engines (report, BQL, wasm, LSP) never read the global option "booking_method", so a global-NONE ledger with a sale at an unheld cost fails report balances and BALANCES on main and on this PR. The per-account open ... "NONE" form works. It only surfaces under NONE, because every other method books concrete lots that a STRICT replay finds.
  • Parse cache: it stores parsed, pre-booking directives, so neither the posting-order change nor zero-lot removal needs a CACHE_VERSION bump.

Overflow headroom (fifth pass, no change needed)

SignCounts::by_sign also feeds add_headroom_for, which decides whether apply opens an undo log and must only ever err toward "cannot prove it". Leaving zero lots out keeps it sound:

  • With every nonzero lot on one sign, stats.total is the sum of their magnitudes and bounds each lot.
  • A zero lot as a merge target yields |needed|, which fits(total) already covers.
  • The mixed-sign refusal needs nonzero lots on both sides, which a zero lot never supplied.

The branch is current with main, and CI is green at this head apart from the always-red rustfava check.

Flake risk from un-ignoring the property

It now runs on every CI build with fresh seeds. A 300-run soak of the whole agreement suite (2048 cases per property per run) found 0 failures. The known #2384 class does not trip it, because there both book and apply refuse and the property skips unbookable transactions.

Evidence at this head

robcohen and others added 2 commits September 22, 2026 02:46
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
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
@robcohen
robcohen merged commit 33a5edc into main Sep 22, 2026
69 of 70 checks passed
@robcohen
robcohen deleted the fix/book-apply-agreement-2378 branch September 22, 2026 11:03
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.

[Booking]: two more book/apply disagreements behind #2368: an undated merged lot, and AVERAGE zero/cost-less lots

1 participant