Skip to content

fix(booking): detect ambiguous lot match + track per-account methods - #745

Merged
robcohen merged 4 commits into
mainfrom
fix/issue-737-ambiguous-booking
Apr 10, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/issue-737-ambiguous-booking

Conversation

@robcohen

@robcohen robcohen commented Apr 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Originally a one-line bug: STRICT booking silently accepted wildcard reductions (-5 AAPL {}) against inventories holding lots at different costs, instead of raising AmbiguousMatchError. Investigation surfaced a second latent bug in the same layer — the BookingEngine was using a single engine-wide booking method for every account, ignoring per-account FIFO / LIFO / NONE / HIFO / STRICT_WITH_SIZE / AVERAGE declarations on open directives. The silent swallow in book.rs was compensating for that by dropping the spurious errors it produced.

This PR fixes all three layers of the problem:

  1. reduce_strict detects real ambiguity — aligning with the formal spec/tla/STRICTCorrect.tla model (which the previous implementation contradicted).
  2. BookingEngine respects per-account booking methods — new account_methods map + set_account_method / register_account_methods APIs, wired into every consumer.
  3. book.rs propagates errors instead of swallowing them — errors flow cleanly through convert_core_booking_error and are reported exactly once.

Closes #737.

What changed

Core fix: ambiguous lot match detection (rustledger-core)

reduce_strict previously 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:

  1. Interchangeable lots fast path: if all matched lots share the same (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.
  2. Total-match exception: if the reduction equals the sum of all matched units, the user is liquidating the entire matched inventory and lot order is irrelevant — accept (mirrors reduce_strict_with_size).
  3. Otherwise: return BookingError::AmbiguousMatch.

Expanded doc comment on reduce_strict explains the interchangeable-lots heuristic and where a stricter spec-derived check would differ.

Per-account booking methods (rustledger-booking)

  • New BookingEngine::account_methods: FxHashMap<InternedStr, BookingMethod> override map.
  • New set_account_method(account, method) and method_for(&account) APIs.
  • New convenience register_account_methods(iter) that scans any directive iterator and registers methods from open directives in one call.
  • Both book() and apply() use method_for() so per-account methods apply consistently.
  • New BookingError::AmbiguousMatch { account, currency, num_matches } variant; InsufficientUnits gains an account field.
  • New convert_core_booking_error helper to map rustledger_core::BookingError → BookingError with account context.

Error propagation in book.rs

book.rs no longer silently swallows inv.reduce errors. 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 BookingEngine now registers per-account methods before booking:

  • rustledger/src/cmd/check.rs
  • rustledger-loader/src/process.rs
  • 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)

Before this PR, LSP diagnostics and the FFI path would have booked every account against STRICT regardless of declared method.

Deduplication in rustledger check

  • New booking_errors bucket alongside interpolation_errors.
  • Failed-booking transaction indices are tracked; spanned_directives is filtered before being passed to the validator so the validator's independent lot-matching pass doesn't double-report the same diagnostic.
  • Booking errors emitted as E4xxx (E4001 NoMatchingLot, E4002 InsufficientUnits, E4003 AmbiguousMatch) with phase="validate".
  • Library-level validate() entry point still reports these errors itself, so LSP/embedded consumers that call validate() directly without going through booking still get the diagnostics.

Before / After

Issue input ({} cost spec against two lots at different costs):

2024-01-01 open Assets:Stock AAPL "STRICT"
...
2024-01-15 * "Buy lot 1"
  Assets:Stock 10 AAPL {150 USD}
  Assets:Cash -1500 USD
2024-01-20 * "Buy lot 2"
  Assets:Stock 10 AAPL {160 USD}
  Assets:Cash -1600 USD
2024-02-15 * "Sell - ambiguous"
  Assets:Stock -5 AAPL {}
  Assets:Cash 800 USD
  Income:Gains

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 (returns AmbiguousMatch, 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 via test_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 from prop_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.
  • Existing booking-scenarios.beancount fixture 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-failing test_booking_scenarios_validates.
  • cargo clippy --all-features --all-targets -- -D warnings clean.
  • cargo fmt --all -- --check clean.
  • Issue input produces exactly one E4003 for both explicit-STRICT and default-STRICT variants.
  • cargo check -p rustledger-wasm --target wasm32-unknown-unknown clean.
  • cargo check -p rustledger-ffi-wasi --all-features clean.

Commit history

  1. fix(booking): detect ambiguous lot match in STRICT mode — original reduce_strict fix.
  2. fix(booking): propagate errors, track per-account booking methods — silent swallow removed, per-account methods added, rustledger check wired up, double-report prevention.
  3. fix(booking): apply per-account methods across all consumers — LSP, FFI, WASM, loader all updated via register_account_methods.

Closes #737

🤖 Generated with Claude Code

@robcohen
robcohen requested a review from a team as a code owner April 9, 2026 23:42
Copilot AI review requested due to automatic review settings April 9, 2026 23:42
@codecov

codecov Bot commented Apr 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.77419% with 35 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-booking/src/book.rs 38.59% 35 Missing ⚠️

📢 Thoughts on this report? Let us know!

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 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_strict to allow FIFO only for financially interchangeable lots (same cost number/currency) or full-liquidation “total match”, otherwise return BookingError::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.

@github-actions

github-actions Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 36.9ms ± 0.5ms 22.9 MB
beancount 860.9ms ± 10.3ms 50.1 MB
Comparison 23.3x faster 2.2x less

vs main branch (2026-04-09)

Metric main this PR Change
Time 43.4ms 36.9ms -15.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 Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 99%
BQL Compatibility 100%
Full AST Match 98%
Total Files 784
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 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
robcohen force-pushed the fix/issue-737-ambiguous-booking branch from c1c5529 to 6077e9c Compare April 10, 2026 01:28
@robcohen robcohen changed the title fix(booking): detect ambiguous lot match in STRICT mode fix(booking): detect ambiguous lot match + track per-account methods Apr 10, 2026
robcohen and others added 4 commits April 9, 2026 21:04
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
robcohen force-pushed the fix/issue-737-ambiguous-booking branch from 4a97967 to 8883c4b Compare April 10, 2026 02:23
@robcohen
robcohen added this pull request to the merge queue Apr 10, 2026
Merged via the queue into main with commit 13041a4 Apr 10, 2026
37 of 39 checks passed
@robcohen
robcohen deleted the fix/issue-737-ambiguous-booking branch April 10, 2026 02:35
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]>
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.

Ambiguous booking reduction not detected (follow-up to conformance testing)

2 participants