Repository navigation
fix(booking): carry {*} into application instead of resolving it away - #2069
Conversation
`{*}` 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
📊 Benchmark Results
vs main branch (2026-08-17)
What do these numbers mean?
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
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.mergethrough the single-lot rewrite so{*}is re-executed duringapplyinstead of being resolved away. - Introduce
BookingError::MergeMismatchand 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.
✅ Compatibility Test Results
What's tested
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
|
Added one more assertion after review of my own diff. The mismatch is detected after Two boundary cases worth recording, both erring toward not firing:
|
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
Deep review of my own diffThree defects, two of them panics. Each fix has a test that fails without it (6185248). 1. The check fired on postings that never merge. 2. Rejecting a
3. It rejected a buy and a One thing this PR does not fixThat third case exposes a book-vs-apply disagreement that is not merge-specific but is only observable through 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 I have left it alone rather than adjudicate it inside a bug fix — on Gates: 145 suites green, clippy/fmt/doc clean. |
|
Filed the ordering divergence as #2070. Worth noting what turned up while writing it up: it is not on an 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. |
* 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).
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 reportedNo matching lotfor holdings the account plainly had:rledger check→No matching lot for X in Assets:Stock. beancount accepts this ledger.The fix
The single-lot rewrite carries
cost_spec.mergethrough, 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_mergereturns 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_postingcompares that against what the re-executed merge actually produced, reporting a newBookingError::MergeMismatchon 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:a_wildcard_merge_loads_without_errorsloada_wildcard_merge_books_and_applies_leaving_the_pool15 X @ 110a_merge_applied_against_different_inventory_is_reportedReverting only
merge: cost_spec.mergefails all three; disabling only the checksum fails the third alone. Both halves are independently necessary.Gates:
cargo test --workspace --all-features143 suites green;cargo +1.97.0 clippy --workspace --all-features --all-targets -D warnings,cargo fmt --check, andRUSTDOCFLAGS=-D warnings cargo docall clean.Surfaces that see the flag
rledger formatis source-faithful (unchanged), and BQL renders the resolvedCostfrom the inventory, not theCostSpec— so-5 X {110.00 USD}, no*leaking into user-facing output. The flag reaches onlymeta.hashand the FFICostSpecpassthrough, 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 view10 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 offAVERAGEaccounts. That is the separate question raised on #2068.🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr