Repository navigation
fix(booking): detect ambiguous lot match + track per-account methods - #745
Merged
Merged
Conversation
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
There was a problem hiding this comment.
Pull request overview
This PR fixes STRICT lot reduction semantics to detect genuinely ambiguous matches (multiple matching lots with different cost values) instead of silently falling back to FIFO, aligning behavior with Python beancount and addressing #737.
Changes:
- Update
Inventory::reduce_strictto allow FIFO only for financially interchangeable lots (same cost number/currency) or full-liquidation “total match”, otherwise returnBookingError::AmbiguousMatch. - Add/adjust tests (unit + proptest) to pin the new ambiguity behavior and the two accepted exceptions.
- Clarify (via comments) why booking (
book.rs) continues to swallow reduce errors to avoid duplicate validator diagnostics.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| crates/rustledger-core/src/inventory/booking.rs | Implements STRICT multi-match handling: interchangeable-lots fast path, total-match exception, otherwise AmbiguousMatch. |
| crates/rustledger-core/src/inventory/mod.rs | Reworks STRICT unit tests to cover ambiguous-different-costs, identical-costs FIFO, and total-match exception. |
| crates/rustledger-core/tests/tla_proptest.rs | Updates STRICT proptest to expect AmbiguousMatch for wildcard reductions across different-cost lots. |
| crates/rustledger-booking/src/book.rs | Adds rationale comment for intentionally not surfacing reduce errors during booking to avoid duplicate validator output. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Contributor
📊 Benchmark Results
vs main branch (2026-04-09)
What do these numbers mean?
|
Contributor
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
robcohen
added a commit
that referenced
this pull request
Apr 10, 2026
Addresses review feedback on PR #745: the booking layer no longer silently swallows reduce() errors, and the BookingEngine now respects per-account booking methods from open directives. Background: the original PR fixed reduce_strict to detect ambiguous lot matches but kept book.rs's existing silent-swallow of reduce errors, relying on the validator's independent lot-matching pass to surface the E4xxx diagnostic. That was a defensible pragmatic choice but left book.rs in an architecturally wrong state, and it hid a second bug: the BookingEngine was using a single engine-wide booking method for all accounts, ignoring per-account methods from / / etc. Changes: 1. BookingEngine now tracks a per-account map, populated via a new API. falls back to the engine default when an account is not registered. Both and use the resolved method. 2. pre-populates the engine by scanning open directives before the booking loop. This finally makes FIFO, LIFO, NONE, HIFO, etc. accounts book against the method the user declared instead of the engine-wide STRICT default. 3. book.rs propagates reduce errors via (no more silent swallow) through a new helper that attaches account context. 4. BookingError gains an variant and gains an field for better error messages. 5. reports propagated booking errors as E4xxx diagnostics (E4001 NoMatchingLot, E4002 InsufficientUnits, E4003 AmbiguousMatch) with phase=validate, and filters the failed transactions out of the validator's input so the independent validator pass doesn't double-report them. The library-level validate() entry point still reports these errors itself, so non-CLI consumers (LSP, embedded) still get the diagnostics. 6. New integration test pins the exact-one-E4003 contract against the #737 input, guarding against both the original silent-accept bug and the booking/validator double-report regression. 7. New inventory test closes the review gap on the same-cost-different-dates path, which previously was only covered indirectly via a validator integration test. 8. Expanded doc comment on reduce_strict explaining the interchangeable-lots heuristic ((number, currency) only, not full cost equality), why that matches Python beancount, and where the deeper spec-derived check would differ. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
robcohen
added a commit
that referenced
this pull request
Apr 10, 2026
Addresses review feedback on PR #745: the booking layer no longer silently swallows reduce() errors, and the BookingEngine now respects per-account booking methods from open directives. Background: the original PR fixed reduce_strict to detect ambiguous lot matches but kept book.rs's existing silent-swallow of reduce errors, relying on the validator's independent lot-matching pass to surface the E4xxx diagnostic. That left book.rs in an architecturally wrong state, and it hid a second bug: the BookingEngine was using a single engine-wide booking method for all accounts, ignoring per-account methods from `open "FIFO"` / `"LIFO"` / `"NONE"` etc. Changes: 1. BookingEngine now tracks a per-account `account_methods` map, populated via a new `set_account_method` API. `method_for()` falls back to the engine default when an account is not registered. Both `book()` and `apply()` use the resolved method. 2. `rustledger check` pre-populates the engine by scanning open directives before the booking loop. This finally makes FIFO, LIFO, NONE, HIFO, etc. accounts book against the method the user declared instead of the engine-wide STRICT default. 3. book.rs propagates reduce errors via `?` (no more silent swallow) through a new `convert_core_booking_error` helper that attaches account context. 4. BookingError gains an `AmbiguousMatch { account, currency, num_matches }` variant and `InsufficientUnits` gains an `account` field for better error messages. 5. `rustledger check` reports propagated booking errors as E4xxx diagnostics (E4001 NoMatchingLot, E4002 InsufficientUnits, E4003 AmbiguousMatch) with phase="validate", and filters the failed transactions out of the validator's input so the independent validator pass doesn't double-report them. The library-level validate() entry point still reports these errors itself, so non-CLI consumers (LSP, embedded) still get the diagnostics. 6. New integration test `test_check_ambiguous_lot_match_reports_once` pins the exact-one-E4003 contract against the #737 input, guarding against both the original silent-accept bug and the booking/validator double-report regression. 7. New inventory test `test_reduce_strict_multiple_match_different_dates_same_cost_uses_fifo` closes the review gap on the same-cost-different-dates path, which previously was only covered indirectly via a validator integration test. 8. Expanded doc comment on reduce_strict explaining the interchangeable-lots heuristic ((number, currency) only, not full cost equality), why that matches Python beancount, and where the deeper spec-derived check would differ. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
robcohen
force-pushed
the
fix/issue-737-ambiguous-booking
branch
from
April 10, 2026 01:28
c1c5529 to
6077e9c
Compare
reduce_strict previously fell back to FIFO whenever multiple lots matched
the cost spec, even when the lots had different cost values. This silently
accepted reductions like '-5 AAPL {}' against an inventory containing
both {150 USD} and {160 USD} lots, instead of raising AmbiguousMatchError
as Python beancount does.
The intent of the FIFO fallback was to handle truly interchangeable
lots (same cost, possibly different dates/labels) where the user could
not have meant to distinguish them. The implementation didn't actually
check identity though.
Refine the multi-match arm of reduce_strict:
- If all matched lots share the same (cost number, cost currency), they
are financially interchangeable from the user's perspective and FIFO
is safe. Date and label differences alone do NOT make a reduction
ambiguous because the cost spec the user wrote could not have
distinguished them.
- Else, if the reduction equals the sum of all matched units, the
user is liquidating the entire matched inventory and the lot order
is irrelevant — accept via the existing total-match exception.
- Otherwise, return BookingError::AmbiguousMatch, which the existing
E4003 validator surfaces as 'Ambiguous lot match for X: N lots
match in account'.
The book.rs and check.rs paths are intentionally untouched: the
validator already runs the same lot-matching logic and reports the
diagnostic, so propagating the error from book() too would produce
duplicate output.
Tests:
- New test_reduce_strict_multiple_match_with_different_costs_is_ambiguous
pins the issue scenario at the inventory level.
- New test_reduce_strict_multiple_match_with_identical_costs_uses_fifo
pins the interchangeable-lots fast path (same cost, different dates).
- New test_reduce_strict_multiple_match_total_match_exception pins the
full-liquidation accept path.
- Updated tla_proptest::prop_strict_errors_on_ambiguous_match to
reflect Python-compatible behavior (was inverted).
Closes #737
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Addresses review feedback on PR #745: the booking layer no longer silently swallows reduce() errors, and the BookingEngine now respects per-account booking methods from open directives. Background: the original PR fixed reduce_strict to detect ambiguous lot matches but kept book.rs's existing silent-swallow of reduce errors, relying on the validator's independent lot-matching pass to surface the E4xxx diagnostic. That left book.rs in an architecturally wrong state, and it hid a second bug: the BookingEngine was using a single engine-wide booking method for all accounts, ignoring per-account methods from `open "FIFO"` / `"LIFO"` / `"NONE"` etc. Changes: 1. BookingEngine now tracks a per-account `account_methods` map, populated via a new `set_account_method` API. `method_for()` falls back to the engine default when an account is not registered. Both `book()` and `apply()` use the resolved method. 2. `rustledger check` pre-populates the engine by scanning open directives before the booking loop. This finally makes FIFO, LIFO, NONE, HIFO, etc. accounts book against the method the user declared instead of the engine-wide STRICT default. 3. book.rs propagates reduce errors via `?` (no more silent swallow) through a new `convert_core_booking_error` helper that attaches account context. 4. BookingError gains an `AmbiguousMatch { account, currency, num_matches }` variant and `InsufficientUnits` gains an `account` field for better error messages. 5. `rustledger check` reports propagated booking errors as E4xxx diagnostics (E4001 NoMatchingLot, E4002 InsufficientUnits, E4003 AmbiguousMatch) with phase="validate", and filters the failed transactions out of the validator's input so the independent validator pass doesn't double-report them. The library-level validate() entry point still reports these errors itself, so non-CLI consumers (LSP, embedded) still get the diagnostics. 6. New integration test `test_check_ambiguous_lot_match_reports_once` pins the exact-one-E4003 contract against the #737 input, guarding against both the original silent-accept bug and the booking/validator double-report regression. 7. New inventory test `test_reduce_strict_multiple_match_different_dates_same_cost_uses_fifo` closes the review gap on the same-cost-different-dates path, which previously was only covered indirectly via a validator integration test. 8. Expanded doc comment on reduce_strict explaining the interchangeable-lots heuristic ((number, currency) only, not full cost equality), why that matches Python beancount, and where the deeper spec-derived check would differ. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Follow-up to the per-account booking method tracking introduced in the previous commit: that commit only wired up the CLI path. LSP, FFI-WASI, rustledger-wasm, and rustledger-loader all create their own BookingEngine and were still using the engine-wide default for all accounts. Add a convenience method `BookingEngine::register_account_methods(iter)` that scans any directive iterator and registers per-account booking methods from `open` directives in one call. Update all six consumers: - rustledger/src/cmd/check.rs (simplifies the inline scan added earlier) - rustledger-loader/src/process.rs (run_booking) - rustledger-lsp/src/handlers/diagnostics.rs - rustledger-lsp/src/handlers/code_lens.rs - rustledger-ffi-wasi/src/jsonrpc/router.rs - rustledger-ffi-wasi/src/helpers.rs - rustledger-wasm/src/lib.rs (test) Every path that feeds directives through a BookingEngine now honors per-account FIFO / LIFO / NONE / HIFO / STRICT_WITH_SIZE / AVERAGE declarations on open directives, matching Python beancount's behavior. The `book_transactions(&[Transaction], method)` helper in the booking crate is unchanged — its API takes bare transactions and cannot discover opens, so callers of that entry point are documented as accepting the engine-wide default. It is only used by the booking crate's own tests today. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Fallback ordering is cost.date-based (matching FIFO), not insertion order. - Document the total-match (full liquidation) exception that STRICT still honors alongside the identical-cost fast path. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
robcohen
force-pushed
the
fix/issue-737-ambiguous-booking
branch
from
April 10, 2026 02:23
4a97967 to
8883c4b
Compare
robcohen
added this pull request to the merge queue
Apr 10, 2026
robcohen
added a commit
that referenced
this pull request
Apr 11, 2026
PR #745 made the booking layer propagate `InsufficientUnits` errors directly to the user instead of letting them be silently swallowed and re-emitted by the validator. That was the right architectural move, but the booking variant's Display string ("insufficient units: need X but only Y available") differed from the validator's pre-existing phrasing ("Not enough units in <account>: requested X, available Y; not enough to reduce"), and the conformance suite (and downstream user tooling) matches on "not enough". Result: pta-standards `reduction-exceeds-inventory` regressed from passing to failing on the error_contains assertion, even though the error itself is still correctly detected. Align the booking layer's Display to match the validator's wording verbatim. The `account` field is already on the variant (added in #745 for exactly this purpose), so no struct change is needed. Add a regression test that pins the Display string against the three assertions that matter: contains "not enough", contains the account name, contains both numbers. The test references #748 in its docstring so the next person to touch the variant understands why the exact phrasing is load-bearing. Closes #748 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
This was referenced Apr 11, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Originally a one-line bug: STRICT booking silently accepted wildcard reductions (
-5 AAPL {}) against inventories holding lots at different costs, instead of raisingAmbiguousMatchError. Investigation surfaced a second latent bug in the same layer — theBookingEnginewas using a single engine-wide booking method for every account, ignoring per-accountFIFO/LIFO/NONE/HIFO/STRICT_WITH_SIZE/AVERAGEdeclarations onopendirectives. The silent swallow inbook.rswas compensating for that by dropping the spurious errors it produced.This PR fixes all three layers of the problem:
reduce_strictdetects real ambiguity — aligning with the formalspec/tla/STRICTCorrect.tlamodel (which the previous implementation contradicted).BookingEnginerespects per-account booking methods — newaccount_methodsmap +set_account_method/register_account_methodsAPIs, wired into every consumer.book.rspropagates errors instead of swallowing them — errors flow cleanly throughconvert_core_booking_errorand are reported exactly once.Closes #737.
What changed
Core fix: ambiguous lot match detection (
rustledger-core)reduce_strictpreviously fell back to FIFO whenever multiple lots matched the cost spec — even when the lots had different cost values. The intent of the fallback was to handle truly interchangeable lots, but the implementation didn't check identity.New logic in the multi-match arm:
(cost.number, cost.currency), they're financially interchangeable from the user's perspective and FIFO is safe. Date and label differences alone do NOT make a reduction ambiguous because the user's cost spec could not have distinguished them without naming those fields. Matches Python beancount.reduce_strict_with_size).BookingError::AmbiguousMatch.Expanded doc comment on
reduce_strictexplains the interchangeable-lots heuristic and where a stricter spec-derived check would differ.Per-account booking methods (
rustledger-booking)BookingEngine::account_methods: FxHashMap<InternedStr, BookingMethod>override map.set_account_method(account, method)andmethod_for(&account)APIs.register_account_methods(iter)that scans any directive iterator and registers methods fromopendirectives in one call.book()andapply()usemethod_for()so per-account methods apply consistently.BookingError::AmbiguousMatch { account, currency, num_matches }variant;InsufficientUnitsgains anaccountfield.convert_core_booking_errorhelper to maprustledger_core::BookingError→BookingErrorwith account context.Error propagation in
book.rsbook.rsno longer silently swallowsinv.reduceerrors. Failures propagate via?through the new conversion helper. The previous comment claiming "intentionally not surfaced" is removed.All consumers updated to register account methods
Every place that creates a
BookingEnginenow registers per-account methods before booking:rustledger/src/cmd/check.rsrustledger-loader/src/process.rsrustledger-lsp/src/handlers/diagnostics.rsrustledger-lsp/src/handlers/code_lens.rsrustledger-ffi-wasi/src/jsonrpc/router.rsrustledger-ffi-wasi/src/helpers.rsrustledger-wasm/src/lib.rs(test)Before this PR, LSP diagnostics and the FFI path would have booked every account against STRICT regardless of declared method.
Deduplication in
rustledger checkbooking_errorsbucket alongsideinterpolation_errors.spanned_directivesis filtered before being passed to the validator so the validator's independent lot-matching pass doesn't double-report the same diagnostic.E4001NoMatchingLot,E4002InsufficientUnits,E4003AmbiguousMatch) withphase="validate".validate()entry point still reports these errors itself, so LSP/embedded consumers that callvalidate()directly without going through booking still get the diagnostics.Before / After
Issue input (
{}cost spec against two lots at different costs):Before:
validate success— silently picked the first lot via FIFO. Same behavior for the default-STRICT variant.After: exactly one
error[E4003]: ambiguous lot match: 2 lots match for AAPL in account Assets:Stock. Same for default STRICT.Tests
test_reduce_strict_multiple_match_with_different_costs_is_ambiguous— inventory-level pin for the issue scenario (returnsAmbiguousMatch, inventory unchanged).test_reduce_strict_multiple_match_with_identical_costs_uses_fifo— same date, same cost → FIFO (interchangeable lots fast path).test_reduce_strict_multiple_match_different_dates_same_cost_uses_fifo— different dates, same cost → FIFO. This was only tested indirectly viatest_validate_multiple_lot_match_uses_fifo; now pinned directly at the inventory level.test_reduce_strict_multiple_match_total_match_exception— full liquidation across mixed-cost lots accepted.prop_strict_errors_on_ambiguous_match(renamed fromprop_strict_uses_fifo_on_ambiguous) — proptest now asserts the spec-correct behavior. The previous proptest had inverted expectations with a misleading comment that claimed it matched Python beancount.test_check_ambiguous_lot_match_reports_once— end-to-end integration test against the exact Ambiguous booking reduction not detected (follow-up to conformance testing) #737 input. Asserts exactly ONE E4003 diagnostic, guarding against both the original silent-accept bug and any future regression that introduces double-reporting from booking + validator.booking-scenarios.beancountfixture continues to pass — the FIFO/LIFO/NONE/STRICT_WITH_SIZE accounts now work for the right reason (per-account methods) instead of the wrong reason (silent-swallow + engine default).Verification
cargo test --all-features— 3,000+ tests pass, including all the new tests and the previously-failingtest_booking_scenarios_validates.cargo clippy --all-features --all-targets -- -D warningsclean.cargo fmt --all -- --checkclean.cargo check -p rustledger-wasm --target wasm32-unknown-unknownclean.cargo check -p rustledger-ffi-wasi --all-featuresclean.Commit history
fix(booking): detect ambiguous lot match in STRICT mode— originalreduce_strictfix.fix(booking): propagate errors, track per-account booking methods— silent swallow removed, per-account methods added,rustledger checkwired up, double-report prevention.fix(booking): apply per-account methods across all consumers— LSP, FFI, WASM, loader all updated viaregister_account_methods.Closes #737
🤖 Generated with Claude Code