From 172a034c6775c74895986951a191499b89ae1d17 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Fri, 28 Aug 2026 20:20:20 -0700 Subject: [PATCH] The startup scan answers requests as it goes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A request sent right after initialized waited out the whole startup scan — 780 ms cold, 287 ms warm over 200 files, against 26-64 us once the scan was done. The scan is now a value (Scan: begin/step/publish/ finish; rebuild_index_with is the same three-line loop, so one-shot and interleaved are structurally the same code and fingerprint identically), fed to the live index with one WorkspaceIndex::absorb per drain — per-file merging measured quadratic, 11.7 s over 800 files — and the message queue drains between files: the first hover of a session answers in 15.5 ms cold / 12.8 ms warm against the index so far, open file first, scan totals inside noise. Order contract kept: only the startup scan answers mid-way (must_wait holds requests queued behind any rescan), scans under 64 files stay one-shot (a count, not a clock), mid-scan rescan requests coalesce into exactly one follow-up, shutdown stops the scan where it stands. All three tables publish together. QA pinned the INTERLEAVE_ABOVE boundary, the absorb duplicate-path edge and the mid-scan didOpen double-publish; the whole pre-existing suite passes unmodified, stable over repeated runs. Co-Authored-By: Claude Fable 5 --- TODO.md | 13 + crates/lucisv_server/src/candidates.rs | 22 +- crates/lucisv_server/src/includes.rs | 24 + crates/lucisv_server/src/perf.rs | 96 +++ crates/lucisv_server/src/server.rs | 912 +++++++++++++++++++++-- crates/lucisv_server/src/state.rs | 520 ++++++++++++- crates/lucisv_server/tests/e2e.rs | 39 +- crates/vlog_semantic/src/workspace.rs | 57 +- crates/vlog_semantic/tests/workspace.rs | 116 +++ docs/features/hover-line-index/README.md | 18 +- docs/features/lucisv-server/README.md | 13 + docs/features/scan-interleave/README.md | 592 +++++++++++++++ docs/perf/README.md | 50 ++ 13 files changed, 2335 insertions(+), 137 deletions(-) create mode 100644 docs/features/scan-interleave/README.md diff --git a/TODO.md b/TODO.md index 96e26c5..c32c118 100644 --- a/TODO.md +++ b/TODO.md @@ -598,6 +598,19 @@ later: measured is not an incrementality problem at all**: the first request of a session waits out the startup scan (780 ms cold, 287 ms warm), because `Server::new` scans before the message loop starts. Filed there, not fixed. + → **Fixed 2026-08-28** (`docs/features/scan-interleave/README.md`): the scan + is now per-file steps with the message queue drained between them, so a + startup scan of more than 64 files answers requests while it runs — 780 ms → + **15.5 ms** cold, 287 ms → **12.8 ms** warm, with the scan's own total moving + under a percent (860-file corpus: 351 → 353 ms cold, 187 → 189 ms warm). The + merge cost was measured first and ruled per-file feeding out: a merge is a + pass over the whole index, so one per file would have cost 631 ms of merging + on 200 files against 464 ms of parsing. Records are staged per file and folded + in with one `WorkspaceIndex::absorb` per *drain*, and a drain only happens + when a message is waiting — so a scan nobody is waiting on pays nothing. + Answers given mid-scan read the index as of that moment, and only the startup + scan gives them: a request queued behind a message that asked for a rescan + waits for that rescan, which is the order contract the loop always kept. - [x] **Release prep.** `LICENSE` (MIT), `CHANGELOG.md` (v0.2.0), version bumped to 0.2.0 across the workspace and the extension, `tools/release.sh` (release binaries + `.vsix` + `SHA256SUMS` into a gitignored `dist/`) and diff --git a/crates/lucisv_server/src/candidates.rs b/crates/lucisv_server/src/candidates.rs index c07d4c2..decc60f 100644 --- a/crates/lucisv_server/src/candidates.rs +++ b/crates/lucisv_server/src/candidates.rs @@ -126,6 +126,21 @@ impl Candidates { self.set_words(path, words); } + /// [`Candidates::update_words`] for a batch of files — the form a scan + /// publishing what it has indexed so far uses. + /// + /// One re-derivation of the two index tables for the whole batch rather + /// than one per file: they are read off the index and nothing else, so + /// doing it once at the end of the batch is doing it once with the same + /// answer. The word table is patched per file exactly as it is there. + pub fn absorb(&mut self, index: &WorkspaceIndex, batch: Vec<(PathBuf, Vec)>) { + for (path, words) in batch { + self.set_words(&path, words); + } + self.units = units_of(index); + self.macros = macros_of(index); + } + /// Drop one file's contribution entirely. pub fn remove_file(&mut self, index: &WorkspaceIndex, path: &Path) { self.units = units_of(index); @@ -229,7 +244,12 @@ fn macros_of(index: &WorkspaceIndex) -> Vec { /// orders of magnitude more identifier *tokens* than distinct identifiers /// (900k against 17k over this repo's corpus), and copying every one of them /// only to sort the copies away costs more than the lexing does. -fn words_in(text: &str) -> Vec { +/// +/// `pub(crate)` because a scan lexes each file as it reaches it rather than in +/// one pass at the end: no part of a scan may be longer than one file, or the +/// message queue goes unanswered for the length of it +/// (`docs/features/scan-interleave/README.md`). +pub(crate) fn words_in(text: &str) -> Vec { // A file that does not lex contributes nothing rather than being guessed // at with a regex — the same all-or-nothing rule the lexer gives every // other consumer. diff --git a/crates/lucisv_server/src/includes.rs b/crates/lucisv_server/src/includes.rs index 469c1a9..85ff548 100644 --- a/crates/lucisv_server/src/includes.rs +++ b/crates/lucisv_server/src/includes.rs @@ -144,6 +144,30 @@ impl IncludeGraph { }; } + /// [`IncludeGraph::update_file`] for a batch of files, with the `+incdir+`s + /// the scope resolves to right now — the form a scan publishing what it + /// has indexed so far uses. + /// + /// `known` is the scan's whole work list rather than the files it has + /// reached, so the known-file and folded-spelling tables are complete from + /// the first publish: which files *exist* is settled the moment the scope + /// is resolved, and only the edges are discovered file by file. One + /// `relearn` for the batch, for the same reason + /// [`Candidates::absorb`](crate::candidates::Candidates::absorb) re-derives + /// its index tables once. + pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]) { + self.incdirs = incdirs.to_vec(); + self.relearn(known); + for (path, text) in batch { + let targets: Vec = + scan(text).iter().filter_map(|include| self.resolve(Some(path), include)).collect(); + match targets.is_empty() { + true => self.edges.remove(*path), + false => self.edges.insert(path.to_path_buf(), targets), + }; + } + } + /// Drop one file from the graph: its own edges, and its place among the /// known files. pub fn remove_file(&mut self, path: &Path, known: &[PathBuf]) { diff --git a/crates/lucisv_server/src/perf.rs b/crates/lucisv_server/src/perf.rs index a11ba90..8d8df75 100644 --- a/crates/lucisv_server/src/perf.rs +++ b/crates/lucisv_server/src/perf.rs @@ -379,6 +379,102 @@ fn reindexing_one_changed_file() { } } +/// `cargo test --release -p lucisv_server perf::what_a_scan -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] +fn what_a_scan_does_before_its_first_file() { + // The floor under a mid-scan answer's latency. A scan answers messages + // between two *files*, so whatever it does before the first one is a + // block no drain can break up: resolving the scope, reading every + // in-scope file, and opening the persistent store. Measured because + // `docs/features/scan-interleave/README.md` files "read the files lazily" + // as a deliberate not-done, and a not-done is only honest with a number. + let files: Vec<(String, String)> = + (0..200).map(|n| (format!("m{n}.sv"), generated_module(&format!("m{n}"), 1_000))).collect(); + let refs: Vec<(&str, &str)> = + files.iter().map(|(name, text)| (name.as_str(), text.as_str())).collect(); + let dir = scratch("scanhead", &refs); + let mut workspace = Workspace::default(); + workspace.set_client_settings(crate::settings::ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + ..Default::default() + }); + workspace.adopt_roots(vec![dir.clone()]); + let started = Instant::now(); + let mut scan = workspace.begin_scan(&mut |_| {}); + let head = started.elapsed(); + let started = Instant::now(); + workspace.scan_step(&mut scan, &mut |_| {}); + let one = started.elapsed(); + let started = Instant::now(); + while workspace.scan_step(&mut scan, &mut |_| {}) {} + let rest = started.elapsed(); + let started = Instant::now(); + workspace.finish_scan(scan); + let tail = started.elapsed(); + eprintln!( + "scan of {} files of 1k lines: before the first file {head:?}, \ + one file {one:?}, the other {} {rest:?}, finishing {tail:?}", + files.len(), + files.len() - 1 + ); + let _ = std::fs::remove_dir_all(&dir); +} + +/// `cargo test --release -p lucisv_server perf::publishing -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] +fn publishing_a_half_built_index_mid_scan() { + // What an interleaved scan's *publish* costs, against the per-file work it + // is interleaved with. `docs/features/scan-interleave/README.md` chose the + // publish rhythm from these numbers: a merge is a whole-index pass, so one + // per file would be quadratic and one per drain is not. + for files in [50usize, 200, 800] { + let sources: Vec<(PathBuf, String)> = (0..files) + .map(|n| (PathBuf::from(format!("m{n}.sv")), generated_module(&format!("m{n}"), 1_000))) + .collect(); + let records: Vec = sources + .iter() + .map(|(path, src)| vlog_semantic::FileFacts::of(path.clone(), src)) + .collect(); + let parse = mean(3, || { + let (path, src) = &sources[0]; + black_box(vlog_semantic::FileFacts::of(black_box(path.clone()), black_box(src))); + }); + let build = mean(3, || { + let mut builder = vlog_semantic::IndexBuilder::new(); + for facts in &records { + builder.add_facts(facts.clone()); + } + black_box(builder.finish()); + }); + let clone = mean(3, || { + black_box(records.clone()); + }); + let index = WorkspaceIndex::build( + sources.iter().map(|(path, src)| (path.clone(), src.as_str())).collect::>(), + ); + let held = mean(10, || { + let mut index = index.clone(); + index.update_facts(black_box(records[files / 2].clone())); + black_box(index); + }); + let index_clone = mean(10, || { + black_box(index.clone()); + }); + eprintln!( + "{files} files of 1k lines: one file's parse {parse:?}; \ + one whole merge {:?} (build {build:?} less {clone:?} of record cloning); \ + one update_facts on a held file {:?} (less {index_clone:?} of index cloning); \ + per-file feeding would cost {:?} of merging against {:?} of parsing", + build.saturating_sub(clone), + held.saturating_sub(index_clone), + held.saturating_sub(index_clone) * files as u32, + parse * files as u32, + ); + } +} + /// `cargo test --release -p lucisv_server perf::looking_up -- --ignored --nocapture --test-threads=1` #[test] #[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index 957d933..c87506c 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -66,7 +66,7 @@ use serde::de::DeserializeOwned; use serde_json::Value; use crate::settings::ClientSettings; -use crate::state::{IndexEvent, Workspace}; +use crate::state::{IndexEvent, Scan, Workspace}; use crate::{ code_action, completion, diagnostics, file_ops, folding, format, hierarchy, hover, includes, inlay, inline, large, lens, linked, nav, on_type, pairs, ports, rename, selection, settings, @@ -162,6 +162,32 @@ pub struct Server { /// request, the next non-`didChange` notification, or the quiet-period /// timer in `run`. See `docs/features/change-debounce/README.md`. dirty: Vec<(Uri, String)>, + /// Everything the client has sent, forwarded off the transport's + /// rendezvous channel by [`forward`]. Held here rather than made in `run` + /// because a **scan** drains it too: the loop must not go quiet for the + /// length of one (`docs/features/scan-interleave/README.md`). + queue: std::sync::mpsc::Receiver, + /// Whether a scan is running. A message answered mid-scan can ask for + /// another one, and this is what turns that into the flag below rather + /// than a scan inside a scan. + scanning: bool, + /// A rescan asked for while a scan was running. Coalesced: any number of + /// requests is one more scan when this one ends, whatever asked for them. + rescan_wanted: bool, + /// Whether the scan now running is one a *message* asked for. The startup + /// scan is not — nothing was queued ahead of it — and that is the whole + /// difference between a request answered mid-scan and one that waits. See + /// [`Server::must_wait`]. + answering_a_rescan: bool, + /// Whether the client has shut the server down. Set by a `shutdown` + /// answered mid-scan, which stops the scan where it stands and keeps `run` + /// from taking another message. + stopped: bool, + /// Messages a mid-scan drain would have answered out of order, kept in + /// arrival order until the rescan they are queued behind has run. See + /// [`Server::must_wait`] — this is the order contract, not a queue of its + /// own. + held: Vec, } /// How long a burst of `didChange` notifications may sit unanalyzed once the @@ -170,6 +196,27 @@ pub struct Server { /// is worth nothing if diagnostics never arrive until the next request does. const CHANGE_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(150); +/// How many files a scan must have to be worth answering messages in the +/// middle of. +/// +/// **The whole trade of `docs/features/scan-interleave/README.md`, in one +/// number.** A mid-scan answer reads the index as far as the scan has built +/// it, so it can be *less* than the answer the same request would get a +/// moment later — and that is only ever worth it when "a moment later" is a +/// wait a person can feel. Below this, a scan is over in a few milliseconds +/// (the 860-file corpus is 340 ms, so sixty-four files is under thirty), and +/// trading a complete answer for those milliseconds would be a bad bargain; +/// above it, the measured wait is hundreds of milliseconds and the trade is +/// the point of the round. +/// +/// A count rather than a clock deliberately: a rule about elapsed time makes +/// what a server answers depend on how loaded the machine was, which is +/// exactly the property a test suite — and a bug report — cannot work with. +/// The known limit of counting is a workspace of a *few very large* files, +/// which is under this bar and can still take a second; that is written down +/// as a deliberate not-done rather than papered over with a second rule. +const INTERLEAVE_ABOVE: usize = 64; + /// What the workspace-rescan progress bar calls itself. One title for every /// rescan — startup, save, watched file, changed scope — because they are the /// same work and a user reading the status bar wants to know that. @@ -209,7 +256,14 @@ impl Server { abilities: ClientAbilities, storage: Option, ) -> Server { - Server::started(connection, roots, abilities, ClientSettings::default(), storage) + Server::started( + connection, + roots, + abilities, + ClientSettings::default(), + storage, + Vec::new(), + ) } /// [`Server::new`] with a client's settings already in hand — the seam the @@ -217,13 +271,27 @@ impl Server { /// one whose subject is not the scope says so here rather than driving a /// `didChangeConfiguration` and then reasoning about the extra rescan it /// buys. + /// + /// `queued` is what the client had already sent when the server was built + /// — the opening burst, put straight onto the queue the startup scan + /// drains. Empty for [`Server::new`]; a test fills it because racing the + /// forwarder thread for it would make the test a coin toss rather than a + /// check. fn started( connection: Connection, roots: Vec, abilities: ClientAbilities, client: ClientSettings, storage: Option, + queued: Vec, ) -> Server { + // Started before the first scan, not in `run`: the scan below answers + // whatever the client has already sent, and it can only do that off a + // queue that is already being filled. + let (forwarded, queue) = forward(&connection); + for message in queued { + let _ = forwarded.send(message); + } let mut server = Server { connection, workspace: Workspace::default(), @@ -238,6 +306,12 @@ impl Server { token_results: 0, indexings: 0, dirty: Vec::new(), + queue, + scanning: false, + rescan_wanted: false, + answering_a_rescan: false, + stopped: false, + held: Vec::new(), }; // Nothing has been built yet, so there is no rebuild to owe: the // `true` this returns for a non-default `client` is the rebuild that @@ -253,16 +327,30 @@ impl Server { // so the loop below never sees one to hang these off instead. The // first index build is the slowest one of the session, so it gets the // same bar every later rescan gets. - let bar = server.begin_indexing(); - // The fields are split apart because the watcher writes to the - // connection while the workspace is borrowed mutably for the rebuild - // it is watching. The same two operations on the same value, in the - // same order, as the one-line call they replace. - let Server { connection, workspace, .. } = &mut server; - let mut watch = IndexWatch::new(connection, bar.as_ref(), workspace.client_settings()); - let warnings = workspace.open_roots_with(roots, &mut |event| watch.see(event)); - let (skipped, cached) = (watch.skipped, watch.cached); - server.end_indexing(bar, skipped, cached); + // + // And it answers messages while it runs, which is what stops the first + // request of a session waiting out the whole scan + // (`docs/features/scan-interleave/README.md`). Everything below it is + // therefore reached with the client's opening burst already handled — + // and skipped altogether if that burst shut the server down. + server.workspace.adopt_roots(roots); + let warnings = server.scan_until_settled(false); + if server.stopped { + return server; + } + // A buffer can now be *opened* during the startup scan, and what was + // published for it then was computed against a half-built index. This + // is the same debt a rescan pays at the end of `reindex`, owed here + // for the first time because before this round no buffer could exist + // at this point. Nothing at all is sent when nothing is open, which is + // every session whose client did not get a `didOpen` in edgeways. + if !server.workspace.open_uris().is_empty() { + server.refresh_code_lenses(); + server.generation += 1; + for uri in server.workspace.open_uris() { + server.publish(&uri); + } + } server.report_scope(warnings); server.register_watchers(); // The pull half of the settings model. Asked here because this is the @@ -290,15 +378,32 @@ impl Server { /// come — diagnostics are the one answer the client never asks for. pub fn run(&mut self) -> Result<(), Box> { use std::sync::mpsc::RecvTimeoutError; - let queue = self.queue(); loop { + // A `shutdown` the startup scan answered has already been through + // `handle_shutdown`; there is nothing left to receive and nothing + // left to answer. + if self.stopped { + return Ok(()); + } + // Whatever a scan set aside is answered before anything newer is + // taken — the rescan those messages were queued behind has run, + // and they are older than everything still on the queue. Handling + // them here rather than at the end of the scan is what keeps this + // a loop instead of a scan inside a scan inside a scan. + if !self.held.is_empty() { + let batch = std::mem::take(&mut self.held); + if self.process_batch(batch)? { + return Ok(()); + } + continue; + } let message = if self.dirty.is_empty() { - match queue.recv() { + match self.queue.recv() { Ok(message) => message, Err(_) => return Ok(()), } } else { - match queue.recv_timeout(CHANGE_DEBOUNCE) { + match self.queue.recv_timeout(CHANGE_DEBOUNCE) { Ok(message) => message, Err(RecvTimeoutError::Timeout) => { self.flush_dirty(); @@ -307,46 +412,13 @@ impl Server { Err(RecvTimeoutError::Disconnected) => return Ok(()), } }; - if self.process_batch(burst(&queue, message))? { + let batch = burst(&self.queue, message); + if self.process_batch(batch)? { return Ok(()); } } } - /// Move the incoming messages onto a queue of our own, and report it. - /// - /// Necessary because `lsp-server`'s transport hands messages over - /// *rendezvous* channels — `bounded(0)`. Its reader thread parks holding - /// one message until this loop takes it, so a client's backlog never sits - /// on `connection.receiver` at all: it sits in the OS pipe, invisible and - /// one message deep. Forwarding onto an unbounded queue is what makes - /// "everything already sent" observable without blocking, which is the - /// whole premise of the burst below. - /// - /// The forwarder stops at `shutdown` and never reads past it, because - /// `handle_shutdown` reads the `exit` notification off the *connection* - /// itself — a forwarder that kept going would steal it and strand the - /// handshake for thirty seconds. It owns nothing but messages in flight - /// and touches no server state — and it never parses, which is why it is - /// the one thread the server spawns without - /// `vlog_parser::PARSE_STACK_SIZE` (`docs/features/recursion-limit`). - fn queue(&self) -> std::sync::mpsc::Receiver { - let (sender, receiver) = std::sync::mpsc::channel(); - let source = self.connection.receiver.clone(); - // A failed spawn would leave the server unable to receive anything at - // all; there is nothing useful to do with that but let `run` end when - // the queue's sender is dropped. - let _ = std::thread::Builder::new().name("lucisv-queue".to_string()).spawn(move || { - while let Ok(message) = source.recv() { - let last = is_shutdown(&message); - if sender.send(message).is_err() || last { - break; - } - } - }); - receiver - } - /// Handle one burst in arrival order, reporting whether the client shut us /// down. /// @@ -359,7 +431,34 @@ impl Server { /// of shutting down. fn process_batch(&mut self, batch: Vec) -> Result> { let mut cancelled = cancelled_in(&batch); - for message in batch { + // Where this burst's own held messages have to be spliced in. A scan + // this burst starts can hold messages of its *own* — ones that arrived + // while it ran, and therefore after everything still in this burst — + // so what is held from here goes in front of those and behind whatever + // was already waiting when the burst began. + let already_waiting = self.held.len(); + // The `$/cancelRequest`s this burst has already carried, kept only + // long enough to put them back if a request behind them has to wait. + let mut consumed_cancels: Vec = Vec::new(); + let mut messages = batch.into_iter(); + while let Some(message) = messages.next() { + // A request that must wait takes everything behind it with it, or + // the burst's arrival order would not survive the wait — + // `shutdown` included, because a request sent before a shutdown + // is a request the client is still owed an answer to. + if self.must_wait() && matches!(message, Message::Request(_)) { + // The cancels this burst carried were consumed on the way + // here, and `cancelled_in` runs again over the held batch — so + // they go back in front of what they cancel rather than being + // lost. A cancel naming nothing in the held batch is dropped + // there exactly as it was dropped here. + let mut rest: Vec = std::mem::take(&mut consumed_cancels); + rest.push(message); + rest.extend(messages); + rest.extend(self.held.split_off(already_waiting)); + self.held.extend(rest); + return Ok(false); + } match message { Message::Request(request) => { if self.connection.handle_shutdown(&request)? { @@ -376,8 +475,11 @@ impl Server { } // The cancels themselves are consumed here — `notification` // has nothing to do with one, and everything it could do has - // already been done above. - Message::Notification(notification) if notification.method == Cancel::METHOD => {} + // already been done above. Kept only so that a request behind + // one that has to wait takes its cancel with it. + Message::Notification(notification) if notification.method == Cancel::METHOD => { + consumed_cancels.push(Message::Notification(notification)); + } Message::Notification(notification) => self.notification(notification), Message::Response(response) => self.response(response), } @@ -385,6 +487,36 @@ impl Server { Ok(false) } + /// Whether a request reaching the dispatch right now must wait instead of + /// being answered. + /// + /// **This is the order contract, and it is the one thing interleaving a + /// scan with the message loop must not cost.** The loop has always + /// promised that everything queued *ahead* of a request is applied before + /// that request is answered — a `didChange` before a completion, and + /// equally a `didOpen` that widened the scope, a `didSave`, a changed + /// setting or an added workspace folder before a go-to-definition. Those + /// four ask for a rescan, and "applied" for them means the rescan has + /// **run**: one message at a time, the server would have finished it + /// before ever taking the request. Three clauses, one rule: + /// + /// * `answering_a_rescan` — this scan is one a message asked for, so + /// every request that arrives while it runs arrived *after* that + /// message and is owed its effect; + /// * `rescan_wanted` — a message in this very burst has just asked for + /// one, and the requests behind it in the burst are owed the same; + /// * `held` — a request is already waiting, and answering a newer one + /// ahead of it would reorder them just as badly. + /// + /// What is left answered mid-scan is exactly what is queued behind + /// *nothing*: the opening burst of a session, whose scan is the server's + /// own startup and not something a message asked for. That is the case + /// the round is about, and it is the one a user feels + /// (`docs/features/scan-interleave/README.md`). + fn must_wait(&self) -> bool { + self.answering_a_rescan || self.rescan_wanted || !self.held.is_empty() + } + // ------------------------------------------------------------------ // requests // ------------------------------------------------------------------ @@ -1616,6 +1748,17 @@ impl Server { /// scope was not re-resolved: nothing about which files exist changed, so /// repeating a filelist's complaints would be repeating stale news. fn reindex_one(&mut self, path: &Path) -> bool { + // Mid-scan the cheap path is not available and is not needed: the scan + // holds the text this file had when it started and will index *that*, + // so patching the half-built index here would be overwritten by older + // bytes a moment later. One more scan when this one ends is the whole + // answer, and it is the same flag every other mid-scan trigger sets. + // `true` because the caller's fallback — a whole rebuild, right now — + // is exactly what must not happen. + if self.scanning { + self.rescan_wanted = true; + return true; + } if !self.workspace.update_one(path) { return false; } @@ -1632,15 +1775,16 @@ impl Server { /// new `lucisv.exclude`/`lucisv.filelist`, a watched file changing on disk, /// or a file the client renamed or deleted. fn reindex(&mut self) { - let bar = self.begin_indexing(); - // Split apart for the same reason `Server::new` splits them: the - // watcher writes to the connection throughout a rebuild that holds the - // workspace mutably. - let Server { connection, workspace, .. } = self; - let mut watch = IndexWatch::new(connection, bar.as_ref(), workspace.client_settings()); - let warnings = workspace.rebuild_index_with(&mut |event| watch.see(event)); - let (skipped, cached) = (watch.skipped, watch.cached); - self.end_indexing(bar, skipped, cached); + // A rescan asked for by a message this scan answered is *this* scan's + // successor, not a scan inside it. See `scan_until_settled`. + if self.scanning { + self.rescan_wanted = true; + return; + } + let warnings = self.scan_until_settled(true); + if self.stopped { + return; + } // A rescan can change any module's instantiation count, so every lens // a client is holding may now read wrong. Sent after the bar comes // down, for the same reason the bar comes down before the republishes: @@ -1656,6 +1800,115 @@ impl Server { } } + /// Scan, and go on scanning while the messages answered along the way keep + /// asking for one. Reports the last scan's scope warnings. + /// + /// **The whole of the coalescing rule, and it is a loop rather than a + /// recursion on purpose.** A `didSave`, a widened scope, a changed + /// setting or a watched-file burst answered mid-scan sets + /// `rescan_wanted`; any number of them is one more scan. Finishing the + /// current scan and then running another was chosen over aborting and + /// restarting it because it needs no way to unwind a half-published index + /// and cannot loop for ever on its own — the follow-up scan reads the + /// persistent cache for every file the abandoned one already parsed, so + /// it is the cheap kind. Each scan gets its own progress token, which is + /// what a client showing a bar expects of two scans. + fn scan_until_settled(&mut self, mut asked_for: bool) -> Vec { + self.scanning = true; + let warnings = loop { + self.answering_a_rescan = asked_for; + let warnings = self.scan_once(); + if !std::mem::take(&mut self.rescan_wanted) || self.stopped { + break warnings; + } + // Every scan after the first one here is one a message asked for, + // whatever the first one was. + asked_for = true; + }; + self.answering_a_rescan = false; + self.scanning = false; + warnings + } + + /// One whole scan: the bar up, every file indexed with the client's + /// messages answered between two of them, the bar down. + /// + /// A scan a `shutdown` interrupted stops where it stands and reports no + /// warnings: nothing after this may speak to a client that has gone. The + /// records of the files it did index are already in the persistent store — + /// they are written through per file — so the next session resumes from + /// them, exactly as it does after any other half-done scan. + fn scan_once(&mut self) -> Vec { + let bar = self.begin_indexing(); + let mut scan = self.watching(bar.as_ref(), |workspace, watch| workspace.begin_scan(watch)); + let interleave = scan.total() > INTERLEAVE_ABOVE; + while self.watching(bar.as_ref(), |workspace, watch| workspace.scan_step(&mut scan, watch)) + { + if interleave && self.answer_what_is_waiting(&mut scan) { + return Vec::new(); + } + } + let (skipped, cached) = (scan.skipped(), scan.cached()); + let warnings = self.workspace.finish_scan(scan); + self.end_indexing(bar, skipped, cached); + warnings + } + + /// Do one piece of a scan with the progress bar and the per-file log + /// watching it. + /// + /// The fields are split apart because the watcher writes to the connection + /// while the workspace is borrowed mutably for the work it is watching — + /// the split `Server::new` used to make inline, made once here because a + /// scan is now several calls instead of one. A fresh `IndexWatch` per call + /// costs nothing and re-reads `lucisv.index.logFiles`, so a settings change + /// answered mid-scan is honoured by the very next file's log line. + fn watching( + &mut self, + bar: Option<&ProgressToken>, + step: impl FnOnce(&mut Workspace, &mut dyn FnMut(IndexEvent)) -> T, + ) -> T { + let Server { connection, workspace, .. } = self; + let mut watch = IndexWatch::new(connection, bar, workspace.client_settings()); + step(workspace, &mut |event| watch.see(event)) + } + + /// Answer everything the client has already sent, against the index as far + /// as this scan has built it. Reports whether the client shut us down. + /// + /// **This is the round's whole point, and its whole cost.** Polling costs + /// one `try_recv` per file and finds nothing in a scan nobody is waiting + /// on, so a quiet scan pays nothing at all; a scan somebody *is* waiting + /// on pays one merge per burst to make the records it has taken since the + /// last one answerable ([`Workspace::publish_scan`]). The messages then go + /// through the same `process_batch` the loop uses, so a `didChange` queued + /// ahead of a hover is applied before that hover is answered and a cancel + /// beside its request still answers it `RequestCancelled` — the order + /// contract is the loop's, unchanged, because it is the loop's code. + /// + /// An error here is a client that has gone: there is nobody to report it + /// to and no reason to go on scanning, so it stops the scan the same way a + /// `shutdown` does. + fn answer_what_is_waiting(&mut self, scan: &mut Scan) -> bool { + let mut batch = Vec::new(); + while let Ok(message) = self.queue.try_recv() { + batch.push(message); + } + if batch.is_empty() { + return false; + } + let opened = opened_in(&batch); + self.workspace.publish_scan(scan); + self.stopped = !matches!(self.process_batch(batch), Ok(false)); + // The file the user has just opened is the one they are looking at, so + // it is indexed next rather than when the alphabet reaches it — the + // open-first rule, for a file opened after the work list was taken. + for path in opened { + scan.index_next(&path); + } + self.stopped + } + /// Put a progress bar up for the rescan that is about to run, and report /// the token it must be taken down with. `None` for a client that cannot /// show one — the spec forbids creating progress it never asked for. @@ -1727,9 +1980,11 @@ impl Server { /// /// Silent for a client that did not advertise /// `workspace.codeLens.refreshSupport` — the request is server-initiated - /// and the spec makes that capability the gate. Nothing is sent at startup - /// either: no buffer is open there, so there are no lenses to invalidate. - /// The answer is ignorable and rides `response`'s fall-through path. + /// and the spec makes that capability the gate. Since scan-interleave, the + /// startup scan can send it too: a `didOpen` answered mid-scan leaves a + /// buffer whose lenses were computed against the half-built index, and + /// `started` refreshes them once the bar comes down. The answer is + /// ignorable and rides `response`'s fall-through path. fn refresh_code_lenses(&mut self) { if !self.abilities.code_lens_refresh { return; @@ -1916,14 +2171,6 @@ struct IndexWatch<'a> { bar: Option<&'a ProgressToken>, /// `lucisv.index.logFiles`: whether the per-file lines are sent at all. log_files: bool, - /// How many files the size cap kept out of this rebuild. Counted whether - /// or not the log is on, because the end message names it either way. - skipped: usize, - /// How many files came out of the persistent cache instead of being - /// parsed. Counted for the same reason and named in the same message: it - /// is the difference between "this scan was fast" and "this scan was fast - /// **because** it did not have to redo last session's work". - cached: usize, } impl<'a> IndexWatch<'a> { @@ -1932,7 +2179,7 @@ impl<'a> IndexWatch<'a> { bar: Option<&'a ProgressToken>, settings: &ClientSettings, ) -> IndexWatch<'a> { - IndexWatch { connection, bar, log_files: settings.log_files, skipped: 0, cached: 0 } + IndexWatch { connection, bar, log_files: settings.log_files } } /// Report one thing the rebuild just did. @@ -1946,7 +2193,6 @@ impl<'a> IndexWatch<'a> { // tick: a cached file is a file of the work list, and the bar // flying through them is exactly what the cache bought. IndexEvent::Cached { done, total, path } => { - self.cached += 1; self.say(format!("cached: {}", path.display())); self.tick(done, total, path); } @@ -1961,7 +2207,6 @@ impl<'a> IndexWatch<'a> { self.tick(done, total, path); } IndexEvent::Skipped { path, size, cap } => { - self.skipped += 1; self.say(format!( "skipped ({} > {} cap): {}", human_size(size), @@ -2080,6 +2325,43 @@ fn is_shutdown(message: &Message) -> bool { matches!(message, Message::Request(request) if request.method == Shutdown::METHOD) } +/// Move the incoming messages onto a queue of our own, and report it. +/// +/// Necessary because `lsp-server`'s transport hands messages over +/// *rendezvous* channels — `bounded(0)`. Its reader thread parks holding one +/// message until this loop takes it, so a client's backlog never sits on +/// `connection.receiver` at all: it sits in the OS pipe, invisible and one +/// message deep. Forwarding onto an unbounded queue is what makes "everything +/// already sent" observable without blocking, which is the whole premise of +/// [`burst`] — and of the drain a scan does between two of its files. +/// +/// The forwarder stops at `shutdown` and never reads past it, because +/// `handle_shutdown` reads the `exit` notification off the *connection* +/// itself — a forwarder that kept going would steal it and strand the +/// handshake for thirty seconds. It owns nothing but messages in flight and +/// touches no server state — and it never parses, which is why it is the one +/// thread the server spawns without `vlog_parser::PARSE_STACK_SIZE` +/// (`docs/features/recursion-limit`). +fn forward( + connection: &Connection, +) -> (std::sync::mpsc::Sender, std::sync::mpsc::Receiver) { + let (sender, receiver) = std::sync::mpsc::channel(); + let source = connection.receiver.clone(); + let ours = sender.clone(); + // A failed spawn would leave the server unable to receive anything at + // all; there is nothing useful to do with that but let `run` end when the + // queue's sender is dropped. + let _ = std::thread::Builder::new().name("lucisv-queue".to_string()).spawn(move || { + while let Ok(message) = source.recv() { + let last = is_shutdown(&message); + if sender.send(message).is_err() || last { + break; + } + } + }); + (ours, receiver) +} + /// `first` plus everything already waiting on the queue behind it — the /// client's backlog, in arrival order. Never blocks: what is not there yet /// belongs to the next burst. @@ -2109,6 +2391,26 @@ fn cancelled_in(batch: &[Message]) -> HashSet { batch.iter().filter_map(cancelled_id).filter(|id| queued.contains(id)).collect() } +/// The files a burst opened, in the order the client opened them. +/// +/// Read off the raw messages rather than off the workspace afterwards, +/// because the workspace holds its buffers in a `HashMap` and "which file did +/// the user just open" is a question about order. +fn opened_in(batch: &[Message]) -> Vec { + batch + .iter() + .filter_map(|message| match message { + Message::Notification(notification) + if notification.method == DidOpenTextDocument::METHOD => + { + document_uri(¬ification.params) + } + _ => None, + }) + .filter_map(|uri| crate::uri::uri_to_path(&uri)) + .collect() +} + /// The request id a `$/cancelRequest` names, or `None` for any other message. /// Both id forms the protocol allows are read; a cancel whose params do not /// parse is dropped, because there is no id to act on. @@ -2333,7 +2635,35 @@ mod tests { storage: Option, ) -> Session { let (server_end, client) = Connection::memory(); - let server = Server::started(server_end, roots, abilities, settings, storage); + let server = + Server::started(server_end, roots, abilities, settings, storage, Vec::new()); + Session { server, client } + } + + /// [`Session::started`] against a client that had **already sent** + /// `queued` when the server was built. + /// + /// The opening burst of a real editor: `initialized` is answered by + /// `initialize_finish`, and everything the client sent behind it is + /// sitting on the transport before the startup scan takes its first + /// file. That is the case + /// `docs/features/scan-interleave/README.md` is about, and the only + /// way to reach it is to put the messages there first. + fn started_behind( + roots: Vec, + abilities: ClientAbilities, + settings: ClientSettings, + on_the_wire: Vec, + queued: Vec, + ) -> Session { + let (server_end, client) = Connection::memory(); + // Anything that has to reach the *connection* rather than the + // queue — an `exit`, which `handle_shutdown` reads for itself — + // goes here, ahead of the forwarder ever starting. + for message in on_the_wire { + client.sender.send(message).expect("the client's wire traffic"); + } + let server = Server::started(server_end, roots, abilities, settings, None, queued); Session { server, client } } @@ -2567,6 +2897,405 @@ mod tests { ClientAbilities { work_done_progress: true, ..Default::default() } } + // ------------------------------------------------------------------ + // a scan that answers messages while it runs + // ------------------------------------------------------------------ + + /// A tree of `files` one-package files, plus one that names the last of + /// them — enough files that a scan over it interleaves. + fn workspace_of(tag: &str, files: usize) -> Tree { + let tree = Tree::new(tag); + for n in 0..files { + tree.package(&format!("p{n:03}.sv"), &format!("p{n:03}")); + } + tree + } + + /// A `workspace/symbol` request over the wire, by id. + fn symbol_request(id: i32, query: &str) -> Message { + Message::Request(Request::new( + RequestId::from(id), + WorkspaceSymbolRequest::METHOD.to_string(), + serde_json::json!({ "query": query }), + )) + } + + /// Where the indexing bar's `end` sits among everything the server said, + /// and where the response to `id` sits. `None` for either if it never + /// came. + fn positions(messages: &[Message], id: i32) -> (Option, Option) { + let ended = messages.iter().position(|message| { + matches!(message, Message::Notification(n) if n.method == Progress::METHOD + && n.params["value"]["kind"] == "end") + }); + let answered = messages.iter().position( + |message| matches!(message, Message::Response(r) if r.id == RequestId::from(id)), + ); + (ended, answered) + } + + #[test] + fn a_request_the_client_had_already_sent_is_answered_during_the_startup_scan() { + // The round's point, over the real dispatch: a request sitting on the + // transport when the server is built used to wait for the whole + // startup scan, because `Server::new` ran that scan before `run()` + // took its first message. It is now answered *inside* the scan — the + // response goes out before the bar comes down, which is the only + // ordering a test can check without a stopwatch. + let tree = workspace_of("interleaveanswer", INTERLEAVE_ABOVE + 6); + let session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![symbol_request(7, "p0")], + ); + let said = session.drain(); + let (ended, answered) = positions(&said, 7); + let answered = answered.expect("the request is answered at all"); + let ended = ended.expect("the bar comes down"); + assert!( + answered < ended, + "the answer must go out before the scan ends, not after it: {said:#?}" + ); + // And the index really did finish, so nothing was traded for the + // latency but the completeness of that one answer. + assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 6); + } + + #[test] + fn a_scan_short_enough_to_wait_for_answers_nothing_in_the_middle_of_itself() { + // The other side of `INTERLEAVE_ABOVE`. A handful of files is over in + // milliseconds, so a request that arrived with them is answered from + // the *finished* index — the complete answer, which is worth more than + // the few milliseconds an interleaved one would have saved. + let tree = workspace_of("interleaveshort", 4); + let session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![symbol_request(7, "p0")], + ); + // Nothing is answered during construction at all: the burst is still + // on the queue for `run` to take. + let said = session.drain(); + assert_eq!(positions(&said, 7).1, None, "{said:#?}"); + } + + #[test] + fn interleave_above_is_a_hard_boundary_at_the_file_count_not_before_or_after() { + // QA attack (`docs/features/scan-interleave/README.md`, settling + // attacks): the exact edge of `INTERLEAVE_ABOVE`. `scan_once` compares + // with `>`, not `>=`, so a scan of *exactly* the threshold must still + // run one-shot and one file more must interleave. Both sides in one + // test so a future off-by-one in that comparison shows up as a single + // failing assertion rather than two tests that each only prove half. + let at_threshold = workspace_of("interleaveboundaryat", INTERLEAVE_ABOVE); + let one_shot = Session::started_behind( + vec![at_threshold.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![symbol_request(7, "p0")], + ); + let said = one_shot.drain(); + assert_eq!( + positions(&said, 7).1, + None, + "exactly INTERLEAVE_ABOVE files must run one-shot: {said:#?}" + ); + + let above_threshold = workspace_of("interleaveboundaryabove", INTERLEAVE_ABOVE + 1); + let interleaved = Session::started_behind( + vec![above_threshold.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![symbol_request(7, "p0")], + ); + let said = interleaved.drain(); + let (ended, answered) = positions(&said, 7); + assert!( + answered.expect("answered mid-scan") < ended.expect("the bar comes down"), + "one file over INTERLEAVE_ABOVE must interleave: {said:#?}" + ); + } + + #[test] + fn a_request_queued_behind_a_rescan_waits_for_that_rescan() { + // The order contract, which interleaving must not cost: a message + // that asks for a rescan is *applied* — rescan run and all — before + // anything queued behind it is answered. Here the cap is pushed down + // to nothing, which empties the index, and the request behind it must + // see the empty one rather than the half-built one it was sent into. + let tree = workspace_of("interleaveorder", INTERLEAVE_ABOVE + 6); + let mut session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![ + Message::Notification(Notification::new( + DidChangeConfiguration::METHOD.to_string(), + capping(1), + )), + symbol_request(7, "p0"), + ], + ); + // The configuration was applied mid-scan and the rescan it asked for + // ran; the request behind it is still waiting, because it is owed that + // rescan's result. + assert!(session.server.held.len() == 1, "the request waits: {:?}", session.server.held); + assert_eq!(session.server.workspace.index().files().len(), 0, "the cap emptied the index"); + let said = session.drain(); + assert_eq!(positions(&said, 7).1, None, "not answered yet: {said:#?}"); + + // `run` answers it before it takes anything newer, and by then the + // rescan the client asked for has happened. + let held = std::mem::take(&mut session.server.held); + assert!(!session.batch(held), "the held burst is handled"); + let answered = session.answers(); + assert_eq!(answered.len(), 1, "{answered:#?}"); + assert_eq!( + answered[0].response_result.as_ref().ok().and_then(|v| v.as_array()).map(Vec::len), + Some(0), + "answered from the index the push asked for, not the one it was sent into" + ); + } + + #[test] + fn a_held_request_keeps_its_place_and_takes_its_cancel_with_it() { + // Two corners of holding, in one experiment. The burst carries a + // cancel for the request it also carries, and the scan the burst's + // settings push asks for holds a *newer* request of its own along the + // way. What comes out has to be: the burst's own request first (it + // arrived first), the newer one behind it, and the cancel still in + // front of what it cancels — a cancel dropped by the wait would turn + // into a computed answer the client has stopped listening for. + let tree = workspace_of("interleaveheldorder", INTERLEAVE_ABOVE + 6); + let mut session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![ + Message::Notification(Notification::new( + DidChangeConfiguration::METHOD.to_string(), + capping(1), + )), + Message::Notification(Notification::new( + Cancel::METHOD.to_string(), + serde_json::json!({ "id": 7 }), + )), + symbol_request(7, "p0"), + symbol_request(8, "p0"), + ], + ); + let held: Vec = session + .server + .held + .iter() + .map(|message| match message { + Message::Request(request) => format!("req {}", request.id), + Message::Notification(n) => format!("notif {}", n.method), + Message::Response(r) => format!("resp {}", r.id), + }) + .collect(); + assert_eq!(held, ["notif $/cancelRequest", "req 7", "req 8"], "{held:?}"); + + let batch = std::mem::take(&mut session.server.held); + assert!(!session.batch(batch), "the held burst is handled"); + let answered = session.answers(); + assert_eq!(answered.len(), 2, "{answered:#?}"); + assert_eq!(answered[0].id, RequestId::from(7)); + assert!( + answered[0] + .response_result + .as_ref() + .is_err_and(|e| e.code == lsp_server::ErrorCode::RequestCanceled as i32), + "the cancel survived the wait: {:#?}", + answered[0] + ); + assert_eq!(answered[1].id, RequestId::from(8), "and the newer one is behind it"); + assert!( + answered[1].response_result.is_ok(), + "which is answered normally: {:#?}", + answered[1] + ); + } + + #[test] + fn a_rescan_asked_for_mid_scan_is_coalesced_into_exactly_one_more_scan() { + // Three settings pushes land inside one startup scan, each of which + // would rebuild the index on its own. They cost one more scan between + // them, not three, and no scan runs inside another: two bars, two + // tokens, in order. + let tree = workspace_of("interleavecoalesce", INTERLEAVE_ABOVE + 6); + let cap = |bytes: u64| { + Message::Notification(Notification::new( + DidChangeConfiguration::METHOD.to_string(), + capping(bytes), + )) + }; + let session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![cap(1), cap(2), cap(3)], + ); + assert!(!session.server.scanning, "no scan is left running"); + assert!(!session.server.rescan_wanted, "and none is left owed"); + let bars: Vec<(&str, String)> = session + .drain() + .into_iter() + .filter_map(progress_step) + .filter(|(step, _)| *step != "report") + .collect(); + assert_eq!( + bars, + vec![ + ("create", "lucisv-index-0".to_string()), + ("begin", "lucisv-index-0".to_string()), + ("end", "lucisv-index-0".to_string()), + ("create", "lucisv-index-1".to_string()), + ("begin", "lucisv-index-1".to_string()), + ("end", "lucisv-index-1".to_string()), + ], + "one startup scan and exactly one coalesced rescan behind it" + ); + } + + #[test] + fn a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands() { + // A scan is interruptible now that it takes messages, and `shutdown` + // is what interrupts it: the bar never comes down, nothing is + // published after it, and `run` returns without taking another + // message. What the scan had already parsed is in the persistent + // store — it is written through per file — so the next session + // resumes from it exactly as it does after any other half-done scan. + let tree = workspace_of("interleaveshutdown", INTERLEAVE_ABOVE + 6); + let shutdown = || { + Message::Request(Request::new( + RequestId::from(9), + Shutdown::METHOD.to_string(), + Value::Null, + )) + }; + let mut session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + // On the connection as well as on the queue, and in this order: + // the queued copy is what the scan's first drain is *certain* to + // see, and the copy the forwarder carries is what stops it reading + // — so the `exit` behind it is still there for `handle_shutdown`, + // which reads the connection itself. Whichever of the two the + // handshake ends up consuming, the scan stops here. + vec![shutdown(), Message::Notification(Notification::new("exit".into(), Value::Null))], + vec![shutdown()], + ); + assert!(session.server.stopped, "the scan saw the shutdown"); + assert_eq!(session.ended(), Vec::>::new(), "the bar never came down"); + assert!( + session.server.workspace.index().files().len() < INTERLEAVE_ABOVE + 6, + "the scan stopped where it stood rather than running to the end" + ); + session.server.run().expect("run returns at once"); + } + + #[test] + fn a_buffer_opened_during_the_startup_scan_is_published_and_lenses_refreshed_once() { + // QA attack (`docs/features/scan-interleave/README.md`, + // progress/log-continuity): before this round no buffer could be + // *open* while `Server::new` was still running, so `Server::started` + // never had to pay the one-time republish-and-refresh `reindex` has + // always owed at the end of a rescan. A `didOpen` answered mid-scan + // now creates exactly that buffer, and the work log says + // `Server::started` pays the debt at the end of construction. + // + // Two publishes for the opened file are both correct, not a + // duplicate: `didOpen`'s own handler has always published against + // whatever index exists the moment a file opens (unrelated to this + // round), which here is the half-built one — so the debt payment + // after the bar comes down is what gives the client a diagnostics set + // computed against the *finished* index, and it must come after the + // `end` event, not folded into the mid-scan one. + let tree = workspace_of("interleaveopenedpublish", INTERLEAVE_ABOVE + 6); + let target = tree.path.join("p000.sv"); + let opened = Message::Notification(Notification::new( + DidOpenTextDocument::METHOD.to_string(), + serde_json::json!({ + "textDocument": { + "uri": path_to_uri(&target).expect("uri"), + "languageId": "systemverilog", + "version": 1, + "text": "package p000;\nendpackage\n", + } + }), + )); + let abilities = ClientAbilities { + work_done_progress: true, + code_lens_refresh: true, + ..Default::default() + }; + let session = Session::started_behind( + vec![tree.path.clone()], + abilities, + wide_ish(), + Vec::new(), + vec![opened], + ); + let said = session.drain(); + let target_uri = path_to_uri(&target).expect("uri"); + let ended = said + .iter() + .position(|m| { + matches!(m, Message::Notification(n) if n.method == Progress::METHOD + && n.params["value"]["kind"] == "end") + }) + .expect("the bar comes down"); + let publish_positions: Vec = said + .iter() + .enumerate() + .filter_map(|(i, m)| match m { + Message::Notification(n) + if n.method == PublishDiagnostics::METHOD + && serde_json::from_value::(n.params.clone()) + .is_ok_and(|p| p.uri == target_uri) => + { + Some(i) + } + _ => None, + }) + .collect(); + assert_eq!( + publish_positions.len(), + 2, + "one publish from didOpen's own handler, one from the debt Server::started pays: \ + {said:#?}" + ); + assert!( + publish_positions[0] < ended, + "the first publish is didOpen's own, against the half-built index: {said:#?}" + ); + assert!( + publish_positions[1] > ended, + "the second is the debt payment, against the finished index: {said:#?}" + ); + let refreshes = said + .iter() + .filter(|m| matches!(m, Message::Request(r) if r.method == CodeLensRefresh::METHOD)) + .count(); + assert_eq!(refreshes, 1, "exactly one lens refresh, not one per drain: {said:#?}"); + } + + /// Settings a test uses when its subject is not the scope, spelled once. + fn wide_ish() -> ClientSettings { + ClientSettings { index_scope: crate::settings::IndexScope::Workspace, ..Default::default() } + } + #[test] fn the_startup_index_build_runs_under_the_first_bar() { // It is the slowest rescan of the session, and it happens after @@ -5985,8 +6714,28 @@ mod tests { // the server down leaks a process. `handle_shutdown` runs before the // cancelled set is consulted, so the cancel never gets a say. let (_tree, mut session, _uri) = cancelling_session("cancelshutdown", ONE_MODULE); - // `handle_shutdown` waits for the `exit` that follows; queue it the - // way a real client's would already be queued. + // `handle_shutdown` waits for the `exit` that follows, and reads it off + // the *connection* — so the forwarder has to have stopped first, or it + // takes the `exit` and the handshake finds nothing. It stops at the + // first `shutdown` it forwards, so one is sent through it and waited + // for: once that message is off the queue the forwarder has already + // broken out of its loop and will never read the connection again. + // (Before 2026-08-28 the forwarder did not exist until `run`, which + // this test never calls, so the `exit` simply sat there.) + session + .client + .sender + .send(Message::Request(Request::new( + RequestId::from(99), + Shutdown::METHOD.to_string(), + Value::Null, + ))) + .expect("queue a shutdown for the forwarder to stop at"); + session + .server + .queue + .recv_timeout(std::time::Duration::from_secs(5)) + .expect("the forwarder stops at it"); session .client .sender @@ -6145,7 +6894,10 @@ mod tests { .send(Message::Notification(Notification::new("exit".to_string(), Value::Null))) .expect("queue exit"); - let queue = session.server.queue(); + // The server's own queue — the one the forwarder started at + // construction is filling — rather than a second one: two forwarders + // over one connection would each take half the messages. + let queue = &session.server.queue; let forwarded = queue.recv_timeout(std::time::Duration::from_secs(1)).expect("shutdown is forwarded"); assert!(matches!(&forwarded, Message::Request(request) if request.id == shutdown_id)); diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index c2be32d..b5dcd21 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -15,8 +15,8 @@ use vlog_parser::defines::{collect_defines, DefineTable}; use vlog_parser::token::Token; use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic}; use vlog_semantic::{ - analyze, index_order, resolve_external, ExternalResolutions, FileFacts, IndexBuilder, - Semantics, WorkspaceIndex, + analyze, index_order, resolve_external, ExternalResolutions, FileFacts, Semantics, + WorkspaceIndex, }; use lucisv_core::config::Discovery; @@ -291,6 +291,91 @@ enum HeldAnalyses { Unused, } +/// One workspace scan in flight: the work list it took when it began, and how +/// far through it the workspace has got. +/// +/// A value rather than a loop inside [`Workspace::rebuild_index_with`] because +/// the server answers the client's messages *between* two files of a scan +/// (`docs/features/scan-interleave/README.md`), and a message it answers needs +/// the very workspace the scan is feeding — which a callback called from +/// inside a `&mut self` loop can never be handed. Splitting the loop is what +/// puts the scan's state somewhere the message can be answered around. +pub struct Scan { + /// Every in-scope file and the text it had when the scan began, in index + /// order with the open buffers' own files first. + work: Vec<(PathBuf, String)>, + /// The paths of `work`, kept flat so the include graph's known-file table + /// can be relearned from a slice. Which files *exist* is settled the + /// moment the scope is resolved, so this never moves while the scan runs — + /// reordering the tail of `work` does not reorder a set. + paths: Vec, + /// What the open buffers among `work` already knew about themselves, taken + /// from as each of them is reached. + analyzed: Analyzed, + incdirs: Vec, + warnings: Vec, + /// How many of `work` have been indexed. + at: usize, + /// The records taken since the last publish, and which files of `work` + /// they came from. Staged rather than merged because a merge is a pass + /// over the whole index — see [`vlog_semantic::WorkspaceIndex::absorb`]. + staged: Vec, + staged_at: Vec, + /// The completion words of every file taken so far, which the tables built + /// when the scan ends are assembled from. + words: HashMap>, + /// How many files the size cap kept out, and how many came from the + /// persistent cache instead of a parse. Facts about this scan, so they + /// live on it — the end message names both. + skipped: usize, + cached: usize, +} + +impl Scan { + /// How many files the size cap kept out of this scan. + pub fn skipped(&self) -> usize { + self.skipped + } + + /// How many files came from the persistent cache instead of being parsed. + pub fn cached(&self) -> usize { + self.cached + } + + /// How many files this scan will index — known before the first parse, + /// which is what lets the caller decide whether the scan is long enough to + /// be worth answering messages in the middle of. + pub fn total(&self) -> usize { + self.work.len() + } + + /// Move `path` to the front of what is left to index, if it is still + /// waiting there. Reports whether it moved. + /// + /// The open-first rule, applied to a file opened *after* the work list was + /// taken: a `didOpen` answered mid-scan puts that file next rather than + /// leaving the user waiting for the alphabet to reach it. Reordering the + /// tail cannot change the finished index — records are merged in path + /// order whatever order they were taken in + /// ([`vlog_semantic::IndexBuilder`]) — so this is a latency decision and + /// nothing more. + pub fn index_next(&mut self, path: &Path) -> bool { + let at = self.at; + let Some(offset) = self.work[at.min(self.work.len())..] + .iter() + .position(|(held, _)| held == path) + .filter(|offset| *offset > 0) + else { + return false; + }; + // The file steps back to the front of what is left and everything it + // passed steps one place later; nothing is dropped and nothing is + // indexed twice. + self.work[at..=at + offset].rotate_right(1); + true + } +} + /// What an index rebuild reports about itself as it runs. /// /// This module speaks no protocol, so an event carries numbers and paths and @@ -436,17 +521,29 @@ impl Workspace { self.open_roots_with(roots, watch) } - /// [`Workspace::open_roots`], watched — the startup build reports itself - /// exactly as every later rescan does. + /// [`Workspace::open_roots`], watched — the unwatched form's sibling, and + /// test-only for the same reason: the server drives the scan itself now, + /// one file at a time, so it adopts the roots and steps the scan rather + /// than calling this. + #[cfg(test)] pub fn open_roots_with( &mut self, roots: Vec, watch: &mut dyn FnMut(IndexEvent), ) -> Vec { - self.roots = roots; + self.adopt_roots(roots); self.rebuild_index_with(watch) } + /// Take the workspace roots without indexing anything. + /// + /// The half of [`Workspace::open_roots_with`] that is not a scan, for the + /// caller that drives the scan itself — the server, which runs the startup + /// scan through the same interleaved path every later rescan takes. + pub fn adopt_roots(&mut self, roots: Vec) { + self.roots = roots; + } + /// Add and remove workspace roots mid-session, reporting whether the set /// actually moved — which is whether the caller owes a rebuild. /// @@ -730,72 +827,206 @@ impl Workspace { /// include graph are built from the same list afterwards and are not /// reported: they cost a small fraction of the parse, and a bar that went /// to 100% and then sat there would be worse than one that ends. + /// + /// A scan with nothing happening between its files, which is what every + /// caller but the server's message loop wants. The loop drives the same + /// three calls itself and answers messages between two of them + /// (`docs/features/scan-interleave/README.md`) — so "one shot" and + /// "interleaved" are not two scans that have to be kept in step, they are + /// this loop with and without a drain in it. + /// + /// Test-only for that reason: the server takes the three calls, and this + /// is what every test that just wants an index calls instead. + #[cfg(test)] pub fn rebuild_index_with(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Vec { + let mut scan = self.begin_scan(watch); + while self.scan_step(&mut scan, watch) {} + self.finish_scan(scan) + } + + /// Take the work list one scan will run through: resolve the scope, read + /// every in-scope file, and put the open buffers' own files at the front. + /// + /// Nothing is indexed here and the live index is untouched, so a scan that + /// is never stepped changes nothing but the view cache and the open cache + /// handle. + pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Scan { // A rescan says nothing about *which* file moved, so nothing held from // before it can be trusted. self.views.borrow_mut().clear(); - let mut scope = self.collect_sources(watch, HeldAnalyses::Wanted); - let sources = std::mem::take(&mut scope.texts); - let mut analyzed = std::mem::take(&mut scope.analyzed); + let mut skipped = 0usize; + let mut scope = { + // The cap's skips are reported by `collect_sources` and counted + // here, because the end message names them and the scan is what + // owns that number now. + let mut counting = |event: IndexEvent<'_>| { + if matches!(event, IndexEvent::Skipped { .. }) { + skipped += 1; + } + watch(event); + }; + self.collect_sources(&mut counting, HeldAnalyses::Wanted) + }; + let texts = std::mem::take(&mut scope.texts); + let analyzed = std::mem::take(&mut scope.analyzed); // The same list the index will be built from — asked of // `vlog_semantic` rather than re-derived here, so the count reported // is the count parsed — with the user's own open files moved to the // front of it. - let ordered = - self.open_first(index_order(sources.iter().map(|(p, t)| (p.clone(), t.as_str())))); - let total = ordered.len(); + let work = self.open_first(index_order(texts)); + let paths: Vec = work.iter().map(|(path, _)| path.clone()).collect(); // Re-opened here rather than held across rescans: the directory it // belongs in depends on settings that arrive after startup, and a // second session over the same workspace may have written records // this one has not seen. self.cache = IndexCache::open(self.cache_dir()); - let mut builder = IndexBuilder::new(); - for (done, (path, text)) in ordered.into_iter().enumerate() { - // An open buffer's own finished analysis comes first. It describes - // the exact bytes about to be indexed — `collect_sources` took the - // record and the text from the same `Document` in the same loop — - // and it is the only source of facts that is right when the buffer - // has unsaved edits, which is precisely when the content-keyed - // cache below has nothing to offer. The record is written through - // all the same, so the next session starts from it. - if let Some(facts) = analyzed.facts.remove(&path) { + Scan { + work, + paths, + analyzed, + incdirs: scope.incdirs, + warnings: scope.warnings, + at: 0, + staged: Vec::new(), + staged_at: Vec::new(), + words: HashMap::new(), + skipped, + cached: 0, + } + } + + /// Index the next file of `scan`, reporting whether there was one. + /// + /// One file is the whole step: its record is taken — from the open + /// buffer's own analysis, from the persistent cache, or from a parse — and + /// its completion words are lexed. Both are *staged* on the scan rather + /// than merged, because merging is a pass over the whole workspace and one + /// per file would be quadratic ([`WorkspaceIndex::absorb`]). + pub fn scan_step(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool { + let (done, total) = (scan.at, scan.work.len()); + if done == total { + return false; + } + scan.at += 1; + let path = scan.work[done].0.clone(); + // Taken out of the scan before the text is borrowed off it, so the two + // borrows never overlap. Both describe the same bytes as that text: + // `collect_sources` read the record and the text off one `Document` in + // one loop. + let held = scan.analyzed.facts.remove(&path); + let known_words = scan.analyzed.words.remove(&path); + let text = scan.work[done].1.as_str(); + let facts = match held { + // An open buffer's own finished analysis comes first. It is the + // only source of facts that is right when the buffer has unsaved + // edits, which is precisely when the content-keyed cache below has + // nothing to offer. The record is written through all the same, so + // the next session starts from it. + Some(facts) => { watch(IndexEvent::Analyzed { done, total, path: &path }); self.cache.record(&facts, text); - builder.add_facts(facts); - continue; + facts } // The cache answers for the exact bytes about to be indexed, so a // hit is the parse and not a guess at it. A miss — a new file, a // changed one, a record this version cannot read — parses, and // the result is written through immediately, which is what makes // an interrupted scan resumable. - match self.cache.facts_for(&path, text) { + None => match self.cache.facts_for(&path, text) { Some(facts) => { + scan.cached += 1; watch(IndexEvent::Cached { done, total, path: &path }); - builder.add_facts(facts); + facts } None => { watch(IndexEvent::Parsing { done, total, path: &path }); - let facts = FileFacts::of(path, text); + let facts = FileFacts::of(path.clone(), text); self.cache.record(&facts, text); - builder.add_facts(facts); + facts } - } + }, + }; + // Lexed here rather than in one pass at the end, so that no part of a + // scan is longer than one file — an open buffer's words are the ones + // it was analyzed from and are not lexed a second time, exactly as + // `Candidates::build` has always taken them. + let words = known_words.unwrap_or_else(|| crate::candidates::words_in(text)); + scan.words.insert(path, words); + scan.staged.push(facts); + scan.staged_at.push(done); + true + } + + /// Make every table answer for the files `scan` has taken since the last + /// publish — the moment a mid-scan answer is worth paying a merge for. + /// + /// **All three tables together, never one of them.** The index, the + /// completion tables and the include graph are what an answer reads, and a + /// hover that saw a scanned file while a completion or an include link + /// could not would make "the workspace as far as it has been scanned" + /// three different things at once. Each is folded in with the batch form + /// of the incremental update it already had, so one publish is one pass + /// over the index and not one per file. + pub fn publish_scan(&mut self, scan: &mut Scan) { + if scan.staged.is_empty() { + return; } - self.index = builder.finish(); + let taken = std::mem::take(&mut scan.staged_at); + self.index.absorb(std::mem::take(&mut scan.staged), &[]); + let words = taken + .iter() + .map(|&at| { + let path = &scan.work[at].0; + (path.clone(), scan.words.get(path).cloned().unwrap_or_default()) + }) + .collect(); + self.candidates.absorb(&self.index, words); + let texts: Vec<(&Path, &str)> = + taken.iter().map(|&at| (scan.work[at].0.as_path(), scan.work[at].1.as_str())).collect(); + self.includes.absorb(&scan.incdirs, &scan.paths, &texts); + // Every open buffer resolves against the index, so a buffer whose + // cross-file names the scan has just reached must be able to see them. + for doc in self.docs.values_mut() { + doc.refresh_overlay(&self.index); + } + } + + /// Finish `scan`: the index, the completion tables, the include graph and + /// every open buffer's overlay. Reports the warnings from resolving the + /// scope. + /// + /// **What comes out is the index a one-shot scan over the same work list + /// would have produced**, however many times [`Workspace::publish_scan`] + /// ran in between: a publish only ever folds records in, and the index's + /// tables are a pure function of the records it holds + /// ([`WorkspaceIndex::absorb`]). + pub fn finish_scan(&mut self, scan: Scan) -> Vec { + let Scan { work, incdirs, warnings, staged, words, .. } = scan; + // Whatever the last scan left in the index that this one's work list + // does not name is a file that is no longer in scope. + let held: HashSet<&Path> = work.iter().map(|(path, _)| path.as_path()).collect(); + let gone: Vec = self + .index + .files() + .iter() + .filter(|path| !held.contains(path.as_path())) + .cloned() + .collect(); + self.index.absorb(staged, &gone); // The one moment the live set of entries is known, so the one moment // the append log is worth rewriting. self.cache.compact(); // Built here, from the same list, so a file the scope ladder excluded - // contributes no completion candidates either. - self.candidates = Candidates::build(&self.index, &sources, analyzed.words); + // contributes no completion candidates either. Every file's words are + // in `words` already, so nothing is lexed twice. + self.candidates = Candidates::build(&self.index, &work, words); // Same list again: an `` `include`` in a file the scope excluded is // not an edge, and a file it excluded is not a hop away from anything. - self.includes = IncludeGraph::build(&sources, scope.incdirs); + self.includes = IncludeGraph::build(&work, incdirs); for doc in self.docs.values_mut() { doc.refresh_overlay(&self.index); } - scope.warnings + warnings } /// Rebuild the index for **one** file, leaving every other file's @@ -931,7 +1162,7 @@ impl Workspace { /// changes nothing about the result. Pinned both ends: the builder's own /// `no_insertion_order_can_change_what_the_builder_produces`, and /// `the_open_files_are_indexed_first_and_the_index_cannot_tell` here. - fn open_first<'a>(&self, mut files: Vec<(PathBuf, &'a str)>) -> Vec<(PathBuf, &'a str)> { + fn open_first(&self, mut files: Vec<(PathBuf, T)>) -> Vec<(PathBuf, T)> { let open: Vec<&Path> = self.docs.values().filter_map(|doc| doc.path.as_deref()).collect(); files.sort_by_key(|(path, _)| !open.contains(&path.as_path())); files @@ -1692,6 +1923,227 @@ mod tests { ); } + // ------------------------------------------------------------------ + // an interleaved scan against the one-shot scan it must equal + // ------------------------------------------------------------------ + + /// Everything a scan produces, rendered as one comparable value: the + /// index's own witness, the completion tables and the include graph. + /// + /// The index's fingerprint alone would not do — this round publishes all + /// three tables together, so all three have to be shown to come out the + /// same however many publishes happened on the way. + fn everything(ws: &Workspace) -> String { + let mut out = ws.index().fingerprint(); + out.push_str(&format!("words {:?}\n", ws.candidates().words(""))); + out.push_str(&format!( + "units {:?}\n", + ws.candidates().units("").iter().map(|c| &c.name).collect::>() + )); + out.push_str(&format!( + "macros {:?}\n", + ws.candidates().macros("").iter().map(|m| &m.name).collect::>() + )); + let mut reachable: Vec = ws + .index() + .files() + .iter() + .map(|path| { + let mut hops: Vec = ws + .includes() + .reachable(vec![path.clone()]) + .iter() + .filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())) + .collect(); + hops.sort(); + format!("reaches {} {hops:?}", path.display()) + }) + .collect(); + reachable.sort(); + out.push_str(&reachable.join("\n")); + out + } + + /// Run a scan the way `server.rs` does, publishing after **every** file — + /// the worst case the interleaved path can produce, and the one a + /// one-shot scan has to agree with. + fn scan_publishing_every_file(ws: &mut Workspace) -> Vec { + let mut scan = ws.begin_scan(&mut |_| {}); + while ws.scan_step(&mut scan, &mut |_| {}) { + ws.publish_scan(&mut scan); + } + ws.finish_scan(scan) + } + + /// A tree of three files that declare each other's names and include each + /// other, so a half-published index has something to get wrong. + fn tangled(tag: &str) -> Tree { + let tree = Tree::new(tag); + tree.write("defs.svh", "`define WIDE 32\n"); + tree.write( + "a.sv", + "`include \"defs.svh\"\npackage a;\n localparam K = 1;\n \ + typedef logic [`WIDE-1:0] word_t;\nendpackage\n", + ); + tree.write( + "b.sv", + "`include \"defs.svh\"\nmodule b;\n import a::*;\n word_t w;\n \ + localparam K2 = a::K;\nendmodule\n", + ); + tree.write("c.sv", "module c;\n b inner ();\nendmodule\n"); + tree + } + + #[test] + fn publishing_between_every_file_leaves_what_a_one_shot_scan_leaves() { + // The round's central invariant. The interleaved scan and the one-shot + // scan are the same three calls with and without a drain between them, + // so this pins the thing a drain could break: that folding records in + // as they are taken lands the same index, the same completion tables + // and the same include graph as folding them all in at the end. + let tree = tangled("interleavesame"); + let mut one_shot = Workspace::default(); + one_shot.open_whole_workspace(vec![tree.path.clone()]); + + let mut stepped = Workspace::default(); + stepped.client.index_scope = IndexScope::Workspace; + stepped.adopt_roots(vec![tree.path.clone()]); + scan_publishing_every_file(&mut stepped); + + assert_eq!(everything(&one_shot), everything(&stepped)); + assert!(one_shot.index().files().len() == 4, "premise: every file was scanned"); + } + + #[test] + fn a_rescan_that_publishes_as_it_goes_still_drops_what_left_the_scope() { + // A publish only ever folds records *in*, so the removal a rescan owes + // — files the last scan held that this one's work list does not name — + // has to survive every publish that happened before it. + let tree = tangled("interleavegone"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + assert!(!ws.index().units("c").is_empty(), "premise: c.sv is indexed"); + + std::fs::remove_file(tree.path.join("c.sv")).expect("remove"); + scan_publishing_every_file(&mut ws); + + let mut fresh = Workspace::default(); + fresh.open_whole_workspace(vec![tree.path.clone()]); + assert_eq!(everything(&fresh), everything(&ws)); + assert!(ws.index().units("c").is_empty(), "the file that left the scope is gone"); + assert_eq!(ws.index().files().len(), 3); + } + + #[test] + fn a_buffer_opened_or_changed_mid_scan_does_not_change_what_the_scan_indexes() { + // The scan holds the text every file had when its work list was taken, + // and indexes *that* — which is exactly what a `didOpen` or a + // `didChange` landing a moment after the scan finished would leave in + // the index too (neither touches it; a save is what does). So a + // message answered in the middle of a scan cannot move the scan's + // result, and the fingerprint is the witness. + let tree = tangled("interleavemidchange"); + let mut one_shot = Workspace::default(); + one_shot.open_whole_workspace(vec![tree.path.clone()]); + + let mut stepped = Workspace::default(); + stepped.client.index_scope = IndexScope::Workspace; + stepped.adopt_roots(vec![tree.path.clone()]); + let mut scan = stepped.begin_scan(&mut |_| {}); + assert!(stepped.scan_step(&mut scan, &mut |_| {}), "premise: there is a first file"); + stepped.publish_scan(&mut scan); + // The client opens `b.sv` and types in it, mid-scan. + let opened = uri(&format!("file://{}", tree.path.join("b.sv").display())); + stepped + .set_document(opened.clone(), "module b;\n localparam MID = 1;\nendmodule\n".into()); + while stepped.scan_step(&mut scan, &mut |_| {}) { + stepped.publish_scan(&mut scan); + } + stepped.finish_scan(scan); + + assert_eq!(everything(&one_shot), everything(&stepped)); + assert_eq!( + stepped.document(&opened).map(|doc| doc.text.as_str()), + Some("module b;\n localparam MID = 1;\nendmodule\n"), + "the buffer keeps the text it was given, index or no index" + ); + } + + #[test] + fn a_file_opened_mid_scan_is_indexed_next_and_the_index_cannot_tell() { + // The open-first rule for a file opened *after* the work list was + // taken. It moves to the front of what is left, everything it passed + // keeps its place behind it, and the finished index is byte-identical + // — records are merged in path order whatever order they arrived in. + let tree = tangled("interleaveopenfirst"); + let mut one_shot = Workspace::default(); + one_shot.open_whole_workspace(vec![tree.path.clone()]); + + let mut stepped = Workspace::default(); + stepped.client.index_scope = IndexScope::Workspace; + stepped.adopt_roots(vec![tree.path.clone()]); + let mut scan = stepped.begin_scan(&mut |_| {}); + assert!(stepped.scan_step(&mut scan, &mut |_| {}), "premise: a.sv goes first"); + assert!(stepped.index().units("c").is_empty(), "premise: c.sv is not indexed yet"); + + assert!(scan.index_next(&tree.path.join("c.sv")), "the newly opened file jumps the queue"); + assert!(!scan.index_next(&tree.path.join("c.sv")), "and does not jump twice"); + assert!(!scan.index_next(&tree.path.join("nothing.sv")), "a file not waiting cannot jump"); + assert!(stepped.scan_step(&mut scan, &mut |_| {})); + stepped.publish_scan(&mut scan); + assert!(!stepped.index().units("c").is_empty(), "c.sv was indexed next, not last"); + + while stepped.scan_step(&mut scan, &mut |_| {}) {} + stepped.finish_scan(scan); + assert_eq!(everything(&one_shot), everything(&stepped)); + } + + #[test] + fn a_scan_reports_the_same_events_in_the_same_order_however_it_is_driven() { + // The progress bar and the per-file log are the same two things a + // one-shot scan reports, in the same order, against the same total: + // interleaving adds drains between the events, never events. + let tree = tangled("interleaveevents"); + let mut one_shot = Workspace::default(); + one_shot.client.index_scope = IndexScope::Workspace; + one_shot.adopt_roots(vec![tree.path.clone()]); + let mut said = Vec::new(); + one_shot.rebuild_index_with(&mut |event| said.push(seen(&event))); + + let mut stepped = Workspace::default(); + stepped.client.index_scope = IndexScope::Workspace; + stepped.adopt_roots(vec![tree.path.clone()]); + let mut also = Vec::new(); + let mut scan = stepped.begin_scan(&mut |event| also.push(seen(&event))); + while stepped.scan_step(&mut scan, &mut |event| also.push(seen(&event))) { + stepped.publish_scan(&mut scan); + } + assert_eq!(scan.skipped(), 0); + assert_eq!(scan.cached(), 0); + stepped.finish_scan(scan); + + assert_eq!(said, also); + assert_eq!(said.len(), 4, "one event per file, and nothing else: {said:?}"); + } + + /// One [`IndexEvent`] as the word and the numbers a caller would report. + fn seen(event: &IndexEvent) -> String { + match event { + IndexEvent::Parsing { done, total, path } => { + format!("indexing {done}/{total} {}", path.display()) + } + IndexEvent::Cached { done, total, path } => { + format!("cached {done}/{total} {}", path.display()) + } + IndexEvent::Analyzed { done, total, path } => { + format!("analyzed {done}/{total} {}", path.display()) + } + IndexEvent::Skipped { path, size, cap } => { + format!("skipped {} {size} {cap}", path.display()) + } + } + } + #[test] fn a_root_added_mid_session_widens_the_scan_and_a_removed_one_narrows_it() { let first = Tree::new("rootsfirst"); diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index bda6e7b..e1331dc 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -4829,13 +4829,16 @@ fn a_keystroke_round_trip_over_the_wire() { /// `cargo test --release -p lucisv_server --test e2e a_hover_issued -- --ignored --nocapture --test-threads=1` #[test] #[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] -fn a_hover_issued_during_the_initial_scan_waits_for_it() { - // Suspect 2 of the hover-latency round, measured rather than argued: - // `Server::new` runs the whole startup scan *before* `run()`'s message - // loop takes its first message, so anything a client sends the moment it - // has sent `initialized` sits in the OS pipe until that scan is done. The - // number below is what a user feels when they hover the first thing they - // see after opening a folder. +fn a_hover_issued_during_the_initial_scan_is_answered_during_it() { + // The probe the hover-latency round left behind, now measuring the other + // side of the change it filed for. It used to read + // `..._waits_for_it`, because `Server::new` ran the whole startup scan + // *before* `run()`'s message loop took its first message and anything a + // client sent the moment it had sent `initialized` sat in the OS pipe + // until that scan was done: 780 ms cold / 287 ms warm over these 200 + // files. The scan now answers messages between its files + // (`docs/features/scan-interleave/README.md`), so what this prints is + // one file's step and not a whole scan. // // A `lucisv.toml` naming a filelist is what makes the startup scan index // the whole tree: it is the top rung of the scope ladder and the only one @@ -4872,8 +4875,10 @@ fn a_hover_issued_during_the_initial_scan_waits_for_it() { let mut took = Vec::new(); for session in 0..2 { let mut live = Live::start(); + // The progress capability is what makes "the scan is over" observable + // to the client, and therefore to the second measurement below. live.send(&format!( - r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}},"initializationOptions":{{"storagePath":"{}"}}}}}}"#, + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}},"initializationOptions":{{"storagePath":"{}"}}}}}}"#, dir.join("storage").display() )); live.wait_for(|m| m["id"] == 1); @@ -4887,18 +4892,22 @@ fn a_hover_issued_during_the_initial_scan_waits_for_it() { serde_json::to_string(top).expect("json") )); live.send(&hover(2)); - let first = live.wait_for(|m| m["id"] == 2); + live.wait_for(|m| m["id"] == 2); let queued_behind_the_scan = started.elapsed(); - assert!( - format!("{first:#?}").contains("m7.sv"), - "the hover must really answer across files: {first:#?}" - ); - // The same hover, with the scan long finished. + // The same hover, with the scan long finished — which is where the + // cross-file answer is required, because *that* one reads a finished + // index. The mid-scan one above reads the index as of the moment it + // was asked, and `m7.sv` sorts a long way down 200 paths. + live.wait_for(|m| m["params"]["value"]["kind"] == "end"); let started = std::time::Instant::now(); live.send(&hover(3)); - live.wait_for(|m| m["id"] == 3); + let done = live.wait_for(|m| m["id"] == 3); let after_the_scan = started.elapsed(); + assert!( + format!("{done:#?}").contains("m7.sv"), + "the hover must really answer across files once the scan is done: {done:#?}" + ); live.finish(); took.push((session, queued_behind_the_scan, after_the_scan)); diff --git a/crates/vlog_semantic/src/workspace.rs b/crates/vlog_semantic/src/workspace.rs index e121d2b..fb729c1 100644 --- a/crates/vlog_semantic/src/workspace.rs +++ b/crates/vlog_semantic/src/workspace.rs @@ -450,6 +450,52 @@ impl WorkspaceIndex { } } + /// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for + /// many files at once — and for **one** merge rather than one each. + /// + /// Same contract as both — what comes out is the index a full + /// [`WorkspaceIndex::build`] over the records it now holds would have + /// produced — **provided each path appears once in `records`**. It holds + /// for the same reason theirs does: the records are kept path-sorted and + /// one file to a path, and [`WorkspaceIndex::merge`] is then the same loop + /// [`IndexBuilder::finish`] runs over the same list. A batch that names + /// one path twice is an update applied twice, so the **last** record wins, + /// where a `build` over the same duplicated input keeps the *first* + /// (`index_order` dedups) — the update semantic is the right one for an + /// "absorb what changed" API, and the one caller that feeds a scan + /// (`Scan::work`) is deduped before anything is staged. QA pinned the + /// divergence + /// (`absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records`). + /// + /// One merge, because a merge is a pass over **every** record the index + /// holds: a scan that merged after each of its files would be quadratic in + /// the size of the workspace, which is measured rather than argued in + /// `docs/features/scan-interleave/README.md`. A caller feeding a scan + /// therefore batches — it stages records as it takes them and folds a + /// batch in only when something is about to read the index. + /// + /// `gone` is dropped first, so a path in both lists ends up held: a file + /// that moved out of one scan's scope and back into the next's is one + /// file, not a removal that happens to run second. + pub fn absorb(&mut self, records: Vec, gone: &[PathBuf]) { + for path in gone { + if let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) { + self.files.remove(at); + self.facts.remove(at); + } + } + for facts in records { + match self.facts.binary_search_by(|held| held.path.cmp(&facts.path)) { + Ok(at) => self.facts[at] = facts, + Err(at) => { + self.files.insert(at, facts.path.clone()); + self.facts.insert(at, facts); + } + } + } + self.merge(None); + } + /// Drop one file from the index, reporting whether it was there. /// /// Same contract as [`WorkspaceIndex::update_file`]: what is left is the @@ -984,10 +1030,13 @@ fn collect_members( /// the first file is parsed. Getting that ordering from here rather than /// re-deriving it is what keeps a watched build and a plain /// [`WorkspaceIndex::build`] the same index in the same order. -pub fn index_order<'a>( - files: impl IntoIterator, -) -> Vec<(PathBuf, &'a str)> { - let mut sources: Vec<(PathBuf, &str)> = files.into_iter().collect(); +/// +/// Generic in what rides beside the path — a borrowed `&str` for a caller that +/// holds the texts, an owned `String` for one that is handing them over — so a +/// scan that owns its work list gets the same ordering from the same function +/// rather than sorting for itself. +pub fn index_order(files: impl IntoIterator) -> Vec<(PathBuf, T)> { + let mut sources: Vec<(PathBuf, T)> = files.into_iter().collect(); sources.sort_by(|a, b| a.0.cmp(&b.0)); // A path handed over twice is one file; the first copy wins. sources.dedup_by(|a, b| a.0 == b.0); diff --git a/crates/vlog_semantic/tests/workspace.rs b/crates/vlog_semantic/tests/workspace.rs index ae9b6ef..ca7e4de 100644 --- a/crates/vlog_semantic/tests/workspace.rs +++ b/crates/vlog_semantic/tests/workspace.rs @@ -1103,6 +1103,122 @@ fn removing_a_file_gives_the_index_a_whole_build_would_have() { assert!(!ws.remove_file(Path::new("a.sv")), "and removing it again says so"); } +#[test] +fn absorbing_a_batch_gives_the_index_a_whole_build_would_have() { + // The batch form the interleaved scan feeds + // (`docs/features/scan-interleave/README.md`), against the same witness + // every other incremental path is held to. Every shape at once: a file + // replaced, two files added — one of which sorts *first*, so every id + // moves — and one dropped. + let held = [ + ("m.sv", "module m;\n sub u1 ();\nendmodule\n"), + ("z.sv", "package z;\n localparam K = 1;\nendpackage\n"), + ("gone.sv", "module gone;\nendmodule\n"), + ]; + let mut ws = index(&held); + assert_eq!(ws.files().len(), 3, "premise"); + + let batch = [ + ("a.sv", "module sub;\nendmodule\n"), + ("m.sv", "module m;\n sub u1 ();\n sub u2 ();\nendmodule\n"), + ("zz.sv", "class leaf extends base;\nendclass\n"), + ]; + ws.absorb( + batch.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(), + &[PathBuf::from("gone.sv")], + ); + + let mut expected: Vec<(&str, &str)> = vec![("z.sv", held[1].1)]; + expected.extend(batch); + assert_eq!( + ws.fingerprint(), + index(&expected).fingerprint(), + "a batch folded in is the index a whole build over what is left would have" + ); + assert_eq!(ws.files()[0], PathBuf::from("a.sv"), "the added file took FileId(0)"); + assert!(ws.units("gone").is_empty(), "and the dropped one is gone"); + assert_eq!(ws.instantiations_of("sub").len(), 2, "the replaced file's new edges are in"); + assert_eq!(ws.subclasses_of("base").len(), 1); +} + +#[test] +fn absorbing_one_batch_and_absorbing_it_in_pieces_are_the_same_index() { + // What makes a *publish* free of consequence: the scan folds records in + // whenever it happens to be asked a question, so how the same records are + // grouped into batches must not reach the result. + let records = |files: &[(&str, &str)]| -> Vec { + files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect() + }; + let files = [ + ("a.sv", "module sub;\nendmodule\n"), + ("m.sv", "module m;\n sub u1 ();\nendmodule\n"), + ("z.sv", "package z;\n localparam K = 1;\nendpackage\n"), + ("dup.sv", "module m;\nendmodule\n"), + ]; + let mut whole = WorkspaceIndex::default(); + whole.absorb(records(&files), &[]); + + let mut piecemeal = WorkspaceIndex::default(); + for one in &files { + piecemeal.absorb(records(std::slice::from_ref(one)), &[]); + } + assert_eq!(whole.fingerprint(), piecemeal.fingerprint()); + assert_eq!(whole.fingerprint(), index(&files).fingerprint(), "and both are a whole build"); + assert_eq!(piecemeal.units("m").len(), 2, "the duplicate name is still disambiguated"); +} + +#[test] +fn absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records() { + // QA attack (`docs/features/scan-interleave/README.md`, absorb attacks): + // a duplicate path inside one batch. Not constructible through the scan + // that actually feeds `absorb` — `Scan::work` is built from `index_order`, + // which already dedupes by path — but `absorb` is a public entry point on + // `WorkspaceIndex`, and its doc comment claims "what comes out is the + // index a full build over the records it now holds would have produced." + // `WorkspaceIndex::build` goes through `index_order`, which keeps the + // *first* of a duplicate path (`Vec::dedup_by`'s contract). `absorb`'s own + // loop walks `records` left to right and overwrites on a hit, keeping the + // *last*. So handed the exact same two records for one path, the two + // entry points disagree — the claimed equivalence does not hold for a + // batch with a duplicate path. Filed as a finding, not fixed here: which + // one should win is a design call, not a QA fix. + let files = [ + ("a.sv", "module first_shape;\nendmodule\n"), + ("a.sv", "package second_shape;\nendpackage\n"), + ]; + let built = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s))); + + let mut absorbed = WorkspaceIndex::default(); + absorbed.absorb(files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(), &[]); + + assert_eq!(absorbed.files().len(), 1, "one file survives either way"); + assert_ne!( + built.fingerprint(), + absorbed.fingerprint(), + "build (first-wins) and absorb (last-wins) disagree on a duplicate path in one batch" + ); + // Naming what absorb actually did, so a fix that changes this is a + // deliberate, visible diff rather than a silent behavior change. + assert_eq!( + absorbed.fingerprint(), + index(&[("a.sv", files[1].1)]).fingerprint(), + "absorb kept the second (last) record for the duplicate path" + ); +} + +#[test] +fn absorbing_nothing_changes_nothing() { + // A publish with nothing staged and a finish with nothing left are both + // this call, and neither may disturb an index that is already right. + let files = [("a.sv", "module a;\nendmodule\n")]; + let mut ws = index(&files); + let before = ws.fingerprint(); + ws.absorb(Vec::new(), &[]); + assert_eq!(ws.fingerprint(), before); + ws.absorb(Vec::new(), &[PathBuf::from("never_held.sv")]); + assert_eq!(ws.fingerprint(), before, "dropping a file the index never held is harmless"); +} + #[test] fn removing_a_file_moves_the_disambiguation_winner() { // The sharpest thing a removal can do to a *derived* answer: the file that diff --git a/docs/features/hover-line-index/README.md b/docs/features/hover-line-index/README.md index 42d68e6..893382a 100644 --- a/docs/features/hover-line-index/README.md +++ b/docs/features/hover-line-index/README.md @@ -179,7 +179,7 @@ into one file is free; giving `Define` its own line would mean a field in `vlog_parser`'s `Define` and is filed rather than done — it buys the first touch of one card and costs a second crate a field. -### Suspect 2 — **reported, not fixed**, filed here as a handshake request +### Suspect 2 — **reported, not fixed here; DELIVERED 2026-08-28** by `docs/features/scan-interleave/README.md` The brief named a second suspect and asked for it to be measured and filed rather than redesigned. It is real, and on the owner's own complaint it is by @@ -207,6 +207,16 @@ the include scan, which that feature's README already names as uncached. hover is really slow" mostly lives, and the probe that measures it is `e2e::a_hover_issued_during_the_initial_scan_waits_for_it`. +**DELIVERED, 2026-08-28.** `docs/features/scan-interleave/README.md` took the +scan apart into per-file steps and drains the message queue between them, so a +startup scan long enough to be worth it answers requests while it runs. The +same probe, flipped and renamed +(`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`), now +reports **15.5 ms cold / 12.8 ms warm** where the table above says 780 / 287 — +and the scan's own total moved by under a percent. The request is closed; what +that round did *not* do (the files are still read eagerly, a rescan still makes +requests wait) is filed in its own Status/TODO with numbers. + ## Measured Machine and method are `docs/perf/README.md`'s: Apple M1 Max, macOS 27.0, @@ -279,8 +289,10 @@ and is the owner's "a few KB for 20 000 modules" measured on real source. them through the view cache would mean `text_of` handing out an `Rc` instead of a `String`, which is a different change with a different argument. -- [ ] **Reported, not fixed: the first request of a session waits out the - startup scan.** Numbers and the filed request are in Handshakes. +- [x] **Reported, not fixed *here*: the first request of a session waits out + the startup scan.** Numbers and the filed request are in Handshakes; + **delivered 2026-08-28** by `docs/features/scan-interleave/README.md` + (780 ms → 15.5 ms cold, 287 ms → 12.8 ms warm). ## Work log diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index 4563dbb..1987710 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -270,6 +270,19 @@ folder brings it into scope. `"lucisv.index.scope": "workspace"` restores the pre-2026-08-27 behaviour in full. Rules, the clamp, the close decision and the one `.gitignore` gap: `docs/features/index-scope/README.md`. +**And scope-relative in *time*, since 2026-08-28** (scan-interleave). A +**startup** scan of more than 64 files no longer blocks the message loop: it +indexes one file at a time and answers whatever the client has already sent +between two of them, so the first request of a session comes back in +milliseconds instead of waiting out the whole scan (780 ms → 15.5 ms cold over +200 files). The price is that such an answer reflects the index **as of that +moment** — a declaration in a file the scan has not reached yet does not exist +yet, in exactly the sense a declaration outside the scope does not exist. Two +narrowings keep that from reaching anywhere it is not worth it: a scan of 64 +files or fewer runs one shot as it always did, and a request queued *behind* a +message that asked for a rescan waits for that rescan, so the loop's order +contract is unchanged. `docs/features/scan-interleave/README.md`. + **Open buffers override disk** in every index rebuild: the scope is walked, each file read, and then every open document with a path replaces the disk copy (adding itself if it exists only in the editor). So the index never diff --git a/docs/features/scan-interleave/README.md b/docs/features/scan-interleave/README.md new file mode 100644 index 0000000..116e563 --- /dev/null +++ b/docs/features/scan-interleave/README.md @@ -0,0 +1,592 @@ +# scan-interleave + +## Goal + +`Server::new` ran the whole startup scan before `run()`'s message loop took its +first message, so everything a client sent the instant the handshake was done +sat in the OS pipe until the scan was over: **780 ms cold store / 287 ms warm** +over a 200-file workspace, against 26–64 µs for the same hover once the scan +had finished (filed as "suspect 2" in +`docs/features/hover-line-index/README.md`, and the larger half of the owner's +"hover is really slow on first try"). This round takes the scan apart into +per-file steps and drains the message queue between them, so a scan long enough +for a person to notice answers questions while it runs. The first hover of a +session now comes back in **15.5 ms cold / 12.8 ms warm** on the same fixture — +a 50× and 22× improvement — and the scan's own total is unchanged inside +run-to-run noise. + +## Assumptions + +- **An answer given mid-scan reads the index as of that moment.** It is + scope-relative in *time* exactly the way every answer is already + scope-relative in *space* (`crates/lucisv_server/README.md`): a declaration in + a file the scan has not reached yet is a declaration this server does not know + about yet, and it says so by answering nothing rather than by making the + client wait. Which files that means depends on how far the scan got, so a + mid-scan answer is genuinely **not reproducible** — which is why the rule + below narrows the cases it can happen in to the one where it is worth it. +- **Only a scan nobody asked for answers mid-way.** The message loop has always + promised that everything queued *ahead* of a request is applied before that + request is answered. A `didOpen` that widened the scope, a `didSave`, a + changed setting or an added workspace folder ask for a rescan, and "applied" + for those means the rescan has **run** — one message at a time, the server + would have finished it before ever taking the request. So requests that arrive + during a rescan wait for it, and only the *startup* scan — which nothing was + queued ahead of — answers from a half-built index. See `Server::must_wait`. +- **And only a scan long enough to be worth it.** A scan of at most + `INTERLEAVE_ABOVE` (64) files is over in a few milliseconds and runs exactly as + it always did, one shot, no drains: trading a complete answer for those + milliseconds would be a bad bargain. A count rather than a clock, because a + rule about elapsed time makes what a server answers depend on how loaded the + machine is — which is a property neither a test suite nor a bug report can + work with. +- **The scan indexes the text each file had when its work list was taken.** A + `didOpen` or a `didChange` answered mid-scan changes the *buffer* and not the + index — exactly as it does when it lands a millisecond after the scan + finished, because neither notification touches the index (a save is what + does). So a message answered in the middle of a scan cannot move that scan's + result. +- **A record written through is a record kept.** A scan a `shutdown` interrupts + leaves every file it had already parsed in the persistent store, because the + store is appended to per file (`docs/features/index-persistence/README.md`). + That was already true of a scan a `kill` interrupted; it is now reachable + through the protocol as well. + +## Handshakes + +### `vlog_semantic` — `WorkspaceIndex::absorb` + +```rust +/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for +/// many files at once — and for **one** merge rather than one each. +pub fn absorb(&mut self, records: Vec, gone: &[PathBuf]); + +// generic in what rides beside the path, so an owning caller gets the same order +pub fn index_order(files: impl IntoIterator) -> Vec<(PathBuf, T)>; +``` + +`absorb` keeps the same promise `update_facts` does — what comes out is the +index a full `build` over the records it now holds would have produced — and for +the same structural reason: the records stay path-sorted and one file to a path, +and `merge` is then the loop `IndexBuilder::finish` runs over the same list. It +exists because **a merge is a pass over every record the index holds**, which is +measured below and is the difference between a linear scan and a quadratic one. + +`index_order`'s lifetime parameter became a type parameter. Every existing +caller passes `&str` and is unchanged; the scan passes `String`, because it owns +its work list. + +### `lucisv_server::state` — the scan as a value + +```rust +pub struct Scan { /* work list, how far through it, what is staged */ } + +impl Scan { + pub fn skipped(&self) -> usize; + pub fn cached(&self) -> usize; + pub fn total(&self) -> usize; + pub fn index_next(&mut self, path: &Path) -> bool; +} + +impl Workspace { + pub fn adopt_roots(&mut self, roots: Vec); + pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Scan; + pub fn scan_step(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool; + pub fn publish_scan(&mut self, scan: &mut Scan); + pub fn finish_scan(&mut self, scan: Scan) -> Vec; +} +``` + +**A value rather than a loop, because a callback cannot be handed the workspace +it is called from.** `rebuild_index_with` held `&mut self` for the whole scan, +so its watcher callback could reach the connection (a disjoint field) but never +the workspace — and answering a message needs exactly that. Splitting the loop +puts the scan's state somewhere the server can own it, and `rebuild_index_with` +is now literally + +```rust +let mut scan = self.begin_scan(watch); +while self.scan_step(&mut scan, watch) {} +self.finish_scan(scan) +``` + +so "one shot" and "interleaved" are not two scans that have to be kept in step: +they are this loop with and without a drain in it. That is what makes the +fingerprint equivalence structural rather than tested-and-hoped. + +`skipped`/`cached` moved from `IndexWatch` to `Scan`: they are facts about the +scan, and `IndexWatch` is now purely the thing that speaks protocol. +`open_roots_with` and `rebuild_index_with` are `#[cfg(test)]` now — the server +drives the three calls itself, and every test that just wants an index still +calls the one-shot form. + +### `lucisv_server::candidates`, `::includes` — the batch forms + +```rust +impl Candidates { + pub fn absorb(&mut self, index: &WorkspaceIndex, batch: Vec<(PathBuf, Vec)>); +} +impl IncludeGraph { + pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]); +} +``` + +Both are the batch form of the incremental update each already had +(`update_words`, `update_file`), doing the whole-table half once for the batch +instead of once per file. **All three tables are published together, never one +of them**: an index that had seen a scanned file while a completion or an +include link could not would make "the workspace as far as it has been scanned" +three different things at once. + +`candidates::words_in` became `pub(crate)`, because a scan lexes each file's +completion words as it reaches it rather than in one pass at the end. That moves +work rather than adding it — `Candidates::build` at the end of the scan now +finds every file's words already in hand and lexes nothing — and it is what +keeps the *tail* of a scan from being an unbroken block longer than one file. + +### `docs/features/hover-line-index` — suspect 2, **DELIVERED** + +That round measured the wait, filed it as a request to "whoever owns the message +loop next" and named the probe. This is that round; the probe is flipped and +renamed (`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`) +and its before-numbers are the ones in the table below. + +## Measured + +Machine and method are `docs/perf/README.md`'s: Apple M1 Max, macOS 27.0, +`--release`, `#[ignore]`d probes, `--test-threads=1`. Taken 2026-08-28, before +and after, in the same session. + +### The merge cost, measured before the design was chosen + +`perf::publishing_a_half_built_index_mid_scan`, files of 1 000 lines: + +| workspace | one file's parse | one whole merge | one `update_facts` | per-file feeding would cost | against parsing | +|---|---:|---:|---:|---:|---:| +| 50 files | 2.35 ms | 0.73 ms | 0.66 ms | 32.8 ms | 117.6 ms | +| 200 files | 2.32 ms | 3.35 ms | 3.15 ms | **630.7 ms** | 464.4 ms | +| 800 files | 2.23 ms | 15.90 ms | 14.66 ms | **11.73 s** | 1.78 s | + +**So: not per file.** A merge is linear in the whole workspace, so feeding the +live index one file at a time is quadratic — at 200 files it would have *more +than doubled* the scan, and at 800 files multiplied it by seven. The decision +the numbers make is **deferred**: records are staged as they are taken and +folded in with one `absorb` per *drain*, and a drain only happens when the queue +is not empty. A scan nobody is waiting on therefore pays nothing beyond one +`try_recv` per file, and a scan somebody is waiting on pays 3.35 ms per burst at +200 files — one and a half files' worth of parse. + +### The latency the round is about + +`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`, 200 files +of 1 000 lines with a filelist, over the wire against the real binary: + +| the first hover of a session | before | after | +|---|---:|---:| +| issued the moment `initialized` was sent, cold store | 780 ms | **15.5 ms** | +| — warm store | 287 ms | **12.8 ms** | +| the same hover once the scan is done | 64 / 61 µs | 191 / 151 µs | + +Two honest caveats on that table. The "after" figures move with how busy the +machine is — a second run minutes later, with the corpus suite running beside +it, reported 19.8 ms and 14.0 ms — so read them as *tens of milliseconds +against hundreds*, which is the claim, and not as three significant figures. +And the last row is the same answer either way, measured differently now: the +"after" run waits for the progress bar to come down before asking, which is +what makes it a *post*-scan measurement rather than a race with the scan. Both +are microseconds and neither is what the round moved. + +### What the scan's total cost + +`state::tests::qa_perf_cold_warm_and_half_warm_scans`, the 860-file corpus, +before and after on the same machine minutes apart: + +| | before | after | +|---|---:|---:| +| no cache | 321.5 ms | 322.0 ms | +| cold, filling the store | 351.3 ms | 353.4 ms | +| warm, every file from the store | 187.0 ms | 188.6 ms | +| the store | 2 380 790 B | 2 380 790 B | + +**+0.2 % / +0.6 % / +0.9 %**, which is well under the "a few percent" this +round was allowed — and inside the run-to-run band, which is worth stating with +a number of its own: the same "after" measurement taken again on a busier +machine reported 357 / 375 / 201 ms, so the pair above is only meaningful +*because* it was taken minutes apart in one session on one tree. Nothing was added to the +per-file path; the completion word lex moved into it from the tail, and the +index is folded in with the same number of merges a one-shot scan always did +(one) when nothing is waiting. + +### The floor under a mid-scan answer + +`perf::what_a_scan_does_before_its_first_file`, 200 files of 1 000 lines: + +| | quiet machine | busy machine | +|---|---:|---:| +| before the first file (resolve the scope, read every file, open the store) | 6.9 ms | 9.8 ms | +| one file | 4.0 ms | 5.7 ms | +| the other 199 | 682 ms | 723 ms | +| finishing (last merge, completion tables, include graph, overlays) | 10.7 ms | 10.9 ms | + +So the 15.5 ms above is the first two rows plus the handshake and the message's +own travel, and it is **not** the "single digit ms" the brief hoped for. The +first row is one block no drain can break up, and reading the files lazily is +what would break it up — filed as a deliberate not-done below with this number +attached. + +## Status / TODO + +- [x] Measure the merge cost before choosing a rhythm; per-file feeding + rejected on the numbers above, deferred-and-batched chosen. +- [x] `WorkspaceIndex::absorb`, with the fresh-build equivalence tested three + ways (a batch of every shape, one batch against the same records in + pieces, and an empty batch). +- [x] `Scan` + `begin_scan`/`scan_step`/`publish_scan`/`finish_scan`, with + `rebuild_index_with` rewritten as the loop over them. +- [x] The server drives the scan and drains the queue between files; the + queue moved onto `Server` so a scan and `run` share it. +- [x] Order preserved: `Server::must_wait` holds a request (and everything + behind it) that is queued behind a rescan, and `run` answers what was + held before it takes anything newer — keeping its place among messages + the rescan itself held, and carrying its `$/cancelRequest` with it. +- [x] Coalescing: a rescan asked for mid-scan is a flag, and + `scan_until_settled` is a loop — never a scan inside a scan. +- [x] Shutdown mid-scan stops the scan where it stands and `run` returns + without taking another message. +- [x] The completion tables and the include graph are published with the + index, so a mid-scan answer is one generation and not three. +- [x] A file opened mid-scan is indexed next (`Scan::index_next`). +- [x] The startup scan republishes and refreshes lenses when a buffer was + opened during it — a debt that did not exist before this round. +- [x] The e2e probe flipped and renamed; the before-numbers kept above. +- [x] `cargo fmt` / `cargo clippy --all-targets --workspace` / `cargo test + --workspace` / `node editors/vscode/smoke.js`. +- [ ] **Not done, deliberately: the files are still read eagerly.** The 6.9 ms + before the first file is mostly 200 `read_to_string`s. Reading each file + in `scan_step` instead would take the mid-scan floor to single digits, + and it costs a work list of `Option` and a decision about what a + file that turns out to be unreadable does to the progress bar's `total` + (today such a file never joins the work list at all, because the read + that fails happens before the list is taken). Worth doing; not worth + guessing at inside a round that is already changing when answers happen. +- [ ] **Not done, deliberately: a scan of a few very large files still + blocks.** `INTERLEAVE_ABOVE` counts files, and 20 netlist-shaped files + can take a second. A second rule on elapsed time would catch it and would + make what the server answers depend on machine load; the honest fix is a + cost estimate from the sizes the cap already reads (`oversize` does a + `metadata` call per walked file), which is a design, not a patch. +- [ ] **Not done, deliberately: a rescan still makes requests wait.** The + brief named later rescans as blocking the loop the same way, and they + still block *requests* — notifications, cancels and responses are + processed throughout. Answering a request from a half-updated index would + break the order contract the loop has always kept, and no measurement + says a rescan is where the pain is: the owner's report is about the first + request of a session. + +## Work log + +### 2026-08-28 — dev + +**Measured the merge first, and the number chose the design.** The brief left +per-file / chunked / deferred open and asked for numbers. `update_facts` on an +already-held file is 3.15 ms at 200 files and 14.7 ms at 800, because +`merge_references` re-resolves every reference in the workspace; one per file is +630 ms and 11.7 s of pure merging. The rhythm that survives is **stage per +file, fold in per drain, and drain only when something is waiting** — which +makes the cost of interleaving zero for a scan nobody is waiting on and one +merge per burst for a scan somebody is. There is no chunk size to tune, which +is the nicest property of it: the client's own traffic sets the rhythm. + +**The scan had to become a value before it could be interrupted.** The +blocker was borrowing, not design: `rebuild_index_with(&mut self)` holds the +workspace for the whole scan, and a message answered from inside it needs that +same workspace. `Scan` owns the work list and the staged records, so +`scan_step(&mut self, scan: &mut Scan)` borrows two separate things and the +server can put whatever it likes between two calls. `rebuild_index_with` is now +three lines over the same three methods, which is what makes "the interleaved +scan is the one-shot scan with a drain in it" a fact about the code rather than +a claim in a document. + +**The hard part was not latency, it was the order contract.** The first +working version answered requests mid-scan unconditionally, and sixteen e2e +tests began failing *intermittently* — which is the real finding, not the +failures. Those sessions pipeline a whole conversation into the pipe +(`initialize`, `initialized`, a `didOpen` that widens the scope, three +requests, `shutdown`), so whether a request saw a finished index depended on +whether the forwarder thread got scheduled before the scan ended. Three +decisions came out of that: + +1. **`must_wait`.** A request queued behind a message that asked for a rescan + waits for that rescan, because that is what one message at a time would have + done, and once one request is waiting every later one waits too. Held + messages keep their arrival order and are answered by `run` before it takes + anything newer. `shutdown` waits with them: a request sent before a shutdown + is a request the client is still owed an answer to. +2. **Only the startup scan answers mid-way.** A scan a *message* asked for has + that message queued ahead of everything else, so nothing arriving during it + may be answered from a half-updated index. The startup scan has nothing + queued ahead of it, and it is the one the owner's report is about. +3. **`INTERLEAVE_ABOVE`.** Even the startup scan should not trade a complete + answer for milliseconds. Sixty-four files is the line: below it the scan runs + exactly as it always did, which is also why the whole existing suite passes + unmodified — every fixture in it is a handful of files. A count and not a + clock, so that what the server answers never depends on how busy the machine + was. + +**All three tables, or none.** After `must_wait` there were still failures +where a macro hover and an include link came back empty mid-scan: the index was +being published but `Candidates` and `IncludeGraph` were still built whole at +the end. Publishing one of three tables makes "as far as the scan has got" mean +three different things at once, so both grew a batch `absorb` and all three are +folded in together. The include graph's known-file table is relearned from the +scan's **whole work list** rather than the files it has reached, because which +files *exist* is settled the moment the scope is resolved and only the edges are +discovered file by file. + +**Coalescing: finish, then rescan again — not abort and restart.** A message +answered mid-scan sets `rescan_wanted`; `scan_until_settled` is a loop that +scans again while the flag is set, and `reindex`/`reindex_one` set the flag +instead of running when `scanning`. Finishing was chosen over aborting because +it needs no way to unwind a half-published index and cannot loop forever: the +follow-up scan reads the persistent store for every file the abandoned one had +already parsed. Each scan keeps its own progress token, which is what a client +showing a bar expects of two scans. `reindex_one` returns `true` when it defers, +because its caller's fallback is "rebuild the whole thing right now", which is +precisely what must not happen. + +**Two debts this round created and paid.** A buffer can now be *opened* during +the startup scan, so `Server::started` owes what `reindex` has always owed at +the end of a scan — a code-lens refresh, a generation bump and a republish — +and pays it when any buffer is open (which is nothing at all for a session +whose client did not get a `didOpen` in edgeways). And `reindex_one` can no +longer patch one file mid-scan without the scan overwriting it with older bytes +a moment later, so it defers too. + +**A test seam, named as one.** `Server::started` grew a `queued: Vec` +parameter — what the client had already sent when the server was built, put +straight onto the queue the startup scan drains. `Server::new` passes an empty +one. The alternative was for the test to send on the client end and race the +forwarder thread for it, which made the first version of +`a_request_the_client_had_already_sent_is_answered_during_the_startup_scan` +pass alone and fail under a loaded suite. A coin-toss test is worse than no +test. + +**Files touched.** `crates/vlog_semantic/src/workspace.rs`, +`crates/vlog_semantic/tests/workspace.rs`, +`crates/lucisv_server/src/{server.rs,state.rs,candidates.rs,includes.rs,perf.rs}`, +`crates/lucisv_server/tests/e2e.rs`, this README, +`docs/features/hover-line-index/README.md`, `docs/perf/README.md`, `TODO.md`. +No new dependency, no `unsafe`, no `#[allow]`, no version bump, no commits. +Single-threaded throughout: the only thread this round touches is the message +forwarder, which existed already and still only moves messages. + +**Tests added** (14). + +| test | where | pins | +|---|---|---| +| `absorbing_a_batch_gives_the_index_a_whole_build_would_have` | `vlog_semantic/tests/workspace.rs` | the house witness for the new entry point: a file replaced, two added (one sorting first, so every id moves), one dropped | +| `absorbing_one_batch_and_absorbing_it_in_pieces_are_the_same_index` | same | what makes a publish free of consequence — how records are grouped into batches cannot reach the result | +| `absorbing_nothing_changes_nothing` | same | the empty publish and the empty finish | +| `publishing_between_every_file_leaves_what_a_one_shot_scan_leaves` | `lucisv_server/src/state.rs` | the round's central invariant, over index **and** completion tables **and** include graph, publishing after every single file | +| `a_rescan_that_publishes_as_it_goes_still_drops_what_left_the_scope` | same | a publish only folds records *in*, so the removal a rescan owes has to survive every publish before it | +| `a_buffer_opened_or_changed_mid_scan_does_not_change_what_the_scan_indexes` | same | fingerprint equality with a `didChange` injected mid-scan | +| `a_file_opened_mid_scan_is_indexed_next_and_the_index_cannot_tell` | same | `Scan::index_next` moves it, does not move it twice, refuses a file not waiting — and the finished index is byte-identical | +| `a_scan_reports_the_same_events_in_the_same_order_however_it_is_driven` | same | progress and log continuity: interleaving adds drains between events, never events | +| `a_request_the_client_had_already_sent_is_answered_during_the_startup_scan` | `lucisv_server/src/server.rs` | the point of the round, over the real dispatch: the response goes out before the bar comes down | +| `a_scan_short_enough_to_wait_for_answers_nothing_in_the_middle_of_itself` | same | the other side of `INTERLEAVE_ABOVE` | +| `a_request_queued_behind_a_rescan_waits_for_that_rescan` | same | the order contract: the request sees the index the push asked for, not the one it was sent into | +| `a_held_request_keeps_its_place_and_takes_its_cancel_with_it` | same | the two corners holding creates: a burst's own request stays in front of one the scan it started held later, and a cancel consumed on the way in goes back with what it cancels | +| `a_rescan_asked_for_mid_scan_is_coalesced_into_exactly_one_more_scan` | same | three settings pushes inside one scan cost one more scan, two bars, two tokens, no nesting | +| `a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands` | same | the bar never comes down, the index is short, `run` returns at once | + +Two `#[ignore]`d probes added +(`perf::publishing_a_half_built_index_mid_scan`, +`perf::what_a_scan_does_before_its_first_file`); one existing probe flipped and +renamed (`e2e::a_hover_issued_during_the_initial_scan_waits_for_it` → +`..._is_answered_during_it`), which is the before/after pair this README's +latency table is read from. + +**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets +--workspace` silent. `cargo test --workspace` green, 0 failed: +`lucisv_server`'s unit tests **1 225 passed / 26 ignored** (+11 tests, +2 +`#[ignore]`d probes), its `e2e` suite **56 passed / 2 ignored** (unmodified +except the flipped probe), `vlog_semantic`'s `workspace` suite **70 passed** +(+3). `node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`. + +## QA log + +### 2026-08-28 — QA + +Read `CLAUDE.md`, the dev brief, and this README's Handshakes/Work log before +attacking. Traced `process_batch`'s held-message splice, `must_wait`, +`scan_until_settled`/`scan_once`/`answer_what_is_waiting`, `Scan`, and +`WorkspaceIndex::absorb` line by line against the charter's five attack +classes, then exercised the parts a trace alone couldn't settle. Two real +findings, both narrow; one confirmed-correct-but-untested behavior now pinned; +gates and numbers reproduced. + +**Finding 1 (low, doc-contract) — `WorkspaceIndex::absorb` does not dedupe a +duplicate path in one batch the way `WorkspaceIndex::build` does.** +`crates/vlog_semantic/src/workspace.rs:472-489` (`absorb`). `build` goes +through `index_order`, which keeps the *first* of a duplicate path +(`Vec::dedup_by`'s contract, `crates/vlog_semantic/src/workspace.rs:1034`). +`absorb`'s own loop walks `records` left to right and overwrites on a +`binary_search` hit, keeping the *last*. `absorb`'s doc comment claims "what +comes out is the index a full build over the records it now holds would have +produced" — that equivalence does not hold for a batch with a duplicate path. +Not reachable through the scan that actually feeds `absorb` today: `Scan::work` +is built from `index_order` before the scan starts, so it can never contain two +entries for the same path, and `scan_step` therefore never stages a duplicate. +But `absorb` is `pub` on `WorkspaceIndex`, its doc comment states the +equivalence unconditionally, and a future caller (or a future change to how +`Scan::work` is assembled) could reintroduce the gap silently. Repro and +permanent regression test added and passing: +`crates/vlog_semantic/tests/workspace.rs`, +`absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records` +— builds `[("a.sv", module first_shape), ("a.sv", package second_shape)]` both +ways and asserts the fingerprints differ, then pins which one `absorb` actually +keeps (the last). Not fixed here — whether `absorb` should match `build`'s +first-wins or the doc comment should be narrowed to describe last-wins is a +design call, not a QA fix. Verified harmless in production as things stand +today, precisely because the scan can't construct the input that trips it. + +**Finding 2 (very low, stale doc comment) — `refresh_code_lenses`'s doc comment +contradicts what this round now does.** +`crates/lucisv_server/src/server.rs:1979-1984`: "Nothing is sent at startup +either: no buffer is open there, so there are no lenses to invalidate." That +was true before this round; `Server::started` now calls exactly this method at +the end of construction whenever a `didOpen` answered mid-scan left a buffer +open (`crates/lucisv_server/src/server.rs:347-354`), and the new test below +confirms it fires. The comment should say client-refresh-capable + a buffer +open, no longer "never at startup." Not fixed here per QA's remit not to edit +outside the change's own tests, but it is a one-line fix the dev should make in +the same file the round already touched. + +**Verified correct, previously untested — the two-publish behavior for a file +opened mid-startup-scan.** Traced through `Server::started`'s new "pay the +`reindex` debt" block and found it produces *two* `publishDiagnostics` for the +file a mid-scan `didOpen` opens: one from `didOpen`'s own always-existing +handler (against the half-built index, mid-scan — correct, not new), and one +from the debt-payment block after the bar comes down (against the finished +index — the new behavior). That is correct, not a duplicate-publish bug, but +it was unverified by any test in the round's own "Tests added" table. Added +`crates/lucisv_server/src/server.rs`, +`a_buffer_opened_during_the_startup_scan_is_published_and_lenses_refreshed_once`: +asserts exactly two publishes for the opened file, the first before the `end` +progress event and the second after it, and exactly one `workspace/codeLens/refresh` +(also after `end`, implicitly, since it can only fire once open_uris is +non-empty at the end of construction). Passes. + +**Also added, no bug found — `INTERLEAVE_ABOVE` exact-boundary test.** The +charter asked for the 64/65 edge explicitly; the round's own tests exercise +`INTERLEAVE_ABOVE + 6` and `4`, neither of which pins the `>` vs `>=` choice in +`scan_once`. Added +`crates/lucisv_server/src/server.rs`, +`interleave_above_is_a_hard_boundary_at_the_file_count_not_before_or_after`: a +scan of exactly 64 files answers nothing mid-construction (one-shot), a scan of +65 answers before the bar comes down (interleaved). Passes as written — no +off-by-one found, now locked in. + +**Attacks traced and found sound, not turned into new tests (existing coverage +or structurally excluded):** +- *Order-contract, cancel-through-a-wait*: traced `process_batch`'s + `consumed_cancels` splice by hand against + `a_held_request_keeps_its_place_and_takes_its_cancel_with_it` + (`crates/lucisv_server/src/server.rs:2985`-ish) with a constructed batch + where a cancel's target is answered *before* the wait point is reached — the + stale cancel does get re-queued into `held`, but `cancelled_in` re-filters by + the ids actually present in the replayed batch, so it is inert on replay, + never mis-cancels an unrelated request. Not a bug; not worth a dedicated + test since it changes nothing observable. +- *Gone-file races during a scan that also answers mid-way*: `finish_scan` + defers the `gone` computation to one `absorb` call at the very end, so a + file leaving scope is not removed from the live index until the scan + finishes. This only matters if a mid-scan answer could see a file that + should already be gone — and every scan capable of having `gone` files + non-empty is a *rescan* (`answering_a_rescan = true`), which `must_wait` + already blocks from answering anything mid-way. The startup scan (the only + one that answers mid-way) always starts from an empty index, so it can never + have a `gone` file. Structural, not incidental — traced through + `scan_until_settled`'s `asked_for` threading, not tested further. +- *Include graph's `known` set includes not-yet-scanned files mid-scan*: + intentional per the Handshakes section ("which files exist is settled the + moment the scope is resolved"); this can make an `` `include `` targeting an + unscanned file resolve to a path with no edges of its own yet, which is the + same "not there yet" story the index already tells for symbols. Not a + divergence from the round's own stated contract. +- *Shutdown delivered twice (queue-injection copy + forwarder-relayed copy) in + `a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands`*: the test + deliberately sends the same logical `shutdown` through two paths and says so + in its own comment ("whichever of the two ... the scan stops here"). Traced + the `forward`/`handle_shutdown` interaction and confirmed the real `exit` + notification can never be stolen by the forwarder (it stops at the first + shutdown it relays and never reads again), so the raciness is a test-harness + artifact for reaching the scenario at all, not a client-facing bug. Ran the + test 20x in a loop (`cargo test ... -- --test-threads=1`, repeated) with no + flake. + +**Gates.** `cargo fmt --all -- --check` clean (after formatting the one test I +added that needed it). `cargo clippy --all-targets --workspace` silent. +`cargo test --workspace` run 3x after all QA additions: **0 failures each run, +2457 total passed each run**, identical every time. One transient failure seen +*before* the final 3-run check +(`large::tests::references_on_one_giant_line_locate_their_hits_in_linear_time`, +a pre-existing wall-clock perf gate unrelated to any file this round touches) +under self-inflicted contention (I had a background `cargo test` and a 3-run +loop racing on the same machine at once); reproduced clean on both master +(pre-round, 3/3) and this round's tree (3/3) once run without that +contention — not a regression, not flagged further. +`node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`. + +**Numbers reproduced**, same machine, `--release`, `--test-threads=1`: +- `e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`: 16.1 ms + cold / 14.0 ms warm (README claims 15.5 / 12.8, and says a rerun elsewhere + saw 19.8 / 14.0 — this sits inside that band). +- `perf::publishing_a_half_built_index_mid_scan`, all three sizes including + 800 (not skipped — it ran in 5.4s, not slow): 200-file whole merge 3.85 ms + (claimed 3.35 ms), 800-file per-file-feeding-would-cost 12.9 s (claimed + 11.7 s) against 2.06 s of parsing (claimed 1.78 s) — same shape, same + conclusion (deferred-batched, not per-file), numbers within normal + machine-to-machine variance. +- `state::tests::qa_perf_cold_warm_and_half_warm_scans`: no-cache 347 ms / + cold 387 ms / warm 203 ms (claimed 322/353/189) — store size **exactly** + 2 380 790 bytes, matching the README bit for bit, which is the number that + actually matters (deterministic index size, unaffected by machine noise). + +**Verdict: SHIP.** No masked-corruption, no order-contract violation, no +non-settling loop found across five attack classes and direct code tracing. +Two findings filed above are both low severity, both narrow (one is +structurally unreachable through the round's own code paths today, the other +is a one-line stale comment), and neither touches the hard invariants +(never-corrupt, idempotent, comments-preserved) or the round's own claimed +equivalences in the paths actually exercised. Three regression tests added, +all passing, all documenting real (if narrow) findings or previously-untested +correct behavior — none required a design change. + +## Review + +**2026-08-28 — lead.** Reviewed after QA's SHIP; gates re-run +independently (fmt clean, clippy silent, 2457 workspace tests green, +QA ran the suite ×3 with identical results). This was the riskiest +round of the wave — interleaving is where order contracts go to die — +and the two rules that survived the dev's own 16-test intermittent +failure (`must_wait`, so only the startup scan answers mid-way; and +`INTERLEAVE_ABOVE` as a count, not a clock) are the reason the whole +existing suite passes unmodified and deterministic. The measure-first +discipline paid again: per-file merging looked obvious and would have +been quadratic (11.7 s over 800 files); one absorb per non-empty-queue +drain costs the idle scan a `try_recv` per file and nothing else. The +structural fingerprint argument — one-shot and interleaved are +literally the same three-line loop over `Scan` — is the strongest +equivalence guarantee of the wave. First hover of a session: +780 → 15.5 ms cold, 287 → 12.8 ms warm, scan totals inside noise; the +remaining 6.9 ms of eager pre-scan reads is measured and filed, not +hidden. QA's two low findings were the lead's to settle and are fixed +in this commit: `absorb`'s doc now states the distinct-paths +precondition and why last-wins is the right update semantic (behavior +unchanged — the one production caller feeds deduped work, and QA's +divergence test pins the edge), and `refresh_code_lenses`' comment +caught up with `started`. The double-publish for a buffer opened +mid-scan (half-built answer, then finished answer) is correct by the +scope-relative-in-time doctrine and now pinned. Accepted; committed by +the lead. diff --git a/docs/perf/README.md b/docs/perf/README.md index 6f2d69e..b34150e 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -309,6 +309,45 @@ is slow" mostly lives. Fixing it is a change to request scheduling — answering while the index is half-built, or scanning off the message-loop thread — and was explicitly out of this round's scope. +## Before / after — round 4 (2026-08-28) + +`docs/features/scan-interleave/README.md`: D2, answered. The scan is per-file +steps with the message queue drained between them, so a startup scan of more +than 64 files answers requests while it runs — single-threaded, interleaved, +not scanned off-thread. Same fixture, same probe, flipped and renamed +(`tests/e2e.rs::a_hover_issued_during_the_initial_scan_is_answered_during_it`): + +| the first hover of a session | before | after | +|---|---:|---:| +| issued the moment `initialized` was sent, cold store | **780 ms** | **15.5 ms** | +| — warm store | **287 ms** | **12.8 ms** | +| the same hover once the scan is done | 64 / 61 µs | 191 / 151 µs | + +The "after" figures are tens of milliseconds, not three significant figures: a +second run on a busier machine reported 19.8 / 14.0 ms. The claim is the order +of magnitude, and the post-scan row is measured after waiting for the progress +bar rather than racing the scan. + +**What it cost the scan: under a percent.** The merge was measured before the +design was chosen, and the numbers ruled out the obvious shape — a merge is a +pass over the whole index, so folding each file in as it is taken would be +quadratic (`perf::publishing_a_half_built_index_mid_scan`, 200 files of 1k +lines: 630 ms of merging against 464 ms of parsing; 800 files: 11.7 s against +1.78 s). Records are staged and folded in once per *drain* instead, and a drain +only happens when a message is waiting: + +| 860-file corpus | before | after | +|---|---:|---:| +| no cache | 321.5 ms | 322.0 ms | +| cold, filling the store | 351.3 ms | 353.4 ms | +| warm, every file from the store | 187.0 ms | 188.6 ms | + +The floor under the 15.5 ms is one block no drain can break up: +`perf::what_a_scan_does_before_its_first_file` puts **6.9 ms** before the first +file (resolve the scope, read all 200 files, open the store) against 4.0 ms for +one file — so reading the files lazily is what a single-digit number would take, +and it is filed as a deliberate not-done in that feature's README. + ## What it would take to go faster Ranked by what the measurements above say is there, with what each would @@ -321,6 +360,10 @@ cost. None of these were attempted; each is a future round. costs the user is that the message loop has not started yet. Any fix is a change to what an answer *means* while the index is half-built, so it needs a design round, not an optimisation. + → **Done in round 4**, 780 → 15.5 ms cold and 287 → 12.8 ms warm; the + design round it needed is `docs/features/scan-interleave/README.md`, and + what an answer means mid-scan is written down there. What is left of this + item is 6.9 ms of eager file reading before the scan's first file. 1. **Incremental lexing and parsing — 24.5 ms of a 31 ms flush at 10 000 lines (79 %).** This is the only large lever left. It is also the one change that runs straight into `CLAUDE.md`'s hard invariants 1 and 2: the @@ -378,6 +421,13 @@ cost. None of these were attempted; each is a future round. the shipped binary, with a cold store and a warm one (`tests/e2e.rs::a_hover_issued_during_the_initial_scan_waits_for_it`). `perf::breaking_down_one_flushed_keystroke`. +- [x] **Added in round 4 (2026-08-28):** what one mid-scan publish costs + against the per-file parse it is interleaved with + (`perf::publishing_a_half_built_index_mid_scan`, at 50 / 200 / 800 + files), and what a scan does *before* its first file — the block no + drain can break up (`perf::what_a_scan_does_before_its_first_file`). + The e2e probe above was flipped to + `a_hover_issued_during_the_initial_scan_is_answered_during_it`. - [ ] **Round 1's second open TODO, restated and still open:** memory. Nothing in the repo measures resident size. Round 2 added no data structure — two free functions and no state — so the figure it would