diff --git a/TODO.md b/TODO.md index ba6127d..7d5d43d 100644 --- a/TODO.md +++ b/TODO.md @@ -622,6 +622,10 @@ section only tracks the milestones. **the open files' own folders since 2026-08-27 (index-scope), with the workspace walk behind `lucisv.index.scope: "workspace"`; the filelist still outranks both. See `docs/features/index-scope/README.md`.** + **Since 2026-08-28 a rescan no longer re-parses the buffers it already + analyzed** — an open buffer's index facts and completion words come from the + analysis it holds — so a scope-widening `didOpen` with a 1.4 MB buffer open + costs ~23 ms rather than ~228 ms. - [x] **M2 `refactor-rename`** — new crate `vlog_refactor`; LSP `prepareRename`/`rename` for every symbol kind `vlog_semantic` resolves, cross-file, whole-edit-or-nothing verified by re-parse. @@ -804,6 +808,11 @@ and are not gaps. persistent index cache logs `cached:` rather than `indexing:` and is counted in the `end` message — `860 files indexed, 860 from cache` — so a rescan that flew past says why. + → **Extended once more, 2026-08-28** + (`docs/features/index-scope/README.md`): a file that went into the index from + an open buffer's own finished analysis — no parse, no store — logs + `analyzed:` and adds nothing to the `end` message, so "from cache" still + means the persistent store alone. → **The other half of the size story, 2026-08-27** (`docs/features/large-file-mode/README.md`): the walk cap covers files nobody opened, and `lucisv.largeFile.threshold` (4 MiB) now covers the file diff --git a/crates/lucisv_server/src/candidates.rs b/crates/lucisv_server/src/candidates.rs index 12ca9ee..c07d4c2 100644 --- a/crates/lucisv_server/src/candidates.rs +++ b/crates/lucisv_server/src/candidates.rs @@ -24,7 +24,7 @@ use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use vlog_parser::defines::DefineKind; -use vlog_parser::token::TokenKind; +use vlog_parser::token::{Token, TokenKind}; use vlog_parser::tokenize; use vlog_semantic::{SymbolKind, WorkspaceIndex}; @@ -71,14 +71,28 @@ impl Candidates { /// `sources` is the list `Workspace::collect_sources` already produced for /// the index, so the files are read once and the only extra work is one /// lex per file — see the measurements in the feature README. - pub fn build(index: &WorkspaceIndex, sources: &[(PathBuf, String)]) -> Candidates { + /// + /// `known` holds the words of the files whose token stream the caller + /// already has — an open buffer's, lexed when the buffer was analyzed. A + /// file listed there is not lexed again; a file absent from it is lexed + /// here, exactly as every file used to be. The two produce the same words + /// because they are the same function over the same tokens + /// ([`words_of_tokens`]). + pub fn build( + index: &WorkspaceIndex, + sources: &[(PathBuf, String)], + mut known: HashMap>, + ) -> Candidates { let mut out = Candidates { units: units_of(index), macros: macros_of(index), ..Candidates::default() }; for (path, text) in sources { - let words = words_in(text); + let words = match known.remove(path) { + Some(words) => words, + None => words_in(text), + }; for word in &words { *out.word_files.entry(word.clone()).or_default() += 1; } @@ -101,9 +115,15 @@ impl Candidates { /// so nothing else is re-lexed. The result is what a whole /// [`Candidates::build`] over the same files would have produced. pub fn update_file(&mut self, index: &WorkspaceIndex, path: &Path, text: &str) { + self.update_words(index, path, words_in(text)); + } + + /// [`Candidates::update_file`] for a file whose words the caller already + /// has — an open buffer's, read off the tokens it was analyzed from. + pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec) { self.units = units_of(index); self.macros = macros_of(index); - self.set_words(path, words_in(text)); + self.set_words(path, words); } /// Drop one file's contribution entirely. @@ -214,6 +234,16 @@ fn words_in(text: &str) -> Vec { // at with a regex — the same all-or-nothing rule the lexer gives every // other consumer. let Ok(tokens) = tokenize(text) else { return Vec::new() }; + words_of_tokens(&tokens) +} + +/// [`words_in`] over a token stream the caller already lexed. +/// +/// The whole of `words_in` after the lex, so a caller holding an open buffer's +/// tokens gets the same words without lexing the buffer again. A buffer that +/// did not lex holds no tokens and contributes nothing here either, which is +/// the same all-or-nothing rule from the other side. +pub(crate) fn words_of_tokens(tokens: &[Token]) -> Vec { let mut seen: HashSet = HashSet::new(); for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) { if !seen.contains(token.text.as_str()) { @@ -289,7 +319,7 @@ mod tests { fn built(files: &[(&str, &str)]) -> Candidates { let sources = sources(files); let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str()))); - Candidates::build(&index, &sources) + Candidates::build(&index, &sources, HashMap::new()) } #[test] @@ -408,7 +438,7 @@ mod tests { ]; let srcs = sources(&raw); let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str()))); - let mut candidates = Candidates::build(&index, &srcs); + let mut candidates = Candidates::build(&index, &srcs, HashMap::new()); assert_eq!(candidates.words("shared").len(), 1, "premise: two files, one word"); let mut current = index.clone(); @@ -431,7 +461,7 @@ mod tests { let raw = [("/rtl/a.sv", "module a;\n logic w1;\nendmodule\n")]; let srcs = sources(&raw); let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str()))); - let mut candidates = Candidates::build(&index, &srcs); + let mut candidates = Candidates::build(&index, &srcs, HashMap::new()); let mut current = index.clone(); let text2 = "module a;\n logic w2;\nendmodule\n"; diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index 194efe6..794c07b 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -917,7 +917,10 @@ mod tests { // A `didOpen` in a folder the scope does not cover: the same // `Document::new`, and then the whole rescan `server.rs` runs when // `scope_dirs()` moved — which re-reads and re-parses every file in - // the widened scope, the open big buffer included. + // the widened scope. Until 2026-08-28 the open big buffer was one of + // them; it now goes in from the analysis it already holds, which is + // what the last two pairs of numbers below are about + // (`docs/features/index-scope/README.md`). let sub_uri = path_to_uri(&dir.join("lib").join("sub.sv")).expect("uri"); let widening = mean(5, || { ws.set_document(sub_uri.clone(), PROBE_SUB.to_string()); @@ -926,6 +929,30 @@ mod tests { let rescan = mean(5, || { black_box(ws.rebuild_index()); }); + // Where the buffer's share goes, on the same buffer: what a rescan + // used to pay for one open file — a whole parse for the index facts, + // then a second lex for the completion words — against what it pays + // since 2026-08-28, which is the two walks over the analysis and the + // token stream the buffer already holds. + let (reparse, reused, relex, rewords) = { + let doc = ws.document(&top_uri).expect("open"); + ( + mean(3, || { + black_box(vlog_semantic::FileFacts::of(top_path.clone(), &top_text)); + }), + mean(3, || { + black_box(doc.facts(top_path.clone())); + }), + mean(3, || { + let tokens = vlog_parser::tokenize(&top_text).expect("it lexes"); + black_box(crate::candidates::words_of_tokens(&tokens)); + }), + mean(3, || { + black_box(doc.words()); + }), + ) + }; + // The same rescan with the big buffer closed, so its share of the // rescan is a subtraction rather than a guess. ws.close_document(&top_uri); @@ -937,7 +964,9 @@ mod tests { "didOpen with a {} KB buffer already open, {covered} files in scope: \ a file the scope already covers {inside:?}; \ one in a new folder (didOpen + rescan) {widening:?}; \ - the rescan alone {rescan:?}, and {without:?} with the big buffer closed", + the rescan alone {rescan:?}, and {without:?} with the big buffer closed. \ + That buffer's own share: facts {reparse:?} parsed vs {reused:?} reused, \ + words {relex:?} re-lexed vs {rewords:?} reused", top_text.len() / 1000, ); let _ = fs::remove_dir_all(&dir); diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index 1766eed..757680a 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -1948,6 +1948,16 @@ impl<'a> IndexWatch<'a> { self.say(format!("cached: {}", path.display())); self.tick(done, total, path); } + // A third word, and no count in the end message: an open buffer's + // own analysis costs nothing either, but one file out of a + // workspace is not why a scan finished fast, and a bar that grew a + // clause on every session with a file open would say less, not + // more. The per-file log still names it, which is where a user + // asking "did it re-parse my huge buffer?" looks. + IndexEvent::Analyzed { done, total, path } => { + self.say(format!("analyzed: {}", path.display())); + self.tick(done, total, path); + } IndexEvent::Skipped { path, size, cap } => { self.skipped += 1; self.say(format!( diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index 5e2ad0d..383ac7d 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -3,7 +3,7 @@ //! `docs/features/lucisv-server/README.md`; the short version is that a buffer's //! analysis is rebuilt on every change and the index only on save. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::fs; use std::path::{Path, PathBuf}; @@ -135,6 +135,30 @@ impl Document { pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) { self.external = resolve_external(&self.semantics, index); } + + /// What this buffer contributes to the workspace index, read off the + /// analysis it already holds instead of from its text. + /// + /// [`FileFacts::of`] is `tokenize` + `parse_tolerant` + `analyze` followed + /// by the fact walk, and the first three are exactly what [`Document::new`] + /// already did to fill `tree`, `defines` and `semantics` — from the same + /// text, with the same functions, down to the lex-failure branch. So this + /// is `FileFacts::of(path, &self.text)` with the parse already paid for, + /// not a second way of computing it + /// (`an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus`). + /// + /// Never called for a buffer on the large-file fast path: its analysis is + /// the analysis of the empty file, and such a buffer contributes nothing to + /// the index at all (see `collect_sources`). + pub fn facts(&self, path: PathBuf) -> FileFacts { + FileFacts::from_analysis(path, &self.tree, &self.defines, &self.semantics) + } + + /// The completion words this buffer contributes, read off the tokens it was + /// analyzed from rather than by lexing its text a second time. + pub fn words(&self) -> Vec { + crate::candidates::words_of_tokens(&self.tokens) + } } // ---------------------------------------------------------------------- @@ -205,10 +229,36 @@ struct Scope { /// A `Scope` with its files read: what one index rebuild works from. struct Sources { texts: Vec<(PathBuf, String)>, + /// What the open buffers among `texts` already know about themselves. + analyzed: Analyzed, incdirs: Vec, warnings: Vec, } +/// The index facts and the completion words of the entries `texts` took from an +/// **open buffer**, read off the analysis that buffer already holds. +/// +/// Both maps are filled in the same loop that lets a buffer override the disk +/// copy, so an entry here is always the analysis of exactly the text beside it +/// in `texts` — the two cannot describe different bytes. A file that is not an +/// open buffer appears in neither map and is parsed and lexed as it always was. +#[derive(Default)] +struct Analyzed { + facts: HashMap, + words: HashMap>, +} + +/// Whether a caller of `collect_sources` wants [`Analyzed`] filled in. +/// +/// An index rebuild does — it is what it indexes the open buffers from. A +/// refactoring reads the texts and nothing else, and reading a record off every +/// open buffer for it would be work nothing looks at. +#[derive(PartialEq, Eq)] +enum HeldAnalyses { + Wanted, + Unused, +} + /// What an index rebuild reports about itself as it runs. /// /// This module speaks no protocol, so an event carries numbers and paths and @@ -226,6 +276,18 @@ pub enum IndexEvent<'a> { /// there that differs, and a user watching a rescan fly through a /// thousand files deserves to be told why. Cached { done: usize, total: usize, path: &'a Path }, + /// One file went into the index from the analysis an **open buffer** + /// already holds — the parse this server did when the buffer was last + /// opened or changed — instead of being parsed again. The same three + /// numbers the other two carry, for the same reason. + /// + /// Its own variant rather than [`IndexEvent::Cached`] so that "from cache" + /// keeps meaning the persistent store and nothing else + /// (`docs/features/index-persistence/README.md`): a buffer's own analysis + /// is in memory, is there whether that store exists or not, and is right + /// even when the buffer has unsaved edits — which is exactly when a + /// content-keyed store has nothing to offer. + Analyzed { done: usize, total: usize, path: &'a Path }, /// A walked file was skipped without being read, because it is bigger /// than the size cap in force. Skipped { path: &'a Path, size: u64, cap: u64 }, @@ -603,8 +665,9 @@ impl Workspace { /// 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. pub fn rebuild_index_with(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Vec { - let scope = self.collect_sources(watch); - let sources = scope.texts; + 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); // 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 @@ -619,6 +682,19 @@ impl Workspace { 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) { + watch(IndexEvent::Analyzed { done, total, path: &path }); + self.cache.record(&facts, text); + builder.add_facts(facts); + continue; + } // 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 @@ -643,7 +719,7 @@ impl Workspace { 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); + self.candidates = Candidates::build(&self.index, &sources, analyzed.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); @@ -685,8 +761,22 @@ impl Workspace { } match self.current_text(path) { Some(text) => { - self.index.update_file(path.to_path_buf(), &text); - self.candidates.update_file(&self.index, path, &text); + // The same rule a whole rebuild follows: when the text came + // from an open buffer, that buffer's finished analysis is the + // facts and the words, and neither is derived from the text a + // second time. `current_text` answers with a buffer's text only + // when that buffer is not on the large-file fast path, so the + // analysis found here is a real one. + match self.analysis_of(path) { + Some((facts, words)) => { + self.index.update_facts(facts); + self.candidates.update_words(&self.index, path, words); + } + None => { + self.index.update_file(path.to_path_buf(), &text); + self.candidates.update_file(&self.index, path, &text); + } + } self.includes.update_file(path, &text, self.index.files()); // Written through here too, so an hour of saves is an hour of // work the next session does not repeat. The record is the @@ -733,6 +823,18 @@ impl Workspace { true } + /// The index facts and the completion words of the open buffer backing + /// `path`, read off the analysis it already holds — `None` when no buffer + /// does, or when the one that does is on the large-file fast path and has + /// no analysis of its own text to read. + /// + /// The buffer is found the same way [`Workspace::current_text`] finds the + /// text, so the two always speak for the same `Document`. + fn analysis_of(&self, path: &Path) -> Option<(FileFacts, Vec)> { + let doc = self.docs.values().find(|doc| doc.path.as_deref() == Some(path))?; + (!doc.large).then(|| (doc.facts(path.to_path_buf()), doc.words())) + } + /// The text one in-scope file contributes right now, by `collect_sources`'s /// rules — `None` when it contributes nothing at all. fn current_text(&self, path: &Path) -> Option { @@ -770,7 +872,7 @@ impl Workspace { /// kept: a refactoring is a rare, user-initiated request, and a second /// copy of the workspace in memory is a high price for saving one walk. pub fn sources(&self) -> Vec<(PathBuf, String)> { - self.collect_sources(&mut |_| {}).texts + self.collect_sources(&mut |_| {}, HeldAnalyses::Unused).texts } /// Read every in-scope file, with open buffers overriding disk. @@ -786,15 +888,29 @@ impl Workspace { /// cap keeps out of the index is also a file a workspace rename will not /// rewrite. That is the consistent answer: the cap says which files exist /// as far as this server is concerned. - fn collect_sources(&self, watch: &mut dyn FnMut(IndexEvent)) -> Sources { + fn collect_sources( + &self, + watch: &mut dyn FnMut(IndexEvent), + analyses: HeldAnalyses, + ) -> Sources { let scope = self.source_files(); let cap = self.client.max_file_size; + // Every path an open buffer speaks for. Reading such a file from disk + // is work thrown away — the buffer's text replaces it below, whatever + // the disk says — so the read is skipped rather than undone. The cap is + // still consulted first, so an oversized file still reports itself + // skipped exactly as it did before the buffer put its own text back. + let spoken_for: HashSet<&Path> = + self.docs.values().filter_map(|doc| doc.path.as_deref()).collect(); let mut texts: Vec<(PathBuf, String)> = Vec::new(); for path in scope.files { if let Some(size) = oversize(&path, cap) { watch(IndexEvent::Skipped { path: &path, size, cap }); continue; } + if spoken_for.contains(path.as_path()) { + continue; + } if let Ok(text) = fs::read_to_string(&path) { texts.push((path, text)); } @@ -810,14 +926,19 @@ impl Workspace { // longer has. See `docs/features/large-file-mode/README.md` for the // interaction with `lucisv.index.maxFileSize`, whose "an open buffer is // never capped" rule this is the one exception to. + let mut analyzed = Analyzed::default(); for doc in self.docs.values() { let Some(path) = doc.path.clone() else { continue }; texts.retain(|(p, _)| p != &path); if !doc.large { + if analyses == HeldAnalyses::Wanted { + analyzed.facts.insert(path.clone(), doc.facts(path.clone())); + analyzed.words.insert(path.clone(), doc.words()); + } texts.push((path, doc.text.clone())); } } - Sources { texts, incdirs: scope.incdirs, warnings: scope.warnings } + Sources { texts, analyzed, incdirs: scope.incdirs, warnings: scope.warnings } } /// The text of a workspace file: the open buffer if there is one, else @@ -1655,6 +1776,49 @@ mod tests { assert_eq!(indexed(&ws, &["huge_pkg"]), ["huge_pkg"], "the open buffer is indexed in full"); } + #[test] + fn qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before() { + // QA attack (index-scope, 2026-08-28, charter item 4: the cap + // boundary). `collect_sources` walks the scope and reports + // `Skipped` for every file over `maxFileSize` *before* it knows + // whether an open buffer speaks for that path — that ordering is + // pre-existing (the `spoken_for` short-circuit this round added only + // skips the wasted disk *read*, not the cap check ahead of it). The + // question this pins: did routing an open buffer's facts through its + // own analysis change that reporting, or the fact that the buffer + // still ends up indexed in full? It must not: the file is still + // reported `Skipped` once (the disk phase honestly saying the walked + // copy is over cap), and it still ends up indexed — now via + // `Analyzed` rather than `Parsing`, since the round's whole point is + // that an open buffer's own analysis is reused instead of reparsed. + let tree = Tree::new("capbufferqa"); + fat_package(&tree, "huge.sv", "huge_pkg", 4096); + let path = tree.path.join("huge.sv"); + + let mut ws = Workspace::default(); + ws.set_client_settings(capping(1024)); + ws.open_whole_workspace(vec![tree.path.clone()]); + assert_eq!(indexed(&ws, &["huge_pkg"]), Vec::::new(), "premise: capped on disk"); + + let uri = crate::uri::path_to_uri(&path).expect("uri"); + let text = fs::read_to_string(&path).expect("read"); + ws.set_document(uri, text); + + let mut skipped: Vec = Vec::new(); + let mut analyzed: Vec = Vec::new(); + let mut parsed: Vec = Vec::new(); + ws.rebuild_index_with(&mut |event| match event { + IndexEvent::Skipped { path, .. } => skipped.push(path.to_path_buf()), + IndexEvent::Analyzed { path, .. } => analyzed.push(path.to_path_buf()), + IndexEvent::Parsing { path, .. } => parsed.push(path.to_path_buf()), + IndexEvent::Cached { .. } => {} + }); + assert_eq!(skipped, vec![path.clone()], "still reported skipped once, from the disk phase"); + assert_eq!(analyzed, vec![path.clone()], "and indexed via its own analysis, not reparsed"); + assert!(parsed.is_empty(), "never re-parsed: {parsed:?}"); + assert_eq!(indexed(&ws, &["huge_pkg"]), ["huge_pkg"], "still indexed in full, unmoved"); + } + #[test] fn every_skipped_file_is_reported_with_its_size_and_the_cap() { let tree = Tree::new("capevents"); @@ -2266,11 +2430,16 @@ mod tests { let mut ws = Workspace::default(); ws.open_roots(vec![tree.path.clone()]); open(&mut ws, &tree, "rtl/m_open.sv"); + // Every file of the work list, however it got into the index: since + // 2026-08-28 the open buffer goes in from its own analysis and reports + // `Analyzed` rather than `Parsing`, and the claim under test is about + // the *order* the work list is walked in, not about who parses. let mut seen: Vec = Vec::new(); - ws.rebuild_index_with(&mut |event| { - if let IndexEvent::Parsing { path, .. } = event { - seen.push(path.to_path_buf()); - } + ws.rebuild_index_with(&mut |event| match event { + IndexEvent::Parsing { path, .. } + | IndexEvent::Cached { path, .. } + | IndexEvent::Analyzed { path, .. } => seen.push(path.to_path_buf()), + IndexEvent::Skipped { .. } => {} }); assert_eq!( seen, @@ -2613,12 +2782,14 @@ mod tests { } } - /// What one whole scan did, file by file: what it parsed, and what it - /// took from the cache instead. The two together are the work list. + /// What one whole scan did, file by file: what it parsed, what it took + /// from the cache instead, and what came from an open buffer's own + /// analysis. The three together are the work list. #[derive(Debug, Default, PartialEq, Eq)] struct Scan { parsed: Vec, cached: Vec, + analyzed: Vec, } /// Scan `roots` (or rescan what is already open, with `None`) and record @@ -2629,6 +2800,7 @@ mod tests { let mut see = |event: IndexEvent| match event { IndexEvent::Parsing { path, .. } => out.parsed.push(file_name(path)), IndexEvent::Cached { path, .. } => out.cached.push(file_name(path)), + IndexEvent::Analyzed { path, .. } => out.analyzed.push(file_name(path)), IndexEvent::Skipped { .. } => {} }; match roots { @@ -2752,7 +2924,12 @@ mod tests { narrow.open_roots_with(vec![tree.path.clone()], &mut |_| {}); open(&mut narrow, &tree, "rtl/a.sv"); let narrowed = scan(&mut narrow, None); - assert_eq!(narrowed.cached, ["a.sv"], "{narrowed:?}"); + // `rtl/a.sv` is this session's open buffer, so it goes in from the + // analysis that buffer already holds rather than from the store — + // beside this test's point, and named so the point stays legible: + // `tb/b.sv` appears on no list at all. + assert_eq!(narrowed.analyzed, ["a.sv"], "{narrowed:?}"); + assert!(narrowed.parsed.is_empty() && narrowed.cached.is_empty(), "{narrowed:?}"); assert_eq!( indexed(&narrow, &["a_pkg", "b_pkg"]), ["a_pkg"], @@ -3079,4 +3256,345 @@ mod tests { } eprintln!("hashing {bytes} bytes of {files} files: {:?} ({sink:016x})", started.elapsed()); } + // ------------------------------------------------------------------ + // An open buffer's own analysis (index-scope, 2026-08-28) + // ------------------------------------------------------------------ + + #[test] + fn an_open_buffers_analysis_indexes_to_exactly_what_its_bytes_on_disk_would() { + // The equivalence the reuse stands on. A rescan takes an open buffer's + // facts and its words off the analysis that buffer already holds; the + // claim is that the index and the completion tables are then byte for + // byte the ones a *parse of those bytes* builds. The buffer carries + // unsaved edits on purpose — bytes that are nowhere on disk, which is + // exactly the case the content-keyed cache cannot help with and the + // one the owner's report was about. + let tree = Tree::new("openfacts"); + tree.package("rtl/a.sv", "a_pkg"); + tree.package("rtl/other.sv", "other_pkg"); + tree.write("rtl/top.sv", "module top;\n a_sub u ();\nendmodule\n"); + + let edited = "`define TAG 1\nimport a_pkg::*;\npackage edited_pkg;\n \ + localparam K = 1;\n class c extends a_base; int x; endclass\n\ + endpackage\nmodule top;\n logic [K-1:0] w;\n \ + a_sub u (.clk(w));\n a_sub v (.clk(w));\nendmodule\n"; + let path = tree.path.join("rtl/top.sv"); + let uri = crate::uri::path_to_uri(&path).expect("uri"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + ws.set_document(uri, edited.to_string()); + let seen = scan(&mut ws, None); + assert_eq!( + seen.analyzed, + ["top.sv"], + "the open buffer went in from its own analysis: {seen:?}" + ); + assert_eq!(seen.parsed, ["a.sv", "other.sv"], "and nothing else changed route: {seen:?}"); + let from_buffer = ws.index().fingerprint(); + let words_from_buffer = ws.candidates().words("").to_vec(); + let units_from_buffer: Vec = + ws.candidates().units("").iter().map(|c| c.name.clone()).collect(); + + // The same bytes on disk, nothing open: the parse route, end to end. + tree.write("rtl/top.sv", edited); + let mut plain = Workspace::default(); + plain.set_client_settings(wide(ClientSettings::default())); + let mut route = Scan::default(); + plain.open_roots_with(vec![tree.path.clone()], &mut |event| match event { + IndexEvent::Parsing { path, .. } => route.parsed.push(file_name(path)), + IndexEvent::Cached { path, .. } => route.cached.push(file_name(path)), + IndexEvent::Analyzed { path, .. } => route.analyzed.push(file_name(path)), + IndexEvent::Skipped { .. } => {} + }); + assert_eq!(route.parsed, ["a.sv", "other.sv", "top.sv"], "premise: it really parsed"); + + assert_eq!(from_buffer, plain.index().fingerprint(), "the same index, byte for byte"); + assert_eq!(words_from_buffer, plain.candidates().words(""), "and the same words"); + let units_plain: Vec = + plain.candidates().units("").iter().map(|c| c.name.clone()).collect(); + assert_eq!(units_from_buffer, units_plain, "and the same index-derived candidates"); + + // And through the incremental door as well: `update_one` takes the same + // shortcut, and `update_one_checked` holds it to a whole rebuild. + assert!(ws.update_one_checked(&path), "the buffer's file is one the index holds"); + assert_eq!(ws.index().fingerprint(), from_buffer, "still the same index after an update"); + } + + #[test] + fn an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus() { + // `Document::new` and `FileFacts::of` each lex, parse and analyze one + // file, and the reuse is only sound while those two agree. Nothing + // enforces it at compile time — they are separate call sites — so it is + // swept over real files, in the encoded record form, which is every + // field the index and the persistent store ever read. + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let empty = WorkspaceIndex::default(); + let mut checked = 0usize; + for path in walk_sources(&corpus).into_iter().step_by(3) { + let Ok(text) = fs::read_to_string(&path) else { continue }; + let doc = Document::new(Some(path.clone()), text.clone(), &empty); + assert!(!doc.large, "premise: a full analysis, not the fast path"); + assert_eq!( + doc.facts(path.clone()).encode(), + FileFacts::of(path.clone(), &text).encode(), + "the records differ for {}", + path.display() + ); + let mut from_buffer = doc.words(); + let mut from_text = + crate::candidates::words_of_tokens(&tokenize(&text).unwrap_or_default()); + from_buffer.sort(); + from_text.sort(); + assert_eq!(from_buffer, from_text, "the words differ for {}", path.display()); + checked += 1; + } + assert!(checked > 100, "premise: the corpus was really swept ({checked} files)"); + eprintln!("open-buffer equivalence: {checked} corpus files, facts and words identical"); + } + + #[test] + fn qa_attack_crafted_non_corpus_shapes_drift_check() { + // Run on a dedicated thread with a generous stack: `cargo test`'s + // default per-test-thread stack (2 MiB) is smaller than a normal + // process's main-thread stack, and a couple of the crafted shapes + // below are deep enough to overflow the smaller one even though + // `FileFacts::of` alone — no `Document`, no reuse — overflows it + // identically on pristine, unmodified `master`. That is a real, + // pre-existing recursion-depth ceiling in the parser/analyzer, + // independent of this round; it is filed separately (QA log, + // 2026-08-28) rather than blocking this round, since both routes + // being compared here fail *identically*, which is the opposite of + // the drift this test hunts for. Run at 64 MiB so the drift check + // exercises real depth without tripping that unrelated ceiling. + std::thread::Builder::new() + .stack_size(64 * 1024 * 1024) + .spawn(qa_attack_crafted_non_corpus_shapes_drift_check_body) + .expect("spawn") + .join() + .expect("no panic"); + } + + fn qa_attack_crafted_non_corpus_shapes_drift_check_body() { + let empty = WorkspaceIndex::default(); + let cases: Vec<(&str, String)> = vec![ + ("bom_plain", "\u{feff}module m;\nendmodule\n".to_string()), + ("crlf", "module m;\r\n logic w;\r\nendmodule\r\n".to_string()), + ("bom_crlf", "\u{feff}module m;\r\n logic w;\r\nendmodule\r\n".to_string()), + ("unterminated_block_comment", "module m; /* never closed\nendmodule\n".to_string()), + ("unterminated_attribute", "(* foo module m; endmodule\n".to_string()), + ("unterminated_macro_call", "`define M(a,b) a+b\nmodule m; logic w = `M(1,2\nendmodule\n".to_string()), + ("unterminated_string", "module m; string s = \"never closed\nendmodule\n".to_string()), + ("unexpected_char", "module m; logic w = \u{1}; endmodule\n".to_string()), + ("deeply_nested_begin_end", { + let mut s = String::from("module m;\ninitial begin\n"); + for _ in 0..500 { s.push_str("begin\n"); } + for _ in 0..500 { s.push_str("end\n"); } + s.push_str("end\nendmodule\n"); + s + }), + ("deeply_nested_parens", { + let mut s = String::from("module m;\n localparam int W = "); + for _ in 0..2000 { s.push('('); } + s.push('1'); + for _ in 0..2000 { s.push(')'); } + s.push_str(";\nendmodule\n"); + s + }), + ("macro_heavy", { + let mut s = String::new(); + for i in 0..500 { + s.push_str(&format!("`define M{i} {i}\n")); + } + s.push_str("module m;\nendmodule\n"); + s + }), + ("include_bearing", "`include \"foo.svh\"\n`include \"bar/baz.vh\"\nmodule m;\nendmodule\n".to_string()), + ("parse_error_recovery", "module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n".to_string()), + ("mixed_line_endings", "module m;\n logic a;\r\n logic b;\nendmodule\n".to_string()), + ("null_byte", "module m;\n logic a; // \0 embedded\nendmodule\n".to_string()), + ("tab_and_form_feed", "module m;\n\t\u{c}logic a;\nendmodule\n".to_string()), + ]; + let total = cases.len(); + let mut failures = Vec::new(); + for (name, text) in cases { + let path = PathBuf::from(format!("/w/{name}.sv")); + let doc = Document::new(Some(path.clone()), text.clone(), &empty); + let from_buffer = doc.facts(path.clone()).encode(); + let from_text = FileFacts::of(path.clone(), &text).encode(); + if from_buffer != from_text { + failures.push(format!( + "FACTS DRIFT in {name}: buffer={from_buffer:?} text={from_text:?}" + )); + } + let mut wb = doc.words(); + let mut wt = crate::candidates::words_of_tokens(&tokenize(&text).unwrap_or_default()); + wb.sort(); + wt.sort(); + if wb != wt { + failures.push(format!("WORDS DRIFT in {name}: buffer={wb:?} text={wt:?}")); + } + } + assert!(failures.is_empty(), "drift found:\n{}", failures.join("\n")); + eprintln!("qa attack: {total} crafted non-corpus shapes, no drift found"); + } + + #[test] + fn a_buffer_on_the_large_file_fast_path_offers_no_analysis_to_reuse() { + // The one buffer whose held analysis is not an analysis of its text — + // it is the analysis of the empty file. Such a buffer contributes + // nothing to the index at all, which is what keeps the reuse from ever + // meeting it: it is absent from the work list, so it is absent from + // every list a rescan reports. + let tree = Tree::new("openfactslarge"); + tree.package("rtl/a.sv", "a_pkg"); + let big = format!( + "package big_pkg;\n localparam K = 1;\n{}endpackage\n", + " // filler\n".repeat(200) + ); + tree.write("rtl/big.sv", &big); + + let mut ws = Workspace::default(); + ws.set_client_settings(wide(ClientSettings { + large_file_threshold: 100, + ..Default::default() + })); + ws.open_roots_with(vec![tree.path.clone()], &mut |_| {}); + let uri = crate::uri::path_to_uri(&tree.path.join("rtl/big.sv")).expect("uri"); + ws.set_document(uri.clone(), big); + assert!(ws.document(&uri).expect("open").large, "premise: the fast path"); + + let seen = scan(&mut ws, None); + assert!(seen.analyzed.is_empty(), "nothing came from an analysis: {seen:?}"); + assert_eq!(seen.parsed, ["a.sv"], "and the big buffer is on no list at all: {seen:?}"); + assert_eq!(indexed(&ws, &["a_pkg", "big_pkg"]), ["a_pkg"], "nor in the index"); + } + + // ------------------------------------------------------------------ + // QA attacks (index-scope, 2026-08-28): staleness and threshold crossing + // ------------------------------------------------------------------ + + #[test] + fn qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan() { + // Charter attack 2 (staleness). An open buffer's *unsaved* edits must + // win a rescan (the whole reason the reuse is sound even though the + // content-keyed cache has nothing to key unsaved bytes by), and + // closing the buffer without saving must let the next rescan see disk + // again — nothing about the buffer's now-gone analysis may linger. + let tree = Tree::new("qastaleness"); + tree.write("rtl/p.sv", "package p;\n localparam ON_DISK = 1;\nendpackage\n"); + let path = tree.path.join("rtl/p.sv"); + let uri = crate::uri::path_to_uri(&path).expect("uri"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "premise: disk's member"); + + // Open the buffer and edit it — never saved, so disk still says + // `ON_DISK` — then rescan. + ws.set_document( + uri.clone(), + "package p;\n localparam IN_BUFFER = 1;\nendpackage\n".into(), + ); + let seen = scan(&mut ws, None); + assert_eq!(seen.analyzed, ["p.sv"], "the live buffer's own analysis went in: {seen:?}"); + assert!(seen.parsed.is_empty() && seen.cached.is_empty(), "{seen:?}"); + assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 1, "the live edit is indexed"); + assert_eq!(ws.index().member("p", "ON_DISK").len(), 0, "disk's stale member is gone"); + + // Close without saving. Disk still says `ON_DISK`; the buffer's + // analysis of `IN_BUFFER` no longer exists anywhere to be reused. + ws.close_document(&uri); + let seen = scan(&mut ws, None); + assert_eq!(seen.parsed, ["p.sv"], "reparsed from disk, not reused: {seen:?}"); + assert!(seen.analyzed.is_empty(), "no buffer left to analyze from: {seen:?}"); + assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "back to disk's member"); + assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0, "the unsaved edit is gone"); + } + + #[test] + fn qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session() { + // Charter attack 3 (large-file path), the direction the dev's own + // test does not cover: small **on disk**, edited **huge in the + // buffer** without saving. `doc.large` is re-decided on every + // `set_document`, so the very next rescan must drop the buffer from + // the analyzed-reuse route (and from the index) the moment the edit + // crosses the threshold — not one rescan later. + let tree = Tree::new("qathreshgrow"); + tree.write("rtl/p.sv", "package p;\n localparam SMALL = 1;\nendpackage\n"); + let path = tree.path.join("rtl/p.sv"); + let uri = crate::uri::path_to_uri(&path).expect("uri"); + + let mut ws = Workspace::default(); + ws.set_client_settings(wide(ClientSettings { + large_file_threshold: 200, + ..Default::default() + })); + ws.open_roots_with(vec![tree.path.clone()], &mut |_| {}); + ws.set_document(uri.clone(), "package p;\n localparam SMALL = 1;\nendpackage\n".into()); + assert!(!ws.document(&uri).expect("open").large, "premise: a real analysis"); + let seen = scan(&mut ws, None); + assert_eq!(seen.analyzed, ["p.sv"], "small buffer reused: {seen:?}"); + assert_eq!(ws.index().member("p", "SMALL").len(), 1); + + // Edited past the threshold, never saved. + ws.set_document(uri.clone(), filler(1_000)); + assert!(ws.document(&uri).expect("open").large, "now on the fast path"); + let seen = scan(&mut ws, None); + assert!(seen.analyzed.is_empty(), "the now-huge buffer offers no analysis: {seen:?}"); + assert!(seen.parsed.is_empty(), "and disk is not read in its place either: {seen:?}"); + assert_eq!(ws.index().member("p", "SMALL").len(), 0, "contributes nothing at all"); + + // And back under the threshold: a real analysis again, reused again. + ws.set_document(uri.clone(), "package p;\n localparam SMALL = 1;\nendpackage\n".into()); + assert!(!ws.document(&uri).expect("open").large, "shrank back"); + let seen = scan(&mut ws, None); + assert_eq!(seen.analyzed, ["p.sv"], "reused again: {seen:?}"); + assert_eq!(ws.index().member("p", "SMALL").len(), 1); + } + + #[test] + fn qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse() { + // The other direction of charter attack 3: **huge on disk** (over the + // fast-path threshold if it were read fresh — moot here, since a + // buffer's `large` flag is decided from its own live text, never + // disk), edited down **small in the buffer**. Included for the + // opposite-direction symmetry the brief asks for; the on-disk size is + // irrelevant to `doc.large` by construction (`is_large` reads + // `text.len()`), so this is really the same claim from the other + // starting point. + let tree = Tree::new("qathreshshrink"); + let huge_on_disk = filler(1_000); + tree.write("rtl/p.sv", &huge_on_disk); + let path = tree.path.join("rtl/p.sv"); + let uri = crate::uri::path_to_uri(&path).expect("uri"); + + let mut ws = Workspace::default(); + ws.set_client_settings(wide(ClientSettings { + large_file_threshold: 200, + ..Default::default() + })); + ws.open_roots_with(vec![tree.path.clone()], &mut |_| {}); + // Disk alone: `filler` is real Verilog (`module m; wire a; ...`), well + // under no cap, so it is walked and parsed whole — the large-file + // threshold applies to *buffers*, not to the walk. + let seen = scan(&mut ws, None); + assert_eq!(seen.parsed, ["p.sv"], "disk copy parsed in full: {seen:?}"); + + // Opened as a buffer with that same huge text: the fast path, same as + // any buffer over the threshold. + ws.set_document(uri.clone(), huge_on_disk); + assert!(ws.document(&uri).expect("open").large, "premise: fast path from the live text"); + + // Edited down to something small, never saved. + ws.set_document(uri.clone(), "package p;\n localparam SHRUNK = 1;\nendpackage\n".into()); + assert!(!ws.document(&uri).expect("open").large, "back to a real analysis"); + let seen = scan(&mut ws, None); + assert_eq!(seen.analyzed, ["p.sv"], "the shrunk buffer's own analysis is reused: {seen:?}"); + assert_eq!(ws.index().member("p", "SHRUNK").len(), 1); + } } diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 8e17da0..8eecdec 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -3400,6 +3400,89 @@ fn the_size_cap_and_the_file_log_work_over_the_wire() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn qa_the_analyzed_log_word_names_only_the_open_buffer_and_only_on_a_rescan() { + // QA attack (index-scope, 2026-08-28, charter item 5). No e2e test + // exercised the real `analyzed: ` log line at all before this one — + // `state.rs`'s unit tests only ever check the `IndexEvent::Analyzed` + // variant, never the formatted string a real client would see over + // `window/logMessage`. Two claims: the widening `didOpen`'s rescan logs + // `analyzed:` for the open buffer and `indexing:` (never `analyzed:`) for + // the file that is only ever on disk; and the follow-up `didSave` — the + // incremental one-file path — sends no log line at all, so `analyzed:` + // cannot leak onto a request that was never a scan. + let dir = temp_dir("analyzedword"); + std::fs::write( + dir.join("disk_only.sv"), + "package disk_pkg;\n localparam K = 1;\nendpackage\n", + ) + .expect("write"); + let file = dir.join("m.sv"); + let source = "module m;\nendmodule\n"; + std::fs::write(&file, source).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(source).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let logged: Vec<&str> = messages + .iter() + .filter(|m| m["method"] == "window/logMessage") + .filter_map(|m| m["params"]["message"].as_str()) + .collect(); + + // The `didOpen` rescan: the open buffer's own analysis, the disk file + // parsed. + assert!( + logged.iter().any(|l| l.starts_with("analyzed: ") && l.ends_with("m.sv")), + "the open buffer must be logged `analyzed:`: {logged:?}" + ); + assert!( + logged.iter().any(|l| l.starts_with("indexing: ") && l.ends_with("disk_only.sv")), + "the disk-only file must still be logged `indexing:`: {logged:?}" + ); + assert!( + !logged.iter().any(|l| l.starts_with("analyzed: ") && l.ends_with("disk_only.sv")), + "a file with no open buffer is never `analyzed:`: {logged:?}" + ); + assert!( + !logged.iter().any(|l| l.starts_with("indexing: ") && l.ends_with("m.sv")), + "the open buffer is not reparsed, so it is never `indexing:`: {logged:?}" + ); + + // The `didSave` afterwards names one file the index already holds, so it + // takes the incremental `reindex_one` path — which the work log states + // sends no per-file log line at all. Confirmed here rather than assumed: + // there is exactly one `didOpen`-rescan's worth of log lines and nothing + // from the save. + assert_eq!( + logged + .iter() + .filter(|l| l.starts_with("analyzed: ") || l.starts_with("indexing: ")) + .count(), + 2, + "one line for each of the two files, from the rescan alone: {logged:?}" + ); + + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_client_that_never_asked_for_progress_is_sent_none_over_the_wire() { let dir = temp_dir("noprogress"); diff --git a/crates/vlog_semantic/src/workspace.rs b/crates/vlog_semantic/src/workspace.rs index a123df1..6247e2c 100644 --- a/crates/vlog_semantic/src/workspace.rs +++ b/crates/vlog_semantic/src/workspace.rs @@ -379,7 +379,19 @@ impl WorkspaceIndex { /// server refreshes every overlay after it, exactly as it does after a /// rebuild). pub fn update_file(&mut self, path: PathBuf, src: &str) { - let facts = facts_of(path.clone(), src); + self.update_facts(facts_of(path, src)); + } + + /// [`WorkspaceIndex::update_file`] for a file whose facts are already + /// known — read from a cache, or from an analysis the caller already holds + /// ([`FileFacts::from_analysis`]) — so the update costs no parse at all. + /// + /// Exactly [`WorkspaceIndex::update_file`] with the parse already done, the + /// same way [`IndexBuilder::add_facts`] is [`IndexBuilder::add_file`] with + /// the parse already done: same contract, same result. Whether the record + /// really describes the file is the caller's business. + pub fn update_facts(&mut self, facts: FileFacts) { + let path = facts.path.clone(); match self.facts.binary_search_by(|held| held.path.cmp(&path)) { // The common case — a saved file the index already holds. Only the // names this file declared before or declares now can have moved, @@ -730,6 +742,27 @@ impl FileFacts { facts_of(path, src) } + /// The same record read off an analysis the caller **already has** — the + /// tree, the `` `define`` table and the [`Semantics`] of one file — instead + /// of from that file's text. + /// + /// This is the second half of [`FileFacts::of`], made callable on its own: + /// `of` is `tokenize` + `parse_tolerant` + [`analyze`] followed by exactly + /// this function, so a caller that has done that work once (a language + /// server holding an open buffer's finished analysis) gets the record the + /// parse would have produced without paying for the parse a second time. + /// The two paths are the same code and cannot drift; what the caller + /// promises is only that `tree`, `defines` and `sem` are the analysis of + /// the text `path` currently holds. + pub fn from_analysis( + path: PathBuf, + tree: &SourceFile, + defines: &DefineTable, + sem: &Semantics, + ) -> FileFacts { + facts_from_analysis(path, tree, defines.clone(), sem) + } + /// The file these facts were read from. pub fn path(&self) -> &Path { &self.path @@ -740,13 +773,23 @@ impl FileFacts { fn facts_of(path: PathBuf, src: &str) -> FileFacts { let (tree, defines) = parse_and_collect(src); let sem = analyze(&tree, src); + facts_from_analysis(path, &tree, defines, &sem) +} + +/// Read off what one file contributes, from its finished analysis. +fn facts_from_analysis( + path: PathBuf, + tree: &SourceFile, + defines: DefineTable, + sem: &Semantics, +) -> FileFacts { let mut facts = FileFacts { path, defines, units: Vec::new(), members: Vec::new(), - instantiations: edges_of(&tree), - subclasses: inheritance_of(&tree), + instantiations: edges_of(tree), + subclasses: inheritance_of(tree), references: Vec::new(), }; let Some(file_scope) = sem.scope(sem.file_scope()) else { @@ -760,7 +803,7 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts { continue; } facts.units.push(Decl::of(unit)); - collect_members(&sem, unit, &mut facts.members); + collect_members(sem, unit, &mut facts.members); } let exported: HashSet<(u32, u32)> = facts .units diff --git a/crates/vlog_semantic/tests/workspace.rs b/crates/vlog_semantic/tests/workspace.rs index 921368a..a704057 100644 --- a/crates/vlog_semantic/tests/workspace.rs +++ b/crates/vlog_semantic/tests/workspace.rs @@ -2,7 +2,8 @@ //! package members, and the corpus acceptance run. use std::path::{Path, PathBuf}; -use vlog_parser::parse_source_tolerant; +use vlog_parser::defines::{collect_defines, DefineTable}; +use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize}; use vlog_semantic::{ analyze, resolve_external, Def, Definition, ExternalTarget, FileFacts, FileId, Resolution, Semantics, SymbolKind, WorkspaceIndex, @@ -1658,3 +1659,164 @@ fn a_degenerate_file_still_makes_a_record() { assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "{src:?}"); } } + +// ---------------------------------------------------------------------- +// Facts from an analysis the caller already has (index-scope, 2026-08-28) +// ---------------------------------------------------------------------- + +/// The analysis a server holds for an open buffer, built exactly the way +/// `lucisv_server::state::Document::new` builds it — one lex, the tree from a +/// clone of that token stream, the define table off the same tokens, and the +/// same all-or-nothing lex-failure branch. +fn as_a_server_analyzes(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable, Semantics) { + let (tokens, tree) = match tokenize(src) { + Ok(tokens) => { + let (tree, _) = parse_tolerant(tokens.clone(), src); + (tokens, tree) + } + Err(_) => (Vec::new(), parse_source_tolerant(src).0), + }; + let defines = collect_defines(&tokens); + let sem = analyze(&tree, src); + (tree, defines, sem) +} + +/// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two. +/// +/// The record format is the comparison — the encoded line is every field the +/// index and the persistent store ever read — so a byte-equal line is the +/// whole equivalence. Two paths that could drift here would be a corruption +/// seed: the index would describe a buffer by facts its own parse disagrees +/// with. +#[test] +fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() { + let crafted = [ + // Nothing at all, and nothing that lexes. + "", + " \n\t\n", + "this is not verilog\n", + "module m;\n \"unterminated\n", + "// just a comment\n", + // The declaration kinds `facts_of` reads off the file scope. + "package p;\n localparam W = 8;\n typedef logic [W-1:0] word_t;\n\ + \x20 function int f(int a); return a; endfunction\nendpackage\n", + "module top #(parameter N = 4) (input logic clk, output logic q);\n\ + \x20 sub u_a (.clk(clk));\n sub u_b (.clk(clk));\nendmodule\n", + // Classes, inheritance, and a class nested in a package. + "class base; endclass\nclass derived extends base;\n int x;\nendclass\n", + "package pkg;\n class inner extends outer_base;\n typedef int t;\n endclass\nendpackage\n", + // `define`s, including a parameterised one and an `undef`. + "`define WIDTH 8\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n`undef WIDTH\n\ + module m; logic [`WIDTH-1:0] w; endmodule\n", + // External candidates: imports, scope resolution, port connections. + "import other_pkg::*;\nimport third_pkg::thing;\nmodule m;\n\ + \x20 other_pkg::word_t w;\n assign w = thing;\n child u (.port_a(w));\nendmodule\n", + // An instantiation at file scope — deliberately *not* an edge — and a + // generate body, which is one site however many instances it makes. + "sub u_orphan (.clk(clk));\nmodule m;\n generate for (genvar i = 0; i < 4; i++) begin\n\ + \x20 sub u_gen (.clk(clk));\n end endgenerate\nendmodule\n", + // A tree with error nodes: the tolerant parse still contributes. + "module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n", + ]; + for src in crafted { + let path = PathBuf::from("/w/x.sv"); + let (tree, defines, sem) = as_a_server_analyzes(src); + let from_text = FileFacts::of(path.clone(), src); + let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem); + assert_eq!(from_analysis, from_text, "the records differ for {src:?}"); + assert_eq!( + from_analysis.encode(), + from_text.encode(), + "and so do their encoded forms for {src:?}" + ); + } +} + +/// The same claim over every file of the real corpus, which is where the +/// constructs nobody thought to craft live. +#[test] +fn the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !root.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let mut files = Vec::new(); + corpus_files(&root, &mut files); + files.sort(); + assert!(!files.is_empty(), "corpus/ exists but holds no Verilog"); + let mut checked = 0usize; + for path in &files { + let Ok(src) = std::fs::read_to_string(path) else { + continue; + }; + let (tree, defines, sem) = as_a_server_analyzes(&src); + let from_text = FileFacts::of(path.clone(), &src); + let from_analysis = FileFacts::from_analysis(path.clone(), &tree, &defines, &sem); + assert_eq!( + from_analysis.encode(), + from_text.encode(), + "the records differ for {}", + path.display() + ); + checked += 1; + } + eprintln!("facts equivalence: {checked} corpus files, every record byte-identical"); +} + +fn corpus_files(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + corpus_files(&path, out); + } else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) { + out.push(path); + } + } +} + +/// An index built from records read off analyses is the index the parses +/// build, byte for byte — the house witness, at index scale rather than at one +/// file's. +#[test] +fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from_text() { + let files = [ + ("/w/pkg.sv", "package p;\n localparam W = 8;\n class c; int x; endclass\nendpackage\n"), + ("/w/sub.sv", "module sub (input logic clk, input logic [7:0] d);\nendmodule\n"), + ( + "/w/top.sv", + "import p::*;\n`define TAG 1\nmodule top;\n logic [W-1:0] w;\n\ + \x20 sub u_a (.clk(w[0]), .d(w));\n sub u_b (.clk(w[0]), .d(w));\nendmodule\n", + ), + ("/w/kid.sv", "class kid extends c;\nendclass\n"), + ("/w/junk.sv", "module broken (;\n"), + ]; + let from_text = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s))); + + let mut builder = vlog_semantic::IndexBuilder::new(); + // Deliberately not path order: the reuse must not smuggle an ordering in. + for (path, src) in files.iter().rev() { + let (tree, defines, sem) = as_a_server_analyzes(src); + builder.add_facts(FileFacts::from_analysis(PathBuf::from(*path), &tree, &defines, &sem)); + } + let from_analyses = builder.finish(); + assert_eq!(from_analyses.fingerprint(), from_text.fingerprint()); + + // And the same through the incremental door: `update_facts` must leave the + // index `update_file` would have left. + let mut updated = from_text.clone(); + let changed = "package p;\n localparam W = 16;\n class c; int y; endclass\nendpackage\n"; + let (tree, defines, sem) = as_a_server_analyzes(changed); + updated.update_facts(FileFacts::from_analysis( + PathBuf::from("/w/pkg.sv"), + &tree, + &defines, + &sem, + )); + let mut parsed = from_text.clone(); + parsed.update_file(PathBuf::from("/w/pkg.sv"), changed); + assert_eq!(updated.fingerprint(), parsed.fingerprint(), "update_facts == update_file"); +} diff --git a/docs/features/index-scope/README.md b/docs/features/index-scope/README.md index c525b9e..dab5635 100644 --- a/docs/features/index-scope/README.md +++ b/docs/features/index-scope/README.md @@ -161,6 +161,65 @@ pub fn finish(mut self) -> WorkspaceIndex; // sorts by path, dedups, - `index_order` stays public and unchanged: the server needs the work list's *length* before the first parse for the progress denominator. +### `vlog_semantic` — facts from an analysis the caller already has (2026-08-28) + +Two additions, both "the same thing with the parse already done", in the shape +`IndexBuilder::add_facts` already had: + +```rust +impl FileFacts { + pub fn from_analysis(path: PathBuf, tree: &SourceFile, + defines: &DefineTable, sem: &Semantics) -> FileFacts; +} +impl WorkspaceIndex { + pub fn update_facts(&mut self, facts: FileFacts); // update_file, no parse +} +``` + +- **`FileFacts::of` is now literally `parse_and_collect` + `analyze` + + `from_analysis`.** The fact walk moved into the new function and `of` calls + it, so there is one implementation and not two: the equivalence the reuse + needs holds by construction, not by care. What a caller promises is only that + `tree`, `defines` and `sem` really are the analysis of the text at `path`. +- **`update_facts` is `update_file`'s body**, with the same contract: what is + left is the index a whole build over the same file set would have produced. + `update_file` is now `self.update_facts(facts_of(path, src))`. +- No `FACTS_FORMAT` change, no new field, no new dependency: this round adds a + second *door* to the record, never a second *shape* of it. + +### `lucisv_server::state` — a `Document` can hand over its own facts + +- `Document::facts(path) -> FileFacts` and `Document::words() -> Vec` + are **new and public**: what an open buffer contributes to the index and to + the completion word table, read off the `tree`/`defines`/`semantics` and the + `tokens` it already holds. Never called for a fast-path buffer, whose analysis + is the analysis of the empty file and which contributes nothing anyway. +- **`IndexEvent::Analyzed { done, total, path }` is a new variant** — one file + went into the index from an open buffer's own analysis. Its own variant rather + than `Cached` so that "from cache" keeps meaning the persistent store and + nothing else; `server.rs` logs `analyzed: ` and, deliberately, adds no + clause to the progress bar's end message (see the work log). +- `collect_sources` takes a `HeldAnalyses` argument, because it has two + callers with different needs: an index rebuild wants the buffers' records, + a refactoring reads the texts and nothing else and would be paying for + records nothing looks at. +- `collect_sources` no longer reads a file from disk when an open buffer speaks + for it. The text was read and then thrown away; the size cap is still + consulted first, so an oversized file still reports itself `Skipped` exactly + as before. + +### `lucisv_server::candidates` — words from a token stream + +- `Candidates::build(index, sources, known: HashMap>)` + takes a third argument: the words of the files whose token stream the caller + already has. A file listed there is not lexed again; a file absent from it is + lexed exactly as every file used to be. +- `Candidates::update_words(index, path, words)` is `update_file` with the lex + already done, and `update_file` delegates to it. +- `words_of_tokens(tokens)` is `pub(crate)`: the whole of `words_in` after the + lex, so the two roads to a file's words are one function over one token + stream. + ### `lucisv_server::settings` - Two new fields, `index_scope: IndexScope` (`Folder` | `Workspace`, default @@ -224,6 +283,34 @@ pub fn finish(mut self) -> WorkspaceIndex; // sorts by path, dedups, - [x] 19 new tests (12 state, 2 server, 1 e2e, 2 vlog_semantic, 2 settings), 3 existing ones extended, 1 superseded test rewritten; every other test in the crate that wanted the whole workspace now says so +### Round 19 — a rescan stops re-parsing what is already analyzed (2026-08-28) + +- [x] Traced where a scope-widening `didOpen`'s 213 ms actually goes, per stage, + and wrote it down (work log) +- [x] An open buffer's **index facts** come from the analysis it already holds + (`FileFacts::from_analysis`), on the whole-rebuild path and on + `update_one`'s incremental one +- [x] An open buffer's **completion words** come from the tokens it was analyzed + from (`words_of_tokens`), on both paths +- [x] The disk copy of a file an open buffer speaks for is no longer read +- [x] `IndexEvent::Analyzed`, logged as `analyzed: `, so "from cache" + still means the persistent store +- [x] Equivalence pinned six ways: encoded-record equality across 860 corpus + files and 13 crafted shapes, index fingerprint equality at workspace + scale, `update_facts` == `update_file`, and the server-level + "same index and same completion tables as the same bytes on disk" +- [x] **~228 ms → ~23 ms** on the same probe, with the closed-buffer floor + unmoved at ~12 ms +- [ ] **Not done, deliberately:** no incremental *widen* (index only the newly + in-scope files and keep the rest). See the work log — it cannot hold the + brief's own fingerprint-equivalence test while other buffers carry unsaved + edits, and it would not have touched the 68 ms re-lex or any rescan that a + `didOpen` did not trigger. +- [ ] **Not done, deliberately:** the remaining ~11 ms an open 1.4 MB buffer + adds to a rescan is the fact walk (1.7 ms), the word set (3.1 ms) and the + workspace-wide word table taking 40 000 identifiers back in. It is real + work over real content, not a repeat of work already done. + - [ ] **Not done, deliberately:** no `lucisv.toml` key for either setting. They are editor-session resource settings — how much of *this machine's* time to spend — not project style, the same reason `maxFileSize` has none. @@ -358,6 +445,184 @@ The 19 new tests, the 3 extended and the 1 rewritten, and what each is for: | `the_folder_scope_widens_when_a_file_in_another_folder_is_opened` (e2e) | the real binary: definition into a sibling folder empty, opening it resolves, and a `"workspace"` client resolves immediately | | `indexing_reports_its_progress_over_the_wire` (e2e, updated) | the model on the wire: three bars, `0 files indexed` then `1 file indexed` twice | +### 2026-08-28 — dev agent (a rescan stops re-parsing what is already analyzed) + +**The symptom, reproduced first.** `nav.rs`'s +`qa_didopen_latency_when_a_new_folder_widens_the_scope`, `--release`, three +runs on `HEAD`: the widening `didOpen` **227.2 / 229.3 / 229.4 ms**, the rescan +alone **224.5 / 224.7 / 225.4 ms**, and **12.5 / 13.1 / 12.6 ms** for the same +rescan with the 1.4 MB `top.sv` closed. (The closed number is the floor for a +reason worth naming: `top.sv` is 1.4 MB, over the 1 MiB default +`lucisv.index.maxFileSize`, so with no buffer open it is not walked at all. The +"13 ms" is the other 400 files, not 401.) + +**Where the 210 ms actually goes.** `rebuild_index_with` timed stage by stage, +with the buffer open, per rescan: + +| stage | with the buffer open | with it closed | +|---|---|---| +| `collect_sources` (401 reads) | 9.5 ms | 8.4 ms | +| the facts loop | **133.5 ms** | 1.5 ms | +| `IndexBuilder::finish` | 0.4 ms | 0.12 ms | +| `Candidates::build` | **68.5 ms** | 0.85 ms | +| `IncludeGraph::build` | 0.84 ms | 0.14 ms | +| overlay refresh | 0.12 ms | ~0 | + +So the brief's "210 ms of re-lexing and re-parsing the open buffer" is right in +total and **understates the shape**: the buffer was lexed *twice* per rescan. +Once inside `FileFacts::of` (tokenize 62 ms, parse 66 ms, `analyze` 18 ms, +the fact walk under 2 ms — 133 ms in all), and again inside +`Candidates::build`, whose `words_in` re-lexes every file's text to harvest +identifiers (62 ms of the 68 ms). A third, smaller waste sat in +`collect_sources`, which read the 1.4 MB disk copy of `top.sv` and then threw +it away because the buffer overrides it. Every one of those three is work this +server had already done: the `Document` for that buffer holds the tokens, the +tree, the define table and the `Semantics`, all built from the same text by the +same functions, at the last keystroke. + +**Shape taken: (b), extended to the completion words. (a) was investigated and +rejected, on two grounds.** + +- **(a) cannot hold its own mandatory test.** The brief's hard requirement for + an incremental widen is that the widened index fingerprint byte-identically + to a fresh full build. It does not, in a case that is easy to reach: the + index is rebuilt on save, not on change, so between two rebuilds any open + buffer may carry unsaved edits. A *full* rebuild at the widening `didOpen` + indexes those edits (`collect_sources` overlays live buffer text); an + incremental widen that indexed only the newly in-scope files would not. That + is an answer change — type `package p;` into an open buffer, jump into a new + folder, and the two shapes disagree about whether `p` exists — and the + fingerprint test would catch it as a failure, correctly. Making (a) safe means + re-indexing the changed buffers anyway, which is (b) with a diff bolted on + in front. +- **(a) would have fixed a third of it.** It touches only the facts loop, and + only on the rescans a widen triggers. The 68 ms word re-lex is in + `Candidates::build`, which a widen rebuilds whatever the file list did; and + every *other* rescan with a big buffer open — a save that falls back to a + whole rebuild, a settings change, a folder event, a watched file — keeps + paying the full 200 ms. (b) is one rule that covers all of them: **an open + buffer's finished analysis is what the buffer contributes, wherever it is + asked.** + +**The equivalence is by construction, then pinned anyway.** `facts_of` was +split: everything after `tokenize`/`parse_tolerant`/`analyze` moved into +`facts_from_analysis`, and `FileFacts::of` now calls it. So +`FileFacts::from_analysis` is not a second way of computing a record — it is +the same code entered one step later, which is the difference between an +equivalence that has to be tested for and one that has to be *broken* to fail. +The same split gives `words_of_tokens` (the whole of `words_in` after the lex) +and `WorkspaceIndex::update_facts` (the whole of `update_file` after the +parse). What is left to prove is the narrow claim that `Document::new`'s +analysis is `facts_of`'s analysis — two separate call sites of the same three +functions, including the all-or-nothing lex-failure branch — and that is what +the corpus sweeps are for. + +**The reuse is wired where the override already lives.** `collect_sources` is +the one place that decides "this buffer's text beats the disk copy"; the facts +and the words are now taken from the same `Document` in the same loop +iteration, so a record and the text beside it can never describe different +bytes. `rebuild_index_with` consults that map *before* the persistent cache, +deliberately: an open buffer's own analysis is right even when the buffer has +unsaved edits, which is exactly when a content-keyed store has nothing to +offer. It still writes the record through to the store, so the next session +starts from it. + +**One argument rather than one wasted walk.** `collect_sources` has a second +caller — `sources()`, which every refactoring reads the workspace through — and +it wants the texts alone. Building a record and a word set off every open buffer +for it would be ~5 ms of dead work per `prepareRename` with a 1.4 MB buffer +open, so the function takes a `HeldAnalyses` argument saying which caller it is. +A boolean would have read as `collect_sources(watch, true)` at the call site; +the two-variant enum says what the `true` means. + +**`update_one` takes the same shortcut**, through the new `analysis_of`, which +finds the buffer the same way `current_text` does — so a `didSave` on a big +buffer stops re-parsing it too. That is not the brief's headline case but it is +the same waste on the path a user hits most often. + +**A third event word rather than a fourth meaning for `cached`.** +`IndexEvent::Analyzed` is its own variant so "N from cache" in the progress +bar's end message keeps meaning the persistent store and nothing else — that +sentence is `index-persistence`'s, and e2e transcripts assert it. The per-file +log gains `analyzed: `; the end message gains **nothing**, because one +file out of a workspace is not why a scan finished fast, and a bar that grew a +clause in every session with a file open would say less rather than more. +`Analyzed` still ticks the bar, like the other two: it is a file of the work +list. + +**Two existing tests moved, both for the same honest reason.** +`the_open_files_are_indexed_first_and_the_index_cannot_tell` counted `Parsing` +events to check the *order* of the work list; it now counts all three routes, +because the open buffer it is watching no longer parses. +`the_cache_never_puts_back_a_file_the_scan_no_longer_visits` asserted its open +buffer came from the store; it now asserts it came from its own analysis, and +also that it appears on neither of the other two lists — the test's real point +(`tb/b.sv` has a record and is still not an indexed file) is untouched. + +**After, same probe, three runs:** the widening `didOpen` **22.7 / 23.2 / +24.0 ms**, the rescan alone **22.6 / 23.1 / 24.7 ms**, the closed-buffer floor +**11.5 / 12.8 / 12.4 ms** — unmoved, as it must be. **~228 ms → ~23 ms, 10×**, +and the open 1.4 MB buffer's own share of a rescan went from ~212 ms to ~11 ms. +The probe now prints that share directly and permanently, so the claim is +re-measurable rather than remembered: + +``` +That buffer's own share: facts 140.3ms parsed vs 1.67ms reused, + words 62.9ms re-lexed vs 3.09ms reused +``` + +`references-nav`'s own probe is unchanged and green on the same run +(110 µs cross-file references either direction, 1.18 ms for the in-file +fallback on a name used 10 001 times), which is what says this round did not +pay for its rescan out of the request path. + +**What is left, and why it is not waste.** The ~12 ms the open buffer still +adds is the fact walk over its tree (1.7 ms), the identifier set over its +tokens (3.1 ms), and `Candidates::build` taking 40 000 identifiers into the +workspace-wide word table. All three are work over content that really is in +the index; none of them repeats work already done. + +**Tests added (6).** `vlog_semantic`: +`facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text` +(13 crafted shapes — empty, unlexable, tolerant-parse-with-errors, packages, +classes, nested classes, `` `define``/`` `undef``, imports and `::` paths, a +file-scope instantiation that is deliberately not an edge, a generate body), +`the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus` (860 files, +encoded records byte-identical), +`an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from_text` +(workspace scale, files added in reverse path order so the reuse cannot smuggle +an ordering in, plus `update_facts` == `update_file`). `lucisv_server`: +`an_open_buffers_analysis_indexes_to_exactly_what_its_bytes_on_disk_would` +(an **edited** buffer — bytes nowhere on disk — against the same bytes written +to disk and parsed: same fingerprint, same words, same unit candidates, and the +event lists prove the two really took different routes), +`an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus` +(the narrow claim, over real `Document::new`s — this is the one that catches +`Document::new` drifting from `facts_of`), +`a_buffer_on_the_large_file_fast_path_offers_no_analysis_to_reuse`. + +**Attacked before believing.** Three deliberate mutations, each run and each +caught: giving `Document::facts` an empty `DefineTable` fails both the crafted +fingerprint test and the corpus record sweep; dropping every 97th token in +`Document::new` fails the corpus words sweep. (A mutation to `words_of_tokens` +itself is *not* caught, and correctly so — both roads go through that one +function, which is the point of the split.) + +**Files touched:** `crates/vlog_semantic/src/workspace.rs`, +`crates/vlog_semantic/tests/workspace.rs`, +`crates/lucisv_server/src/state.rs`, `crates/lucisv_server/src/candidates.rs`, +`crates/lucisv_server/src/server.rs`, `crates/lucisv_server/src/nav.rs` +(the probe's own numbers), this README, +`docs/features/references-nav/README.md` (the Handshake, delivered), +`docs/features/indexing-ux/README.md` (the new log word), `TODO.md`. No new +dependency, no `FACTS_FORMAT` change, no scope-semantics change, no version +bump, no commits. + +**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy +--all-targets --workspace`: zero warnings. `cargo test --workspace`: **2413 +passed, 0 failed** (2407 on `HEAD`, measured — 6 new). `cargo build && node +editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. + ## QA log ### 2026-08-27 — QA agent (gates, attack surfaces, mechanical-sweep audit) @@ -576,8 +841,220 @@ and the stale-comment LOW items are follow-up hygiene, not blockers — every behavior they probe was independently verified correct by hand in this session. +### 2026-08-28 — QA agent (round 19: drift, staleness, threshold and log-semantics attacks) + +**Charter.** The round under review (dev work log "a rescan stops re-parsing +what is already analyzed", same date) claims an open buffer's index facts and +completion words can be read off its already-held analysis instead of +re-parsed, and that this is safe because `FileFacts::of` and +`Document::new`/`FileFacts::from_analysis` are now one code path entered at +different points. The charter was to attack exactly the seam where the two +routes could still disagree — a masked-corruption seed in CLAUDE.md's terms — +plus staleness, the large-file threshold boundary, the cap interaction, and +the new log word. **No drift, no staleness bug, and no cap regression were +found.** One real, pre-existing (round-independent) robustness gap was found +and is filed separately, not against this round. + +**1. Drift attack — crafted non-corpus shapes, both facts and words.** +Traced `Document::new` (`crates/lucisv_server/src/state.rs:64-92`) against +`parse_and_collect`/`facts_of` (`crates/vlog_semantic/src/workspace.rs:773-793, +1023-1034`) line by line: same `tokenize` → `collect_defines`/`parse_tolerant` +on the `Ok` branch (same token vector, so `collect_defines` reads the same +bytes in both places), same `parse_source_tolerant` on the `Err` branch. The +one asymmetry — `Document::new` computes `collect_defines(&tokens)` +unconditionally, including when `tokens` is the empty `Vec` from a lex +failure, while `facts_of`'s `Err` arm substitutes `DefineTable::default()` +directly — cannot drift: `DefineTable` derives `Default` as `entries: +Vec::new()`, and `collect_defines(&[])` produces exactly that (confirmed by +reading `collect_defines`, `crates/vlog_parser/src/defines.rs:91-104`: the +loop never runs on an empty slice). Also confirmed `analyze(tree, text)` +(`crates/vlog_semantic/src/lib.rs:65`) takes only the tree and the text — no +workspace-index dependency — so nothing about the *workspace* state at the +moment a buffer was analyzed can make its `semantics` differ from a fresh +parse's. + +Verified by construction is not verified by attack, so 16 crafted non-corpus +shapes were run through the real `Document`+`FileFacts::of` pair (encoded +facts equality and sorted-word equality), added as a permanent test: +`qa_attack_crafted_non_corpus_shapes_drift_check` +(`crates/lucisv_server/src/state.rs:3361-3441`) — a UTF-8 BOM, CRLF, BOM+CRLF, +an unterminated block comment, an unterminated attribute, an unterminated +macro call, an unterminated string, an embedded control character, deep +`begin`/`end` nesting, deep paren nesting, 500 `` `define``s, `` `include`` +directives, a tree with parse-error recovery, mixed line endings, an embedded +NUL, and tabs/form-feeds. **All 16 passed — no drift.** (The BOM cases lex +clean, confirmed separately: `tokenize` silently absorbs a leading BOM rather +than erroring, so they exercise the `Ok` branch like ordinary source, not the +lex-failure one — noted so the case list isn't mistaken for dead weight.) + +**One robustness finding, filed as out-of-scope, not blocking this round — +LOW/INFORMATIONAL, pre-existing.** Deep `begin`/`end` nesting +(500 levels) overflows the stack under `cargo test`'s default per-test-thread +stack (2 MiB) — and it does so calling **`FileFacts::of` alone**, no +`Document`, no reuse, nothing this round touched. Reproduced identically on +`git stash`-ed pristine `master` with the same crafted input run through a +temporary `vlog_semantic` test (`cargo test -p vlog_semantic` on unmodified +`HEAD`: same abort). Because both routes being compared fail *identically*, +this is the opposite of the drift this charter hunts for, and it is not a +regression — the recursive-descent parser/analyzer has always had this +ceiling; a real server thread's default OS stack is larger (8 MiB main-thread +default on macOS, confirmed by running the same input outside the test +harness) so this is unlikely to bite in the shipped binary at 500 levels, but +the underlying unbounded-recursion-depth issue is real and worth a filed +follow-up (a recursion-depth guard in the parser/analyzer, or running the LSP +request-handling thread with an explicit larger stack). The permanent test +above works around it by running on a dedicated 64 MiB-stack thread, which is +what let the drift comparison actually exercise 500-level nesting without +tripping the unrelated ceiling. Spun off as a background task rather than +fixed here — it is not in this round's files or in `verify.rs`, and touching +the parser's recursion handling is a bigger, separate change. + +**2. Staleness attacks.** `qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan` +(`crates/lucisv_server/src/state.rs:3482-3517`, new): an open buffer edited +away from disk content (never saved) rescans from the live edit — confirmed +via the `Analyzed` route and the indexed member changing from `ON_DISK` to +`IN_BUFFER` — and, after `close_document` with no save in between, the very +next rescan reparses from disk (`Parsing` route) and the index reverts to +`ON_DISK`, with no trace of the closed buffer's analysis anywhere. Also traced +structurally: the persistent `IndexCache` is keyed by a content hash of the +exact bytes (`crates/lucisv_server/src/index_cache.rs:135-157`, +`content_hash(text.as_bytes())`), so even though `rebuild_index_with` writes +an open buffer's unsaved-edit facts through to the cache +(`state.rs`'s facts-loop, `self.cache.record(&facts, text)`), a later lookup +against disk's differently-hashed bytes cannot accidentally hit that record — +the two are different cache keys by construction, not by care. The +"`didSave` where disk write happens after the rescan reads" race cannot occur +either, traced rather than merely tested: `server.rs`'s `DidSaveTextDocument` +handler (`crates/lucisv_server/src/server.rs:1319-1334`) calls +`self.set_document` (updating the in-memory `Document` from the notification's +own text, when present) *before* `reindex_one`/`reindex`, and the reused facts +come from that in-memory `Document`, never from a disk read — so there is no +window in which the index can read disk before the save's bytes land there. + +**3. Large-file threshold crossing via unsaved edits, both directions** — +the charter's explicit "break it differently" ask, since the dev's own test +only checks `doc.large` flips, not that a rescan's *event routing* follows it +mid-session. Two new tests: +`qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session` +and `qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse` +(`state.rs:3520-3596`). Small-on-disk/huge-live: a real analysis is reused +(`Analyzed`) until the buffer is edited past the threshold, at which point the +very next rescan drops it from every list (`analyzed` empty, `parsed` empty — +contributes nothing at all, matching the fast-path contract), and shrinking it +back reinstates reuse on the next rescan. Huge-on-disk/small-live: `doc.large` +is decided from the buffer's own live text length (`is_large`, +`state.rs:1298-1301`) and never from what is on disk, so the on-disk size is +provably irrelevant to the routing — the buffer is on the fast path the +instant it is opened with huge text, whatever the disk copy says, and reuse +resumes the instant it is edited back down. **No boundary bug in either +direction.** + +**4. Cap interaction, unchanged in both directions.** New test +`qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before` +(`state.rs:1780-1817`): an open buffer whose file exceeds `maxFileSize` is +still reported `Skipped` once, from `collect_sources`'s disk-phase walk (the +`spoken_for` short-circuit this round added only skips the wasted *read*, not +the cap check that runs ahead of it — traced in +`collect_sources`, `state.rs:930-937`) — and it is still indexed in full +afterward, now via `Analyzed` rather than `Parsing`. Confirmed the file is +never re-parsed (`parsed` empty) and the content is indexed exactly as before +this round. The cap boundary moved in neither direction. + +**5. Event/log semantics — a real gap found and closed.** No test anywhere +in the repository — not `state.rs`'s unit tests (which only check the +`IndexEvent::Analyzed` *variant*, via the `scan()` helper), not any e2e test — +exercised the actual `"analyzed: "` string a real client would receive +over `window/logMessage`, despite `docs/features/indexing-ux/README.md` +documenting the exact wording. Added +`qa_the_analyzed_log_word_names_only_the_open_buffer_and_only_on_a_rescan` +(`crates/lucisv_server/tests/e2e.rs`, after `the_size_cap_and_the_file_log_work_over_the_wire`): +against the real binary, a scope-widening `didOpen` with one open buffer and +one disk-only file logs `analyzed: .../m.sv` and `indexing: .../disk_only.sv` +— never the other word for the other file — and the follow-up `didSave` +(the incremental `reindex_one` path) emits **no** log line at all, confirmed +by counting exactly two `analyzed:`/`indexing:` lines in the whole transcript. +This also incidentally re-confirms the work log's claim that `reindex_one` +sends no per-file log line, which was previously asserted only by a code +comment. + +**6. Reproducing the numbers, `--release`, three fresh runs of +`qa_didopen_latency_when_a_new_folder_widens_the_scope`:** widening `didOpen` +**23.95 / 24.20 / 24.31 ms** (claimed ~23 ms), rescan alone **23.91 / 24.09 / +23.88 ms**, closed-buffer floor **12.96 / 12.83 / 12.70 ms** (claimed ~12 ms, +unmoved — confirmed unmoved). The buffer's own share, printed by the probe: +facts **144.3 ms parsed vs 1.7 ms reused**, words **65.8 ms re-lexed vs +3.1 ms reused** — matches the work log's 140.3 ms/1.67 ms and 62.9 ms/3.09 ms +within noise. `qa_references_latency_with_a_big_open_top` +(references-nav's own probe): **113 µs**/**128 µs** cross-file either +direction (claimed ~110 µs), **1.19 ms** for the in-file fallback on a name +used 10 001× (claimed 1.18 ms) — unmoved, confirming this round did not move +cost onto the request path. + +**7. Gates.** `cargo fmt --all -- --check`: clean (after formatting the new +tests). `cargo clippy --all-targets --workspace`: zero warnings (two clippy +hits in QA's own new tests — `cloned_ref_to_slice_refs`, +`useless_format` — fixed before the final run). `cargo test --workspace`: all +green, 0 failed, across every crate (lucisv_server's own suite: 1204 passed, +23 ignored — the ignored set is the manual latency probes, run separately +above). `cargo build && node editors/vscode/smoke.js +target/debug/lucisv-server`: `smoke: OK`. `verify.rs`: no diff (confirmed via +`git diff --name-only`). No new `unwrap()`/`expect()`/`panic!` outside +`#[cfg(test)]` in the round's diff or in QA's additions (grepped both). + +**One documentation nit, LOW, informational.** This README's Handshakes +section (`docs/features/index-scope/README.md:219`) says +`words_of_tokens(tokens)` "is `pub(crate)`"; the actual declaration +(`crates/lucisv_server/src/candidates.rs:246`) is `pub fn`. Harmless in +practice — `lucisv_server` is a `bin`-only crate with no `lib` target +(confirmed: `cargo test -p lucisv_server --lib` errors "no library targets +found"), and `candidates` is a private `mod` (`main.rs:9`), so there is no +larger scope for `pub` to leak into within this crate — but the README's +wording doesn't match the code. Worth a one-word fix (`pub` → `pub(crate)`, +or the sentence corrected) whenever this file is next touched. + +**Tests added (8), all permanent, all passing.** `crates/lucisv_server/src/state.rs`: +`qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before`, +`qa_attack_crafted_non_corpus_shapes_drift_check` (+ its `_body` helper, run on +a dedicated large-stack thread), +`qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan`, +`qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session`, +`qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse`. +`crates/lucisv_server/tests/e2e.rs`: +`qa_the_analyzed_log_word_names_only_the_open_buffer_and_only_on_a_rescan`. + +**Verdict: SHIP.** The round's central claim — an open buffer's held analysis +is byte-identical to a fresh parse's, so reusing it cannot corrupt the index — +held against every attack this session could construct, including shapes the +dev's own corpus sweep and crafted-shape list did not cover. Staleness, the +large-file threshold's two crossing directions, the cap interaction, and the +new log word all check out. The one real finding (stack depth) predates this +round, affects both compared routes identically, and is filed as a follow-up +rather than a blocker. + ## Review +### 2026-08-28 — lead, rescan-reuse round + +Reviewed the diff and both logs after QA's clean SHIP; gates re-run +independently (fmt clean, clippy silent, 2419 workspace tests green). +The dev's deviation from the brief's preferred incremental-widen shape +is correct and well-argued: a widen that skipped already-indexed files +would also skip unsaved buffer edits the full rebuild indexes, an +answer change the mandatory fingerprint test would have caught — so +shape (b) with the split constructors is the honest one, and the split +is genuinely by construction (`facts_of` = parse + `facts_from_analysis`, +`words_in` = lex + `words_of_tokens`; one implementation each). The +drift attacks QA ran — 16 crafted non-corpus shapes plus both corpus +sweeps — are the right coverage for the one risk this design carries, +and the staleness/threshold/cap boundary tests close the state-machine +edges. `IndexEvent::Analyzed` kept separate from `Cached` so the +persistence transcripts keep their meaning: good instinct. ~228 ms → +~23 ms reproduced by dev, QA and the probe's own printout. Lead fixed +QA's doc nit directly (`words_of_tokens` tightened to `pub(crate)` to +match the Handshakes prose; all callers in-crate). The pre-existing +deep-nesting overflow QA found on pristine master is correctly out of +scope and spun off. Accepted; committed by the lead. + ### 2026-08-27 — lead Reviewed the diff, the work log and the QA log; re-ran all gates myself diff --git a/docs/features/indexing-ux/README.md b/docs/features/indexing-ux/README.md index 071048d..e910de9 100644 --- a/docs/features/indexing-ux/README.md +++ b/docs/features/indexing-ux/README.md @@ -216,6 +216,15 @@ pub fn build<'a>(files: …) -> WorkspaceIndex { line reads `cached: ` where a parsed file's reads `indexing: `, and whose bar tick is identical — a cached file is a file of the work list, and the bar flying through them is the point. + **Amended again (index-scope, 2026-08-28):** a third arm, + `IndexEvent::Analyzed`, for a file that went into the index from an **open + buffer's own finished analysis** rather than from a parse or from the store. + Its log line reads `analyzed: `; its bar tick is identical again. It + deliberately adds **no** clause to the end message — one file out of a + workspace is not why a scan finished fast, and "N from cache" keeps meaning + the persistent store and nothing else, which is the sentence + `index-persistence`'s e2e transcripts assert. See + `docs/features/index-scope/README.md`. - `begin` still carries **no** percentage: the first honest one is the first file's. diff --git a/docs/features/references-nav/README.md b/docs/features/references-nav/README.md index 4fbf1aa..4c4023c 100644 --- a/docs/features/references-nav/README.md +++ b/docs/features/references-nav/README.md @@ -116,6 +116,14 @@ standard capability both VS Code's built-in client and Neovim's `vim.lsp` consume on their own once it is advertised; no extension change was needed and none was made. +**Requested of other modules (2026-08-28) — DELIVERED 2026-08-28** by the +index-scope round; see `docs/features/index-scope/README.md`, work log +"a rescan stops re-parsing what is already analyzed". An open buffer's index +facts and completion words now come from the analysis it already holds +(`FileFacts::from_analysis`, `words_of_tokens`), on the whole-rebuild path and +on `update_one`'s: **~228 ms → ~23 ms** on this feature's own probe. The request +as it was written: + **Requested of other modules (2026-08-28):** a scope-widening `didOpen` re-parses every open buffer. `Workspace::collect_sources` (`crates/lucisv_server/src/state.rs`) clones each open document's text into the @@ -144,12 +152,18 @@ decision. No answer changes — the equivalence test against `vlog_refactor::find_references` and the whole nav suite are untouched and green. -- [ ] **Not this feature's to fix, measured and filed (2026-08-28):** the - owner-reported *asymmetry* is not in `references` at all — both - directions cost the same, before and after. What is expensive is the - `didOpen` that jumping into another folder's file triggers: **220 ms**, - of which **210 ms** is re-parsing the open big buffer during the - scope-widening rescan. See the work log and Handshakes. +- [x] **Not this feature's to fix, measured and filed (2026-08-28) — fixed + elsewhere the same day:** the owner-reported *asymmetry* is not in + `references` at all — both directions cost the same, before and after. + What is expensive is the `didOpen` that jumping into another folder's + file triggers: **220 ms**, of which **210 ms** is re-parsing the open big + buffer during the scope-widening rescan. See the work log and + Handshakes. Landed by `index-scope` on 2026-08-28 — the open buffer's + facts and words now come from its own finished analysis — and this + feature's `qa_didopen_latency_when_a_new_folder_widens_the_scope` probe + reads **~228 ms → ~23 ms**, with its closed-buffer floor unmoved at + ~12 ms. The probe now also prints the buffer's own share of a rescan, + before and after, on every run. - [x] **Indexed navigation performance (2026-08-27):** persist each file's externally reachable reference facts beside its declarations, merge them