The startup scan answers requests as it goes
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 21s

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 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-28 20:20:20 -07:00
1 parent 20567e1a7f
commit 172a034c67
13 files changed
+2335 -137

No files matched your search

+13
View File
@@ -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
+21 -1
View File
@@ -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<String>)>) {
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<Macro> {
/// 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<String> {
///
/// `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<String> {
// 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.
+24
View File
@@ -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<PathBuf> =
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]) {
+96
View File
@@ -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<vlog_semantic::FileFacts> = 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::<Vec<_>>(),
);
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"]
File diff suppressed because it is too large. Load diff
+486 -34
View File
@@ -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<PathBuf>,
/// What the open buffers among `work` already knew about themselves, taken
/// from as each of them is reached.
analyzed: Analyzed,
incdirs: Vec<PathBuf>,
warnings: Vec<String>,
/// 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<FileFacts>,
staged_at: Vec<usize>,
/// The completion words of every file taken so far, which the tables built
/// when the scan ends are assembled from.
words: HashMap<PathBuf, Vec<String>>,
/// 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<PathBuf>,
watch: &mut dyn FnMut(IndexEvent),
) -> Vec<String> {
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<PathBuf>) {
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<String> {
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<PathBuf> = 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<String> {
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<PathBuf> = 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<T>(&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::<Vec<_>>()
));
out.push_str(&format!(
"macros {:?}\n",
ws.candidates().macros("").iter().map(|m| &m.name).collect::<Vec<_>>()
));
let mut reachable: Vec<String> = ws
.index()
.files()
.iter()
.map(|path| {
let mut hops: Vec<String> = 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<String> {
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");
+24 -15
View File
@@ -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));
+53 -4
View File
@@ -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<FileFacts>, 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<Item = (PathBuf, &'a str)>,
) -> 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<T>(files: impl IntoIterator<Item = (PathBuf, T)>) -> 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);
+116
View File
@@ -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<FileFacts> {
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
+15 -3
View File
@@ -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
+13
View File
@@ -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
+592
View File
@@ -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<FileFacts>, gone: &[PathBuf]);
// generic in what rides beside the path, so an owning caller gets the same order
pub fn index_order<T>(files: impl IntoIterator<Item = (PathBuf, T)>) -> 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<PathBuf>);
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<String>;
}
```
**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<String>)>);
}
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<String>` 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<Message>`
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.
+50
View File
@@ -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