Repository navigation
fix: overlay in-memory buffer on stale ledger snapshot for LSP diagnostics - #758
Conversation
…stics The LSP's `LedgerState` is loaded from disk at startup and refreshed only by file-watcher events, which fire on save. In-memory buffer edits never touch it. Before this fix, `all_diagnostics` passed the stale `LedgerState` directives to `validation_errors_to_diagnostics`, which preferred them over the fresh parse whenever a `current_file_id` was known. Two bad behaviors followed: 1. A new error the user introduced in the buffer was not reported until after the next save. 2. After the user saved (pushing the bad content into `LedgerState`) and then fixed the error in the buffer, the error was still reported against the now-stale `LedgerState` until the next save. That matched the asciicast in #685 exactly. Fix: live overlay in `all_diagnostics`. When both `ledger_state` and `current_file_id` are present, build a merged directive list that removes the stale entries for the current file and appends the fresh parse from the buffer (remapped to `current_file_id` so the per-file filter in `validation_errors_to_diagnostics` still works). Validation then sees the in-memory buffer state for the current file plus the on-disk state for every other file in the ledger. The overlay construction is extracted into a separate `build_live_directive_overlay` helper so it can be unit-tested without building a full `LedgerState` over a tempdir. Two regression tests pin both of the bad behaviors: - `test_live_overlay_reflects_buffer_edits_issue_685`: exercises both scenarios end-to-end through `validation_errors_to_diagnostics`, asserting (a) that without the overlay the bugs reproduce and (b) that with the overlay applied the expected E3001 diagnostics appear and disappear in sync with the buffer. - `test_live_overlay_returns_none_without_file_id`: pins the fallback semantics so a regression that makes the overlay eagerly clone an empty list (or silently fail) is caught at compile+test time. Closes #685 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
📊 Benchmark Results
vs main branch (2026-04-11)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
Fixes LSP diagnostics lag when the server is started against a real journal by overlaying the current in-memory parse directives onto the (potentially stale) on-disk LedgerState snapshot before validation, ensuring diagnostics reflect buffer edits without requiring a save.
Changes:
- Added
build_live_directive_overlayto replace stale directives for the actively edited file with fresh in-memory directives (preserving the existing per-file filtering behavior). - Updated
all_diagnosticsto apply the overlay when bothledger_statedirectives andcurrent_file_idare available. - Added regression tests covering both “new error appears only after save” and “fixed error persists until save” scenarios, plus a fallback-semantics test.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…iant Two improvements on top of the #685 fix: 1. `build_live_directive_overlay` gains a debug_assert that the fresh directives the caller passes in were not pre-tagged with an unexpected file_id. The parser produces directives with file_id=0 by default; anything else would get silently overwritten by the remap loop, which would likely indicate a bug upstream. The assert makes that bug visible in debug builds. 2. New end-to-end regression test `test_all_diagnostics_applies_live_overlay_issue_685` that stands up a real `LedgerState` over a tempdir-backed journal file and runs the full `all_diagnostics` code path. The existing regression tests exercise `build_live_directive_overlay` and `validation_errors_to_diagnostics` directly, which pins the helper logic but not the wiring inside `all_diagnostics`. A future refactor that moves or renames the overlay call (or adds a new caller that forgets it) could break the fix without tripping the direct tests. The end-to-end test catches that class of regression. Adds `tempfile` as a dev-dep for `rustledger-lsp` (already a workspace dep). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Pushed two improvements in
Also filed #760 as a follow-up for the multi-buffer case: this PR's fix only overlays the file currently being validated, so edits in other open buffers are still ignored. That's a legitimately different bug with its own edge cases (e.g. what to do with buffers that have parse errors), and bundling it here would have made this PR harder to review. Sketched the fix in the new issue for whoever picks it up. All gates still green: full workspace tests, clippy |
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
#758 fixed the single-file case of the stale-ledger-state bug: when 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]>
Copilot flagged that `build_live_directive_overlay` clones most of `full_directives` into a new `Vec`, and then `validation_errors_to_diagnostics` immediately cloned that slice again via `to_vec()` before booking and sorting. In the multi-file overlay path (the one that actually fires on every keystroke in a loaded ledger), that meant two full-ledger directive clones per keystroke. Change `validation_errors_to_diagnostics` to take its directive list by value (`Vec<Spanned<Directive>>` instead of two separate `&[Spanned<Directive>]` parameters with fallback logic). The overlay path now moves its owned Vec directly into the function, so the second clone goes away. Non-overlay paths still pay one clone, same as before. Also simplifies the function: - Removes the `directives` fallback parameter (callers construct the owned Vec themselves, so the if-chain for single-file fallback moves up to the caller, where it's clearer anyway). - Removes the internal `directives_to_validate` conditional. Updated call sites: - `all_diagnostics` now constructs `booked_directives` explicitly: prefer the owned overlay, fall back to `full_directives.to_vec()` when there is no overlay but a ledger state is present, fall back to `result.directives.clone()` in the single-file case. This is the same three-way choice as before, just visible at the call site. - 8 test call sites updated to pass owned `Vec` (5 clones, 3 moves). All existing tests pass unchanged. No behavior change, just one fewer allocation per keystroke on loaded-ledger editing. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
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]>
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]>
The `validation_errors_to_diagnostics` docs used rustdoc intra-doc link syntax (`[\`build_live_directive_overlay\`]`) to reference the crate-internal helper. Rustdoc rejects that under `-D warnings` because `build_live_directive_overlay` is not `pub`, which broke CI on #758: error: public documentation for `validation_errors_to_diagnostics` links to private item `build_live_directive_overlay` Drop the link syntax and refer to the helper as plain prose (`crate-internal build_live_directive_overlay helper`). The helper stays `fn` (not `pub(crate)`) because the only external reference is this doc comment, and the prose form makes the visibility constraint obvious to readers. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
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]>
Closes #685.
Summary
When the LSP is started against a journal file,
LedgerStateis loaded from disk at startup and refreshed only by file-watcher events (which fire on save). In-memory buffer edits never touch it, soall_diagnosticswas validating the current file against the stale on-disk directives instead of the fresh parse of the buffer. That produced exactly the two symptoms in the asciicast:My earlier diagnosis was wrong
I previously closed the issue after testing via raw JSON-RPC
didOpen/didChangeagainst an LSP instance with no journal file loaded. That path takes theledger_state.ledger().is_none()branch inpublish_diagnostics, which correctly uses fresh directives from the current parse. The buggy path is the one your nvim setup actually hits when the LSP is started against a real journal. Apologies to @lutzky for the runaround.Fix
Live overlay at the
all_diagnosticslayer. When bothledger_stateandcurrent_file_idare present, build a merged directive list that:full_directivesfromledger_state,file_id == current_file_id,current_file_idso the existing per-file filter invalidation_errors_to_diagnosticsstill works.Validation then sees the in-memory buffer state for the current file plus the on-disk state for every other file in the ledger. Other files in a multi-file ledger behave exactly as before.
The overlay construction is extracted into a
build_live_directive_overlayhelper so it can be unit-tested without having to stand up a fullLedgerStateover a tempdir.Regression tests
Two new tests in
crates/rustledger-lsp/src/handlers/diagnostics.rs:test_live_overlay_reflects_buffer_edits_issue_685exercises both scenarios end-to-end throughvalidation_errors_to_diagnostics:full_directivesstill holds the clean on-disk version. Without the overlay the E3001 is missing (bug reproduction). With the overlay applied, E3001 appears.full_directivesholds the broken post-save version. Without the overlay, E3001 persists (bug reproduction). With the overlay applied, diagnostics are clean.test_live_overlay_returns_none_without_file_idpins the fallback semantics (nocurrent_file_idmeans no overlay, caller falls back to the originalfull_directives) so a future refactor that eagerly clones an empty list or silently fails is caught.Test plan
cargo test -p rustledger-lsp --lib handlers::diagnostics— 7/7 pass (5 existing + 2 new)cargo test --workspace --all-features— all suites green, 0 failurescargo clippy --all-features --all-targets -- -D warnings— cleancargo fmt --all -- --check— cleanFiles touched
crates/rustledger-lsp/src/handlers/diagnostics.rs— overlay helper, call site, two regression testsNet: 1 file, 262 insertions, 2 deletions.
Notes for reviewers
publishDiagnosticscall. For a 10K-directive multi-file ledger this is aVec::cloneon each keystroke while editing. If that turns out to be a bottleneck in practice, the obvious optimization is to wrapLedgerState::directives()in anArc<[Spanned<Directive>]>so the overlay can share memory with the ledger snapshot and only pay for the slice filter + append. I held off on that because (a) the currentLedgerStateAPI returns&[Spanned<Directive>]and changing it would ripple, and (b) I haven't measured that this is actually a hot path yet. Happy to follow up as a separate PR if benchmarks show it matters.Option<Vec<…>>rather than always cloning, so in the single-file case (current_file_idisNone) we pay zero allocations and fall back to the existingfull_directivespath unchanged.