Skip to content

fix(booking): apply a transaction's reductions before its augmentations - #2081

Merged
robcohen merged 3 commits into
mainfrom
fix/apply-reduction-order
Aug 18, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/apply-reduction-order

Conversation

@robcohen

Copy link
Copy Markdown
Member

Fixes #2070. Two commits: a detector, then the fix — in that order deliberately.

The bug

book decides every posting against the inventory as it stood before the transaction, threaded with that transaction's earlier reductions and nothing else. That matches beancount's book_reductions exactly, including the reason its comment gives:

# Update the local balance in order to avoid matching against
# the same postings twice when processing multiple postings in
# the same transaction. Note that we only do this for postings
# held at cost because the other postings may need interpolation
# in order to be resolved properly.
for posting in reduction_postings:
    balance.add_position(posting)

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 — AVERAGE and {*} — it moves the pool:

2000-01-01 open Assets:Stock X "AVERAGE"

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

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

rledger check reports 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, on main today, with no {*} required.

The detector comes first

Nothing checked that book and apply agree, 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:

  1. It shrinks the bug far below what I hand-built: hold 40 @ 100, then buy 1 @ 101 and {*}-sell 1 in one transaction. Two postings.
  2. It found 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.
  3. It says the fix is complete, not merely that my example stopped failing: 256 generated cases across STRICT/FIFO/LIFO/AVERAGE pass 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 book does) decides order only: apply_posting classifies 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. book already rejects that, so it is the stricter gate either way — verified identical before and after:

$ rledger check oversell.beancount
error[BOOK]: Not enough units in Assets:Stock: requested 15, available 10

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 "make apply a 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-regressions is 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 book computes a decision and discards it, leaving apply to recompute it — see the options analysis on #2070, where "carry the decision" (making booking's plan_* result a value apply consumes) 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

robcohen and others added 2 commits August 18, 2026 03:22
`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
@robcohen
robcohen requested a review from a team as a code owner August 18, 2026 03:49
Copilot AI lite review requested due to automatic review settings August 18, 2026 03:49
@github-actions

github-actions Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 26.8ms ± 0.5ms 24.2 MB
beancount 512.7ms ± 8ms 50.7 MB
Comparison 19.1x faster 2.1x less

vs main branch (2026-08-18)

Metric main this PR Change
Time 39.1ms 26.8ms -31.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

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 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::apply to apply cost-bearing reductions before augmentations/other postings to prevent pool-moving for AVERAGE / {*} 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, so apply failures 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.

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%, 170 masked)
Full AST Match 100%
Total Files 811
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

@codecov

codecov Bot commented Aug 18, 2026

Copy link
Copy Markdown

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
@robcohen
robcohen merged commit f320e75 into main Aug 18, 2026
83 of 85 checks passed
@robcohen
robcohen deleted the fix/apply-reduction-order branch August 18, 2026 11:45
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]>
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.

Booking and application disagree about lots created earlier in the same transaction

2 participants