Skip to content

fix(core): try_reduce is now reduce-on-a-clone — equivalent by construction - #1690

Merged
robcohen merged 1 commit into
mainfrom
fix/try-reduce-equivalence
Jul 2, 2026
Merged

robcohen merged 1 commit into
mainfrom
fix/try-reduce-equivalence

Conversation

@robcohen

@robcohen robcohen commented Jul 2, 2026

Copy link
Copy Markdown
Member

FV follow-up #1 (of the improvement menu): the try_reduce preview must predict reduce exactly — and it didn't.

The divergences (equivalence property written first, as the oracle)

try_reduce re-implemented every booking method's selection logic in a parallel try_* tree (~330 lines). The property test caught it drifting in three places:

  1. STRICT: try_ fell back to FIFO on any multi-lot match; reduce returns AmbiguousMatch unless the lots are financially interchangeable.
  2. NONE: try_ routed to ordered reduction (NoMatchingLot on an empty inventory); reduce_none appends/shorts (oracle's minimal case).
  3. {*} merge: try_ dispatched to try_reduce_average; the mutating path uses the separate reduce_merge.

Same one-logic-two-paths class as #1648/#1663/#1686 — a preview surface silently disagreeing with the commit.

The structural fix

try_reduce = reduce on a clone — equivalent by construction, cannot re-drift, and deletes the whole duplicate tree (−326 lines). Cheap: positions is an imbl::Vector (O(1) structural-sharing clone); reduce's copy-on-write rebuild touches only the clone. (Note: try_reduce currently has no in-repo callers — deleting the API entirely is also an option, but keeping it correct + guarded seemed the conservative call; happy to drop it instead.)

Guard

tests/try_reduce_equivalence.rs: 500 randomized cases × 7 methods × satisfiable/unsatisfiable specs (labels, unmatched costs, {*}, wrong currency, oversells) — preview == commit exactly (same Ok matched+basis or same Err).

Verification

Equivalence property green; core lib 422/422 (no existing test had pinned the divergent preview); replay + TLA proptests green; clippy -D warnings + fmt clean.

🤖 Generated with Claude Code

…uction

The read-only preview duplicated every booking method's selection logic in a
parallel try_* tree (~330 lines) and had drifted from the mutating path in
three places, found by a new equivalence property test used as the oracle:

- STRICT: try_ fell back to FIFO on ANY multi-lot match; reduce returns
  AmbiguousMatch unless the lots are financially interchangeable.
- NONE: try_ routed to try_reduce_ordered (NoMatchingLot on an empty
  inventory); reduce_none appends/shorts.
- {*} merge: try_ dispatched to try_reduce_average; the mutating path uses
  the separate reduce_merge.

This is the recurring one-logic-two-paths drift class (#1648, #1663, #1686).
Structural fix: try_reduce = reduce on a clone — equivalence holds by
construction and cannot re-drift. The clone is cheap (imbl::Vector positions
clone via O(1) structural sharing; reduce's copy-on-write rebuild touches only
the clone). The whole try_* tree is deleted.

New tests/try_reduce_equivalence.rs pins the obligation: 500 randomized cases
across all 7 methods x satisfiable/unsatisfiable specs (labels, unmatched
costs, {*} merge, wrong currency, oversells) — preview == commit exactly.

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

codecov Bot commented Jul 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 31.7ms ± 0.5ms 23.7 MB
beancount 900.5ms ± 13.8ms 50.4 MB
Comparison 28.4x faster 2.1x less

vs main branch (2026-07-02)

Metric main this PR Change
Time 39.8ms 31.7ms -20.4% 🟢
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 makes Inventory::try_reduce predict Inventory::reduce exactly by implementing try_reduce as reduce executed on a cloned inventory, eliminating duplicated booking-method selection logic that previously drifted from the mutating path.

Changes:

  • Re-implement Inventory::try_reduce as self.clone().reduce(...), deleting the parallel try_* dispatch tree.
  • Add a proptest property test to pin try_reduce(...) == reduce(&mut inv.clone(), ...) across booking methods/specs and error cases.
  • Check in a proptest regression seed for a previously failing minimal counterexample.

Reviewed changes

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

File Description
crates/rustledger-core/src/inventory/booking.rs Replaces try_reduce’s duplicated logic with reduce-on-a-clone to guarantee equivalence.
crates/rustledger-core/tests/try_reduce_equivalence.rs Adds randomized equivalence property testing for try_reduce vs reduce.
crates/rustledger-core/tests/try_reduce_equivalence.proptest-regressions Adds a saved regression seed to re-run a previously found failing case.

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

@github-actions

github-actions Bot commented Jul 2, 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 86106f9 into main Jul 2, 2026
50 checks passed
@robcohen
robcohen deleted the fix/try-reduce-equivalence branch July 2, 2026 16:52
@robcohen robcohen mentioned this pull request Jul 2, 2026
robcohen added a commit that referenced this pull request Jul 2, 2026
Patch release. User-facing fixes since v0.19.0:

- NONE booking: over-reduction now shorts past zero from ANY balance
  (consumes available units, appends the remainder as a negative position),
  fixing the inconsistency where shorting from a positive balance was
  rejected while shorting from zero was allowed (#1686, via #1688).
- try_reduce: the read-only preview is now reduce-on-a-clone — equivalent to
  the mutating path by construction. Previously it diverged under STRICT
  (FIFO fallback instead of AmbiguousMatch), NONE (error instead of short),
  and {*} merge (wrong dispatch) (#1690).

No WIT change (rustledger:ledger stays 3.2.0); embedders are unaffected.
Also carries the formal-verification hardening arc (#1683-#1697): behavior
replay across 11 corpora, dual-direction trace validation, exact-rational
AVERAGE model, coverage lint, weekly escalated replay, pad-directive spec,
and Kani proofs for the new NONE semantics.

Workspace 0.19.0 -> 0.19.1; packages/mcp-server bumped to match.

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