Skip to content

fix(lsp): validate multi-file ledgers once, not once per file (#1799) - #1813

Merged
robcohen merged 3 commits into
mainfrom
fix/lsp-cross-file-diag-single-pass
Jul 19, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/lsp-cross-file-diag-single-pass

Conversation

@robcohen

Copy link
Copy Markdown
Member

The regression

Bisected by the reporter to c3e8454 (#1487, cross-file diagnostics for unopened included files). That commit's compute_unopened_ledger_diagnostics calls all_diagnostics once per ledger file, and each call re-runs the entire ledger's booking + both plugin passes + Early/Late validation (validation_errors_to_diagnostics) just to keep one file's errors, filtering the rest away. So per-keystroke cost went from one whole-ledger book+validate to O(files) of them.

didChange is handled synchronously on the single LSP main-loop thread (on_did_change → publish_diagnostics, no dispatch_async), while completion requests are dispatched to a worker pool — but only after the notification returns. So each keystroke's O(files) validation blocks the loop from even dequeuing the completion request behind it, and it times out. This matches every symptom: large multi-file ledgers only, worse without --release, "more currencies made it reproduce" (more directives ⇒ slower each pass).

The fix

The validation errors already carry file_id (that's what the per-file filter uses), so one whole-ledger validation yields every file's errors. This splits validation into:

  • run_ledger_validation — the file-independent, expensive half (sort + book + plugin passes + Early/Late), run once.
  • map_validation_to_diagnostics — cheap per-file mapping: filter the shared errors to a file, map spans against that file's source, add its plugin notes.

ledger_diagnostics_multi produces the current file's and every unopened file's diagnostics from that single validation. publish_diagnostics routes multi-file ledgers through it; the single-file path is unchanged. Unopened files are also no longer re-parsed by a redundant per-file all_diagnostics.

Net: per-keystroke cost on a multi-file ledger drops from O(files) whole-ledger validations back to one — the pre-#1487 level — so the main loop frees up and completions return.

Correctness

  • The two fix(lsp): publish diagnostics for unopened included files #1487 behavior tests (included_file_validation_errors_are_published, included_file_diagnostics_are_cleared_when_fixed) still pass — the cross-file feature is preserved, just computed once.
  • validation_errors_to_diagnostics keeps its signature (now = run + map), so single-file callers and all_diagnostics are untouched.
  • The semantic helpers that must not drift (booking_sort_key, ValidationSession, build_live_directive_overlay, build_validation_options_from_loader, validation_error_to_diagnostic) are reused, not copied.

Regression guard

ledger_diagnostics_multi_validates_once_for_all_files builds a 3-file ledger and asserts exactly one whole-ledger validation runs regardless of file count (via a thread-local counter, so parallel tests don't interfere). A future change that reintroduces per-file validation trips it.

cargo test -p rustledger-lsp green (286 tests); clippy/doc/fmt clean.

Closes #1799.

🤖 Generated with Claude Code

https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

The cross-file diagnostics added in #1487 (c3e8454) called all_diagnostics
once per ledger file, and each call re-ran the WHOLE ledger's booking +
plugin passes + Early/Late validation just to keep one file's errors —
O(files) full validations on every keystroke. Because didChange is
handled synchronously on the single LSP main-loop thread, that work
blocked completion requests (dispatched only after the notification
returns), so completions timed out on large multi-file ledgers
(the reporter's 4-file / ~50k-line ledger). Worse without --release,
worse with more currencies — both just mean more directives per pass.

Split the file-independent, expensive half of validation into
run_ledger_validation (sort + book + plugins + Early/Late), computed
ONCE, and map each file's diagnostics from the shared result by
filtering errors on file_id. ledger_diagnostics_multi produces the
current file's AND every unopened file's diagnostics from that single
validation; publish_diagnostics routes multi-file ledgers through it and
leaves the single-file path unchanged. Unopened files are also no longer
re-parsed via a redundant per-file all_diagnostics.

Regression test ledger_diagnostics_multi_validates_once_for_all_files
asserts exactly one whole-ledger validation regardless of file count
(thread-local counter so parallel tests don't interfere). The #1487
behavior tests (included_file_validation_errors_are_published,
included_file_diagnostics_are_cleared_when_fixed) still pass.

Closes #1799.
@robcohen
robcohen requested a review from a team as a code owner July 19, 2026 14:29
Copilot AI review requested due to automatic review settings July 19, 2026 14:29
@codecov

codecov Bot commented Jul 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.07459% with 34 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-lsp/src/handlers/diagnostics.rs 90.65% 30 Missing ⚠️
crates/rustledger-lsp/src/main_loop.rs 96.29% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.9ms ± 0.5ms 23.8 MB
beancount 758ms ± 3.8ms 50.7 MB
Comparison 21.7x faster 2.1x less

vs main branch (2026-07-19)

Metric main this PR Change
Time 35ms 34.9ms -0.3% ✅
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

Fixes an LSP performance regression for multi-file ledgers by ensuring whole-ledger booking + plugin execution + Early/Late validation is performed once per diagnostics publish, then cheaply mapped to per-file diagnostics (including unopened included files).

Changes:

  • Route multi-file ledgers through a new single-validation multi-file diagnostics path in the LSP main loop.
  • Split diagnostics generation into “run whole-ledger validation once” and “map shared validation to per-file diagnostics”.
  • Add a regression test asserting multi-file diagnostics performs exactly one whole-ledger validation regardless of file count.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
crates/rustledger-lsp/src/main_loop.rs Switch multi-file ledgers to a single-validation diagnostics path that emits current + unopened-file diagnostics together.
crates/rustledger-lsp/src/handlers/diagnostics.rs Introduce shared validation (run_ledger_validation) + per-file mapping, add ledger_diagnostics_multi, and add a regression guard test.

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

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 811
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 added 2 commits July 19, 2026 14:56
Copilot review: ledger_diagnostics_multi ran the whole-ledger
book+plugin+validate even when every target failed validation_would_run
(all parse errors, or all over the size cap), discarding the result and
still blocking the main loop. Gate the validation (and the expensive
directive-overlay build) behind `any target validates`; skip to an empty
LedgerValidation otherwise. Regression test extended to assert ZERO
validations when all targets have parse errors.
Two real regressions the review caught in the first cut:

1. Editing a buffer NOT part of the multi-file ledger (a scratch file,
   current_file_id == None) fell to the else branch, which published an
   EMPTY cross-file set and thereby CLEARED genuine diagnostics in
   unopened included files. Now `is_multi_file` alone routes through the
   cross-file path: the current (non-ledger) buffer self-validates via
   the single-file path while the unopened ledger files' diagnostics are
   still recomputed and republished, not cleared. multi_file_diagnostics
   handles current_file_id == None (unopened targets only).

2. ledger_diagnostics_multi injected the current file's fresh plugins
   into the shared whole-ledger validation UNCONDITIONALLY — even when
   the current parse was broken, whose recovered .plugins list is partial
   or empty. That dropped e.g. auto_accounts from the validation the clean
   unopened files run against, producing phantom E1001s. Now the fresh
   plugins are used only when the current file is a ledger file AND parsed
   cleanly (mirroring the directive-overlay's clean guard); otherwise the
   ledger's stored plugins are kept, matching the old per-file behavior.

Also: restored the size-cap "Skipping validation for large file" debug
log for parity with all_diagnostics, and corrected the merged_plugins
comment.

Regression tests: editing_a_non_ledger_buffer_keeps_unopened_file_diagnostics
(integration) and broken_current_parse_keeps_stored_plugins_for_cross_file_validation
(unit, asserts no phantom E1001).
@robcohen
robcohen merged commit 3416d6a into main Jul 19, 2026
42 checks passed
@robcohen
robcohen deleted the fix/lsp-cross-file-diag-single-pass branch July 19, 2026 15:49
robcohen added a commit that referenced this pull request Nov 11, 2026
- LSP: restore the #1813 guard in `ledger_diagnostics_multi`, so a buffer
  broken mid-edit no longer replaces the stored plugins the unopened files
  are validated with, and re-add
  `broken_current_parse_keeps_stored_plugins_for_cross_file_validation`.
- LSP: keep overlaying a broken current buffer (its own diagnostics come
  from its text, as in `rledger check`), but hold the unopened files'
  diagnostics while it has a parse error, so a half-typed string that
  swallows an `open` cannot make them flap. Keep overlaying other broken
  open buffers. Pin both through `MainLoopState`.
- WASM: `validateMultiFile` / `validateWithHost` take only the parse errors
  and leave the other load errors to `process`, as `Ledger.fromFiles` does,
  so they keep the code `LOAD`; drift guard
  `validate_and_ledger_report_load_errors_alike`.
- WASM cache comment: v100 is not held by an open PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 12, 2026
…does (#2952)

* fix(wasm): restore cached ledgers holding custom directives or metadata

ParsedLedger.fromCache and Ledger.fromCache threw "Deserialization
failed: unaligned pointer ... alignment 8" on any ledger with a custom
directive or a metadata entry.

Root cause: rkyv::from_bytes reads the archive in place, so every
archived value must sit at its own alignment in memory. ArchivedMetaValue
needs 8 bytes (its Int(i64) variant, added in #1513), and every custom
value and metadata entry archives one. The WASM cache blob puts its
archive 12 bytes in, after the magic and version header, so even in a
16-aligned blob those values sat 4 bytes off. The blob itself is not
aligned either: wasm-bindgen copies a JS Uint8Array into wasm memory with
alignment 1.

Fix: decoding copies the payload into an rkyv AlignedVec before reading
it, which does not depend on where the caller's bytes lie. The cache
format is unchanged, so CACHE_VERSION stays at 94 and blobs already
written restore as they are.

The loader's on-disk cache reads its header separately, so it does not
have the offset bug, but it read the archive into a plain Vec<u8>, whose
alignment is 1 by contract and 16 only because the system allocator
happens to give it. It now reads straight into an AlignedVec. Its format
is unchanged too.

Tests: a round trip over one ledger per directive type, per metadata
value type and per custom value type, plus error cases, comparing
directives, errors and options on both ParsedLedger and Ledger, natively
and under wasm-pack test --node; a native round trip over every
.beancount file in the repository's test corpora; a decode of each
payload at every offset from a 16-byte boundary; and a loader save/load
of custom values and metadata. All but the loader test fail without the
fix.

Closes #2934

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix: make check, WASM, FFI and LSP agree on close-with-balance and after a booking error

Two cases where the diagnostic surfaces disagreed (#2937), settled by
bean-check 3.2.3:

- Closing an account that still holds a balance (E1004). bean-check does
  not flag it, with or without auto_accounts / currency_accounts, and
  `rledger check` stays silent to match (`lint closed-nonempty` reports
  it). WASM, the FFI component and the LSP reported it. They now leave
  it out through the one predicate, `ErrorCode::is_advisory_only`.
- Validation after a booking error. bean-check and `check` report an
  ambiguous STRICT reduction and the `Balance failed` that follows it,
  the refused transaction left out of the balance. WASM `validateSource`
  and `ParsedLedger` skipped validation on any load error, and the FFI
  counted the refused transaction into the balance (-1600 USD where
  bean-check says -2100 USD). The loader now records which transactions
  booking refused (`Ledger::booking_refused`), and both surfaces set them
  aside as the validating loader does: Early sees them, Late does not,
  and the session reports the account errors Early held for them.

A shared case file (`rustledger-loader/tests/surface_agreement/cases.rs`)
drives one drift-guard test per surface: the loader, `rledger check`,
WASM (`validateSource`, `validateMultiFile`, `ParsedLedger`, `Ledger`,
fresh and from cache), the FFI component (`validate`, `load`) and the
LSP, each comparing codes (the FFI wire error has none: line and
message), lines and messages.

The WASM cache moves to v97: both payloads' archived errors change.
WASM `fromCache` now reads the archive from an aligned copy: it starts 12
bytes into the blob, and the new cache round trip hit an "unaligned
pointer" refusal on it. The format is unchanged.

Closes #2937

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(wasm): drop the duplicate cache alignment fix in favor of #2942

The AlignedVec copy in deserialize_parsed / deserialize_ledger duplicates
the fix in #2942 (#2934), which also covers the loader cache and has its
own tests. #2942's branch is merged in next, so this PR's WASM cache round
trip still decodes; #2947 depends on #2942 landing first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(wasm): address #2947 review round 1

- Rewrite the comments that still said run_validation gates on load.errors
  or skips on has_fatal (helpers.rs, api.rs, parsed_ledger.rs).
- run_validation: drop the span-length-mismatch branch, which set refused
  transactions aside without noting them; load_and_book always keeps one
  span per directive, now a debug_assert.
- CHANGELOG: Ledger::booking_refused listed under Breaking, as
  PluginError::failed was.
- Cache notes: v93 and v96 were never released; #2931 holds v95.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix: validate after a parse error on every surface, as rledger check does

`rledger check` and bean-check 3.2.3 report a syntax error and still
validate the entries that did parse. WASM (`validateSource`,
`ParsedLedger`, `validateMultiFile`, `validateWithHost`), the FFI
component (`validate`, `load`) and the LSP validated nothing once a file
failed to parse, so one bad line hid every other finding.

Each surface now follows the validating loader's rule, under which no
load error stops validation:

- WASM `load_and_book` no longer returns early on a parse error; the
  loader keeps what parsed and `process` books it, and `run_validation`
  validates it. `validateMultiFile` / `validateWithHost` report every
  load error, then run `process` with them cleared, as `check` does.
- `LoadResult::take_parse_errors` (new) takes the parse errors out of a
  load so a surface reports them one by one with code and line, rather
  than `process` folding them into one line-less `parse errors in
  <path>`. WASM's single-source load, `Ledger.fromFiles` and the FFI
  string load use it.
- The FFI's `semantic_validation_errors` drops its parse-phase gate.
- The LSP's `validation_would_run` keeps only the size cap, and an open
  buffer with a parse error is overlaid in a multi-file ledger.

The shared surface_agreement cases gain one parse error plus an
unbalanced transaction and a failing balance (P0012 line 8, E3001 line
4, E2001 line 10, bean-check's three findings on the same lines),
asserted on the CLI, the loader, WASM, the FFI and the LSP.

WASM cache v101.

Closes #2949

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix: address #2952 review round 1

- LSP: restore the #1813 guard in `ledger_diagnostics_multi`, so a buffer
  broken mid-edit no longer replaces the stored plugins the unopened files
  are validated with, and re-add
  `broken_current_parse_keeps_stored_plugins_for_cross_file_validation`.
- LSP: keep overlaying a broken current buffer (its own diagnostics come
  from its text, as in `rledger check`), but hold the unopened files'
  diagnostics while it has a parse error, so a half-typed string that
  swallows an `open` cannot make them flap. Keep overlaying other broken
  open buffers. Pin both through `MainLoopState`.
- WASM: `validateMultiFile` / `validateWithHost` take only the parse errors
  and leave the other load errors to `process`, as `Ledger.fromFiles` does,
  so they keep the code `LOAD`; drift guard
  `validate_and_ledger_report_load_errors_alike`.
- WASM cache comment: v100 is not held by an open PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(lsp): validate other files against a clean view, not a held one

Review round 2 of #2952. Round 1 held the unopened files' diagnostics
while the edited buffer had a parse error. That hold never published
the includes of a main file saved with a syntax error, let a clean
buffer's edit recompute them against another broken buffer, and the
restored plugin guard made a broken buffer's own diagnostics differ
from rledger check on its text.

Replace it with a stateless rule. Every file other than the one being
published is validated against the clean view: the ledger as loaded
with each open buffer that parses cleanly overlaid, a broken one left
as on disk. The published buffer's own diagnostics come from the clean
view plus its own text and plugins, as check reports them. For a clean
buffer the two views coincide, so the all-clean path still runs one
validation. didClose republishes the unopened files from disk.

Removed: the hold flag, multi_file_diagnostics' with_unopened, and the
parse-error plugin guard in ledger_diagnostics_multi. The changelog now
names the surfaces that report parse errors one by one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(lsp): keep a broken buffer's last clean text and every buffer's plugins in the clean view

Review round 3 of #2952.

- The clean view used the stored load for a broken buffer, so breaking a
  buffer with unsaved clean edits undid them for every other file. Each
  open buffer now keeps its last clean parse (dropped on close) and
  contributes it while its current text is broken.
- The clean view applied only the published buffer's plugin lines, so
  one revalidation could publish a file twice with different content.
  ledger_diagnostics_multi now takes the view as parses: every file in
  it contributes its directives and its plugin lines, replaced in place.
- didClose republishes every other open ledger buffer, not only the
  unopened files.
- Docs: the own view's file set is the stored load's (an include edit
  takes effect on the next load); the WIT balance diff and the ffi-wasi
  error-phase docs no longer describe the removed parse gate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(lsp): run a view's plugins in the loader's order, and record a clean parse only in diagnostics passes

Review round 4 of #2952.

- view_plugins appended the plugins of a view file that had none stored
  at the end, in the order the view listed its files (the published
  buffer first, then VFS HashMap order), so two chained rename_accounts
  ran in a different order than rledger check runs them and the clean
  view depended on which buffer was published. It now stable-sorts by
  file_id, the loader's order (pinned by a new loader test).
- last_clean_parse was recorded by every parse_result() call, request
  handlers included; it is now recorded only by clean_view_parse, which
  only diagnostics passes call.
- The wasm cache comment no longer calls v100 unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(lsp): validate a buffer saved broken as loaded, and pin the loader's plugin order on disk

Review round 5 of #2952 (issue #2949).

- After every successful load of the ledger (watched-file reload, root
  adoption), an open buffer whose current text equals the text that load
  read for its file drops its last clean parse: it was saved, so until it
  next parses cleanly its file is validated as `rledger check` validates
  the saved text. A buffer edited past what was saved keeps it. Before,
  a buffer saved broken kept validating its includes against its old
  clean text, hiding the E1001 `check` reports on disk.
- Docs: the set AND ORDER of the files come from the last load (plugin
  order and same-day tie-breaks follow it), on `publish_diagnostics`,
  `view_plugins` and in the CHANGELOG.
- Loader test: the plugin `file_id` order on disk, through the parallel
  pre-parse branch (a glob include matching several files).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(lsp): forget a saved-broken buffer's clean parse when its file has a BOM

The loader keeps a file's leading BOM, while editors send the buffer
without it, so the round-5 "saved broken" check never matched a
BOM-prefixed file and kept validating other files against its last
clean text. Compare both texts with the parser's canonical
`bom::strip_leading`, and pin the BOM and CRLF cases with tests.

Review round 6 of #2952.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[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.

[Bug]: LSP - Performance regression causes completions to fail in nvim

2 participants