Skip to content

refactor: unify InsufficientUnits error type across booking and validate - #751

Merged
robcohen merged 2 commits into
mainfrom
fix/issue-750-unify-booking-error
Apr 11, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/issue-750-unify-booking-error

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Implements #750. Unifies the three independent error types for inventory-level booking failures into a single canonical type with one Display impl.

Why

Before this PR, the same logical failure (reduction exceeds available inventory) was encoded as three separate error types with three separate hand-written Display strings across three crates:

Type Location Variants
rustledger_core::BookingError crates/rustledger-core/src/inventory/mod.rs 4 (no account context)
rustledger_booking::BookingError crates/rustledger-booking/src/book.rs 4 wrapped + Interpolation
rustledger_validate::ValidationError crates/rustledger-validate/src/validators/transaction.rs Hand-formatted from core

12 match arms across three crates all encoded the same 4-way structure, and the three Display strings drifted apart — that was the root cause of #748, where the booking layer's "insufficient units: need X but only Y available" bypassed the validator's "Not enough units in ..." and dropped the phrasing the pta-standards conformance suite asserts on.

What changed

  1. rustledger-core: new AccountedBookingError { error: BookingError, account: InternedStr } struct with a single canonical Display impl covering all four variants. Added BookingError::with_account(self, account) constructor. The raw BookingError is still what Inventory::reduce returns (it doesn't know its own account) — but every user-facing rendering goes through the new wrapper.

  2. rustledger-booking: collapsed BookingError::{InsufficientUnits, NoMatchingLot, AmbiguousMatch} (3 variants) into a single BookingError::Inventory(AccountedBookingError) variant with #[error(transparent)] Display. convert_core_booking_error becomes a one-liner.

  3. rustledger-validate: stopped hand-formatting inventory errors. Each match arm now calls format!(\"{}\", err.with_account(posting.account.clone())). ~15 lines of hand-rolled format strings deleted.

  4. rustledger (cmd/check.rs): code_for now dispatches on the inner core::BookingError variant of the unified BookingError::Inventory arm.

Net: 8 of 12 match arms eliminated, one canonical Display impl, zero hand-formatted duplicates. Adding a fifth booking failure variant now means touching one crate, not three.

Canonical Display strings (locked by tests and conformance)

Variant Display
InsufficientUnits Not enough units in {account}: requested {req}, available {avail}; not enough to reduce
NoMatchingLot No matching lot for {currency} in {account}
AmbiguousMatch Ambiguous lot match for {currency}: {n} lots match in {account}
CurrencyMismatch Currency mismatch in {account}: expected {e}, got {g}

The InsufficientUnits string is byte-for-byte identical to the one locked in #749 — so #749's regression test passes unchanged, now exercising the new unified path. The other three strings are equivalent rewordings of the pre-existing validator messages (I verified against pta-standards that only reduction-exceeds-inventory asserts on wording — it requires \"not enough\", which the new canonical string contains).

Test plan

  • cargo test --workspace --all-features — all suites green, 0 failures
  • cargo clippy --all-features --all-targets -- -D warnings — clean
  • cargo fmt --all -- --check — clean
  • Booking layer regression: InsufficientUnits message no longer contains 'not enough' #748 regression test (test_insufficient_units_display_contains_not_enough) passes, now exercising the unified path via BookingError::Inventory(core_err.with_account(...))
  • rustledger-core/tests/tla_proptest.rs AmbiguousMatch pattern-match still works (it uses the unchanged rustledger_core::BookingError, not the booking-layer wrapper)
  • pta-standards reduction-exceeds-inventory remains green (inherited from fix: restore "not enough" phrasing for InsufficientUnits booking error #749)
  • pta-standards reduction-no-matching-lot remains green (only asserts validate: error, no wording check)

Risks

  • Public API break on rustledger_booking::BookingError. In-tree, only crates/rustledger/src/cmd/check.rs pattern-matches on the removed variants, and that's updated. Any out-of-tree consumer pattern-matching on BookingError::{InsufficientUnits, NoMatchingLot, AmbiguousMatch} will get a compile error and need to match on BookingError::Inventory(inner) + inner.error instead.
  • CurrencyMismatch now produces a real user-facing message (\"Currency mismatch in {account}: ...\") where previously the validator silently ignored it. This is strictly an improvement — the comment in the old code was \"This shouldn't happen in normal validation\" — but it's a behavior change in edge cases. If you'd prefer to preserve silent-ignore, I can add an explicit skip in the validator.

Related

Closes #750

Before this change, the same logical failure ("reduction exceeds
available inventory") was encoded as three separate error types with
three separate hand-written Display strings across three crates:

  - `rustledger_core::BookingError` — inventory-level, no account
  - `rustledger_booking::BookingError` — wraps core, adds account
  - `rustledger_validate::ValidationError` — hand-formatted from core

Twelve match arms across three crates all encoded the same 4-way
structure (`InsufficientUnits`, `NoMatchingLot`, `AmbiguousMatch`,
`CurrencyMismatch`), and the three Display strings drifted apart —
that was the root cause of #748, where the booking layer's "insufficient
units: need X but only Y available" bypassed the validator's "Not enough
units in ..." and dropped the phrasing the pta-standards conformance
suite asserts on.

This commit unifies the user-facing wording into a single
`rustledger_core::AccountedBookingError { error, account }` type with
one canonical `Display` impl per variant, constructed via
`BookingError::with_account(self, account)`:

  - `rustledger-core`: add `AccountedBookingError` struct + Display +
    `BookingError::with_account` constructor. The raw `BookingError`
    still exists for `Inventory::reduce` (which doesn't know its own
    account), but every user-facing rendering goes through the new type.

  - `rustledger-booking`: collapse `BookingError::{InsufficientUnits,
    NoMatchingLot, AmbiguousMatch}` (3 variants) into a single
    `BookingError::Inventory(AccountedBookingError)` variant with
    transparent Display. `convert_core_booking_error` becomes a
    one-liner: `BookingError::Inventory(err.with_account(account))`.

  - `rustledger-validate`: stop hand-formatting inventory errors.
    Each match arm now calls `format!("{}", err.with_account(...))`
    and assigns the appropriate `ErrorCode`. ~15 lines of hand-rolled
    format strings deleted.

  - `rustledger`: `cmd/check.rs` `code_for` now dispatches on the
    inner `core::BookingError` variant of the unified
    `BookingError::Inventory` arm.

Net: 8 of 12 match arms eliminated, and no independent Display strings
remain that can drift apart. Adding a fifth booking failure variant
now means touching one crate, not three.

The #748 regression test from #749 still passes unchanged (it exercises
the new path via `BookingError::Inventory(core_err.with_account(...))`,
which is the same code path `rledger check` and the validator now use).

Canonical Display strings (locked by the test and by pta-standards):
  - InsufficientUnits: "Not enough units in {account}: requested {req},
    available {avail}; not enough to reduce"
  - NoMatchingLot:     "No matching lot for {currency} in {account}"
  - AmbiguousMatch:    "Ambiguous lot match for {currency}: {n} lots
    match in {account}"
  - CurrencyMismatch:  "Currency mismatch in {account}: expected {e},
    got {g}"

Closes #750

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner April 11, 2026 12:49
Copilot AI review requested due to automatic review settings April 11, 2026 12:49
@codecov

codecov Bot commented Apr 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.78378% with 18 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
.../rustledger-validate/src/validators/transaction.rs 19.04% 17 Missing ⚠️
crates/rustledger-booking/src/book.rs 90.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Apr 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 36.9ms ± 0.5ms 22.8 MB
beancount 859ms ± 4.2ms 50.1 MB
Comparison 23.3x faster 2.2x less

vs main branch (2026-04-11)

Metric main this PR Change
Time 41.9ms 36.9ms -11.9% 🟢
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

Unifies inventory-level booking failure reporting across rustledger-core, rustledger-booking, rustledger-validate, and the rustledger CLI by introducing a single canonical, account-aware error wrapper and delegating user-facing formatting to it.

Changes:

  • Added rustledger_core::AccountedBookingError + BookingError::with_account() to provide one canonical Display for inventory booking failures with account context.
  • Collapsed rustledger_booking::BookingError inventory variants into BookingError::Inventory(AccountedBookingError) and simplified core→booking error conversion.
  • Updated validator and CLI error rendering / code mapping to operate on the unified inventory error shape.

Reviewed changes

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

Show a summary per file
File Description
crates/rustledger/src/cmd/check.rs Routes booking errors through BookingError::Inventory and maps error codes based on the inner core::BookingError variant.
crates/rustledger-validate/src/validators/transaction.rs Replaces hand-formatted inventory error messages with formatting via err.with_account(posting.account.clone()).
crates/rustledger-core/src/lib.rs Re-exports the new AccountedBookingError type from the core crate.
crates/rustledger-core/src/inventory/mod.rs Introduces AccountedBookingError + canonical Display and adds BookingError::with_account() constructor.
crates/rustledger-booking/src/book.rs Replaces multiple inventory-specific BookingError variants with a single transparent Inventory(AccountedBookingError) variant and updates the pinned InsufficientUnits display test.

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

Comment thread crates/rustledger/src/cmd/check.rs Resolved
@github-actions

github-actions Bot commented Apr 11, 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

Three inline comments on PR #751, all legitimate:

1. `CurrencyMismatch` mapped to `E4001` (NoMatchingLot) produced a
   misleading "Currency mismatch in ..." message under that code.
   Fix: unify the rendering — CurrencyMismatch is semantically a
   specialization of NoMatchingLot (there is no lot for the given
   currency in this inventory), so the canonical `AccountedBookingError`
   Display now renders it with the same "No matching lot for X in Y"
   phrasing. The `E4001` code is now semantically accurate, and
   consumers filtering on that code no longer need to special-case it.

2. Validator's direct `inv.reduce()` path still silently ignored
   `CurrencyMismatch` even though the booking-engine path now surfaced
   it via `cmd/check.rs`. Same condition, two different behaviors.
   Fix: replace the silent-ignore in `validators/transaction.rs` with
   the same `err.with_account(...)` formatting under
   `ErrorCode::NoMatchingLot`, mirroring the booking-engine path.

   The variant remains defensive — no `Inventory::reduce` path in
   `rustledger-core` currently emits it — but if a future emission site
   is added, both paths now handle it identically.

3. No tests pinned the new `AccountedBookingError::Display` wording for
   three of its four variants. The whole point of the unification is
   that Display is the single source of truth, and a single source of
   truth with no tests is one refactor away from drifting again — which
   is exactly the failure mode that produced #748.

   Fix: add four targeted unit tests in `rustledger-core/src/inventory/mod.rs`
   covering every `AccountedBookingError` variant. Each test asserts
   the key substrings that matter (conformance assertions, account
   name, numbers/currency) without over-pinning exact wording, so
   small stylistic tweaks don't break the tests but material semantic
   changes do.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@robcohen

Copy link
Copy Markdown
Member Author

Addressed all three Copilot inline comments in 472b33a:

  1. CurrencyMismatch → E4001 mapping (cmd/check.rs:1122) — Went with option (a) from the suggestion. CurrencyMismatch is semantically a specialization of NoMatchingLot (there is no lot for the given currency in this inventory), so the canonical AccountedBookingError::Display now renders it with the same "No matching lot for X in Y" phrasing. The E4001 code is now semantically accurate, and consumers filtering on that code no longer need to special-case it.

  2. Validator silent-ignore inconsistency (transaction.rs:437) — Replaced the silent-ignore branch with the same err.with_account(...) formatting under ErrorCode::NoMatchingLot, mirroring the booking-engine path via cmd/check.rs. Both paths now handle CurrencyMismatch identically. The variant remains defensive (no Inventory::reduce path currently emits it), but if a future emission site is added, both paths will surface it consistently.

  3. Missing Display tests (inventory/mod.rs:180) — Added four targeted unit tests in rustledger-core/src/inventory/mod.rs covering every AccountedBookingError variant (InsufficientUnits, NoMatchingLot, AmbiguousMatch, CurrencyMismatch). Each test asserts the key substrings that matter (conformance assertions, account name, numbers/currency) without over-pinning exact wording, so stylistic tweaks don't break the tests but material semantic changes do. Together with the existing test_insufficient_units_display_contains_not_enough booking-layer test from fix: restore "not enough" phrasing for InsufficientUnits booking error #749, the "single source of truth" Display now has pinning at every layer that uses it.

All gates still green: full workspace tests, clippy -D warnings, fmt.

@robcohen
robcohen added this pull request to the merge queue Apr 11, 2026
Merged via the queue into main with commit 4ebba6a Apr 11, 2026
47 of 53 checks passed
@robcohen
robcohen deleted the fix/issue-750-unify-booking-error branch April 11, 2026 14:50
robcohen added a commit that referenced this pull request Apr 11, 2026
Bumps the whole workspace from 0.11.0 to 0.12.0 (minor version bump
under pre-1.0 semver because the cycle since 0.11.0 includes
user-visible breaking changes that release-plz's auto-detection
missed).

release-plz auto-generated a v0.11.1 patch bump from the `fix:` /
`feat:` commits since 0.11.0. That's too conservative. The cycle
since 0.11.0 shipped the following breaking changes, all merged as
`refactor:` / `fix:` without the `!` conventional-commit marker:

- **`rustledger_booking::BookingError`** collapsed three variants
  (`InsufficientUnits`, `NoMatchingLot`, `AmbiguousMatch`) into a
  single `Inventory(AccountedBookingError)` variant (#751). Out-of-tree
  consumers pattern-matching on the old variants break.

- **`rustledger_core::AccountedBookingError`** added as a new
  canonical user-facing type with `BookingError::with_account()` as
  the constructor (#751). Not a break on its own, but part of the
  unification.

- **`rustledger_lsp::handlers::diagnostics::all_diagnostics`**
  signature changed to take an additional `other_buffer_overlays:
  &[(u16, &[Spanned<Directive>])]` parameter for multi-buffer LSP
  overlays (#760 / #764).

- **`rustledger_lsp::handlers::diagnostics::validation_errors_to_diagnostics`**
  signature changed to take an owned `Vec<Spanned<Directive>>`
  instead of borrowed slices (#758). Optimizes a hot path but breaks
  the function's public signature.

- **`rustledger_loader::LoadError::IncludeCycle`** Display format
  rewritten to match Python beancount's `"Duplicate filename
  parsed: ..."` wording (#767). Substring-matching consumers break.

Under pre-1.0 semver, any breaking change should bump the minor
version (0.x → 0.(x+1)). So 0.11.0 → 0.12.0 is correct.

Highlights since 0.11.0:

### Breaking

- Unified `BookingError` under a single `Inventory` variant with one
  canonical `Display` impl, preventing the wording drift that
  produced #748 (#751).
- `LoadError::IncludeCycle` Display now begins with `"Duplicate
  filename parsed: "` to match beancount's wording for conformance
  (#767).
- LSP `all_diagnostics` and `validation_errors_to_diagnostics`
  signatures changed to support the multi-buffer overlay and avoid
  double-cloning directive lists (#758 / #764).

### Features

- LSP live overlay so in-memory buffer edits reflect in diagnostics
  before save, for both the current file (#685 / #758) and any other
  open buffer in a multi-file ledger (#760 / #764).
- Parser `Vec::with_capacity` hints with DoS caps on `source.len()`
  heuristics (#754).
- `working_inventories` cloning in the booking engine now only
  touches accounts actually referenced in the transaction, and
  dedupes repeated account references (#756).

### Fixes

- `InsufficientUnits` booking error wording restored to `"Not enough
  units in ..."` so pta-standards `reduction-exceeds-inventory`
  conformance assertion passes (#748 / #749).
- `noduplicates` plugin now hashes flag, tags, links, cost, and
  price in addition to date and narration — complete beancount
  `hash_entry` parity (#746 / #747).
- Parser test suite: 14 fake-coverage tests replaced with real tests
  that exercise the functions they claim to cover (#766).
- All Copilot inline review comments on #754-#763, #766, #767
  addressed in fix commits.
- Closed PRs #768 (dead incremental parser) and #769 (hallucinated
  simdutf8 API) — no code shipped from these.

### Internal

- Forbid-unsafe-code invariant now has a dedicated CI check and
  pre-push hook (#770).
- New pre-push `cargo check` hook to catch compile errors before PRs
  are opened (#770).

This commit supersedes release-plz's auto-generated v0.11.1 proposal
to produce the minor bump the breaking changes require.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@robcohen robcohen mentioned this pull request Apr 11, 2026
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.

Unify InsufficientUnits error type across rustledger-core, -booking, and -validate

2 participants