Skip to content

refactor: validate phases + PluginOp protocol + pipeline (closes #1115, #1117) - #1116

Merged
robcohen merged 23 commits into
mainfrom
refactor/validate-phase-split
May 15, 2026
Merged

robcohen merged 23 commits into
mainfrom
refactor/validate-phase-split

Conversation

@robcohen

@robcohen robcohen commented May 14, 2026 •

Copy link
Copy Markdown
Member

Summary

What started as a focused validate phase split (closing #1115) grew into a comprehensive correctness refactor of the loader pipeline and plugin protocol. The scope settled at three intertwined changes:

  1. Validate phase split — ValidationSession with Phase::Early (pre-booking) and Phase::Late (post-booking). Replaces the INTERPOLATED_MARKER metadata side-channel from chore(compat): classify 3 sum-number-by-currency mismatches as known-Rust divergences (refs #1112) #1114 with type-checked phase ordering.
  2. PluginOp transformation-record protocol — PluginOutput.directives: Vec<DirectiveWrapper> → ops: Vec<PluginOp> (Keep / Modify / Insert / Delete). Span identity preserved by construction, not best-effort.
  3. Loader pipeline restructure — synth/regular plugin split, partition-based failed-booking handling, single canonical sort.

Closes #1115. Closes #1117.

Pipeline

Before                          After
1. Sort                         1. Sort
2. Book                         2. Synth plugins (auto_accounts, document_discovery)
3. Plugins                      3. Early validation (account presence, lifecycle, structural)
4. Validate                     4. Book
                                5. Partition (failed-booking txns set aside)
                                6. Regular plugins (file plugins + extras, on booked subset)
                                7. Late validation (balance, currency, inventory)
                                8. Finalize (unused-pad warnings)
                                9. Re-merge (booked + failed → final Ledger.directives)

Each step has a load-bearing reason — see numbered comments in crates/rustledger-loader/src/process.rs.

Breaking changes

This PR isn't backward-compatible. Specifically:

Removed Replacement
rustledger_validate::validate() and four spanned/today variants ValidationSession::new(opts).run_phase(_, Early, today) → run_phase(_, Late, today) → finalize()
PluginOutput { directives, errors } PluginOutput { ops, errors } where PluginOp { Keep(i) | Modify(i, w) | Insert(w) | Delete(i) }
INTERPOLATED_MARKER const + meta-tagging Phase split — Early validates before booking prunes
run_plugins(..) 6-arg signature 7-arg signature with PluginPass { PreBookingSynth | PostBooking | All }
run_booking returns Vec<usize> of failed indices Returns (booked, failed): (Vec<Spanned<Directive>>, Vec<Spanned<Directive>>)

Standalone callers (LSP, FFI, tests) use PluginPass::All to preserve the one-pass shape; loader uses the split.

New public types

  • rustledger_validate::Phase, ValidationSession
  • rustledger_loader::PluginPass
  • rustledger_plugin_types::PluginOp
  • NativePlugin::is_synth() trait method (default false; AutoAccountsPlugin overrides to true)

Bugs caught and fixed along the way

Real correctness bugs (not new — surfaced by the refactor):

  • Duplicate Open synthesis in split_expenses, capital_gains_classifier (both branches), and effective_date. The plugins emitted Open directives without checking whether the user had already declared them, cascading E1002 (AccountAlreadyOpen) in late validation. Fixed by adding the existing_opens filter that currency_accounts and zerosum already used.
  • Multi-currency pad regression — my own retain-too-eager bug; a single Pad must remain available for subsequent Balance assertions in different currencies. Fixed by tracking padded_currencies: FxHashSet<InternedStr> instead of a single used: bool.
  • Future-dated pads leaking into earlier balances — phase split moved all Pad processing into Early, so by Late, pending_pads contained future-dated entries. Filter pending_pads by pad.date < bal.date.
  • Duplicate same-day Close double-emitting AccountCloseNotEmpty — late phase needed late_close_processed: FxHashSet<(InternedStr, NaiveDate)> to skip the duplicate.
  • Plugin error source locations were silently dropped — PluginError::source_file / line_number now flow into LedgerError::location.

Three regression tests pin each of these. Also added 6 new validate-crate tests for phase semantics and one loader integration test for the partition behavior.

Process correctness

  • apply_plugin_ops validates the partition invariant — every input index must appear in exactly one of {Keep, Modify, Delete}. Protocol violations get a PLUGIN error; directives is left untouched.
  • Modify(i, w) always inherits directives[i]'s span and file_id — plugins can't accidentally lose source identity by emitting a wrapper with different location fields.
  • Insert(w) resolves the wrapper's filename against the source map: real-file matches inherit that file's file_id + line-start span; synthetic origins ("<auto_accounts>") get SYNTHESIZED_FILE_ID.
  • Failed-booking transactions partitioned out of the post-booking flow — they don't reach regular plugins or late validation, so cascading errors are suppressed at the source rather than at lookup time.

Documentation refresh

Touched every doc surface that referenced the old APIs:

  • crates/rustledger-validate/README.md, crates/rustledger-plugin-types/README.md
  • docs/guides/custom-plugins.md, docs/development/contributing-plugins.md, docs/reference/plugins.md, docs/reference/architecture.md, docs/reference/adr/0001-crate-organization.md
  • spec/core/wasm-plugins.md, spec/impl/architecture.md, spec/project/compatibility.md
  • AGENTS.md, CLAUDE.md, top-level README.md, packages/mcp-server/README.md
  • All 4 examples/wasm-plugin*/src/lib.rs reference implementations
  • 7 inline source-comment pipeline summaries across LSP / WASM / CLI crates

Verified post-edit: no stale PluginOutput { directives literals, validate_with_options call sites, or old-order pipeline summaries remain anywhere outside CHANGELOGs and intentional migration notes. Error-code and plugin counts reconciled across 10+ surfaces.

Verification

  • cargo test --workspace --all-features — green (2657+ tests across 52 groups).
  • cargo clippy --workspace --all-features --all-targets -- -D warnings — clean.
  • cargo doc -p rustledger-validate --no-deps --all-features with RUSTDOCFLAGS=-Dwarnings — clean.
  • BQL compat suite locally: 100% Check / 100% BQL / 99% Full AST on 786 fixtures.
  • Multi-currency pad regression test pinning the bug that refactor: validate phases + PluginOp protocol + pipeline (closes #1115, #1117) #1116's own retain refactor would have introduced.
  • Duplicate-Open regression tests across three plugins.
  • Phase-ordering debug-assert regression tests (double-Early, Late-before-Early).
  • Partition regression test exercising NoMatchingLot + auto_tag round-trip.

Out of scope / follow-ups

  • Zero-pruned interpolated postings bypass currency-constraint validation #1118 filed and closed as not-a-bug: zero-pruned interpolated postings bypass currency-constraint validation — Python beancount has the same behavior, so this isn't a divergence.
  • Plugin protocol changes break Python and WASM plugins built against the old directives shape. Per project policy (pre-1.0), this is acceptable.
  • The 6 reshaped crates don't have ## [Unreleased] CHANGELOG headings; release-plz convention is to inject on release.

🤖 Generated with Claude Code

…phases (closes #1115)

The `INTERPOLATED_MARKER` side channel introduced in #1114 was a
working but ugly workaround for a real conflict: rledger preserves
zero-value interpolated postings during booking (to match #877's
strictness around unopened-account references), then drops them
post-validation via a tag-and-strip dance through `Posting.meta`.

This commit replaces that scheme with a phase split inside the
validate crate, removing the metadata side channel entirely.

## What changed

### `rustledger-validate`

  * New `Phase::{Early, Late}` enum and `ValidationSession` struct.
    The session carries `LedgerState` across phases so account /
    commodity / pad bookkeeping accumulated by `Early` is visible to
    `Late`'s balance / inventory checks.
  * Per-kind validators split where the contract requires it:
      - `validate_transaction` → `validate_transaction_early`
        (structure + account-presence + lifecycle) and
        `validate_transaction_late` (currency-constraint + balance +
        inventory).
      - `validate_balance` → `validate_balance_early` (account-exists)
        and `validate_balance_late` (pad application + assertion
        check).
      - `validate_close` → `validate_close` (mark closed) and
        `validate_close_late` (non-zero-balance warning, which needs
        post-booking inventory state).
  * Legacy `validate()`, `validate_with_options()`, `validate_*_with_today()`
    keep their signatures and behavior — internally they now chain
    `Early` + `Late` via the session and produce identical output to
    the pre-split implementation. Pinned by
    `test_validate_chained_matches_explicit_phases`.

### `rustledger-loader::process`

  Pipeline reordered to: sort → plugins → `validate_early` → booking
  → `validate_late`. Plugins now run BEFORE booking so plugins like
  `auto_accounts` (which synthesizes Open directives) get a chance
  to register accounts before the early-phase E1001 check runs.
  This is a deliberate deviation from Python beancount's
  plugins-after-booking ordering — the built-in plugins we ship
  (`auto_accounts`, `implicit_prices`, document discovery) don't
  need booked state. See the `Phase` doc + CLAUDE.md's new
  "Python Compatibility Policy" section.

  The `prune_zero_interpolated_postings` step from #1114 is deleted.

### `rustledger-booking::interpolate`

  Booking once again unconditionally prunes zero-value interpolated
  postings, restoring the pre-7706be9c behavior. The early-phase
  validator runs BEFORE this, so the #877 invariant (catching E1001
  on elided posting to unopened account) is preserved via phase
  ordering instead of via a metadata marker.

  `INTERPOLATED_MARKER` const + the `posting.meta.insert(...)` block
  are deleted. `pub use` from `lib.rs` is dropped. Three
  preserves-zero tests are renamed and flipped to assert pruning
  (`test_interpolate_balanced_cost_prunes_zero_posting` etc.); the
  separate `test_zero_value_posting_preserved_for_validation` is
  deleted (replaced by the end-to-end loader-level
  `test_zero_interpolated_posting_keeps_e1001_on_unopened_account`
  added in #1114, which still passes).

### `CLAUDE.md`

  New "Python Compatibility Policy" section codifies the
  match-but-fix-fixable-bugs rule and the deliberate-deviation
  checklist so future strictness decisions have a defined rubric.

## Verification

  * `cargo test -p rustledger-booking -p rustledger-validate -p rustledger-loader -p rustledger --all-features` — all green.
  * `cargo clippy ... -- -D warnings` clean.
  * `cargo fmt --all -- --check` clean.
  * `#877` reproducer end-to-end:
    ```
    $ rledger check zero-to-unopened.bean
    E1001 Account Expenses:NeverOpened was never opened
    exit_code: 1
    ```
  * Three new validate-crate unit tests pin the contract:
      - `test_validate_early_emits_e1001_on_elided_posting`
      - `test_validate_late_does_not_duplicate_e1001`
      - `test_validate_chained_matches_explicit_phases`

## Out of scope

  * Plugin-injected directives — the early phase already runs AFTER
    plugins (so injected Opens are visible), but plugin-INJECTED
    elided postings to unopened accounts would still be subject to
    the early account-presence check. This is consistent behavior;
    no plugin in our test corpus exercises this path.
  * User-written Python plugins that depend on POST-booking state
    will see a behavior change (plugins now run pre-booking). No
    such plugin exists in our test corpus.

Closes #1115.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 14, 2026 04:32
@robcohen
robcohen requested a review from a team as a code owner May 14, 2026 04:32
@github-actions

github-actions Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 32.9ms ± 0.4ms 23.8 MB
beancount 883.7ms ± 8.5ms 50.5 MB
Comparison 26.9x faster 2.1x less

vs main branch (2026-05-15)

Metric main this PR Change
Time 40.3ms 32.9ms -18.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 refactors validation into early and late phases so account-presence checks can run before booking while booking restores pruning of zero-value interpolated postings.

Changes:

  • Adds Phase and ValidationSession APIs in rustledger-validate.
  • Splits transaction, balance, and close validators into early/late responsibilities.
  • Reorders loader processing and removes the INTERPOLATED_MARKER side-channel.

Reviewed changes

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

Show a summary per file
File Description
crates/rustledger-validate/src/validators/transaction.rs Splits transaction validation into pre-booking and post-booking phases.
crates/rustledger-validate/src/validators/mod.rs Updates validator re-exports for split validation functions.
crates/rustledger-validate/src/validators/balance.rs Splits balance validation into account-presence and inventory assertion phases.
crates/rustledger-validate/src/validators/account.rs Defers close non-empty balance checks to late validation.
crates/rustledger-validate/src/lib.rs Adds phased validation API/session and updates validation flow/tests.
crates/rustledger-loader/src/process.rs Reorders plugins/validation/booking and wires phased validation into processing.
crates/rustledger-loader/tests/loader_test.rs Updates loader regression tests around zero interpolated postings.
crates/rustledger-booking/src/lib.rs Removes public re-export of the interpolation marker.
crates/rustledger-booking/src/interpolate.rs Removes marker tagging and restores pruning of zero-filled interpolated postings.
CLAUDE.md Documents the Python compatibility policy for deliberate deviations.

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

Comment thread crates/rustledger-loader/src/process.rs Resolved
@github-actions

github-actions Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 786
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 and others added 2 commits May 13, 2026 23:53
Per #1116 self-review: the five `validate*` free-function shortcuts
were keeping the phase-split half-hidden. Callers could pretend
validation was a single call and skip thinking about Early vs Late.
Drop them. `ValidationSession` is the only supported entry now.

## Removed from public API

  * `validate(directives) -> Vec<ValidationError>`
  * `validate_with_options(directives, options) -> Vec<ValidationError>`
  * `validate_with_today(directives, options, today) -> Vec<ValidationError>`
  * `validate_spanned_with_options(directives, options) -> Vec<ValidationError>`
  * `validate_spanned_with_today(directives, options, today) -> Vec<ValidationError>`
  * `fn validate_inner` (was internal, now dead)
  * `fn today` (was internal, now dead)

Callers that just want "validate this list of directives, give me all
errors" now wire three calls explicitly:

```rust
let mut session = ValidationSession::new(options);
let mut errors = session.run_phase(directives, Phase::Early, today);
errors.extend(session.run_phase(directives, Phase::Late, today));
errors.extend(session.finalize());
```

The verbosity is intentional — it surfaces the phase split so callers
think about whether they want to interleave booking between phases.

## Migrated callers

  * `rustledger-lsp/src/handlers/diagnostics.rs` — LSP receives
    already-booked directives, so it runs both phases back-to-back.
  * `rustledger-ffi-wasi/src/jsonrpc/router.rs` — same shape. Added
    `jiff` as a dependency for `Zoned::now()`.
  * `rustledger/benches/pipeline_bench.rs` — inline helper preserves
    bench shape.

## Tests

Integration test files (`tests/validation_integration_test.rs`,
`tests/tla_proptest.rs`) and the bench (`benches/validate_bench.rs`)
each carry a small inline helper that mirrors the deleted shortcut.
Test code unchanged elsewhere. 63 lib tests + integration suite all
pass.

The one time-dependent test (`test_validate_future_date_warning`)
gets an explicit anchor "today" so it's no longer wall-clock
sensitive.

Closes the open question from #1116's self-review about legacy
surface area.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Per #1116 self-review: the five `validate*` free-function shortcuts
were keeping the phase-split half-hidden. Callers could pretend
validation was a single call and skip thinking about Early vs Late.
Drop them. `ValidationSession` is the only supported entry now.

## Removed from public API

  * `validate(directives) -> Vec<ValidationError>`
  * `validate_with_options(directives, options) -> Vec<ValidationError>`
  * `validate_with_today(directives, options, today) -> Vec<ValidationError>`
  * `validate_spanned_with_options(directives, options) -> Vec<ValidationError>`
  * `validate_spanned_with_today(directives, options, today) -> Vec<ValidationError>`
  * `fn validate_inner` (was internal, now dead)
  * `fn today` (was internal, now dead)

Callers that just want "validate this list of directives, give me all
errors" now wire three calls explicitly:

```rust
let mut session = ValidationSession::new(options);
let mut errors = session.run_phase(directives, Phase::Early, today);
errors.extend(session.run_phase(directives, Phase::Late, today));
errors.extend(session.finalize());
```

The verbosity is intentional — it surfaces the phase split so callers
think about whether they want to interleave booking between phases.

## Migrated callers

  * `rustledger-lsp/src/handlers/diagnostics.rs` — LSP receives
    already-booked directives, so it runs both phases back-to-back.
  * `rustledger-ffi-wasi/src/jsonrpc/router.rs` — same shape. Added
    `jiff` as a dependency for `Zoned::now()`.
  * `rustledger/benches/pipeline_bench.rs` — inline helper preserves
    bench shape.

## Tests

Integration test files (`tests/validation_integration_test.rs`,
`tests/tla_proptest.rs`) and the bench (`benches/validate_bench.rs`)
each carry a small inline helper that mirrors the deleted shortcut.
Test code unchanged elsewhere. 63 lib tests + integration suite all
pass.

The one time-dependent test (`test_validate_future_date_warning`)
gets an explicit anchor "today" so it's no longer wall-clock
sensitive.

Closes the open question from #1116's self-review about legacy
surface area.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* New `tests/common/mod.rs` carries `validate`, `validate_with_options`,
  `validate_with_today`, `validate_spanned_with_options`, and a shared
  `test_today()` anchor (2030-01-01) — replaces the inline copies that
  `validation_integration_test.rs` and `tla_proptest.rs` each had.
* Documents the workspace \"today\" convention on `test_today()`:
  tests/benches → 2030-01-01, WASM → 2999-12-31, production → `Zoned::now()`.
* Adds `test_phase_order_early_then_late_then_finalize` to pin the
  emission ordering (E1001 → E2002 → E2003) so future pipeline tweaks
  can't silently reshuffle the error stream that LSP / CLI consumers
  rely on.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen and others added 17 commits May 14, 2026 00:22
…omment

* `rustledger-validate/src/lib.rs`: remove the dangling `[`validate`]`
  intra-doc link in the `Phase` rustdoc — the shortcut was deleted in
  this PR, but the doc reference survived. Documentation CI job was
  failing on this; `build` was failing as a rollup of the same.
* `currency_accounts.rs`: the inline comment explaining why this
  plugin keeps prices claimed \"rustledger runs booking first.\" That
  hasn't been true since plugins moved before booking in this PR.
  Rewrite the comment to match the new pipeline order while preserving
  the actual rationale (the appended neutralizing postings already
  per-currency-balance each group, so keeping the price annotations
  is redundant rather than harmful). Flagged by Copilot inline review.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…oses

When two `Close` directives target the same account on the same date,
the early phase correctly rejects the second one with `AccountClosed`
without overwriting `account_state.closed`. But the late-phase guard
in `validate_close_late` used `closed != Some(close.date)` to skip
already-flagged closes — which incorrectly let BOTH same-day duplicates
through, double-emitting `AccountCloseNotEmpty` (E2010) on the same
non-zero balance.

Fix: track per-account \"late close check already ran\" in
`LedgerState.late_close_processed`. The first late-phase Close
processes the inventory check; subsequent same-account closes (the
duplicates the early phase rejected) become no-ops.

Adds regression test `test_duplicate_same_day_close_emits_close_not_empty_once`
pinning the corrected behavior: exactly one `AccountClosed` from
the duplicate AND exactly one `AccountCloseNotEmpty` from the late
phase, regardless of how many duplicate Close directives exist.

Caught by Copilot inline review on PR #1116.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ow-ups

Addresses four findings from the PR #1116 deep self-review:

* Phase-ordering guard: run_phase now tracks executed phases in a u8
  bitmask. debug_assert! panics on double-Late, double-Early, or
  Late-before-Early; release builds no-op the offending call and return
  an empty Vec. Without this, a second Late pass would double-book
  every transaction's inventory and silently break every subsequent
  balance assertion. Two #[should_panic] regression tests pin the
  debug-build contract.

* Re-key late_close_processed from InternedStr to
  (InternedStr, NaiveDate). The single-account key would silently
  swallow a legitimate close after a reopen if reopen-after-close
  is ever supported (Python permits it under some edge cases). Today
  the early-phase Open check rejects the reopen, so this is latent —
  but the (account, date) form costs nothing and removes a future
  footgun.

* Drain used pads from pending_pads. The vec previously grew for the
  session's lifetime because Balance only marked the last pad
  `used = true` without removing it. The E2003 finalize sweep now
  scans only unused pads. retain(|p| !p.used) at the top of
  validate_balance_late's pad path.

* Public-API rustdoc: replace the ```ignore example block on
  ValidationSession with a compilable one (FFI/LSP integrators can
  now copy-paste); add "Migration from pre-#1116" naming the five
  removed free-functions; add "Preconditions" documenting the
  single-use contract; add "Panics (debug only)" to run_phase and
  run_phase_spanned.

Workspace check + clippy + validate tests (67 unit + 8 proptest +
28 integration + 1 doctest) + loader tests (69 + 7 + 63 + 2) all
green.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Found via second-pass deep PR review of #1116. The phase split moved
ALL Pad processing into the Early phase (because Pad needs to mutate
LedgerState before any Balance runs), so by the time the Late phase
iterates Balance directives every pad on the account is already sitting
in `pending_pads`, regardless of date.

The original single-pass code interleaved Pad registration and Balance
application in date-sorted order, so a Balance only ever saw the pads
that pre-dated it. Post-phase-split, a sequence like:

  2024-01-01  Pad   Assets:Bank  Equity
  2024-01-02  Balance ...                 ← sees [Pad1, Pad2, Pad3]
  2024-02-01  Pad   Assets:Bank  Equity
  2024-02-02  Pad   Assets:Bank  Equity
  2024-02-03  Balance ...

emits E2004 on the first Balance (claiming three pending pads — two of
which are future-dated and shouldn't apply yet) AND uses the latest
future-dated pad to fill the difference, debiting the wrong source.

Fix: in `validate_balance_late`'s pad path, filter `pending_pads` to
those whose date strictly precedes the balance date before counting
for E2004 or selecting which pad applies. Matches Python beancount
semantics ("Pad on date D is effective for the next Balance dated > D").

Also:
* Drop the now-vacuous `!any(used)` clause from the E2004 check — the
  `retain(|p| !p.used)` from the prior commit (05fcba8) makes every
  remaining pad guaranteed unused, so the count check is sufficient.
* Update the rustdoc + inline comments to reflect the tightened
  semantics: Pad → Balance → Pad → Pad → Balance now correctly emits
  E2004 on the second Balance (previously suppressed because the first
  pad's `used = true` flag persisted in the vec).
* Drop the dead `bool` return from `validate_balance_early`; nothing
  consumed it.
* Fall through to the regular balance check when no effective pad is
  available, instead of silently skipping the user's assertion.

Regression test `test_e2004_fires_after_prior_balance_consumed_a_pad`
pins the new behavior. Existing `test_validate_multiple_pads_for_balance`
still passes unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Found via third-pass deep PR review of #1116. Commit 05fcba8's
`retain(|p| !p.used)` was too aggressive: after a Pad serves the FIRST
currency-specific Balance on its target, the retain dropped it from
`pending_pads`, leaving subsequent Balances on the same account in
other currencies with no pad to consume — they fell through to the
regular check and the assertion failed against an unpadded inventory.

The comment at balance.rs:114 ("a pad can apply to multiple
currencies") was load-bearing but no longer enforced.

Fix: track per-currency in PendingPad. Replace `used: bool` with
`padded_currencies: FxHashSet<InternedStr>`. `validate_balance_late`
retains pads that have NOT padded the current currency (instead of
unconditionally dropping any used pad); after applying, it inserts the
currency rather than setting a global flag. `check_unused_pads` /
E2003 now fires on `padded_currencies.is_empty()` — a pad that never
served any currency.

Adds three regression tests:

* `test_pad_serves_multi_currency_balances_on_same_day` — the bug this
  fix closes: Pad → Balance USD → Balance EUR on the same account.
* `test_same_day_pad_does_not_apply_to_same_day_balance` — pins the
  Python `>` semantics already encoded in the date filter (a Pad on
  date D only applies to Balances dated strictly after D), and pins
  that E2003 fires on the orphaned same-day Pad.
* `test_future_pad_does_not_apply_to_earlier_balance` — regression
  test for commit 83369fd's date filter; a Pad dated 2024-06-01 must
  not consume a Balance dated 2024-01-02.

Also documents the date-sorted push invariant that
`effective_idx.last()` relies on.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Fourth-pass deep PR review of #1116 surfaced one substantive cleanup
and three doc/clarity fixes.

* Drop `LedgerState.tolerances` and the write loop in
  `validate_transaction_late`. The accumulator was originally added so
  balance assertions could pick up transaction-derived tolerances, but
  commit 670b447 switched balance tolerance derivation to come from
  `bal.amount.scale()` (or the explicit `bal.tolerance` field) — so
  every transaction was paying an FxHashMap write to a never-read map.
  Removes 11 lines of cold-path work per transaction in the late
  phase.

* Compute `today` once in `process()` instead of calling
  `jiff::Zoned::now().date()` separately for the Early and Late
  phases. Avoids a midnight-crossing edge case where the two phases
  could disagree on the reference date.

* Fix the misleading rustdoc that described the pipeline as
  `... Early -> booking + plugins -> Late`. The actual loader order
  is `plugins -> Early -> booking -> Late` (plugins run BEFORE Early so
  `auto_accounts` can inject Opens before E1001 fires). Updated the
  top-level `Phase` rustdoc, the `ValidationSession` doc, and the
  inline example comment.

* Generalize the `debug_assert!` panic strings on
  `check_phase_ordering` to mention `run_phase{,_spanned}` instead of
  just `run_phase`. Prevents a confusing panic message if the spanned
  variant is the actual misuse site. Existing `#[should_panic]`
  regression tests still match (substring match).

Workspace test suite + clippy clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ase errors

Two cleanups from the deep PR review of #1116.

# 1. Single canonical sort of the directive vec

The loader pipeline previously called `sort_by_cached_key` on the full
`Vec<Spanned<Directive>>` twice: once before booking (with
`has_cost_reduction` as the tie-break so reductions came last) and
once after booking (with `(file_id, span.start)` as the tie-break to
restore display order for BQL / format / validate). On large ledgers
this was wasted O(n log n) work moving large structs.

Now the vec is sorted exactly once into canonical display order at the
top of `process()`. `run_booking` walks the vec via a transient
`Vec<usize>` index sorted by `(date, priority, has_cost_reduction)`;
the original index order preserves the display tie-break by transitivity
through the stable sort. Mutations land in the underlying vec via
index, so the display order is preserved without a second sort.

Effect: one fewer full sort of large structs per `process()` call.
No behavior change in test or compat fixtures.

# 2. Late phase skips checks on transactions whose booking failed

When booking fails on a transaction (e.g. `NoMatchingLot`,
`InsufficientUnits`), the loader emits a `BOOK` error and moves on
without applying the txn to the booking engine's inventory. Pre-fix,
the late-phase validator would then iterate the same (still-unbooked)
transaction and emit additional `TransactionUnbalanced` / inventory
errors, drowning the user in cascading reports for one root cause.

Fix: `run_booking` returns `FxHashSet<(u16, usize)>` of failed
transactions identified by `(file_id, span.start)`. The loader passes
this to `ValidationSession::set_failed_bookings` before running the
Late phase. `validate_phase_inner` checks the set when dispatching
`(Phase::Late, Directive::Transaction(_))` and skips
`validate_transaction_late` entirely for flagged txns. Standalone
callers (no booking, e.g., LSP on parse-only input) have an empty
set and proceed normally.

Regression test `test_set_failed_bookings_skips_late_transaction_checks`
verifies baseline-vs-with-skip: an unbalanced txn emits
`TransactionUnbalanced` when the flag is absent, no such error when
the (file_id, span.start) is in the failed set.

Workspace test suite (248 tests across validate + loader) + clippy
clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Fifth-pass deep PR review of #1116 caught a latent collision in the
failed_bookings skip-set introduced in 9cee964.

All plugin-synthesized directives share `(SYNTHESIZED_FILE_ID, 0)`
as their `(file_id, span.start)` identity (see
`crates/rustledger-loader/src/process.rs` around line 800 where
plugin output falls back to the sentinel). If a plugin like
`auto_tag`, `rx_txn`, `box_accrual`, `no_unused`, or
`rename_accounts` synthesizes a Transaction that then fails booking,
inserting that key into the set would over-match every other
synthesized directive in the same file — silently suppressing
late-phase checks on all of them.

Fix: in `run_booking`, skip the failed-set insertion when
`file_id == SYNTHESIZED_FILE_ID`. For synthesized failures we
accept the cascading-error behavior as the lesser evil (it's no
worse than the pre-9cee9649 baseline for file-authored txns, and
preserves correctness for the synthesized siblings that didn't
fail). Documented the constraint on `set_failed_bookings`.

Workspace test suite + clippy clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Documentation CI job was failing under `RUSTDOCFLAGS=-Dwarnings` because the `set_failed_bookings` rustdoc referenced `[`run_phase_spanned`]` without an associated path — rustdoc resolved it to the same-named free function (none exists) instead of the inherent method. Qualify as `[`run_phase_spanned`](Self::run_phase_spanned)`. Local `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-validate --no-deps --all-features` now builds clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Closes #1117. Restores post-booking semantics for the 6 cost-spec-reading
plugins broken by the original phase-split refactor.

When PR #1116 introduced the validate-phase-split, it moved ALL plugins
to run BEFORE booking so that `auto_accounts` could inject Opens before
Early validation's E1001 fires. The pipeline became:

  sort → plugins → Early → book → Late

But that broke 6 plugins that read `cost.number_per` (filled by the
booking engine):

  - capital_gains_classifier (reads cost.number_per + cost.date)
  - check_average_cost       (reads cost.number_per)
  - implicit_prices          (self-documents post-booking dependency)
  - sell_gains               (reads cost.number_per + price.amount.number)
  - unrealized               (reads cost.number_per to compute cost basis)
  - valuation                (emits postings expecting booker re-processing)

All six silently return wrong results when run pre-booking because
`unwrap_or_default()` on `cost.number_per` gives them zero.

Fix: introduce `PluginPass` enum + split the single plugin call into
two. Only synthesizer plugins (`auto_accounts` and the built-in
`document_discovery` walker) run pre-booking — they synthesize Opens /
Documents that Early needs to see. Everything else (file-declared
plugins + CLI `extra_plugins`) runs after booking, restoring Python
parity for the 6 affected plugins.

New pipeline:

  sort → synth-plugins → Early → book → regular-plugins → Late → finalize

API changes:
  * Add `pub enum PluginPass { PreBookingSynth, PostBooking, All }`
    to rustledger-loader.
  * Add `pass: PluginPass` parameter to `pub fn run_plugins`.
  * `LSP` and other standalone callers pass `PluginPass::All` for the
    historical behavior (one-pass, everything-runs).
  * Loader's `process()` calls `run_plugins(..., PreBookingSynth)`
    before Early and `run_plugins(..., PostBooking)` after booking.

Audit of all 30 native plugins documented in #1117 comment. 24 are
safe to run pre- or post-booking; 6 require post-booking. The split
preserves the auto_accounts pre-booking workaround that motivated
#1115 / #1116 while restoring Python-compat semantics for the rest.

Workspace test suite (validate + loader + plugin + lsp + others —
1100+ tests) + clippy `-D warnings` all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Replaces the `ValidationSession::set_failed_bookings` skip-set
mechanism (introduced 9cee964, hardened 83d3d4e) with a cleaner
directive-partition approach. The previous design had a latent bug
that the deep pipeline review surfaced: `failed_bookings` keys
identified failed transactions by `(file_id, span.start)`, but the
wrapper round-trip in `run_plugins` reconstructs span as
`(line_start, line_start)` — not the original directive-start byte
offset. Any regular plugin that round-trips an existing transaction
through the wrapper protocol (e.g. `auto_tag`, `rename_accounts` —
both common) would change the failed txn's span, breaking the Late
phase's lookup, and cascading errors would return.

The cleanest fix doesn't track identity at all. Instead, immediately
after booking — while indices are still stable — partition the
directives vec into `booked` and `failed`. Regular plugins and the
Late validation phase operate on `booked` only; `failed` is held
aside and re-merged into the final `Ledger.directives` for output so
the user still sees their original input.

Pipeline now:

  sort → synth-plugins → Early
       → book (collects failed_indices)
       → partition (booked, failed)
       → regular-plugins (on booked only)
       → Late (on booked only)
       → finalize
       → merge (booked + failed) → Ledger.directives

Code changes:

* `run_booking` returns `Vec<usize>` of failed indices instead of an
  identity-keyed `FxHashSet`. Indices are valid until the immediate
  partition step.
* Deleted `ValidationSession::set_failed_bookings`,
  `LedgerState.failed_bookings`, and the skip-check in
  `validate_phase_inner` — none are needed once partition handles
  the filtering at the loader layer.
* Deleted the obsolete validate-crate regression test that pinned
  the session-skip semantics; replaced with a loader integration
  test (`test_booking_failure_partitioned_from_late_validation`)
  that exercises end-to-end behavior via a fixture combining a
  failed `NoMatchingLot` with `auto_tag` (the round-tripping plugin
  whose span rewriting broke the prior mechanism).

Asserts in the new test: exactly one `BOOK` error, zero cascading
validation errors, and all three transactions present in the final
`Ledger.directives` output (booking failures don't drop directives
from the user's view).

Workspace test suite (1100+ tests across all crates) + clippy
`-D warnings` clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sixth-pass deep PR review caught two leftover cleanups, both
non-functional:

* `process()` rustdoc still listed a 4-step pipeline; the actual
  pipeline is now 9 steps (sort → synth → Early → book → partition
  → regular plugins → Late → finalize → re-merge). Refreshed the
  doc block so contributors see the real flow without reading the
  body.

* `validate_transaction_early` returned `bool` but every caller
  discarded it — the analogous dead return on `validate_balance_early`
  was already cleaned up in commit 73d8f75; this is the same pattern
  in the sister validator.

No behavior change. Workspace test suite + clippy `-D warnings`
clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…wns partition

Two correctness improvements identified by the deep pipeline review.
Same observable behavior; smaller invariant surface for future
contributors.

# A. Synth classification lives on the plugin

Pre: the loader had a hardcoded `is_synth(name) = matches!(name,
"auto_accounts")` filter. Adding a new synthesizer required editing
this list — easy to miss, drifts from the plugin's own knowledge.

Post: `NativePlugin::is_synth() -> bool { false }` default on the
trait, overridden to `true` on `AutoAccountsPlugin`. The loader's
classifier calls `registry.find(name).is_some_and(NativePlugin::is_synth)`
so each plugin self-classifies. Non-native plugins (WASM / Python)
keep the default `false` — they run post-booking like every other
file-declared beancount plugin.

The registry is now constructed once at the top of `run_plugins`
(was previously built lazily inside the runner loop); cost is
O(n_plugins) struct instantiation and the existing lazy-construction
branch was deleted.

# B. `run_booking` owns its partition

Pre: `run_booking` took `&mut [Spanned<Directive>]`, returned
`Vec<usize>` of failed indices. The caller then partitioned the vec
using those indices. There was a window — between booking's return
and the partition step — where the indices were "valid until the
next mutation", a fragile invariant a future change could break.

Post: `run_booking` takes `Vec<Spanned<Directive>>` by value, returns
`(Vec<Spanned<Directive>>, Vec<Spanned<Directive>>)` — `(booked,
failed)` directly. No external index window: the partition is fait
accompli before the function returns. Booking owns its output shape
end-to-end.

The caller's signature becomes a clean tuple destructure and the
explicit `failed_indices: Vec<usize>` plus partition block in
`process()` collapses to a single `let (mut booked, failed) =
run_booking(directives, ...)`.

# Verification

* Workspace clippy `-D warnings` clean.
* Full workspace test suite (1100+ tests) green.
* No public-API breakage — `PluginPass` enum unchanged; LSP/FFI
  callers of `run_plugins` continue to pass `PluginPass::All`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Replaces `PluginOutput.directives: Vec<DirectiveWrapper>` (a replacement
list) with `PluginOutput.ops: Vec<PluginOp>` (an ordered transformation
record). Eliminates span-fidelity loss through the plugin wrapper
round-trip by construction.

# Why

The old protocol made plugins return a flat list of `DirectiveWrapper`s
with no notion of identity. The loader had to guess which output
directive corresponded to which input, and reconstructed spans from
`(filename, lineno)` — losing the original byte-precise `Span` and
forcing all plugin-transformed directives to point at the line start
instead of the directive start. Late-phase validation errors and rich
error renderers (miette snippets) showed degraded source locations
for any directive that went through a plugin that round-trips
wrappers (auto_tag, rename_accounts, etc.).

# Protocol

```rust
pub enum PluginOp {
    Keep(usize),                       // reuse input[i] with original span
    Modify(usize, DirectiveWrapper),   // new content, inherit input[i]'s identity
    Insert(DirectiveWrapper),          // fresh directive (synthesized span)
    Delete(usize),                     // drop input[i]
}

pub struct PluginOutput {
    pub ops: Vec<PluginOp>,
    pub errors: Vec<PluginError>,
}
```

Every input index must appear in EXACTLY ONE op across
`{Keep, Modify, Delete}`. The loader's `apply_plugin_ops` validates
this invariant and emits a plugin error on violations (forgotten
index, duplicate index, out-of-bounds index).

# Span preservation by construction

The loader materializes the output by walking ops:

* `Keep(i)`        → `directives[i].clone()`           — original span/file_id
* `Modify(i, w)`   → `Spanned { wrapper_to_directive(w), span: directives[i].span, file_id: directives[i].file_id }` — content from `w`, identity from `i`
* `Insert(w)`      → `Spanned { wrapper_to_directive(w), Span(0,0), SYNTHESIZED_FILE_ID }`
* `Delete(_)`      → omitted

Plugins can't accidentally lose source identity. Errors on
plugin-transformed directives now point at the original directive
start.

# What changed

* `rustledger-plugin-types`: new `PluginOp` enum, `PluginOutput.ops`
  replaces `.directives`; `passthrough(len)` constructor for the
  common case.
* `rustledger-plugin`: all 30 native plugins migrated to emit ops:
  - Pure validators (`leaf_only`, `no_duplicates`, `check_*`, etc.):
    emit `Keep(i)` for every input.
  - Per-directive transformers (`auto_tag`, `rx_txn`): emit
    `Modify(i, w)` for transformed, `Keep(i)` otherwise.
  - Insert-only synthesizers (`auto_accounts`, `document_discovery`,
    `implicit_prices`, `forecast`, `generate_base_ccy_prices`,
    `check_closing`, `check_drained`, `close_tree`): `Keep` everything,
    append `Insert(w)` for synthesized output.
  - Transform-and-insert (`currency_accounts`, `effective_date`,
    `box_accrual`, `rename_accounts`, `valuation`, `split_expenses`,
    `zerosum`, `capital_gains_classifier`, `no_unused`): mix `Keep`/
    `Modify`/`Insert`/`Delete`.
  - `test_helpers::materialize_ops` for tests that want to inspect
    a plugin's effective output without going through the loader.
* `rustledger-loader`: new `apply_plugin_ops` helper validates the
  protocol invariant and materializes ops into the directives vec.
  WASM and Python plugin runners now return `Vec<PluginOp>` instead
  of `Vec<DirectiveWrapper>`. Final wrapper→directive conversion
  step deleted (no longer needed — directives is the source of
  truth throughout).
* `rustledger-plugin::runtime`: `PluginManager::execute_all` and
  `WatchingPluginManager::execute_all` materialize ops between
  chained WASM plugins (cross-plugin span identity isn't preserved
  in chains; per-plugin span identity is).
* `rustledger-plugin::python::runtime`: parses Python plugin output's
  replacement list as `Delete(0..input_len) + Insert(...)` —
  pragmatic adaptation since Python plugins use the replacement-list
  protocol natively.
* `rustledger-wasm`, `rustledger-ffi-wasi`: materialize ops at the
  boundary where they round-trip to user-facing directives.

# No backwards compat

The protocol is a breaking change. Old-style plugins that returned
`PluginOutput { directives, errors }` won't compile. Cross-language
plugin protocols (Python, WASM) are likewise broken — by design.

# Verification

* Workspace clippy `-D warnings` clean.
* `cargo test --workspace --all-features` — all green (2657+ tests
  across 52 test groups).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two pre-existing bugs surfaced by the PluginOp protocol audit
(commit a9ceef2):

* `split_expenses` and `capital_gains_classifier`'s `process_long_short`
  / `process_gain_loss` paths emit `PluginOp::Insert(Open ...)` for
  every newly-referenced sub-account without checking whether the user
  has already declared an Open. Result: an E1002 (AccountAlreadyOpen)
  cascade in Late validation whenever the user pre-opened an account
  the plugin happened to name. `currency_accounts` and `zerosum` got
  this right; these two paths missed it.

Fix: collect `existing_opens` in one pre-pass over `input.directives`,
then filter `new_accounts` against that set before emitting the
synthesized `Open` Inserts. Matches the pattern used by
`currency_accounts`.

Also: add a debug-only protocol-invariant assertion to
`test_helpers::materialize_ops`. The helper is intentionally
permissive (it doesn't return errors), but in debug builds it now
panics on out-of-bounds / duplicate / omitted-index op sets — making
plugin-author mistakes loud in unit tests instead of producing
silently surprising materialization. Release builds skip the check
(zero overhead for fuzz / bench paths).

Workspace clippy `-D warnings` clean. `cargo test --workspace
--all-features` green.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Same pre-existing bug as fixed in 8965ec3 for split_expenses and
capital_gains_classifier. effective_date synthesized Open directives
for every account it referenced in inserted transactions, without
checking whether the user had already declared an Open for those
accounts — triggering E1002 (AccountAlreadyOpen) in Late validation
when the user pre-opened a holding account the plugin happened to
name.

Mirrors the pattern in zerosum, currency_accounts, split_expenses,
and capital_gains_classifier: collect existing_opens in a pre-pass
over input.directives, then filter new_accounts against that set
before emitting the synthesized Open Inserts.

Workspace clippy + tests green.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three follow-ups bundled into one commit — each making
plugin-source attribution survive the round trip from plugin output
into the loader's error / directive stream.

# 1. `PluginError::source_file` / `line_number` → `ErrorLocation`

`record_plugin_errors` previously discarded the plugin's
self-reported source location, leaving downstream renderers (CLI,
LSP JSON output, miette) without anywhere to anchor the diagnostic.
Now it builds an `ErrorLocation { file, line, column: 1 }` whenever
the plugin set both `source_file` and `line_number`.

When `source_file` matches a real loaded file, the resolved `path`
from `SourceMap.get_by_path` is used (preserves the include-root
form rather than echoing back whatever literal string the plugin
sent). When `source_file` is a synthetic origin like
`"<auto_accounts>"`, the literal is passed through as
`PathBuf::from(name)` so renderers can still attribute the error
to the originating plugin.

Plugin error column information isn't carried through the wrapper
protocol; defaults to 1.

# 2. `apply_plugin_ops` resolves `Insert` wrapper filename → real file_id

Previously every `Insert(w)` got `(Span::new(0, 0),
SYNTHESIZED_FILE_ID)` regardless of whether the plugin set
`w.filename` / `w.lineno`. Now: if the wrapper's filename matches a
loaded file in the `SourceMap`, the resulting `Spanned<Directive>`
gets that file's `file_id` plus a span at the line start. This is
the same reconstruction path the old pre-PluginOp protocol used —
restoring source attribution for plugins that legitimately emit
"this Open belongs to line N of the user's file" (e.g., a future
`auto_accounts` revision that records the first-use lineno).

Plugin-only attribution (`"<auto_accounts>"`, `"<effective_date>"`,
etc.) still falls back to `SYNTHESIZED_FILE_ID` — those filenames
don't match any loaded file, and that's the correct behavior.

# 3. `record_plugin_errors` phase-tag consistency

The `tag_phase: bool` parameter that special-cased document
discovery is gone. Every plugin error now gets `phase: "plugin"` —
JSON consumers and the LSP can filter on phase uniformly.

# Verification

* `cargo clippy --workspace --all-features --all-targets -- -D warnings` clean.
* `cargo test --workspace --all-features` — all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen and others added 2 commits May 15, 2026 10:50
Six doc files referenced APIs that PR #1116 removed or reshaped.
Refresh them all in one pass so a contributor reading any doc gets
the post-#1116 picture:

* crates/rustledger-validate/README.md — replace the
  validate_with_options example with the three-step
  ValidationSession + Phase::Early + Phase::Late + finalize sequence
  that replaces it.

* crates/rustledger-plugin-types/README.md — rewrite the Quick Start
  example to construct Vec<PluginOp> instead of
  Vec<DirectiveWrapper>. Refresh the type-overview table to describe
  PluginOutput as carrying ops. Add a PluginOp variants table
  (Keep / Modify / Insert / Delete).

* docs/guides/custom-plugins.md — migrate all six example plugins
  (require-tags validator, auto-metadata transformer, currency
  validator, etc.) to the ops protocol. Update unit-test assertions
  to pattern-match PluginOp::Modify(0, _).

* docs/development/contributing-plugins.md — rewrite the MyPlugin
  process skeleton, the Modifying / Adding / Reporting sections,
  and the test-helper assertions to use Keep / Modify / Insert ops.
  Mention is_synth for the pre-booking opt-in.

* docs/reference/plugins.md — refresh the protocol-shape ASCII
  diagram (ops instead of directives). Rewrite the Plugin Execution
  Order section to describe the synth/regular pass split via
  PluginPass + is_synth.

* docs/reference/adr/0001-crate-organization.md — update the
  rustledger-loader pipeline summary from the old
  (sort, book, plugins, validate) order to the new
  (sort, synth, Early, book, regular, Late, finalize) order.

Net diff: +210/-91. No stale PluginOutput-with-directives literals
or validate_with_options call sites remain in any doc.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Final-audit pass found 5 categories of stale references:

# 1. CRITICAL: 4 example WASM plugins were broken against the new API

examples/* crates are not in workspace members, so cargo didn't catch
that their PluginOutput constructions still used the removed
directives field. Users follow these as templates.

* examples/wasm-plugin/src/lib.rs — transformer + warner; emits
  Modify(i, w) when adding the processed tag, Keep(i) otherwise.
  Test asserts matches!(output.ops[0], PluginOp::Modify(0, _)) with
  a local materialize() helper.
* examples/wasm-plugin-template/src/lib.rs — starter template;
  same Modify/Keep pattern at smaller scope.
* examples/wasm-plugin-currency-check/src/lib.rs — pure validator;
  PluginOutput::passthrough(n) + errors. Test asserts every op is
  Keep.
* examples/wasm-plugin-duplicate-detect/src/lib.rs — pure validator;
  same passthrough pattern.

# 2. HIGH: docs/reference/architecture.md pipeline diagram

Replaced the 5-box (PARSE → LOAD → SORT+BOOK → PLUGINS → VALIDATE)
diagram with the new 7-step (sort → synth → Early → book → regular
→ Late → finalize) one. Rewrote the Plugin System paragraph to
describe the synth/regular split via PluginPass + NativePlugin::is_synth.

# 3. MEDIUM: 7 inline pipeline-order comments across LSP/WASM/CLI

Updated each call site's pipeline summary in:
* crates/rustledger-wasm/src/api.rs (validate + query paths)
* crates/rustledger-wasm/src/helpers.rs
* crates/rustledger-wasm/src/parsed_ledger.rs
* crates/rustledger-lsp/src/handlers/diagnostics.rs (both rustdoc
  and inline comment now explicitly document the LSP's deliberate
  single-pass simplification vs the loader's interleaved pipeline)
* crates/rustledger/src/cmd/check.rs

# 4. LOW: Error-code count reconciled to 26 across all surfaces

Audit showed 27/28 scattered across surfaces; actual variant count
in ErrorCode is 26 (5+4+4+4+3+3+1+2 by category). Updated:
crates/rustledger-validate/{Cargo.toml,README.md}, AGENTS.md,
CLAUDE.md, README.md, docs/reference/architecture.md,
spec/impl/architecture.md, packages/mcp-server/README.md.

# 5. LOW: Plugin count updated from 20 to 30

crates/rustledger-plugin/Cargo.toml description and AGENTS.md
table row both said 20; actual count via grep is 30.

# Bonus — spec docs caught by verification grep

* spec/project/compatibility.md — Rust plugin porting example
  rewritten to ops protocol.
* spec/core/wasm-plugins.md — Rust + AssemblyScript plugin
  templates rewritten to ops; corrected the Rust template's import
  path to rustledger_plugin_types.

Workspace cargo check + clippy -D warnings clean. Sanity grep for
stale PluginOutput / pipeline / count references returns zero
matches (verified post-edit).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen robcohen changed the title refactor(validate): split into early/late phases, retire INTERPOLATED_MARKER (closes #1115) refactor: validate phases + PluginOp protocol + pipeline (closes #1115, #1117) May 15, 2026
@robcohen
robcohen merged commit 73e7eb9 into main May 15, 2026
47 checks passed
@robcohen
robcohen deleted the refactor/validate-phase-split branch May 15, 2026 16:25
@robcohen robcohen mentioned this pull request May 15, 2026
9 tasks done
robcohen added a commit that referenced this pull request May 15, 2026
Bumps the workspace from 0.14.1 to 0.15.0. Minor-version bump per
SemVer because 0.14.2..0.15.0 ships PR #1116, which is a breaking
API change for downstream consumers:

* `rustledger_validate` — removed the `validate()`,
  `validate_with_options()`, `validate_with_today()`, and the two
  spanned variants. Replaced with `ValidationSession::new(opts).
  run_phase(_, Phase::Early, today).run_phase(_, Phase::Late, today).
  finalize()`.

* `rustledger_plugin_types` — `PluginOutput.directives:
  Vec<DirectiveWrapper>` replaced with `ops: Vec<PluginOp>` where
  `PluginOp { Keep(usize) | Modify(usize, DirectiveWrapper) |
  Insert(DirectiveWrapper) | Delete(usize) }`. The wrapper
  round-trip's span-fidelity loss is now eliminated by construction.

* `rustledger_plugin::NativePlugin` — new `is_synth()` trait method
  for self-classifying plugins as pre-booking synthesizers.

* `rustledger_loader` — new `PluginPass { PreBookingSynth |
  PostBooking | All }` enum; `run_plugins` takes a `pass` parameter.
  `run_booking` returns `(Vec<Spanned<Directive>>,
  Vec<Spanned<Directive>>)` partitioned into (booked, failed) instead
  of `Vec<usize>` of failed indices.

* `rustledger_booking` — `INTERPOLATED_MARKER` const removed.

Plus the v0.14.1..v0.15.0 fix train: pad multi-currency / future-date
regressions, duplicate-Open suppression across five plugins,
plugin-error source-location propagation, `--clobber` post-fetch
dedup hardening (#1120 / #1119) and the `cfg(debug_assertions)` gate
on the should-panic phase-ordering tests so Nix package builds via
`cargo test --release` pass.

# Surface coverage (per RELEASING.md)

* Workspace `Cargo.toml`: `[workspace.package].version` + 10
  `[workspace.dependencies]` path-pinned crates.
* 14 crate `Cargo.toml` files.
* `Cargo.lock` regenerated via `cargo check --workspace`.
* `packages/mcp-server/package.json`: `version` and the
  `@rustledger/wasm` dep pin.
* `packaging/rpm/rustledger.spec`: `Version`, `Source0` URL, and
  `%setup -n rustledger-X.Y.Z` directory. `BuildRequires: rust >=
  1.94` already matches the workspace MSRV — no change.

# Pre-flight smoke checks

* `cargo check --workspace --all-features --all-targets` — clean.
* `cd packages/mcp-server && npm ci && npm run build` — clean
  (temporarily reverted `@rustledger/wasm` to `^0.14.1` during the
  build since `^0.15.0` isn't on npm yet; restored to `^0.15.0`
  before committing).
* `cd crates/rustledger-wasm && wasm-pack build --target web
  --release` — clean.

Co-authored-by: Claude Opus 4.7 (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

2 participants