Repository navigation
fix(booking): report a failed reduction instead of panicking in debug and lying in release - #1988
Conversation
…rofile and lying in the other Closes #1987. `apply()` ended its posting loop with `debug_assert!(reduced.is_ok())` followed by `let _ = reduced`, described as "release builds keep the historical ignore-and-continue behavior". So the two build profiles disagreed about a user's ledger: debug `report balances` PANICKED, exit 101 release the reduction was DROPPED — 20 AAPL reported for an account holding 15 The release half is the worse one, and it is the one real users got. An over-stated holding is not a crash you can see; it is a number you act on. CI never saw it because CI runs debug, where the same input panics. Reduction failures are now returned. The precondition is unchanged and still documented — `apply` wants booked input — but violating it is reported rather than asserted in one profile and ignored in the other. Every existing caller already handles the `Err`: `book()` records it and marks the transaction failed, the wasm entry checks `is_ok()`. ATOMICITY. Returning mid-loop would leave the earlier postings applied, which is exactly #1976's shape, so the snapshot gate widens from `overflow_is_possible` to `rollback_needed` = overflow OR the transaction contains a reduction. Kept as two predicates so #1897's reasoning stays legible: snapshotting EVERY transaction cost 2.4x heap churn and 6% CPU, and reductions are a minority of transactions, so this widens the gate without reopening that regression. `has_reduction` calls the canonical `Inventory::is_booking_reduction` rather than re-deriving "is this a reduction" from the sign. Not relying on the coincidence that `overflow_is_possible` returns true for an unfilled posting: a filled-but-unbookable transaction (ambiguous STRICT with explicit amounts) would otherwise mutate half its accounts and then return Err. THE CLI. The root cause is upstream of `apply`: `run_booking` partitions failures out, and `finalize` re-merges them so the user still sees their own input — documented as being "for output", with nothing stopping the same directives flowing into computation. `account_balances` even documents the precondition the pipeline then fails to establish. `bail_on_booking_errors` now gates `query` and `report`, mirroring `bail_on_parse_errors` one phase later, and says what to run instead. That also fixes the query half of #1987, which never touched `apply`: BALANCES re-aggregates by lot key and printed a dangling `-5 AAPL` for an account holding 15, exiting 0. before: report panics (exit 101), query prints a wrong row (exit 0) after: both refuse with the same message and exit 1; `check` still reports it, and a clean ledger is untouched TWO TESTS CHANGED BECAUSE THE BEHAVIOR DID. `strict_ambiguity_is_reported_by_both_surfaces` was the characterization test added with the guard in #1986. It tripped, which is what it was for, and is now the agreement assertion it was always meant to be. `ambiguous_strict_reduction_yields_no_rows` asserted that capgains succeeded with a header-only CSV. Not fabricating a disposal was right; exiting 0 was not — a header-only capital-gains CSV is indistinguishable from "you had no disposals this year". It now asserts the refusal AND that no row is fabricated. The parity guard's NONE fixture also turned out to be comparing two WRONG answers: `-5 AAPL {}` cannot book under NONE (cost tracking off, "2 unknowns"), so both surfaces were realizing an unbooked transaction and agreeing. Making failures fatal is what exposed it; NONE now reduces by price, the only shape that means anything without lots. Sabotage-verified: restoring ignore-and-continue fails two tests, returning Err without rolling back fails the atomicity test. The new tests pass identically under --release, which is the point.
📊 Benchmark Results
vs main branch (2026-08-07)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
Fixes a correctness bug where booking reduction failures produced different (and unsafe) outcomes between debug and release builds (panic vs silently ignoring the reduction), and updates CLI surfaces to refuse to compute figures when booking did not complete (avoiding silently wrong reports/queries).
Changes:
- Make
BookingEngine::applyreturn reduction failures (and roll back) instead ofdebug_assert!+ release ignore, and widen the snapshot gate to cover reductions. - Add
bail_on_booking_errorsand wire it intoreportandqueryto refuse deriving figures from ledgers containing BOOK failures. - Update/extend tests to assert refusal semantics and add a direct booking-engine regression test for the precondition/atomicity behavior.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/rustledger-booking/src/book.rs | Treat posting-application failures (overflow or reduction failure) as fatal with rollback, and snapshot when rollback may be needed. |
| crates/rustledger-booking/tests/apply_precondition_test.rs | New regression tests ensuring failed reductions are reported consistently and transactions are rolled back atomically. |
| crates/rustledger/src/cmd/loadcache.rs | Add bail_on_booking_errors helper (BOOK errors gate figure-deriving commands). |
| crates/rustledger/src/cmd/query/mod.rs | Call booking-failure gate during query load path (but see comment about --no-errors). |
| crates/rustledger/src/cmd/report_cmd/mod.rs | Call booking-failure gate during report load path. |
| crates/rustledger/tests/query_report_realization_parity_test.rs | Update parity guard to assert both surfaces refuse on STRICT ambiguity; adjust NONE fixture reduction line. |
| crates/rustledger/tests/report_capgains_test.rs | Update capgains test to assert refusal (non-zero) instead of “header-only success” on ambiguous STRICT reduction. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
| Metric | Result |
|---|---|
| Check Compatibility | 100% |
| BQL Compatibility | 95% (raw 89%, 162 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
…edger Copilot, and it was a real hole in the fix. The guard sat INSIDE the `!args.no_errors` block, so: rledger query --no-errors x.beancount BALANCES walked past the booking failure and printed the dangling `-5 AAPL` row with exit 0 — the exact bug this PR exists to prevent, reachable through a flag documented as suppressing the PRINTING of diagnostics. Verbosity is not permission to compute figures from a ledger that did not book. Worth recording how the first attempt to reproduce it "passed": with `query FILE QUERY --no-errors` the flag lands after the positionals, where it is swallowed into the BQL text and never registers, so `no_errors` stayed false and the guard fired. The order matters, and the regression test says so. Also derives the fixture cash leg from its lot instead of hard-coding -1500.00 for both buys, the second of which is 10 @ 200.00. `apply` does not check balance today, so nothing failed — which is why an internally inconsistent fixture is worth fixing before something starts depending on it. Sabotage-verified: nesting the guard back inside `--no-errors` fails the new test.
|
Both Copilot comments fixed in 3cf8d19 — and the first was a real hole in the fix.
The dangling Worth recording how my first attempt to reproduce it "passed": I ran The fixture inconsistency was real too — both buys paid Sabotage-verified: nesting the guard back inside |
…e stale All four Copilot comments. 1. carried TWO summary blocks and two sections: my insertion landed between \s existing doc and its signature, orphaning the old one onto the new. That old doc was also stale in its own right — it described the reduction failure as ignored and detectable via a , which #1988 removed. Fixed by deleting the wrapper rather than the duplicate text: the public was a one-line call through to a private with no other caller worth the indirection, so it is now one function with one doc. 2. walked the directive stream TWICE — once to register account booking methods, once to build . Registration now reads the vec already built. only looks at directives, so order is irrelevant and this is the same registration one pass earlier. 3. was computed for every posting even when nothing read it. Before this PR the per-account accumulation used it, so unconditional was right; resolves the position itself, leaving as the only consumer. Now gated on that. 4. The method list said "Four methods" with AVERAGE added. And one the comment led to: the FILE docstring described an architecture this PR removed. It explained that the two surfaces agree "ONLY because both consume post-booking directives ... so naive re-aggregation lands on the same keys" — true for FIFO/LIFO/HIFO, false for AVERAGE, and the whole reason #1985 existed. A comment asserting an invariant nobody checks, with a live exception, is the stale-invariant class #1902 names. Rewritten to say what is true now and to record why the old claim held for as long as it did.
…e stale All four Copilot comments. 1. `apply_posting` carried TWO summary blocks and two `# Errors` sections: my insertion landed between `try_apply_posting`'s existing doc and its signature, orphaning the old one onto the new. That old doc was also stale in its own right — it described the reduction failure as ignored and detectable via a `debug_assert`, which #1988 removed. Fixed by deleting the wrapper rather than the duplicate text: the public `apply_posting` was a one-line call through to a private `try_apply_posting` with no other caller worth the indirection, so it is now one function with one doc. 2. `scan_postings` walked the directive stream TWICE — once to register account booking methods, once to build `directive_iter`. Registration now reads the vec already built. `register_account_methods` only looks at `Open` directives, so order is irrelevant and this is the same registration one pass earlier. 3. `resolved` was computed for every posting even when nothing read it. Before this PR the per-account accumulation used it, so unconditional was right; `apply_posting` resolves the position itself, leaving `needs_balance` as the only consumer. Now gated on that. 4. The method list said "Four methods" with AVERAGE added. And one the comment led to: the FILE docstring described an architecture this PR removed. It explained that the two surfaces agree "ONLY because both consume post-booking directives ... so naive re-aggregation lands on the same keys" — true for FIFO/LIFO/HIFO, false for AVERAGE, and the whole reason #1985 existed. A comment asserting an invariant nobody checks, with a live exception, is the stale-invariant class #1902 names. Rewritten to say what is true now and to record why the old claim held for as long as it did.
…dd (#1990) * fix(query): realize BALANCES through the booking engine, not a bare add Closes #1985. BQL accumulated per-account balances with `Inventory::add` — unconditionally, with no reduction branch at all. Reports realize through `BookingEngine`, which resolves the account's booking method and then REDUCES against a lot or ADDS a new one. The two agreed for FIFO/LIFO/HIFO by COINCIDENCE: booking has already resolved a reduction's cost, so its lot key matches an existing lot and `add` nets it. Under AVERAGE it does not — the reduction is booked at the MERGED average cost, a key belonging to no augmentation — so it survived as a dangling negative and BALANCES reported 10 AAPL {200.00} 10 AAPL {150.00} -5 AAPL {175.00} for an account holding 15. `SELECT SUM(number)` agreed with the report all along at 15, so the units were right and only the lot-keyed presentation was wrong. BQL now calls `BookingEngine::apply_posting`, newly public because the query engine needed exactly this decision and was re-deriving a broken half of it. One realization rather than two that agree by luck — the duplication registry's realization family, and this was the drift. WHY NO DIFFERENTIAL TEST COULD FIND THIS. Python beancount does not implement AVERAGE. `booking_method_AVERAGE` raises `AmbiguousMatchError("AVERAGE method is not supported")` with the real implementation commented out ("DISABLED - This is the code for AVERAGE"), while `Booking.AVERAGE` stays in the enum and is accepted in an `open` directive — so a ledger declaring it parses and books nothing. Run the fixture through beancount and 20 units remain. So the compat oracle cannot referee this. Correctness rests on the definition — 10 @ 150 plus 10 @ 200 is 3500 over 20 units, 175.00 per unit, less 5 leaves 15 at 175.00 — and on the two surfaces agreeing. That is the general point, not a footnote: a divergence in a feature the reference implementation lacks is invisible to differential testing BY CONSTRUCTION, and the internal parity guard was the only thing that could have caught it. Documented at `reduce_average`, which is where someone will next be tempted to "match beancount". `average_booking_diverges_today` was the characterization test added with the guard in #1986; it asserted the wrong behavior on purpose so a fix would trip it. It did. Replaced by `average_booking_nets_to_a_single_merged_lot`, and AVERAGE joins the agreeing-methods loop. Sabotage-verified: restoring the unconditional `add`, and building the engine without registering account methods so AVERAGE falls back to the default, each fail two tests. 134 suites, 0 failures; the beancount oracle reports 0 divergences on every axis. * fix(query): one doc, one directive pass, and a docstring that had gone stale All four Copilot comments. 1. `apply_posting` carried TWO summary blocks and two `# Errors` sections: my insertion landed between `try_apply_posting`'s existing doc and its signature, orphaning the old one onto the new. That old doc was also stale in its own right — it described the reduction failure as ignored and detectable via a `debug_assert`, which #1988 removed. Fixed by deleting the wrapper rather than the duplicate text: the public `apply_posting` was a one-line call through to a private `try_apply_posting` with no other caller worth the indirection, so it is now one function with one doc. 2. `scan_postings` walked the directive stream TWICE — once to register account booking methods, once to build `directive_iter`. Registration now reads the vec already built. `register_account_methods` only looks at `Open` directives, so order is irrelevant and this is the same registration one pass earlier. 3. `resolved` was computed for every posting even when nothing read it. Before this PR the per-account accumulation used it, so unconditional was right; `apply_posting` resolves the position itself, leaving `needs_balance` as the only consumer. Now gated on that. 4. The method list said "Four methods" with AVERAGE added. And one the comment led to: the FILE docstring described an architecture this PR removed. It explained that the two surfaces agree "ONLY because both consume post-booking directives ... so naive re-aggregation lands on the same keys" — true for FIFO/LIFO/HIFO, false for AVERAGE, and the whole reason #1985 existed. A comment asserting an invariant nobody checks, with a live exception, is the stale-invariant class #1902 names. Rewritten to say what is true now and to record why the old claim held for as long as it did.
Closes #1987.
The bug was worse in release than the issue said
apply()ended its posting loop withdebug_assert!(reduced.is_ok())followed bylet _ = reduced, commented "release builds keep the historicalignore-and-continue behavior". So the two build profiles disagreed about a
user's ledger:
report balancespanicked, exit 101The release half is the worse one, and it's the one real users got. An
over-stated holding isn't a crash you can see; it's a number you act on. CI never
saw it because CI runs debug, where the same input panics instead.
Reduction failures are now returned. The precondition is unchanged and still
documented —
applywants booked input — but violating it is reported ratherthan asserted in one profile and ignored in the other. Every existing caller
already handles the
Err:book()records it and marks the transaction failed,the wasm entry checks
is_ok().Atomicity
Returning mid-loop would leave earlier postings applied — exactly #1976's shape.
The snapshot gate widens from
overflow_is_possibletorollback_needed=overflow or the transaction contains a reduction.
Kept as two predicates so #1897's reasoning stays legible: snapshotting every
transaction cost 2.4× heap churn and 6% CPU, and reductions are a minority of
transactions, so this widens the gate without reopening that regression.
has_reductioncalls the canonicalInventory::is_booking_reductionrather thanre-deriving "is this a reduction" from the sign.
Deliberately not relying on the coincidence that
overflow_is_possiblereturnstrue for an unfilled posting — a filled-but-unbookable transaction (ambiguous
STRICT with explicit amounts) would otherwise mutate half its accounts and then
return
Err.The CLI half
The root cause is upstream of
apply:run_bookingpartitions failures out, andfinalizere-merges them so the user still sees their own input — documented as"for output", with nothing stopping the same directives flowing into
computation.
account_balanceseven documents the precondition the pipeline thenfails to establish.
bail_on_booking_errorsnow gatesqueryandreport, mirroringbail_on_parse_errorsone phase later. That also fixes the query half, whichnever touched
apply: BALANCES re-aggregates by lot key and printed a dangling-5 AAPL, exiting 0.rledger checkstill reports it, and a clean ledger is untouched (verified).Two tests changed because the behavior did
strict_ambiguity_is_reported_by_both_surfaceswas the characterization testadded with the guard in #1986. It tripped — which is what it was for — and is now
the agreement assertion it was always meant to be.
ambiguous_strict_reduction_yields_no_rowsasserted capgains succeeded witha header-only CSV. Not fabricating a disposal was right; exiting 0 was not — a
header-only capital-gains CSV is indistinguishable from "you had no disposals this
year". It now asserts the refusal and that no row is fabricated.
A third finding
The parity guard's NONE fixture was comparing two wrong answers.
-5 AAPL {}cannot book under NONE (cost tracking off → "2 unknowns"), so both surfaces were
realizing an unbooked transaction and agreeing. Making failures fatal is what
exposed it. NONE now reduces by price, the only shape that means anything without
lots.
Verification
Errwithout rolling backThe new tests pass identically under
--release, which is the point — the olddebug_assertis exactly why debug and release disagreed.cargo test --workspace— 134 suites, 0 failures. Clippy and fmt clean.