Repository navigation
test: extend the green/red and realization parity guards - #1986
Conversation
#1902 Phase 3, the last open item. Both guards existed; both had a hole big enough to hide a live bug, and one of them was hiding one. GREEN/RED: the fuzzer cannot reach the thing it is named after `fuzz_green_eq_red` mutates raw BYTES. Measured before writing anything: of 20 000 random byte inputs, ZERO produced even one directive - let alone the well-formed simple transaction the green converter is the only consumer of. It is a fine guard on lexing and error recovery and it is structurally incapable of exercising the green path. So that path's correctness rested entirely on ~25 hand-picked corpus entries, i.e. on what someone thought to write down. A structured generator inverts that: 487 of 500 generated ledgers parse and 166 are error-free transactions with postings. It also CROSSES features - costs by prices by flags by tags - where the corpus has one entry per feature. #1713 was a product bug. What that buys, measured rather than asserted. Deleting green's bail on an arithmetic price amount passes the ENTIRE existing parser suite - 317 lib tests plus ast, fuzz_regressions and structured_directives - and fails only the new property. The generator itself was fixed by sabotage. Two candidate divergences (removing the price bail; latching the LAST amount rather than the first, the #1713 shape one level down) were caught by nothing at all, because nothing generated an arithmetic price amount. Added those, and the first is now caught. The second still is not: it needs two AMOUNT children in one PRICE_ANNOTATION, which appears to be syntactically unreachable - a defensive branch, not a coverage gap, and not claimed as covered. REALIZATION: five of seven booking methods were unpinned, and one diverges `query_report_realization_parity_test` pinned FIFO-via-empty-`{}` and an explicit-cost reduction. Running the same fixture through the whole matrix found AVERAGE diverging today - filed as #1985. The file's own docstring names the mechanism and states an invariant that does not hold: "they agree ONLY because both consume post-booking directives ... so naive re-aggregation lands on the same keys." AVERAGE is the one method where a reduction is booked at a cost belonging to NO augmentation (the merged average), so it has no key to net against and survives as a negative row. `report balances` gives the correct `15 AAPL {175.00}`; BQL BALANCES gives `10 {200} 10 {150} -5 {175}`. The old `broker_holding` helper could not express any of this - it asserts exactly ONE AAPL line, right for a netted holding and wrong for every method that legitimately leaves two lots standing. Comparison is now on the MULTISET of (units, cost), which drops the lot date the report shows and BQL does not, for the same reason the original helper dropped it. AVERAGE is pinned as a characterization test, not `#[ignore]`d: it asserts the wrong current behavior so that fixing #1985 FAILS it and forces AVERAGE into the agreeing set. An ignored test would let the fix land with nothing noticing, which is how a known divergence becomes a permanent one. That test also turned out to be the comparator's self-check. Sabotaging `aapl_lots` to return a constant makes every surface compare equal, so the agreeing-methods test passes vacuously - and only the AVERAGE assertion catches it. Sabotage-verified throughout: @@ mapped to per-unit, a dropped tag, the removed price bail, mismatched ledgers across surfaces, and a constant comparator each fail exactly the tests they should; restored is green. cargo test --workspace: 133 suites, 0 failures.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-08-07)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
Extends correctness guardrails added under #1902 Phase 3 by strengthening two differential/parity test suites: (1) query vs report realization parity across booking methods (including pinning the known AVERAGE divergence, #1985) and (2) green vs red parser parity using structured, beancount-shaped generation to actually exercise the green path.
Changes:
- Expand
query_report_realization_parity_testfrom two hand-picked fixtures to a booking-method matrix, including STRICT error parity and an AVERAGE characterization test. - Add
rustledger-parserproperty tests that generate structured ledgers and assert green-wiredparsematchesparse_red_onlyacross all relevantParseResultobservables (plus a generator self-check).
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| crates/rustledger/tests/query_report_realization_parity_test.rs | Adds booking-matrix parity tests and introduces multiset lot comparison to cover multi-lot methods; pins known AVERAGE divergence. |
| crates/rustledger-parser/tests/green_red_properties.rs | Adds structured proptest-based green/red parity suite designed to reach the green transaction converter reliably. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
| 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
All three Copilot comments, and the second one was hiding a bug.
1. `aapl_lots` used `unwrap_or_default()` for the lot cost, so a change
to how costs render would hand BOTH surfaces an empty string and they
would compare equal — a guard whose entire job is comparing costs,
passing precisely when it had stopped seeing them. It now panics with
the offending line unless the cost is a parseable number. A lot with no
`{...}` at all stays a legitimate shape (NONE booking, and the unbooked
reduction in #1987) and is recorded as such rather than conflated with
a cost that failed to parse.
2. The STRICT test said "must FAIL on both surfaces" and only asserted
that both PRINTED the ambiguity. Checking the exit codes, as Copilot
suggested, found that they do not fail alike at all:
query BALANCES exit 0, prints `-5 AAPL` for an account holding 15
report balances exit 101, PANICS in apply()
Filed as #1987. The panic is `apply()`'s own assertion about unbooked
reductions doing its job — the ambiguity is emitted as a WARNING, the
pipeline continues, and realization is then handed a reduction booking
declined to book. Reached from a normal command on ordinary input, that
is a crash rather than a guard.
Pinned as a characterization test naming the issue, like AVERAGE: a fix
changes those exit codes and trips it, forcing it to be rewritten as the
agreement assertion it was always supposed to be.
3. `observables` claimed "every observable on ParseResult" while
mirroring the fuzz target's list, which omits `syntax_root`. Now says
so, and says why it is omitted: both paths build the SAME lossless CST
and differ only in how they walk it, so comparing the tree would pass by
construction while saying nothing about the conversion under test.
Sabotage-verified: making the cost unreadable fails the matrix and the
AVERAGE pin; pretending #1987 is fixed fails the STRICT pin.
|
All three Copilot comments fixed in 524b178 — and the second one was hiding a bug. 1. Sabotage-verified: making the cost unreadable fails both the matrix and the AVERAGE pin. 2. The STRICT test said "must FAIL on both surfaces" and only checked that both PRINTED the message. Following the suggestion to assert exit status found that they do not fail alike at all:
Filed as #1987. The panic is Pinned as a characterization test naming the issue, like AVERAGE — a fix changes those exit codes and trips it, forcing it to be rewritten as the agreement assertion it was always meant to be. Sabotage-verified by pretending the fix landed. 3. Worth noting that this is the second time in this PR that a Copilot comment about a test's precision turned into a production bug — the same shape as the AVERAGE finding. |
… and lying in release (#1988) * fix(booking): report a failed reduction instead of panicking in one profile 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. * fix(query): --no-errors must not license answering over an unbooked ledger 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.
…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.
#1902 Phase 3, the last open item. Both guards existed; both had a hole big
enough to hide a live bug, and one of them was hiding one.
Green/red: the fuzzer cannot reach the thing it is named after
fuzz_green_eq_redmutates raw bytes. Measured before writing anything: of20,000 random byte inputs, zero produced even one directive — let alone the
well-formed simple transaction the green converter is the only consumer of. It's
a fine guard on lexing and error recovery, and it is structurally incapable of
exercising the green path. That path's correctness rested entirely on ~25
hand-picked corpus entries, i.e. on what someone thought to write down.
A structured generator inverts that — 487 of 500 generated ledgers parse and
166 are error-free transactions with postings. It also crosses features
(costs × prices × flags × tags) where the corpus has one entry per feature.
#1713 was a product bug.
What that buys, measured rather than argued. Deleting green's bail on an
arithmetic price amount:
ast,fuzz_regressions,structured_directivesThe generator was itself fixed by sabotage. Two candidate divergences —
removing the price bail, and latching the last amount rather than the first
(the #1713 shape one level down) — were caught by nothing at all, because
nothing generated an arithmetic price amount. Added those; the first is now
caught. The second still isn't: it needs two
AMOUNTchildren in onePRICE_ANNOTATION, which appears syntactically unreachable — a defensivebranch, not a coverage gap, and not claimed as covered.
Realization: five of seven booking methods were unpinned, and one diverges
The guard pinned FIFO-via-empty-
{}and an explicit-cost reduction. Running thesame fixture through the whole matrix found AVERAGE diverging today — #1985.
The file's own docstring names the mechanism and states an invariant that turns
out not to hold: "they agree ONLY because both consume post-booking directives
… so naive re-aggregation lands on the same keys." AVERAGE is the one method
where a reduction is booked at a cost belonging to no augmentation (the
merged average), so it has no key to net against and survives as a negative row.
report balancesgives the correct15 AAPL {175.00}; BQL BALANCES gives10 {200} 10 {150} -5 {175}.The old
broker_holdinghelper couldn't express any of this — it assertsexactly one AAPL line, right for a netted holding and wrong for every method
that legitimately leaves two lots standing. Comparison is now on the multiset
of
(units, cost), dropping the lot date the report shows and BQL doesn't, forthe same reason the original helper dropped it.
AVERAGE is pinned as a characterization test, not
#[ignore]d. It assertsthe wrong current behaviour on purpose, so fixing #1985 fails it and forces
AVERAGE into the agreeing set. An ignored test would let the fix land with
nothing noticing, which is how a known divergence becomes a permanent one.
That test also turns out to be the comparator's self-check: sabotaging
aapl_lotsto return a constant makes every surface compare equal, so theagreeing-methods test passes vacuously — and only the AVERAGE assertion catches
it.
Sabotage-verified
@@to per-unitaapl_lotsreturns a constantcargo test --workspace— 133 suites, 0 failures. Clippy and fmt clean.