Skip to content

fix: overlay all open buffers when publishing LSP diagnostics - #764

Merged
robcohen merged 1 commit into
fix/issue-685-lsp-buffer-overlayfrom
fix/issue-760-multi-buffer-overlay
Apr 11, 2026
Merged

robcohen merged 1 commit into
fix/issue-685-lsp-buffer-overlayfrom
fix/issue-760-multi-buffer-overlay

Conversation

@robcohen

Copy link
Copy Markdown
Member

Closes #760. Stacked on top of #758 (merge that first). When #758 merges, I'll retarget this PR's base to main.

Summary

#758 fixed the single-file case of the stale-ledger-state bug. This PR fixes the multi-file case: when the user has several open buffers in a multi-file ledger and a balance assertion in one file depends on a transaction in another, edits in the second buffer should be visible to validation of the first.

The bug

With #758's fix alone:

  • User has bank.beancount and credit_card.beancount both open with unsaved changes.
  • bank.beancount has a balance assertion for Assets:Bank:Checking 4950 USD that depends on the -50 USD transaction in credit_card.beancount.
  • User edits the credit card transaction in the buffer from -50 USD to -75 USD.
  • When bank.beancount is validated, all_diagnostics overlays bank.beancount's fresh parse onto the ledger state — but credit_card.beancount's directives are still the stale on-disk version.
  • The balance assertion is validated against the stale credit card data, appears to hold, and no diagnostic is produced.
  • In reality the user's actual in-buffer state makes the actual 4925 USD, and the assertion should fail.

This is a real editing workflow for anyone maintaining a multi-file journal (one file per account or per category, included from a root main.beancount).

What changed

  1. build_live_directive_overlay generalized. Old signature took one fresh parse and one file_id. New signature takes &[(u16, &[Spanned<Directive>])] — a slice of (file_id, fresh_directives) pairs. Stale directives matching any overlay's file_id are filtered out of full_directives; fresh directives are appended with their file_id remapped. Single-file callers pass a one-element slice.

  2. all_diagnostics gains an other_buffer_overlays parameter. It constructs the full overlay list internally by prepending the current file's fresh parse (from result) and appending the caller's overlays, then calls the helper. Existing single-file callers pass &[].

  3. main_loop::publish_diagnostics walks the VFS. For each open document that is part of the ledger, is not the current file, and has no parse errors, it adds a (file_id, directives) entry to other_buffer_overlays and passes the list to all_diagnostics. Uses the VFS's existing iter_with_parse() which leverages the per-document parse cache — so this is O(1) per open buffer on the hot path and only pays parse cost on the first access after an edit.

Design decisions

  • Buffers with parse errors are skipped (stale directives are retained). Overlaying a partial/broken parse could spuriously invalidate balance assertions in other files, which is strictly worse than keeping a stale-but-valid snapshot. Documented in the code comment.

  • Current file is always first in the overlay list. If a caller passed the current file in other_buffer_overlays too (shouldn't happen, but harmless), the helper's first-match semantics mean the current file's fresh parse wins.

  • Helper is generalized rather than adding a parallel API. The earlier fix: overlay in-memory buffer on stale ledger snapshot for LSP diagnostics #758 discussion flagged this as a mild anti-pattern ("don't design for hypothetical future requirements") but the future requirement is now; this PR makes the generalization concrete rather than speculative.

  • Canonicalization happens twice per other buffer per keystroke (once when filtering out the current file, once when looking up the file_id). Could be cached in LedgerState, but that's an optimization for a separate PR if measurements show it matters.

Tests

  • test_live_overlay_returns_none_when_nothing_to_overlay — updated for the new signature. Covers both fallback conditions (no ledger state, empty overlays).
  • test_multi_buffer_overlay_replaces_multiple_files_issue_760 (new) — directly exercises the helper with two overlays at once, asserts the merged list contains fresh content for both files, then runs validation_errors_to_diagnostics on a scenario where a balance assertion in file A depends on a transaction in file B and verifies the assertion fails only when B's buffer is also overlaid.
  • test_all_diagnostics_multi_buffer_overlay_issue_760 (new) — end-to-end test using a real LedgerState backed by a tempdir with main.beancount + an included credit_card.beancount. Asserts the baseline (no overlays → balance assertion holds) and the fix path (credit_card buffer edited to -75 USD → main's 4950 USD balance assertion fails with actual 4925 USD).
  • All existing call sites updated to pass &[] for other_buffer_overlays. Existing [Bug]: nvim - LSP Restarts required to show and clear balance #685 tests (test_live_overlay_reflects_buffer_edits_issue_685, test_all_diagnostics_applies_live_overlay_issue_685) continue to pass.

Test plan

  • cargo test -p rustledger-lsp --lib handlers::diagnostics — 10/10 pass (7 pre-existing from fix: overlay in-memory buffer on stale ledger snapshot for LSP diagnostics #758 + 3 new)
  • cargo test --workspace --all-features — all suites green, 0 failures
  • cargo clippy --all-features --all-targets -- -D warnings — clean
  • cargo fmt --all -- --check — clean
  • Manual verification in nvim with two open buffers where one file's balance assertion depends on another's transaction

Files touched

  • crates/rustledger-lsp/src/handlers/diagnostics.rs — helper generalization, all_diagnostics signature change, call site update, 2 new tests, 1 updated test
  • crates/rustledger-lsp/src/main_loop.rs — VFS walk + overlay collection in publish_diagnostics, imports

Risks

  • Canonicalization cost. Every open buffer gets 2 canonicalize() syscalls per keystroke (once to match against the current URI, once to look up the file_id). For typical 1-5 open buffers this is microseconds. For pathological cases (20+ open buffers) it could add up. Benchmark first if this matters.
  • Helper signature is a breaking change for any out-of-tree caller (none in the workspace).
  • The VFS parse cache is per-document and invalidates on update() — so after an edit, the first call to iter_with_parse() re-parses that document. On subsequent publish_diagnostics calls for other files, it's a cache hit. No regression in the common case.

Related

@robcohen
robcohen requested a review from a team as a code owner April 11, 2026 16:13
the user edited file A and A was part of a multi-file ledger,
validation would use the fresh in-memory parse of A instead of A's
on-disk copy. But the fix was scoped to just the file currently
being validated. Edits in other open buffers were still ignored by
`all_diagnostics`.

Scenario this fixes: a multi-file ledger with bank.beancount and
credit_card.beancount both open in the LSP. bank.beancount has a
balance assertion that depends on a transaction in
credit_card.beancount. The user edits the transaction amount in
credit_card.beancount's buffer without saving. With the #758 fix
alone, bank.beancount's validation sees the stale on-disk version of
credit_card.beancount and reports no imbalance, even though the
user's actual state does have one. After this fix, the validator
sees both buffers' fresh state and the balance assertion correctly
reflects the in-memory reality.

Implementation:

- `build_live_directive_overlay` generalized to take a slice of
  `(file_id, fresh_directives)` pairs instead of a single fresh
  parse. Stale directives matching any overlay's `file_id` are
  filtered out; fresh directives are appended with their `file_id`
  remapped. Single-file callers pass a one-element slice.

- `all_diagnostics` gains an `other_buffer_overlays` parameter. It
  constructs the full overlay list by prepending the current file's
  fresh parse (from `result`) and appending the caller's overlays,
  then calls the helper. Existing single-file callers pass `&[]`.

- `main_loop::publish_diagnostics` walks the VFS via the existing
  `iter_with_parse()` method (which uses the per-document parse
  cache, so it's O(1) per open buffer on the hot path and only pays
  parse cost on the first access after an edit). For each open
  document that's part of the ledger and is not the current file
  and has no parse errors, it adds a `(file_id, directives)` entry
  to `other_buffer_overlays`. Buffers with parse errors are
  deliberately skipped: keeping the stale-but-valid ledger
  directives is strictly better than overlaying a partial/broken
  parse (which could spuriously invalidate balance assertions in
  other files).

Tests:

- `test_live_overlay_returns_none_when_nothing_to_overlay` updated
  to match the new helper signature.
- `test_multi_buffer_overlay_replaces_multiple_files_issue_760`
  exercises `build_live_directive_overlay` with two overlays at
  once, verifying the merged directive list contains fresh content
  for both files and stale content for neither.
- `test_all_diagnostics_multi_buffer_overlay_issue_760` uses a real
  `LedgerState` backed by a tempdir with main.beancount + an
  included credit_card.beancount. Asserts the baseline (no
  overlays → no error) and the fix path (credit_card buffer edited
  to -75 → bank balance assertion for 4950 fails with actual 4925).
- All existing call sites updated to pass `&[]` for
  `other_buffer_overlays`. Existing #685 tests continue to pass.

Closes #760

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@robcohen
robcohen force-pushed the fix/issue-760-multi-buffer-overlay branch from da53dad to eeed619 Compare April 11, 2026 16:44
@robcohen
robcohen merged commit 0d17f1a into fix/issue-685-lsp-buffer-overlay Apr 11, 2026
5 checks passed
@robcohen
robcohen deleted the fix/issue-760-multi-buffer-overlay branch April 11, 2026 16:46
@rustledger-bot rustledger-bot Bot mentioned this pull request Apr 11, 2026
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]>
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.

1 participant