Skip to content

fix(booking): carry {*} into application instead of resolving it away - #2069

Merged
robcohen merged 4 commits into
mainfrom
fix/carry-merge-into-apply
Aug 18, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/carry-merge-into-apply

Conversation

@robcohen

Copy link
Copy Markdown
Member

Fixes #2068.

The bug

{*} is the one cost spec that is an operation rather than a filter.

Every other spec — {100.00 USD}, {2024-01-01}, {"lot-a"} — selects among lots that already exist, so booking can resolve it into the single lot it picked and clear the spec. {*} merges the pool and only then reduces it.

Booking resolved {*} into the per-unit cost of the pool it would create and cleared the marker (merge: false). That names a lot which does not exist until the merge has run, so the application pass reported No matching lot for holdings the account plainly had:

2024-01-01 * "buy lot 1"
  Assets:Stock  10 X {100.00 USD}
  Assets:Cash  -1000.00 USD

2024-01-02 * "buy lot 2"
  Assets:Stock  10 X {120.00 USD}
  Assets:Cash  -1200.00 USD

2024-02-01 * "sell against the merged pool"
  Assets:Stock  -5 X {*}     ; booked to {110.00 USD} — a lot nobody holds
  Assets:Cash   600.00 USD
  Income:PnL

rledger check → No matching lot for X in Assets:Stock. beancount accepts this ledger.

The fix

The single-lot rewrite carries cost_spec.merge through, so application re-runs the merge rather than searching for its result. The account ends holding one merged pool at the weighted average (15 X @ 110), which is what {*} means.

reduce_merge returns a single synthetic matched position by design (its comment says so: expanding into one posting per original lot "would be incorrect for {*}"), so a {*} reduction can never reach the multi-lot expansion branch. This one site is the whole fix.

The cost of carrying an operation, and the check that pays it

A carried operation is only meaningful against the inventory it was booked against. Applied to different state it would silently build a different pool — the outcome this codebase treats as worse than any error.

So booking records the per-unit cost of the pool it computed, and apply_posting compares that against what the re-executed merge actually produced, reporting a new BookingError::MergeMismatch on a disagreement. A merge is now either the pool booking saw or a loud error; it is never a quietly different pool.

Verification

Three tests, each shown to be load-bearing by mutating the one changed line back to merge: false:

test crate catches
a_wildcard_merge_loads_without_errors loader the reported bug, end to end through load
a_wildcard_merge_books_and_applies_leaving_the_pool booking the engine holds exactly 15 X @ 110
a_merge_applied_against_different_inventory_is_reported booking the checksum fires when the pool moved

Reverting only merge: cost_spec.merge fails all three; disabling only the checksum fails the third alone. Both halves are independently necessary.

Gates: cargo test --workspace --all-features 143 suites green; cargo +1.97.0 clippy --workspace --all-features --all-targets -D warnings, cargo fmt --check, and RUSTDOCFLAGS=-D warnings cargo doc all clean.

Surfaces that see the flag

rledger format is source-faithful (unchanged), and BQL renders the resolved Cost from the inventory, not the CostSpec — so -5 X {110.00 USD}, no * leaking into user-facing output. The flag reaches only meta.hash and the FFI CostSpec passthrough, where carrying it is the more faithful representation. Any hash drift is confined to {*} ledgers, which today error out rather than load.

Not in scope

Whether an explicit {*} should realize the merged pool in reports (BQL still shows the journal view 10 X {120} 10 X {100} -5 X {110}, which nets to the same 15 X / 1650 USD) is ADR-0007 behaving as designed — realization keys off AVERAGE accounts. That is the separate question raised on #2068.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`{*}` is the one cost spec that is an OPERATION rather than a filter.
Every other spec selects among lots that already exist, so booking can
safely resolve it into the single lot it picked and clear the marker.
`{*}` merges the pool and only then reduces it, so resolving it into the
per-unit cost of the pool it created names a lot that does not exist
until the merge has run. The application pass then reported
`No matching lot` for holdings the account plainly had, and a ledger
beancount accepts failed `rledger check` (#2068).

The single-lot rewrite now carries `cost_spec.merge` through, so
application re-runs the merge rather than searching for its result.

Carrying an operation has one cost a filter does not: the booked posting
is only meaningful against the inventory it was booked against, and
applied to different state it would silently build a different pool.
Booking records the per-unit cost of the pool it computed, so
`apply_posting` compares that against what the re-executed merge
produced and reports the new `BookingError::MergeMismatch` on a
disagreement — a wrong pool is the outcome this codebase treats as worse
than any error.

`reduce_merge` returns a single synthetic matched position by design, so
the multi-lot expansion branch cannot see a `{*}` reduction; this one
site is the whole fix.

Fixes #2068

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner August 17, 2026 12:17
Copilot AI lite review requested due to automatic review settings August 17, 2026 12:17
@github-actions

github-actions Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 38.2ms ± 0.9ms 24 MB
beancount 900.4ms ± 3.7ms 50.7 MB
Comparison 23.6x faster 2.1x less

vs main branch (2026-08-17)

Metric main this PR Change
Time 38ms 38.2ms +0.5% ✅
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@codecov

codecov Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.29630% with 3 lines in your changes missing coverage. Please review.

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

📢 Thoughts on this report? Let us know!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes the two-phase booking/apply failure for the {*} cost-merge operator by preserving the merge operation into the application phase and adding a checksum-style guard to prevent silently re-merging against different inventory state.

Changes:

  • Carry CostSpec.merge through the single-lot rewrite so {*} is re-executed during apply instead of being resolved away.
  • Introduce BookingError::MergeMismatch and surface/classify it in validation as an inventory reduction failure.
  • Add end-to-end and engine-level tests covering successful {*} application and the mismatch guard.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
crates/rustledger-booking/src/book.rs Preserve {*} merge marker during booking and add apply-time merge checksum detection.
crates/rustledger-core/src/inventory/mod.rs Add MergeMismatch booking error variant and render it in Display.
crates/rustledger-validate/src/error.rs Map MergeMismatch to an error code (classified as NoMatchingLot).
crates/rustledger-validate/src/validators/transaction.rs Include MergeMismatch in reduction error context formatting.
crates/rustledger-loader/tests/wildcard_merge_test.rs New loader-level regression test ensuring {*} books and applies end-to-end.
crates/rustledger-booking/tests/apply_precondition_test.rs New booking tests for {*} success case and mismatch detection when inventory changes.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread crates/rustledger-booking/src/book.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 169 masked)
Full AST Match 100%
Total Files 812
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

The mismatch is detected after `reduce` has already merged and drained,
so it relies on `apply`'s undo log (#2067) to restore the lots. A
cost-bearing negative posting always opens one, but a half-merged
inventory is exactly the silent corruption the check exists to prevent,
so assert it rather than assume it. Mutating `has_reduction` to `false`
fails the new assertion.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

Copy link
Copy Markdown
Member Author

Added one more assertion after review of my own diff.

The mismatch is detected after reduce has already merged and drained the lots, so reporting it correctly depends on apply's undo log (#2067) putting the pool back. A cost-bearing negative posting always sets has_reduction, so the log is open — but a half-merged inventory is precisely the silent corruption this check exists to prevent, so the test now asserts all three lots survive unmerged and undrained rather than assuming it. Mutating has_reduction to false fails that assertion.

Two boundary cases worth recording, both erring toward not firing:

  • CostNumber::per_unit() returns None for Total and Compound, so a {{550.00 USD, *}} spec that booking did not rewrite skips the check rather than comparing against an effective per-unit it cannot know yet.
  • A raw, never-booked {*} reaching apply directly has number: None and also skips — nothing was recorded, so there is nothing to check against.

Decimal's PartialEq scale-aligns, so a recorded 110 and a produced 110.00 compare equal and do not false-fire.

robcohen and others added 2 commits August 17, 2026 14:32
Copilot's review caught two things on the checksum, and the second one
was hiding a false positive I had shipped.

`apply_posting` is not only `apply`'s inner loop — the query executor
calls it directly to replay a FILTERED transaction stream. There a
different pool is the CORRECT answer for the stream it was given, not
evidence of corruption, so the checksum aborted any query whose FROM
filter excluded one of the merged lots:

  select account, account_balance from not (narration ~ 'lot 1')
  => evaluation error: {*} merge ... produced a pool cost of 120.00,
     but booking recorded 110.00

The check now lives in `apply`, which is the caller whose contract is
"reproduce booking's decision", and it runs BEFORE the merge mutates
anything rather than reporting after. That also answers the review's
other point: a precondition that reports post-mutation depends on
rollback to stay honest, and `apply_posting`'s own contract goes back to
"reduce only errors when the lot it would match is missing".

Knowing the pool without building it needs the selection half of
`reduce_merge` callable from `&self`, so `{*}` gets the plan/commit split
(#2061): `plan_merge` computes which lots merge and at what average,
`reduce_merge` commits it, and `merged_pool_cost` exposes the read-only
half. One implementation, two callers — perturbing the plan's pool fails
six `reduce_merge` tests, so the commit half really does consume it.

`MergeMismatch` now carries `Amount`s rather than bare decimals: the pool
cost is denominated in the COST currency, so `110.00 USD` where the
message previously read `110.00` next to a commodity named `X`.

Checked per posting rather than as a pre-pass over the transaction: an
earlier posting of the same transaction can legitimately change the pool
a later `{*}` sees.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Deep review of my own diff found three defects in the precondition, two
of them panics.

1. It fired on postings that never merge. `apply_posting` reduces only
   when `is_booking_reduction` says so; an augmentation carrying an
   explicit `{110.00 USD, *}` is ADDED, and comparing it against a pool
   it will not build rejected a valid posting. Now gated on the same
   canonical predicate, so the two cannot disagree.

2. Rejecting a `{*}` that CLOSES A SHORT panicked. A reduction is not
   the same thing as a negative posting — closing a short reduces
   cost-bearing lots with positive units. `rollback_needed` counts by
   sign (deliberately: reading current state to answer it caused the
   #2067 panic), so such a posting reached `apply`'s "the guard is
   unsound" assert with no undo log open. `has_reduction` now counts
   `{*}` postings in both directions: sign-independent, state-
   independent, and only `{*}` widens the gate, so the #1897 snapshot
   regression stays closed.

3. It rejected a buy and a `{*}` sale in ONE transaction. Booking books
   every posting against the inventory as it stood BEFORE the
   transaction; `apply` mutates sequentially. The earlier buy therefore
   moves the pool the sale meets, and the recorded cost is not
   comparable against it. The check now runs only for an account this
   transaction has not already touched — the state booking actually saw.

Also drops a stale doc header on `has_reduction` claiming it uses
`Inventory::is_booking_reduction`; it has not since #2067, and the
inline comment right below it explains why it must not.

Each fix has a test that fails without it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

Copy link
Copy Markdown
Member Author

Deep review of my own diff

Three defects, two of them panics. Each fix has a test that fails without it (6185248).

1. The check fired on postings that never merge. apply_posting reduces only when is_booking_reduction says so; an augmentation carrying an explicit {110.00 USD, *} is added. Comparing it against a pool it will not build rejected a valid posting. Now gated on that same canonical predicate.

2. Rejecting a {*} that closes a short panicked. A reduction is not the same thing as a negative posting — closing a short reduces cost-bearing lots with positive units. rollback_needed counts by sign (deliberately: reading current state to answer it is what caused the #2067 panic), so such a posting reached apply's "the guard is unsound" assert with no undo log open:

thread 'probe' panicked at book.rs:1084:
rollback_needed() returned false but posting application failed
({*} merge of X would produce a pool cost of 100 USD, but booking recorded 110 USD)

has_reduction now counts {*} postings in both directions — sign- and state-independent, and only {*} widens the gate, so #1897's snapshot regression stays closed.

3. It rejected a buy and a {*} sale in ONE transaction. Booking books every posting against the inventory as it stood before the transaction; apply mutates sequentially. The earlier buy legitimately moves the pool the sale meets. The check now runs only for an account the transaction has not already touched — the state booking actually saw.

One thing this PR does not fix

That third case exposes a book-vs-apply disagreement that is not merge-specific but is only observable through {*}:

2024-02-01 * "buy and merge-sell together"
  Assets:Stock   10 X {120.00 USD}
  Assets:Stock   -5 X {*}

Booking records the reduction at 100.00 (the pre-transaction pool), while the engine's inventory ends at 15 X @ 110 (the sequential pool). The journal view totals 1,700 USD of basis; the engine holds 1,650. Beancount's semantics book against the pre-transaction state, which suggests booking is right and apply merges too much.

I have left it alone rather than adjudicate it inside a bug fix — on main this ledger fails to load at all, so nothing regresses. Happy to file it as its own issue with this repro if you want it tracked.

Gates: 145 suites green, clippy/fmt/doc clean.

@robcohen

Copy link
Copy Markdown
Member Author

Filed the ordering divergence as #2070.

Worth noting what turned up while writing it up: it is not {*}-specific and not introduced by this PR. AVERAGE booking has the same shape and reproduces on main today with no {*} anywhere:

2024-02-01 * "buy then sell in ONE transaction"
  Assets:Stock   10 X {120.00 USD}
  Assets:Stock   -5 X {}

on an "AVERAGE" account — booked postings aggregate to 15 X {113.33 USD} (1,700 USD basis) while the engine inventory holds 15 X @ 110 (1,650). rledger check reports no errors either way.

Both mergers re-derive a pool from whatever the account holds when they run, so both see the lot an earlier posting of the same transaction added; booking saw only the pre-transaction state. Specs that name a concrete lot are unaffected.

@robcohen
robcohen merged commit ebfaa3d into main Aug 18, 2026
79 of 86 checks passed
@robcohen
robcohen deleted the fix/carry-merge-into-apply branch August 18, 2026 01:58
robcohen added a commit that referenced this pull request Aug 23, 2026
* test(compat): add a differential booking fuzzer

Booking decides WHICH lot a reduction consumes. Get it wrong and the
postings still balance, the count is still right and the error list is
still empty — the ledger is simply wrong about what you own and what you
gained. Example-based tests are worst at exactly that, and the fix log
shows it: five booking fixes in twenty commits (#2058, #2069, #2081,
#2093, #2099), each an ordering or lot-selection case nobody had written
a test for.

So this generates ledgers and compares BOOKED LOTS against Python
beancount — an independent implementation, not a restatement of our own
logic. For every account it compares full lot identity, (currency,
per-unit cost, cost currency, lot date) -> units, so consuming the wrong
lot at the same total value is still a failure. It also compares
ACCEPTANCE: a ledger one engine books and the other rejects is a
divergence even when no numbers differ, which is the shape of #2099.

It found a real divergence on its first campaign — 58/60 agreed, both
failures LIFO with same-date lots. Filed separately with a 12-line
reproduction.

Two things learned building it, both encoded in the script:

`cost(position)` is the wrong column to read. For a costless posting it
returns the units themselves, so a cash leg looks like it holds a cost
of 1. `cost_number` is per-unit and null when there is no cost, which is
what makes it the right discriminator. The first draft compared cash
legs against nothing and reported four false divergences per run.

AVERAGE and NONE booking are deliberately not generated: beancount
rejects both outright, so every such run would be a known-unsupported
skip rather than a test.

`--self-test` plants six known outcomes (wrong lot, wrong units, either
side rejecting, and two agreements) and requires each be classified
correctly, then requires the real engines to agree on a hand-checked
ledger. A harness that has only ever printed "no divergences" cannot be
distinguished from one that is incapable of printing anything else; this
one is checked in both directions before it is believed.

* test(compat): address review of the booking fuzzer

Two of the four were real defects, not style.

The `--python` default was `/home/dev/.compat-venv/bin/python` — my own
machine's path, committed. It now defaults to `sys.executable`, which
matches how the sibling compat scripts are invoked (`python3
scripts/compat-values.py`, under an interpreter that already has
beancount) and still takes an override for a dedicated venv.

`json.loads` was unguarded on the rledger side while the beancount side
already caught decode failures. A banner or stray log line on stdout
would have aborted the whole campaign rather than counting as one
booking failure — and the asymmetry between the two paths is what made
it wrong, since the comparison treats them as equivalent. Verified: a
non-JSON stdout now returns ERROR instead of raising.

Also extracted the query out of adjacent string literals so the intent
is explicit, and stopped materializing the seed sequence a second time
after iterating it.

Self-test still passes and seed 35 still reproduces the LIFO divergence
(#2115).
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.

[Bug]: {*} cost-merge reduction books but cannot apply — E4001 on a lot the account holds

2 participants