Skip to content

fix(booking): a cost matching only its own side adds to that side - #2391

Merged
robcohen merged 5 commits into
mainfrom
fix/same-sign-cost-match-2384
Sep 22, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/same-sign-cost-match-2384

Conversation

@robcohen

@robcohen robcohen commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

What

A cost-bearing posting is now an augmentation when its cost spec matches none of the opposite-sign lots but does match a lot of its own sign. Otherwise the reduction rule is unchanged.

Holding Posting beancount main this PR
short -2 {101}, long 5 {102} +3 {102} accepts: 8 {102, 01-01} (backdated) No matching lot new lot 3 {102, 01-05}
long 5 {102}, short -2 {101} -1 {101} accepts, backdated No matching lot new lot -1 {101, 01-05}
long 10 {100} -5 {101} (typo) No position matches No matching lot No matching lot (unchanged)
short -2 {101} only +3 {102} No position matches No matching lot No matching lot (unchanged)
long 10 {100}, short -2 {101} -1 {2020-01-09} (date typo) No position matches No matching lot No matching lot (unchanged)

How

  • Inventory::is_booking_reduction, the one predicate book, apply, the validator and the query replay share, gains the exception.
  • Only a spec that names a per-unit cost qualifies. That cost is what identifies "the own side". A spec of only a date or label would match every own-side lot once those are set aside, so a mistyped lot date could open a position; review caught this (e6c2771).
  • The two sides are matched differently. Against the opposite side the spec is a reduction filter, date and label included. Against the own side it is an augmentation, whose date is an acquisition date, so only the cost is compared. Booking fills that date in, and apply asks the question again of the booked posting. The first version compared the date too and failed exactly there; review caught it, and two tests now pin it.
  • Cost. One cached lookup answers both "any opposite lot?" and "any own-sign lot?". An account holding one side never scans. Callgrind on check is +0.01% to +0.27%.
  • book classifies with the cost currency it will book with. A spec without one, {102}, is otherwise a wildcard at classification and a fixed currency by the time apply asks again (inferred_cost_currency, shared with the augmentation fill; review, dffb053).
  • book had two private copies of the rule (the classification, and the augmentation date fill). Both now call the canonical predicate.

Deliberately not beancount

Beancount's lot matching ignores sign. It merges the units into the same-sign lot, backdating them to that lot's date, and refuses the posting when the quantity exceeds that lot (Not enough lots to reduce). Units and cost basis agree with beancount everywhere; the lot date and acceptance follow the posting instead.

Against beancount 3.2.3 on 2000 generated same-transaction ledgers: 1985 agree, 3 differ in lot date only, and 12 are ledgers beancount refuses with Not enough lots to reduce. None differ in units or cost.

Evidence

  • Core: a_cost_matching_only_its_own_side_is_an_augmentation covers each shape, the booked form with its filled-in date, a spec matching both sides, {}, and NONE.
  • Loader: mixed_sign_holdings_test.rs covers both ledgers with their holdings and dates, and a mistyped cost still refused.
  • Agreement: a_buy_at_a_long_side_cost_applies_as_it_booked_beside_a_short checks that book and apply agree end to end. The property alone can't reach this, because it skips anything book refuses.
  • Dirty checks. With the own-side match reverted to the full spec (the first version), the core test and the agreement test fail. With the rule removed, both loader acceptance tests and the agreement test fail.
  • Workspace suite green; clippy and rustdoc clean. compat-booking-fuzz 300/300; agreement properties clean over 100 fresh runs. check and BALANCES output byte-identical to main on seven benchmark ledgers.

Follow-up

This PR is the third time a rule re-asked of the booked posting has disagreed with book, after #2368 and #2378. #2390 proposes recording book's decision on each posting instead of re-deriving it.

Closes #2384
Refs #2390

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

Whether a cost-bearing posting reduces was decided by the currency alone: any
opposite-sign lot made it a reduction, which then found no lot its cost named
on that side and failed. Holding a short at 101 and a long at 102,
`+3 X {102 USD}` was refused with `No matching lot`; beancount accepts it.

`Inventory::is_booking_reduction` now treats a spec that matches none of the
opposite-sign lots but does match an own-sign lot as an augmentation: a new
lot at the transaction date. A spec that matches nothing is still a reduction
and still fails, so a mistyped cost is still caught, as beancount catches it.
Gated on the cached sign counts, so an account holding one side never scans.

The two sides are matched differently. Against the opposite side the spec is
a reduction filter, date and label included. Against the own side it is an
augmentation, whose date is an acquisition date, so only the cost is compared.
The first version compared the date too: `book` booked `{102}` as `{102 USD,
<txn date>}`, `apply` asked again of that, the date matched no lot, and the
booked augmentation read as a failed reduction. Caught in review; a core test
and an agreement test now fail on that version.

`book` held two private copies of the rule (the classification and the
augmentation date fill); both now call the canonical predicate, like `apply`,
the validator and the query replay.

Deliberately not beancount's result. Its lot matching ignores sign, so it
merges the units into the same-sign lot and backdates them to that lot's
date, and refuses the posting when the quantity exceeds that lot. Against
beancount on 2000 generated same-transaction ledgers: 1985 agree, 3 differ
in lot date only, 12 are ledgers beancount refuses with `Not enough lots to
reduce`; none differ in units or cost.

Also: compat-booking-fuzz 300/300; the book/apply agreement properties 100
fresh runs clean; `check` and `BALANCES` byte-identical to main on seven
benchmark ledgers; callgrind on `check` +0.01% to +0.21%.

Closes #2384
Refs #2390

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 14:18
@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 44.9ms ± 0.6ms 846.6ms ± 12.1ms 18.8x 50.9 MB / 50.1 MB
investment 70.4ms ± 1.2ms 3133.3ms ± 39.7ms 44.5x 57.1 MB / 58.2 MB
fifo 69.0ms ± 1.1ms 15743.0ms ± 148.6ms 228.2x 56.9 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 44.9ms ± 0.5ms 44.9ms ± 0.6ms +0.1% ✅ within noise 50.8 MB → 50.9 MB (+0.1%)
investment 69.8ms ± 1.2ms 70.4ms ± 1.2ms +0.8% ✅ within noise 55.1 MB → 57.1 MB (+3.5%)
fifo 67.0ms ± 1.1ms 69.0ms ± 1.1ms +3.0% ✅ within noise 57.1 MB → 56.9 MB (-0.4%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.4ms, investment 0.8ms, fifo 0.7ms), 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 #2391. The own side is matched on cost alone, with the spec's date
and label set aside. A spec with no cost, only a date or a label, then has
nothing left to compare and matches every own-side lot. On an account holding
a long at 100 and a short at 101, a sale written `-1 X {2020-01-09}`, naming
a lot date nothing has, booked as a new short lot dated with the typo when the
cash leg implied 101. Beancount refuses it, and so did main.

The exception now needs a per-unit cost in the spec. That cost is what says
"the own side"; without it the posting stays a reduction and still fails.
Core and loader tests fail with the guard removed. The beancount
differential, fuzz and agreement results are unchanged (the generator only
writes numbered costs or `{}`).

Refs #2384

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 4e7d044, four passes)

Verdict: ready once CI is green. Two real defects found and fixed (e6c2771, dffb053), plus three test gaps closed.

Found: a mistyped lot date could open a position (fixed)

The own side is matched on cost alone, with date and label set aside, because on the own side the date is an acquisition date. A spec with no cost (only a date or label) then has nothing left to compare and matches every own-side lot:

2020-01-01 * "a long at 100 and a short at 101"
  Assets:Stock  10 X {100 USD}
  Assets:Stock  -2 X {101 USD}
  Assets:Cash  -798 USD
2020-01-05 * "sell 1, naming a lot date nothing has"
  Assets:Stock  -1 X {2020-01-09}
  Assets:Cash   101 USD

Beancount and main refuse this. At c905c0d it booked -1 X {101 USD, 2020-01-09}, a new short dated with the typo. With a cash leg implying 100 instead, it failed, but only by accident. The exception now requires a per-unit cost in the spec. a_mistyped_lot_date_still_fails_on_a_mixed_account and the date-only/label-only assertions in the core test fail with the guard removed.

Found (second pass): a currency-less cost spec could make book and apply disagree (fixed)

{102} with no currency is booked with one inferred from the price or the other postings, and apply asks again of the booked {102 USD}. book asked of {102}, where a missing currency matches any. Holding a long at 102 EUR and a short at 101 USD, it took the EUR lot as the own side and booked an augmentation, which apply then refused. Beancount refuses this ledger too, so the outcome was right, but only because apply refused what book had accepted.

book now classifies with the currency the augmentation branch fills in, through one shared inferred_cost_currency. The reduction match still uses the spec as written. cost_currency_inference_agreement pins both directions: EUR → refused by book; USD → accepted by both. With the change reverted it fails as (book accepts, apply refuses).

This is the same class as the date issue: booking rewrites the posting between the two askings. #2390 would remove the class.

Mutation testing on the diff (cargo mutants --in-diff)

31 mutants: 24 caught, 1 unviable, 6 missed. It first found three real gaps in the own-side match, now covered in the core test:

  • a label on the buy is not compared, like its date;
  • a lot of another commodity at the same cost is not the own side;
  • a lot netted to zero, which a shared store keeps, is not the own side.

The six left are equivalent or performance-only. The five sign-count guard mutants in the fused lookup only decide whether the own-side scan runs, and the scan gives the same answer. The date-fill site's currency only decides when an augmentation's date is filled, not what the date is.

Checked and fine

  • The fused lookup keeps both paths: a cached (opposite, own) pair, and the scan when the cache is unbuilt. The debug assertion still ties the counts to is_reduced_by_scan, and a currency absent from a non-empty cache answers (false, false).
  • The other shapes of cost spec:
    • {} matches the opposite side, so it reduces.
    • {*} is excluded.
    • {{T}} has no per-unit cost, so it reduces, as before.
    • A buy naming cost plus date (+3 {102, 2020-01-03}) is an augmentation carrying that acquisition date. That is how a date works on any buy.
  • All four consumers ask one predicate. book (both former private copies), apply, the validator and the query replay call is_booking_reduction. Beyond the two dirty-checked cases, the agreement properties stay clean over 100 fresh runs.
  • Unaffected paths: single-sided accounts never scan; check output is byte-identical to main on seven benchmark ledgers. Callgrind on check is +0.01% to +0.27%. The second-pass currency fix first cost +0.17% because every {} sale ran the inference; f1de637 skips specs that name no per-unit cost or already carry a currency.

Third pass: documentation

The PR adds a deliberate difference from beancount, so 4e7d044 records it in both lists the project keeps: docs/reference/compatibility.md §14, with a worked example and both engines' holdings, and the migration guide's known differences. No doc stated the old per-currency rule, and the TLA+ specs model reductions without the classification step, so neither went stale. In passing: the migration list and compat-booking-fuzz.py still describe #2118 as open (#2392).

Fourth pass: correctness on mixed accounts (no change to this PR)

Divergence from beancount, re-measured at this head

Across 2000 generated same-transaction ledgers: 1985 agree, 3 differ in lot date only (beancount backdates into the existing lot), and 12 are ledgers beancount refuses with Not enough lots to reduce (its sign-blind matching treats adding to a short as reducing it). 0 differ in units or cost. The generator writes only numbered costs or {}, so the new guard does not change these numbers. The date-typo shape above is covered by its own test.

robcohen and others added 2 commits September 22, 2026 15:02
Second review of #2391. A cost spec written without a currency, `{102}`, is
booked with one inferred from the price or the other postings, and `apply`
then asks its question of the booked `{102 USD}`. `book` asked of `{102}`,
where a missing currency matches any: holding a long at 102 EUR and a short
at 101 USD, it matched the EUR lot as the posting's own side, booked an
augmentation, and `apply` refused it. The ledger was refused either way, as
beancount refuses it, but by `apply` after `book` accepted.

`book` now classifies with the currency the augmentation branch fills in,
through one `inferred_cost_currency` shared by both; the reduction match
itself still uses the spec as written. `cost_currency_inference_agreement`
pins both directions and fails with the classification reverted: book
accepts, apply refuses.

Mutation testing on the PR's lines (`cargo mutants --in-diff`) also found
three untested conditions in the own-side match: a label on the buy, a lot of
another commodity at the same cost, and a lot netted to zero. The core test
now covers each. The remaining survivors are equivalent or performance-only:
the fused sign-count guards only decide whether the own-side scan runs, and
the date-fill site's currency only decides when an augmentation's date is
filled, not what it is.

Refs #2384

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…use it

Classifying with the inferred cost currency cost +0.13 to +0.17% on `check`:
the benchmark ledgers sell with `{}`, which has no currency, so every sale
ran the inference and cloned its spec, and the augmentation date fill cloned
the spec for every cost-bearing buy. A spec naming no per-unit cost never
reaches the own-side rule, and a spec that already has a currency needs no
filling, so both now skip it. Callgrind on `check` vs main: +0.01% to +0.27%.

Refs #2384

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Third review of #2391. The PR adds a deliberate difference from Python
beancount (a new lot at the transaction date where beancount merges and
backdates, and acceptance regardless of quantity where beancount refuses one
larger than the matched lot), and the project keeps two lists of those. Adds
it to both: a worked example with both engines' holdings in the compatibility
reference, and a short entry in the migration guide's known differences.

Also checked: no doc states the old per-currency reduction rule, and the TLA+
specs model reductions without the classification step, so neither is stale.
Found in passing: the same migration list still describes #2118 as open
(#2392).

Refs #2384

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit 6f72d84 into main Sep 22, 2026
70 of 71 checks passed
@robcohen
robcohen deleted the fix/same-sign-cost-match-2384 branch September 22, 2026 16:44
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 posting is classed as a reduction by an opposite-sign lot its cost spec cannot match: No matching lot on a ledger beancount accepts

1 participant