Skip to content

fix(core): failed reductions must not mutate inventory + booking property tests - #1677

Merged
robcohen merged 1 commit into
mainfrom
fix/booking-properties
Jul 1, 2026
Merged

robcohen merged 1 commit into
mainfrom
fix/booking-properties

Conversation

@robcohen

@robcohen robcohen commented Jul 1, 2026

Copy link
Copy Markdown
Member

Implements the booking property-test improvement (idea #5 from the improvement review) — and it caught a real bug on its very first run.

The property tests

crates/rustledger-booking/tests/booking_properties.rs — randomized buy/sell sequences across STRICT/FIFO/LIFO/AVERAGE asserting the invariants the silent-corruption class (#1444, #1666) violated:

  1. Conservation — aggregate units = buys − successful sells
  2. Aggregate = Σ lots
  3. No minted lot identity on reduction (AVERAGE's synthesized pool excepted)
  4. No phantom negative lots
  5. A failed reduce must not mutate the inventory
    plus an engine-level property: a labeled sell books with its lot's label and nets against it (Cost-lot reduction drops the matched lot's label (phantom negative lot in holdings) #1666 as a property).

These complement spec/tla/ (which models the design) by fuzzing the implementation.

The bug it found (invariant 5, first run, minimal case buy 1, sell 2 under FIFO)

reduce_ordered (FIFO/LIFO) and reduce_hifo mutate lots during the walk and only check sufficiency afterwards — an oversell error returned with the inventory partially drained (the minimal case leaves the lot at 0 instead of 1). The validator reduces against the live LedgerState inventories, so one oversell error corrupted every later balance-assertion check on that account.

Fix: check sufficiency across the matched lots before mutating. Error values (requested/available) unchanged, so the #748-pinned message is unaffected.

Verification

Property tests pass (and now keep fuzzing in CI); full rustledger-core + rustledger-booking suites green; clippy -D warnings + fmt clean.

🤖 Generated with Claude Code

…tory; add booking property tests

Property-based tests for the silent-corruption class (the #1444 AVERAGE pool
wipe and #1666 phantom-lot signature): randomized buy/sell sequences assert
units conservation, aggregate==sum-of-lots, no minted lot identity, no phantom
negatives, and failed-reduce-does-not-mutate, across STRICT/FIFO/LIFO/AVERAGE;
plus an engine-level property that a labeled sell nets against its lot.

The failed-reduce invariant found a REAL bug on the first run: reduce_ordered
(FIFO/LIFO) and reduce_hifo mutate lots during the walk and only check
sufficiency afterwards, so an oversell error left the inventory partially
drained. The validator reduces against the live LedgerState inventories, so an
oversell error corrupted every subsequent balance-assertion check on that
account. Fixed by checking sufficiency across the matched lots BEFORE mutating;
the error values (requested/available) are unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Copilot AI review requested due to automatic review settings July 1, 2026 21:29
@robcohen
robcohen requested a review from a team as a code owner July 1, 2026 21:29

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

Fixes a booking-layer correctness bug where oversell errors in FIFO/LIFO/HIFO could partially mutate (drain) an inventory before returning InsufficientUnits, and adds property-based tests to prevent silent-corruption regressions in lot booking behavior across booking methods.

Changes:

  • Make reduce_ordered (FIFO/LIFO) and reduce_hifo perform a sufficiency check across matched lots before mutating any positions, ensuring failed reductions leave inventories untouched.
  • Add proptest-based invariants for randomized buy/sell sequences across STRICT/FIFO/LIFO/AVERAGE, including “failed reduce must not mutate” and labeled-lot netting behavior (#1666 class).
  • Check in the first proptest regression seed to keep the minimal failing case reproducible.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
crates/rustledger-core/src/inventory/booking.rs Prevents partial inventory mutation on the error path by pre-checking available units before reduction mutation.
crates/rustledger-booking/tests/booking_properties.rs Adds property tests enforcing conservation, lot-identity, non-negativity, and non-mutation-on-failure invariants (plus labeled-lot netting).
crates/rustledger-booking/tests/booking_properties.proptest-regressions Stores the minimal proptest regression seed that triggered the discovered bug for deterministic re-runs.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 33.2ms ± 0.6ms 23.6 MB
beancount 903.4ms ± 5.7ms 50.7 MB
Comparison 27.2x faster 2.1x less

vs main branch (2026-07-01)

Metric main this PR Change
Time 36.5ms 33.2ms -9.0% 🟢
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

@github-actions

github-actions Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 792
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@robcohen
robcohen merged commit bae4894 into main Jul 1, 2026
105 of 107 checks passed
@robcohen
robcohen deleted the fix/booking-properties branch July 1, 2026 22:06
robcohen added a commit that referenced this pull request Jul 2, 2026
…a stutter (#1683)

TLA+ actions are atomic: a disabled guard means NO transition, so the models
cannot express (and TLC can never catch) partial-mutation-then-error. That
obligation lives at the refinement boundary — and it is exactly where #1677
hid: TLC was green while FIFO/LIFO/HIFO oversells drained lots before
erroring. The then-current conformance layer could not see it either:
prop_conservation_invariant clamped reductions to min(current) and skipped
Err with if-let-Ok; prop_non_negative_inventory generated the precise failing
input but asserted NOTHING on the Err branch.

- prop_conservation_invariant: unclamped reduce amounts (Err now reachable),
  Err asserts a full inventory snapshot unchanged, conservation checked after
  every step.
- prop_non_negative_inventory: oversell must Err AND leave the inventory
  untouched.
- NEW prop_failed_reduce_is_a_stutter: all 7 booking methods x 4 error
  classes (oversell / wrong currency / unknown label / unmatched cost,
  ambiguous under STRICT) — Err implies snapshot-identical state.
- RUST_MAPPING.md: new 'Refinement Obligations' section documenting the
  stutter obligation, where it is checked, and the generator rules for future
  conformance tests (violate the guards; never if-let-Ok-skip Err).

Co-authored-by: Claude Opus 4.8 <[email protected]>
robcohen added a commit that referenced this pull request Jul 2, 2026
… all specs per run (#1684)

Restores the formal-verification roadmap's 'Now' item (the workflow that once
produced tla_fifo_bug_test.rs, whose converter was deleted in spring cleaning
and documented in-workflow as 'removed pending someone porting it').

- scripts/tla-trace-to-test.py: parses TLC error traces (ports the retired
  tla_trace_to_json.py value parser) and emits Rust regression-test skeletons —
  concrete Inventory calls for the inventory/booking spec family (state diffs
  -> Add/Reduce), a pinned-trace #[ignore] skeleton for other specs. --self-test
  with canned traces.
- tla.yml: the 16 uniform TLC steps become one loop that checks EVERY spec per
  run (fail-fast previously masked later spec failures), tees each output to
  tlc-logs/, and on failure converts every counterexample into a test skeleton
  in the job summary + artifact.
- Fixes a stale trigger path: 'crates/rustledger-core/src/inventory.rs'
  predates inventory/ becoming a directory, so inventory changes (e.g. the
  #1677 reduction fix) stopped triggering the models entirely. Now
  inventory/**, plus the converter and the workflow itself.

Co-authored-by: Claude Opus 4.8 <[email protected]>
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.

2 participants