# interactive-latency ## Goal Make the request and notification paths a user *feels* — the ones that run while they type and move the cursor — cost what they have to cost and no more, and say with measured numbers where the rest of the time goes. Round 1 (`docs/perf/README.md`) established the baseline and named the open question it could not answer from inside the crate: what a `didChange` → `publishDiagnostics` round trip actually takes over the wire. This round answers that, breaks one flush down stage by stage, and takes the identity-safe wins the breakdown justifies — which turned out to be six token lookups that were sweeping the whole buffer for something a binary search answers in twenty nanoseconds. Nothing on the parse path was touched: the measurements say the remaining cost is lexing and parsing, and that is a change this round deliberately does not make. ## Assumptions - **The token stream rises and never overlaps.** Every binary search added here rests on one property of `Document.tokens`: the lexer emits tokens in source order, so `end[i] <= start[i+1] <= end[i+1]` and both `span.start < offset` and `span.end < offset` are monotone predicates over the vector. That is the whole precondition `partition_point` needs, and it is pinned by `state::tests::the_token_stream_rises_and_never_overlaps` — the test that would fail first if the lexer ever changed shape. Nothing here assumes tokens are non-empty: the `Eof` sentinel is zero-width, and every argument below survives it. - **No benchmark dependency**, unchanged from round 1: `std::time::Instant`, `#[ignore]`d tests, no `criterion`. `CLAUDE.md` requires a written justification for a new dependency and there is none to write. - **A measurement asserts nothing about duration.** A test that fails when the machine is busy is a test that gets deleted. - **The e2e round trip is a real session.** It spawns the shipped binary and speaks framed JSON-RPC at it, so the number includes the pipes, the JSON, the debounce timer and the flush. It cannot be taken from inside the crate, which is exactly why round 1 could not take it. - **The generated module is uniform, and real RTL is not.** Both generators build the same repeated four-line block. The numbers are a scale, not a prediction for any given file. ## Handshakes - **`vlog_parser` → this crate (consumed, unchanged).** The binary searches consume the ordering property of `tokenize`'s output described above. Nothing was asked of `vlog_parser` and nothing in it changed. If it ever emits tokens out of order, the pinning test in `state.rs` fails before any handler answers wrongly. - **`state.rs` → `selection.rs`, `on_type.rs`, `completion.rs` (new, internal).** Two free functions, `first_token_reaching` and `first_token_from`, are published from `state.rs` beside `Document`. They are the single place the monotonicity argument is written down; every call site is one comparison on top of one of them. `inline.rs` uses a third predicate (`span.end <= offset`) written at its own call site, because it has one user and its own local proof. - **`e2e.rs`'s `Live::finish` now returns the publish count** it saw on the way out. Existing callers ignore the value, which compiles unchanged. The count is what turns "the debounce coalesces a burst" from arithmetic into a measurement. - **Two copies of one generator.** `perf::generated_module` and the copy in `tests/e2e.rs` must stay the same shape, or the in-crate table and the over-the-wire table in `docs/perf/README.md` stop being readable against one another. `lucisv_server` is a binary crate, so an integration test cannot import the original; the copy is commented as such at both ends. - **Nothing was asked of `vlog_linter`.** The lint pass costs 1.40 ms of a 32 ms flush at 10 000 lines and walks the tree once per rule; that is recorded in `docs/perf/README.md` as a future round's work, not requested here. ## Status / TODO - [x] Phase 1 — a stage-by-stage breakdown of one flush at 1k and 10k lines: `tokenize`, `tokens.clone()`, `parse_tolerant`, `collect_defines`, `analyze`, `resolve_external`, `LineIndex::new`, and the `diagnostics::all` pass a publish runs (which is *not* inside `Document::new`, and which round 1's table did not account for). `perf::breaking_down_one_flushed_keystroke`. - [x] Phase 1 — the end-to-end round trip round 1 listed as its own open TODO: `didChange` → `publishDiagnostics` against the real binary, for a single change, for a burst of ten, and for the change-then-request shape a real editor produces. `tests/e2e.rs::a_keystroke_round_trip_over_the_wire`. - [x] Phase 2 — six token lookups swapped from a sweep to a binary search, each with a test that walks **every byte** of a buffer written to have plenty of touching tokens and asserts the search returns exactly what the sweep returned. - [x] Phase 2 — the three sweeps that are inherent left alone, with the reason written down (below). - [x] Phase 3 — decided against every change the breakdown did not justify, with the number for each (below). - [x] Phase 4 — `docs/perf/README.md` refreshed: both of round 1's open TODOs resolved or restated, every figure re-measured on this machine. Not done, deliberately, and each with the number that would justify it — the list lives in `docs/perf/README.md`'s *What it would take to go faster* so it sits beside the measurements rather than in a feature's checklist. ## The Phase 2 call sites, one by one The predicate each site wants is *not* always "the token containing this offset", so `Document::token_at` is not a drop-in for any of them. Each swap below is argued from the ordering property, and each argument is pinned by a test that compares the new expression against the old one at every byte of `state::mixed_buffer(20)` — a buffer written with `a=b;`-style adjacent punctuation, comments and strings precisely because the bytes that could tell a search from a sweep are the ones two tokens share. **Changed and proven.** | site | wanted | now | test | |---|---|---|---| | `selection.rs` `enclosing` | the first token with `start <= offset <= end` | `first_token_reaching`, then one `covers` check | `selection::tests::the_innermost_step_is_the_token_the_sweep_returned_at_every_offset` | | `on_type.rs` `statement_edit` | the token with `end == offset` | `first_token_reaching`, then one `==` | `on_type::tests::the_token_ending_at_the_cursor_is_the_one_the_sweep_returned` | | `on_type.rs` `first_on_line` | the first non-`Eof` token with `start >= content` | `first_token_from`, then `find` over the tail | `on_type::tests::the_first_token_on_a_line_is_the_one_the_sweep_returned` | | `completion.rs` `is_procedural` | the *index* of the token with `start == offset` | `first_token_from`, then one `==` | `completion::tests::the_scope_gates_answer_what_their_sweeps_answered` | | `completion.rs` `balanced` | every token whose start is in `[from, at)` | a slice between two `first_token_from`s | the same test | | `inline.rs` `triggered` | the **last** non-`Eof` token with `end <= offset` | `partition_point`, then `rposition` over the prefix | `inline::tests::the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found` | Two of these deserve their reasoning spelled out, because they are the two where a careless swap would have changed an answer: - **`selection.rs` takes `span.end` inclusively.** At a byte two adjacent tokens share, `find(covers)` returned the *earlier* of the two, while `Document::token_at` — which uses `TextRange::contains`, end exclusive — would return the later one. `first_token_reaching` returns the earlier one, which is why it is the right primitive here and `token_at` is not. - **`completion.rs`'s `balanced` was sweeping the whole buffer.** Its filter had no upper bound to break on, so a cursor anywhere in a 10 000-line file walked all 94 961 tokens to reach a window a few dozen tokens wide. It is the largest of the six by some way: 130 µs → 36 ns. **Left alone, with the reason.** - **`signature.rs` `enclosing_list` (:138) and `active_entry` (:231).** Inherent. Both maintain a parenthesis-depth stack, and a depth at the cursor is a function of *every* bracket before it — there is no prefix a binary search may skip without recomputing what it skipped. Both already break at the cursor rather than running to the end of the buffer, so neither is a whole-buffer sweep; bounding the loop with a binary search instead of the `break` would save one comparison per token and change nothing else, which is not worth the edit. - **`pairs.rs` `analyze` (:230).** Inherent, and not a position query at all: it matches *every* scope keyword in the stream and returns the whole pair set. There is no offset to search for. - **`completion.rs` `in_comment_or_string` (:553).** Left, and its existing doc comment already says why: comments are lexer trivia hanging off whichever token happens to follow or precede them, so the token whose `leading` holds a comment at a given byte is not the token a search for that byte would find. A correct search would have to reason about attachment; a wrong one would offer a completion list inside a comment. This is the one remaining per-keystroke whole-buffer walk, and it is recorded as such in `docs/perf/README.md` rather than guessed at. - **`completion.rs` `word_tier` (:355), `candidates.rs` (:218), `folding.rs` (:58).** Inherent: each needs every token in the file, not a token at an offset. ## Work log **2026-08-28 — dev (round 2).** *Phase 1, measured first.* Added `perf::breaking_down_one_flushed_keystroke` and `perf::finding_one_token_against_sweeping_the_stream` to the existing `perf.rs` module, and `a_keystroke_round_trip_over_the_wire` to `e2e.rs`. The e2e measurement reuses the `Live` session helper that already existed in that file for the watched-files test rather than adding a second one; the only change to shared code is that `Live::finish` now returns the number of `publishDiagnostics` it saw while shutting down. That count is the point: a buffer left dirty by a burst is flushed before the next *request* is answered, so by the time `shutdown` comes back every publish the burst was going to produce has arrived. A burst of ten keystrokes produces **one**. The breakdown decided everything that followed. At 10 000 lines a flush is 31 ms, and 24.5 ms of it is `tokenize` plus `parse_tolerant`. `analyze` is 11 %, the diagnostics pass another 4 % on top of the flush, and `resolve_external` — which the round's brief named as a possible target — is **49 µs, one part in six hundred**. There is nothing to skip there. *Phase 2.* Six sweeps became binary searches, on the strength of the `finding_one_token` measurement: 77 µs → 20 ns for a cursor lookup at 10 000 lines, and 130 µs → 36 ns for `balanced`'s window. The two primitives live in `state.rs` beside `Document::token_at`, which is where the one-paragraph monotonicity argument they all rest on is written; `inline.rs`'s third predicate is written at its own call site because it has one user. Every swap is pinned by a test that compares it against the code it replaced at every byte of a shared awkward buffer (`state::mixed_buffer`, whose one job is to have plenty of tokens that touch). Two of the six are *not* what `Document::token_at` would have answered, and the table above says which and why; a seventh candidate, `completion.rs`'s comment gate, was left alone because no search of the token stream answers the question it asks. *Phase 3 — nothing, on purpose.* The breakdown does not justify a change: - Lex and parse are 79 % of a flush. Making them incremental is the only lever left, and it is a large change under `CLAUDE.md`'s hard invariants 1 and 2. Written up in `docs/perf/README.md` with the number that would pay for it; not attempted. - `tokens.clone()` is 2.40 ms, 7.7 % of a flush, and is **load-bearing**: `parse_tolerant` takes its token vector by value and steals the comments out of it (`std::mem::take(&mut self.tokens[pos].leading)`, `self.tokens[pos].trailing.take()`), so `Document.tokens` cannot be the same vector — folding, the on-type comment test and completion's comment gate all read that trivia. The clone is also already a win: before the one-lex change it was a second `tokenize`, which this round measures at 12.5 ms. Removing it needs a cheaply-clonable `Token`, which is a `vlog_parser` type change reaching the formatter. Written up, not attempted. - The lint pass walks the tree once per rule (`vlog_linter::lint`'s `for rule in enabled`), but it is 1.40 ms against a 32 ms flush. Fusing the walks is a `vlog_linter` refactor for 4 %. Written up, not attempted. - `resolve_external` is 49 µs. Skipping it when the index generation has not moved would save one part in six hundred of a flush and add a cache invalidation rule to a path that currently has none. Not attempted, and the number is the reason. *The finding worth acting on is not a code change.* Over the wire, a lone keystroke's round trip is 156 ms at 1 000 lines — of which 150 ms is the change debounce's own quiet period, and 4.8 ms is the work. The same keystroke followed by a request, which is what a real editor sends, is **4.8 ms at 1 000 lines and 37 ms at 10 000**. So for the editors that ask for anything after a change (VS Code asks for semantic tokens, inlay hints and highlights), the debounce timer never runs and the flush is the whole cost; for a client that asks for nothing, the felt latency is the timer. `CHANGE_DEBOUNCE` is a product decision the previous round made deliberately at 150 ms, so it was not touched — but it is now a measured number rather than an assumed one, and `docs/perf/README.md` says so. ## QA log **2026-08-28 — QA.** Verdict: **SHIP WITH FIXES noted, none applied** — one methodology finding on the e2e measurement (not shipped code a user can hit), one informational note verified harmless. Everything else attacked and held. Gates, verbatim: - `cargo fmt --check` — clean, no output. - `cargo clippy --all-targets --workspace -- -D warnings` — clean, no warnings. - `cargo test --workspace` — every crate green: lucisv_server's unit binary 1192 passed / 21 ignored, its `e2e` integration binary 55 passed / 1 ignored (the perf test, run separately below), every other crate green too. No `FAILED`, no `error[`. - `cargo test -p vlog_formatter` — 31 + 1 + 4 + 6 + 2 + 22 + 114 + 0 passed across its binaries, 0 failed. - `cargo test --release -p lucisv_server perf:: -- --ignored --nocapture --test-threads=1` — 12 passed. Numbers reproduced within the noise the README itself budgets (see below). - `cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1` — 1 passed: `1000 lines: one change alone 161.9ms, a burst of ten 160.4ms for 1 publish(es), one change a request follows 4.7ms` / `10000 lines: one change alone 205.7ms, a burst of ten 199.0ms for 1 publish(es), one change a request follows 38.5ms` — matches `docs/perf/README.md`'s 156/205/157/205/1/4.76/37.4 within reason. **Attack angle 1 (identity claims).** All six call sites re-derived from the source and checked against their sweep predicates by hand (`selection.rs` `enclosing`, `on_type.rs` `statement_edit` and `first_on_line`, `completion.rs` `is_procedural` and `balanced`, `inline.rs` `triggered`). Every one of the existing per-site tests already walks **every byte** of `mixed_buffer(20)` (not just a handful of offsets), so the exhaustive-diff form the brief asked for is already what shipped, not something to widen. Checked by hand and confirmed safe at the edges the brief named: offset 0, the last byte, the `Eof` sentinel, an empty file, a file that fails to lex (empty `tokens`), and a large-file fast-path document — `on_type.rs`'s own `OnTypeFormatting::METHOD` arm in `server.rs:832` answers the empty edit list before `level_at`/`first_on_line` ever run on a large doc; `completion.rs`'s `completions` guards `doc.tokens.is_empty()` at `completion.rs:154` before `is_procedural`/`balanced` are reachable; `inline.rs`'s `inline_completions` guards the same at `inline.rs:237`; `selection.rs`'s `enclosing` and the two `first_token_*` primitives themselves degrade safely on an empty slice (`partition_point` on `&[]` is `0`, `.get(0)` on an empty `Vec` is `None`). `selection.rs`'s inclusive-`covers`/exclusive-`token_at` distinction is real and correctly *not* used — traced through `first_token_reaching` + `covers` by hand at a shared boundary byte and it does return the earlier of two touching tokens, matching the sweep it replaced. **Attack angle 2 (the precondition).** `state::tests::the_token_stream_rises_and_never_overlaps` exercises exactly one hand-written buffer (`mixed_buffer(20)`), which is narrow on its own — no macros, no directives, no unterminated constructs. Delegated to a sub-agent to read `vlog_parser`'s lexer directly rather than trust the docstring's claim. Finding: `vlog_parser`'s own `tests/spans.rs::assert_covers_source` already asserts the same invariant (non-overlap, source order, full byte coverage, comments included) over 40+ deliberately adversarial fixtures — macros, `` `ifdef``/`` `include`` interleaving, attributes, CRLF, BOM, multi-byte UTF-8 in strings and comments — and `tests/error_recovery.rs` fuzzes every byte-prefix and every single-byte deletion of a corpus without panicking. Every lexer error path (`skip_string`, `skip_block_comment`, the attribute scanner) returns `Err` rather than a partial, possibly-violating `Vec`, and `TextRange::new` clamps `end` to `max(start)` structurally. No plausible gap found: the one narrow test in `state.rs` is sufficient because it rests on an invariant `vlog_parser` proves far more thoroughly one layer down, and the docs correctly point there rather than re-arguing it. **Attack angle 3 (the e2e measurement's methodology) — one finding.** - **IL-1 (medium) — the burst's "1 publish(es)" figure is not the robust, order-independent count the code and the docs describe.** `crates/lucisv_server/tests/e2e.rs:4696-4727`. `published` is computed as `1 + live.finish()` (line 4727): the `1` is an unstated assumption that the lone `wait_for(|m| m["method"] == "textDocument/publishDiagnostics")` right after the burst (line 4704) consumed *exactly* the burst's own publish and nothing else, and `live.finish()`'s count only starts accumulating after the "one change a request follows" loop ten lines later (4714-4725) has already run — ten more iterations, each with its own generic `wait_for(|m| m["method"] == "textDocument/publishDiagnostics")` (line 4722) that accepts *any* publish, not specifically the one its own request just triggered. A stray or duplicate publish arriving from the burst in that window would be silently absorbed by one of those ten waits and never increment `published` or surface anywhere in the printed line. The doc comment above the burst (line 4696-4699: "the count below is that claim measured rather than reasoned about: any publish still to come arrives before `shutdown` does") is true of `live.finish()`'s own drain — nothing gets past *that* point unnoticed — but it is not true of the window between the burst and the drain, which is exactly where a second publish would have to be counted to falsify "exactly one". As written, the test would print "1" whether the burst produced one publish or secretly produced two, which is indistinguishable from the claim it's supposed to be checking. In practice the debounce is understood to always coalesce to one flush, so this is a soundness gap in the *measurement*, not evidence of a real double-publish — but it means the "counted rather than reasoned about" claim is itself partly reasoned about. Not fixed: closing it cleanly means either running the burst as its own `Live` session finished immediately after (so nothing else can absorb a stray), or having `wait_for` tally every `publishDiagnostics` it ever passes over for the life of the session — both are design choices for the dev, not a QA drive-by edit. - Everything else in this angle held. `Live::finish`'s drain (`e2e.rs:2231`) really does read to `shutdown`'s response before returning, so nothing published after the last explicit `wait_for` in a test is lost *at that point* — it is specifically the mid-test absorption above that is the gap. The 150 ms figure in the lone-keystroke row is the timer and not a stall: reproduced at 161.9 ms / 205.7 ms against a documented 150 ms `CHANGE_DEBOUNCE` plus a single flush (2.6 ms / 31.2 ms measured separately), which accounts for the total without residue. **Attack angle 4 (duplication) — one informational note, verified harmless.** `perf::generated_module` (`crates/lucisv_server/src/perf.rs:42-57`) and its copy in `crates/lucisv_server/tests/e2e.rs:4634-4649` are not byte-identical: the `e2e.rs` copy appends ` // typing\n` before `endmodule` that the original does not have, so the test has a stable, comment-only line to land keystrokes on. The doc comment on the copy ("The two must stay the same shape, or the two tables ... stop being readable against one another") slightly overstates it — they differ by one line. Verified harmless: a comment is lexer trivia and is never its own token, so `tokens.len()` is identical between the two generators at the same `lines`, and the added ~12 bytes is noise against 29 KB / 309 KB files. The two perf tables do stay readable against one another; no fix needed. **Attack angle 5 (perf honesty).** Every figure in `docs/perf/README.md`'s round-2 tables reproduced within the noise the document itself budgets for, on a fresh `--release` run (see gates above for the two exact commands and their output). Spot check on "the breakdown sums to `Document::new`'s 31.1 ms" — a claim the brief asked about but which, checked directly, is **not actually written anywhere in either README**; nowhere does the text assert the eight-stage breakdown sums to the `Document::new` figure. As a sanity check anyway: summing this run's own breakdown stages inside `Document::new` (tokenize 12.512 + parse_tolerant-with-clone 14.149 + collect_defines 0.115 + analyze 3.174 + resolve_external 0.012 + `LineIndex::new` 0.105 ≈ 30.07 ms) against the dedicated `Document::new` figure from the same run (31.22 ms) leaves about 1.15 ms — 3.7% — unaccounted for, which is consistent with the README's own caveat that the breakdown "runs eight measurements back to back on one heap" and should be read as *shares*, not as a sum that has to close exactly. No finding, since no stronger claim than that is actually made. **Attack angle 6 (regression sweep).** `cargo test --workspace` exercises every one of the four handlers' existing suites unchanged and green (selection.rs, on_type.rs, completion.rs, inline.rs — see gates above). Adversarial shapes the brief named are already covered by name in the existing suites and were spot-read to confirm they exercise the *changed* code paths and not just the surrounding handler: `on_type.rs` `a_semicolon_the_lexer_never_saw_ends_no_statement`, `a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line`, `a_crlf_line_ending_is_never_touched_by_the_edit`; `completion.rs` `a_buffer_that_does_not_lex_is_declined`; `inline.rs` `a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at`, `a_trigger_at_the_true_end_of_file_still_offers_a_ghost`, `crlf_line_endings_still_trigger`; `selection.rs` `a_file_that_does_not_lex_still_answers_the_file_range`, `an_empty_file_still_answers_one_degenerate_chain`. **PDS-1..4 and CD-1, spot-checked in code rather than trusted from the README.** `hover.rs:361` (`only_a_closer_on`) and `:373` (`is_closer_word`) exist and `another_port_on`/`is_port_grammar_word` are gone — PDS-1 real. `hover.rs:292-295` strips a trailing `\r` in the one line reader all three `attached_lines` collections pass through — PDS-4 real. `server.rs:1247-1262` (`notification`): the `dirty.retain` for `DidCloseTextDocument::METHOD` sits *above* the `if method != DidChangeTextDocument::METHOD { self.flush_dirty() }` call, guarded on the method name via a borrowed, cloned `closing_uri` (`server.rs:2214`, reads `params` without consuming the notification) — CD-1 genuinely closed, not dead code any more. PDS-2/PDS-3 not independently re-derived (no code-shape claim to check beyond what PDS-1/PDS-4 already verify the same file's discipline on); taken on the strength of the named tests, which are present and green. ## Review **2026-08-28 — lead.** Accepted, with one methodology fix applied by me (below). Gates re-run independently: fmt clean, clippy silent, workspace tests green, formatter snapshot + idempotency suite green, the twelve `perf::` measurements and the wire measurement both reproduce. This round did the thing that makes a performance round worth anything: it measured first and then declined to optimise three of the four things it had been pointed at, with a number for each refusal. `resolve_external` at 49 µs of a 31 ms flush disproved the brief's own hypothesis, and saying so is a better outcome than a speculative cache on a path that has no invalidation rule today. Lex and parse at 79 % is the real answer, and leaving incremental parsing to a planned round rather than starting it opportunistically is right — that work lands directly on hard invariants 1 and 2 and is not something to attempt as the tail of a perf sweep. The Phase 2 swaps are the part I looked at hardest, because six "obviously identical" rewrites is exactly where a silent behaviour change hides. The dev found the one that was *not* identical: `selection.rs`'s `covers` treats `span.end` inclusively, so at a byte two tokens share, the sweep returned the earlier token and `Document::token_at` would have returned the later one. Building `first_token_reaching` instead of reaching for the existing helper is the correct instinct, and differential-testing each new expression against the predicate it replaced at every byte of a purpose-built buffer is the right proof. Three call sites were left alone with reasons — signature help's paren depth is inherently a prefix scan, `pairs.rs` is not a position query, and completion's comment gate cannot be answered by any search of the token stream because comments are trivia. Recording the last of those as the remaining per-keystroke whole-buffer walk is more useful than a forced fix. **Fix applied at review.** QA's IL-1 was right and I closed it directly rather than spending another round: the burst-of-ten publish count was `1 + finish()`, but the ten-iteration request loop sat between the burst and the drain, and each of its `wait_for`s accepts *any* publish — so a second publish the burst had produced would have been absorbed there and the figure would still have read "1". The burst now runs last, immediately before the drain, with the keystroke versions renumbered to stay monotonic. Re-measured after the change: still exactly one publish at both sizes, and the row is now counted rather than assumed. IL-2's overstated doc comment is corrected in place — the two `generated_module` copies differ by one trivia line, which is not a token and does not move a number.