Repository navigation
fix(booking): apply a transaction's reductions before its augmentations - #2081
Merged
Merged
Conversation
`book` and `apply` are two derivations of the same quantity, and nothing checked that they agree. #2070 is what that costs: for a buy and a reduction in ONE transaction, the journal and the engine report different cost bases, silently. The invariant is that the engine's holdings equal the sum of the booked postings. It compares units and basis rather than lot structure, because ADR-0007 deliberately lets the engine pool while the journal keeps per-lot costs — pooling preserves both totals, so this asserts only what the two representations must agree on and stays silent about the representation itself. Proptest over four booking methods and the four reduction shapes (explicit cost, bare `{}`, `{*}`, and buys) shrinks #2070 to a two-posting minimal case: hold 40 @ 100, then buy 1 @ 101 and `{*}`-sell 1 in the same transaction, and the two answers differ by 0.0244. Finding worth recording: the run also surfaced a SECOND, unrelated class — a pooled cost like 7939/79 does not terminate, so the engine stores it rounded on the remainder while the journal keeps the un-rounded sum, and the two differ in the 25th significant digit. That is inherent to per-unit average costing rather than a disagreement about a decision, so `within_rounding_residue` absorbs it, at a bar twenty orders of magnitude below the divergence this file hunts. The self-check tests the COMPARATOR, not the product. Asserting "the known-bad shape still diverges" inverts the moment the bug is fixed, leaving the harness unguarded exactly when it starts mattering. Verified in both states: fails on `main`, passes with the `research/2070-apply-order` prototype applied. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
`book` decides every posting against the inventory as it stood before the
transaction, threaded with that transaction's earlier reductions and
nothing else. That is not an accident of implementation: beancount's
`book_reductions` does the same, and its comment states the reason — an
augmentation's cost may still need interpolation, so it is not a
resolvable position yet.
`apply` mutated in posting order, so a buy earlier in the transaction was
already in the account when a later reduction ran. For a spec naming a
concrete lot that changes nothing. For the two that RE-DERIVE a pool,
`AVERAGE` and `{*}`, it moves the pool — and the engine then disagreed
with the journal about cost basis, silently:
2024-02-01 * "buy then sell in ONE transaction"
Assets:Stock 10 X {120.00 USD}
Assets:Stock -5 X {}
booked postings 1,700.00 USD of basis; the engine held 1,650.00.
Ordering the cost-bearing reductions first restores the agreement.
Classifying against the pre-transaction inventory rather than threading
decides ORDER only — `apply_posting` classifies each posting itself
against live state — and the disagreement can only run one way, since
threading removes units and so can only make a posting look less like a
reduction.
Nothing that used to load stops loading: `book` already rejects a
reduction covered only by its own transaction's augmentation, so it is
the stricter gate either way. Verified unchanged on that ledger.
Fixes #2070
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Contributor
📊 Benchmark Results
vs main branch (2026-08-18)
What do these numbers mean?
|
Contributor
There was a problem hiding this comment.
Pull request overview
This PR fixes a booking/realization divergence in rustledger-booking by ensuring BookingEngine::apply processes cost-bearing reductions before other postings in the same transaction, aligning application with how book decides reductions against the pre-transaction inventory (Fixes #2070).
Changes:
- Adds a proptest-based detector asserting that engine holdings (units + basis) equal the sum of booked postings, plus committed regression seeds.
- Pins the specific “buy then merge-reduce in one transaction” arithmetic with a focused regression test.
- Updates
BookingEngine::applyto apply cost-bearing reductions before augmentations/other postings to prevent pool-moving forAVERAGE/{*}paths.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| crates/rustledger-booking/tests/book_apply_agreement.rs | New property test and comparator self-check guarding book/apply agreement on units + basis. |
| crates/rustledger-booking/tests/book_apply_agreement.proptest-regressions | Adds saved proptest failure seeds to permanently replay discovered counterexamples. |
| crates/rustledger-booking/tests/apply_precondition_test.rs | Adds a concrete regression test that pins the #2070 numeric outcome for a single transaction shape. |
| crates/rustledger-booking/src/book.rs | Reorders apply execution to run cost-bearing reductions before other postings to match booking semantics for pooling specs. |
Suppressed comments (1)
crates/rustledger-booking/tests/book_apply_agreement.rs:217
- Similarly,
engine.book(&txn)succeeded here and the generator values are small, soapplyfailures should be treated as a hard test failure rather than being silently skipped (otherwise a future regression could be masked).
if engine.apply(&booked.transaction).is_ok() {
add_booked_postings(&mut journal, &booked.transaction);
}
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…le name Copilot's review, all three findings. The module doc named `the_detector_can_report_dirty`, which was renamed to `the_comparison_can_report_dirty` when the self-check moved from asserting the product still has the bug to exercising the comparator. The seed buys were applied under `if ... .is_ok()`, so a regression in `apply` would have silently skipped them and let the property hold vacuously — the exact failure mode this file exists to prevent. They are fixtures; they now assert. So does applying a transaction that booked: `apply`'s precondition is booked input and `book` just produced it, so that pair failing is itself a defect rather than a case to skip. Only an unbookable transaction is still skipped, which is a different failure and says nothing about this invariant. The ordering pre-pass built two `Vec`s per transaction; it now classifies once into a `u64` bitmask, with source order beyond the 64th posting. The other half of that finding does not apply: the pre-pass and `apply_posting` ask the same predicate about deliberately DIFFERENT state — pre-transaction versus live — and sharing one answer between them would reintroduce the divergence this PR fixes. Nor is the call a scan: `is_reduced_by` has read per-currency sign counts since #2062, so both calls are hash lookups. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
This was referenced Aug 18, 2026
robcohen
added a commit
that referenced
this pull request
Aug 18, 2026
* test(booking): stop the rollback property failing at random
`a_failed_transaction_restores_the_account_exactly` assumed its doomed
final leg — overselling `STK` by 100,000 — always fails. It does not. A
generated prefix of `{*}` merges can empty the account, and an empty cost
spec against an empty account is an AUGMENTATION rather than a failed
reduction. Beancount's `book_reductions` makes the same call: reduction
only `if balance.is_reduced_by(units)`, else augment. So the transaction
succeeded, the property reported "the doomed leg must reject the
transaction", and whether CI saw it depended on which prefix proptest
happened to generate.
Found by proptest generating `[Merge, Merge, Merge, Merge]` while I was
measuring something unrelated. It reproduces on every commit I tried,
including before #2085 and #2081, so it has been latent since the file
was added in #2067.
The doomed posting now reduces a commodity the generated legs never
mention, seeded once up front. That makes "this leg always fails" a fact
about the fixture rather than a hope about the prefix, and the prefix
still exercises every mutation shape the undo log has to cover.
Verified: the seed that fails on main passes here, eight randomized runs
pass, and the property still catches a rollback bug — neutering
`has_reduction` so the undo log is never armed fails it.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
* test(booking): reuse per_unit for the anchor and drop a stale commodity name
Copilot's review. The anchor lot spelled out a `CostSpec` that `per_unit`
already builds, which is how a fixture drifts from the shape the rest of
the file uses; and two comments called the generated commodity `STK`
while the constant has been `X` since the file was written.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
* test(booking): snapshot the commodity in the rollback property
Review of my own change. `holdings` compared units, cost and lot date but
not the commodity, which was harmless while the account held one. This
change gave it two — the generated legs work on one, the doomed leg
reduces the other — so a rollback that restored the right numbers against
the wrong commodity would have compared equal.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
---------
Co-authored-by: Claude Opus 5 <[email protected]>
This was referenced Aug 23, 2026
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #2070. Two commits: a detector, then the fix — in that order deliberately.
The bug
bookdecides every posting against the inventory as it stood before the transaction, threaded with that transaction's earlier reductions and nothing else. That matches beancount'sbook_reductionsexactly, including the reason its comment gives:The augmentation branch never touches
balance.apply, however, mutated in posting order — so a buy earlier in the transaction was already in the account when a later reduction ran.For a spec naming a concrete lot that changes nothing; the lot is found either way. For the two specs that re-derive a pool —
AVERAGEand{*}— it moves the pool:rledger checkreports no errors, and then the two views disagree: the booked postings total 1,700.00 USD of basis (1000 + 1200 − 500), while the engine holds 1,650.00 (15 × 110). Silently, onmaintoday, with no{*}required.The detector comes first
Nothing checked that
bookandapplyagree, which is why this shipped. The first commit adds that check —the engine's holdings equal the sum of the booked postings— as a proptest over four booking methods and all four reduction shapes.It earned its place three times over:
{*}-sell 1 in one transaction. Two postings.7939/79does not terminate, so the engine stores it rounded on the remainder while the journal keeps the un-rounded sum, and the two differ in the 25th significant digit. That is inherent to per-unit average costing rather than a disagreement about a decision, sowithin_rounding_residueabsorbs it — at a bar twenty orders of magnitude below the divergence this file hunts.STRICT/FIFO/LIFO/AVERAGEpass with the fix and fail without it.The invariant compares units and basis, not lot structure, because ADR-0007 deliberately lets the engine pool while the journal keeps per-lot costs — pooling preserves both totals, so this asserts only what the two representations must agree on.
The self-check tests the comparator, with synthetic values. My first version asserted "the known-bad shape still diverges", which inverts the moment the fix lands — leaving the harness unguarded exactly when it starts mattering.
The fix
Order the cost-bearing reductions ahead of the other postings. Classifying against the pre-transaction inventory rather than threading (as
bookdoes) decides order only:apply_postingclassifies each posting itself against live state, so a posting sorted into the wrong bucket still does the right thing, and the disagreement can only run one way, since threading removes units and can only make a posting look less like a reduction. Reductions keep their relative order, which a second reduction on one account depends on.Nothing that used to load stops loading
The case that could regress is a reduction covered only by its own transaction's augmentation.
bookalready rejects that, so it is the stricter gate either way — verified identical before and after:Also verified unchanged end to end:
{*}books and applies (#2069), and a merged pool is still referenceable by cost in a later transaction — the property that rules out "makeapplya pure fold" as an alternative fix, since a fold would leave no positive lot at the pool cost.Verification
146 test suites green; clippy (1.97.0), fmt and doc clean.
.proptest-regressionsis committed per repo convention, pinning both discovered counterexamples as permanent seeds.Not in scope
This aligns two derivations of the same quantity; it does not remove the second one. The root cause is that
bookcomputes a decision and discards it, leavingapplyto recompute it — see the options analysis on #2070, where "carry the decision" (making booking'splan_*result a valueapplyconsumes) is the architectural end state. The detector is the guard that makes that refactor safe to attempt, and it should be pointed at the Late validator next — a third implementation of the same reduction decision.🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr