# change-debounce ## Goal Stop paying a full reanalysis for every keystroke. Before this round each `textDocument/didChange` notification ran `set_document` immediately — lex, parse, `analyze`, `resolve_external`, lint, publish — so a burst of ten keystrokes cost ten of everything and nine of those answers were thrown away before anyone could read them. A `didChange` now only records the buffer's new text as *dirty*; the analysis runs at the first moment anything actually needs it: the next request, the next non-`didChange` notification, or a 150 ms quiet-period timer in the message loop. The buffer's **text** is still exactly current after every notification — only the analysis of it is deferred — so nothing that reads `didChange` results out of order can see a stale buffer. On a 10 000-line file one deferred keystroke saves 31 ms of work (`docs/perf/README.md`); a ten-keystroke burst saves nine of them. ## Assumptions - **A client sends a burst, not a single change.** Typing produces notifications faster than 150 ms apart; the debounce only pays off while that is true, and costs at most 150 ms of latency when it is not. - **150 ms is short enough not to be felt and long enough to coalesce a burst.** It is the same order as the debounce every mainstream language server uses. It is a constant (`CHANGE_DEBOUNCE` in `server.rs`), not a setting: a knob here would be one more thing to get wrong, and no user has asked for one (`TODO.md` §7, "no option explosion"). - **Diagnostics are the one answer nobody requests.** A pushing client never asks for them, so waiting for "the next request" alone would leave a file undiagnosed indefinitely for a user who types and then stops. That is the whole reason the timer exists, rather than flushing only on demand. - **A flush is cheap to trigger from anywhere.** `flush_dirty` returns immediately when nothing is dirty, so the calls at the top of `request` and `notification` cost a `Vec::is_empty` on every message. - **Order within a burst does not matter, order across buffers does.** Dirty buffers are flushed oldest-first (`mark_dirty` replaces an entry in place rather than moving it to the back), so the sequence of `publish` calls a client sees for two edited files is the order they were first edited in. - **Losing an unanalyzed change with its buffer is correct.** `didClose` drops the buffer's pending text: there is nothing left to flush it into, and the client is not looking at the file any more. The drop happens at the *top* of `notification`, ahead of the universal flush — doing it in the `didClose` arm is too late, because the flush has already run by then (QA, CD-1). Closing one buffer says nothing about the others, so every other dirty buffer flushes on that same notification exactly as before. ## Handshakes - **Amends `docs/features/incremental-sync/README.md`'s pinned invariant.** That round promised "one `didChange` = one `set_document` = one generation bump, however many ranges". The promise is now: **one *flush* is one `set_document`, one generation bump and one `publish` per dirty buffer** — however many ranges *and however many notifications* were coalesced into it. Everything the old promise protected still holds: the generation counter (which is `docs/features/pull-diagnostics/README.md`'s whole `resultId`) never moves twice for work that happened once, and never fails to move for a buffer whose text changed. `incremental-sync`'s own test, `one_notification_is_one_generation_bump_however_many_ranges`, still passes unchanged, because the test helper flushes after each notification — which is exactly the quiet-period timer firing. - **Observable consequence, pinned in `crates/lucisv_server/tests/e2e.rs`** (`incremental_changes_are_advertised_and_applied_over_the_wire`): **intermediate diagnostics states are no longer published**. Two changes arriving back to back — the first breaking a line, the second finishing it — used to produce three publishes (open, broken, fixed) and now produce two (open, composed). Every state that *is* published is a state the buffer really passed through; there are simply fewer of them. That test asserted the old count and now asserts the new one, with the reason written beside it. - **Consumes `sync::apply_changes` unchanged.** Ranged changes are composed against the newest text the server holds, which while a buffer is dirty is the *pending* text, not the last analyzed one. `Server::notification` looks in `dirty` before `workspace.document`. Nothing in `sync.rs` moved. - **Consumes `lsp_server`'s queue as a `std::sync::mpsc` receiver.** The timer is `Receiver::recv_timeout` on the queue `cancel-request` already introduced (`docs/features/cancel-request/README.md`); no thread and no timer object was added. A `Disconnected` receiver ends the loop exactly as the old `while let Ok(..)` did. - **Promises every request still sees the client's own changes.** The flush at the top of `Server::request` runs before dispatch, so a request answered after a `didChange` is answered from that change's analysis — the order contract the loop always had. The large-file fast path is behind that flush, not in front of it. - **No protocol change, no settings change, no index change.** The capabilities advertised at `initialize` are byte-identical. ## Status / TODO - [x] `dirty: Vec<(Uri, String)>` on `Server` — newest text per buffer, in first-dirtied order. - [x] `mark_dirty` replaces in place, so a burst does not reorder buffers. - [x] `flush_dirty` — one `set_document` + one `publish` per dirty buffer. - [x] `didChange` composes ranges against the pending text when there is one. - [x] Flush on every request, before dispatch. - [x] Flush on every notification that is not a `didChange`. - [x] `CHANGE_DEBOUNCE` (150 ms) quiet-period flush in `run`, via `recv_timeout`, only while something is dirty. - [x] `didClose` drops the buffer's pending change — before the flush, so the drop is real (QA, CD-1), pinned by `closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone`. - [x] Test: a burst is one reparse (`a_burst_of_changes_coalesces_into_one_reparse`). - [x] Server tests drive one notification at a time, so the test helper `change()` flushes — documented there as the timer firing. - [x] e2e: the publish count and the reason for it. - [ ] Not done: a flush for a *long* burst that never pauses (a paste-and-hold or a client replaying a file's history sends changes closer together than 150 ms forever). Today such a burst is analyzed when it ends or when the next request arrives. A "flush after N pending changes" backstop is the obvious answer if anyone ever reports it; it is not written because no client behaves that way and an untested backstop is worse than none. ## Work log **2026-08-28 — dev.** Implemented as part of the LSP performance round (plan: "Improve LSP performance + hover accuracy", part A1). - The deferral is a `Vec`, not a `HashMap`: it holds one entry per *dirty* buffer, which is one in practice and two while a user alt-tabs. A linear scan of that is cheaper than hashing a `Uri`, and the `Vec` gives the flush order for free. - Deferred **analysis only, never text**. The alternative — deferring `apply_changes` too and keeping a queue of unapplied changes — was rejected: every reader of `Document::text` would then need to know about the queue, and the ones that forgot would be silently wrong. Composing the text eagerly keeps the pending state to exactly one `String` that only `didChange` and `flush_dirty` know about. - The flush points were chosen to be exhaustive rather than clever: *every* request and *every* notification except the one being deferred. Anything that needs analysis is downstream of one of those two, so there is no handler that has to remember to flush for itself. - `run` only arms the timeout while something is dirty, so an idle server still blocks in `recv()` and wakes for nothing. - The server unit tests drive notifications one at a time through a helper rather than through the loop, so no burst ever forms and nothing would flush them; the helper flushes explicitly, which is the timer's behavior. Three tests that hand-rolled a `didChange` notification were moved onto that helper. **2026-08-28 — dev (QA fix).** - **CD-1 — fixed.** The `didClose` arm's `dirty.retain` was dead code: the universal flush at the top of `notification` had already drained `dirty` through `std::mem::take` by the time the arm ran, so a buffer closed mid-edit paid a full `Document::new` and published its real diagnostics one line before the close cleared them. The retain moved to the top of `notification`, *ahead* of the flush, guarded on the method name; the arm's comment now says where the drop happened instead of pretending to do it. - The uri has to be read without consuming the notification, since `extract` takes it by value and the arm below still needs it. That is a four-line `closing_uri` beside `extract`, deserializing a clone of the params — a `didClose`'s params are a single uri, so the clone is not worth avoiding with a peek into the raw `Value`. `None` (params that do not parse) drops nothing, which is exactly what the arm below already does with the same params. - The "flush on every notification but `didChange`" rule is unchanged: the flush still runs for `didClose`, and every *other* dirty buffer still goes through it. What changed is only that the closing buffer is no longer in `dirty` when it does. - Pinned by `closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone` (`server.rs`): two buffers dirtied with text that would diagnose, one closed with no request in between; the generation bumps exactly once (the buffer still open), the closed buffer gets exactly one publish and it is the clearing one, and the other buffer's pending edit is published as usual. Verified the test fails on the pre-fix code — `left: 5, right: 4` on the generation assertion — before keeping it. ## QA log **2026-08-28 — QA.** Gates run and green: `cargo fmt --check`, `cargo clippy --all-targets --workspace -- -D warnings`, `cargo test --workspace` (0 failed everywhere; `lucisv_server`: 1179 passed, 19 ignored perf tests), `cargo test -p vlog_formatter` (114 passed). All findings below were reproduced with temporary `#[test]`s added to `server.rs`, run, and then removed once confirmed — none are left in the tree. - **Finding CD-1 (medium — contradicts a checked-off invariant, wastes work, does not corrupt anything).** `didClose` does **not** actually drop a buffer's pending dirty change before analyzing it. `Server::notification` (`server.rs:1247`) flushes unconditionally for any non-`didChange` method (`server.rs:1253`, `if method != DidChangeTextDocument::METHOD { self .flush_dirty(); }`) — and `didClose` is such a method. That flush runs *before* the `match` statement even reaches the `DidCloseTextDocument:: METHOD` arm (`server.rs:1407`), so by the time `self.dirty.retain(|(pending, _)| *pending != uri)` executes (`server.rs:1413`), `flush_dirty` has already drained `self.dirty` via `std::mem::take` — the retain is a no-op in the normal flow. Net effect: closing a buffer that was mid-edit costs one full, wasted reparse + `publish` of the real (about-to-be-discarded) diagnostics, immediately followed by the close handler's own `send_diagnostics(uri, Vec::new())` clearing them — **two** publishes instead of the zero extra ones the design claims. This directly contradicts both the checked-off status-line "`[x]` `didClose` drops the buffer's pending change" and the code comment beside the (dead) retain: "there is nothing left to flush it into" — there is, and it does get flushed. - Repro (temporary test, `server.rs`, removed after confirming): open a clean buffer (`module m;\nendmodule\n`), drain the open publish, note `generation`, send one `didChange` to `module m;\n wire ;\nendmodule\n` (introduces a parse error, buffer stays dirty — `generation` provably unchanged, `dirty` non-empty), then send `didClose` with **no** request in between (`session.notify`, which calls `Server::notification` directly, exactly the production path — no manual flush helper involved). Observed: `generation` bumps by exactly one during the `didClose` call (`2` → `3`), and `session.published()` returns **2** messages: one carrying the real parse-error diagnostic (`"expected identifier (found \";\")"`), then one with `diagnostics: []`. - Not a data-corruption bug — the client ends up with the correct final state (empty diagnostics for a closed file) — but it is a real, reproducible functional gap in exactly the case the debounce is supposed to help most: a user who edits and then immediately closes a buffer pays the full analysis cost the feature exists to avoid, silently. Left unfixed (not small/unambiguous — the right fix wants a decision about whether the top-of-`notification` flush should special-case `didClose`, or whether `didClose` should remove its own `dirty` entry *before* that flush runs, which touches the "flush on every notification but `didChange`" rule this round explicitly checked off). - **Attack angles from the brief, checked and clean:** - *An un-flushed edge, generally.* Every request and every non-`didChange` notification flushes at its own top (`server.rs:1253` for notifications, the equivalent at the top of `request`), so the only genuinely un-flushed state is "nothing has asked for analysis yet" — which is exactly what the quiet-period timer exists to bound at 150 ms, and the documented, un-checked TODO item (a burst that never pauses) is real but already honestly disclosed, not silently missing. - *`didChange` on a file the client never opened.* `mark_dirty` does not require a prior `didOpen`, and neither did the pre-debounce `set_document` call it replaces — `flush_dirty`'s `set_document` creates the buffer exactly as before. No new behavior here. - *`didChange` racing `didSave`.* `didSave` is not `didChange`, so it flushes first (`server.rs:1253`) — a save's reindex always sees the latest edited text analyzed, never a stale buffer racing a fresh disk scan. - *Version-number ordering.* The server does not track LSP version numbers at all (`publishDiagnostics`'s own `version` field is hard-coded `None` at `server.rs:1848`, unchanged by this round) — nothing new to get out of order. - *Pending vs. analyzed text observed inconsistent by a request.* Cannot happen: `request` flushes before dispatch (`server.rs`'s `fn request`), so a request is always answered from the analysis of whatever is currently held, dirty or not. - *The `e2e.rs` publish-count change (3 → 2).* Confirmed the buffer genuinely passed through both published states and no diagnostic was lost: traced `incremental_changes_are_advertised_and_applied_over_the_wire` — the two `didChange` notifications and the `textDocument/formatting` request all arrive in one write to the mock transport, so the request's own top-of-`request` flush (or the burst's internal ordering) coalesces both notifications into the one flush that produces publish #2; publish #1 is the clean `didOpen`. The removed middle publish (the transiently *broken* half-edited state) was never a state a real, unhurried client would see anyway — it is the debounce's whole point. - *`a_burst_of_changes_coalesces_into_one_reparse`.* Re-derived by hand: `generation` provably does not move across the two-notification burst, then moves by exactly one at the first request after it, and `dirty` is empty afterward — matches the claimed semantics exactly. - **Perf claims (A1's "before/after" in `docs/perf/README.md`).** Arithmetic over already-measured numbers, not a separate measurement — reviewed there, no finding. ## Review **2026-08-28 — lead.** Accepted. Gates re-run independently of both agents: `cargo fmt --check` clean, `cargo clippy --all-targets --workspace -D warnings` silent, `cargo test --workspace` green. The shape is right. Deferring analysis while applying text immediately is the standard split, and flushing before every request and before every non-`didChange` notification means no handler ever reads a stale buffer — today's correctness guarantee is preserved exactly, and only keystroke-storm reparses are coalesced. The quiet-period timer in `run()` matters as much as the coalescing: diagnostics are the one answer a client never asks for, so a burst that ends in silence still gets drawn. QA's CD-1 was a real finding and correctly diagnosed: the universal flush ran *before* the `didClose` arm, so the arm's `retain` was dead and a buffer closed mid-burst paid a full `Document::new` and published diagnostics for a file the user had stopped looking at, only to clear them a line later. The fix drops the pending text ahead of the flush rather than special-casing the flush, which keeps "every other dirty buffer still flushes" true by construction. The dev verified the pinning test fails on pre-fix code before keeping it; that is the right standard. The one honest cost is recorded in `docs/perf/README.md` and is not hidden: a keystroke with *nothing* following it now publishes at 164 ms rather than one flush, because it waits out the 150 ms quiet period. Any request flushes early, so a real editor sees 4.35 ms / 37.6 ms instead — but the regression is real for a client that asks for nothing, and the number is written down rather than argued away.