Skip to content

perf(lsp): coalesce diagnostics during bursts of edits - #2941

Merged
robcohen merged 3 commits into
mainfrom
perf/lsp-coalesce-diagnostics
Nov 11, 2026
Merged

robcohen merged 3 commits into
mainfrom
perf/lsp-coalesce-diagnostics

Conversation

@robcohen

@robcohen robcohen commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

What changed

textDocument/didChange no longer runs a diagnostics pass per change. It still applies the edit to the VFS and bumps the revision immediately, so hover, completion, definition and every other request see the latest text exactly as before. The diagnostics pass is only scheduled, and runs once the document has gone DIAGNOSTICS_DEBOUNCE (200 ms) without another change.

  • DiagnosticsSchedule (new, crates/rustledger-lsp/src/diagnostics_schedule.rs): path-keyed set of documents owing a pass, each with a deadline of last change + 200 ms. It never reads the clock; every method takes now.
  • Main loop: a third select! arm waits on crossbeam_channel::at(earliest deadline) (or never() when nothing is pending). When it fires, it first drains the messages already queued (bounded by receiver.len() at that moment, so a client that never stops sending cannot trap the loop), then runs the passes that are still due. A backlog that piled up behind a slow pass therefore pushes the deadline back and collapses into one pass.
  • No stale versions: a pass reads the document's text from the VFS at the moment it runs, so it can only describe the current version; an intermediate version is never validated, let alone published.
  • Injectable clock: MainLoopState holds a clock (Instant::now in production) so tests advance time by hand.

Why

#2858 measured about 46 ms per change on a 108k-line ledger, i.e. 15 to 30% of a core while typing at Neovim's default 150 ms debounce, and every pass but the last in a burst is thrown away. 200 ms sits above Neovim's 150 ms cadence so consecutive client batches still collapse while the user is typing.

Per-trigger decisions

Trigger Behavior Why
didChange VFS + revision now, pass debounced The point of the change
didOpen Publishes immediately (unchanged) A newly opened file should show its diagnostics at once; opens do not come in bursts
Root adoption / watched-file revalidation Publishes immediately (unchanged) Rare, and the user expects the external change to show up
Any immediate publish Cancels a pending pass for that file It used the current text, so the pending pass would be redundant
didClose Cancels the pending pass, then clears (unchanged clear) Otherwise a pass could re-publish for a closed file
didSave n/a The server does not register for save notifications (sync kind only)
codeLens Runs the pending pass for its document first The balance lens reads the diagnostics cache (#1264); serving it with a pass pending would show the verdict of the pre-edit text
codeAction / resolve Unchanged They compute from the current text and do not read cached diagnostics
Non-file URI Immediate publish (unchanged) It never reaches the VFS, so a deferred pass would have nothing to read
didChange with no prior didOpen Immediate publish from the given text (unchanged) A client protocol violation, but main answered it; there is no buffer for a deferred pass to read
shutdown Drops every pending pass; later document and watched-file notifications are ignored The server should not act on anything but exit after shutdown, so nothing is published between the two

How to test

cargo test -p rustledger-lsp --all-features

New tests, all on a hand-advanced clock (no sleeping):

  • diagnostics_schedule::tests::*: burst due once after the last change, interleaved documents each due once, cancel drops the pass.
  • main_loop::tests::coalescing:: (plus the three round-1 tests below)
    • test_burst_of_changes_runs_one_pass_matching_final_text: 50 changes give exactly one pass, and its diagnostics equal a fresh didOpen of the final text; requests see each edit immediately.
    • test_timer_drains_queued_changes_into_one_pass: 20 changes queued behind a due pass are drained first, giving one pass for the last version.
    • test_interleaved_documents_each_get_their_final_pass
    • test_no_publish_for_an_intermediate_version: version 2's deadline passes after version 3 arrived; nothing is published for version 2.
    • test_code_lens_during_pending_pass_sees_current_diagnostics: an edit that breaks a balance assertion, then codeLens with the pass pending, shows the warning.
    • test_did_close_during_pending_pass_cancels_and_clears
    • test_did_open_publishes_immediately

Removing the codeLens flush or the drain makes the corresponding test fail (checked).

Measured

A throwaway driver (not committed) runs the server in-process over Connection::memory, opens a generated 99,999-line single-file ledger, sends 50 full-text didChanges, then counts publishDiagnostics for the URI until 15 s of quiet (one publish per pass). Release build, same machine, run sequentially.

Scenario main: passes main: last publish this PR: passes this PR: last publish
50 changes back-to-back (sent in ~0.2 s) 50 56.3 s 1 2.3 s
50 changes 150 ms apart (Neovim default cadence, ~7.6 s) 50 27.4 s 1 8.1 s

"Last publish" is measured from the first change. A single pass on this ledger costs about 0.7 to 1.5 s here, so on main the server was still working through the backlog for 20 to 50 s after the user stopped typing; with this PR the final diagnostics arrive one debounce plus one pass after the last edit.

Note on behavior: while a client keeps sending changes faster than every 200 ms, diagnostics wait until the edits pause. That is the requested debounce. In practice only continuous typing waits: vscode-languageclient already batches FULL-sync changes through a 250 ms trailing delayer and flushes them before sending a request, and Neovim sends at most one change per 150 ms by default. There is deliberately no max-wait cap (rust-analyzer coalesces without one, and the TypeScript tooling uses a trailing debounce); a comment in DiagnosticsSchedule::schedule marks where one would go if continuous typing should ever refresh periodically.

Review round 1

  • CHANGELOG: Performance entry with the measured pass counts.
  • Docs: docs/development/lsp-support.md no longer claims the validator runs on every didChange / didSave: didChange passes are debounced, didSave is never received (FULL sync, no save option), and codeLens runs a pending pass first.
  • Untested cancel: new test_revalidation_settles_a_pending_pass (edit A, then a watched-file change inside the debounce window, then assert nothing is pending and no redundant pass runs later). Deleting the cancel at the top of publish_diagnostics now fails it.
  • Shutdown: the Shutdown arm clears the schedule; test_shutdown_drops_pending_passes.
  • didChange without didOpen: restored main's immediate publish from the given text; test_did_change_without_open_publishes_from_given_text.
  • Each of the three new guards was mutation-checked: removing it fails exactly its test.

Review round 2

  • After shutdown: handle_notification now ignores everything but exit once shutdown_requested is set (LSP 3.17 §Lifecycle), so a late didOpen, didChange or watched-file change can neither schedule nor publish a pass. Combined with the cleared schedule, nothing is published between shutdown and exit. test_notifications_after_shutdown_are_ignored pins it (and that exit is still handled); disabling the guard fails it.
  • Docs: lsp-support.md now says a didChange for a document with no buffer (non-file URI, or no prior didOpen) still publishes immediately, and that shutdown drops pending passes and ignores document notifications.

Closes #2940

🤖 Generated with Claude Code

didChange ran a full diagnostics pass per change, so a burst of edits
paid for one whole-ledger validation per notification while only the
last result mattered (#2858 measured about 46 ms per change on a
108k-line ledger).

didChange now applies the edit to the VFS and bumps the revision at
once, as before, so every request sees the latest text, but only
schedules the diagnostics pass. A pass falls due once its document has
gone DIAGNOSTICS_DEBOUNCE (200 ms) without another change. The main
loop sleeps on a select! timer arm for the earliest deadline; when it
fires, it first drains the messages already queued, so a backlog that
piled up behind a slow pass pushes the deadline back and collapses
into one pass. A pass reads the document's text from the VFS when it
runs, so it can only describe the current version.

Per trigger:
- didOpen, root adoption and watched-file revalidation still publish
  immediately; any publish settles a pending pass for the same file.
- didClose cancels a pending pass and clears, as before.
- codeLens reads the diagnostics cache, so it runs a pending pass for
  its document first. Code actions compute from the current text and
  need nothing.
- A URI with no file path never reaches the VFS and keeps the old
  immediate publish.

The schedule never reads the clock itself; MainLoopState takes an
injectable clock so the tests advance time by hand instead of sleeping.

Closes #2940

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 11, 2026 06:14
@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 51.0ms ± 1.0ms 782.3ms ± 8.2ms 15.3x 44.9 MB / 51.1 MB
investment 75.5ms ± 0.8ms 2876.9ms ± 17.3ms 38.1x 47.1 MB / 59.1 MB
fifo 73.9ms ± 0.6ms 14520.1ms ± 62.6ms 196.4x 48.3 MB / 59.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 50.8ms ± 0.4ms 51.0ms ± 1.0ms +0.6% ✅ within noise 44.8 MB → 44.9 MB (+0.4%)
investment 75.7ms ± 0.6ms 75.5ms ± 0.8ms -0.2% ✅ within noise 47.2 MB → 47.1 MB (-0.2%)
fifo 73.6ms ± 0.9ms 73.9ms ± 0.6ms +0.4% ✅ within noise 49.1 MB → 48.3 MB (-1.6%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.5ms, investment 0.4ms, fifo 0.5ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@codecov

codecov Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.26335% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-lsp/src/main_loop.rs 99.10% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 826
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 2 commits November 11, 2026 01:16
…cument

Review round 1 on the diagnostics debounce:

- Shutdown drops every pending pass, so nothing is published between
  shutdown and exit.
- A didChange with no prior didOpen (a client protocol violation) has
  no buffer for a deferred pass to read, so it publishes immediately
  from the given text, as before the debounce.
- New test pins that an immediate publish (here a watched-file
  revalidation inside the debounce window) settles a pass pending for
  the same file; deleting that cancel now fails it.
- CHANGELOG Performance entry with the measured pass counts, and the
  LSP support doc now says didChange is debounced, didSave is never
  received, and codeLens runs a pending pass first.
- Note in DiagnosticsSchedule::schedule where a max-wait cap would go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review round 2 on the diagnostics debounce:

- After shutdown, handle_notification ignores everything but exit (LSP
  3.17 Lifecycle), so a late didOpen, didChange or watched-file change
  can neither schedule nor publish a diagnostics pass. Pinned by
  test_notifications_after_shutdown_are_ignored.
- docs: a didChange for a document with no buffer (non-file URI, or no
  prior didOpen) still publishes immediately, and shutdown drops
  pending passes and ignores document notifications.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit 662aa9f into main Nov 11, 2026
54 of 55 checks passed
@robcohen
robcohen deleted the perf/lsp-coalesce-diagnostics branch November 11, 2026 11:30
robcohen added a commit that referenced this pull request Nov 11, 2026
#2947 merged as 4bc5bd8. Its hunks take main's side; this PR's own
changes (6c601dd..00c8866) are applied on top. In the test tail of
the LSP main loop, #2941's coalescing tests and this PR's tests are both
kept, and change_doc flushes the debounced diagnostics pass before the
publishes are read.

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.

perf(lsp): coalesce diagnostics during bursts of edits instead of recomputing per change

1 participant