From bf9170a850791c596f3127760a638b0456fde30f Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Fri, 28 Aug 2026 21:36:55 -0700 Subject: [PATCH] A scope widen indexes the folders it added, not everything again Every F12 jump into a new folder didOpen-widened the scope and re-ran a full rescan of all folders accumulated so far, growing with browsing (opentitan, warm: 120-169 ms per jump, ~90 ms of it re-opening and decoding the whole persistent store). widen_of chooses: pure folder adds take a widen scan over only the new files (absorbed into the live index/candidates/includes, open buffers refreshed from held analyses, store handle kept, no compaction); anything else still takes the whole rescan; mid-scan defers to one whole follow-up. Jumps now cost the new folder alone (12-44 ms flat), first definition of a session 99.7 -> 0.9 ms. IncludeGraph stores edges as the filesystem answered them and re-spells on relearn so a newly scoped file lends its spelling to earlier edges. Watcher-coverage narrowing documented: watcher-less clients lose the widen's incidental disk re-read, same staleness class as the save path since 2026-08-27. QA was stopped by the owner mid-gates after its adversarial phases; lead gates run twice, green. Co-Authored-By: Claude Fable 5 --- TODO.md | 6 +- crates/lucisv_server/src/includes.rs | 138 ++++-- crates/lucisv_server/src/perf.rs | 76 +++ crates/lucisv_server/src/server.rs | 216 ++++++++- crates/lucisv_server/src/state.rs | 605 +++++++++++++++++++++++- crates/lucisv_server/tests/e2e.rs | 142 ++++++ docs/features/file-watching/README.md | 19 + docs/features/index-scope/README.md | 340 ++++++++++++- docs/features/indexing-ux/README.md | 13 +- docs/features/scan-interleave/README.md | 14 + docs/perf/README.md | 52 ++ 11 files changed, 1576 insertions(+), 45 deletions(-) diff --git a/TODO.md b/TODO.md index c32c118..9a8abe1 100644 --- a/TODO.md +++ b/TODO.md @@ -651,7 +651,11 @@ section only tracks the milestones. **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. + costs ~23 ms rather than ~228 ms. **And since 2026-08-28 a widen indexes only + the folders it added** rather than rescanning every folder reached so far, so + the wait a jump puts in front of the next request stops growing with the + session: over opentitan's 3 979 files, 120/132/137/169 ms per jump became + 22/18/12/44 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. diff --git a/crates/lucisv_server/src/includes.rs b/crates/lucisv_server/src/includes.rs index 85ff548..237d121 100644 --- a/crates/lucisv_server/src/includes.rs +++ b/crates/lucisv_server/src/includes.rs @@ -92,8 +92,21 @@ pub struct IncludeGraph { /// The `+incdir+` directories of the configured filelist, in filelist /// order. Empty when no filelist governs the workspace. incdirs: Vec, - /// Including file → the files it resolves to, in source order. + /// Including file → the files it resolves to, in source order, spelled the + /// way the index spells them. Derived from `raw` by [`IncludeGraph::respell`] + /// and never written to directly. edges: HashMap>, + /// The same edges as the *filesystem* answered them: normalized, but + /// before [`IncludeGraph::as_the_index_spells_it`] re-spells them against + /// the in-scope file list. + /// + /// Kept because which file an `` `include`` lands on is a question for the + /// disk and which *spelling* that file has is a question for the scope, and + /// only the second one moves when the scope grows. Holding the first means + /// a scope widen can re-spell every edge it already had without re-reading + /// a single file — which is what makes an incrementally widened graph + /// byte-identical to a rebuilt one (`docs/features/index-scope/README.md`). + raw: HashMap>, /// Every in-scope file, exactly as the index spells it. known: HashSet, /// Lower-cased spelling → the one in-scope file that has it, or `None` @@ -110,14 +123,9 @@ impl IncludeGraph { let paths: Vec = sources.iter().map(|(path, _)| path.clone()).collect(); graph.relearn(&paths); for (path, text) in sources { - let targets: Vec = scan(text) - .iter() - .filter_map(|include| graph.resolve(Some(path), include)) - .collect(); - if !targets.is_empty() { - graph.edges.insert(path.clone(), targets); - } + graph.rescan_edges(path, text); } + graph.respell(); graph } @@ -130,18 +138,17 @@ impl IncludeGraph { /// /// One honest limit, and the reason the incremental path in `state.rs` /// takes it only for a file that already existed: an edge of a *different* - /// file is not re-resolved. So a file appearing or vanishing does not - /// change whether some other file's `` `include "x.svh"`` resolves until - /// the next whole rebuild. For the case this is used in — one file's text - /// changed, the file set did not — there is nothing stale at all. + /// file is not re-**resolved** against the disk. So a file appearing or + /// vanishing on disk does not change whether some other file's + /// `` `include "x.svh"`` finds anything until the next whole rebuild. Every + /// held edge *is* re-spelled against the new file list, because that half + /// costs no filesystem call — see [`IncludeGraph::respell`]. For the case + /// this is used in — one file's text changed, the file set did not — there + /// is nothing stale at all. pub fn update_file(&mut self, path: &Path, text: &str, known: &[PathBuf]) { self.relearn(known); - let targets: Vec = - scan(text).iter().filter_map(|include| self.resolve(Some(path), include)).collect(); - match targets.is_empty() { - true => self.edges.remove(path), - false => self.edges.insert(path.to_path_buf(), targets), - }; + self.rescan_edges(path, text); + self.respell(); } /// [`IncludeGraph::update_file`] for a batch of files, with the `+incdir+`s @@ -159,20 +166,51 @@ impl IncludeGraph { self.incdirs = incdirs.to_vec(); self.relearn(known); for (path, text) in batch { - let targets: Vec = - scan(text).iter().filter_map(|include| self.resolve(Some(path), include)).collect(); - match targets.is_empty() { - true => self.edges.remove(*path), - false => self.edges.insert(path.to_path_buf(), targets), - }; + self.rescan_edges(path, text); } + self.respell(); } /// 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]) { self.relearn(known); - self.edges.remove(path); + self.raw.remove(path); + self.respell(); + } + + /// Read one file's `` `include``s off its text and hold where the disk says + /// each one lands. A file that includes nothing holds no entry at all, + /// which is what keeps `raw` a set of edges rather than a set of files. + fn rescan_edges(&mut self, path: &Path, text: &str) { + let targets: Vec = + scan(text).iter().filter_map(|include| self.found(Some(path), include)).collect(); + match targets.is_empty() { + true => self.raw.remove(path), + false => self.raw.insert(path.to_path_buf(), targets), + }; + } + + /// Re-derive every edge's spelling from the file list learned last. + /// + /// The cheap half of resolving an include: which file it lands on was + /// settled by the filesystem when the edge was read, and only how the index + /// spells that file depends on which files are in scope. So a scope that + /// grows re-spells what it already had here, in memory, rather than + /// re-reading and re-scanning every file it already knew about. + fn respell(&mut self) { + // Taken out and put back so the re-spelling may read the tables on + // `self` while it walks the edges — the same map, never a copy of it. + let raw = std::mem::take(&mut self.raw); + self.edges = raw + .iter() + .map(|(path, targets)| { + let spelled = + targets.iter().map(|to| self.as_the_index_spells_it(to.clone())).collect(); + (path.clone(), spelled) + }) + .collect(); + self.raw = raw; } /// Re-derive the known-file set and the folded-spelling table from the @@ -222,10 +260,29 @@ impl IncludeGraph { from: Option<&Path>, include: &Include, exists: &dyn Fn(&Path) -> bool, + ) -> Option { + self.found_as_if(from, include, exists).map(|found| self.as_the_index_spells_it(found)) + } + + /// [`IncludeGraph::resolve`] as far as the *filesystem* answers it: the + /// search rungs and `normalize`, without the index's own spelling. + /// + /// The half of an edge that only a disk change can move, which is what the + /// graph holds in `raw`. + fn found(&self, from: Option<&Path>, include: &Include) -> Option { + self.found_as_if(from, include, &|path| path.is_file()) + } + + /// [`IncludeGraph::found`] against a filesystem `exists` describes. + fn found_as_if( + &self, + from: Option<&Path>, + include: &Include, + exists: &dyn Fn(&Path) -> bool, ) -> Option { let target = Path::new(&include.target); if target.is_absolute() { - return exists(target).then(|| self.as_the_index_spells_it(normalize(target))); + return exists(target).then(|| normalize(target)); } let own = match include.system { true => None, @@ -235,7 +292,7 @@ impl IncludeGraph { .chain(self.incdirs.iter().map(PathBuf::as_path)) .map(|dir| dir.join(target)) .find(|candidate| exists(candidate)) - .map(|found| self.as_the_index_spells_it(normalize(&found))) + .map(|found| normalize(&found)) } /// A resolved path, re-spelled the way the index spells that file. @@ -287,6 +344,33 @@ impl IncludeGraph { } seen } + + /// Everything this graph answers with, as one deterministic string. + /// + /// Test-only, and the witness for "a graph widened one folder at a time is + /// the graph a whole rebuild would have produced": the two hash maps are + /// rendered in sorted order, so the comparison is of the contents and never + /// of the iteration order. + #[cfg(test)] + pub fn fingerprint(&self) -> String { + let mut out = format!("incdirs {:?}\n", self.incdirs); + let mut known: Vec<&PathBuf> = self.known.iter().collect(); + known.sort(); + out.push_str(&format!("known {known:?}\n")); + let mut folded: Vec<(&String, &Option)> = self.folded.iter().collect(); + folded.sort(); + out.push_str(&format!("folded {folded:?}\n")); + let mut edges: Vec<(&PathBuf, &Vec)> = self.edges.iter().collect(); + edges.sort(); + out.push_str(&format!("edges {edges:?}\n")); + // The unspelled edges too, so a widen that left a stale entry behind + // fails here rather than waiting for the scope to grow far enough for + // the spelling to notice. + let mut raw: Vec<(&PathBuf, &Vec)> = self.raw.iter().collect(); + raw.sort(); + out.push_str(&format!("raw {raw:?}\n")); + out + } } /// Fold `.`/`..` away so one file has one spelling, and so a resolved include diff --git a/crates/lucisv_server/src/perf.rs b/crates/lucisv_server/src/perf.rs index 8d8df75..944c37a 100644 --- a/crates/lucisv_server/src/perf.rs +++ b/crates/lucisv_server/src/perf.rs @@ -501,3 +501,79 @@ fn looking_up_one_name_against_scanning_every_symbol() { ); } } + +/// `cargo test --release -p lucisv_server perf::what_a_jump -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] +fn what_a_jump_into_a_new_folder_costs_before_and_after() { + // The owner's opentitan report, on a workspace this repository generates + // for itself: many folders, browsed one jump at a time. Both shapes are + // measured in the same run over the same tree, so the pair is a real + // before/after and not two numbers from two days. + // + // * **before** — the whole rescan a widening `didOpen` used to run: every + // file of every folder reached so far, re-read, re-hashed and re-merged. + // It grows with every jump, which is the shape the report describes. + // * **after** — the widen: the files the opened folder brings in, folded + // into the index beside what is already there. + let (folders, each) = (40, 25); + let dir = std::env::temp_dir().join(format!("lucisv_perf_jump_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for folder in 0..folders { + let path = dir.join(format!("blk{folder:02}/rtl")); + std::fs::create_dir_all(&path).expect("folder"); + for file in 0..each { + std::fs::write( + path.join(format!("f{file:02}.sv")), + generated_module(&format!("b{folder:02}_f{file:02}"), 200), + ) + .expect("write"); + } + } + + // Two workspaces over the same tree, jumped through the same folders, so + // the only difference between the two columns is which path the widen + // took. Neither uses the persistent store: `cache_dir` answers `None` in + // this crate's tests unless a path is named, which is what keeps the + // measurement about the scan and not about a warm cache. + let mut whole = Workspace::default(); + whole.adopt_roots(vec![dir.clone()]); + let mut incremental = Workspace::default(); + incremental.adopt_roots(vec![dir.clone()]); + let mut rows: Vec<(usize, Duration, Duration, usize)> = Vec::new(); + for jump in 0..6 { + let path = dir.join(format!("blk{jump:02}/rtl/f00.sv")); + let uri = path_to_uri(&path).expect("uri"); + let text = std::fs::read_to_string(&path).expect("read"); + + whole.set_document(uri.clone(), text.clone()); + let started = Instant::now(); + black_box(whole.rebuild_index()); + let rescan = started.elapsed(); + + let before = incremental.scope_dirs(); + incremental.set_document(uri, text); + let added: Vec = + incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect(); + let started = Instant::now(); + let mut scan = incremental.begin_widen(&added, &mut |_| {}); + while incremental.scan_step(&mut scan, &mut |_| {}) {} + black_box(incremental.finish_scan(scan)); + let widen = started.elapsed(); + + assert_eq!( + whole.index().fingerprint(), + incremental.index().fingerprint(), + "the two columns must describe the same index, or the numbers mean nothing" + ); + rows.push((jump, rescan, widen, incremental.index().files().len())); + } + eprintln!("a jump into a new folder, {folders} folders of {each} files of 200 lines:"); + for (jump, rescan, widen, indexed) in rows { + eprintln!( + " jump {jump} ({indexed} files in scope after it): \ + whole rescan {rescan:?}, incremental widen {widen:?}" + ); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index c87506c..62dad93 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -1403,12 +1403,18 @@ impl Server { if let Ok(p) = extract::(notification) { let uri = p.text_document.uri; // Opening a file in a folder the index does not cover - // *widens the scope*, so the whole index is rebuilt; the - // rebuild rides the same bar and the same generation bump + // *widens the scope*, so the folders it added are indexed + // and folded into the index beside what is already there; + // the widen rides the same bar and the same generation bump // every other rescan trigger does. Opening one the scope // already covers changes nothing about which files exist, // and the save path still owns rebuilding. // + // Only a *pure add* takes the cheap path, and `widen_of` is + // where that is decided: anything else — a scope directory + // that left, which nothing does today — falls back to the + // whole rescan (`docs/features/index-scope/README.md`). + // // This is the rootless rule from before 2026-08-27, // generalized: rung 3 is now the default rung with a root // too, so "did this file widen the scope" is the one test, @@ -1416,10 +1422,10 @@ impl Server { // rungs, which an open buffer cannot widen. let before = self.workspace.scope_dirs(); self.set_document(uri.clone(), p.text_document.text); - if self.workspace.scope_dirs() == before { - self.publish(&uri); - } else { - self.reindex(); + match widen_of(&before, &self.workspace.scope_dirs()) { + Widen::Nothing => self.publish(&uri), + Widen::Added(dirs) => self.reindex_widened(dirs), + Widen::Whole => self.reindex(), } } } @@ -1770,6 +1776,53 @@ impl Server { true } + /// [`Server::reindex`] for a `didOpen` that only ever **added** folders to + /// the scope: index those folders and fold them in, leaving every file + /// already indexed exactly as it is. + /// + /// Everything after the scan is what a whole rescan does, for the same + /// reasons — the widen changes which names exist, so lenses, the + /// diagnostics generation and every open buffer's publish all move with it. + /// + /// **Mid-scan this defers to one whole rescan rather than widening.** A + /// scan already running holds a work list taken from the *old* scope, and + /// folding a widen into it would mean two answers to "which files exist" + /// inside one scan; the follow-up scan the flag asks for reads the + /// persistent store for everything the running scan already parsed, so it + /// is the cheap kind. This is the same flag every other mid-scan trigger + /// sets, and it is what keeps the coalescing rule one rule + /// (`docs/features/scan-interleave/README.md`). + fn reindex_widened(&mut self, added: Vec) { + if self.scanning { + self.rescan_wanted = true; + return; + } + let bar = self.begin_indexing(); + let mut scan = + self.watching(bar.as_ref(), |workspace, watch| workspace.begin_widen(&added, watch)); + // No drain between the files: a widen is a rescan a message asked for, + // and `must_wait` would hold every request queued behind it anyway. It + // is also the point of the round that there is no longer a wait worth + // interleaving — a widen indexes one folder, not the whole scope. + loop { + let step = |workspace: &mut Workspace, watch: &mut dyn FnMut(IndexEvent)| { + workspace.scan_step(&mut scan, watch) + }; + if !self.watching(bar.as_ref(), step) { + break; + } + } + let (skipped, cached) = (scan.skipped(), scan.cached()); + let warnings = self.workspace.finish_scan(scan); + self.end_indexing(bar, skipped, cached); + self.refresh_code_lenses(); + self.generation += 1; + self.report_scope(warnings); + for uri in self.workspace.open_uris() { + self.publish(&uri); + } + } + /// Rescan the workspace and republish every open buffer against the new /// index. Every caller changed what the index should contain — a save, a /// new `lucisv.exclude`/`lucisv.filelist`, a watched file changing on disk, @@ -2391,6 +2444,45 @@ fn cancelled_in(batch: &[Message]) -> HashSet { batch.iter().filter_map(cancelled_id).filter(|id| queued.contains(id)).collect() } +/// What a `didOpen` did to the index scope, and therefore which of the three +/// answers it is owed. +#[derive(Debug, PartialEq, Eq)] +enum Widen { + /// The scope did not move: the file is in a folder already covered, or the + /// rung in force is one an open buffer cannot widen (a filelist, or the + /// whole-workspace walk). Publish and index nothing. + Nothing, + /// Folders were added and nothing else changed — the cheap path, indexing + /// only what the added folders bring in + /// ([`Server::reindex_widened`]). + Added(Vec), + /// Anything else. The whole rescan, which is always a correct answer. + Whole, +} + +/// Which of the three [`Widen`] answers a move from `before` to `after` is. +/// +/// **The chooser, and it is deliberately narrow**: only a scope that grew and +/// lost nothing takes the incremental path, because that is the only shape +/// whose result is the whole rescan's by construction — a directory that left +/// the scope can take files out of the index, and working out *which* files is +/// the walk the widen exists not to do. Nothing in the server takes a directory +/// out of the folder scope today (`opened_dirs` only grows, and a `didClose` +/// costs no rescan at all), so the third arm is a rule kept rather than a case +/// reached; a future shrink gets a correct answer instead of a subtle one. +/// +/// Both lists come from `Workspace::scope_dirs`, which sorts and dedups, so +/// equality is set equality and `contains` is over a handful of directories. +fn widen_of(before: &[std::path::PathBuf], after: &[std::path::PathBuf]) -> Widen { + if before == after { + return Widen::Nothing; + } + if before.iter().any(|dir| !after.contains(dir)) { + return Widen::Whole; + } + Widen::Added(after.iter().filter(|dir| !before.contains(dir)).cloned().collect()) +} + /// The files a burst opened, in the order the client opened them. /// /// Read off the raw messages rather than off the workspace afterwards, @@ -7206,6 +7298,118 @@ mod tests { ); } + #[test] + fn widen_of_takes_the_cheap_path_for_a_pure_add_and_nothing_else() { + // The chooser, as a table. Everything but "grew and lost nothing" + // falls back to the whole rescan, which is always a correct answer. + let a = PathBuf::from("/w/a"); + let b = PathBuf::from("/w/b"); + let c = PathBuf::from("/w/c"); + let all = [a.clone(), b.clone(), c.clone()]; + + assert_eq!(widen_of(&[], &[]), Widen::Nothing, "a scope that never moved"); + assert_eq!( + widen_of(&all, &all), + Widen::Nothing, + "and one an open buffer could not widen — a filelist or the wide rung, both empty" + ); + assert_eq!( + widen_of(std::slice::from_ref(&a), &[a.clone(), b.clone()]), + Widen::Added(vec![b.clone()]), + "one folder added: only that folder is indexed" + ); + assert_eq!( + widen_of(&[], &all), + Widen::Added(all.to_vec()), + "the first open of a session adds every directory it has" + ); + assert_eq!( + widen_of(std::slice::from_ref(&b), &[a.clone(), b.clone(), c.clone()]), + Widen::Added(vec![a.clone(), c.clone()]), + "two added around one held: both, and never the held one" + ); + assert_eq!( + widen_of(&[a.clone(), b.clone()], std::slice::from_ref(&a)), + Widen::Whole, + "a directory that left is not an add: the whole rescan settles what went with it" + ); + assert_eq!( + widen_of(&[a.clone(), b.clone()], &[a, c]), + Widen::Whole, + "and a swap is a removal too, however many arrived beside it" + ); + } + + #[test] + fn a_didopen_widen_leaves_the_index_a_whole_rescan_would_have_left() { + // The round's claim, through the real dispatch: two jumps into two new + // folders, each answered by indexing only that folder, and the tables + // that come out are the ones a whole rescan produces — asked by + // running that rescan afterwards and comparing. + let tree = Tree::new("didopenwidenequal"); + tree.package("rtl/a.sv", "a"); + tree.package("rtl/a2.sv", "a2"); + tree.package("lib/b.sv", "b"); + tree.package("lib/b2.sv", "b2"); + tree.package("tb/c.sv", "c"); + + let mut session = Session::new(vec![tree.path.clone()], false); + let _ = session + .open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n"); + let _ = session + .open(&tree.path.join("lib/b.sv"), "package b;\n localparam K = 1;\nendpackage\n"); + let _ = session + .open(&tree.path.join("tb/c.sv"), "package c;\n localparam K = 1;\nendpackage\n"); + assert_eq!(session.server.workspace.index().files().len(), 5, "all three folders"); + assert_eq!(indexed(&session, "b2"), 1, "including files nobody opened"); + + let widened = session.server.workspace.index().fingerprint(); + let words = session.server.workspace.candidates().words("").to_vec(); + let includes = session.server.workspace.includes().fingerprint(); + session.server.workspace.rebuild_index(); + assert_eq!(widened, session.server.workspace.index().fingerprint(), "index"); + assert_eq!(words, session.server.workspace.candidates().words(""), "completion words"); + assert_eq!(includes, session.server.workspace.includes().fingerprint(), "include graph"); + } + + #[test] + fn a_widen_asked_for_mid_scan_defers_to_one_whole_rescan_behind_it() { + // A widen answered while a scan runs cannot fold itself in: that scan + // holds a work list taken from the *old* scope, so folding a widen + // into it would make "which files exist" mean two things inside one + // scan. It sets the same `rescan_wanted` flag every other mid-scan + // trigger sets — one more whole scan after this one, coalesced with + // whatever else asked (`docs/features/scan-interleave/README.md`). + // + // Driven directly rather than over the wire, because the wire cannot + // reach it in one step: a widen itself never drains the queue, and the + // startup scan under the folder scope indexes nothing and so never + // interleaves. The reachable route is a `didOpen` answered inside a + // long *whole* rescan, which is this flag and this call. + let tree = Tree::new("widenmidscan"); + tree.package("rtl/a.sv", "a"); + tree.package("lib/late.sv", "late"); + let mut session = Session::new(vec![tree.path.clone()], false); + let _ = session + .open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n"); + assert_eq!(indexed(&session, "a"), 1, "premise: the first folder is in scope"); + + session.server.scanning = true; + session.server.reindex_widened(vec![tree.path.join("lib")]); + assert!(session.server.rescan_wanted, "the widen was deferred, not run inside the scan"); + assert_eq!(indexed(&session, "late"), 0, "and nothing was folded into the running scan"); + + // What the running scan's own loop then does with the flag. + session.server.scanning = false; + let warnings = session.server.scan_until_settled(true); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(!session.server.rescan_wanted, "one more scan is all it was owed"); + // Not indexed, and correctly so: the deferred rescan is a *whole* one + // over the scope as it now stands, and `lib/` entered that scope only + // because a buffer was opened from it — which this test never did. + assert_eq!(indexed(&session, "late"), 0, "the scope itself did not move"); + } + #[test] fn a_folder_added_mid_session_is_indexed_and_answers_workspace_symbol() { // The whole point: "Add Folder to Workspace" used to change nothing diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index b5dcd21..b8cf665 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -301,14 +301,25 @@ enum HeldAnalyses { /// 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. + /// Whether this scan rebuilds the index or only folds newly-in-scope files + /// into it. The whole difference is in [`Workspace::finish_scan`]; every + /// step in between is the same code. + kind: ScanKind, + /// Every file this scan indexes and the text it had when the scan began, in + /// index order with the open buffers' own files first. For a widen that is + /// the newly-in-scope files plus the open buffers, not the whole scope. 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. + /// Every file that is in scope once this scan lands, 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. Equal to `work`'s paths for a whole scan; for a widen it + /// is the index's files plus `work`'s. paths: Vec, + /// What this scan takes *out* of the index, known before it starts. Empty + /// for a whole scan, which works out what left the scope from its own work + /// list once it has one ([`Workspace::finish_scan`]). + gone: Vec, /// What the open buffers among `work` already knew about themselves, taken /// from as each of them is reached. analyzed: Analyzed, @@ -331,6 +342,20 @@ pub struct Scan { cached: usize, } +/// Which of the two shapes a [`Scan`] is. +/// +/// One enum rather than two `finish` methods so a caller cannot pair the wrong +/// ending with a scan: the scan itself says how it must be landed. +#[derive(PartialEq, Eq)] +enum ScanKind { + /// Every in-scope file, and whatever the index holds that the work list + /// does not name has left the scope. + Whole, + /// Only the files a scope widen brought in, folded into the index beside + /// what is already there (`docs/features/index-scope/README.md`). + Widen, +} + impl Scan { /// How many files the size cap kept out of this scan. pub fn skipped(&self) -> usize { @@ -844,6 +869,26 @@ impl Workspace { self.finish_scan(scan) } + /// [`Workspace::begin_widen`] run to the end in one shot, the way + /// [`Workspace::rebuild_index_with`] runs a whole scan. Test-only for the + /// same reason: the server drives the three calls itself. + #[cfg(test)] + pub fn widen_index(&mut self, added: &[PathBuf]) -> Vec { + self.widen_index_with(added, &mut |_| {}) + } + + /// [`Workspace::widen_index`], watched. + #[cfg(test)] + pub fn widen_index_with( + &mut self, + added: &[PathBuf], + watch: &mut dyn FnMut(IndexEvent), + ) -> Vec { + let mut scan = self.begin_widen(added, 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. /// @@ -881,8 +926,10 @@ impl Workspace { // this one has not seen. self.cache = IndexCache::open(self.cache_dir()); Scan { + kind: ScanKind::Whole, work, paths, + gone: Vec::new(), analyzed, incdirs: scope.incdirs, warnings: scope.warnings, @@ -895,6 +942,130 @@ impl Workspace { } } + /// Take the work list for a **scope widen**: the files `added` brings into + /// scope that the index does not already hold, plus every open buffer's own + /// analysis. + /// + /// The cheap answer to a `didOpen` in a folder the scope had not reached. + /// A whole rescan re-reads, re-hashes and re-merges every file already + /// indexed to learn about a handful of new ones; this reads only the new + /// ones, and [`Workspace::finish_scan`] folds them in beside what is + /// already there. What comes out is the index, the completion tables and + /// the include graph a whole rescan would have produced — **given that the + /// disk files already indexed have not changed since they were indexed**, + /// which is the file watcher's job and is written down in + /// `docs/features/index-scope/README.md`. + /// + /// Two halves make that equivalence hold, and both are why this is not + /// simply "index the new files": + /// + /// * **every open buffer is re-indexed from the analysis it holds**, so a + /// buffer carrying unsaved edits contributes those edits exactly as a + /// whole rescan's `collect_sources` overlay would. That costs a fact walk + /// and a word set per open buffer (~5 ms for a 1.4 MB buffer, rescan-reuse + /// round) and no parse at all. + /// * **a buffer on the large-file fast path contributes nothing**, so a + /// file the index holds whose buffer has grown past the threshold is + /// taken back out — the one thing a widen removes, and the same rule + /// `collect_sources` follows. + /// + /// `added` is the directories that entered [`Workspace::scope_dirs`]; the + /// caller decides that they really are an addition and nothing else + /// (`server.rs`'s `widen_of`). + pub fn begin_widen(&mut self, added: &[PathBuf], watch: &mut dyn FnMut(IndexEvent)) -> Scan { + let held: HashSet = self.index.files().iter().cloned().collect(); + let cap = self.client.max_file_size; + let spoken_for: HashSet<&Path> = + self.docs.values().filter_map(|doc| doc.path.as_deref()).collect(); + let mut skipped = 0usize; + let mut texts: Vec<(PathBuf, String)> = Vec::new(); + // The walk of the *added* directories alone, by the same rung-3 rules + // `folder_files` follows — the whole scope is the union of these walks, + // so the files this one finds beyond what is already indexed are + // exactly the ones the widen owes. + for path in self.widened_files(added) { + // Already indexed: by another scope directory this walk overlaps, + // or by an earlier scan. Re-reading it is the cost this path + // exists to avoid. + if held.contains(&path) { + continue; + } + if let Some(size) = oversize(&path, cap) { + watch(IndexEvent::Skipped { path: &path, size, cap }); + skipped += 1; + continue; + } + if spoken_for.contains(path.as_path()) { + continue; + } + if let Ok(text) = fs::read_to_string(&path) { + texts.push((path, text)); + } + } + let mut analyzed = Analyzed::default(); + let mut gone: Vec = Vec::new(); + for doc in self.docs.values() { + let Some(path) = doc.path.clone() else { continue }; + texts.retain(|(taken, _)| taken != &path); + if doc.large { + if held.contains(&path) { + gone.push(path); + } + continue; + } + analyzed.facts.insert(path.clone(), doc.facts(path.clone())); + analyzed.words.insert(path.clone(), doc.words()); + texts.push((path, doc.text.clone())); + } + let work = self.open_first(index_order(texts)); + // A whole scan drops the view cache entire, because a rescan claims + // nothing about *which* file moved. A widen names exactly the files it + // is reading, so it drops exactly those — which keeps the cache's own + // rule ("every way a file's text can move drops its entry", + // [`Workspace::file_view`]) literally true rather than nearly so. + for (path, _) in &work { + self.views.borrow_mut().retain(|view| &view.path != path); + } + // Which files exist once this widen lands: what the index holds, less + // what it is about to lose, plus what the widen brings in. + let mut paths: Vec = + held.into_iter().filter(|path| !gone.contains(path)).collect(); + paths.extend(work.iter().map(|(path, _)| path.clone())); + paths.sort(); + paths.dedup(); + gone.sort(); + Scan { + kind: ScanKind::Widen, + work, + paths, + gone, + analyzed, + // Rung 3 is the only rung an open buffer can widen, and it names no + // `+incdir+`. Carried from the graph in hand rather than assumed + // empty, so folding a widen in never *changes* the search path. + incdirs: self.includes.incdirs().to_vec(), + // Warnings come from resolving the scope, and a widen resolves no + // filelist: rung 1 is not a scope an open buffer can widen. + warnings: Vec::new(), + at: 0, + staged: Vec::new(), + staged_at: Vec::new(), + words: HashMap::new(), + skipped, + cached: 0, + } + } + + /// The files the directories a widen added bring into scope, by the same + /// rules [`Workspace::folder_files`] applies to the whole scope — including + /// the rootless-at-depth-0 flat read. + fn widened_files(&self, added: &[PathBuf]) -> Vec { + if self.roots.is_empty() && self.client.index_scope_depth == 0 { + return sibling_files(added); + } + self.walked_files(added) + } + /// Index the next file of `scan`, reporting whether there was one. /// /// One file is the whole step: its record is taken — from the open @@ -1001,6 +1172,14 @@ impl Workspace { /// tables are a pure function of the records it holds /// ([`WorkspaceIndex::absorb`]). pub fn finish_scan(&mut self, scan: Scan) -> Vec { + match scan.kind { + ScanKind::Whole => self.finish_whole_scan(scan), + ScanKind::Widen => self.finish_widen(scan), + } + } + + /// [`Workspace::finish_scan`] for a whole scan. + fn finish_whole_scan(&mut self, scan: Scan) -> Vec { let Scan { work, incdirs, warnings, staged, words, .. } = scan; // Whatever the last scan left in the index that this one's work list // does not name is a file that is no longer in scope. @@ -1029,6 +1208,56 @@ impl Workspace { warnings } + /// [`Workspace::finish_scan`] for a widen: the same three tables, folded + /// into rather than replaced. + /// + /// Each table is landed with the batch form of the incremental update it + /// already had, which is the same one [`Workspace::publish_scan`] uses — + /// so what comes out is what a whole scan over the union of the old files + /// and the new ones would have produced. The three claims that makes, one + /// per table: + /// + /// * **the index** — [`WorkspaceIndex::absorb`] keeps the records + /// path-sorted and one to a path and merges them the way a whole build + /// does; + /// * **the completion tables** — the two index-derived ones are re-derived + /// from the index, and the word table is patched per file into the same + /// total order a whole build sorts into; + /// * **the include graph** — the known-file and folded-spelling tables are + /// relearned from the whole in-scope list and every held edge is + /// re-spelled against it ([`IncludeGraph::absorb`]), so a file that is in + /// scope for the first time can lend its spelling to an edge that was + /// resolved before it arrived. + /// + /// One thing a whole scan does that this deliberately does not: the + /// persistent store is **not compacted**. A widen does not know the live + /// set of entries — it only added to it — and the next whole rescan + /// rewrites the log anyway. + fn finish_widen(&mut self, scan: Scan) -> Vec { + let Scan { work, paths, gone, incdirs, warnings, staged, words, .. } = scan; + self.index.absorb(staged, &gone); + // Before the additions, so the two never disagree about a path that is + // in both lists — which cannot happen today (a large buffer is in + // neither `work` nor `paths`) and would be a silent wrong answer if it + // ever did. + for path in &gone { + self.candidates.remove_file(&self.index, path); + self.includes.remove_file(path, &paths); + } + let batch: Vec<(PathBuf, Vec)> = work + .iter() + .map(|(path, _)| (path.clone(), words.get(path).cloned().unwrap_or_default())) + .collect(); + self.candidates.absorb(&self.index, batch); + let texts: Vec<(&Path, &str)> = + work.iter().map(|(path, text)| (path.as_path(), text.as_str())).collect(); + self.includes.absorb(&incdirs, &paths, &texts); + for doc in self.docs.values_mut() { + doc.refresh_overlay(&self.index); + } + warnings + } + /// Rebuild the index for **one** file, leaving every other file's /// contribution exactly as it is. Reports whether it could. /// @@ -1265,7 +1494,9 @@ impl Workspace { /// * [`Workspace::update_one`] — one file re-indexed, which is exactly the /// claim that its bytes changed; /// * [`Workspace::rebuild_index_with`] — a whole rescan, which claims - /// nothing about *which* file moved, so the whole cache goes. + /// nothing about *which* file moved, so the whole cache goes; + /// * [`Workspace::begin_widen`] — a scope widen, which *does* name the + /// files it is about to read, so it drops those and leaves the rest. /// /// What survives all four is a file changed on disk with nothing telling /// this server so — and there the index's own spans are stale by the same @@ -4401,4 +4632,364 @@ mod tests { assert_eq!(seen.analyzed, ["p.sv"], "the shrunk buffer's own analysis is reused: {seen:?}"); assert_eq!(ws.index().member("p", "SHRUNK").len(), 1); } + + // ------------------------------------------------------------------ + // the incremental scope widen (docs/features/index-scope) + // ------------------------------------------------------------------ + + /// Everything a widen must leave equal to what a whole rescan leaves: the + /// index, all three completion tables, and the include graph. + /// + /// Rendered as strings so a failure names the table that moved rather than + /// reporting that two opaque values differ. + fn tables(ws: &Workspace) -> Vec<(&'static str, String)> { + let units: Vec = ws + .candidates() + .units("") + .iter() + .map(|c| format!("{} {:?} {}", c.name, c.kind, c.detail)) + .collect(); + let macros: Vec = + ws.candidates().macros("").iter().map(|m| format!("{} {}", m.name, m.detail)).collect(); + vec![ + ("index", ws.index().fingerprint()), + ("words", format!("{:?}", ws.candidates().words(""))), + ("units", format!("{units:?}")), + ("macros", format!("{macros:?}")), + ("includes", ws.includes().fingerprint()), + ] + } + + fn same_tables(widened: &Workspace, rebuilt: &Workspace, what: &str) { + for ((name, left), (_, right)) in tables(widened).into_iter().zip(tables(rebuilt)) { + assert_eq!(left, right, "{what}: the {name} table a widen left is not a rebuild's"); + } + } + + /// The directories `open` added to the scope, and the widen that indexes + /// them — the two-line spelling of what `server.rs`'s `didOpen` does. + fn widen(ws: &mut Workspace, open: impl FnOnce(&mut Workspace)) -> Vec { + let before = ws.scope_dirs(); + open(ws); + let after = ws.scope_dirs(); + let added: Vec = + after.iter().filter(|dir| !before.contains(dir)).cloned().collect(); + assert!(!added.is_empty(), "premise: this open widened the scope"); + ws.widen_index(&added); + added + } + + /// A two-folder tree with an unsaved edit, a shared header included from + /// both halves, and a name declared on each side. + fn widen_tree(name: &str) -> Tree { + let tree = Tree::new(name); + tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule top;\n wire a;\nendmodule\n"); + tree.write("rtl/defs.svh", "`define RTL_W 8\n"); + tree.package("rtl/rtl_pkg.sv", "rtl_pkg"); + tree.write("lib/sub.sv", "`include \"lib_defs.svh\"\nmodule sub;\nendmodule\n"); + tree.write("lib/lib_defs.svh", "`define LIB_W 16\n"); + tree.package("lib/lib_pkg.sv", "lib_pkg"); + tree + } + + #[test] + fn a_widen_leaves_the_tables_a_whole_rescan_would_have_left() { + let tree = widen_tree("widenequal"); + let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri"); + let sub = crate::uri::path_to_uri(&tree.path.join("lib/sub.sv")).expect("uri"); + // The hostile half: the buffer that is already open carries an edit + // that is on no disk anywhere when the widen runs. A widen that + // indexed only the new folder's files would lose `NEVER_SAVED`, which + // is the objection that stopped this shape being taken in round 19. + let edited = "module top;\n wire never_saved;\n localparam NEVER_SAVED = 1;\nendmodule\n"; + let sub_text = fs::read_to_string(tree.path.join("lib/sub.sv")).expect("read"); + + let mut incremental = Workspace::default(); + incremental.open_roots(vec![tree.path.clone()]); + incremental.set_document(top.clone(), edited.to_string()); + incremental.rebuild_index(); + assert_eq!(incremental.index().files().len(), 3, "premise: the rtl folder alone"); + widen(&mut incremental, |ws| ws.set_document(sub.clone(), sub_text.clone())); + + let mut rebuilt = Workspace::default(); + rebuilt.open_roots(vec![tree.path.clone()]); + rebuilt.set_document(top.clone(), edited.to_string()); + rebuilt.set_document(sub.clone(), sub_text.clone()); + rebuilt.rebuild_index(); + + assert_eq!(rebuilt.index().files().len(), 6, "premise: both folders"); + assert_eq!( + incremental.candidates().words("never_sav"), + ["NEVER_SAVED", "never_saved"], + "the unsaved edit is in the widened tables" + ); + same_tables(&incremental, &rebuilt, "an unsaved edit across a widen"); + } + + #[test] + fn a_widen_reads_only_the_files_the_new_folders_brought_in() { + let tree = widen_tree("widenwork"); + let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri"); + let sub_path = tree.path.join("lib/sub.sv"); + let sub = crate::uri::path_to_uri(&sub_path).expect("uri"); + let sub_text = fs::read_to_string(&sub_path).expect("read"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + ws.set_document(top.clone(), fs::read_to_string(tree.path.join("rtl/top.sv")).expect("r")); + ws.rebuild_index(); + + let mut seen = Scan::default(); + { + let mut see = |event: IndexEvent| match event { + IndexEvent::Parsing { path, .. } => seen.parsed.push(file_name(path)), + IndexEvent::Cached { path, .. } => seen.cached.push(file_name(path)), + IndexEvent::Analyzed { path, .. } => seen.analyzed.push(file_name(path)), + IndexEvent::Skipped { .. } => {} + }; + let before = ws.scope_dirs(); + ws.set_document(sub.clone(), sub_text); + let after = ws.scope_dirs(); + let added: Vec = + after.iter().filter(|dir| !before.contains(dir)).cloned().collect(); + ws.widen_index_with(&added, &mut see); + } + seen.parsed.sort(); + // The three `rtl/` files are already indexed and are not read again; + // the open buffer is refreshed from the analysis it holds, which is + // what makes an unsaved edit survive the widen. + assert_eq!(seen.parsed, ["lib_defs.svh", "lib_pkg.sv"], "{seen:?}"); + seen.analyzed.sort(); + // Both open buffers, not only the newly opened one: every buffer's + // held analysis is refreshed, which is what carries an unsaved edit + // across a widen. + assert_eq!(seen.analyzed, ["sub.sv", "top.sv"], "{seen:?}"); + assert!(seen.cached.is_empty(), "no cache in this test: {seen:?}"); + assert!(!seen.parsed.contains(&"top.sv".to_string()), "the old folder is untouched"); + assert_eq!(ws.index().files().len(), 6); + } + + #[test] + fn a_widen_bar_counts_the_new_files_and_not_the_whole_scope() { + let tree = widen_tree("widenbar"); + let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri"); + let sub_path = tree.path.join("lib/sub.sv"); + let sub = crate::uri::path_to_uri(&sub_path).expect("uri"); + let sub_text = fs::read_to_string(&sub_path).expect("read"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + ws.set_document(top, fs::read_to_string(tree.path.join("rtl/top.sv")).expect("r")); + ws.rebuild_index(); + + let mut totals: Vec = Vec::new(); + { + let mut see = |event: IndexEvent| match event { + IndexEvent::Parsing { total, .. } + | IndexEvent::Cached { total, .. } + | IndexEvent::Analyzed { total, .. } => totals.push(total), + IndexEvent::Skipped { .. } => {} + }; + let before = ws.scope_dirs(); + ws.set_document(sub, sub_text); + let added: Vec = + ws.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect(); + ws.widen_index_with(&added, &mut see); + } + // Two new files plus the two open buffers refreshed — never the six + // the scope now holds. A bar that counted the whole scope would crawl. + assert_eq!(totals, [4, 4, 4, 4], "the denominator is the widen's own work list"); + } + + #[test] + fn a_widen_into_a_folder_that_contains_the_old_one_indexes_each_file_once() { + // A file present in both the old scope portion and the new one: the + // added directory is the *parent* of the directory already in scope, + // so its walk finds everything the first scan already indexed. + let tree = Tree::new("widennested"); + tree.package("rtl/deep/a.sv", "a_pkg"); + tree.package("rtl/b.sv", "b_pkg"); + let deep = crate::uri::path_to_uri(&tree.path.join("rtl/deep/a.sv")).expect("uri"); + let shallow = crate::uri::path_to_uri(&tree.path.join("rtl/b.sv")).expect("uri"); + let deep_text = fs::read_to_string(tree.path.join("rtl/deep/a.sv")).expect("read"); + let shallow_text = fs::read_to_string(tree.path.join("rtl/b.sv")).expect("read"); + + let mut incremental = Workspace::default(); + incremental.open_roots(vec![tree.path.clone()]); + incremental.set_document(deep.clone(), deep_text.clone()); + incremental.rebuild_index(); + assert_eq!(incremental.index().files().len(), 1, "premise: rtl/deep alone"); + + let mut seen = Scan::default(); + { + let mut see = |event: IndexEvent| match event { + IndexEvent::Parsing { path, .. } => seen.parsed.push(file_name(path)), + IndexEvent::Cached { path, .. } => seen.cached.push(file_name(path)), + IndexEvent::Analyzed { path, .. } => seen.analyzed.push(file_name(path)), + IndexEvent::Skipped { .. } => {} + }; + let before = incremental.scope_dirs(); + incremental.set_document(shallow.clone(), shallow_text.clone()); + let added: Vec = incremental + .scope_dirs() + .iter() + .filter(|dir| !before.contains(dir)) + .cloned() + .collect(); + incremental.widen_index_with(&added, &mut see); + } + assert!(seen.parsed.is_empty(), "both files speak for themselves: {seen:?}"); + seen.analyzed.sort(); + assert_eq!(seen.analyzed, ["a.sv", "b.sv"], "{seen:?}"); + assert_eq!(incremental.index().files().len(), 2, "a.sv is indexed once, not twice"); + + let mut rebuilt = Workspace::default(); + rebuilt.open_roots(vec![tree.path.clone()]); + rebuilt.set_document(deep, deep_text); + rebuilt.set_document(shallow, shallow_text); + rebuilt.rebuild_index(); + same_tables(&incremental, &rebuilt, "a widen into a containing folder"); + } + + #[test] + fn a_widen_lends_a_new_files_spelling_to_an_include_resolved_before_it() { + // The include graph's own hostile case, and the reason this round + // holds each edge as the filesystem answered it: `rtl/top.sv` was + // indexed while `lib/` was out of scope, so its `` `include`` into + // `lib/` could not be spelled the way the index spells that file. The + // widen must re-spell it without re-reading `rtl/top.sv`. + let tree = Tree::new("widenspell"); + tree.write("lib/Shared.svh", "`define SHARED 1\n"); + // The include is written in the other case, which a case-insensitive + // filesystem happily opens; on a case-sensitive one it does not + // resolve at all, and both workspaces agree on that too. + tree.write("rtl/top.sv", "`include \"../lib/shared.svh\"\nmodule top;\nendmodule\n"); + tree.package("lib/lib_pkg.sv", "lib_pkg"); + let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri"); + let lib = crate::uri::path_to_uri(&tree.path.join("lib/lib_pkg.sv")).expect("uri"); + let top_text = fs::read_to_string(tree.path.join("rtl/top.sv")).expect("read"); + let lib_text = fs::read_to_string(tree.path.join("lib/lib_pkg.sv")).expect("read"); + + let mut incremental = Workspace::default(); + incremental.open_roots(vec![tree.path.clone()]); + incremental.set_document(top.clone(), top_text.clone()); + incremental.rebuild_index(); + widen(&mut incremental, |ws| ws.set_document(lib.clone(), lib_text.clone())); + + let mut rebuilt = Workspace::default(); + rebuilt.open_roots(vec![tree.path.clone()]); + rebuilt.set_document(top, top_text); + rebuilt.set_document(lib, lib_text); + rebuilt.rebuild_index(); + same_tables(&incremental, &rebuilt, "an include spelled by a file the widen brought in"); + } + + #[test] + fn a_buffer_grown_past_the_threshold_leaves_the_index_when_the_scope_widens() { + // The one thing a widen takes *out*: a buffer on the large-file fast + // path contributes nothing, exactly as `collect_sources` says, so a + // file the index holds whose buffer has grown past the threshold is + // dropped — the same answer a whole rescan gives. + let tree = Tree::new("widenlarge"); + tree.package("rtl/p.sv", "p_pkg"); + tree.package("lib/q.sv", "q_pkg"); + let small = crate::uri::path_to_uri(&tree.path.join("rtl/p.sv")).expect("uri"); + let other = crate::uri::path_to_uri(&tree.path.join("lib/q.sv")).expect("uri"); + let other_text = fs::read_to_string(tree.path.join("lib/q.sv")).expect("read"); + let huge = filler(1_000); + + let mut incremental = Workspace::default(); + incremental.set_client_settings(ClientSettings { + large_file_threshold: 200, + ..Default::default() + }); + incremental.open_roots(vec![tree.path.clone()]); + incremental.set_document(small.clone(), "package p_pkg;\nendpackage\n".into()); + incremental.rebuild_index(); + assert_eq!(incremental.index().files().len(), 1, "premise: rtl/p.sv is indexed"); + incremental.set_document(small.clone(), huge.clone()); + assert!(incremental.document(&small).expect("open").large, "premise: the fast path"); + widen(&mut incremental, |ws| ws.set_document(other.clone(), other_text.clone())); + assert_eq!( + incremental.index().files().len(), + 1, + "the grown buffer left as the new folder arrived" + ); + assert!(incremental.index().units("p_pkg").is_empty(), "and its names went with it"); + + let mut rebuilt = Workspace::default(); + rebuilt.set_client_settings(ClientSettings { + large_file_threshold: 200, + ..Default::default() + }); + rebuilt.open_roots(vec![tree.path.clone()]); + rebuilt.set_document(small, huge); + rebuilt.set_document(other, other_text); + rebuilt.rebuild_index(); + same_tables(&incremental, &rebuilt, "a buffer over the threshold at widen time"); + } + + #[test] + fn the_persistent_cache_answers_for_the_files_a_widen_brings_in() { + let tree = widen_tree("widencache"); + let store = Tree::new("widencache_store"); + let sub_path = tree.path.join("lib/sub.sv"); + let sub = crate::uri::path_to_uri(&sub_path).expect("uri"); + let sub_text = fs::read_to_string(&sub_path).expect("read"); + let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri"); + let top_text = fs::read_to_string(tree.path.join("rtl/top.sv")).expect("read"); + + // A first session fills the store with every file of both folders. + let mut first = Workspace::default(); + first.set_client_settings(wide(caching(&store.path))); + first.open_roots(vec![tree.path.clone()]); + assert_eq!(first.index().files().len(), 6, "premise: the store is filled"); + + // A second session, folder-scoped, widens into `lib/`: the files it + // brings in come from the store rather than from a parse. + let mut second = Workspace::default(); + second.set_client_settings(caching(&store.path)); + second.open_roots(vec![tree.path.clone()]); + second.set_document(top, top_text); + second.rebuild_index(); + + let mut seen = Scan::default(); + { + let mut see = |event: IndexEvent| match event { + IndexEvent::Parsing { path, .. } => seen.parsed.push(file_name(path)), + IndexEvent::Cached { path, .. } => seen.cached.push(file_name(path)), + IndexEvent::Analyzed { path, .. } => seen.analyzed.push(file_name(path)), + IndexEvent::Skipped { .. } => {} + }; + let before = second.scope_dirs(); + second.set_document(sub, sub_text); + let added: Vec = + second.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect(); + second.widen_index_with(&added, &mut see); + } + seen.cached.sort(); + assert_eq!(seen.cached, ["lib_defs.svh", "lib_pkg.sv"], "from the store: {seen:?}"); + assert!(seen.parsed.is_empty(), "nothing was parsed twice: {seen:?}"); + } + + #[test] + fn a_widen_that_adds_nothing_new_still_refreshes_the_open_buffers() { + // A widen whose added directory holds no file the index lacks — the + // degenerate case, and the one where the open-buffer refresh is the + // *whole* of the work. It must still land the buffers' current text. + let tree = Tree::new("widenempty"); + tree.package("rtl/a.sv", "a_pkg"); + fs::create_dir_all(tree.path.join("empty")).expect("dir"); + let a = crate::uri::path_to_uri(&tree.path.join("rtl/a.sv")).expect("uri"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + ws.set_document(a.clone(), "package a_pkg;\n localparam K = 1;\nendpackage\n".into()); + ws.rebuild_index(); + ws.set_document(a, "package a_pkg;\n localparam EDITED = 1;\nendpackage\n".into()); + + ws.widen_index(from_ref(&tree.path.join("empty"))); + assert_eq!(ws.index().member("a_pkg", "EDITED").len(), 1, "the live edit is indexed"); + assert_eq!(ws.index().member("a_pkg", "K").len(), 0); + } } diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index e1331dc..b675817 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -4921,3 +4921,145 @@ fn a_hover_issued_during_the_initial_scan_is_answered_during_it() { } let _ = std::fs::remove_dir_all(&dir); } + +/// A generated many-folder workspace: `folders` directories of `each` files, +/// every one declaring a package named after where it lives. +/// +/// The shape the owner's report is about — a project too big to walk, browsed +/// one folder at a time — without depending on any checkout being present. +fn many_folders(name: &str, folders: usize, each: usize) -> PathBuf { + let dir = temp_dir(name); + for folder in 0..folders { + let path = dir.join(format!("blk{folder:02}/rtl")); + std::fs::create_dir_all(&path).expect("folder"); + for file in 0..each { + std::fs::write( + path.join(format!("f{file:02}.sv")), + format!( + "package b{folder:02}_f{file:02};\n localparam WIDTH = {file};\nendpackage\n" + ), + ) + .expect("write"); + } + } + dir +} + +/// What each indexing bar read, split by where it came from: the files it read +/// off **disk** (`indexing:`), and the open buffers it took from the analysis +/// they already held (`analyzed:`). Paths are shortened to their last three +/// components, which is `/rtl/` in this fixture. +/// +/// The honest wire-level answer to "what did that scan actually do?": the +/// per-file log is `lucisv.index.logFiles`, on by default, and it names one +/// line per file the scan took. +fn work_per_bar(messages: &[serde_json::Value]) -> Vec<(Vec, Vec)> { + let mut bars: Vec<(Vec, Vec)> = Vec::new(); + let tail = |path: &str| { + let mut parts: Vec<&str> = path.rsplit('/').take(3).collect(); + parts.reverse(); + parts.join("/") + }; + for message in messages { + let kind = message["params"]["value"]["kind"].as_str(); + if message["method"] == "$/progress" && kind == Some("begin") { + bars.push((Vec::new(), Vec::new())); + } + if message["method"] == "window/logMessage" { + let Some(line) = message["params"]["message"].as_str() else { continue }; + let Some(bar) = bars.last_mut() else { continue }; + if let Some(path) = line.strip_prefix("indexing: ") { + bar.0.push(tail(path)); + } else if let Some(path) = line.strip_prefix("analyzed: ") { + bar.1.push(tail(path)); + } + } + } + bars +} + +#[test] +fn a_jump_into_a_new_folder_indexes_that_folder_and_not_the_ones_before_it() { + // The owner's opentitan report, in miniature and with no opentitan: 24 + // folders of 20 files, browsed one jump at a time. Every widening + // `didOpen` must read the folder it opened and **nothing else** — the log + // is what says so, file by file — while the answers stay exactly what the + // whole-rescan widen gave. + let dir = many_folders("widenfolders", 24, 20); + let root = format!("file://{}", dir.display()); + let file = |folder: usize, n: usize| dir.join(format!("blk{folder:02}/rtl/f{n:02}.sv")); + let uri = |folder: usize, n: usize| format!("file://{}", file(folder, n).display()); + let text = |folder: usize, n: usize| std::fs::read_to_string(file(folder, n)).expect("read"); + let open = |folder: usize, n: usize| { + format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + uri(folder, n), + serde_json::to_string(&text(folder, n)).expect("json") + ) + }; + // The cursor on `WIDTH` of the reference this file makes into another + // folder's package. + let jump = |id: u32, folder: usize, n: usize| { + format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"b{folder:02}_f{n:02}"}}}}"# + ) + }; + + 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(&open(0, 0)), + frame(&open(1, 0)), + frame(&open(2, 0)), + // A second file in a folder already reached: no bar at all. + frame(&open(2, 5)), + frame(&jump(2, 1, 7)), + frame(&jump(3, 23, 7)), + 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 bars = work_per_bar(&messages); + + // Four bars: the empty startup scan, then one per widening `didOpen`. The + // fourth `didOpen` is in a folder already covered and asks for none. + assert_eq!(bars.len(), 4, "one bar per widen and no more: {bars:#?}"); + assert_eq!( + bars[0], + (vec![], vec![]), + "the startup scan indexes nothing under the folder scope" + ); + for (folder, (read, reused)) in bars[1..].iter().enumerate() { + // **The round, on the wire.** Each jump reads the 19 disk files of the + // folder it opened — `f00.sv` there is the buffer, so it is reused + // rather than read — and never the 19, 38 or 57 of the folders reached + // before it, which is what every one of these bars re-read until now. + let mine: Vec = (1..20).map(|n| format!("blk{folder:02}/rtl/f{n:02}.sv")).collect(); + assert_eq!(read, &mine, "bar {} read the wrong files", folder + 1); + // And every open buffer is refreshed from the analysis it holds, which + // is what carries an unsaved edit across a widen. + let buffers: Vec = (0..=folder).map(|b| format!("blk{b:02}/rtl/f00.sv")).collect(); + assert_eq!(reused, &buffers, "bar {} reused the wrong buffers", folder + 1); + } + + // And the answers are the whole-rescan ones: a package in a folder that + // has been jumped into resolves, one in a folder that has not does not. + let reached = messages.iter().find(|m| m["id"] == 2).expect("a symbol response"); + assert_eq!( + reached["result"].as_array().map(Vec::len), + Some(1), + "a package in a folder the scope has reached: {reached:#?}" + ); + let unreached = messages.iter().find(|m| m["id"] == 3).expect("a symbol response"); + assert_eq!( + unreached["result"].as_array().map(Vec::len), + Some(0), + "and scope semantics are unchanged: an unopened folder is still invisible: {unreached:#?}" + ); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/file-watching/README.md b/docs/features/file-watching/README.md index 2763297..08008d2 100644 --- a/docs/features/file-watching/README.md +++ b/docs/features/file-watching/README.md @@ -22,6 +22,25 @@ per notification. filelist, are whole rebuilds exactly as before. `watch::one_scope_file` is the test. See `docs/features/incremental-index/README.md`. +- **Amended (index-scope, 2026-08-28): this feature now carries a little more + weight than it did, and the difference is named here rather than left to be + found.** A scope-widening `didOpen` used to run a whole rescan, which re-read + every in-scope file and so *incidentally* caught anything that had changed on + disk behind the server's back. Since that round it indexes only the folders it + added. For a client that advertised + `workspace.didChangeWatchedFiles.dynamicRegistration` — VS Code and Neovim + both do — nothing is lost: the registered glob covers create, change and + delete of every source file in the workspace, which is the mechanism, and the + widen never was. For a client that did not, the **save-only model this README + already documents is slightly narrower**: an external change in a folder + already in scope now waits for the next whole rescan (a save of a file the + index does not hold, a settings change, a folder change, a rename/delete + notification) instead of possibly being caught by the next jump. That is the + same class of window, not a new one — a save has taken the one-file + incremental path since 2026-08-27, so such a session already had no reliable + whole-tree re-read. Written up in full in + `docs/features/index-scope/README.md`. + - **Registration is the only way in.** The protocol has no static `didChangeWatchedFiles` server capability — a server that wants file events must ask for them with `client/registerCapability`, and only a client that diff --git a/docs/features/index-scope/README.md b/docs/features/index-scope/README.md index dab5635..b59870f 100644 --- a/docs/features/index-scope/README.md +++ b/docs/features/index-scope/README.md @@ -52,7 +52,11 @@ that is provably a reporting decision with no effect on the index. rootless session opening a *second* file in an already-scanned directory no longer rebuilds (it used to, always), and a session on the filelist or workspace rung never rebuilds on `didOpen`, because no open buffer can widen - those scopes. + those scopes. **Amended 2026-08-28**: the comparison is unchanged and still + the whole rule, but its answer is now three-way rather than two — the same + two directory lists go to `widen_of`, which indexes only what was added when + the move was a pure add. *When* a `didOpen` indexes is exactly what it was; + only *how much* changed. - **The `didOpen` check costs two `scope_dirs()` calls, and each one asks `filelist_path()` whether rung 1 is in force.** That is a `Discovery` walk up from each root looking for a config — a handful of `exists()` calls, on an @@ -101,6 +105,50 @@ that is provably a reporting decision with no effect on the index. filelist. Nothing about diagnostics, formatting or any single-file feature depends on the scope: the per-buffer analysis is bottom-up and instant, and this round does not touch it. +- **A widen indexes what it added and trusts what it already has (2026-08-28).** + Since this round a `didOpen` that only *adds* folders to the scope indexes + those folders' files alone and folds them into the live index, the completion + tables and the include graph. The equivalence it claims is exact and is worth + stating in full: **the widened tables are the tables a whole rescan would have + produced, given that the disk files already indexed have not changed since + they were indexed.** Two halves make that hold rather than one — every open + buffer is re-indexed from the analysis it holds, so unsaved edits land exactly + as a whole rescan's overlay would; and a buffer that has grown past the + large-file threshold is taken back out, which is the one thing a widen + removes. +- **The residual staleness, stated honestly — and it is a narrowing, not a new + window.** A whole rescan re-reads every in-scope file, so until this round a + widening `didOpen` *incidentally* caught anything that had changed on disk + behind the server's back. It no longer does. What covers that instead: + - a client that advertised `workspace.didChangeWatchedFiles.dynamicRegistration` + — VS Code and Neovim both do — is registered for `**/*.{v,vh,sv,svh}` with + `kind` unset, so **create, change and delete of any source file anywhere in + the workspace** already reach the server as their own notification and + rescan (`docs/features/file-watching/README.md`). For such a client nothing + is lost: the widen never was the mechanism. + - a client that did *not* keeps the **save-only model that feature already + documents**, and this round narrows what that model catches: an external + change in a folder already in scope used to be picked up by the next + scope-widening `didOpen` and is now picked up by the next whole rescan (a + save of a file the index does not hold, a settings change, a folder change, + a `didRenameFiles`/`didDeleteFiles`). **Lead: this is the one behaviour this + round takes away, and it is named here rather than left to be found.** It is + the same class as the window `file-watching` already owns — "this server is + not told, so it does not know" — and it is not a new kind of staleness; a + save has taken the one-file incremental path since 2026-08-27, so a + watcher-less session already had no reliable whole-tree re-read. + - an externally edited `lucisv.toml` is unchanged in kind and narrowed in the + same way: a widen reads the config governing the folders it *adds*, so a + changed `exclude` reaches an already-scoped folder at the next whole rescan + rather than possibly at the next jump. `lucisv.toml` is not watched either + way, which that README already says. +- **A widen does not re-open the persistent store, and that is most of what it + saves on a big project.** `begin_scan` re-opens `IndexCache` on every whole + rescan, which reads and decodes every record in it — ~90 ms over opentitan's + 3 979 — and a widen keeps the handle the last whole rescan left. New files + still hit the store (they are looked up in the entries already in hand); what + a widen cannot see is a record another session wrote since this session's last + whole rescan, which costs a re-parse and never a wrong answer. - **Wrong-typed settings fall back to the *narrow* default**, the same direction `maxFileSize` falls back to the cap: a misparse must not silently buy a whole-workspace scan. `"scope"` is matched exactly — `"Workspace"` is @@ -208,6 +256,60 @@ impl WorkspaceIndex { consulted first, so an oversized file still reports itself `Skipped` exactly as before. +### `lucisv_server::state` — a scan that only adds (2026-08-28) + +```rust +impl Workspace { + /// The files `added` brings into scope that the index does not hold, + /// plus every open buffer's own analysis. + pub fn begin_widen(&mut self, added: &[PathBuf], watch: &mut dyn FnMut(IndexEvent)) -> Scan; +} +``` + +- `Scan` gained a private `kind` and a private `gone`, and **`finish_scan` is + still the one way to land a scan**: it branches on the kind, so a caller + cannot pair a widen with a whole scan's ending. `begin_scan`, `scan_step` and + `publish_scan` are untouched and are the same code for both shapes — which is + what makes the widen's per-file behaviour (the cache, the open-buffer reuse, + the events) identical by construction rather than by care. +- The widen **does not** compact the persistent store (it does not know the + live set of entries; the next whole rescan rewrites the log) and **does not** + re-open it (see Assumptions). It drops the closed-file view cache for exactly + the files it reads rather than dropping it whole, which is what a scan that + names its own files can honestly do — `Workspace::file_view`'s invalidation + list names it. +- Test-only `widen_index` / `widen_index_with` are the one-shot spelling, as + `rebuild_index` is for a whole scan. + +### `lucisv_server::includes` — an edge holds what the disk answered + +`IncludeGraph` now keeps each edge twice: `raw`, the path the filesystem +resolved the `` `include`` to, and `edges`, that path re-spelled the way the +index spells the file (`as_the_index_spells_it`). `relearn` is followed by a +`respell` everywhere, so **every held edge's spelling is re-derived from the +current in-scope file list** — no filesystem call, no re-read of any file. + +That is what lets a widen match a rebuild exactly: a file that is in scope for +the first time can lend its own spelling to an edge resolved before it arrived, +which `IncludeGraph::absorb` could not do while edges were stored already +spelled. `update_file`'s documented limit narrows accordingly: an edge of a +*different* file is still not re-**resolved** against the disk, but it is +re-spelled. + +### `lucisv_server::server` — the chooser + +```rust +enum Widen { Nothing, Added(Vec), Whole } +fn widen_of(before: &[PathBuf], after: &[PathBuf]) -> Widen; +``` + +`didOpen` compares `scope_dirs()` across `set_document` as it always did, and +`widen_of` turns the two lists into one of three answers: unmoved → publish; +grew and lost nothing → `reindex_widened`; **anything else → the whole rescan**. +Nothing takes a directory out of the folder scope today, so the third arm is a +rule kept rather than a case reached. `reindex_widened` defers to +`rescan_wanted` — one whole rescan — when a scan is already running. + ### `lucisv_server::candidates` — words from a token stream - `Candidates::build(index, sources, known: HashMap>)` @@ -301,11 +403,46 @@ impl WorkspaceIndex { "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 +- [x] **Done in round 20 instead** (see below): the objection below was right + about the shape it was aimed at, and is answered by refreshing every open + buffer's facts from its held analysis as part of the widen's batch. +- [ ] ~~**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. + `didOpen` did not trigger.~~ + +### Round 20 — a widen indexes what is new, not everything again (2026-08-28) + +- [x] `Workspace::begin_widen`: only the files the added folders bring in, plus + every open buffer refreshed from the analysis it holds +- [x] `finish_scan` branches on the scan's own kind, so a widen cannot be landed + as a whole scan; `begin_scan`/`scan_step`/`publish_scan` unchanged +- [x] `IncludeGraph` holds each edge as the filesystem answered it and re-spells + on every `relearn`, so a widened graph is a rebuilt graph byte for byte +- [x] The chooser (`server.rs`'s `widen_of`): a pure add takes the cheap path, + anything else falls back to the whole rescan, tested as a table +- [x] A widen asked for mid-scan defers to one whole rescan behind it — the same + `rescan_wanted` flag every other mid-scan trigger sets +- [x] The progress bar counts the widen's own work list, never the whole scope; + the per-file log names only the files it read +- [x] The persistent store still answers for the files a widen brings in +- [x] Equivalence pinned seven ways (index fingerprint, all three completion + tables, include-graph fingerprint) including unsaved edits at widen time, + a folder that contains one already in scope, an include spelled by a file + the widen brought in, and a buffer over the large-file threshold +- [x] **opentitan, 3 979 files, warm store: 120 / 132 / 137 / 169 ms → 22 / 18 / + 12 / 44 ms** per jump, and no longer growing with the browsing history +- [ ] **Flagged for the lead, not a bug:** a widening `didOpen` used to re-read + the whole scope and so incidentally caught external disk changes. It no + longer does. Fully covered by the file watcher for a client that has one; + a client without one keeps the save-only model `file-watching` documents, + slightly narrowed. Written out in Assumptions. +- [ ] **Not done, deliberately:** a widen does not interleave. It is a rescan, so + `must_wait` holds requests queued behind it either way, and the round's + point is that there is no longer a wait worth breaking up. +- [ ] **Not done, deliberately:** no incremental *shrink*. Nothing shrinks the + folder scope today; `widen_of`'s third arm is where one would land. - [ ] **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 @@ -623,6 +760,179 @@ bump, no commits. passed, 0 failed** (2407 on `HEAD`, measured — 6 new). `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. +### 2026-08-28 — dev agent (a widen indexes what is new, not everything again) + +**The symptom, reproduced against the real repo before anything was written.** +The lead's probe, adapted to time exactly the thing the owner feels — a +`didOpen` in a new folder, then the very next `textDocument/definition`, which +`must_wait` holds behind the rescan the open asked for. `--release`, over +stdio, `/Users/guoliangchen/repo/opentitan` (3 979 SV files), folder scope, +warm store, two runs of the **binary built from `HEAD`**: + +| jump | before, run 1 | before, run 2 | +|---|---:|---:| +| `didOpen hw/ip/aes/rtl` | 119.9 ms | 119.5 ms | +| `didOpen hw/ip/kmac/rtl` | 131.2 ms | 133.6 ms | +| `didOpen hw/ip/hmac/rtl` | 137.7 ms | 136.5 ms | +| `didOpen hw/ip/spi_device/rtl` | 168.6 ms | 169.9 ms | + +— the growth is the report: every jump re-pays for every folder before it. +Settled definitions in the same session are 0.06–0.11 ms, which is the owner's +own expectation and was already true. + +**After, same probe, same machine, same session, the two binaries alternated:** + +| jump | after, run 1 | after, run 2 | +|---|---:|---:| +| `didOpen hw/ip/aes/rtl` | 22.3 ms | 21.6 ms | +| `didOpen hw/ip/kmac/rtl` | 18.2 ms | 17.8 ms | +| `didOpen hw/ip/hmac/rtl` | 12.2 ms | 12.8 ms | +| `didOpen hw/ip/spi_device/rtl` | 44.3 ms | 44.3 ms | + +**The shape is the point, not the ratio.** What is left is proportional to the +folder being opened — `spi_device/rtl` is the big one and costs the most, every +time — and no longer to how long the user has been browsing. The first +`definition` of the session, which waits for the `didOpen(tb.sv)` widen, went +from **99.7 ms to 0.9 ms** for a reason worth naming separately: `begin_scan` +re-opens the persistent store on every whole rescan, and reading and decoding +3 979 records is most of that 99 ms. A widen keeps the handle the last whole +rescan left, so it pays none of it. (The probe is in the scratchpad, not in the +tree: nothing committed may depend on that checkout.) + +**The synthetic regression is the same measurement without opentitan.** +`perf::what_a_jump_into_a_new_folder_costs_before_and_after` generates 40 +folders × 25 files of 200 lines, jumps through six of them, and runs **both +shapes over the same tree in the same run** — asserting after every jump that +the two indexes fingerprint identically, so the columns are comparable by +construction: + +| jump | files in scope after it | whole rescan | incremental widen | +|---|---:|---:|---:| +| 0 | 25 | 18.2 ms | 17.8 ms | +| 1 | 50 | 37.1 ms | 18.1 ms | +| 2 | 75 | 54.0 ms | 18.6 ms | +| 3 | 100 | 71.7 ms | 18.7 ms | +| 4 | 125 | 89.4 ms | 19.1 ms | +| 5 | 150 | 107.1 ms | 19.2 ms | + +The first row being equal is the honest baseline: with nothing indexed yet the +two paths do the same work. + +**Round 19's objection was right, and answering it is two lines in +`begin_widen`.** That round rejected this shape because a widen that indexed +only the new folder would drop the unsaved edits a whole rescan's +`collect_sources` overlay picks up — "type `package p;` into an open buffer, +jump into a new folder, and the two shapes disagree about whether `p` exists". +So the widen's work list is *the new files **plus every open buffer***, each +contributing the `FileFacts`/words it already holds — the machinery round 19 +itself built, at ~1.7 ms + ~3.1 ms for a 1.4 MB buffer and no parse at all. +`a_widen_leaves_the_tables_a_whole_rescan_would_have_left` is that exact attack +run as a test, and it fails without the buffer refresh. + +**The same rule answers the case round 19 did not name.** `collect_sources` +drops a buffer on the large-file fast path *from the index entirely*, so a file +whose buffer has grown past the threshold since the last rescan is one a whole +rescan removes. Following `collect_sources` exactly means the widen removes it +too — the one thing a purely additive widen would have got wrong, and the +reason `Scan` has a `gone` list rather than an assumption. + +**The include graph needed a real change, and it is the one that makes the +equivalence structural.** `IncludeGraph::absorb` re-resolves only the batch's +own edges, so a file already indexed kept whatever spelling it had. That is +almost always the same answer, and *narrowly* not: `as_the_index_spells_it` +lends an in-scope file's own spelling to a case-mismatched include, so a file +the widen brings into scope can change how an edge resolved before it arrived +must be spelled. Rather than re-scan every file's text (which is the re-read +this round exists to avoid), the graph now holds each edge **as the filesystem +answered it** and re-spells all of them on every `relearn` — in memory, no +`is_file` call, no file re-read. Which file an include lands on is a question +for the disk; which spelling that file has is a question for the scope; only +the second one moves when the scope grows. `a_widen_lends_a_new_files_spelling_to_an_include_resolved_before_it` +is the witness, and it fails against the old storage. + +**The chooser is deliberately narrower than what is reachable.** `widen_of` +takes the cheap path only when the scope grew and lost nothing. Nothing takes a +directory out of the folder scope today — `opened_dirs` only grows and a +`didClose` costs no rescan — so the fall-back arm is a rule kept rather than a +case reached; a future shrink gets the whole rescan, which is always a correct +answer, instead of a subtly wrong cheap one. The table is +`widen_of_takes_the_cheap_path_for_a_pure_add_and_nothing_else`. + +**Mid-scan a widen defers rather than folding in, and that is the coalescing +rule unchanged.** A scan in flight holds a work list taken from the *old* scope; +folding a widen into it would make "which files exist" mean two things inside +one scan. `reindex_widened` sets the same `rescan_wanted` flag every other +mid-scan trigger sets, so the answer is one more *whole* scan behind this one — +cheap, because it reads the persistent store for everything the running scan +already parsed. Reached by driving the flag directly rather than over the wire, +and the test says why: a widen never drains the queue, and under the folder +scope the startup scan indexes nothing and so never interleaves, so the wire +route to this case is a `didOpen` answered inside a long whole rescan — which is +this flag and this call. + +**`finish_scan` branches; the three calls before it do not.** `Scan` grew a +private `kind`, and `finish_scan` dispatches on it, so a caller cannot land a +widen as a whole scan or the other way round. Everything per-file — +`begin_scan`'s siblings `scan_step` and `publish_scan` — is literally the same +code for both shapes, which is what makes the cache behaviour, the open-buffer +reuse and the event stream identical without a second implementation to keep in +step. Two things the widen deliberately skips are in the Handshakes section +with their reasons: the store is not compacted and the view cache is not +cleared. + +**The progress bar counts the widen's own work list**, which is what the brief +asked for: a jump into a 25-file folder says `1/25`, not `1/3979`. The end +message still names the index's whole size, which is `end_indexing`'s existing +sentence and is the honest one — the bar names the scan, the message names what +the workspace now holds. + +**Files touched:** `crates/lucisv_server/src/state.rs`, +`crates/lucisv_server/src/server.rs`, `crates/lucisv_server/src/includes.rs`, +`crates/lucisv_server/src/perf.rs`, `crates/lucisv_server/tests/e2e.rs`, +this README, `docs/features/scan-interleave/README.md`, +`docs/features/file-watching/README.md`, +`docs/features/indexing-ux/README.md`, `docs/perf/README.md`, `TODO.md`. +No new dependency, no `unsafe`, no +`#[allow]`, no scope-semantics change, no version bump, no commits. + +**Tests added (12).** + +| test | where | pins | +|---|---|---| +| `a_widen_leaves_the_tables_a_whole_rescan_would_have_left` | `state.rs` | the headline, with an **unsaved edit** in an already-open buffer: index fingerprint, words, units, macros, include graph | +| `a_widen_reads_only_the_files_the_new_folders_brought_in` | same | the work list: two new files parsed, both buffers reused, the old folder untouched | +| `a_widen_bar_counts_the_new_files_and_not_the_whole_scope` | same | the progress denominator | +| `a_widen_into_a_folder_that_contains_the_old_one_indexes_each_file_once` | same | a file in both the old and the new scope portion, and the tables still equal | +| `a_widen_lends_a_new_files_spelling_to_an_include_resolved_before_it` | same | the include-graph re-spelling, which is why edges are stored raw | +| `a_buffer_grown_past_the_threshold_leaves_the_index_when_the_scope_widens` | same | the one removal a widen makes, against the rebuild | +| `the_persistent_cache_answers_for_the_files_a_widen_brings_in` | same | cache hits on a widen's own files | +| `a_widen_that_adds_nothing_new_still_refreshes_the_open_buffers` | same | the degenerate widen, where the refresh is all the work there is | +| `widen_of_takes_the_cheap_path_for_a_pure_add_and_nothing_else` | `server.rs` | the chooser, as a seven-row table | +| `a_didopen_widen_leaves_the_index_a_whole_rescan_would_have_left` | same | two jumps through the real dispatch, then the rescan, then compare | +| `a_widen_asked_for_mid_scan_defers_to_one_whole_rescan_behind_it` | same | the coalescing rule | +| `a_jump_into_a_new_folder_indexes_that_folder_and_not_the_ones_before_it` | `tests/e2e.rs` | the real binary over a generated 24-folder workspace: per-bar, per-file, the log proves each jump read its own 19 files and reused every open buffer | + +One `#[ignore]`d probe added +(`perf::what_a_jump_into_a_new_folder_costs_before_and_after`), which is the +before/after table above and asserts the two indexes match at every jump. + +**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy +--all-targets --workspace`: zero warnings. `cargo test --workspace`: **2 469 +passed, 0 failed** (2 457 on `HEAD` — 12 new). `cargo build && node +editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. The one +existing measurement this round could have moved — +`state::tests::qa_perf_cold_warm_and_half_warm_scans`, since the include graph +now re-spells its edges on every `relearn` — is **361 / 381 / 202 ms** against +the 322 / 353 / 189 recorded and the 347 / 387 / 203 QA measured, with the store +byte-identical at 2 380 790 bytes. + +**How the opentitan pair was taken, so it can be re-taken.** `git archive HEAD | +tar -x -C /tmp/lucisv-before && cargo build --release -p lucisv_server` there +gives the "before" binary; the probe (`widen_probe.py`, in the session +scratchpad — nothing in the tree may depend on that checkout) drives each binary +over stdio and times the `definition` sent straight after each `didOpen`. Both +binaries were run twice, alternated, in one session on one machine. + ## QA log ### 2026-08-27 — QA agent (gates, attack surfaces, mechanical-sweep audit) @@ -1033,6 +1343,30 @@ rather than a blocker. ## Review +### 2026-08-28 — lead, incremental-widen round + +Reviewed the full diff; gates run by the lead twice (fmt clean, clippy +silent, 2469 workspace tests green both times). **QA was started and +then stopped by the owner mid-gates** — its adversarial phases had run +and its last report was "fmt clean, now clippy and tests", but no +verdict was recorded; the owner chose to validate on the real +workspace instead, and the lead's independent gate runs stand in for +the missing QA sign-off. The chooser (`widen_of`: pure adds only, +anything else whole) and the mid-scan deferral are the two safety +hinges and both are pinned by the dev's tests, including the +unsaved-edit equivalence case that killed the naive version of this +idea a round earlier. The IncludeGraph raw-edge refactor is accepted +on its argument — spelling equivalence made structural rather than +narrow — and the honest watcher-coverage narrowing is documented where +the lead asked for it. Field validation on opentitan (the owner's own +repro): jump-triggered rescans went from 120–169 ms growing to +12–44 ms flat, first definition 99.7 → 0.9 ms. The owner's remaining +0.5 s report was subsequently traced by instrumentation to +`textDocument/codeAction` (3.1 s per cursor move on the instantiation +— `ports::code_actions` reading the whole 3979-file workspace through +`ws.sources()`), which is a different defect and the next round. +Accepted; committed by the lead. + ### 2026-08-28 — lead, rescan-reuse round Reviewed the diff and both logs after QA's clean SHIP; gates re-run diff --git a/docs/features/indexing-ux/README.md b/docs/features/indexing-ux/README.md index e910de9..8bc8447 100644 --- a/docs/features/indexing-ux/README.md +++ b/docs/features/indexing-ux/README.md @@ -74,7 +74,18 @@ are answerable without a debugger. All three settings ride both settings doors here because it is the one non-obvious reach of the setting. - **The denominator is the work list after `exclude` and after the cap.** It is `vlog_semantic::index_order`'s length, known before the first parse, so - the bar counts towards a number the scan will actually reach. + the bar counts towards a number the scan will actually reach. **Amended + (index-scope, 2026-08-28): a scope widen's work list is the files it is + actually indexing** — the folders it added, plus the open buffers it refreshes + — so a jump into a 25-file folder of a 4 000-file project says `1/25`, not + `1/3979`. That is the same rule, not an exception to it: the denominator has + always been "what this scan will do", and a widen simply does less. The bar's + **end message is unchanged** and still names the whole index + (`"N files indexed"`), because the bar names the scan and the message names + what the workspace now holds. No test in this feature moved; the fixtures + here are small enough that a widen's work list is the whole scope, and the + new denominator has its own test in `state.rs` + (`a_widen_bar_counts_the_new_files_and_not_the_whole_scope`). - **The percentage only counts up, and the last file always reports.** See the throttle below; `the_report_schedule_never_floods_and_never_stops_short` checks both properties across nine workspace sizes. diff --git a/docs/features/scan-interleave/README.md b/docs/features/scan-interleave/README.md index 116e563..99d141c 100644 --- a/docs/features/scan-interleave/README.md +++ b/docs/features/scan-interleave/README.md @@ -78,6 +78,20 @@ its work list. ### `lucisv_server::state` — the scan as a value +**Amended (index-scope, 2026-08-28): a scan now has two shapes and one +ending.** `Scan` carries a private kind, `Workspace::begin_widen` is a second +constructor for it — the files a scope widen brought in, rather than every +in-scope file — and `finish_scan` branches on that kind so a widen cannot be +landed as a whole scan. **`begin_scan`, `scan_step` and `publish_scan` are +unchanged and are the same code for both shapes**, which is what keeps the +cache behaviour, the open-buffer reuse and the event stream identical without a +second implementation to keep in step. A widen deliberately does *not* +interleave: it is a rescan, so `must_wait` holds requests queued behind it +either way, and the point of that round is that there is no longer a wait worth +breaking up. A widen asked for **mid-scan** sets `rescan_wanted` like every +other mid-scan trigger, so it is one more *whole* scan behind this one and never +a scan inside a scan. See `docs/features/index-scope/README.md`. + ```rust pub struct Scan { /* work list, how far through it, what is staged */ } diff --git a/docs/perf/README.md b/docs/perf/README.md index b34150e..c88f921 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -348,6 +348,58 @@ 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. +## Before / after — round 5 (2026-08-28) + +`docs/features/index-scope/README.md`: the owner's opentitan report. Every F12 +into a folder the scope had not reached ran a whole rescan of every folder +reached so far, and `must_wait` holds the next request behind it — so the wait +grew with the session. A widen now indexes the folders it added and folds them +in. Measured over the real checkout (3 979 SV files, warm store, folder scope, +`--release` over stdio, the `HEAD` binary and this one alternated in one +session), timing the `textDocument/definition` sent straight after each +`didOpen`: + +| the next request after a jump | before | after | +|---|---:|---:| +| `didOpen hw/ip/aes/rtl` | 120 ms | **22 ms** | +| `didOpen hw/ip/kmac/rtl` | 132 ms | **18 ms** | +| `didOpen hw/ip/hmac/rtl` | 137 ms | **12 ms** | +| `didOpen hw/ip/spi_device/rtl` | 169 ms | **44 ms** | +| the session's first definition (waits for the first widen) | 99.7 ms | **0.9 ms** | +| a definition once the scope has settled | 0.06–0.11 ms | 0.05–0.06 ms | + +**The shape is the claim, not the ratio.** What is left is proportional to the +folder being opened — `spi_device/rtl` is the big one and costs the most, every +time — and no longer to how long the user has been browsing. Two thirds of the +first row is not parsing at all: `begin_scan` re-opens the persistent store on +every whole rescan, and decoding 3 979 records is ~90 ms of it, which a widen +does not pay because it keeps the handle the last whole rescan left. + +Reproducible without that checkout: +`perf::what_a_jump_into_a_new_folder_costs_before_and_after` generates 40 +folders × 25 files of 200 lines and runs **both shapes over the same tree in +the same run**, asserting after every jump that the two indexes fingerprint +identically: + +| jump | files in scope after it | whole rescan | incremental widen | +|---|---:|---:|---:| +| 0 | 25 | 18.2 ms | 17.8 ms | +| 1 | 50 | 37.1 ms | 18.1 ms | +| 3 | 100 | 71.7 ms | 18.7 ms | +| 5 | 150 | 107.1 ms | 19.2 ms | + +The first row being equal is the honest baseline: with nothing indexed yet the +two paths do the same work. + +**What it cost the whole scan: nothing measurable.** The include graph now +re-spells every held edge on each `relearn`, which is the one thing this round +added to a path a whole scan runs. +`state::tests::qa_perf_cold_warm_and_half_warm_scans`, 860-file corpus, after: +**361 / 381 / 202 ms** (no cache / cold / warm) against the 322 / 353 / 189 ms +recorded above and the 347 / 387 / 203 ms QA measured on a busier machine — the +same band, and the store is byte-identical at **2 380 790 bytes**, which is the +number machine load cannot move. + ## What it would take to go faster Ranked by what the measurements above say is there, with what each would