Repository navigation
refactor: unify InsufficientUnits error type across booking and validate - #751
Conversation
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]>
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-04-11)
What do these numbers mean?
|
There was a problem hiding this comment.
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 canonicalDisplayfor inventory booking failures with account context. - Collapsed
rustledger_booking::BookingErrorinventory variants intoBookingError::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.
✅ Compatibility Test Results
What's tested
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]>
|
Addressed all three Copilot inline comments in 472b33a:
All gates still green: full workspace tests, clippy |
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]>
Summary
Implements #750. Unifies the three independent error types for inventory-level booking failures into a single canonical type with one
Displayimpl.Why
Before this PR, the same logical failure (reduction exceeds available inventory) was encoded as three separate error types with three separate hand-written
Displaystrings across three crates:rustledger_core::BookingErrorcrates/rustledger-core/src/inventory/mod.rsrustledger_booking::BookingErrorcrates/rustledger-booking/src/book.rsInterpolationrustledger_validate::ValidationErrorcrates/rustledger-validate/src/validators/transaction.rs12 match arms across three crates all encoded the same 4-way structure, and the three
Displaystrings 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
rustledger-core: newAccountedBookingError { error: BookingError, account: InternedStr }struct with a single canonicalDisplayimpl covering all four variants. AddedBookingError::with_account(self, account)constructor. The rawBookingErroris still whatInventory::reducereturns (it doesn't know its own account) — but every user-facing rendering goes through the new wrapper.rustledger-booking: collapsedBookingError::{InsufficientUnits, NoMatchingLot, AmbiguousMatch}(3 variants) into a singleBookingError::Inventory(AccountedBookingError)variant with#[error(transparent)]Display.convert_core_booking_errorbecomes a one-liner.rustledger-validate: stopped hand-formatting inventory errors. Each match arm now callsformat!(\"{}\", err.with_account(posting.account.clone())). ~15 lines of hand-rolled format strings deleted.rustledger(cmd/check.rs):code_fornow dispatches on the innercore::BookingErrorvariant of the unifiedBookingError::Inventoryarm.Net: 8 of 12 match arms eliminated, one canonical
Displayimpl, 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)
InsufficientUnitsNot enough units in {account}: requested {req}, available {avail}; not enough to reduceNoMatchingLotNo matching lot for {currency} in {account}AmbiguousMatchAmbiguous lot match for {currency}: {n} lots match in {account}CurrencyMismatchCurrency mismatch in {account}: expected {e}, got {g}The
InsufficientUnitsstring 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 onlyreduction-exceeds-inventoryasserts on wording — it requires\"not enough\", which the new canonical string contains).Test plan
cargo test --workspace --all-features— all suites green, 0 failurescargo clippy --all-features --all-targets -- -D warnings— cleancargo fmt --all -- --check— cleantest_insufficient_units_display_contains_not_enough) passes, now exercising the unified path viaBookingError::Inventory(core_err.with_account(...))rustledger-core/tests/tla_proptest.rsAmbiguousMatchpattern-match still works (it uses the unchangedrustledger_core::BookingError, not the booking-layer wrapper)reduction-exceeds-inventoryremains green (inherited from fix: restore "not enough" phrasing for InsufficientUnits booking error #749)reduction-no-matching-lotremains green (only assertsvalidate: error, no wording check)Risks
rustledger_booking::BookingError. In-tree, onlycrates/rustledger/src/cmd/check.rspattern-matches on the removed variants, and that's updated. Any out-of-tree consumer pattern-matching onBookingError::{InsufficientUnits, NoMatchingLot, AmbiguousMatch}will get a compile error and need to match onBookingError::Inventory(inner)+inner.errorinstead.\"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