diff --git a/CHANGELOG.md b/CHANGELOG.md index f834421..67cd391 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,62 @@ All notable changes to lucisv are recorded here. Versions follow [semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes (see `README.md`) are the only frozen contract. +## 0.65.6 — 2026-11-19 + +### Saving a file no longer re-indexes the workspace + +(`docs/features/localized-reindex`; TODO §71.1. Measured on OpenTitan's `hw` +tree, 4 058 files, with the server driven the way VS Code drives it.) + +- **What was happening.** Every save cost about 160 ms of whole-index work + whatever was edited — 117 ms of it re-resolving all 470 000 cross-file + references — and VS Code triggered it twice, once for the save and once for + its own file watcher. Watcher events for files the index could not hold (a + generated file in a gitignored directory, a file outside the filelist or + folder scope, a held file reported through a symlinked root or in another + letter case) started a whole rescan with the progress bar, 270–750 ms. +- **Now the index does only what the edit can reach.** + + | edit, then save | before | now | + |---|---:|---:| + | a comment, or the watcher's echo of any save | ~160 ms | under 0.3 ms | + | a local signal in `uart_tx` or `prim_flop` | ~170 ms | 4 ms | + | a member added to `uart_reg_pkg` | ~167 ms | 12 ms | + | a line above a module 125 files instantiate | ~163 ms | 47 ms | + | a member added to a package 677 files import | ~162 ms | 92 ms | + | a watcher event for a file outside the scope | up to 746 ms, with the bar | 3.5 ms | + + The index records which names each file looked up — including the ones it + did not find — and re-resolves only the readers of names whose meaning + changed. A save whose index record is unchanged merges nothing. +- **Still wide, on purpose.** Adding or deleting a file; a burst of more + files in one watcher event than half the index holds (a branch switch), + which takes the one rescan it always did; an edit above a declaration many + files use. Every save still re-checks every open file's diagnostics, so a + `lucisv.toml` or waiver edit takes effect at the next save as before — with + 200 files open that is most of a save (53 ms, against ~205 ms before). +- **The price.** Every whole rescan costs a few per cent more for the table + that makes the rest cheap: warm OpenTitan startup is 40–120 ms slower, + depending on machine load. +- **How it is known to be right.** After any sequence of edits, everything + the server answers must equal what a freshly started server answers for the + same files. QA built that oracle independently and it failed the first cut + on four stale answers (include links to headers outside the scope, lint + configuration, a file-age check macOS defeats, excluded open buffers); all + four are fixed and are now tests. The final build: 312 hand-written + comparisons and twelve random 300–500-step runs over the corpus and + OpenTitan with no divergence it caused. +- **Also.** The language server's `line-length` lint now follows the chosen + formatting style's width (80 under `ansi` and `nxp`, 120 under + `microsoft`), closing the limit noted in 0.65.5. Removing an included + header no longer leaves other files' include links pointing at it. +- **Known, and next.** Found by this round's QA and present in earlier + releases too: an edit made while a whole rescan is running can be applied + out of order, leaving the server's copy of the buffer wrong until the file + is reopened; a watcher event that names only a directory leaves stale + state; an excluded file stays indexed after it is closed. These are the + next round's work. + ## 0.65.5 — 2026-11-19 ### Named formatting styles diff --git a/Cargo.lock b/Cargo.lock index 1477ba9..bffc9d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,7 +97,7 @@ dependencies = [ [[package]] name = "lucisv" -version = "0.65.5" +version = "0.65.6" dependencies = [ "lucisv_core", "rayon", @@ -108,11 +108,11 @@ dependencies = [ [[package]] name = "lucisv_core" -version = "0.65.5" +version = "0.65.6" [[package]] name = "lucisv_mcp" -version = "0.65.5" +version = "0.65.6" dependencies = [ "lucisv_core", "serde", @@ -126,7 +126,7 @@ dependencies = [ [[package]] name = "lucisv_server" -version = "0.65.5" +version = "0.65.6" dependencies = [ "lsp-server", "lsp-types", @@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "vlog_formatter" -version = "0.65.5" +version = "0.65.6" dependencies = [ "vlog_parser", ] [[package]] name = "vlog_linter" -version = "0.65.5" +version = "0.65.6" dependencies = [ "lucisv_core", "vlog_formatter", @@ -279,11 +279,11 @@ dependencies = [ [[package]] name = "vlog_parser" -version = "0.65.5" +version = "0.65.6" [[package]] name = "vlog_refactor" -version = "0.65.5" +version = "0.65.6" dependencies = [ "vlog_formatter", "vlog_parser", @@ -292,7 +292,7 @@ dependencies = [ [[package]] name = "vlog_semantic" -version = "0.65.5" +version = "0.65.6" dependencies = [ "vlog_parser", ] diff --git a/Cargo.toml b/Cargo.toml index 9d22625..c629260 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ members = [ ] [workspace.package] -version = "0.65.5" +version = "0.65.6" authors = ["Guoliang Chen"] edition = "2021" license = "MIT" diff --git a/TODO.md b/TODO.md index ad0a938..a48d70a 100644 --- a/TODO.md +++ b/TODO.md @@ -7315,7 +7315,8 @@ the OpenTitan tree (not only on unit fixtures) before it is called done. The items are the owner's words, lightly condensed; each gets its own subsection, plan and `docs/features//README.md` when its turn comes. -- [ ] **71.1 An edit does not re-index the whole database.** Today every +- [x] **71.1 An edit does not re-index the whole database.** (0.65.6, `docs/features/localized-reindex`) + Today every file edit re-indexes everything. A change to a `define` may have to; a typical, localized edit must not. - [ ] **71.2 Actions stay fast on a huge, heavily-dependent tree.** Do the @@ -7399,8 +7400,29 @@ indexing, collide with each other and with §70's test files, and wait for formatter should not need it. - [ ] `` `ifdef `` between `end` and `else` is a parse error. - [ ] An attribute on an ANSI port (`(* keep *) input a`) is a parse error. - - [ ] The server's `line-length` lint falls back to 100 columns under the + - [x] The server's `line-length` lint falls back to 100 columns under the `ansi`/`microsoft`/`nxp` styles (`lucisv_server/src/lint.rs`); taken when 71.1 merges. - [ ] One-per-line styles give multi-instance declarations (`p1 u8 (...), u9 (...)`) the hanging layout. + +- Wave 5 (lead, 2026-11-19): 71.1 shipped as 0.65.6 after a QA FAIL (four + stale answers), a fix round, a QA pass and a last small round. What the + QA rounds and a read-only investigation turned up, all present before this + wave, becomes lane **71.7** (the owner's Find References item, widened): + - [ ] A caret just past an identifier's last letter asks about the next + character: references, definition, hover and highlight come back + empty (`server/dispatch.rs` `Server::offset`). This is the owner's + "not found, then works after clicking back". + - [ ] A `didChange` arriving during a whole rescan can overtake an older + one still queued (`server/mod.rs` `process_batch`): with incremental + sync the server's buffer is corrupted until the file is reopened. + - [ ] A burst `[request, didOpen]` during the startup scan is re-held at + every file (`server/index.rs` `answer_what_is_waiting`): the scan + takes ~300 s on OpenTitan instead of ~1.7 s. + - [ ] A watcher event naming only a directory leaves stale state; an + excluded buffer stays indexed after close; symlinked files are held + under one or both spellings depending on what was open. + 71.3 (viewport highlighting) passed QA with a gap in the default folder + scope (colours wait out a widen, ~630 ms); it is rebased after 71.7 and + closes that in its fix round. Then 71.2. diff --git a/crates/lucisv_server/src/candidates.rs b/crates/lucisv_server/src/candidates.rs index 7d2d4f0..ab4071d 100644 --- a/crates/lucisv_server/src/candidates.rs +++ b/crates/lucisv_server/src/candidates.rs @@ -197,17 +197,86 @@ impl Candidates { /// patched: this file's old words are given back and its new ones taken, /// so nothing else is re-lexed. The result is what a whole /// [`Candidates::build`] over the same files would have produced. + #[cfg(test)] pub fn update_file(&mut self, index: &WorkspaceIndex, path: &Path, text: &str) { self.update_words(index, path, words_in(text)); } /// [`Candidates::update_file`] for a file whose words the caller already /// has — an open buffer's, read off the tokens it was analyzed from. + #[cfg(test)] pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec) { self.take_index_tables(index); self.set_words(path, words); } + /// [`Candidates::update_words`] in two halves, for a caller that knows + /// which it needs: the word table patched by this file alone… + pub fn set_file_words(&mut self, path: &Path, words: Vec) { + self.set_words(path, words); + } + + /// …and the two index-derived tables re-derived for the names one file declared + /// before or declares now — `symbols` its units and connection members, + /// `macros` its `` `define``s ([`FileFacts::declared_names`]) — which are + /// the only entries its update can move. + /// + /// Exact because every table here is one block per exact name ([`word_cmp`] + /// is total, so equal keys are equal names) and each block is read off + /// the index for that name alone: the unit block from the symbol listing + /// restricted to the name, in the listing's order and deduplicated the + /// same way; a module name present exactly when some unit of it is + /// instantiable; a macro's entry from its first definition in file order. + /// So a block re-derived here is the block a whole re-derivation gives, + /// and every other block is untouched by an update that does not name it. + /// + /// [`FileFacts::declared_names`]: vlog_semantic::FileFacts::declared_names + pub fn refresh_names( + &mut self, + index: &WorkspaceIndex, + symbols: &HashSet<&str>, + macros: &HashSet<&str>, + ) { + let (fresh, _) = unit_tables(index, index.symbols_named(symbols)); + let mut held = std::mem::take(&mut self.units); + held.retain(|unit| !symbols.contains(unit.name.as_str())); + self.units = merge_by_name(held, fresh, |unit| unit.name.as_str()); + self.unit_masks = self.units.iter().map(|unit| char_mask(&unit.name)).collect(); + for name in symbols { + let instantiable = index.units(name).iter().any(|def| def.kind.is_instantiable()); + match (self.modules.binary_search_by(|held| held.as_str().cmp(name)), instantiable) { + (Ok(at), false) => { + self.modules.remove(at); + } + (Err(at), true) => self.modules.insert(at, name.to_string()), + _ => {} + } + } + let mut fresh: Vec = macros + .iter() + .filter_map(|name| index.find_define(name).first().map(|(_, define)| macro_of(define))) + .collect(); + sort_by_name(&mut fresh, |m| m.name.as_str()); + let mut held = std::mem::take(&mut self.macros); + held.retain(|m| !macros.contains(m.name.as_str())); + self.macros = merge_by_name(held, fresh, |m| m.name.as_str()); + } + + /// Every table, rendered for comparison — the equivalence witness the + /// incremental tests hold an updated workspace to a rebuilt one with. + #[cfg(test)] + pub fn fingerprint(&self) -> String { + let mut word_files: Vec<(&String, &usize)> = self.word_files.iter().collect(); + word_files.sort(); + let mut per_file: Vec<(&PathBuf, &Vec)> = self.per_file.iter().collect(); + per_file.sort(); + format!( + "units {:?}\nunit_masks {:?}\nmodules {:?}\nmacros {:?}\nwords {:?}\n\ + word_masks {:?}\nword_files {word_files:?}\nper_file {per_file:?}\n", + self.units, self.unit_masks, self.modules, self.macros, self.words, self.word_masks + ) + } + /// [`Candidates::update_words`] for a batch of files — the form a scan /// publishing what it has indexed so far uses. /// @@ -715,7 +784,15 @@ fn char_mask(text: &str) -> u32 { /// tables want the same records. It is paid once per index build rather than /// once per keystroke, which is the whole point of both. fn index_tables(index: &WorkspaceIndex) -> (Vec, Vec) { - let symbols = index.workspace_symbols(""); + unit_tables(index, index.workspace_symbols("")) +} + +/// [`index_tables`] over a given part of the symbol listing — all of it, or +/// the names one update touched — in the listing's own order. +fn unit_tables( + index: &WorkspaceIndex, + symbols: Vec>, +) -> (Vec, Vec) { // `workspace_symbols` sorts by name first — with `str`'s own `Ord`, not a // case-folded one — so same-named declarations are already adjacent and a // plain `dedup` leaves one entry per module name, in `str` order. That is @@ -757,14 +834,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec { for id in 0..index.files().len() { let Some(table) = index.defines(vlog_semantic::FileId(id as u32)) else { continue }; for define in table.entries().iter().filter(|d| d.kind == DefineKind::Define) { - let args = match &define.params { - Some(params) => format!("({})", params.join(", ")), - None => String::new(), - }; - out.push(Macro { - name: define.name.clone(), - detail: format!("`define {}{args}", define.name), - }); + out.push(macro_of(define)); } } sort_by_name(&mut out, |m| m.name.as_str()); @@ -772,6 +842,31 @@ fn macros_of(index: &WorkspaceIndex) -> Vec { out } +/// One `` `define``'s completion entry. +fn macro_of(define: &vlog_parser::defines::Define) -> Macro { + let args = match &define.params { + Some(params) => format!("({})", params.join(", ")), + None => String::new(), + }; + Macro { name: define.name.clone(), detail: format!("`define {}{args}", define.name) } +} + +/// Two lists sorted by [`word_cmp`] with no name in common, as one. +fn merge_by_name(held: Vec, fresh: Vec, name: impl Fn(&T) -> &str) -> Vec { + let mut out = Vec::with_capacity(held.len() + fresh.len()); + let mut fresh = fresh.into_iter().peekable(); + for item in held { + while let Some(next) = + fresh.next_if(|next| word_cmp(name(next), name(&item)) == Ordering::Less) + { + out.push(next); + } + out.push(item); + } + out.extend(fresh); + out +} + /// Every distinct identifier one file's token stream contains. /// /// **`vlog_semantic::words::harvest_text`, under this crate's old name.** The @@ -786,6 +881,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec { /// one pass at the end: no part of a scan may be longer than one file, or the /// message queue goes unanswered for the length of it /// (`docs/features/scan-interleave/README.md`). +#[cfg(test)] pub(crate) fn words_in(text: &str) -> Vec { words::harvest_text(text) } diff --git a/crates/lucisv_server/src/includes.rs b/crates/lucisv_server/src/includes.rs index 31c0dc8..29cefc7 100644 --- a/crates/lucisv_server/src/includes.rs +++ b/crates/lucisv_server/src/includes.rs @@ -86,7 +86,7 @@ fn include_on_line(line: &str, base: u32) -> Option { /// /// Rebuilt whole on every index rebuild, from the same source list — and /// patched one file at a time when only one file's text moved -/// ([`IncludeGraph::update_file`]). +/// ([`IncludeGraph::update_held`]). #[derive(Debug, Default, Clone)] pub struct IncludeGraph { /// The `+incdir+` directories of the configured filelist, in filelist @@ -107,6 +107,11 @@ pub struct IncludeGraph { /// 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 held file's `` `include`` lines as written, resolved or not — so + /// a file appearing or vanishing anywhere on disk can be answered by + /// re-resolving just the lines that could name it + /// ([`IncludeGraph::refresh_naming`]), without reading a file. + lines: 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` @@ -154,29 +159,81 @@ impl IncludeGraph { graph } - /// Re-scan one file's `` `include``s, the rest of the graph left standing. + /// Re-scan one file's `` `include``s, the rest of the graph left standing — + /// for a file whose text changed while the file set did not, a save of a + /// file the index already holds. The known-file and folded-spelling tables + /// are a function of the file set, and every other file's edges a function + /// of its own text and those tables, so only this file's edges are + /// re-scanned and re-spelled (`docs/features/localized-reindex/README.md`). /// - /// `known` is the index's file list as it stands *after* the update, which - /// is what the known-file and folded-spelling tables are: cheap to rebuild - /// from a list already in memory, and wrong to leave stale when a file has - /// come or gone. - /// - /// 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** 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); + /// Until 2026-11-19 this was `update_file`, which also re-learned both + /// tables and re-spelled every edge — O(files) for an answer that cannot + /// move. Its one honest limit is unchanged: an edge of a *different* file + /// is not re-**resolved** against the disk, which is why the incremental + /// path takes only a file the index already holds. + pub fn update_held(&mut self, path: &Path, text: &str) { self.rescan_edges(path, text); - self.respell(); + self.respell_one(path); } - /// [`IncludeGraph::update_file`] for a batch of files whose `` `include`` + /// Re-resolve the `` `include`` lines of every held file that writes one + /// whose last component could be `path`'s name — the only lines a file + /// appearing, vanishing or moving at `path` can change the answer of, + /// whether or not `path` is in scope: an include is resolved against the + /// disk, not against the scope (`docs/features/localized-reindex`, QA F1). + /// + /// The name is compared case-insensitively, so a case-insensitive disk is + /// covered, and a target with no last component (`..`) counts as naming + /// everything. Reads no file: the lines are held. + pub fn refresh_naming(&mut self, path: &Path) { + self.refresh_naming_all(std::slice::from_ref(&path.to_path_buf())); + } + + /// [`IncludeGraph::refresh_naming`] for every path of one watcher event + /// at once: one pass over the held lines for the whole set of names, so a + /// burst of ten thousand generated files costs one pass, not ten thousand + /// (QA R2-1). A line is re-resolved exactly when it would have been for + /// one of the paths alone, and re-resolving a file twice gives what once + /// does, so the batch is the same answer. + pub fn refresh_naming_all(&mut self, paths: &[PathBuf]) { + let folded = |name: &std::ffi::OsStr| name.to_string_lossy().to_lowercase(); + let names: HashSet = + paths.iter().filter_map(|path| path.file_name()).map(folded).collect(); + if names.is_empty() { + return; + } + let could_name = |include: &Include| { + Path::new(&include.target).file_name().is_none_or(|last| names.contains(&folded(last))) + }; + let mut naming: Vec = self + .lines + .iter() + .filter(|(_, lines)| lines.iter().any(could_name)) + .map(|(from, _)| from.clone()) + .collect(); + naming.sort(); + for from in naming { + let lines = self.lines.get(&from).cloned().unwrap_or_default(); + self.rescan_found(&from, &lines); + self.respell_one(&from); + } + } + + /// Re-spell one file's edges from its raw ones. + fn respell_one(&mut self, path: &Path) { + match self.raw.get(path) { + Some(targets) => { + let spelled = + targets.iter().map(|to| self.as_the_index_spells_it(to.clone())).collect(); + self.edges.insert(path.to_path_buf(), spelled); + } + None => { + self.edges.remove(path); + } + } + } + + /// [`IncludeGraph::update_held`] for a batch of files whose `` `include`` /// lines have already been read, with the `+incdir+`s the scope resolves /// to right now — the form a scan publishing what it has indexed so far /// uses. The lines come from the step that indexed each file, for the @@ -203,11 +260,29 @@ impl IncludeGraph { self.respell(); } + /// Take `path` into the file set: known, folded, and every held edge + /// re-spelled against the new set — what [`IncludeGraph::from_includes`] + /// over the old set and `path` would have learned. Its own edges are + /// [`IncludeGraph::update_held`]'s business. + pub fn add_known(&mut self, path: &Path) { + if !self.known.insert(path.to_path_buf()) { + return; + } + if let Some(key) = path.to_str().map(str::to_lowercase) { + self.folded + .entry(key) + .and_modify(|found| *found = None) + .or_insert_with(|| Some(path.to_path_buf())); + } + 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.raw.remove(path); + self.lines.remove(path); self.respell(); } @@ -223,6 +298,10 @@ impl IncludeGraph { fn rescan_found(&mut self, path: &Path, found: &[Include]) { let targets: Vec = found.iter().filter_map(|include| self.found(Some(path), include)).collect(); + match found.is_empty() { + true => self.lines.remove(path), + false => self.lines.insert(path.to_path_buf(), found.to_vec()), + }; match targets.is_empty() { true => self.raw.remove(path), false => self.raw.insert(path.to_path_buf(), targets), @@ -425,6 +504,9 @@ impl IncludeGraph { let mut raw: Vec<(&PathBuf, &Vec)> = self.raw.iter().collect(); raw.sort(); out.push_str(&format!("raw {raw:?}\n")); + let mut lines: Vec<(&PathBuf, &Vec)> = self.lines.iter().collect(); + lines.sort_by_key(|(path, _)| *path); + out.push_str(&format!("lines {lines:?}\n")); out } } diff --git a/crates/lucisv_server/src/lint.rs b/crates/lucisv_server/src/lint.rs index 1380d87..a9820bc 100644 --- a/crates/lucisv_server/src/lint.rs +++ b/crates/lucisv_server/src/lint.rs @@ -304,7 +304,17 @@ fn configured( } } options.overlay(&client.lint_options); - let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH); + // The formatter's width ladder, so a line lucisv wrote is never a line + // lucisv calls too long: an explicit width (`lucisv.toml`, then the + // editor), else the chosen style's width (`lucisv.toml`'s `style`, then + // `lucisv.format.style`), else the default. `auto` names no preset and so + // no width — it falls through to the default, as it does in the + // formatter (`docs/features/format-styles/README.md`, Handshakes). + let styled = file.format_style.or(client.style).and_then(vlog_formatter::style::preset); + let width = file + .line_length + .or(client.line_length) + .unwrap_or_else(|| styled.map_or(DEFAULT_LINE_LENGTH, |style| style.line_length)); (options, width, file, problems) } @@ -731,6 +741,81 @@ mod tests { assert_eq!(oracle.package_exports("nowhere_pkg"), Exports::Unknown); } + /// Whether the server flags `line-length` on a line of `columns` + /// characters, in a scratch tree governed by `toml` (none for `None`), + /// with the editor's `lucisv.format.style` set to `editor_style`. + fn flags_a_line_of( + columns: usize, + toml: Option<&str>, + editor_style: Option<&'static str>, + ) -> bool { + let dir = std::env::temp_dir().join(format!( + "lucisv_lint_width_{}_{columns}_{}", + std::process::id(), + toml.map_or(0, str::len) + editor_style.map_or(0, str::len) * 1000 + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + if let Some(toml) = toml { + std::fs::write(dir.join("lucisv.toml"), toml).expect("config"); + } + let text = format!("module m;\n // {}\nendmodule\n", "x".repeat(columns - 5)); + let path = dir.join("m.sv"); + std::fs::write(&path, &text).expect("source"); + let mut ws = Workspace::default(); + ws.set_client_settings(ClientSettings { style: editor_style, ..ClientSettings::default() }); + let uri = crate::uri::path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), text); + let doc = ws.document(&uri).expect("open"); + let run = LintRun::for_document(&ws, doc); + let flagged = diagnostics_in(doc, &run) + .iter() + .any(|d| d.code == Some(NumberOrString::String("line-length".into()))); + let _ = std::fs::remove_dir_all(&dir); + flagged + } + + /// The width `lucisv check` holds the same file to: the CLI's own ladder, + /// an explicit width over the named style's over the default + /// (`lucisv`'s `Options::config_with`), with the editor's style standing + /// in for `--style`. + fn check_width(explicit: Option, style: Option<&str>) -> usize { + let config = style.and_then(vlog_formatter::Config::named).unwrap_or_default(); + explicit.unwrap_or(config.max_width) + } + + #[test] + fn line_length_holds_a_buffer_to_the_width_the_formatter_and_check_use() { + // One rung each, from the top: an explicit width beats a style; a + // project's style; the editor's style; the default; and `auto`, which + // names no width and so takes the default. + let rungs: [(&str, Option<&str>, Option<&'static str>, usize); 5] = [ + ( + "explicit", + Some("line-length = 120\n[format]\nstyle = \"ansi\"\n"), + None, + check_width(Some(120), Some("ansi")), + ), + ( + "project style", + Some("[format]\nstyle = \"ansi\"\n"), + None, + check_width(None, Some("ansi")), + ), + ("editor style", None, Some("microsoft"), check_width(None, Some("microsoft"))), + ("default", None, None, check_width(None, None)), + ("auto", Some("[format]\nstyle = \"auto\"\n"), None, check_width(None, Some("auto"))), + ]; + assert_eq!(rungs.map(|r| r.3), [120, 80, 120, 100, 100], "premise: the widths check uses"); + for (rung, toml, editor, width) in rungs { + assert!( + !flags_a_line_of(width, toml, editor), + "{rung}: a line of exactly {width} is fine" + ); + assert!(flags_a_line_of(width + 1, toml, editor), "{rung}: one column more is flagged"); + } + } + #[test] fn a_tab_becomes_one_warning_carrying_its_rule_name() { let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n"); diff --git a/crates/lucisv_server/src/server/diagnostics.rs b/crates/lucisv_server/src/server/diagnostics.rs index 6a63c1b..661b25e 100644 --- a/crates/lucisv_server/src/server/diagnostics.rs +++ b/crates/lucisv_server/src/server/diagnostics.rs @@ -92,7 +92,7 @@ impl Server { /// Everything the server has to say about a buffer — the one computation /// both diagnostic models answer from. A buffer that is not open has /// nothing said about it. - fn diagnostics_of(&self, uri: &Uri) -> Vec { + pub(super) fn diagnostics_of(&self, uri: &Uri) -> Vec { let Some(doc) = self.workspace.document(uri) else { return Vec::new() }; // The lint pass is given the project: the rule selection // `lucisv.lint.*` and the buffer's `[lint]` table resolved to, and the diff --git a/crates/lucisv_server/src/server/index.rs b/crates/lucisv_server/src/server/index.rs index c27f073..c628020 100644 --- a/crates/lucisv_server/src/server/index.rs +++ b/crates/lucisv_server/src/server/index.rs @@ -18,9 +18,21 @@ use super::batch::opened_in; use super::client::{notify_on, plural}; use super::progress::IndexWatch; use super::{Server, INTERLEAVE_ABOVE}; -use crate::state::{IndexEvent, Scan, Workspace}; +use crate::state::{IndexEvent, OneFile, Scan, Watched, Workspace}; use crate::{design_hierarchy, file_ops}; +/// A watcher event naming more than one path per `BURST_DIVISOR` files the +/// index holds takes the whole rescan instead of being sorted path by path. +/// +/// Measured on the full OpenTitan `hw` tree (4 058 files, release, one +/// notification of generated files under a gitignored directory, medians of +/// 3): sorting costs ~0.10 ms a path (1 000 paths 0.10 s, 5 000 paths 0.50 s), +/// a cached whole rescan ~0.16 ms an indexed file (0.63–0.65 s) — so the two +/// cross near 1.6 paths per file, and both scale with the tree. Dividing by 2 +/// keeps the sorted path at or under ~0.3× the rescan it saves on any tree +/// (QA R2-1: never slower than 7408fac's one rescan per notification). +const BURST_DIVISOR: usize = 2; + impl Server { /// Rescan the workspace and republish every open buffer against the new /// index. Every caller changed what the index should contain — a save, a @@ -59,15 +71,22 @@ impl Server { /// that file is one the index already holds. Reports whether it ran; a /// `false` means the caller owes a whole rebuild. /// - /// Everything a rebuild does *after* the scan happens here too, for the - /// same reasons: the code-lens refresh (the file that moved may have - /// changed an instantiation count in any buffer), the diagnostics - /// generation bump (every open buffer's diagnostics are computed against - /// the index), and a republish of every open buffer. The republish stays - /// wholesale rather than narrowing to the buffers that could have moved: - /// a lint reads the index, so any buffer's diagnostics may have changed, - /// and narrowing it correctly needs a dependency graph this server does not - /// have. Worth doing later; wrong to guess at now. + /// When the index moved, everything a rebuild does *after* the scan + /// happens here too, for the same reasons: the code-lens refresh (the file + /// that moved may have changed an instantiation count in any buffer), the + /// hierarchy view's invalidation, the diagnostics generation bump (every + /// open buffer's diagnostics are computed against the index), and a + /// republish of every open buffer. The republish stays wholesale: a lint + /// reads the index, so any buffer's diagnostics may have changed, and it + /// costs ~0.3 ms a buffer on OpenTitan — narrowing it would buy nothing + /// measurable for the one place a stale squiggle could hide + /// (`docs/features/localized-reindex/README.md`). + /// + /// When the file's record did **not** move — the watcher's echo of the + /// save that just ran, a save of an unchanged buffer — every answer read + /// off the index alone is the answer it already was, so no lens refresh + /// and no hierarchy invalidation is sent. The republish still is: see + /// below. /// /// Three things a whole rebuild does that this deliberately does not: /// @@ -93,19 +112,84 @@ impl Server { return true; } let started = self.timer(); - if !self.workspace.update_one(path) { + let outcome = self.workspace.update_one_file(path); + if outcome == OneFile::NotHeld { // No line: nothing was reindexed, and the caller is about to // rebuild the whole index — which times itself. return false; } - self.refresh_code_lenses(); - self.hierarchy_index_changed(); + // Lenses and the hierarchy view are read off the index alone, so an + // unchanged record owes them nothing. Diagnostics are not: a lint + // also reads the buffer's `lucisv.toml` and waiver files from disk, + // which no notification reports, and a save has always been when an + // edit to them takes effect (QA F2). So every save republishes. + if outcome == OneFile::Changed { + self.refresh_code_lenses(); + self.hierarchy_index_changed(); + } + self.republish_all(); + // The unchanged case says so inside the parentheses, so every reader + // of the old `reindex_one() took ` shape still matches. + let unchanged = if outcome == OneFile::Unchanged { ", unchanged" } else { "" }; + self.timed(started, |took| { + format!("reindex_one({}{unchanged}) took {took}", path.display()) + }); + true + } + + /// The rescan a watcher event owes, decided file by file + /// ([`Workspace::watched`]): a file the scope provably cannot take — a + /// generated file under a gitignored directory, one outside the folder + /// scope or the filelist — owes nothing; a held file, by whatever + /// spelling the client used, is the one-file update; anything the scope + /// may take and the index does not hold is a whole rebuild, and so are + /// two or more held files, exactly as a checkout always was. + /// + /// `named` is every path the event named, any extension: the include + /// lines that could name one are re-resolved first, unless the event takes + /// the whole rescan, which re-resolves all of them (QA F1). An event that owes the index + /// nothing still republishes every open buffer, for the reason + /// [`Server::reindex_one`] gives. + pub(super) fn reindex_watched( + &mut self, + paths: &[std::path::PathBuf], + named: &[std::path::PathBuf], + ) { + // A burst — a branch switch, a generator run — is sorted file by file + // only while that is cheaper than the rescan it replaces. + if paths.len().saturating_mul(BURST_DIVISOR) > self.workspace.index().files().len() { + return self.reindex(); + } + self.workspace.refresh_includes_naming(named); + let mut held: Vec = Vec::new(); + for path in paths { + match self.workspace.watched(path) { + Watched::Held(spelled) => held.push(spelled), + Watched::Outside => {} + Watched::Unknown => return self.reindex(), + } + } + held.sort(); + held.dedup(); + match held.as_slice() { + [] => self.republish_all(), + [one] => { + if !self.reindex_one(one) { + self.reindex(); + } + } + _ => self.reindex(), + } + } + + /// Every open buffer's diagnostics said again, under a new generation so + /// a pulling client asks again too — what a save owes even when the index + /// did not move. ~0.3 ms a buffer on OpenTitan. + pub(super) fn republish_all(&mut self) { self.generation += 1; for uri in self.workspace.open_uris() { self.publish(&uri); } - self.timed(started, |took| format!("reindex_one({}) took {took}", path.display())); - true } /// [`Server::reindex`] for a `didOpen` that only ever **added** folders to diff --git a/crates/lucisv_server/src/server/notification.rs b/crates/lucisv_server/src/server/notification.rs index 6215f0d..5b73a02 100644 --- a/crates/lucisv_server/src/server/notification.rs +++ b/crates/lucisv_server/src/server/notification.rs @@ -25,6 +25,7 @@ use serde::de::DeserializeOwned; use super::batch::{widen_of, Widen}; use super::client::ms; use super::Server; +use crate::uri::uri_to_path; use crate::{file_ops, lint, settings, sync, watch}; impl Server { @@ -136,8 +137,18 @@ impl Server { } DidSaveTextDocument::METHOD => { if let Ok(p) = extract::(notification) { + // A save carrying the text the buffer already holds — the + // normal case, since every change was flushed above — has + // nothing to re-analyze. One carrying different text is a + // change the server missed: analyzed and published here, + // so the buffer's own answer is current whatever the + // reindex below finds moved. if let Some(text) = p.text { - self.set_document(p.text_document.uri.clone(), text); + let uri = p.text_document.uri.clone(); + if self.workspace.document(&uri).is_none_or(|doc| doc.text != text) { + self.set_document(uri.clone(), text); + self.publish(&uri); + } } // A save is one of the things that rebuild the index; the // others are a change to `lucisv.exclude`/`lucisv.filelist` @@ -160,15 +171,28 @@ impl Server { // the params carry a list, and a checkout fills it. DidChangeWatchedFiles::METHOD => { if let Ok(p) = extract::(notification) { + // Whatever else the event owes, every path it names may + // be what an `include` line was looking for — in scope or + // not, of a source extension or not (QA F1). A rescan + // re-resolves every line anyway, so only the paths that + // do not take one are refreshed here. + let named: Vec = + p.changes.iter().filter_map(|change| uri_to_path(&change.uri)).collect(); let filelist = self.workspace.filelist_path(); - if watch::touches_scope(&p.changes, filelist.as_deref()) { - // One file named is the incremental case; a checkout - // filling the list, or the filelist itself moving, is - // the whole rebuild. - let one = watch::one_scope_file(&p.changes, filelist.as_deref()); - if !one.is_some_and(|path| self.reindex_one(path.as_path())) { - self.reindex(); + if watch::names_a_config(&p.changes) { + // A `lucisv.toml` moves excludes, the filelist and + // the lint configuration at once — for the client + // that forwards it (ours registers sources only). + self.reindex(); + } else if watch::touches_scope(&p.changes, filelist.as_deref()) { + // The filelist itself moving is the whole rebuild; + // anything else is sorted file by file. + match watch::scope_files(&p.changes, filelist.as_deref()) { + Some(paths) => self.reindex_watched(&paths, &named), + None => self.reindex(), } + } else { + self.workspace.refresh_includes_naming(&named); } } } diff --git a/crates/lucisv_server/src/server/tests/localized_reindex.rs b/crates/lucisv_server/src/server/tests/localized_reindex.rs new file mode 100644 index 0000000..e87bdc4 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/localized_reindex.rs @@ -0,0 +1,754 @@ +//! The localized reindex held to a whole rebuild through the real server +//! (`docs/features/localized-reindex/README.md`). +//! +//! Every step goes through the notifications an editor sends — a change, a +//! save and the watcher's echo of it for an open buffer; a watcher event alone +//! for a file rewritten, created or deleted on disk — and after every step the +//! server's state is compared with what a whole rebuild over the same disk and +//! the same buffers gives: the index (postings and readers table included), +//! the completion tables, the include graph, every open buffer's cross-file +//! answers, and **the diagnostics last published for every open buffer**. The +//! last is the one the narrowing could get wrong without any table showing it: +//! a buffer the server decided not to republish must still be showing what a +//! fresh analysis would say. + +use std::collections::BTreeMap; + +use super::*; + +/// A session over a scratch tree, with what it last published per buffer. +struct Mirror { + tree: Tree, + session: Session, + open: BTreeMap, + shown: BTreeMap, + /// Whole rescans seen, so a sweep can say how much of it the narrowed + /// path carried. + rescans: usize, +} + +impl Mirror { + fn new(name: &str, files: &[(&str, &str)], open: &[&str]) -> Mirror { + let tree = Tree::new(name); + for (rel, text) in files { + tree.write(rel, text); + } + Mirror::over(tree, open) + } + + fn over(tree: Tree, open: &[&str]) -> Mirror { + let wide = ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + ..Default::default() + }; + Mirror::with(tree, open, wide) + } + + fn with(tree: Tree, open: &[&str], settings: ClientSettings) -> Mirror { + // A client that shows a bar, so a whole rescan is visible as one. + let abilities = + ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() }; + let session = Session::started(vec![tree.path.clone()], abilities, settings); + let mut mirror = + Mirror { tree, session, open: BTreeMap::new(), shown: BTreeMap::new(), rescans: 0 }; + for rel in open { + let path = mirror.tree.path.join(rel); + let text = std::fs::read_to_string(&path).expect("an open buffer's file is on disk"); + let uri = mirror.session.open(&path, &text); + mirror.open.insert(path, (uri, 1)); + } + mirror.absorb(); + mirror + } + + /// Remember the newest diagnostics the server pushed for each buffer, and + /// count the whole rescans (a progress bar begun) among the steps. + fn absorb(&mut self) { + for message in self.session.drain() { + let Message::Notification(n) = message else { continue }; + if n.method == PublishDiagnostics::METHOD { + let published: PublishDiagnosticsParams = + serde_json::from_value(n.params).expect("publish params"); + let shown = serde_json::to_value(&published.diagnostics).expect("diagnostics"); + self.shown.insert(published.uri.as_str().to_string(), shown); + } else if n.method == Progress::METHOD && n.params.to_string().contains("\"begin\"") { + self.rescans += 1; + } + } + } + + /// Write `rel` as an editor does: through its buffer when it is open (the + /// change, the save, the disk, the watcher's echo), else on disk alone + /// with the watcher's event. + fn write(&mut self, rel: &str, text: &str) { + let path = self.tree.path.join(rel); + let created = !path.exists(); + if let Some((uri, version)) = self.open.get_mut(&path) { + *version += 1; + let change = serde_json::json!({ + "textDocument": { "uri": uri, "version": *version }, + "contentChanges": [{ "text": text }], + }); + let save = serde_json::json!({ "textDocument": { "uri": uri } }); + self.session.notify(DidChangeTextDocument::METHOD, change); + self.tree.write(rel, text); + self.session.notify(DidSaveTextDocument::METHOD, save); + } else { + self.tree.write(rel, text); + } + let kind = if created { FileChangeType::CREATED } else { FileChangeType::CHANGED }; + self.event(&path, kind); + } + + /// Delete a closed file on disk, as a checkout does. + fn delete(&mut self, rel: &str) { + let path = self.tree.path.join(rel); + assert!(!self.open.contains_key(&path), "the sweep deletes closed files only"); + std::fs::remove_file(&path).expect("delete"); + self.event(&path, FileChangeType::DELETED); + } + + /// Save an open buffer that has not changed, and the watcher's echo — a + /// save the index records nothing about. + fn save_only(&mut self, rel: &str) { + let path = self.tree.path.join(rel); + let (uri, _) = self.open.get(&path).cloned().expect("an open buffer"); + let save = serde_json::json!({ "textDocument": { "uri": uri } }); + self.session.notify(DidSaveTextDocument::METHOD, save); + self.event(&path, FileChangeType::CHANGED); + } + + /// Rewrite an open buffer's file on disk behind the editor's back: the + /// editor reloads the clean buffer (a change carrying the disk's text), + /// and the watcher reports the file. No save. + fn disk_only(&mut self, rel: &str, text: &str) { + let path = self.tree.path.join(rel); + self.tree.write(rel, text); + if let Some((uri, version)) = self.open.get_mut(&path) { + *version += 1; + let change = serde_json::json!({ + "textDocument": { "uri": uri, "version": *version }, + "contentChanges": [{ "text": text }], + }); + self.session.notify(DidChangeTextDocument::METHOD, change); + } + self.event(&path, FileChangeType::CHANGED); + } + + /// Open a file that is on disk, after the startup scan. + fn open_file(&mut self, rel: &str) { + let path = self.tree.path.join(rel); + let text = std::fs::read_to_string(&path).expect("on disk"); + let uri = self.session.open(&path, &text); + self.open.insert(path, (uri, 1)); + } + + fn event(&mut self, path: &Path, typ: FileChangeType) { + let changes = vec![FileEvent { uri: path_to_uri(path).expect("uri"), typ }]; + self.session.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes }); + } + + /// The whole claim: what the server holds and last showed is what a whole + /// rebuild over the same disk and buffers gives. The rebuild is done in + /// place, so a run that passes goes on from the state it already had. + fn holds(&mut self, step: &str) { + self.absorb(); + let workspace = &mut self.session.server.workspace; + let incremental = workspace.derived_fingerprint(); + workspace.rebuild_index(); + let rebuilt = workspace.derived_fingerprint(); + if incremental != rebuilt { + let first = incremental.lines().zip(rebuilt.lines()).find(|(a, b)| a != b); + panic!("{step}: the incremental state is not a rebuild's; first difference {first:?}"); + } + for (uri, _) in self.open.values() { + let fresh = self.session.server.diagnostics_of(uri); + let fresh = serde_json::to_value(&fresh).expect("diagnostics"); + let shown = self.shown.get(uri.as_str()).cloned().unwrap_or(Value::Null); + assert_eq!(shown, fresh, "{step}: {} shows stale diagnostics", uri.as_str()); + } + } + + /// Every step, each followed by the check. + fn steps(&mut self, steps: &[(&str, &str)]) { + self.holds("before any step"); + for (at, (rel, text)) in steps.iter().enumerate() { + self.write(rel, text); + self.holds(&format!("step {at}, `{rel}`")); + } + } +} + +const LEAF: &str = + "module leaf (input logic clk, output logic q);\n logic s;\n assign q = s;\nendmodule\n"; +const TOP: &str = "module top;\n logic c, d;\n leaf u_leaf (.clk(c), .q(d));\nendmodule\n"; +const TB: &str = "module tb;\n top dut ();\n initial $display(dut.u_leaf.s);\nendmodule\n"; +const PKG: &str = + "package cfg_pkg;\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n"; +const USER: &str = "module user import cfg_pkg::*; (input word_t a, output word_t b);\n assign b = a + W;\nendmodule\n"; +const DEFS: &str = "`define WIDTH 8\n`define CLOG(x) $clog2(x)\n"; +const INCLUDER: &str = + "`include \"defs.svh\"\nmodule includer;\n logic [`WIDTH-1:0] v;\nendmodule\n"; + +fn design() -> Vec<(&'static str, &'static str)> { + vec![ + ("rtl/leaf.sv", LEAF), + ("rtl/top.sv", TOP), + ("dv/tb.sv", TB), + ("rtl/cfg_pkg.sv", PKG), + ("rtl/user.sv", USER), + ("rtl/defs.svh", DEFS), + ("rtl/includer.sv", INCLUDER), + ] +} + +#[test] +fn every_kind_of_edit_to_an_open_module_leaves_the_rebuilt_state_and_every_squiggle() { + let mut mirror = + Mirror::new("lr_module", &design(), &["rtl/leaf.sv", "rtl/top.sv", "dv/tb.sv"]); + let open_leaf = |text: &str| ("rtl/leaf.sv", text.to_string()); + let steps = [ + // Nothing the index records: a comment after the last token. + open_leaf(&format!("{LEAF}// trailing\n")), + // A body edit, a local signal, a comment above everything. + open_leaf(&LEAF.replace("assign q = s;", "assign q = ~s;")), + open_leaf(&LEAF.replace(" logic s;\n", " logic s;\n logic t;\n")), + open_leaf(&format!("// above\n{LEAF}")), + // The port list: renamed, removed, added — `top` connects by name, so + // its unknown-port squiggles must follow without `top` being saved. + open_leaf(&LEAF.replace("input logic clk", "input logic clock")), + open_leaf(&LEAF.replace("input logic clk, ", "")), + open_leaf(&LEAF.replace("output logic q", "output logic q, input logic en")), + // The signal the testbench names hierarchically, gone and back. + open_leaf(&LEAF.replace("logic s;\n assign q = s;", "logic r;\n assign q = r;")), + // The module renamed away, so `top`'s instantiation resolves nowhere. + open_leaf(&LEAF.replace("module leaf", "module leaf2")), + open_leaf(LEAF), + ]; + let steps: Vec<(&str, &str)> = steps.iter().map(|(rel, text)| (*rel, text.as_str())).collect(); + mirror.steps(&steps); +} + +#[test] +fn edits_to_a_closed_package_a_define_header_and_an_include_line_all_hold() { + let mut mirror = Mirror::new("lr_package", &design(), &["rtl/user.sv", "rtl/includer.sv"]); + let user_text = USER.replace("+ W", "+ W + DEPTH"); + let pkg_depth = + PKG.replace("localparam int W = 8;", "localparam int W = 8;\n localparam int DEPTH = 4;"); + let defs_more = format!("{DEFS}`define DEPTH 4\n"); + let includer_none = INCLUDER.replace("`include \"defs.svh\"\n", ""); + let pkg_renamed = PKG.replace("package cfg_pkg", "package cfg2_pkg"); + let defs_wider = DEFS.replace("8", "16"); + let defs_params = DEFS.replace("CLOG(x)", "CLOG(x, y)"); + let includer_nowhere = INCLUDER.replace("defs.svh", "nowhere.svh"); + let steps: Vec<(&str, &str)> = vec![ + // A package member the open user does not name yet, then does. + ("rtl/cfg_pkg.sv", &pkg_depth), + ("rtl/user.sv", &user_text), + // The package member it names, gone. + ("rtl/cfg_pkg.sv", PKG), + // The package renamed. + ("rtl/cfg_pkg.sv", &pkg_renamed), + ("rtl/cfg_pkg.sv", PKG), + // A define header: a value, a new macro, a parameter list. + ("rtl/defs.svh", &defs_wider), + ("rtl/defs.svh", &defs_more), + ("rtl/defs.svh", &defs_params), + // An include line removed and put back, and one that resolves nowhere. + ("rtl/includer.sv", &includer_none), + ("rtl/includer.sv", INCLUDER), + ("rtl/includer.sv", &includer_nowhere), + ("rtl/includer.sv", INCLUDER), + ]; + mirror.steps(&steps); +} + +#[test] +fn a_signal_another_file_mentions_keeps_its_lint_answer_as_the_mention_comes_and_goes() { + // `unused-signal` consults the workspace census: `dbg` is unused in + // `probe.sv` but named by `peek.sv`, which is closed. The open buffer is + // never saved here, so only a republish the narrowing owed can move it. + let probe = "module probe;\n logic dbg;\nendmodule\n"; + let peek = "module peek;\n initial $display(probe.dbg);\nendmodule\n"; + let mut mirror = + Mirror::new("lr_census", &[("probe.sv", probe), ("peek.sv", peek)], &["probe.sv"]); + mirror.steps(&[ + ("peek.sv", "module peek;\n initial $display(1);\nendmodule\n"), + ("peek.sv", peek), + ("peek.sv", &format!("{peek}// a comment that moves nothing\n")), + ]); +} + +#[test] +fn files_created_and_deleted_beside_open_buffers_hold() { + let mut mirror = Mirror::new("lr_files", &design(), &["rtl/top.sv", "rtl/includer.sv"]); + mirror.holds("before any step"); + // A second `leaf` makes the instantiation ambiguous; deleting it heals it. + mirror.write("rtl/zz_leaf.sv", LEAF); + mirror.holds("a duplicate module created"); + mirror.delete("rtl/zz_leaf.sv"); + mirror.holds("and deleted"); + mirror.delete("rtl/defs.svh"); + mirror.holds("an included header deleted"); + mirror.write("rtl/defs.svh", DEFS); + mirror.holds("and recreated"); +} + +#[test] +fn a_watcher_event_for_a_file_the_scope_cannot_take_costs_no_rescan() { + // A generated file under a gitignored directory, and a file outside the + // workspace root: neither can change the index, so neither may cost the + // progress bar — and the state is still a rebuild's. + let mut mirror = Mirror::new("lr_outside", &design(), &["rtl/top.sv"]); + mirror.tree.write(".gitignore", "build/\n"); + mirror.holds("before any step"); + let _ = mirror.session.drain(); + mirror.write("build/gen.sv", "module gen;\nendmodule\n"); + assert!(mirror.session.progress().is_empty(), "no bar for a gitignored file"); + mirror.holds("a generated file under build/"); + let outside = Tree::new("lr_outside_elsewhere"); + outside.write("far.sv", "module far;\nendmodule\n"); + let _ = mirror.session.drain(); + mirror.event(&outside.path.join("far.sv"), FileChangeType::CHANGED); + assert!(mirror.session.progress().is_empty(), "no bar for a file outside every root"); + mirror.holds("a file outside the root"); + // A file the scope does take, appearing, is still the whole rebuild — + // which is also what proves the two assertions above can fail. + mirror.rescans = 0; + mirror.write("rtl/new.sv", "module fresh;\nendmodule\n"); + mirror.holds("a new file in scope"); + assert_eq!(mirror.rescans, 1, "a file the scope takes appearing is a rescan"); + assert!( + mirror.session.server.workspace.index().units("fresh").len() == 1, + "the new file is in the index" + ); +} + +#[test] +fn a_buffer_opened_from_outside_the_filelist_joins_the_index_on_its_first_save() { + // VS Code restores editors while the startup scan runs; one outside the + // filelist is open but not indexed until something rebuilds. Its first + // save used to be that rebuild, bar and all. + let mut files = design(); + files.push(("rtl/waits.sv", "`include \"late.svh\"\nmodule waits;\nendmodule\n")); + files.push(("files.f", "rtl/leaf.sv\nrtl/top.sv\nrtl/cfg_pkg.sv\nrtl/waits.sv\n")); + let tree = Tree::new("lr_filelist"); + for (rel, text) in &files { + tree.write(rel, text); + } + let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() }; + let mut mirror = Mirror::with(tree, &["rtl/top.sv", "dv/tb.sv"], listed); + mirror.rescans = 0; + mirror.write("dv/tb.sv", &TB.replace("$display", "$write")); + mirror.holds("the first save of the unlisted buffer"); + assert_eq!(mirror.rescans, 0, "the buffer was on disk before the scan: no rescan"); + assert!(mirror.session.server.workspace.index().units("tb").len() == 1, "and it is indexed"); + // A file born after the scan may be what some `include` was waiting + // for — `waits.sv`'s is: its lines are re-resolved, still no rebuild. + mirror.write("rtl/late.svh", "`define LATE 1\n"); + let path = mirror.tree.path.join("rtl/late.svh"); + let uri = mirror.session.open(&path, "`define LATE 1\n"); + mirror.open.insert(path, (uri, 1)); + mirror.rescans = 0; + mirror.write("rtl/late.svh", "`define LATE 2\n"); + mirror.holds("the first save of a buffer younger than the scan"); + assert_eq!(mirror.rescans, 0, "the include waiting for it is re-resolved in place"); + let graph = mirror.session.server.workspace.includes(); + assert_eq!(graph.reachable(vec![mirror.tree.path.join("rtl/waits.sv")]).len(), 2, "and found"); +} + +/// QA F1: a header the scope cannot take, appearing and vanishing, moves an +/// in-scope includer's edge — an include is resolved against the disk. +#[test] +fn a_header_outside_the_scope_created_and_deleted_moves_the_includers_edges() { + let files = [ + (".gitignore", "gen/\n"), + ("rtl/a.sv", "`include \"../gen/h.svh\"\nmodule a;\nendmodule\n"), + ("rtl/a_inc.svh", "`include \"../gen/h.svh\"\n`define AW 2\n"), + ("rtl/b.sv", "`include \"a_inc.svh\"\nmodule b;\nendmodule\n"), + ]; + let mut mirror = Mirror::new("lr_f1_ignored", &files, &["rtl/b.sv"]); + mirror.steps(&[("gen/h.svh", "`define GEN_W 4\n")]); + mirror.rescans = 0; + mirror.delete("gen/h.svh"); + mirror.holds("the ignored header deleted"); + mirror.write("gen/h.svh", "`define GEN_W 5\n"); + mirror.holds("and created again"); + assert_eq!(mirror.rescans, 0, "the include graph alone, never a rescan"); +} + +/// QA R2-1: one event naming a burst of files is sorted path by path only +/// while that is cheaper than a rescan (`BURST_DIVISOR`); past it the event +/// takes the whole rescan. The state is a rebuild's on both sides. +#[test] +fn a_burst_of_created_files_is_sorted_below_the_threshold_and_rescanned_above() { + let mut files = design(); + files.push((".gitignore", "gen/\n")); + files.push(("rtl/waits.sv", "`include \"../gen/h0.svh\"\nmodule waits;\nendmodule\n")); + let mut mirror = Mirror::new("lr_burst", &files, &["rtl/top.sv"]); + mirror.holds("before any step"); + let held = mirror.session.server.workspace.index().files().len(); + let burst = |mirror: &mut Mirror, count: usize, tag: &str| { + let changes: Vec = (0..count) + .map(|k| { + let rel = format!("gen/{tag}{k}.svh"); + mirror.tree.write(&rel, &format!("`define {}{k} 1\n", tag.to_uppercase())); + let path = mirror.tree.path.join(rel); + FileEvent { uri: path_to_uri(&path).expect("uri"), typ: FileChangeType::CREATED } + }) + .collect(); + let params = DidChangeWatchedFilesParams { changes }; + mirror.session.notify(DidChangeWatchedFiles::METHOD, params); + }; + mirror.rescans = 0; + burst(&mut mirror, held / 2, "h"); + mirror.holds("a burst at the threshold, `h0.svh` among it"); + assert_eq!(mirror.rescans, 0, "sorted path by path: {held} held, {} named", held / 2); + burst(&mut mirror, held / 2 + 1, "k"); + mirror.write("gen/h0.svh", "`define H0 2\n"); + mirror.holds("a burst past the threshold"); + assert_eq!(mirror.rescans, 1, "one path more is the whole rescan"); +} + +/// QA F1, filelist mode: an unlisted header under an `+incdir+`. +#[test] +fn an_unlisted_header_under_an_incdir_created_moves_the_includers_edge() { + let files = [ + ("files.f", "+incdir+inc\nrtl/a.sv\nrtl/top.sv\n"), + ("rtl/a.sv", "`include \"h2.svh\"\nmodule a;\nendmodule\n"), + ("rtl/top.sv", "module top;\n a u_a ();\nendmodule\n"), + ]; + let tree = Tree::new("lr_f1_incdir"); + for (rel, text) in files { + tree.write(rel, text); + } + let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() }; + let mut mirror = Mirror::with(tree, &["rtl/top.sv"], listed); + mirror.holds("before any step"); + mirror.write("inc/h2.svh", "`define H2 1\n"); + mirror.holds("the unlisted header created"); + mirror.delete("inc/h2.svh"); + mirror.holds("and deleted"); +} + +/// QA F2: a `[lint]` edit in `lucisv.toml`, which no notification reports, +/// takes effect at the next save — even one the index records nothing about. +#[test] +fn a_lint_configuration_edit_takes_effect_at_a_save_that_moves_nothing() { + let lint_me = "module lint_me;\n\twire unused_w; \n reg r;\nendmodule\n"; + let mut mirror = Mirror::new("lr_f2_toml", &[("rtl/lint_me.sv", lint_me)], &["rtl/lint_me.sv"]); + mirror.holds("before any step"); + let uri = mirror.open.values().next().map(|(uri, _)| uri.as_str().to_string()).expect("open"); + assert_ne!(mirror.shown.get(&uri), Some(&Value::Array(Vec::new())), "premise: findings"); + mirror.tree.write( + "lucisv.toml", + "[lint]\nignore = [\"no-tabs\", \"no-trailing-whitespace\", \"unused-signal\"]\n", + ); + mirror.save_only("rtl/lint_me.sv"); + mirror.holds("the save after the lint configuration changed"); + mirror.tree.write("lucisv.toml", "[lint]\n"); + mirror.save_only("rtl/lint_me.sv"); + mirror.holds("and after it changed back"); +} + +/// QA F3: a file moved in from elsewhere after the scan keeps its old times; +/// opened and saved, it joins the index and its waiting includer finds it. +/// No watcher event is sent for the move — a client that does not watch, or +/// an event coalesced away — so the save alone must re-resolve the includer +/// (the event's own re-resolution is F1's test). +#[test] +fn a_file_moved_in_after_the_scan_joins_and_is_found_by_its_includer() { + let files = [ + ("files.f", "rtl/a.sv\nrtl/top.sv\n"), + ("rtl/a.sv", "`include \"late.svh\"\nmodule a;\nendmodule\n"), + ("rtl/top.sv", "module top;\n a u_a ();\nendmodule\n"), + ]; + let elsewhere = Tree::new("lr_f3_elsewhere"); + elsewhere.write("late.svh", "`define LATE 7\n"); + let tree = Tree::new("lr_f3_moved"); + for (rel, text) in files { + tree.write(rel, text); + } + let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() }; + let mut mirror = Mirror::with(tree, &["rtl/top.sv"], listed); + mirror.holds("before any step"); + let moved = mirror.tree.path.join("rtl/late.svh"); + std::fs::rename(elsewhere.path.join("late.svh"), &moved).expect("move in"); + mirror.open_file("rtl/late.svh"); + let (uri, _) = mirror.open[&moved].clone(); + let save = serde_json::json!({ "textDocument": { "uri": uri } }); + mirror.session.notify(DidSaveTextDocument::METHOD, save); + mirror.holds("opened and saved, with no watcher echo"); +} + +/// QA F4: an excluded buffer, open and changed on disk, is taken in, as a +/// fresh server takes every open buffer in. +#[test] +fn an_excluded_open_buffer_changed_on_disk_is_taken_in() { + let files = [ + ("lucisv.toml", "exclude = [\"rtl/b.sv\"]\n"), + ("rtl/b.sv", "module b;\nendmodule\n"), + ("rtl/top.sv", "module top;\n b u_b ();\nendmodule\n"), + ]; + let mut mirror = Mirror::new("lr_f4_excluded", &files, &["rtl/top.sv"]); + mirror.holds("before any step"); + mirror.open_file("rtl/b.sv"); + mirror.disk_only("rtl/b.sv", "module b;\n wire w2;\nendmodule\n"); + mirror.holds("the excluded buffer changed on disk"); + assert_eq!(mirror.session.server.workspace.index().units("b").len(), 1, "taken in"); +} + +#[cfg(unix)] +#[test] +fn a_held_file_reported_by_its_real_path_takes_the_one_file_update() { + // The workspace is opened through a symlink; the watcher reports the real + // path. Before this round that was a "file the index does not hold" and a + // whole rescan per save. + let real = Tree::new("lr_real"); + for (rel, text) in design() { + real.write(rel, text); + } + let link = Tree::new("lr_link"); + std::fs::remove_dir_all(&link.path).expect("make room for the link"); + std::os::unix::fs::symlink(&real.path, &link.path).expect("symlink"); + let abilities = + ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() }; + let mut session = Session::wide_with(vec![link.path.clone()], abilities); + let _ = session.drain(); + real.write("rtl/leaf.sv", &LEAF.replace("input logic clk", "input logic clock")); + session.watched(&[real.path.join("rtl/leaf.sv")]); + assert!(session.progress().is_empty(), "the one-file path, not a rescan"); + let index = session.server.workspace.index(); + assert_eq!(index.member("leaf", "clock").len(), 1, "and the update landed"); + assert!( + index.files().iter().all(|path| path.starts_with(&link.path)), + "under the link's spelling" + ); + let _ = std::fs::remove_file(&link.path); +} + +// ---------------------------------------------------------------------- +// The seeded sweep +// ---------------------------------------------------------------------- + +/// xorshift64*: reproducible from a seed, no dependency. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } +} + +/// One random edit: a line inserted, deleted, duplicated or swapped with its +/// neighbour, or one identifier renamed to another the file already uses — +/// edits that move spans, names and whole declarations. +fn mutate(text: &str, rng: &mut Rng) -> String { + let mut lines: Vec = text.lines().map(str::to_string).collect(); + let at = rng.below(lines.len() + 1); + match rng.below(6) { + 0 => lines.insert(at, " // lucisv sweep".to_string()), + 1 if at < lines.len() => { + lines.remove(at); + } + 2 if at < lines.len() => { + let line = lines[at].clone(); + lines.insert(at, line); + } + 3 if at + 1 < lines.len() => lines.swap(at, at + 1), + 4 => lines.insert(at, " logic lucisv_sweep_q;".to_string()), + _ => { + let words = vlog_semantic::words::harvest_text(text); + if words.len() >= 2 { + let from = words[rng.below(words.len())].clone(); + let to = words[rng.below(words.len())].clone(); + if let Some(line) = lines.iter_mut().find(|line| line.contains(from.as_str())) { + *line = line.replacen(from.as_str(), &to, 1); + } + } + } + } + let mut out = lines.join("\n"); + out.push('\n'); + out +} + +/// `steps` seeded mutations over every source file under `tree`, with `open` +/// buffers open, each step checked; now and then a closed file is deleted or +/// a new one created. +fn sweep(tree: Tree, open: usize, seed: u64, steps: usize) { + // `opened` below is also what the lint-configuration step saves. + let mut files: Vec = Vec::new(); + collect(&tree.path, &tree.path, &mut files); + files.sort(); + assert!(!files.is_empty(), "premise: a tree with sources in it"); + let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); + let opened: Vec = (0..open).map(|_| files[rng.below(files.len())].clone()).collect(); + let opened_refs: Vec<&str> = opened.iter().map(String::as_str).collect(); + // The setting the event kinds QA found need: a gitignored `gen/` whose + // headers an in-scope file waits for, and excluded names to open. + tree.write(".gitignore", "gen/\n"); + tree.write("lucisv.toml", "exclude = [\"sweep_excluded_*\"]\n"); + let waits: String = (0..4).map(|k| format!("`include \"gen/h{k}.svh\"\n")).collect(); + tree.write("sweep_waits.sv", &format!("{waits}module sweep_waits;\nendmodule\n")); + let elsewhere = Tree::new(&format!("lr_sweep_elsewhere_{seed}")); + let mut mirror = Mirror::over(tree, &opened_refs); + mirror.holds(&format!("seed {seed}: before any step")); + mirror.rescans = 0; + for step in 0..steps { + let rel = files[rng.below(files.len())].clone(); + let path = mirror.tree.path.join(&rel); + let label = format!("seed {seed}, step {step}, `{rel}`"); + match rng.below(24) { + 0 if !mirror.open.contains_key(&path) && path.exists() => mirror.delete(&rel), + 1 => mirror.write(&format!("sweep_new_{step}.sv"), "module sweep_new;\nendmodule\n"), + // A header outside the scope, waited for, toggled. + 2 => { + let header = format!("gen/h{}.svh", rng.below(4)); + match mirror.tree.path.join(&header).exists() { + true => mirror.delete(&header), + false => mirror.write(&header, &format!("`define SWEEP_{step} 1\n")), + } + } + // The lint configuration edited, then a save that moves nothing. + 3 => { + let rules = ["no-tabs", "unused-signal", "line-length", "no-trailing-whitespace"]; + let ignored: Vec = rules + .iter() + .filter(|_| rng.below(2) == 0) + .map(|r| format!("\"{r}\"")) + .collect(); + let config = format!( + "exclude = [\"sweep_excluded_*\"]\n[lint]\nignore = [{}]\n", + ignored.join(", ") + ); + mirror.tree.write("lucisv.toml", &config); + if let Some(open) = opened.get(rng.below(opened.len().max(1))) { + mirror.save_only(open); + } + } + // A file moved in from elsewhere, old times and all, then opened + // and saved. + 4 => { + let name = format!("sweep_moved_{step}.svh"); + elsewhere.write(&name, &format!("`define SWEEP_MOVED_{step} 1\n")); + let to = mirror.tree.path.join("gen").join(&name); + std::fs::create_dir_all(mirror.tree.path.join("gen")).expect("gen/"); + std::fs::rename(elsewhere.path.join(&name), &to).expect("move in"); + mirror.event(&to, FileChangeType::CREATED); + let rel = format!("gen/{name}"); + mirror.open_file(&rel); + mirror.save_only(&rel); + } + // An excluded file, opened, then changed on disk. + 5 => { + let rel = format!("sweep_excluded_{step}.sv"); + mirror.write(&rel, &format!("module sweep_excluded_{step};\nendmodule\n")); + mirror.open_file(&rel); + let text = format!("module sweep_excluded_{step};\n wire w;\nendmodule\n"); + mirror.disk_only(&rel, &text); + } + _ => { + let Ok(text) = std::fs::read_to_string(&path) else { continue }; + let text = match mirror.open.contains_key(&path) { + true => mirror.session.server.workspace.text_of(&path).unwrap_or(text), + false => text, + }; + mirror.write(&rel, &mutate(&text, &mut rng)); + } + } + mirror.holds(&label); + } + eprintln!( + "seed {seed}: {steps} steps over {} files, {} of them whole rescans", + files.len(), + mirror.rescans + ); +} + +fn collect(root: &Path, dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + collect(root, &path, out); + } else if crate::watch::watched(&path, None) { + if let Ok(rel) = path.strip_prefix(root) { + out.push(rel.to_string_lossy().into_owned()); + } + } + } +} + +/// Copy every source file under `from` into `tree` under `prefix`, saying +/// how many — none when `from` is not on this machine. +fn copy_into(tree: &Tree, from: &Path, prefix: &str) -> usize { + let mut files: Vec = Vec::new(); + collect(from, from, &mut files); + for rel in &files { + let Ok(text) = std::fs::read_to_string(from.join(rel)) else { continue }; + tree.write(&format!("{prefix}{rel}"), &text); + } + files.len() +} + +fn home(rel: &str) -> PathBuf { + std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default().join(rel) +} + +#[test] +fn a_seeded_sweep_over_the_hand_written_design_holds() { + for seed in 1..=3 { + let tree = Tree::new(&format!("lr_sweep_{seed}")); + for (rel, text) in design() { + tree.write(rel, text); + } + sweep(tree, 3, seed, 25); + } +} + +/// `tools/guard.sh -- cargo test --release -p lucisv_server sweep_over_the_corpus -- --ignored --nocapture` +#[test] +#[ignore = "a sweep over ~/.cache/lucisv-corpus, minutes in a debug build"] +fn a_seeded_sweep_over_the_corpus_holds() { + let from = std::env::var_os("LUCISV_CORPUS") + .map(PathBuf::from) + .unwrap_or_else(|| home(".cache/lucisv-corpus")); + for seed in [11, 12, 13] { + let tree = Tree::new(&format!("lr_corpus_{seed}")); + if copy_into(&tree, &from, "") == 0 { + eprintln!("{} not present — skipping", from.display()); + return; + } + sweep(tree, 5, seed, 60); + } +} + +/// `tools/guard.sh -- cargo test --release -p lucisv_server sweep_over_an_opentitan -- --ignored --nocapture` +#[test] +#[ignore = "a sweep over a sample of OpenTitan, minutes in a debug build"] +fn a_seeded_sweep_over_an_opentitan_sample_holds() { + let hw = std::env::var_os("LUCISV_OPENTITAN") + .map(PathBuf::from) + .unwrap_or_else(|| home(".cache/lucisv-opentitan-full/hw")); + for seed in [21, 22] { + let tree = Tree::new(&format!("lr_opentitan_{seed}")); + let mut copied = 0; + for sub in ["ip/uart/", "ip/gpio/", "ip/prim/rtl/", "ip/prim_generic/rtl/", "ip/tlul/rtl/"] + { + copied += copy_into(&tree, &hw.join(sub), sub); + } + if copied == 0 { + eprintln!("{} not present — skipping", hw.display()); + return; + } + sweep(tree, 6, seed, 60); + } +} diff --git a/crates/lucisv_server/src/server/tests/mod.rs b/crates/lucisv_server/src/server/tests/mod.rs index cbf7383..52aab2f 100644 --- a/crates/lucisv_server/src/server/tests/mod.rs +++ b/crates/lucisv_server/src/server/tests/mod.rs @@ -56,6 +56,7 @@ mod hierarchy_reach; mod index; mod large_file; mod lint_snapshot; +mod localized_reindex; mod progress; mod pull_diagnostics; mod qa_generate_label; diff --git a/crates/lucisv_server/src/server/tests/pull_diagnostics.rs b/crates/lucisv_server/src/server/tests/pull_diagnostics.rs index f3bbfa6..de0d737 100644 --- a/crates/lucisv_server/src/server/tests/pull_diagnostics.rs +++ b/crates/lucisv_server/src/server/tests/pull_diagnostics.rs @@ -81,17 +81,36 @@ fn an_index_rebuild_moves_the_result_id_too() { // `inter_file_dependencies: true` is a promise: a save rebuilds the // index, and what the index says can change what a *different* buffer // reports. A stale "unchanged" there would be a wrong squiggle. + // + // Since localized-reindex (2026-11-19) the save whose record did not move + // still moves the stamp — a lint reads `lucisv.toml` from disk, and a + // save is when an edit to it takes effect (QA F2) — and so does the save + // of an edit the index has not seen. let tree = Tree::new("pullreindex"); let mut session = Session::with(vec![tree.path.clone()], pulling()); let uri = session.open(&tree.path.join("m.sv"), BROKEN); - let stamp = document_pull(&mut session, &uri, None)["resultId"] - .as_str() - .expect("a result id") - .to_string(); + let stamp = |session: &mut Session, previous: Option<&str>| { + document_pull(session, &uri, previous)["resultId"] + .as_str() + .expect("a result id") + .to_string() + }; + let first = stamp(&mut session, None); + let save = serde_json::json!({ "textDocument": { "uri": uri } }); + session.notify(DidSaveTextDocument::METHOD, save.clone()); + let after = document_pull(&mut session, &uri, Some(&first)); + assert_eq!(after["kind"], "full", "a save that moved no record: {after:#?}"); - session - .notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })); - let after = document_pull(&mut session, &uri, Some(&stamp)); + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ "text": "module m;\n\twire ;\n wire extra;\nendmodule\n" }], + }), + ); + let edited = stamp(&mut session, Some(&first)); + session.notify(DidSaveTextDocument::METHOD, save); + let after = document_pull(&mut session, &uri, Some(&edited)); assert_eq!(after["kind"], "full", "the index moved: {after:#?}"); } diff --git a/crates/lucisv_server/src/server/tests/requests.rs b/crates/lucisv_server/src/server/tests/requests.rs index 506eb16..ea91730 100644 --- a/crates/lucisv_server/src/server/tests/requests.rs +++ b/crates/lucisv_server/src/server/tests/requests.rs @@ -201,9 +201,22 @@ fn a_rescan_asks_a_capable_client_to_refresh_its_code_lenses() { let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n"); let _ = session.drain(); - // Every rescan trigger, one refresh each. + // Every rescan trigger, one refresh each — a save of an edit the index + // has not seen, since a save that moved nothing refreshes nothing + // (localized-reindex, 2026-11-19). session .notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })); + assert!(session.requests().is_empty(), "a save that moved nothing asks for nothing"); + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }], + }), + ); + session + .notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })); + tree.write("top.sv", "module top;\n sub u_a ();\nendmodule\n"); session.watched(&[tree.path.join("top.sv")]); session.notify( DidChangeConfiguration::METHOD, @@ -223,9 +236,22 @@ fn a_client_that_cannot_refresh_code_lenses_is_never_asked_to() { let mut session = Session::new(vec![tree.path.clone()], false); let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n"); let _ = session.drain(); + // A save of an edit the index has not seen, so the save path really + // moves the index (a save that moves nothing refreshes nothing anyway). + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }], + }), + ); session .notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })); + tree.write("top.sv", "module top;\n sub u_a ();\nendmodule\n"); session.watched(&[tree.path.join("top.sv")]); + let index = session.server.workspace.index(); + let w = index.member_in("sub", "w", vlog_semantic::Surface::Hierarchical); + assert_eq!(w.len(), 1, "premise: the save moved the index"); assert!(session.requests().is_empty(), "silence, on every rescan path"); } @@ -368,6 +394,14 @@ fn qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh() { .open(&tree.path.join("top.sv"), "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n"); let _ = session.drain(); + // An edit the index has not seen, so the save moves it. + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }], + }), + ); session .notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })); let methods: Vec = session.requests().into_iter().map(|(method, _)| method).collect(); diff --git a/crates/lucisv_server/src/state/discover.rs b/crates/lucisv_server/src/state/discover.rs index f0ea2e3..81c76db 100644 --- a/crates/lucisv_server/src/state/discover.rs +++ b/crates/lucisv_server/src/state/discover.rs @@ -389,18 +389,10 @@ impl Workspace { // The walk names its inputs as strings; every directory here came // from a `file:` URI, which cannot carry a non-UTF-8 path. let Some(input) = root.to_str() else { continue }; - // A broken `lucisv.toml` must not stop the server from indexing: an - // index that excludes nothing is a far better failure than a - // server that comes up empty. The error is reported when the user - // formats a file in this tree (`format::settings_for`). + // A broken `lucisv.toml` excludes nothing, and the client's + // `lucisv.exclude` is appended to it — see `walk_excludes`. let configuring = trace.now(); - let mut exclude = - discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default(); - // The client's `lucisv.exclude` is *appended*, never substituted — - // the CLI appends a config's excludes to `--exclude` the same way, - // and a setting that silently dropped a checked-in exclude would - // put vendored code back in the index for one user only. - exclude.extend(self.client.exclude.iter().cloned()); + let exclude = self.walk_excludes(&mut discovery, root); ScanTrace::add(&mut trace.config_ms, configuring); // `.gitignore` is always honoured: it is the CLI's default, and an // editor has no `--no-gitignore` to type. An unreadable directory diff --git a/crates/lucisv_server/src/state/incremental.rs b/crates/lucisv_server/src/state/incremental.rs index 9e04856..0793699 100644 --- a/crates/lucisv_server/src/state/incremental.rs +++ b/crates/lucisv_server/src/state/incremental.rs @@ -1,96 +1,231 @@ //! Re-indexing one saved file the index already holds, patching every //! table rather than rebuilding it — the cheap path a `didSave` takes -//! before falling back to a whole rescan. +//! before falling back to a whole rescan — and doing only the work the +//! file's change can reach (`docs/features/localized-reindex/README.md`). -use std::path::Path; +use std::collections::HashSet; +use std::path::{Path, PathBuf}; + +use lucisv_core::walk::dir_id; + +use vlog_semantic::FileFacts; use super::Workspace; use crate::scan_trace::ScanTrace; +/// What [`Workspace::update_one_file`] did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OneFile { + /// The index does not hold the file; the caller owes a whole rebuild. + NotHeld, + /// The file's record is the one the index already held — the watcher's + /// echo of a save, or a save that changed nothing the index records — so + /// nothing derived from the index moved and no other buffer's answer can + /// have either. + Unchanged, + /// The index moved, and every open buffer's overlay was refreshed. + Changed, +} + impl Workspace { + /// [`Workspace::update_one_file`], for a test that only asks whether the + /// cheap path was taken. + #[cfg(test)] + pub fn update_one(&mut self, path: &Path) -> bool { + self.update_one_file(path) != OneFile::NotHeld + } + /// Rebuild the index for **one** file, leaving every other file's - /// contribution exactly as it is. Reports whether it could. + /// contribution exactly as it is, and say what moved. /// - /// `false` means the caller must fall back to [`Workspace::rebuild_index`]: - /// the file is not one this index already holds, which is the one case the - /// cheap path cannot settle. A file appearing changes which *other* files - /// exist as far as the include graph is concerned (a `` `include`` that had - /// nothing to resolve to now has something), and answering that takes a - /// walk — so the rule is simply "a file the index already holds". + /// [`OneFile::NotHeld`] means the caller must fall back to + /// [`Workspace::rebuild_index`]: the file is not one this index already + /// holds, which the cheap path settles only for an open buffer older than + /// the last whole scan ([`Workspace::add_open_buffer`]). A file appearing + /// changes which *other* files exist as far as the include graph is + /// concerned (a `` `include`` that had nothing to resolve to now has + /// something), and answering that takes a walk. /// /// The four pieces of state a rebuild produces, and what happens to each: /// - /// * **the workspace index** — [`WorkspaceIndex::update_file`] / + /// * **the workspace index** — [`WorkspaceIndex::update_facts`] / /// [`WorkspaceIndex::remove_file`], which promise the index a whole - /// rebuild over the same file set would have produced; - /// * **the completion tables** — the two index-derived ones re-derived, the - /// word table patched by this file's words alone; - /// * **the include graph** — this file's edges re-scanned, the known-file - /// and folded-spelling tables re-learned from the index's list; - /// * **every open buffer's overlay** — refreshed, exactly as a rebuild - /// refreshes it, because any of them may resolve into the file that moved. + /// rebuild over the same file set would have produced, and say when the + /// record did not move at all; + /// * **the completion tables** — the word table patched by this file's + /// words, and the two index-derived ones re-derived for the names this + /// file declared or declares, only when it now declares something + /// different ([`FileFacts::declares_the_same`]); + /// * **the include graph** — this file's edges re-scanned and re-spelled; + /// nothing else in it depends on one file's text; + /// * **every open buffer's overlay** — refreshed when the index moved, + /// because any of them may resolve into the file that moved. /// /// The text is chosen by `collect_sources`'s rules, for one path: an open /// buffer beats disk and is never capped; a walked file over /// `lucisv.index.maxFileSize`, one that has been deleted, and one that /// cannot be read are all "this file is not in the index any more". - pub fn update_one(&mut self, path: &Path) -> bool { - if !self.index.files().iter().any(|held| held == path) { - return false; + /// + /// [`WorkspaceIndex::update_facts`]: vlog_semantic::WorkspaceIndex::update_facts + /// [`WorkspaceIndex::remove_file`]: vlog_semantic::WorkspaceIndex::remove_file + pub fn update_one_file(&mut self, path: &Path) -> OneFile { + if self.index.file_id(path).is_none() { + return self.add_open_buffer(path); } // Re-indexing one file *is* the claim that its bytes moved. self.forget_view(path); - match self.current_text(path) { - Some(text) => { - // The same rule a whole rebuild follows: when the text came - // from an open buffer, that buffer's finished analysis is the - // facts and the words, and neither is derived from the text a - // second time. `current_text` answers with a buffer's text only - // when that buffer is not on the large-file fast path, so the - // analysis found here is a real one. - match self.analysis_of(path) { - Some((facts, words)) => { - self.index.update_facts(facts); - self.candidates.update_words(&self.index, path, words); - } - None => { - self.index.update_file(path.to_path_buf(), &text); - // The words come back out of the record the update - // just wrote, so the file is lexed once rather than - // twice (`FACTS_FORMAT` 13). A path the index somehow - // does not hold falls back to lexing, which is what - // this line always did. - match self.index.facts_for(path).map(|facts| facts.words().to_vec()) { - Some(words) => self.candidates.update_words(&self.index, path, words), - None => self.candidates.update_file(&self.index, path, &text), - } - } - } - self.includes.update_file(path, &text, self.index.files()); - // Written through here too, so an hour of saves is an hour of - // work the next session does not repeat. The record is the - // one the update just made — no second parse — and it is - // keyed by the text it was made from, which is the buffer's - // when a buffer beat disk. That record is simply never hit - // again if the file on disk says something else. - // A save is the other thing that asks the store something, so - // it opens a re-open a scan deferred rather than writing into - // the store the previous rescan left in hand ([`StoreOpen`]). - self.open_store(&mut ScanTrace::default()); - if let Some(facts) = self.index.facts_for(path) { - self.cache.record(facts, &text); - } - } - None => { - self.index.remove_file(path); - self.candidates.remove_file(&self.index, path); - self.includes.remove_file(path, self.index.files()); - } + let Some(text) = self.current_text(path) else { + self.remove_one(path); + return OneFile::Changed; + }; + // The same rule a whole rebuild follows: when the text came from an + // open buffer, that buffer's finished analysis is the facts and the + // words, and neither is derived from the text a second time. + // `current_text` answers with a buffer's text only when that buffer is + // not on the large-file fast path, so the analysis found here is a + // real one. Otherwise the file is parsed once, and its words come back + // out of the record (`FACTS_FORMAT` 13). + let (facts, words) = self.analysis_of(path).unwrap_or_else(|| { + let facts = FileFacts::of(path.to_path_buf(), &text); + let words = facts.words().to_vec(); + (facts, words) + }); + let declared = self.declared_by_either(path, &facts); + let moved = self.index.update_facts(facts); + // The include lines are not in the record — `` `include "a.svh"`` and + // `` `include `` can read the same to it — so they are + // re-scanned whatever the record said. + self.includes.update_held(path, &text); + self.write_through(path, &text); + if !moved { + return OneFile::Unchanged; } + self.candidates.set_file_words(path, words); + if let Some((symbols, macros)) = declared { + let symbols: HashSet<&str> = symbols.iter().map(String::as_str).collect(); + let macros: HashSet<&str> = macros.iter().map(String::as_str).collect(); + self.candidates.refresh_names(&self.index, &symbols, ¯os); + } + self.refresh_overlays(); + OneFile::Changed + } + + /// The half of [`Workspace::update_one_file`] for a file the index does + /// not hold, which it can settle only for an open buffer — one opened + /// after the last whole scan took its work list, from outside the + /// filelist or under an `exclude`, which a rebuild would take in because + /// every open buffer is taken in. + /// + /// What a rebuild would re-read besides the buffer is every other file's + /// `` `include``s, and the only ones the file's arrival can answer + /// differently are those whose last component could be its name — so those + /// are re-resolved ([`IncludeGraph::refresh_naming`]), from the lines the + /// graph holds, against the disk as it is now. No witness of *when* the + /// file appeared is needed, and none is trusted: a birth time was, until + /// QA showed `mv`, `cp -p` and `tar x` set it back (F3). + /// + /// The index is merged whole (every id after the new one moves), which + /// is in memory and reads nothing. + /// + /// [`IncludeGraph::refresh_naming`]: crate::includes::IncludeGraph::refresh_naming + fn add_open_buffer(&mut self, path: &Path) -> OneFile { + let Some((facts, words)) = self.analysis_of(path) else { return OneFile::NotHeld }; + let Some(text) = self.current_text(path) else { return OneFile::NotHeld }; + if self.holds_another_spelling_of(path) { + // A rebuild would take the buffer's spelling *instead of* the + // held one (`discover.rs`'s `Aliased`), which is not an add. + return OneFile::NotHeld; + } + let (symbols, macros) = facts.declared_names(); + let symbols: HashSet = symbols.into_iter().map(str::to_string).collect(); + let macros: HashSet = macros.into_iter().map(str::to_string).collect(); + self.index.update_facts(facts); + self.candidates.set_file_words(path, words); + let symbols: HashSet<&str> = symbols.iter().map(String::as_str).collect(); + let macros: HashSet<&str> = macros.iter().map(String::as_str).collect(); + self.candidates.refresh_names(&self.index, &symbols, ¯os); + self.includes.add_known(path); + self.includes.update_held(path, &text); + self.includes.refresh_naming(path); + self.write_through(path, &text); + self.refresh_overlays(); + OneFile::Changed + } + + /// Whether the index holds the file at `path` under another name — a + /// directory alias — by the test the scan's own overlay applies: the same + /// file name, then the same `(dev, ino)`. + fn holds_another_spelling_of(&self, path: &Path) -> bool { + let Some(id) = dir_id(path) else { return false }; + let named = |held: &&PathBuf| held.file_name() == path.file_name(); + self.index.files().iter().filter(named).any(|held| dir_id(held) == Some(id)) + } + + /// The half of [`Workspace::update_one_file`] for a held file that is + /// gone, capped or unreadable. The files whose `` `include``s could name + /// it are re-resolved, because their lines resolve against the disk and a + /// deleted file is no longer there to find. + fn remove_one(&mut self, path: &Path) { + self.index.remove_file(path); + self.candidates.remove_file(&self.index, path); + self.includes.remove_file(path, self.index.files()); + self.includes.refresh_naming(path); + self.refresh_overlays(); + } + + /// Files appeared, vanished or moved at `paths`, wherever they are: the + /// include lines that could name any of them are re-resolved, in one pass. + /// The whole of what such an event owes the graph for a file the index + /// does not hold. + pub fn refresh_includes_naming(&mut self, paths: &[PathBuf]) { + self.includes.refresh_naming_all(paths); + } + + /// The names the held record and `facts` put in the completion tables' + /// listings, both records' together — or `None` when the two declare the + /// same things ([`FileFacts::declares_the_same`]) and no listing can move. + fn declared_by_either( + &self, + path: &Path, + facts: &FileFacts, + ) -> Option<(HashSet, HashSet)> { + let held = self.index.facts_for(path)?; + if held.declares_the_same(facts) { + return None; + } + let mut symbols: HashSet = HashSet::new(); + let mut macros: HashSet = HashSet::new(); + for record in [held, facts] { + let (names, defines) = record.declared_names(); + symbols.extend(names.into_iter().map(str::to_string)); + macros.extend(defines.into_iter().map(str::to_string)); + } + Some((symbols, macros)) + } + + /// Write the file's record through to the persistent store, so an hour of + /// saves is an hour of work the next session does not repeat. The record + /// is the one the update just made — no second parse — and it is keyed by + /// the text it was made from, which is the buffer's when a buffer beat + /// disk; that record is simply never hit again if the file on disk says + /// something else. A save is the other thing that asks the store + /// something, so it opens a re-open a scan deferred rather than writing + /// into the store the previous rescan left in hand ([`StoreOpen`]). + /// + /// [`StoreOpen`]: super::StoreOpen + fn write_through(&mut self, path: &Path, text: &str) { + self.open_store(&mut ScanTrace::default()); + if let Some(facts) = self.index.facts_for(path) { + self.cache.record(facts, text); + } + } + + /// Re-resolve every open buffer's cross-file references against the index + /// as it now stands, exactly as a rebuild does. + fn refresh_overlays(&mut self) { for doc in self.docs.values_mut() { doc.refresh_overlay(&self.index); } - true } /// [`Workspace::update_one`], then a whole rebuild over the same @@ -99,20 +234,39 @@ impl Workspace { /// /// It is the incremental path's whole claim, checked rather than argued: /// the index's fingerprint (ids, disambiguation order, member tables, - /// edges, define counts) and the completion word table, which is the one - /// piece of derived state that is patched rather than re-derived. The - /// workspace is left holding the *rebuilt* index, which is the same index, - /// so a test may keep using it. + /// edges, define counts, postings and who read what), the completion + /// tables and the include graph. The workspace is left holding the + /// *rebuilt* index, which is the same index, so a test may keep using it. #[cfg(test)] pub fn update_one_checked(&mut self, path: &Path) -> bool { if !self.update_one(path) { return false; } - let index = self.index.fingerprint(); - let words = self.candidates.words("").to_vec(); + let before = self.derived_fingerprint(); self.rebuild_index(); - assert_eq!(index, self.index.fingerprint(), "incremental index != rebuilt index"); - assert_eq!(words, self.candidates.words(""), "incremental words != rebuilt words"); + assert_eq!(before, self.derived_fingerprint(), "incremental state != rebuilt state"); true } + + /// Everything a rebuild derives from the sources, rendered for comparison: + /// the index, the completion tables, the include graph and every open + /// buffer's cross-file answers. + #[cfg(test)] + pub fn derived_fingerprint(&self) -> String { + let mut docs: Vec<(&lsp_types::Uri, &super::Document)> = self.docs.iter().collect(); + docs.sort_by_key(|(uri, _)| uri.as_str()); + let overlays: Vec = docs + .iter() + .map(|(uri, doc)| { + format!("{} {:?}", uri.as_str(), doc.external.iter().collect::>()) + }) + .collect(); + format!( + "{}\n{}\n{}\n{}", + self.index.fingerprint(), + self.candidates.fingerprint(), + self.includes.fingerprint(), + overlays.join("\n") + ) + } } diff --git a/crates/lucisv_server/src/state/mod.rs b/crates/lucisv_server/src/state/mod.rs index 80fc646..5da4eb7 100644 --- a/crates/lucisv_server/src/state/mod.rs +++ b/crates/lucisv_server/src/state/mod.rs @@ -36,13 +36,16 @@ mod scan; mod scope; mod sources; mod views; +mod watched; #[cfg(test)] pub use document::mixed_buffer; pub use document::{first_token_from, first_token_reaching, Document}; +pub use incremental::OneFile; pub use port_grace::PortGrace; pub use scan::{IndexEvent, Scan}; pub use views::FileView; +pub use watched::Watched; /// How many `workspace/symbol` hits are returned. Each one costs a file read /// to turn its byte span into a line, so an unbounded answer to the empty diff --git a/crates/lucisv_server/src/state/tests/mod.rs b/crates/lucisv_server/src/state/tests/mod.rs index 8063353..bd3ab7e 100644 --- a/crates/lucisv_server/src/state/tests/mod.rs +++ b/crates/lucisv_server/src/state/tests/mod.rs @@ -25,6 +25,7 @@ mod large_file; mod lazy_read; mod open_buffers; mod persistence; +mod reindex_perf; mod settings; mod size_cap; mod views; diff --git a/crates/lucisv_server/src/state/tests/reindex_perf.rs b/crates/lucisv_server/src/state/tests/reindex_perf.rs new file mode 100644 index 0000000..41efee4 --- /dev/null +++ b/crates/lucisv_server/src/state/tests/reindex_perf.rs @@ -0,0 +1,206 @@ +//! What a save and a keystroke cost the index at OpenTitan scale — the +//! measurements behind `docs/features/localized-reindex/README.md`. +//! +//! Every test here is `#[ignore]`d and asserts nothing but its premises; run +//! them in release, one at a time, through the guard: +//! +//! `tools/guard.sh -- cargo test --release -p lucisv_server reindex_perf -- --ignored --nocapture --test-threads=1` +//! +//! The tree is `$LUCISV_OPENTITAN` or `~/.cache/lucisv-opentitan-full/hw`; +//! without it every probe says so and returns. + +use std::time::{Duration, Instant}; + +use vlog_semantic::{FileId, SymbolKind}; + +use super::*; + +/// The OpenTitan `hw` tree, when this machine has one. +pub(super) fn opentitan() -> Option { + let root = std::env::var_os("LUCISV_OPENTITAN").map(PathBuf::from).or_else(|| { + std::env::var_os("HOME") + .map(|home| PathBuf::from(home).join(".cache/lucisv-opentitan-full/hw")) + })?; + root.is_dir().then_some(root) +} + +/// A workspace over the whole OpenTitan tree, with `open` buffers open. +fn opentitan_workspace(root: &Path, open: &[&str]) -> Workspace { + let mut ws = Workspace::default(); + ws.set_client_settings(wide(ClientSettings::default())); + ws.open_whole_workspace(vec![root.to_path_buf()]); + for rel in open { + let path = root.join(rel); + let text = fs::read_to_string(&path).expect("the probe's files are on disk"); + ws.set_document(crate::uri::path_to_uri(&path).expect("uri"), text); + } + ws +} + +fn median(mut runs: Vec) -> Duration { + runs.sort(); + runs[runs.len() / 2] +} + +/// The edits a save is measured after: each is applied to the buffer, then +/// `update_one` runs, then the buffer is put back and updated again. +fn edits(text: &str) -> Vec<(&'static str, String)> { + let body = text.rfind("endmodule").or_else(|| text.rfind("endpackage")).unwrap_or(text.len()); + let first = text.find('\n').map_or(0, |at| at + 1); + vec![ + ("no change (the watcher's echo of a save)", text.to_string()), + ("comment appended", format!("{text}\n// an edit\n")), + ( + "local signal added", + format!("{} logic probe_local_q;\n{}", &text[..body], &text[body..]), + ), + ("comment above everything", format!("{}// an edit\n{}", &text[..first], &text[first..])), + ] +} + +const TARGETS: [&str; 5] = [ + "ip/uart/rtl/uart_tx.sv", + "ip/prim_generic/rtl/prim_flop.sv", + "ip/uart/rtl/uart_reg_pkg.sv", + "ip/prim/rtl/prim_assert.sv", + "top_earlgrey/rtl/autogen/top_earlgrey.sv", +]; + +#[test] +#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"] +fn what_one_saved_file_costs_the_index_at_opentitan_scale() { + let Some(root) = opentitan() else { + eprintln!("no OpenTitan tree — skipping"); + return; + }; + let mut ws = opentitan_workspace(&root, &TARGETS); + assert!(ws.index().files().len() > 3_000, "premise: the whole tree is indexed"); + for rel in TARGETS { + let path = root.join(rel); + let uri = crate::uri::path_to_uri(&path).expect("uri"); + let text = fs::read_to_string(&path).expect("on disk"); + for (what, edited) in edits(&text) { + let mut runs = Vec::new(); + for _ in 0..5 { + ws.set_document(uri.clone(), edited.clone()); + let started = Instant::now(); + assert!(ws.update_one(&path), "premise: a held file"); + runs.push(started.elapsed()); + ws.set_document(uri.clone(), text.clone()); + ws.update_one(&path); + } + eprintln!("update_one {rel}, {what}: median {:?}", median(runs)); + } + } +} + +#[test] +#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"] +fn what_the_mention_census_costs_a_keystroke_at_opentitan_scale() { + // The three census rules ask `mentioned_outside` once per candidate + // declaration; every net and variable a file declares is the upper bound + // of what one lint pass over that file can ask. + let Some(root) = opentitan() else { + eprintln!("no OpenTitan tree — skipping"); + return; + }; + let ws = opentitan_workspace(&root, &[]); + let index = ws.index(); + let (mut calls, mut total, mut worst) = (0usize, Duration::ZERO, (Duration::ZERO, 0, None)); + for (id, path) in index.files().iter().enumerate() { + let Ok(text) = fs::read_to_string(path) else { continue }; + let doc = Document::new(Some(path.clone()), text, index); + let names: Vec<&str> = doc + .semantics + .symbols() + .iter() + .filter(|s| matches!(s.kind, SymbolKind::Net | SymbolKind::Var)) + .map(|s| s.name.as_str()) + .collect(); + let started = Instant::now(); + for name in &names { + std::hint::black_box(index.mentioned_outside(name, Some(FileId(id as u32)))); + } + let took = started.elapsed(); + calls += names.len(); + total += took; + if took > worst.0 { + worst = (took, names.len(), Some(path.clone())); + } + } + eprintln!( + "mention census over {} files: {calls} questions, {:?} each on average; \ + worst file {:?} asks {} for {:?}", + index.files().len(), + total / calls.max(1) as u32, + worst.2, + worst.1, + worst.0 + ); +} + +#[test] +#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"] +fn what_the_census_adds_to_a_real_lint_pass_at_opentitan_scale() { + // The bound above is every declaration; this is what the rules really + // ask: one buffer's whole lint pass against the indexed workspace, and the + // same pass with no workspace (no census at all), file by file. + let Some(root) = opentitan() else { + eprintln!("no OpenTitan tree — skipping"); + return; + }; + let ws = opentitan_workspace(&root, &[]); + let alone = Workspace::default(); + let mut added: Vec<(Duration, Duration, PathBuf)> = Vec::new(); + for path in ws.index().files() { + let Ok(text) = fs::read_to_string(path) else { continue }; + // A fresh document per pass: a document remembers its last lint + // pass (`lint_snapshot`), and a remembered pass costs nothing. + let lint = |within: &Workspace| { + let doc = Document::new(Some(path.clone()), text.clone(), ws.index()); + let started = Instant::now(); + let run = crate::lint::LintRun::for_document(within, &doc); + std::hint::black_box(crate::diagnostics::all_in(&doc, &run)); + started.elapsed() + }; + let with = median((0..3).map(|_| lint(&ws)).collect()); + let without = median((0..3).map(|_| lint(&alone)).collect()); + added.push((with.saturating_sub(without), with, path.clone())); + } + added.sort(); + let total: Duration = added.iter().map(|(d, _, _)| *d).sum(); + eprintln!( + "census share of a lint pass over {} files: {:?} on average", + added.len(), + total / added.len().max(1) as u32 + ); + for (delta, with, path) in added.iter().rev().take(5) { + eprintln!(" {delta:?} of {with:?} in {}", path.display()); + } +} + +#[test] +#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"] +fn what_the_readers_table_holds_at_opentitan_scale() { + // The memory the narrowing costs: one key per table entry any file's + // resolution read, and one file id per reader of it — read back out of + // the fingerprint, which renders the table line by line. + let Some(root) = opentitan() else { + eprintln!("no OpenTitan tree — skipping"); + return; + }; + let ws = opentitan_workspace(&root, &[]); + let fingerprint = ws.index().fingerprint(); + let lines: Vec<&str> = fingerprint.lines().filter(|line| line.starts_with("read ")).collect(); + let readers: usize = lines.iter().map(|line| line.matches(',').count() + 1).sum(); + let key_bytes: usize = + lines.iter().filter_map(|line| line.split(' ').nth(2)).map(str::len).sum(); + eprintln!( + "readers table over {} files: {} keys ({} KiB of key text), {} reader entries ({} KiB of ids)", + ws.index().files().len(), + lines.len(), + key_bytes / 1024, + readers, + readers * 4 / 1024 + ); +} diff --git a/crates/lucisv_server/src/state/watched.rs b/crates/lucisv_server/src/state/watched.rs new file mode 100644 index 0000000..d2d9f14 --- /dev/null +++ b/crates/lucisv_server/src/state/watched.rs @@ -0,0 +1,156 @@ +//! What one path a file watcher named is to the index: a file it holds +//! (perhaps under another spelling), a file the scope provably cannot take, +//! or neither — which only a rescan can settle +//! (`docs/features/localized-reindex/README.md`). +//! +//! A watcher event for a `.sv` the index does not hold used to be a whole +//! rescan, progress bar and all, every time: a generated file under a +//! gitignored build directory, a file outside the folder scope or the +//! filelist, or a held file reported by its real path under a symlinked root. +//! Only the last kind of file can change what the index says, and none of +//! them needs the walk to find that out. + +use std::fs; +use std::path::{Path, PathBuf}; + +use lucisv_core::config::Discovery; +use lucisv_core::walk::collect_files_below; + +use super::discover::{oversize, Found}; +use super::Workspace; + +/// What a watched path is to the index. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Watched { + /// A file the index holds, by the spelling it holds it under — or an + /// open buffer it does not hold yet, which a rebuild would take in and the + /// one-file path adds (QA F4). + Held(PathBuf), + /// A file no scan of the scope in force would index. Nothing to do for + /// the index. + Outside, + /// A file the scope may take and the index does not hold: a new file, or + /// one the cap kept out until now. Only a rescan can say. + Unknown, +} + +impl Workspace { + /// What `path` is to the index. Errs towards [`Watched::Unknown`]: a + /// wasted rescan costs time, a skipped one would cost a stale index. + pub fn watched(&self, path: &Path) -> Watched { + if let Some(held) = self.held_spelling(path) { + return Watched::Held(held); + } + if self.docs.values().any(|doc| doc.path.as_deref() == Some(path)) { + return Watched::Held(path.to_path_buf()); + } + match self.scope_could_take(path) { + true => Watched::Unknown, + false => Watched::Outside, + } + } + + /// The spelling the index holds `path` under: `path` itself, or the same + /// file reached through a scope directory's other name — a symlinked root, + /// or a different case on a case-insensitive disk. Resolved through the + /// directories the scope is anchored at, so it costs a handful of + /// `canonicalize` calls rather than one per held file. + fn held_spelling(&self, path: &Path) -> Option { + let holds = |path: &Path| self.index.file_id(path).is_some(); + if holds(path) { + return Some(path.to_path_buf()); + } + let real = canonical(path)?; + let mut anchors: Vec = self.roots.clone(); + anchors.extend(self.scope_dirs()); + anchors.into_iter().find_map(|anchor| { + let rest = real.strip_prefix(fs::canonicalize(&anchor).ok()?).ok()?; + let spelled = anchor.join(rest); + holds(&spelled).then_some(spelled) + }) + } + + /// Whether a scan of the scope in force could index `path` — `false` only + /// when it provably could not: a filelist that does not list it, or a + /// walk of the scope's directories that does not find it or finds it over + /// `lucisv.index.maxFileSize`. The walk is `lucisv_core`'s own, rooted + /// where the scan's is, so `.gitignore`, `exclude` and the config's + /// excludes rule it out exactly as they rule it out of a scan. + fn scope_could_take(&self, path: &Path) -> bool { + if let Some(list) = self.filelist_path() { + // An unreadable filelist sends the scan to the rungs below, and + // so it sends this. + if let Ok(list) = lucisv_core::filelist::read(&list) { + return list.files.iter().any(|listed| same_file(listed, path)); + } + } + let Some(dir) = path.parent() else { return true }; + let dirs = match self.walks_the_workspace() { + true => self.roots.clone(), + false => self.scope_dirs(), + }; + if self.roots.is_empty() && self.client.index_scope_depth == 0 { + // The flat read of a rootless session: siblings only. + return dirs.iter().any(|scope| scope == dir); + } + dirs.iter() + .filter(|scope| path.starts_with(scope)) + .any(|scope| self.walk_finds(scope, path)) + } + + /// Whether a walk of `scope` finds `path` under its cap. + fn walk_finds(&self, scope: &Path, path: &Path) -> bool { + let Some(dir) = path.parent() else { return true }; + let excludes = self.walk_excludes(&mut Discovery::new(true), scope); + let mut found = None; + let take = &mut |file: PathBuf, len| { + if file == path { + found = Some(Found { path: file, len }); + } + }; + if collect_files_below(scope, dir, &excludes, true, take, &mut |_| {}).is_err() { + // The directory is gone or unreadable: nothing in it can be read + // either, and the scan would say the same. + return false; + } + found.is_some_and(|found| oversize(&found, self.client.max_file_size, &mut 0).is_none()) + } + + /// The exclude patterns a walk rooted at `dir` applies: the governing + /// config's, then the client's `lucisv.exclude`. *Appended*, never + /// substituted — the CLI appends a config's excludes to `--exclude` the + /// same way, and a setting that silently dropped a checked-in exclude + /// would put vendored code back in the index for one user only. + pub(super) fn walk_excludes(&self, discovery: &mut Discovery, dir: &Path) -> Vec { + // A broken `lucisv.toml` must not stop the server from indexing: an + // index that excludes nothing is a far better failure than a server + // that comes up empty. The error is reported when the user formats a + // file in this tree (`format::settings_for`). + let mut exclude = discovery.for_dir(dir).unwrap_or_default().exclude.unwrap_or_default(); + exclude.extend(self.client.exclude.iter().cloned()); + exclude + } +} + +/// Whether two spellings name one file: equal, or equal once resolved. The +/// names are compared first, case-insensitively, so a filelist of thousands +/// costs a resolution only for the entries that could be the one. +fn same_file(listed: &Path, path: &Path) -> bool { + if listed == path { + return true; + } + let name = |p: &Path| p.file_name().map(|n| n.to_string_lossy().to_lowercase()); + name(listed) == name(path) + && canonical(listed).is_some() + && canonical(listed) == canonical(path) +} + +/// `path` with every symlink resolved and, on a case-insensitive disk, every +/// component in the case the disk holds it in. A file that is gone resolves +/// through its directory, so a deletion can still be matched. +fn canonical(path: &Path) -> Option { + fs::canonicalize(path).ok().or_else(|| { + let real = fs::canonicalize(path.parent()?).ok()?; + Some(real.join(path.file_name()?)) + }) +} diff --git a/crates/lucisv_server/src/watch.rs b/crates/lucisv_server/src/watch.rs index ec58cbf..27f641a 100644 --- a/crates/lucisv_server/src/watch.rs +++ b/crates/lucisv_server/src/watch.rs @@ -112,16 +112,16 @@ pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool { .any(|path| watched(&path, filelist)) } -/// The one file an event named, when it named exactly one and that one is not -/// the filelist. +/// Every path an event named that the index reads, each once and in order — +/// or `None` when one of them is the filelist, whose change moves the whole +/// scope and is a rebuild by definition. A client is free to send `Changed` +/// and `Created` for one file, and that is still one file. /// -/// The gate on the incremental rescan path (`server.rs`'s `reindex_one`): a -/// checkout fills this list, and a list of one is the case a single file's -/// contribution can be replaced in place. The filelist is excluded because a -/// change to it moves the whole scope, which is a rebuild by definition. An -/// event naming the same path twice — a client is free to send `Changed` and -/// `Created` for one file — is still one file. -pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option { +/// What `server/index.rs`'s `reindex_watched` sorts into held, outside and +/// unknown files (`docs/features/localized-reindex/README.md`); until +/// 2026-11-19 this was `one_scope_file`, which gave up on any list longer +/// than one. +pub fn scope_files(changes: &[FileEvent], filelist: Option<&Path>) -> Option> { let mut named: Vec = changes .iter() .filter_map(|change| uri_to_path(&change.uri)) @@ -129,10 +129,17 @@ pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option< .collect(); named.sort(); named.dedup(); - match named.as_slice() { - [only] if Some(only.as_path()) != filelist => Some(only.clone()), - _ => None, - } + (!named.iter().any(|path| Some(path.as_path()) == filelist)).then_some(named) +} + +/// Whether an event names a `lucisv.toml` (either spelling) — a change to +/// which moves the scope's excludes and filelist and the lint configuration +/// together. The names are `lucisv_core::config::NAMES`, the CLI's own. +pub fn names_a_config(changes: &[FileEvent]) -> bool { + changes.iter().filter_map(|change| uri_to_path(&change.uri)).any(|path| { + let name = path.file_name().and_then(|n| n.to_str()); + name.is_some_and(|n| lucisv_core::config::NAMES.contains(&n)) + }) } /// Whether one path is something the index reads: a source file, or the diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 1d538f1..82c9c40 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -4873,6 +4873,12 @@ fn a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire() { r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, serde_json::to_string(LENS_SUB).expect("json") )), + // An edit before the save: a save that moved nothing the index + // records refreshes nothing (localized-reindex, 2026-11-19). + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#, + serde_json::to_string(&format!("{LENS_SUB}module lens_extra;\nendmodule\n")).expect("json") + )), frame(&format!( r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# )), diff --git a/crates/vlog_semantic/src/workspace/dependents.rs b/crates/vlog_semantic/src/workspace/dependents.rs new file mode 100644 index 0000000..08d866d --- /dev/null +++ b/crates/vlog_semantic/src/workspace/dependents.rs @@ -0,0 +1,152 @@ +//! Which files' references read which merged-table keys: recorded while a +//! file's references are resolved, and asked when an update moves a key, so +//! that only the files that read it are resolved again +//! (`docs/features/localized-reindex/README.md`). +//! +//! The recording is a thread-local switch rather than a parameter because the +//! resolution walk (`external.rs`, `reexport.rs`, `hierarchy.rs`) is shared +//! with every request-time caller through a dozen functions that take a +//! `&WorkspaceIndex`; threading a recorder through all of them would change +//! every signature for the one caller that wants it. The lookups note what +//! they read with [`note`], which costs one thread-local check when nothing is +//! recording — every request — and the index's own pass turns it on with +//! [`recording`]. `lint_trace` and `scan_trace` use the same shape. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; + +use super::FileId; + +/// A merged table a resolution reads, named by what its key is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Table { + /// `units`, by file-scope name. + Unit = 0, + /// `members`, by the unit that exports the member. + Container = 1, + /// `hier_members`, by the unit that declares the member. + Hier = 2, + /// `bases`, by the class whose base it records. + Base = 3, + /// `reexports`, by the exporting package. + Exporter = 4, +} + +const TABLES: [Table; 5] = + [Table::Unit, Table::Container, Table::Hier, Table::Base, Table::Exporter]; + +/// The keys one resolution pass read, table by table — misses included: a +/// lookup that found nothing is exactly the one a new declaration answers. +#[derive(Debug, Default)] +pub(super) struct Reads { + keys: [HashSet; 5], +} + +thread_local! { + static RECORDING: RefCell> = const { RefCell::new(None) }; +} + +/// Note that the resolution running on this thread read `table` under `key`. +pub(super) fn note(table: Table, key: &str) { + RECORDING.with(|cell| { + if let Some(reads) = cell.borrow_mut().as_mut() { + let keys = &mut reads.keys[table as usize]; + if !keys.contains(key) { + keys.insert(key.to_string()); + } + } + }); +} + +/// Run `body` and say every key it read. Nests: an outer recording is put +/// back afterwards, untouched by the inner one. +pub(super) fn recording(body: impl FnOnce() -> R) -> (R, Reads) { + let outer = RECORDING.with(|cell| cell.replace(Some(Reads::default()))); + let out = body(); + let reads = RECORDING.with(|cell| cell.replace(outer)).unwrap_or_default(); + (out, reads) +} + +/// Key → the files whose last resolution read it, each list sorted and +/// without repeats. +/// +/// It holds exactly what resolving every file against the tables as they +/// stand would record, which is what makes "the files that read a moved key" +/// a sound answer to "whose postings can have moved": a file that read no +/// moved key read only values that did not change, so its resolution — a pure +/// function of its own facts and those values — did not change either. +#[derive(Debug, Clone, Default)] +pub(super) struct Dependents { + readers: [HashMap>; 5], +} + +impl Dependents { + /// Forget every reader, for a rebuild from the records. + pub(super) fn clear(&mut self) { + self.readers.iter_mut().for_each(HashMap::clear); + } + + /// Record that `file` read everything in `reads`. + pub(super) fn add(&mut self, file: FileId, reads: Reads) { + for (table, keys) in reads.keys.into_iter().enumerate() { + for key in keys { + let files = self.readers[table].entry(key).or_default(); + // A whole rebuild adds files in id order, so the common case + // is a push; an update re-adds a few files in the middle. + match files.last() { + Some(last) if *last >= file => { + if let Err(at) = files.binary_search(&file) { + files.insert(at, file); + } + } + _ => files.push(file), + } + } + } + } + + /// Take back what [`Dependents::add`] recorded for `file`. + pub(super) fn remove(&mut self, file: FileId, reads: &Reads) { + for (table, keys) in reads.keys.iter().enumerate() { + for key in keys { + let Some(files) = self.readers[table].get_mut(key) else { continue }; + if let Ok(at) = files.binary_search(&file) { + files.remove(at); + } + if files.is_empty() { + self.readers[table].remove(key); + } + } + } + } + + /// Take back everything recorded for every file `gone` says, by one pass + /// over the whole table. + pub(super) fn remove_all(&mut self, gone: &dyn Fn(FileId) -> bool) { + for readers in &mut self.readers { + readers.retain(|_, files| { + files.retain(|file| !gone(*file)); + !files.is_empty() + }); + } + } + + /// The files that read `table` under `key`. + pub(super) fn readers(&self, table: Table, key: &str) -> &[FileId] { + self.readers[table as usize].get(key).map_or(&[], Vec::as_slice) + } + + /// Every reader, one sorted line per key — for the index's fingerprint, so + /// the equivalence tests hold this table to a rebuild's as well. + pub(super) fn render(&self, out: &mut String) { + for table in TABLES { + let mut keys: Vec<(&String, &Vec)> = + self.readers[table as usize].iter().collect(); + keys.sort(); + for (key, files) in keys { + let ids: Vec = files.iter().map(|file| file.0).collect(); + out.push_str(&format!("read {table:?} {key} by {ids:?}\n")); + } + } + } +} diff --git a/crates/vlog_semantic/src/workspace/index.rs b/crates/vlog_semantic/src/workspace/index.rs index 6bc2d1c..b2a90b9 100644 --- a/crates/vlog_semantic/src/workspace/index.rs +++ b/crates/vlog_semantic/src/workspace/index.rs @@ -13,6 +13,7 @@ use vlog_parser::defines::{Define, DefineTable}; use crate::model::{Surface, SymbolKind}; +use super::dependents::{note, Table}; use super::external::{fold_path, last_segment, member_chain, own_members}; use super::hierarchy; use super::record::{FileFacts, ReferenceFact}; @@ -67,6 +68,7 @@ impl WorkspaceIndex { /// in disambiguation order (by file path, then by position in the file). /// More than one means the workspace really does declare the name twice. pub fn units(&self, name: &str) -> &[Def] { + note(Table::Unit, name); self.units.get(name).map_or(&[], Vec::as_slice) } @@ -80,6 +82,7 @@ impl WorkspaceIndex { /// hierarchical path may name besides is /// [`WorkspaceIndex::member_in`]'s business ([`Surface`]). pub fn member(&self, unit: &str, member: &str) -> &[Def] { + note(Table::Container, unit); self.members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice) } @@ -95,6 +98,7 @@ impl WorkspaceIndex { /// — the completion list behind `p::` and behind an instantiation's /// connection list. pub fn members_of(&self, unit: &str) -> impl Iterator { + note(Table::Container, unit); self.members .get(unit) .into_iter() @@ -108,6 +112,7 @@ impl WorkspaceIndex { &self, unit: &str, ) -> impl Iterator { + note(Table::Hier, unit); self.hier_members .get(unit) .into_iter() @@ -116,6 +121,7 @@ impl WorkspaceIndex { /// [`WorkspaceIndex::member`] on the hierarchical-only half alone. pub(super) fn hierarchical_member(&self, unit: &str, member: &str) -> &[Def] { + note(Table::Hier, unit); self.hier_members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice) } @@ -187,6 +193,7 @@ impl WorkspaceIndex { /// edges `reexport`'s two walks follow. Empty for every unit that /// re-exports nothing, which is all but a handful in any workspace. pub(super) fn reexports(&self, unit: &str) -> &[Reexport] { + note(Table::Exporter, unit); self.reexports.get(unit).map_or(&[], Vec::as_slice) } @@ -262,6 +269,7 @@ impl WorkspaceIndex { /// declare — which is what ends the chase in /// [`resolve_external`](super::resolve_external). pub fn base_of(&self, name: &str) -> Option<&str> { + note(Table::Base, name); self.bases.get(name).map(String::as_str) } @@ -315,7 +323,7 @@ impl WorkspaceIndex { /// Whether at least one use could name `def` or another declaration equally. pub fn references_are_ambiguous(&self, def: &Def) -> bool { - self.ambiguous_references.contains(&DefinitionKey::of(def)) + self.ambiguous_references.contains_key(&DefinitionKey::of(def)) } /// Every file holding a use spelled `name` that this index had to look @@ -429,15 +437,26 @@ impl WorkspaceIndex { /// sorted by name and is not truncated, so a caller with a result limit /// applies its own. pub fn workspace_symbols(&self, query: &str) -> Vec> { + self.symbols_where(|name| contains_ignore_ascii_case(name, query)) + } + + /// [`WorkspaceIndex::workspace_symbols`] for exactly these names, in the + /// same order — what a table built from the whole listing re-derives for + /// the names one update touched (`docs/features/localized-reindex`). + pub fn symbols_named(&self, names: &HashSet<&str>) -> Vec> { + self.symbols_where(|name| names.contains(name)) + } + + fn symbols_where(&self, keep: impl Fn(&str) -> bool) -> Vec> { let mut out = Vec::new(); for (name, defs) in &self.units { - if contains_ignore_ascii_case(name, query) { + if keep(name) { out.extend(defs.iter().map(|def| WorkspaceSymbol { name, container: None, def })); } } for (unit, members) in &self.members { for (name, defs) in members { - if contains_ignore_ascii_case(name, query) { + if keep(name) { out.extend(defs.iter().map(|def| WorkspaceSymbol { name, container: Some(unit), @@ -626,7 +645,7 @@ impl IndexBuilder { facts: self.files, ..WorkspaceIndex::default() }; - index.merge(None); + index.merge(); index } } diff --git a/crates/vlog_semantic/src/workspace/mod.rs b/crates/vlog_semantic/src/workspace/mod.rs index db6e7ec..6db62a5 100644 --- a/crates/vlog_semantic/src/workspace/mod.rs +++ b/crates/vlog_semantic/src/workspace/mod.rs @@ -24,21 +24,26 @@ //! two member surfaces holds what, and the reads that take a //! [`crate::Surface`] instead of assuming one. +mod dependents; mod external; mod hierarchy; mod index; mod path_units; mod record; mod reexport; +mod references; +mod replace; mod update; pub use external::{resolve_external, Definition, ExternalResolutions, ExternalTarget}; pub use index::{index_order, IndexBuilder}; pub use record::FileFacts; + +use dependents::Dependents; pub(crate) use record::{Decl, ReferenceFact, SiteFact}; pub(crate) use reexport::Reexport; -use std::collections::{BTreeMap, HashSet}; +use std::collections::{BTreeMap, HashMap}; use std::path::PathBuf; use vlog_parser::span::TextRange; @@ -326,10 +331,18 @@ pub struct WorkspaceIndex { macro_definitions: BTreeMap>, /// Declaration → every unambiguous use, in file then source order. reference_sites: BTreeMap>, - /// Declarations touched by at least one ambiguous external reference. + /// Declarations touched by at least one ambiguous external reference, + /// each with how many such references touch it — counted so one file's + /// references can be taken back without re-resolving the rest. /// Find-references refuses those rather than assigning the use to one of /// several equally plausible declarations. - ambiguous_references: HashSet, + ambiguous_references: HashMap, + /// The same, by the file whose references contributed them — so a sweep + /// can take a file's share back without re-resolving it. + ambiguous_by_file: HashMap>, + /// Which files' references read which table keys — what lets an update + /// re-resolve only the files that read a key it moved. + dependents: Dependents, } /// The headline numbers of a built index. diff --git a/crates/vlog_semantic/src/workspace/record.rs b/crates/vlog_semantic/src/workspace/record.rs index 7d4b8d7..0bf0100 100644 --- a/crates/vlog_semantic/src/workspace/record.rs +++ b/crates/vlog_semantic/src/workspace/record.rs @@ -11,7 +11,7 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; use vlog_parser::ast::SourceFile; -use vlog_parser::defines::{collect_defines, DefineTable}; +use vlog_parser::defines::{collect_defines, Define, DefineKind, DefineTable}; use vlog_parser::span::TextRange; use vlog_parser::token::Token; use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex}; @@ -271,6 +271,58 @@ impl FileFacts { pub fn path(&self) -> &Path { &self.path } + + /// Whether `other` declares what this record declares, as far as + /// [`WorkspaceIndex::workspace_symbols`](super::WorkspaceIndex::workspace_symbols) + /// and the `` `define`` table can see — the same units and + /// connection-surface members by name, kind and owning unit, in the order + /// that listing sorts them, and the same `` `define``s with the same + /// parameters in the same order — wherever in the file they now sit. + /// + /// The completion tables are built from exactly those two views, so an + /// edit that moved no such declaration (a body change, a comment, a new + /// local signal) leaves them as they were and need not re-derive them + /// (`docs/features/localized-reindex/README.md`). + pub fn declares_the_same(&self, other: &FileFacts) -> bool { + let define = |define: &Define| (define.name.clone(), define.params.clone()); + let defines = |facts: &FileFacts| -> Vec<(String, Option>)> { + let entries = facts.defines.entries().iter(); + entries.filter(|d| d.kind == DefineKind::Define).map(define).collect() + }; + self.symbol_view() == other.symbol_view() && defines(self) == defines(other) + } + + /// Every name this file puts in the workspace-symbol listing — its units + /// and its connection-surface members — and every macro it `` `define``s: + /// what a table built from those listings re-derives when the file moves. + pub fn declared_names(&self) -> (HashSet<&str>, HashSet<&str>) { + let units = self.units.iter().map(|decl| decl.name.as_str()); + let members = self.members.iter().filter(|(_, decl)| decl.surface == Surface::Connection); + let symbols = units.chain(members.map(|(_, decl)| decl.name.as_str())).collect(); + let entries = self.defines.entries().iter(); + let macros = + entries.filter(|d| d.kind == DefineKind::Define).map(|d| d.name.as_str()).collect(); + (symbols, macros) + } + + /// This file's workspace symbols, spans aside: `(name, container, kind)` + /// in `workspace_symbols`' order, which within one file is by name, then + /// container, then position. + fn symbol_view(&self) -> Vec<(&str, Option<&str>, SymbolKind)> { + let units = self + .units + .iter() + .map(|decl| (decl.name.as_str(), None, decl.name_span.start, decl.kind)); + let members = + self.members.iter().filter(|(_, decl)| decl.surface == Surface::Connection).map( + |(unit, decl)| { + (decl.name.as_str(), Some(unit.as_str()), decl.name_span.start, decl.kind) + }, + ); + let mut view: Vec<_> = units.chain(members).collect(); + view.sort_by(|a, b| (a.0, a.1, a.2).cmp(&(b.0, b.1, b.2))); + view.into_iter().map(|(name, container, _, kind)| (name, container, kind)).collect() + } } /// One file's two identifier censuses, both read off the same token stream: diff --git a/crates/vlog_semantic/src/workspace/references.rs b/crates/vlog_semantic/src/workspace/references.rs new file mode 100644 index 0000000..b0eba74 --- /dev/null +++ b/crates/vlog_semantic/src/workspace/references.rs @@ -0,0 +1,176 @@ +//! The declaration → use postings, built from every file's reference facts or +//! re-done for a few files: what an update calls once it knows which files +//! read a key it moved (`docs/features/localized-reindex/README.md`). + +use std::collections::HashSet; + +use super::dependents::{recording, Reads}; +use super::external::{resolve_fact, ExternalTarget}; +use super::record::ReferenceFact; +use super::{DefinitionKey, FileId, ReferenceSite, WorkspaceIndex}; + +/// What one reference puts into the postings. +enum Posting { + /// One use of one declaration. + Site(DefinitionKey, ReferenceSite), + /// A use that could name any of these declarations equally. + Ambiguous(Vec), +} + +impl WorkspaceIndex { + /// Rebuild every posting, the ambiguity counts and the readers table from + /// every file's facts. + pub(super) fn merge_references(&mut self) { + self.reference_sites.clear(); + self.ambiguous_references.clear(); + self.ambiguous_by_file.clear(); + self.dependents.clear(); + let every: Vec = (0..self.facts.len()).map(|id| FileId(id as u32)).collect(); + self.resolve_files(&every); + } + + /// Put `files`' postings in, resolved against the tables as they stand. + /// + /// `files` is in id order, and each file's postings go in after every + /// posting of a lower-numbered file and before every higher one — the + /// order [`WorkspaceIndex::merge_references`] produces by visiting the + /// files in that order, so a few files re-done in place give the lists a + /// whole rebuild gives. + pub(super) fn resolve_files(&mut self, files: &[FileId]) { + for &file in files { + let (postings, reads) = self.postings_of(file); + for posting in postings { + match posting { + Posting::Site(key, site) => { + let sites = self.reference_sites.entry(key).or_default(); + let at = sites.partition_point(|held| held.file <= file); + sites.insert(at, site); + } + Posting::Ambiguous(keys) => { + for key in keys { + *self.ambiguous_references.entry(key).or_default() += 1; + self.ambiguous_by_file.entry(file).or_default().push(key); + } + } + } + } + self.dependents.add(file, reads); + } + } + + /// Take `files`' postings out again. + /// + /// Re-resolving them against the tables as they stand finds exactly what + /// [`WorkspaceIndex::resolve_files`] put in, because those are the tables + /// it was put in against — every update keeps the postings equal to a + /// resolution of every file over the current tables, and resolution is a + /// pure function of the two. So nothing per file has to be remembered to + /// undo it. + pub(super) fn unresolve_files(&mut self, files: &[FileId]) { + let leaving: HashSet = files.iter().copied().collect(); + let mut touched: HashSet = HashSet::new(); + for &file in files { + let (postings, reads) = self.postings_of(file); + for posting in postings { + match posting { + Posting::Site(key, _) => { + touched.insert(key); + } + Posting::Ambiguous(keys) => { + keys.iter().for_each(|key| self.forget_ambiguity(key)) + } + } + } + self.dependents.remove(file, &reads); + self.ambiguous_by_file.remove(&file); + } + for key in touched { + let Some(sites) = self.reference_sites.get_mut(&key) else { continue }; + sites.retain(|site| !leaving.contains(&site.file)); + if sites.is_empty() { + self.reference_sites.remove(&key); + } + } + } + + /// [`WorkspaceIndex::unresolve_files`] by one pass over the postings + /// rather than by re-resolving `files`: every site a file put in is + /// dropped wherever it is, its ambiguity taken back from what it is + /// recorded to have contributed, and its id struck from every reader + /// list. Linear in the postings, not in `files` — the cheaper way out when + /// `files` hold a large share of every reference (a package most of the + /// tree imports), where re-resolving them would be most of a whole merge. + pub(super) fn unresolve_by_sweep(&mut self, files: &[FileId]) { + let mut leaving = vec![false; self.facts.len()]; + for file in files { + if let Some(slot) = leaving.get_mut(file.0 as usize) { + *slot = true; + } + } + let gone = |file: FileId| leaving.get(file.0 as usize).copied().unwrap_or(false); + self.reference_sites.retain(|_, sites| { + sites.retain(|site| !gone(site.file)); + !sites.is_empty() + }); + for file in files { + for key in self.ambiguous_by_file.remove(file).unwrap_or_default() { + self.forget_ambiguity(&key); + } + } + self.dependents.remove_all(&gone); + } + + /// How many references `files` hold, against how many every file holds — + /// the two numbers that choose between the two ways out. + pub(super) fn reference_share(&self, files: &[FileId]) -> (usize, usize) { + let count = + |file: &FileId| self.facts.get(file.0 as usize).map_or(0, |f| f.references.len()); + let total = self.facts.iter().map(|facts| facts.references.len()).sum(); + (files.iter().map(count).sum(), total) + } + + fn forget_ambiguity(&mut self, key: &DefinitionKey) { + let Some(count) = self.ambiguous_references.get_mut(key) else { return }; + *count -= 1; + if *count == 0 { + self.ambiguous_references.remove(key); + } + } + + /// One file's postings, and every table key resolving them read. + fn postings_of(&self, file: FileId) -> (Vec, Reads) { + let Some(facts) = self.facts.get(file.0 as usize) else { + return (Vec::new(), Reads::default()); + }; + recording(|| { + let mut out = Vec::new(); + for reference in &facts.references { + let site = ReferenceSite { file, name_span: reference.occurrence() }; + match reference { + ReferenceFact::Local { definition, .. } => { + let key = DefinitionKey { + file, + name_start: definition.start, + name_end: definition.end, + }; + out.push(Posting::Site(key, site)); + } + ReferenceFact::External { name, base, paths, surface, .. } => { + match resolve_fact(self, name, base.as_deref(), paths, *surface) { + ExternalTarget::Resolved(def) => { + out.push(Posting::Site(DefinitionKey::of(&def), site)); + } + ExternalTarget::Ambiguous(defs) => { + out.push(Posting::Ambiguous( + defs.iter().map(DefinitionKey::of).collect(), + )); + } + ExternalTarget::StillUnresolved => {} + } + } + } + } + out + }) + } +} diff --git a/crates/vlog_semantic/src/workspace/replace.rs b/crates/vlog_semantic/src/workspace/replace.rs new file mode 100644 index 0000000..379668d --- /dev/null +++ b/crates/vlog_semantic/src/workspace/replace.rs @@ -0,0 +1,345 @@ +//! Replacing one held file's record with a different one, doing only the +//! work the change can reach: the tables re-merged for the keys either record +//! names, from the files that contribute to them, and the postings re-done for +//! the files whose resolution read a key whose value really moved +//! (`docs/features/localized-reindex/README.md`). + +use std::collections::{BTreeMap, BTreeSet, HashSet}; + +use crate::model::SymbolKind; + +use super::dependents::Table; +use super::record::FileFacts; +use super::reexport::Reexport; +use super::update::Affected; +use super::{Def, FileId, WorkspaceIndex}; + +/// One unit's members: member name → every declaration of it. +type MemberTable = BTreeMap>; + +/// The entries an update names in the four tables resolution reads, held +/// aside: the old tables' entries, swapped back in for as long as it takes to +/// take the readers' old postings out. +#[derive(Default)] +struct Entries { + units: Vec<(String, Option>)>, + members: Vec<(String, Option)>, + hier_members: Vec<(String, Option)>, + reexports: Vec<(String, Option>)>, + /// The whole class → base table, when either record has a class with a + /// base — the only way it can move, and it is rebuilt whole when it does. + bases: Option>, +} + +/// The keys whose value, as resolution reads it, an update changed. +#[derive(Default)] +struct Moved { + keys: Vec<(Table, String)>, +} + +/// One declaration as resolution reads it — see [`seen`]. +type Seen<'a> = (FileId, u32, u32, SymbolKind, Option<&'a str>); + +/// What resolution reads of one declaration: which declaration it is (the +/// posting key is its file and name span), what kind, and the type a member +/// hop continues through. A declaration whose body grew moved its +/// `decl_span` and its lines, and no posting can tell. +fn seen(defs: &[Def]) -> Vec> { + defs.iter() + .map(|d| (d.file, d.name_span.start, d.name_span.end, d.kind, d.type_name.as_deref())) + .collect() +} + +fn seen_members(members: Option<&MemberTable>) -> Vec<(&str, Vec>)> { + members.into_iter().flatten().map(|(name, defs)| (name.as_str(), seen(defs))).collect() +} + +impl WorkspaceIndex { + /// Replace the record at `at` with a different one. + /// + /// * The **tables** are re-merged for the keys either record names + /// ([`Affected`]), from the records of the files that contribute to those + /// keys — the same loop a whole merge runs, over fewer files. + /// * The **postings** are re-done for this file and for every file whose + /// last resolution read a key whose value moved + /// ([`Dependents`](super::dependents::Dependents)): taken out against the + /// old tables, put back against the new ones. + /// + /// A file that read no moved key read only values this replacement did not + /// change, so its postings are already what a rebuild would give. "Moved" + /// is judged as resolution sees a value ([`seen`]): an edit inside a + /// module's body moves the module's extent and the declarations after the + /// edit, but not the module's name, so the files that only instantiate it + /// are left alone. + /// + /// Returns the files whose postings were re-done, for the tests that pin + /// the narrowing itself. + pub(super) fn replace_facts(&mut self, at: usize, facts: FileFacts) -> Vec { + let file = FileId(at as u32); + let mut affected = Affected::of(&self.facts[at]); + affected.add(&facts); + let contributors = self.contributors(&affected, at); + let mut old = self.take_entries(&affected); + let mut old_facts = std::mem::replace(&mut self.facts[at], facts); + self.merge_tables(Some(&affected), contributors.as_deref()); + if old.bases.is_some() { + self.merge_bases(); + } + let readers = self.readers_of(&self.moved(&old, &affected), file); + // The readers' old postings out: re-resolved against the tables and + // the record they were made from, which costs what putting them back + // costs — or, when the readers hold more than an eighth of every + // reference, swept out in one pass over the postings, which is then + // the cheaper of the two (QA F5: every importer of a widely imported + // package re-resolved twice was slower than the old whole merge). + let (share, total) = self.reference_share(&readers); + if sweeps(share, total) { + self.unresolve_by_sweep(&readers); + } else { + self.swap_entries(&mut old); + std::mem::swap(&mut self.facts[at], &mut old_facts); + self.unresolve_files(&readers); + self.swap_entries(&mut old); + std::mem::swap(&mut self.facts[at], &mut old_facts); + } + self.resolve_files(&readers); + readers + } + + /// Take the entries `affected` names out of the tables resolution reads. + fn take_entries(&mut self, affected: &Affected) -> Entries { + Entries { + units: take(&mut self.units, &affected.units), + members: take(&mut self.members, &affected.containers), + hier_members: take(&mut self.hier_members, &affected.containers), + reexports: take(&mut self.reexports, &affected.exporters), + bases: (!affected.classes.is_empty()).then(|| std::mem::take(&mut self.bases)), + } + } + + /// Exchange the held entries with the tables' — twice is no change. + fn swap_entries(&mut self, held: &mut Entries) { + swap_in(&mut self.units, &mut held.units); + swap_in(&mut self.members, &mut held.members); + swap_in(&mut self.hier_members, &mut held.hier_members); + swap_in(&mut self.reexports, &mut held.reexports); + if let Some(bases) = held.bases.as_mut() { + std::mem::swap(&mut self.bases, bases); + } + } + + /// Every key whose value, as resolution reads it, differs between the + /// held entries and the tables now. + fn moved(&self, old: &Entries, affected: &Affected) -> Moved { + let mut out = Moved::default(); + for (name, defs) in &old.units { + let now = self.units.get(name).map_or(&[][..], Vec::as_slice); + if seen(defs.as_deref().unwrap_or_default()) != seen(now) { + out.keys.push((Table::Unit, name.clone())); + } + } + for (table, held, now) in [ + (Table::Container, &old.members, &self.members), + (Table::Hier, &old.hier_members, &self.hier_members), + ] { + for (unit, members) in held { + if seen_members(members.as_ref()) != seen_members(now.get(unit)) { + out.keys.push((table, unit.clone())); + } + } + } + for (exporter, entries) in &old.reexports { + if entries.as_ref() != self.reexports.get(exporter) { + out.keys.push((Table::Exporter, exporter.clone())); + } + } + if let Some(bases) = &old.bases { + for class in &affected.classes { + if bases.get(class) != self.bases.get(class) { + out.keys.push((Table::Base, class.clone())); + } + } + } + out + } + + /// This file and every file whose postings read a moved key, in id order. + fn readers_of(&self, moved: &Moved, file: FileId) -> Vec { + let mut out: BTreeSet = BTreeSet::from([file]); + for (table, key) in &moved.keys { + out.extend(self.dependents.readers(*table, key)); + } + out.into_iter().collect() + } + + /// Every file holding a record under a key in `affected`, in id order — + /// read off the merged tables, whose entries say which file each came + /// from. `None` means every file: a re-export entry does not carry its + /// file, so a record that names an exporter takes the whole loop. + fn contributors(&self, affected: &Affected, at: usize) -> Option> { + if !affected.exporters.is_empty() { + return None; + } + let mut out: BTreeSet = BTreeSet::from([at]); + let id = |file: FileId| file.0 as usize; + for name in &affected.units { + out.extend(self.units.get(name).into_iter().flatten().map(|def| id(def.file))); + } + for unit in &affected.containers { + for table in [&self.members, &self.hier_members] { + let defs = table.get(unit).into_iter().flat_map(|m| m.values()).flatten(); + out.extend(defs.map(|def| id(def.file))); + } + } + for module in &affected.modules { + let edges = self.instantiations.get(module).into_iter().flatten(); + out.extend(edges.map(|edge| id(edge.file))); + } + for base in &affected.bases { + let edges = self.subclasses.get(base).into_iter().flatten(); + out.extend(edges.map(|edge| id(edge.file))); + } + for name in &affected.macros { + let defines = self.macro_definitions.get(name).into_iter().flatten(); + out.extend(defines.map(|(file, _)| id(*file))); + } + Some(out.into_iter().collect()) + } +} + +/// Below this many references in the whole index a sweep never pays: the +/// re-resolution of a few small files is already sub-millisecond. +const SWEEP_FLOOR: usize = 20_000; + +/// Whether the readers' old postings go out by a sweep ([`sweeps`]'s rule: +/// they hold more than an eighth of every reference in an index big enough +/// for that to cost something) or by re-resolution. +fn sweeps(share: usize, total: usize) -> bool { + #[cfg(test)] + if let Some(forced) = tests::FORCE_SWEEP.with(std::cell::Cell::get) { + return forced; + } + total >= SWEEP_FLOOR && share * 8 > total +} + +/// Remove the entries under `keys`, keeping each with its key — an absent +/// one as `None`, so swapping it back in removes what is there. +fn take(table: &mut BTreeMap, keys: &HashSet) -> Vec<(String, Option)> { + keys.iter().map(|key| (key.clone(), table.remove(key))).collect() +} + +/// Exchange each held entry with the table's entry under the same key, an +/// absent entry on either side included. +fn swap_in(table: &mut BTreeMap, held: &mut [(String, Option)]) { + for (key, value) in held { + let current = table.remove(key.as_str()); + if let Some(value) = value.take() { + table.insert(key.clone(), value); + } + *value = current; + } +} + +#[cfg(test)] +mod tests { + use std::cell::Cell; + use std::path::PathBuf; + + use super::*; + + thread_local! { + /// Which way out a test forces, whatever the sizes say. + pub(super) static FORCE_SWEEP: Cell> = const { Cell::new(None) }; + } + + /// Every edit of a small chained design, each checked against a whole + /// build, with the readers' postings taken out each way in turn — the + /// sweep is otherwise taken only on trees of 20 000 references and up. + #[test] + fn both_ways_out_give_the_index_a_whole_build_gives() { + let base = [ + ("a.sv", "package a_pkg;\n localparam int W = 8;\nendpackage\nclass base_c;\n int m;\nendclass\n"), + ("b.sv", "module leaf (input logic clk);\n logic s;\nendmodule\nclass mid_c extends base_c;\nendclass\n"), + ("c.sv", "module top;\n import a_pkg::*;\n logic c;\n leaf u (.clk(c));\n initial $display(u.s, W);\nendmodule\nclass leaf_c extends mid_c;\n function void f(); m = 1; endfunction\nendclass\n"), + ("d.sv", "module dup (input logic a);\nendmodule\nmodule user;\n dup i (.a(1'b0));\nendmodule\n"), + ("e.sv", "module user2;\n dup j ();\nendmodule\n"), + ]; + let edits = [ + ("a.sv", "// top\npackage a_pkg;\n localparam int W = 8;\n localparam int V = 1;\nendpackage\nclass base_c;\n int n, m;\nendclass\n"), + ("b.sv", "module leaf (input logic clq);\n logic s;\nendmodule\nclass mid_c extends other_c;\nendclass\n"), + ("b.sv", "module leaf (input logic clq);\n logic s;\nendmodule\nmodule dup;\nendmodule\n"), + ("e.sv", "// a line\nmodule user2;\n dup j ();\nendmodule\n"), + ("c.sv", "module top;\n logic c;\nendmodule\n"), + ]; + for forced in [true, false] { + FORCE_SWEEP.with(|cell| cell.set(Some(forced))); + let mut files: Vec<(String, String)> = + base.iter().map(|(p, s)| (p.to_string(), s.to_string())).collect(); + let mut index = build(&files); + for round in 0..2 { + for (path, text) in edits.iter().chain(base.iter()) { + let slot = files.iter_mut().find(|(p, _)| p == path).expect("a held file"); + slot.1 = text.to_string(); + index.update_file(PathBuf::from(path), text); + assert_eq!( + index.fingerprint(), + build(&files).fingerprint(), + "sweep={forced}, round {round}: `{path}`" + ); + } + } + FORCE_SWEEP.with(|cell| cell.set(None)); + } + } + + fn build(files: &[(String, String)]) -> WorkspaceIndex { + WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(p), s.as_str()))) + } + + const LEAF: &str = "module leaf (input logic clk);\n logic s;\nendmodule\n"; + const TOP: &str = "module top;\n logic c;\n leaf u (.clk(c));\nendmodule\n"; + const TB: &str = "module tb;\n top t ();\n initial $display(t.u.s);\nendmodule\n"; + + /// The files an update of `leaf.sv` to `text` re-resolves, by path. + fn re_resolved(text: &str) -> Vec { + let mut index = WorkspaceIndex::build([ + (PathBuf::from("leaf.sv"), LEAF), + (PathBuf::from("tb.sv"), TB), + (PathBuf::from("top.sv"), TOP), + ]); + let facts = FileFacts::of(PathBuf::from("leaf.sv"), text); + let files = index.replace_facts(0, facts); + files.iter().filter_map(|&file| index.path(file)).map(|p| p.display().to_string()).collect() + } + + #[test] + fn a_body_edit_re_resolves_only_the_file_itself() { + // The module's name, its port and its signal keep their spans; only + // its extent and its body moved, and no posting can see either. A new + // declaration would be a new member, and the hierarchical reader + // re-resolved for it — a member table is judged whole. + let grown = "module leaf (input logic clk);\n logic s;\n assign s = clk;\nendmodule\n"; + assert_eq!(re_resolved(grown), ["leaf.sv"]); + } + + #[test] + fn a_port_edit_re_resolves_the_file_that_connects_to_it() { + // Same length, so the signal after it keeps its span — but the + // hierarchical path asks the connection surface before the + // hierarchical one, so it read the port table too. + let renamed = "module leaf (input logic clq);\n logic s;\nendmodule\n"; + assert_eq!(re_resolved(renamed), ["leaf.sv", "tb.sv", "top.sv"]); + } + + #[test] + fn a_moved_internal_signal_re_resolves_the_file_whose_path_reaches_it() { + let moved = "module leaf (input logic clk);\n logic pad;\n logic s;\nendmodule\n"; + assert_eq!(re_resolved(moved), ["leaf.sv", "tb.sv"]); + } + + #[test] + fn an_edit_above_everything_re_resolves_every_reader() { + let shifted = format!("// above\n{LEAF}"); + assert_eq!(re_resolved(&shifted), ["leaf.sv", "tb.sv", "top.sv"]); + } +} diff --git a/crates/vlog_semantic/src/workspace/update.rs b/crates/vlog_semantic/src/workspace/update.rs index 839cadf..31c4a59 100644 --- a/crates/vlog_semantic/src/workspace/update.rs +++ b/crates/vlog_semantic/src/workspace/update.rs @@ -4,18 +4,15 @@ //! makes that hold by construction, and the [`WorkspaceIndex::fingerprint`] //! that proves it. -use std::collections::{BTreeMap, HashSet}; +use std::collections::HashSet; use std::path::{Path, PathBuf}; use vlog_parser::defines::DefineKind; use crate::model::Surface; -use super::external::{resolve_fact, ExternalTarget}; -use super::record::{facts_of, FileFacts, ReferenceFact}; -use super::{ - DefinitionKey, FileId, InheritanceEdge, InstantiationEdge, ReferenceSite, WorkspaceIndex, -}; +use super::record::{facts_of, FileFacts}; +use super::{DefinitionKey, FileId, InheritanceEdge, InstantiationEdge, WorkspaceIndex}; impl WorkspaceIndex { /// Replace one file's contribution to the index — or add the file, when @@ -38,8 +35,13 @@ impl WorkspaceIndex { /// remove; nothing in this workspace holds one across an update (the /// server refreshes every overlay after it, exactly as it does after a /// rebuild). - pub fn update_file(&mut self, path: PathBuf, src: &str) { - self.update_facts(facts_of(path, src)); + /// + /// Reports whether the index moved: `false` exactly when the file's new + /// record equals the one held, which is the watcher's echo of a save and a + /// save that changed nothing — the cheapest answer there is, and a sound + /// one, since an index is a function of its records. + pub fn update_file(&mut self, path: PathBuf, src: &str) -> bool { + self.update_facts(facts_of(path, src)) } /// [`WorkspaceIndex::update_file`] for a file whose facts are already @@ -51,26 +53,28 @@ impl WorkspaceIndex { /// [`IndexBuilder::add_file`](super::IndexBuilder::add_file) with /// the parse already done: same contract, same result. Whether the record /// really describes the file is the caller's business. - pub fn update_facts(&mut self, facts: FileFacts) { + /// + /// Reports whether the index moved, as [`WorkspaceIndex::update_file`] + /// does. + pub fn update_facts(&mut self, facts: FileFacts) -> bool { let path = facts.path.clone(); match self.facts.binary_search_by(|held| held.path.cmp(&path)) { + Ok(at) if self.facts[at] == facts => return false, // The common case — a saved file the index already holds. Only the // names this file declared before or declares now can have moved, // and the file list has not, so ids are untouched. Ok(at) => { - let mut affected = Affected::of(&self.facts[at]); - affected.add(&facts); - self.facts[at] = facts; - self.merge(Some(&affected)); + self.replace_facts(at, facts); } // A file the index did not hold: every id from here on shifts, so // every table is rebuilt from the records. No parse, no read. Err(at) => { self.files.insert(at, path); self.facts.insert(at, facts); - self.merge(None); + self.merge(); } } + true } /// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for @@ -117,7 +121,7 @@ impl WorkspaceIndex { } } } - self.merge(None); + self.merge(); } /// Drop one file from the index, reporting whether it was there. @@ -130,7 +134,7 @@ impl WorkspaceIndex { }; self.files.remove(at); self.facts.remove(at); - self.merge(None); + self.merge(); true } @@ -185,11 +189,11 @@ impl WorkspaceIndex { )); } } - let mut ambiguous: Vec = self.ambiguous_references.iter().copied().collect(); + let mut ambiguous: Vec<(&DefinitionKey, &u32)> = self.ambiguous_references.iter().collect(); ambiguous.sort(); - for definition in ambiguous { + for (definition, count) in ambiguous { out.push_str(&format!( - "ambiguous-ref {}:{}..{}\n", + "ambiguous-ref {}:{}..{} x{count}\n", definition.file.0, definition.name_start, definition.name_end )); } @@ -238,17 +242,36 @@ impl WorkspaceIndex { )); } } + // Not an answer any caller reads, but the table that decides which + // files the *next* update re-resolves: one that drifted from a + // rebuild's would be a stale posting waiting to happen. + self.dependents.render(&mut out); out } - /// Rebuild the merged tables from the per-file records. + /// Rebuild every merged table, the postings and the readers table from + /// the per-file records. /// - /// `affected` names the keys that may have moved; `None` means all of - /// them. Either way this is one loop over the path-sorted records pushing - /// in the order it meets them, which is the *only* place any table's order - /// is decided — so a restricted merge and a whole one agree by - /// construction, and both agree with [`IndexBuilder::finish`](super::IndexBuilder::finish). - pub(super) fn merge(&mut self, affected: Option<&Affected>) { + /// The tables are one loop over the path-sorted records pushing in the + /// order it meets them ([`WorkspaceIndex::merge_tables`]), which is the + /// *only* place any table's order is decided — so a restricted merge over + /// a few files and a whole one agree by construction, and both agree with + /// [`IndexBuilder::finish`](super::IndexBuilder::finish). + pub(super) fn merge(&mut self) { + self.merge_tables(None, None); + self.merge_bases(); + // A changed declaration can change how references in any file resolve, + // even when only one file's facts moved. Re-resolving compact facts is + // one in-memory pass; no source is read or parsed. + self.merge_references(); + } + + /// The table half of [`WorkspaceIndex::merge`]: clear the keys `affected` + /// names (all of them for `None`) and push back every record under them, + /// visiting `files` — the files that hold such records, in id order — or + /// every file for `None`. Visiting fewer files is the same loop, because a + /// file with no record under a cleared key pushes nothing. + pub(super) fn merge_tables(&mut self, affected: Option<&Affected>, files: Option<&[usize]>) { match affected { None => { self.units.clear(); @@ -281,117 +304,87 @@ impl WorkspaceIndex { } } } - for (id, facts) in self.facts.iter().enumerate() { - let file = FileId(id as u32); - for decl in &facts.units { - if affected.is_some_and(|a| !a.units.contains(&decl.name)) { - continue; - } - self.units.entry(decl.name.clone()).or_default().push(decl.def(file)); - } - for (unit, decl) in &facts.members { - if affected.is_some_and(|a| !a.containers.contains(unit)) { - continue; - } - // The record's own tag picks the table; the two are keyed - // alike, are cleared together above, and a caller that names - // no surface reads the connection one. - let table = match decl.surface { - Surface::Connection => &mut self.members, - Surface::Hierarchical => &mut self.hier_members, - }; - table - .entry(unit.clone()) - .or_default() - .entry(decl.name.clone()) - .or_default() - .push(decl.def(file)); - } - for (module, edge) in &facts.instantiations { - if affected.is_some_and(|a| !a.modules.contains(module)) { - continue; - } - self.instantiations.entry(module.clone()).or_default().push(InstantiationEdge { - file, - owner: edge.owner.clone(), - site_span: edge.site_span, - instances: edge.instances.clone(), - }); - } - for (base, subclass) in &facts.subclasses { - if affected.is_some_and(|a| !a.bases.contains(base)) { - continue; - } - self.subclasses - .entry(base.clone()) - .or_default() - .push(InheritanceEdge { file, subclass: subclass.clone() }); - } - for (exporter, entry) in &facts.reexports { - if affected.is_some_and(|a| !a.exporters.contains(exporter)) { - continue; - } - self.reexports.entry(exporter.clone()).or_default().push(entry.clone()); - } - for (entry, define) in facts.defines.entries().iter().enumerate() { - if define.kind != DefineKind::Define - || affected.is_some_and(|a| !a.macros.contains(&define.name)) - { - continue; - } - self.macro_definitions.entry(define.name.clone()).or_default().push((file, entry)); - } + match files { + Some(files) => files.iter().for_each(|&id| self.push_records(id, affected)), + None => (0..self.facts.len()).for_each(|id| self.push_records(id, affected)), } - // The reverse inheritance edge is rebuilt whole every time, whatever - // `affected` says: it is one entry per `extends` written anywhere (a - // few thousand on opentitan), and rebuilding it is both cheaper to - // reason about and the reason a restricted merge cannot leave it - // half-updated. First in file order wins, which is `units`' rule. + } + + /// Push one file's records under the keys `affected` names (every key for + /// `None`), in the order the record holds them. + fn push_records(&mut self, id: usize, affected: Option<&Affected>) { + let file = FileId(id as u32); + let Some(facts) = self.facts.get(id) else { return }; + for decl in &facts.units { + if affected.is_some_and(|a| !a.units.contains(&decl.name)) { + continue; + } + self.units.entry(decl.name.clone()).or_default().push(decl.def(file)); + } + for (unit, decl) in &facts.members { + if affected.is_some_and(|a| !a.containers.contains(unit)) { + continue; + } + // The record's own tag picks the table; the two are keyed + // alike, are cleared together above, and a caller that names + // no surface reads the connection one. + let table = match decl.surface { + Surface::Connection => &mut self.members, + Surface::Hierarchical => &mut self.hier_members, + }; + table + .entry(unit.clone()) + .or_default() + .entry(decl.name.clone()) + .or_default() + .push(decl.def(file)); + } + for (module, edge) in &facts.instantiations { + if affected.is_some_and(|a| !a.modules.contains(module)) { + continue; + } + self.instantiations.entry(module.clone()).or_default().push(InstantiationEdge { + file, + owner: edge.owner.clone(), + site_span: edge.site_span, + instances: edge.instances.clone(), + }); + } + for (base, subclass) in &facts.subclasses { + if affected.is_some_and(|a| !a.bases.contains(base)) { + continue; + } + self.subclasses + .entry(base.clone()) + .or_default() + .push(InheritanceEdge { file, subclass: subclass.clone() }); + } + for (exporter, entry) in &facts.reexports { + if affected.is_some_and(|a| !a.exporters.contains(exporter)) { + continue; + } + self.reexports.entry(exporter.clone()).or_default().push(entry.clone()); + } + for (entry, define) in facts.defines.entries().iter().enumerate() { + if define.kind != DefineKind::Define + || affected.is_some_and(|a| !a.macros.contains(&define.name)) + { + continue; + } + self.macro_definitions.entry(define.name.clone()).or_default().push((file, entry)); + } + } + + /// The reverse inheritance edge, rebuilt whole: one entry per `extends` + /// written anywhere (a few thousand on opentitan), first in file order + /// winning, which is `units`' rule. + pub(super) fn merge_bases(&mut self) { self.bases.clear(); for facts in &self.facts { for (base, subclass) in &facts.subclasses { self.bases.entry(subclass.name.clone()).or_insert_with(|| base.clone()); } } - // A changed declaration can change how references in any file resolve, - // even when only one file's facts moved. Re-resolving compact facts is - // one in-memory pass; no source is read or parsed. - self.merge_references(); - } - - /// Rebuild declaration-to-occurrence postings from compact per-file facts. - fn merge_references(&mut self) { - let mut sites: BTreeMap> = BTreeMap::new(); - let mut ambiguous: HashSet = HashSet::new(); - for (id, facts) in self.facts.iter().enumerate() { - let file = FileId(id as u32); - for reference in &facts.references { - let site = ReferenceSite { file, name_span: reference.occurrence() }; - match reference { - ReferenceFact::Local { definition, .. } => { - let key = DefinitionKey { - file, - name_start: definition.start, - name_end: definition.end, - }; - sites.entry(key).or_default().push(site); - } - ReferenceFact::External { name, base, paths, surface, .. } => { - match resolve_fact(self, name, base.as_deref(), paths, *surface) { - ExternalTarget::Resolved(def) => { - sites.entry(DefinitionKey::of(&def)).or_default().push(site); - } - ExternalTarget::Ambiguous(defs) => { - ambiguous.extend(defs.iter().map(DefinitionKey::of)); - } - ExternalTarget::StillUnresolved => {} - } - } - } - } - } - self.reference_sites = sites; - self.ambiguous_references = ambiguous; } } @@ -399,33 +392,37 @@ impl WorkspaceIndex { /// file can leave every other key alone. #[derive(Debug, Default)] pub(super) struct Affected { - units: HashSet, + pub(super) units: HashSet, /// Keys of the `members` table — the *unit* a member is exported by, not /// the member itself. A whole unit's sub-table is the smallest thing worth /// rebuilding: one file adding a member to a package cannot move any other /// package. - containers: HashSet, - modules: HashSet, - bases: HashSet, + pub(super) containers: HashSet, + pub(super) modules: HashSet, + pub(super) bases: HashSet, /// Keys of the `reexports` table — the package that writes the `export`, /// never the package it takes the name from: a file changing what `a_pkg` /// re-exports moves `a_pkg`'s edges and no one else's. - exporters: HashSet, - macros: HashSet, + pub(super) exporters: HashSet, + pub(super) macros: HashSet, + /// Keys of the `bases` table — the *extending* class, which is what a + /// member lookup up the `extends` chain asks it by. + pub(super) classes: HashSet, } impl Affected { - fn of(facts: &FileFacts) -> Affected { + pub(super) fn of(facts: &FileFacts) -> Affected { let mut out = Affected::default(); out.add(facts); out } - fn add(&mut self, facts: &FileFacts) { + pub(super) fn add(&mut self, facts: &FileFacts) { self.units.extend(facts.units.iter().map(|decl| decl.name.clone())); self.containers.extend(facts.members.iter().map(|(unit, _)| unit.clone())); self.modules.extend(facts.instantiations.iter().map(|(module, _)| module.clone())); self.bases.extend(facts.subclasses.iter().map(|(base, _)| base.clone())); + self.classes.extend(facts.subclasses.iter().map(|(_, class)| class.name.clone())); self.exporters.extend(facts.reexports.iter().map(|(exporter, _)| exporter.clone())); self.macros.extend(facts.defines.entries().iter().map(|define| define.name.clone())); } diff --git a/crates/vlog_semantic/tests/localized_reindex.rs b/crates/vlog_semantic/tests/localized_reindex.rs new file mode 100644 index 0000000..0565fe7 --- /dev/null +++ b/crates/vlog_semantic/tests/localized_reindex.rs @@ -0,0 +1,350 @@ +//! The localized update's whole claim, attacked: after any sequence of +//! one-file updates, the index is the index a whole build over the same file +//! contents gives — postings, ambiguity, edges and the readers table that +//! decides which files the *next* update re-resolves included +//! (`docs/features/localized-reindex/README.md`). +//! +//! Each case is a design whose references reach across files through one of +//! the hops resolution takes — a port connection, a package import, a +//! re-export, an `extends` chain, a typedef alias, a hierarchical path through +//! instances, a qualified miss — and a sequence of edits to the file at the +//! far end of the hop, chosen so that a narrowing which forgot that hop would +//! leave a stale posting the fingerprint shows. The randomized sweep at the +//! bottom drives the same designs through seeded mutations. + +use std::collections::BTreeMap; +use std::path::PathBuf; + +use vlog_semantic::WorkspaceIndex; + +fn build(files: &BTreeMap) -> WorkspaceIndex { + WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(p), s.as_str()))) +} + +/// Apply `steps` one update at a time, checking the index against a whole +/// build after every one of them. +fn holds(initial: &[(&str, &str)], steps: &[(&str, &str)]) { + let mut files: BTreeMap = + initial.iter().map(|(p, s)| (p.to_string(), s.to_string())).collect(); + let mut index = build(&files); + for (at, (path, text)) in steps.iter().enumerate() { + files.insert(path.to_string(), text.to_string()); + index.update_file(PathBuf::from(path), text); + assert_eq!( + index.fingerprint(), + build(&files).fingerprint(), + "step {at}: updating `{path}` must give the index a whole build would have" + ); + } +} + +const PORTS: [(&str, &str); 2] = [ + ("leaf.sv", "module leaf (input logic clk, output logic q);\nendmodule\n"), + ("top.sv", "module top;\n logic c, d;\n leaf u_leaf (.clk(c), .q(d));\nendmodule\n"), +]; + +#[test] +fn a_port_connection_follows_every_edit_of_the_instantiated_module() { + holds( + &PORTS, + &[ + // A body edit: the ports keep their spans, the module's extent grows. + ("leaf.sv", "module leaf (input logic clk, output logic q);\n logic s;\nendmodule\n"), + // A comment above everything: every span moves. + ("leaf.sv", "// moved\nmodule leaf (input logic clk, output logic q);\nendmodule\n"), + // A port renamed, then removed, then the module renamed away. + ("leaf.sv", "module leaf (input logic clock, output logic q);\nendmodule\n"), + ("leaf.sv", "module leaf (output logic q);\nendmodule\n"), + ("leaf.sv", "module other (input logic clk, output logic q);\nendmodule\n"), + // And back, so a key that went missing comes home. + (PORTS[0].0, PORTS[0].1), + // The instantiating side moves too. + ("top.sv", "module top;\n logic c, d;\n leaf u_leaf (.q(d), .clk(c));\nendmodule\n"), + ], + ); +} + +const PACKAGES: [(&str, &str); 3] = [ + ("a_pkg.sv", "package a_pkg;\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n"), + ("b_pkg.sv", "package b_pkg;\n import a_pkg::*;\n export a_pkg::*;\nendpackage\n"), + ( + "user.sv", + "module user;\n import b_pkg::*;\n word_t w;\n localparam int X = W + a_pkg::W;\nendmodule\n", + ), +]; + +#[test] +fn an_import_and_a_reexport_follow_every_edit_of_the_package_at_the_end() { + holds( + &PACKAGES, + &[ + ("a_pkg.sv", "package a_pkg;\n // shifted\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n"), + ("a_pkg.sv", "package a_pkg;\n localparam int W2 = 8;\n typedef logic [7:0] word_t;\nendpackage\n"), + // The middle package stops re-exporting, then starts again. + ("b_pkg.sv", "package b_pkg;\n import a_pkg::*;\nendpackage\n"), + (PACKAGES[1].0, PACKAGES[1].1), + // The package at the end renamed: every qualified use becomes a miss. + ("a_pkg.sv", "package c_pkg;\n localparam int W = 8;\nendpackage\n"), + (PACKAGES[0].0, PACKAGES[0].1), + ], + ); +} + +const CLASSES: [(&str, &str); 3] = [ + ("base.sv", "class base_c;\n int m;\n function void f(); endfunction\nendclass\n"), + ("mid.sv", "class mid_c extends base_c;\nendclass\n"), + ("leaf_c.sv", "class leaf_c extends mid_c;\n function void g();\n m = 1;\n f();\n this.m = 2;\n endfunction\nendclass\n"), +]; + +#[test] +fn an_inherited_member_follows_every_edit_along_the_extends_chain() { + holds( + &CLASSES, + &[ + // The member two hops up moves, is renamed, comes back. + ( + "base.sv", + "class base_c;\n int pad;\n int m;\n function void f(); endfunction\nendclass\n", + ), + ("base.sv", "class base_c;\n int n;\n function void f(); endfunction\nendclass\n"), + (CLASSES[0].0, CLASSES[0].1), + // The middle of the chain changes what it extends. + ("mid.sv", "class mid_c extends other_c;\nendclass\n"), + ("mid.sv", "class mid_c;\nendclass\n"), + (CLASSES[1].0, CLASSES[1].1), + // The middle class declares the member itself, shadowing the base. + ("mid.sv", "class mid_c extends base_c;\n int m;\nendclass\n"), + ], + ); +} + +const ALIASES: [(&str, &str); 3] = [ + ("hdr.sv", "package hdr_pkg;\n typedef struct packed { logic [7:0] addr; logic v; } hdr_t;\nendpackage\n"), + ("pkt.sv", "package pkt_pkg;\n import hdr_pkg::*;\n typedef struct packed { hdr_t hdr; logic [31:0] data; } pkt_t;\nendpackage\n"), + ("use.sv", "module use_it;\n import pkt_pkg::*;\n pkt_t p;\n assign p.hdr.addr = 8'h0;\nendmodule\n"), +]; + +#[test] +fn a_member_chain_through_struct_types_follows_every_edit_of_the_innermost_type() { + holds( + &ALIASES, + &[ + ("hdr.sv", "package hdr_pkg;\n typedef struct packed { logic v; logic [7:0] addr; } hdr_t;\nendpackage\n"), + ("hdr.sv", "package hdr_pkg;\n typedef struct packed { logic [7:0] address; logic v; } hdr_t;\nendpackage\n"), + ("pkt.sv", "package pkt_pkg;\n import hdr_pkg::*;\n typedef struct packed { logic [31:0] data; hdr_t hdr; } pkt_t;\nendpackage\n"), + (ALIASES[0].0, ALIASES[0].1), + ], + ); +} + +#[test] +fn a_member_whose_type_alone_changes_moves_the_hop_through_it() { + // `hdr_t` and `oth_t` are the same length, so the member `hdr` keeps its + // span and only its declared type — the hop `p.hdr.addr` takes — moves. + let hdr = "package hdr_pkg;\n typedef struct packed { logic [7:0] addr; } hdr_t;\n \ + typedef struct packed { logic v; logic [7:0] addr; } oth_t;\nendpackage\n"; + holds( + &[("hdr.sv", hdr), ALIASES[1], ALIASES[2]], + &[ + ("pkt.sv", &ALIASES[1].1.replace("hdr_t hdr", "oth_t hdr")), + ("pkt.sv", &ALIASES[1].1.replace("hdr_t hdr", "nop_t hdr")), + ALIASES[1], + ], + ); +} + +#[test] +fn a_unit_whose_kind_alone_changes_moves_a_path_rooted_at_it() { + // `module h_x` and `package h_x` put the name, and the member after it, + // at the same offsets: only the unit's kind moves, and a top-rooted + // hierarchical path roots only at a module. + holds( + &[ + ("h_x.sv", "module h_x;\n logic s;\nendmodule\n"), + ("h_xtb.sv", "module h_xtb;\n initial $display(h_x.s);\nendmodule\n"), + ], + &[ + ("h_x.sv", "package h_x;\n logic s;\nendpackage\n"), + ("h_x.sv", "module h_x;\n logic s;\nendmodule\n"), + ], + ); +} + +const HIERARCHY: [(&str, &str); 4] = [ + ("h_leaf.sv", "module h_leaf;\n logic sig;\nendmodule\n"), + ("h_mid.sv", "module h_mid;\n h_leaf u_leaf ();\nendmodule\n"), + ("h_top.sv", "module h_top;\n h_mid u_mid ();\nendmodule\n"), + ( + "h_tb.sv", + "module h_tb;\n h_top dut ();\n initial $display(dut.u_mid.u_leaf.sig);\nendmodule\n", + ), +]; + +#[test] +fn a_hierarchical_path_follows_every_edit_of_the_module_at_its_tail() { + holds( + &HIERARCHY, + &[ + // The signal at the end moves, goes, comes back as another kind. + ("h_leaf.sv", "module h_leaf;\n logic pad;\n logic sig;\nendmodule\n"), + ("h_leaf.sv", "module h_leaf;\n logic other;\nendmodule\n"), + ("h_leaf.sv", "module h_leaf;\n wire sig;\nendmodule\n"), + // An instance in the middle renamed, then its module swapped. + ("h_mid.sv", "module h_mid;\n h_leaf u_leaf2 ();\nendmodule\n"), + ("h_mid.sv", "module h_mid;\n h_top u_leaf ();\nendmodule\n"), + (HIERARCHY[1].0, HIERARCHY[1].1), + // The tail module turned into a port, which the connection + // surface answers first. + ("h_leaf.sv", "module h_leaf (input logic sig);\nendmodule\n"), + ], + ); +} + +const MISSES: [(&str, &str); 2] = [ + ("asker.sv", "module asker;\n localparam int K = later_pkg::K;\n later_m u ();\nendmodule\n"), + ("other.sv", "module other;\nendmodule\n"), +]; + +#[test] +fn a_use_that_found_nothing_is_answered_the_moment_another_file_declares_it() { + holds( + &MISSES, + &[ + // The other file starts declaring both names, then twice over, + // then stops — a miss, a hit, an ambiguity, a miss. + ("other.sv", "package later_pkg;\n localparam int K = 1;\nendpackage\nmodule later_m;\nendmodule\n"), + ("other.sv", "package later_pkg;\n localparam int K = 1;\n localparam int K = 2;\nendpackage\nmodule later_m;\nendmodule\nmodule later_m;\nendmodule\n"), + ("other.sv", "module other;\nendmodule\n"), + ], + ); +} + +#[test] +fn a_name_two_files_declare_stays_ambiguous_exactly_as_long_as_it_is() { + holds( + &[ + ("d1.sv", "module dup (input logic a);\nendmodule\n"), + ("d2.sv", "module dup (input logic a);\nendmodule\n"), + ("u.sv", "module u;\n logic x;\n dup i (.a(x));\nendmodule\n"), + ], + &[ + ("d1.sv", "module dup_one (input logic a);\nendmodule\n"), + ("d1.sv", "// back\nmodule dup (input logic a);\nendmodule\n"), + ("d2.sv", "module dup (input logic b);\nendmodule\n"), + ], + ); +} + +#[test] +fn a_define_a_broken_file_and_an_unchanged_save_all_hold() { + holds( + &[ + ("defs.svh", "`define W 8\n`define F(a) (a)\n"), + ("m.sv", "module m;\n logic [`W-1:0] x;\nendmodule\n"), + ], + &[ + ("defs.svh", "`define W 16\n`define F(a, b) (a+b)\n"), + ("defs.svh", "`undef W\n`define W 16\n"), + ("m.sv", "module m;\n logic [`W-1:0] x\nendmodule\n"), + ("m.sv", "module m;\n logic [`W-1:0] x;\nendmodule\n"), + ("m.sv", "module m;\n logic [`W-1:0] x;\nendmodule\n"), + ], + ); +} + +#[test] +fn an_unchanged_record_reports_that_nothing_moved() { + let files: BTreeMap = + PORTS.iter().map(|(p, s)| (p.to_string(), s.to_string())).collect(); + let mut index = build(&files); + let before = index.fingerprint(); + assert!(!index.update_file(PathBuf::from(PORTS[0].0), PORTS[0].1), "same text, same record"); + assert_eq!(index.fingerprint(), before); + // A comment after the last token moves no span the record holds. + let trailing = format!("{}// trailing\n", PORTS[0].1); + assert!(!index.update_file(PathBuf::from(PORTS[0].0), &trailing), "{trailing:?}"); + let renamed = PORTS[0].1.replace("clk", "clock"); + assert!(index.update_file(PathBuf::from(PORTS[0].0), &renamed), "a port renamed moves it"); +} + +// ---------------------------------------------------------------------- +// The seeded sweep +// ---------------------------------------------------------------------- + +/// xorshift64*: reproducible from a seed, no dependency. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } +} + +/// One random edit of `text`: a line inserted, deleted, duplicated or swapped +/// with its neighbour, or one identifier-ish word renamed to another from +/// the design — the kinds of edit that move spans, names and whole +/// declarations. +fn mutate(text: &str, words: &[&str], rng: &mut Rng) -> String { + let mut lines: Vec = text.lines().map(str::to_string).collect(); + let at = rng.below(lines.len() + 1); + match rng.below(5) { + 0 => lines.insert(at, " // a comment".to_string()), + 1 if at < lines.len() => { + lines.remove(at); + } + 2 if at < lines.len() => { + let line = lines[at].clone(); + lines.insert(at, line); + } + 3 if at + 1 < lines.len() => lines.swap(at, at + 1), + _ => { + let from = words[rng.below(words.len())]; + let to = words[rng.below(words.len())]; + if let Some(line) = lines.iter_mut().find(|line| line.contains(from)) { + *line = line.replacen(from, to, 1); + } + } + } + let mut out = lines.join("\n"); + out.push('\n'); + out +} + +#[test] +fn a_seeded_sweep_of_mutations_over_every_design_holds() { + let designs: [&[(&str, &str)]; 5] = [&PORTS, &PACKAGES, &CLASSES, &ALIASES, &HIERARCHY]; + let words = [ + "leaf", "clk", "q", "a_pkg", "b_pkg", "W", "word_t", "base_c", "mid_c", "m", "f", "hdr_t", + "addr", "pkt_t", "h_leaf", "u_leaf", "sig", "h_mid", "u_mid", + ]; + let mut checked = 0; + for seed in 1..=8u64 { + let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15)); + let mut files: BTreeMap = BTreeMap::new(); + for design in designs { + files.extend(design.iter().map(|(p, s)| (p.to_string(), s.to_string()))); + } + let mut index = build(&files); + let paths: Vec = files.keys().cloned().collect(); + for step in 0..40 { + let path = &paths[rng.below(paths.len())]; + let text = mutate(&files[path], &words, &mut rng); + files.insert(path.clone(), text.clone()); + index.update_file(PathBuf::from(path), &text); + assert_eq!( + index.fingerprint(), + build(&files).fingerprint(), + "seed {seed}, step {step}: `{path}` became {text:?}" + ); + checked += 1; + } + } + assert_eq!(checked, 320); +} diff --git a/docs/features/localized-reindex/README.md b/docs/features/localized-reindex/README.md new file mode 100644 index 0000000..f700481 --- /dev/null +++ b/docs/features/localized-reindex/README.md @@ -0,0 +1,1286 @@ +# localized-reindex + +## Goal + +The owner's report: *"Every time a file gets edited, the whole database gets +re-indexed, which I think is not needed. I understand that changing a define +might cause the whole database to re-index, but not on typical changes that are +localized."* The incremental-index round (2026-08-27) already replaced a save's +whole rebuild with a one-file update, but that update still did work +proportional to the **workspace** — every file's references re-resolved, the +completion tables re-derived whole, the include graph re-spelled whole — and +VS Code runs it **twice per save**. This round makes a save cost work +proportional to the file that changed plus the files that actually read what +changed, removes the watcher triggers that took a whole rescan for a file the +index could never hold, and pins all of it with differential tests against a +from-scratch build. + +## Assumptions + +- **An index is a function of its records, so an unchanged record moves + nothing.** `WorkspaceIndex::update_facts` now returns whether the index + moved, and answers `false` — touching no table — exactly when the file's new + `FileFacts` equals the held one. That is the watcher's echo of every save + (the second of the two re-indexes VS Code caused per save), a re-save, and + any edit after the file's last token or inside a comment of unchanged length. + The server then owes the index nothing: no merge, no completion tables, no + overlay refresh, no lens refresh, no hierarchy invalidation (those two read + the index alone). **It still republishes every open buffer under a new + generation** (amended in the fix round, QA F2 — see "What a diagnostic reads" + below). Two other things are still done because they are not in the record: + the file's `` `include`` lines are re-scanned (`"a.svh"` and `` read + the same to the record), and the record is written through to the persistent + cache under the new text. +- **Which files a moved key can reach is recorded, not inferred.** Every + lookup the cross-file resolution makes (`units`, `member`, `members_of`, + `hierarchical_member(s_of)`, `reexports`, `base_of`) notes the table and key + it read — misses included — while the index's own resolution pass records + (`workspace/dependents.rs`; off for every request-time caller). The index + keeps *key → files that read it* (the readers table, 13 806 keys / 69 222 + entries on OpenTitan, well under 2 MB). An update re-resolves this file and + the readers of the keys whose values moved, and no one else. This is exact + by construction rather than by a model of the resolution walk: a file that + read no moved key read only unchanged values, and its resolution is a pure + function of those values and its own facts. Inferring readers from the word + census was considered and rejected: a reference two `extends` hops, one + re-export or one hierarchical instance away from the changed file need not + write any of its names (the negative controls below show each of those + hops breaking a narrowing that forgets it). +- **"Moved" is judged the way resolution reads a value.** A posting is keyed by + the declaration's file and name span; resolution also reads a declaration's + kind, its declared type (the next hop) and how many declarations a name has. + It never reads `decl_span`, lines, positions or detail. So a body edit, which + grows a module's extent but not its name, moves the `units` entry for every + consumer that shows extents (overlays, hover, the hierarchy view — all + refreshed) but moves **no posting**, and the 121 files instantiating + `prim_flop` are not re-resolved for it. Member tables are judged a whole unit + at a time, connection and hierarchical surfaces separately: a new local + signal re-resolves only the files whose hierarchical paths read that + module's hierarchical members. +- **The old tables are swapped back for the moment it takes to take the + readers' old postings out.** A posting list carries no record of which + table values produced it; re-resolving the readers against the tables they + were resolved against (the moved entries and the old record, held aside and + swapped in) finds exactly what was put in, so nothing per file is stored to + undo it. +- **Wide on purpose** (sound over-approximations, each re-doing more than + needed rather than less): + - adding or removing a file still merges every table and re-resolves every + file — every `FileId` after it moves; in memory, no file read; + - an edit above a widely referenced declaration moves its name span, and + every file that references it is re-resolved (OpenTitan's + `prim_generic/prim_flop.sv` with a line inserted at the top: 61 ms); + - a re-export entry carries no file, so an update to a file that writes an + `export` re-merges that table from every file; + - the class → base table is rebuilt whole when either record extends a class; + - a `` `define`` change re-merges the macro table entries it names and + re-derives those completion entries; no file is re-parsed for it (lucisv + does not expand macros across files, `docs/features/incremental-index`); + - **the republish stays wholesale** whenever the index moved: every open + buffer is re-linted and republished. Measured at ~0.3 ms a buffer on + OpenTitan (10–20 ms for 50 buffers), it is not the cost the owner saw, and + narrowing it is exactly where a stale squiggle would hide — lints read the + index through the census and `module_interface`, not only through the + overlay. Unchanged records republish too: the index did not move, but + what a lint reads from disk may have (below). +- **What a diagnostic reads, and what invalidates each** (fix round, QA F2). + `Server::diagnostics_of` → `LintRun::for_document` + `diagnostics::all_in`: + 1. the buffer's `Document` (text, parse, semantics, overlay) — `didOpen`, + `didChange` (flushed), a text-carrying `didSave` with new text, and an + overlay refresh whenever the index moves; + 2. the index (the mention census, `module_interface`, the buffer's own + `FileId`) — every update that moves it republishes every buffer; + 3. the client's `lucisv.*` settings — `didChangeConfiguration` / + `workspace/configuration` (`apply_settings`, unchanged by this round); + 4. the `lucisv.toml` governing the buffer — `[lint]` select/ignore, rule + options, `lineLength`, `indent`, the waiver list — read from disk at + every lint. **No notification reports it** (the client watches sources + only), so a save is when an edit to it takes effect, as at 7408fac: every + `didSave` and every watcher event the server acts on republishes every + open buffer under a new generation, whatever the record did; a watcher + event that *names* a `lucisv.toml`/`.lucisv.toml` (a client that forwards + more than it was asked for) is a whole rescan, because the same file moves + excludes and the filelist key; + 5. the waiver files (the config's and `lucisv.lint.waivers`) — read from + disk at every lint, reported by nothing; refreshed by the same + every-save republish; + 6. the workspace roots (editor waivers resolve against them) — + `didChangeWorkspaceFolders`, a whole rescan; + 7. the port-entry grace state — its own timer and release path, untouched. + The cost of the republish is ~0.07 ms a buffer re-sent and ~0.2 ms a buffer + re-linted when the index moved (QA R2-2, full OpenTitan): with 200 buffers + open it is most of a save — 14 ms for a no-op save, 53 ms for a local + signal, against 203–207 ms at 7408fac. The index work it used to ride on is + what the round removed; narrowing the republish is still not done (it is + where a stale squiggle would hide). +- **The completion tables are one block per exact name** (`word_cmp` is a + total order on distinct strings), so an update that changes what a file + declares re-derives only the blocks for the names either record declares, + from `WorkspaceIndex::symbols_named` (`workspace_symbols` for exact names, + same order). An update whose records declare the same names, kinds and + containers in the same order (`FileFacts::declares_the_same`) touches + neither table; the word table is patched per file as before. +- **A watcher event names files, and each is classified before anything is + rescanned** (`state/watched.rs`): held (by its own spelling, or by another + spelling of a scope directory — a symlinked root, a different case on a + case-insensitive disk — resolved through `canonicalize` on the scope's + anchors), provably outside (a filelist that does not list it; a walk of the + scope's directories, `lucisv_core`'s own `collect_files_below` with the + scan's `.gitignore` and excludes, that does not find it or finds it over the + size cap), or unknown (a file the scope may take and the index does not + hold — a creation). An open buffer the index does not hold counts as held: + a rebuild takes every open buffer in, and the one-file path adds it (fix + round, QA F4). Outside costs the index nothing, one held file is the + one-file update, anything unknown or two or more held files is the whole + rebuild, as a checkout always was. +- **But every path a watcher event names re-resolves the `` `include`` lines + that could name it, first, in scope or not** (fix round, QA F1). An include + is resolved against the disk, not the scope, so a header appearing in a + gitignored `gen/`, an unlisted header under a filelist's `+incdir+`, or one + in an excluded directory moves an in-scope includer's edge. The graph now + holds every file's include lines as written (`IncludeGraph::lines`), and + `refresh_naming(path)` re-resolves, against the disk, the lines of every + file that writes a target whose last component is `path`'s name + (case-insensitively; a target with no last component counts as naming + everything) — the only lines whose answer the file's appearance or + disappearance can change. No file is read, no rescan is started. A deleted + *directory* is reported by its own path, which has no source extension and + is dropped by the filter before this (true at 7408fac too; filed below). +- **An open buffer the index does not hold joins it on its first save (or a + watcher event naming it) without a rescan** — a buffer outside the filelist + or under an `exclude`, or one VS Code restored while the startup scan was + taking its work list. What a rebuild would re-read besides the buffer is + every other file's `` `include``s, and the add re-resolves exactly the ones + that could name it (`refresh_naming`). The first cut instead trusted the + file's birth time to prove it was on disk before the scan; QA showed `mv`, + `cp -p`, `ditto`, `rsync -a`, `tar x` and `touch -t` all set it back on macOS + (F3), and Linux often has none. No timestamp is consulted now. A buffer the + index holds under another spelling still takes the rebuild, which would + replace that spelling. +- **A removal re-resolves the include lines that could name the removed file** + (`refresh_naming`, by name rather than by the resolved spelling, so an + includer that wrote another case is covered too). This closes the standing + exception the incremental-index round documented ("another file's + `` `include`` of the removed file keeps its edge until the next whole + rebuild"). +- **The mention census is left as it was.** Measured at 51 µs of an average + lint pass and 2.8 ms at worst on OpenTitan, a keystroke-path cost, not the + save-path cost reported; a merged word → files map is ~10 MB and was rejected + for the same reason by `docs/features/semantic-lints-on`. +- **When the readers hold a large share of every reference, their old postings + are swept out rather than re-resolved** (fix round, QA F5). Re-resolving the + readers once against the old tables and once against the new costs two + resolutions each; for a package most of the tree imports (`prim_mubi_pkg`: + 677 importers) that was slower than 7408fac's single whole pass. When the + readers hold more than an eighth of all references, in an index of at least + 20 000 of them, the sites they contributed are dropped by one pass over the + postings, their ambiguity taken back from a per-file record + (`ambiguous_by_file`), and their ids struck from every reader list — then + they are resolved once. Both ways are held to a whole build by + `replace::tests::both_ways_out_give_the_index_a_whole_build_gives`. +- **The readers table is paid for on every whole merge**, CLI and + `lucisv_mcp` builds included. On OpenTitan it adds ~25–30 ms to the merge + (`absorb` 134–136 → 158–164 ms at startup, 163–165 → 191–195 ms in a cached + rescan, three runs each, back to back), which is +40 to +120 ms of warm + startup depending on machine load: measured +23 ms (first cut, quiet), +40 + ms (fix round), +76 ms and +104 ms (QA, loaded). Every whole rescan, + including a burst's (below), carries the same few per cent. +- **A watcher burst takes the whole rescan past a threshold** (round 3, QA + R2-1). Sorting an event path by path costs ~0.10 ms a path on OpenTitan + (classification; the include-line refresh is one pass for the whole event + since this round), a cached rescan ~0.16 ms an indexed file. An event naming + more than one path per two indexed files (`server/index.rs`'s + `BURST_DIVISOR`) takes the rescan: below it the sorted path costs at most + ~0.3× the rescan it saves, above it the cost is the one rescan 7408fac paid + — plus the readers-table cost above. + +## Handshakes + +### `vlog_semantic` (consumed by `lucisv_server`; `lucisv_mcp`/`vlog_refactor` unaffected) + +- **Changed:** `WorkspaceIndex::update_file(path, src) -> bool` and + `update_facts(facts) -> bool` (were `()`): whether the index moved. Callers + that ignore the value compile unchanged. +- **New:** `WorkspaceIndex::symbols_named(&HashSet<&str>) -> Vec` + — `workspace_symbols` restricted to exact names, same order. +- **New:** `FileFacts::declares_the_same(&FileFacts) -> bool` and + `FileFacts::declared_names() -> (HashSet<&str>, HashSet<&str>)` (workspace + symbols, `` `define``s). +- **Amended:** `WorkspaceIndex::fingerprint()` also renders the readers table + (`read by [ids]` lines), so every existing equivalence test + holds it to a rebuild's too. +- Internal: `merge()` takes no argument (always whole); the restricted path is + `replace.rs`; `ambiguous_references` is a count map (the observable + `references_are_ambiguous` is unchanged). + +### `lucisv_server` + +- **New:** `Workspace::update_one_file(path) -> OneFile { NotHeld, Unchanged, Changed }`; + `update_one(path) -> bool` is now `#[cfg(test)]` over it. +- **New:** `Workspace::watched(path) -> Watched { Held(path), Outside, Unknown }`. +- **Changed:** `watch::one_scope_file` → `watch::scope_files(changes, filelist) + -> Option>` (every scope path an event names; `None` when the + filelist is among them). `watch.rs` was touched for this only. +- **Changed:** `IncludeGraph::update_file` removed; `update_held(path, text)` + (this file's edges, nothing relearned), `add_known(path)` and + `refresh_naming(path)` added (`includers_of`, added in the first cut, is + gone). The graph holds every file's include lines; its test fingerprint + renders them. +- **New:** `Workspace::refresh_includes_naming(path)`; `watch::names_a_config`. +- **Changed:** `WorkspaceIndex::fingerprint` renders each ambiguity's count. +- **Changed:** `Candidates::update_file`/`update_words` are `#[cfg(test)]`; + `set_file_words` and `refresh_names` are the production halves. +- **Changed (protocol):** a `didSave` or watcher event whose record did not + move sends no `workspace/codeLens/refresh` and no + `lucisv/moduleHierarchyChanged`; it still republishes every open buffer + under a new generation (fix round). The `--verbose` line reads + `reindex_one(, unchanged) took ` for it (the old shape still + matches its prefix). A text-carrying `didSave` whose text differs from the + buffer is analyzed and published by the save itself. +- **Changed (protocol):** a watcher event for a file the scope cannot take + starts no rescan and shows no bar; it re-resolves the include lines that + could name the file and republishes every open buffer. +- **Changed (protocol):** a watcher event naming a `lucisv.toml` is a whole + rescan (it was ignored). +- `Server::diagnostics_of` is `pub(super)`, for the differential tests. +- **Taken from the formatter-styles lane (round 3):** `lint.rs`'s `line-length` + width is now `file.line_length.or(client.line_length)`, else the chosen + style's width (`file.format_style.or(client.style)` through + `vlog_formatter::style::preset`), else 100 — the ladder `format::indent_width` + walks and the width `lucisv check` uses. `style = "auto"` names no preset + and takes the configured or default width. Pinned rung by rung in + `lint::tests::line_length_holds_a_buffer_to_the_width_the_formatter_and_check_use` + against `lucisv check`'s own ladder (`Config::named`, then the explicit + width). The request in `docs/features/format-styles/README.md` is answered + here; that README is the other lane's and was not edited. +- `watch::names_a_config` reads `lucisv_core::config::NAMES` (made public by + the formatter-styles lane) rather than a copy. + +### The fast-path trigger table, amended (`docs/features/incremental-index`) + +| trigger | before | now | +|---|---|---| +| `didSave` / watcher `Changed`, held file, record unchanged | one-file, O(index) | include re-scan + republish, no index work | +| `didSave` / watcher `Changed`, held file, record changed | one-file, O(index) | one-file, O(file + readers of moved keys) | +| watcher event for a held file under another spelling | whole rebuild | one-file | +| watcher event for a file the scope cannot take | whole rebuild | include lines naming it re-resolved + republish | +| `didSave` / watcher event for an open buffer the index does not hold | whole rebuild | one-file add (whole merge in memory) + include lines naming it | +| watcher event naming a `lucisv.toml` | nothing | whole rebuild | +| watcher `Created` for a file the scope takes | whole rebuild | whole rebuild | +| watcher event naming two or more held files | whole rebuild | whole rebuild | +| the filelist, settings, folders, renames, deletes via `didDeleteFiles` | whole rebuild | whole rebuild | + +No request to another lane; `editors/vscode/extension.js` was not touched (the +watcher configuration was not the problem — the server's answer to it was). + +### A note for the next lane: an open buffer can lose its latest edit during a whole rescan (QA F6, pre-existing) + +Not fixed here, and present at 7408fac. What is known: + +- **Symptom.** After a sequence that includes whole rescans (creations, + deletions), an open buffer's *own* answers — document symbols, semantic + tokens, its diagnostics — describe the text before its last `didChange`, + while the client's text, the disk and a fresh server agree. Re-sending and + re-saving the buffer repairs every answer, so the index is right and the + `Document` is what is stale. That fits the owner's "Find References says + not found, then works after clicking away and back": coming back sends a + change or a request that flushes or rebuilds the buffer. +- **Reproductions** (QA, deterministic): `QA_PULL=0 rand_run.py + ~/.cache/lucisv-corpus corpuspush 7 200 25` (7408fac fails on the same seed + at step 100), and `rand_run.py ~/.cache/lucisv-opentitan-full/hw otfull + 21 50 50` (both binaries). A 10-iteration isolated race (`oracle/race.py`) + did not reproduce it, so it needs the interleaving of a longer run. +- **Where the losing `didChange` lands:** while a whole rescan is in flight, + i.e. inside `Server::scan_until_settled`, whose interleaved drain answers + messages between two files. Places worth reading first, none proven: + 1. `server/notification.rs`'s `didChange` arm takes its base text from + `self.dirty`, else from the workspace's `Document`; a change applied on + the wrong base (an entry taken by a flush between two drained batches, or + a `Document` replaced mid-drain) would silently drop the previous edit; + 2. `server/batch.rs`'s coalescing of a burst, across a drain the scan cuts; + 3. the 150 ms quiet-timer flush (`server/mod.rs`) runs only in the main + loop, so a buffer dirtied during a scan stays dirty until the next + message — harmless if every path then flushes, wrong if any answers or + publishes from the analyzed `Document` without flushing (requests held by + `must_wait`, the scan's own `publish_scan`). +- The oracle's `QA_REPAIR` mode (re-send and re-save before each check) hides + it, which tells it apart from an index bug quickly. + +### Three more pre-existing items for the next lane (QA round 2, P1–P3; 7408fac the same) + +- **P1 — a watcher event that names only a directory loses what is inside + it.** A header directory created: its includer's edge is missing + (`oracle/r2attack.py dir-create`); a directory of held files deleted: the + index keeps them (`held-dir-delete`, 9 answers differ). The path has no + source extension, so `watch::touches_scope` drops it before anything runs. + Whether VS Code's watcher reports a `git checkout` that removes a directory + per file or by the directory alone is unobserved (git unlinks per file, so + per file is likely). A fix would treat a directory path as "every held file + and include line under it". +- **P2 — an excluded or out-of-filelist buffer, once taken into the index, + stays after `didClose`.** A fresh server without it open does not hold it + (`excluded-open-close`, 20 answers differ after the close). This round + takes such a buffer in on any event naming it (F4), so the state is reached + more often; the close path is 7408fac's (`close_document` does not touch the + index). A fix is a removal on close when the scope would not take the file + (`Workspace::watched` already answers that question). +- **P3 — symlinked files.** OpenTitan's `top_englishbreakfast/rtl/*.sv` are + symlinks into `top_earlgrey/rtl/`. Whether a rebuild holds one spelling or + both depends on whether the target is an open buffer at scan time + (`discover.rs`'s `Aliased`), so the incremental answer and a rebuild's + disagree in all six of `oracle/filelink.py`'s variants, on both builds. The + rule to pick is "one file, one spelling, whatever is open", applied by the + walk, the overlay and the one-file path alike. + +## Status / TODO + +- [x] Step 1 — reproduce over LSP on the full OpenTitan tree, measure, record +- [x] Unchanged facts short-circuit the index work (the save's watcher echo is + free of index work) +- [x] Readers table; references re-resolved only for the readers of keys whose + value moved, as resolution reads it +- [x] Table merge restricted to the files contributing to an affected key +- [x] Completion index tables re-derived only for the names either record declares +- [x] Include graph: one file's edges re-scanned +- [x] Watcher events classified: outside → no rescan; another spelling → one-file +- [x] An open, unheld buffer joins the index on its first save / watcher event +- [x] Differential tests: hand-written cases, seeded sweeps (corpus, OpenTitan + sample), negative controls +- [x] Before/after numbers +- [x] Fix round (QA F1–F5): include lines re-resolved for every watched path + and on a removal or an add; every save and acted-on watcher event + republishes; the birth-time guard replaced; open unheld buffers taken in + on a watcher event; a sweep way out when the readers hold most + references; F1–F4 as differential tests and sweep event kinds +- [ ] **Not done, deliberately:** the republish of open buffers stays wholesale + (see Assumptions). +- [ ] **Not done, deliberately:** the mention census keeps its linear walk. +- [ ] **Filed, not done:** postings are keyed by name span, so an edit above a + widely used declaration re-resolves every user of it. Stable declaration + ids would end that and are a bigger change than this round. +- [ ] **Filed, not done:** the word table's patch is a merge over the sorted + table plus a whole re-mask (~2 ms on OpenTitan when a file gains or loses + a word nobody else has). +- [ ] **Filed, not done:** every whole merge pays for recording the readers + table (re-measured in the fix round's log), CLI and `lucisv_mcp` builds + included. +- [ ] **Filed, not done:** a watcher event for a deleted *directory* names a + path with no source extension and is dropped before anything runs, so + includes of files that were under it keep their edges until a rebuild + (7408fac the same). +- [ ] **Filed, not done (F6, pre-existing):** an open buffer can lose its + latest `didChange` during a whole rescan — see the note under Handshakes. +- [ ] **Filed, not done (P1–P3, pre-existing):** directory-only watcher + events; an excluded buffer stays indexed after close; symlinked files' + spellings — see Handshakes. +- [x] Round 3 (QA R2-1): the include-line refresh is one pass per event; a + burst past `BURST_DIVISOR` takes the whole rescan. +- [x] Round 3 (formatter-styles Handshake): `line-length`'s width falls back to + the chosen style's width. +- [ ] **Known cost (QA R2-2):** with 200 buffers open the republish is most of + a save (53 ms for a local signal; 4× faster than 7408fac). +- [ ] **Known cost (QA R2-3):** warm startup +40 to +120 ms on OpenTitan, + load-dependent (the readers table). + +## Work log + +### 2026-11-19 — dev agent: Step 1, what the owner is actually seeing + +Measured with the real `lucisv-server` (release build of 7408fac, `--verbose`) +driven over stdio by a small LSP client that speaks what VS Code's client +speaks around an edit: `didChange`, `didSave`, and the +`workspace/didChangeWatchedFiles` the client's watcher forwards for the saved +file — the server registers `**/*.{v,vh,sv,svh}` (`watch.rs`) and VS Code's +file watcher reports the editor's own saves, so **one save is two +notifications that both re-index the file**. The client advertises +`hierarchyView`, code-lens refresh and dynamic watcher registration, as the +extension does. Tree: `~/.cache/lucisv-opentitan-full/hw` (4 058 indexed +files, 471 596 reference sites, 94 442 connection members), warm persistent +cache. Apple M5 Max, shared with another lane's builds; medians of 3 runs +(LSP) or 5 (in-process), re-run twice. + +**(a) Which path each trigger takes** (scope `workspace` unless stated; "bar" is +`$/progress` messages): + +| trigger | path | wall | bar | publishes | +|---|---|---:|---:|---:| +| keystroke (`didChange` + flush) | buffer only | 3.4 ms | 0 | 1 | +| `didSave`, leaf module `uart_tx.sv` | one-file | 166 ms | 0 | every open buffer | +| …the watcher's `Changed` for the same file | one-file **again** | 163 ms | 0 | every open buffer | +| `didSave`, `prim_generic/prim_flop.sv` (125 instantiating files) | one-file | 174 ms | 0 | all | +| `didSave`, `uart_reg_pkg.sv` (package) | one-file | 170 ms | 0 | all | +| `didSave`, `prim_assert.sv` (`` `define`` header) | one-file | 163 ms | 0 | all | +| `didSave`, `prim_assert_standard_macros.svh` (include file) | one-file | 158 ms | 0 | all | +| same five, default folder scope (1 778 files) | one-file | 65–82 ms ×2 | 0 | all | +| watcher `Changed` for a source file the index does not hold (outside the folder scope, not in the filelist, a generated file) | **WHOLE rescan** | 271–745 ms | 576–892 | all | +| watcher `Changed` naming a held file by another spelling (symlinked root, or different case on macOS) | **WHOLE rescan** | 714–736 ms | 815 | all | +| watcher `Created` for a new file in scope | WHOLE rescan (by design) | 711 ms | 815 | all | +| watcher `Deleted` for a held file | one-file | 159 ms | 0 | all | +| watcher `Changed` for the `.f` filelist | WHOLE rescan (by design) | 353 ms | 576 | all | +| watcher `Changed` for `lucisv.toml` / an unconfigured `.f` | nothing | 4 ms | 0 | 0 | +| `didSave` of an excluded file that is open | one-file | 85 ms | 0 | all | +| first `didSave` of a file opened *after* the startup scan from outside the filelist/scope | WHOLE rescan | ~620 ms | 577 | all | + +After every one-file update the server also sends +`workspace/codeLens/refresh` and `lucisv/moduleHierarchyChanged`; the +extension answers the latter with a `lucisv/moduleHierarchy` request — +**27.7 ms and a 2.7 MB answer on OpenTitan**, rebuilt client-side, twice per +save. + +**(b) Where a one-file update's ~165 ms goes** (temporary `Instant` probes in +`update_one`/`merge`/`reindex_one`, 20 updates over the five files, 10 buffers +open; probes removed afterwards): + +| stage | mean | +|---|---:| +| `merge_references` — re-resolving **every** external reference in **every** file | **116.8 ms** | +| `Candidates::take_index_tables` — the unit/macro completion tables re-derived whole | **30.9 ms** | +| `merge` loop over every file's records, restricted to the affected keys | 9.6 ms | +| `IncludeGraph::update_file` — relearn + re-spell every file | 1.1 ms | +| republish of 10 open buffers (lint + send) | 1.4 ms | +| `bases` rebuilt whole | 0.7 ms | +| the buffer's facts, overlays of 10 buffers, cache write-through | 0.3 ms | + +With 1 and 50 buffers open the update is 169–173 ms and 165–185 ms: the +republish is ~0.3 ms a buffer and is **not** the cost. The in-process probe +(`state::tests::reindex_perf`, release) agrees: 138–144 ms for every file and +every edit kind, **including an edit that changes nothing at all** (the +watcher's echo of a save) — the cost does not depend on what changed. + +**(c) The mention census per keystroke**: `mentioned_outside` costs 156 µs a +question at this scale (a linear walk of 4 058 sorted word lists). What the +rules really ask, measured as one buffer's lint pass with the workspace minus +the same pass with none: **51 µs on average over all 4 058 files, 2.8 ms worst** +(`alert_handler_reg_top.sv`, of a 4.9 ms pass). Real but small, and on the +keystroke path rather than the save path the owner reported. + +**What the owner is seeing**, in order of how often it happens: + +1. **Every save costs the same ~330 ms of blocking work on OpenTitan whatever + was edited** — two whole-index passes (save + watcher echo), each + re-resolving 470 k references and rebuilding the completion tables, then a + 2.7 MB hierarchy snapshot twice. Nothing shows a bar, but in `--verbose` the + output channel says `reindex_one(...) took 168 ms` twice per save, and every + request behind it waits. This *is* "the whole database re-indexed", just + without the re-read. +2. **Real whole rescans with the progress bar** for triggers that need none: a + watcher event for a `.sv` the scope cannot take (a generated file, a file + outside the folder scope or the filelist) or for a held file under another + spelling; and the first save of a buffer opened from outside the filelist. + +Design consequences: attack `merge_references` and the completion tables +first; make the watcher's echo of a save free; filter watcher events against +the scope. The republish of open buffers is ~0.3 ms each and stays wholesale +when anything changed (narrowing it is where a stale squiggle would hide, for +no measurable gain); the census does not justify a 10 MB inverted word index +(`docs/features/semantic-lints-on` rejected one for the same reason) and is +left as measured. + +### 2026-11-19 — dev agent: the design, and what it measures + +Attacked in the order Step 1 ranked the costs. + +1. **The unchanged record** (`update_facts` → `false`). Kills the watcher's + echo of every save and every re-save outright: ~165 ms → 0.1–0.4 ms at + OpenTitan scale, nothing sent. +2. **`merge_references` → readers table** (`dependents.rs`, `references.rs`, + `replace.rs`). The thread-local recorder follows the precedent of + `lint_trace`/`scan_trace`; the alternative — a recorder parameter through + `external.rs`/`reexport.rs`/`hierarchy.rs` — would have changed a dozen + signatures shared with every request handler for one caller. First cut + judged "moved" by key alone (any key either record names) and re-resolved + 121 files (64 ms) for a local signal in `prim_flop.sv`; judging the value + as resolution reads it (`replace.rs::seen`) and splitting the connection + and hierarchical member keys took that to 2.5 ms. +3. **The completion tables** (`Candidates::refresh_names`). First cut skipped + the 31 ms re-derivation when `declares_the_same` held; a package member + added still paid it, so the blocks for the touched names are now re-derived + alone (uart_reg_pkg member added: 36 → 9 ms). +4. **The restricted merge visits only the contributing files** (read off the + tables' own entries) — same loop, fewer files; 9.6 ms → ~0. +5. **The include graph** re-spells one file (`update_held`). +6. **Watcher classification** (`state/watched.rs`) and the **open-buffer add** + (`add_open_buffer`), both found by Step 1's trigger table. + +Deviations from the brief, each argued in Assumptions: the inverted word index +was not built (the census measured small; the readers table is the reverse map +this needs, keyed by what resolution reads rather than by words, which is the +only shape that is sound across `extends`, re-export and instance hops); the +republish was not narrowed (measured not to be the cost). Four existing tests +pinned "a save that changes nothing still refreshes/republishes" and were +amended to save a real edit, each with an added assertion that the no-op save +now sends nothing: `requests.rs` +`a_rescan_asks_a_capable_client_to_refresh_its_code_lenses` and +`qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh`, +`pull_diagnostics.rs` `an_index_rebuild_moves_the_result_id_too`, `e2e.rs` +`a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire`. + +**Before / after** — same LSP driver, same OpenTitan tree, scope `workspace`, +10 buffers open, release builds of 7408fac and this tree, medians of 3, the +`--verbose` `reindex_one` line (wall time to the next answered request in +brackets). "watched" is the watcher's `Changed` for the same file right after +the save. + +| file / edit | save before | save after | watched before | watched after | +|---|---:|---:|---:|---:| +| `uart_tx.sv` comment at end | 141 ms | 0.14 ms (nothing sent) | 153 ms | 0.10 ms | +| `uart_tx.sv` local signal | 144 ms | 5.2 ms | 158 ms | 0.10 ms | +| `uart_tx.sv` comment at top | 143 ms | 2.1 ms | 171 ms | 0.09 ms | +| `prim_flop.sv` (125 instantiating files) local signal | 145 ms | 5.2 ms | 174 ms | 0.07 ms | +| `prim_flop.sv` comment at top (every user's posting moves) | 144 ms | 61 ms | 167 ms | 0.19 ms | +| `uart_reg_pkg.sv` package member added | 148 ms | 11.7 ms | 152 ms | 0.30 ms | +| `uart_reg_pkg.sv` comment at top | 144 ms | 7.6 ms | 157 ms | 1.1 ms | +| `prim_assert.sv` (`` `define`` header) local edit | 145 ms | 4.7 ms | 169 ms | 0.18 ms | +| `prim_assert_standard_macros.svh` local edit | 148 ms | 4.9 ms | 170 ms | 0.69 ms | +| watcher `Changed` for a `.sv` the scope cannot take | 746 ms, bar | 3.5 ms, nothing | | | +| watcher `Changed`, held file by its real path under a symlinked root | 736 ms, bar | 3.6 ms, one-file | | | +| watcher `Changed`, held file in another case (macOS) | 714 ms, bar | 3.3 ms, one-file | | | +| first save of an unlisted buffer restored during the startup scan (filelist) | 394 ms, bar | one-file add | | | +| watcher `Created`, file in scope | 711 ms, bar | 742 ms, bar (by design) | | | + +With 50 buffers open the changed rows add the republish (~0.3 ms a buffer: +16–35 ms); the unchanged rows are unchanged. Default folder scope (1 778 +files): 65–82 ms before, 0.1–12 ms after. In-process +(`state::tests::reindex_perf`, release): 138–144 ms for every edit kind before; +after, 6–240 µs unchanged, 2.5–3.7 ms for a local signal, 0.2–3 ms for a +comment at the top except `prim_flop.sv` (61 ms), 9 ms for a package member +added. Cost of the readers table: see Assumptions (+23 ms per whole merge). + +**Differential tests** (all green): + +- `vlog_semantic/tests/localized_reindex.rs`: 11 hand-written sequences, one + per resolution hop (port connection, import + re-export, three-level + `extends`, struct member chain, a member whose type alone changes, a unit + whose kind alone changes, a hierarchical path through two instances, misses + that become hits and ambiguities, duplicate modules, defines and a broken + file, the unchanged record), each step checked against a whole build by + fingerprint — postings and readers included; plus a seeded sweep, 8 seeds × + 40 mutations over the five designs (320 checks, 0 divergences). +- `vlog_semantic` `workspace::replace::tests`: four tests pinning the + narrowing itself (which files a body edit, a port rename, a moved internal + signal and an edit above everything re-resolve). +- `lucisv_server` `server::tests::localized_reindex`: drives the real server + with an editor's notifications (change, disk write, save, watcher echo; or a + watcher event alone for closed files, creations, deletions) and after every + step holds the index, completion tables, include graph, every open buffer's + overlay **and the diagnostics last published for every open buffer** to an + in-place whole rebuild. Eight hand-written cases (module edits incl. ports, + hierarchical names and renames; a closed package, a define header, include + lines; the census lint with a closed mentioning file; files created and + deleted beside open buffers; watcher events outside the scope; a symlinked + root; a buffer outside the filelist, older and younger than the scan) and + three seeded sweeps: the design (3 seeds × 25 steps, in the normal suite), + `~/.cache/lucisv-corpus` (860 files, seeds 11–13 × 60 steps, `#[ignore]`, + 35 s in release) and an OpenTitan sample (269 files of `ip/{uart,gpio}`, + `prim`, `prim_generic`, `tlul`, seeds 21–22 × 60 steps, `#[ignore]`); each + step one of: a line inserted, deleted, duplicated or swapped, a local signal + added, an identifier renamed to another the file uses, a closed file deleted + (1 in 20), a file created (1 in 20). 0 divergences; 1–5 whole rescans per + sweep, all of them creations. +- **Negative controls**, each a one-line sabotage of the implementation, run + and reverted: readers ignored (21 tests fail), `base_of` / re-exports / + hierarchical members / units / connection members not recorded (3/4/4/5/8), + `seen` ignoring a declaration's type or kind (3/3, after the two + type-alone and kind-alone cases were added for exactly this), contributors = + the file alone (5), the base table not rebuilt (4); server side: no + republish when the index moved (3), include line not re-scanned (3), + completion names not refreshed (5), a removed file's includers kept (1), + unknown files treated as outside (5), overlays not refreshed (4), words not + patched (7), aliases not resolved (1), the open-buffer add without its age + guard (1, on the `include` edge it exists for). + +The first run of the server-level test found a real divergence older than this +round: a removed header's includers kept their edge (incremental-index's +documented limit). Fixed (`remove_one`). + +**Checks run** (2026-11-19, this tree): `cargo fmt --all -- --check`; +`cargo clippy --all-targets -- -D warnings`; through `tools/guard.sh`: +`cargo test -p vlog_semantic` (434 passed), `-p lucisv_server` (1 985 passed, +47 ignored), `-p lucisv_mcp` (383), `-p vlog_linter` (673); the two `#[ignore]`d +sweeps in release; `tools/gates.sh` — every step passed except `fmt`, on a +probe file appended after the last format, re-run green with +`--only fmt,clippy,build,suite:lucisv_server,suite:vlog_semantic`. + +**Not verified here:** no real VS Code was driven. That its watcher forwards a +`Changed` for the editor's own save (the second re-index per save) is +VS Code's documented watcher behaviour, replayed by the driver, not observed; +and that VS Code maps events under a symlinked or differently-cased workspace +back to the folder's spelling is likewise not observed — the server now +answers either spelling. The LSP driver and the scenario scripts are scratch +(`step1*.py`, `lsp.py`), not checked in. + +### 2026-11-19 — dev agent: fix round for QA's FAIL (F1–F5) + +The principle QA restored: a shortcut may skip work only when everything that +work would have produced is provably unchanged. "Outside the scope" and +"record unchanged" proved it for the index, not for the include graph (resolved +against the disk) or the diagnostics (which read `lucisv.toml` and waiver files +from the disk). What changed: + +- **F1** — `IncludeGraph` keeps every file's include lines; every path a + watcher event names (any extension, any scope) first re-resolves the lines + whose target's last component could be that name (`refresh_naming`), and so + do the open-buffer add and a removal. No rescan, no file read. +- **F2** — every `didSave` and every watcher event the server acts on + republishes every open buffer under a new generation, whatever the record + did; lens refresh and hierarchy invalidation stay gated on the index moving + (they read nothing else). Every input of `diagnostics_of` and what + invalidates it is now listed in Assumptions. A watcher event naming a + `lucisv.toml` is a whole rescan. +- **F3** — the birth-time guard is gone; the add re-resolves the include lines + that could name the file instead, which needs no witness of when it appeared. +- **F4** — an open buffer the index does not hold is `Watched::Held`; the + one-file path adds it. +- **F5** — when the readers hold more than 1/8 of all references (index of at + least 20 000), their old postings are swept out in one pass instead of + re-resolved; per-file ambiguity is recorded for that. The fingerprint now + renders ambiguity counts, so a drifted count shows. +- **Coverage restored:** `requests.rs::a_client_that_cannot_refresh_code_lenses_is_never_asked_to` + saves a real edit again and asserts the index moved. **Five** existing tests + were amended in the first round, not four (that one was missed in the list); + `pull_diagnostics.rs::an_index_rebuild_moves_the_result_id_too` now expects + `full` after the no-op save again, as at 7408fac. vlog_linter is 672 tests as + the gate counts them (673 summed with doc-tests). +- **The README had lost its Status / TODO section** (a replace in the first + round swallowed it); restored. + +**New differential tests** (`server::tests::localized_reindex`), each verified +to fail with its fix reverted: an ignored-dir header created/deleted/recreated +(F1), an unlisted `+incdir+` header created/deleted in filelist mode (F1), a +`[lint]` edit followed by a no-op save, there and back (F2), a file moved in +from elsewhere then opened and saved with no watcher echo (F3), an excluded +open buffer changed on disk (F4); `replace::tests::both_ways_out_…` runs a +chained design through both ways out (sweep sabotage of sites, readers or +ambiguity each caught). The seeded sweeps gained the event kinds QA found: an +out-of-scope header (gitignored `gen/`, waited for by an in-scope file) +toggled, a `lucisv.toml` lint edit plus a no-op save, a file moved in and +opened and saved, an excluded file created, opened and changed on disk. + +**QA's oracle against the fixed binary** (logs `scratchpad/dev711/or-*.log`): +`outside.py`, push and pull: 14/14 cases, 0 diverged (were 4 diverged). +`small.py`, push and pull, workspace and folder scope: every scenario 0 +divergent steps except `NEGCTL-silent` (the negative control, diverging as it +must) in all four runs. `rand_run.py`, 300 steps, check every 25: corpus seeds +1, 2 (pull, workspace) and 3 (push, folder) and OpenTitan sample seeds 11, 12 +(pull) — 12 checks each, 0 divergent, 7 849–9 545 answers compared per check. + +**Timings** — QA's `perf.py`, full OpenTitan, workspace scope, push, 10 buffers, +medians of 5, 7408fac and this tree back to back (`reindex_one` line, which now +includes the republish): + +| edit | 7408fac | first cut (QA) | now | +|---|---:|---:|---:| +| uart_tx comment at end | 162 | 0.13 | 0.05 | +| uart_tx local signal | 170 | 15.1 | 4.4 | +| prim_flop local signal | 167 | 15.7 | 4.2 | +| prim_flop line at top | 163 | 88.8 | 47.1 | +| uart_reg_pkg member added | 167 | 27.1 | 11.5 | +| prim_assert local edit | 159 | 11.0 | 1.5 | +| prim_mubi_pkg member added (677 importers) | 162 | **178** | 92.1 | +| prim_mubi_pkg line at top | 163 | **171** | 84.6 | +| tlul_pkg line at top | 161 | 142 | 67.6 | +| new class `uvm_object` | 164 | 19.4 | 4.2 | +| new `` `define`` in a macros header | 160 | 20.2 | 6.4 | +| clk_rst_if line at top | 157 | 34.7 | 15.9 | + +The watcher echo is 0.03–0.27 ms for every row. **Startup**, warm (cache): +1 113 / 1 124 ms → 1 171 / 1 148 ms, about +40 ms (+4 %); QA measured +76 ms +on a busier machine, the first cut's README said +23 — the honest range is ++25 to +75 ms depending on load. Cold: 2 729 → 2 194 ms (one run, noise). + +**Checks:** fmt clean; clippy `--all-targets -D warnings` clean; guarded +`vlog_semantic` 435, `lucisv_server` 1 990 (48 ignored), `lucisv_mcp` 383, +`vlog_linter` 672 (gate count); both `#[ignore]`d sweeps in release (corpus 3 +seeds, OpenTitan sample 2 seeds, 0 divergences); **full `tools/gates.sh`: +PASS**, every step (corpus 814/6, the same six known failures). + +**Not verified:** no real VS Code; Linux not run (no birth time is consulted +any more, so that question is gone). F6 untouched (see Handshakes). + +### 2026-11-19 — dev agent: round 3 (QA R2-1, the formatter-styles Handshake, docs) + +On the lead's rebase onto 0.65.5 (the three `auto_styles` calls in +`server/notification.rs` kept as they are). + +- **R2-1 — watcher bursts.** Two changes, both boring: + 1. the include-line refresh takes the event's whole path list and makes one + pass over the held lines for the set of names + (`IncludeGraph::refresh_naming_all`); re-resolving a file once per + matching name or once for all of them gives the same answer, so it is + equivalent to the per-path loop it replaces; + 2. an event naming more than one path per `BURST_DIVISOR` (= 2) indexed files + takes the whole rescan, before any per-path work (the rescan re-resolves + every include line itself). The constant's comment carries the + measurement that chose it. + + One notification of N files created under a gitignored directory of the + OpenTitan copy (4 029 files indexed, so the threshold is 2 014 paths), + `scratchpad/dev711/burst.py`, medians of 3, back to back: + + | paths in one event | 7408fac | round 2 | now | + |---:|---:|---:|---:| + | 1 000 | 0.68 s | 0.22 s | 0.11 s | + | 3 000 | 0.64 s | 0.65 s | 0.68 s (rescan) | + | 5 000 | 0.65 s | 1.07 s | 0.68 s (rescan) | + | 10 000 | 0.67 s | (QA: 2.5 s) | 0.70 s (rescan) | + + QA's `genburst.py` on the same tree, this build: one event 0.10 / 0.69 / + 0.70 / 0.71 s for 1 000 / 3 000 / 5 000 / 10 000; the same files as that + many one-path events 0.28 / 0.83 / 1.37 / 2.76 s in all (7408fac rescans + once per event there, 0.65 s each). **Past the threshold the event costs one + rescan, which is 20–40 ms (3–6 %) more than 7408fac's** — the readers-table + cost every whole merge carries (Assumptions), not anything the burst adds. + Below it, never more than ~0.3× the rescan it replaces. + `a_burst_of_created_files_is_sorted_below_the_threshold_and_rescanned_above` + pins both sides (no rescan at `held / 2` paths, one rescan at one more, the + state a rebuild's after each). +- **The formatter-styles Handshake** — `line-length`'s width falls back to the + chosen style's width (Handshakes). `lint::tests::line_length_holds_a_buffer_…` + checks five rungs (explicit width over a style; project style `ansi` 80; + editor style `microsoft` 120; default 100; `auto` 100), each at the width and + one column past it, against `lucisv check`'s ladder; with the fix reverted + it fails at "project style". +- **Docs:** QA's R2-2 (republish at 200 buffers) and R2-3 (startup range) + under Assumptions and Status; P1–P3 beside F6 under Handshakes; the + changelog paragraph rewritten to the final behaviour and numbers. + +## Changelog paragraph (for the lead) + +**Saving a file no longer re-indexes the workspace.** A save used to cost +~160 ms of whole-index work on OpenTitan whatever was edited — and VS Code +triggered it twice, once for the save and once for its own file watcher. Now +the index does only what the edit can reach: the watcher's echo and a save that +changes nothing the index records cost well under a millisecond; a typical edit +inside a module costs a few milliseconds (4 ms for a local signal in +`uart_tx` or `prim_flop`, 12 ms for a package member added); edits that really +reach far still pay for what they reach (a line above a module 125 files +instantiate, 47 ms; a member added to a package 677 files import, 92 ms). Every +save still re-checks every open file's diagnostics, so a `lucisv.toml` or +waiver edit takes effect at the next save as before — with hundreds of files +open that is most of what a save costs (53 ms at 200 buffers, against ~205 ms +before). Watcher events for files the index cannot hold — generated files in a +gitignored directory, files outside the filelist or folder scope — no longer +start a whole rescan with a progress bar, though they still update the include +lines that may name them; nor do held files reported through a symlinked root +or in another case; a file opened from outside the filelist joins the index on +its first save; and a burst of thousands of files in one event still takes the +single rescan it always did. The `line-length` lint now uses the chosen +formatting style's width. Still wide: adding or deleting a file (an in-memory +merge, no re-read), an edit above a declaration many files use, and every whole +rescan, which costs a few per cent more than before (warm OpenTitan startup ++40 to +120 ms, load-dependent) for the table that makes the rest cheap. + +## QA log + +### 2026-11-19 — QA agent (Opus 5.5): FAIL — the index core holds, the watcher and "unchanged sends nothing" rules leave stale answers + +**Verdict: FAIL.** Four reproducible stale answers, each a regression against +7408fac, where a from-scratch server on the same files answers differently +(F1–F4). Nothing my oracle could find is wrong in the vlog_semantic narrowing: +postings, ambiguity, readers, completion tables, overlays, hierarchy and lens +counts all matched a fresh server across every hand case and every random +sequence. The failures are server-side. Two rules — "a watcher event for a file +the scope cannot take does nothing" and "an unchanged record sends nothing" — +drop work whose result is not covered by the index record: the include graph +(resolved against the **disk**, whatever the scope) and the lint configuration +(read from the disk at lint time). Scratch for everything below: +`/private/tmp/claude-501/-Users-lucio-repo-lucisv/d043c274-11ff-4de2-ab0f-45daa8a877f0/scratchpad/qa711/` +(`oracle/` holds the scripts, `*.log` the runs). + +**Baseline checks (final tree).** + +- `cargo fmt --all -- --check`: clean. `tools/gates.sh`, run whole, not inside + `guard.sh`: **PASS**, every step: fmt, clippy, build, vlog_parser 521/0, + vlog_semantic 434/0, vlog_refactor 743/0, vlog_formatter 352/0, vlog_linter + 672/0, lucisv_core 117/0, lucisv 143/0, lucisv_server 1 985/0 (47 ignored), + lucisv_mcp 383/0, docs 1/0, corpus 814/6 (gate exit 0; the same 6 known + failures as at 7408fac), node 37/0. No step killed. +- Test counts against 7408fac's gates log: vlog_semantic 418 → 434 (+4 + `replace::tests`, +12 `tests/localized_reindex.rs`), lucisv_server 1 977 → + 1 985 (+8 run, +6 ignored). Every other crate is unchanged, and the diff + removes no `#[test]`. (The dev reported vlog_linter as 673; the gate counts + 672 at both commits.) +- The two `#[ignore]`d sweeps, release, through `guard.sh`: both pass, 39.5 s. + The readers probe reproduces the dev's figures: 13 806 keys (376 KiB of key + text), 69 222 reader entries. +- **The amended tests.** No assertion was weakened beyond the stated protocol + change, and each amended test gained a "the no-op save sends nothing" + check. One count is off: **five** tests changed, not four. + `requests.rs::a_client_that_cannot_refresh_code_lenses_is_never_asked_to` + gained a `tree.write("top.sv", …)` so that its watcher event really changes + something. Its `didSave` now moves nothing, so for a client that cannot + refresh, "silence on the save path" no longer exercises a moved index (LOW, + coverage). + +**The oracle** (mine; I read the dev's harness only to find entry points). A +Python LSP client drives the release `lucisv-server` over stdio, through +`tools/guard.sh`. Edits are sent the way VS Code sends them: `didChange`, disk +write, `didSave`, then the watcher `Changed`. A disk-only edit sends just the +watcher event, after a `didChange` reload when the file is open and clean. A +checkout sends one watcher event for several files. There are creates, +deletes, and renames as delete+create in both orders, in one event or two. +After each step a **fresh** server is started with an empty storage dir on the +resulting files and the same buffers, and every answer is compared verbatim +(only `resultId`, `revision` and `version` are dropped): + +- per buffer: documentSymbol, codeLens, documentLink, semanticTokens/full, + inlayHint, pull diagnostics, the last pushed diagnostics; +- per identifier: definition, typeDefinition, references, hover, + documentHighlight, completion, prepareCall/TypeHierarchy plus + incoming/outgoing and super/subtypes; +- workspace/symbol, `lucisv/moduleHierarchy`, and `willRenameFiles` for + chosen headers (the include graph's observable). + +Push and pull diagnostic modes were both run. Negative control: a disk edit +with no notification diverges on 14 answers as expected (`NEGCTL-silent`). + +| edit kind | small trees (ws + folder scope, push + pull) | corpus / OpenTitan | +|---|---|---| +| comment, whitespace, same-length comment, newline-in-comment at the same byte length, UTF-16-only column shift, CRLF, tab↔space | pass | pass (random) | +| local signal; add/remove/rename a port; rename a module and back; param default/type | pass | pass (random) | +| package member add/remove/rename, typedef, enum member, struct field | pass | pass (random) | +| `import p::*` ↔ explicit import; `export`; 3-level `extends` (base member add/remove, extends retarget, base rename) | pass | — | +| interface/modport rename, interface signal rename | pass | — | +| `` `define `` add/remove/params change; redefine in a second header; include order swap; `` `include `` add/remove; `"x"`→`` | pass | pass (random include toggles) | +| miss→hit / hit→miss (create, edit, delete); ambiguity appears/disappears | pass | pass (random) | +| two files alternately; A, B-depends-on-A, undo A; no-op save right after a change | pass | pass (random) | +| create, delete, rename (both orders, one or two events), delete+recreate, header delete+recreate | pass | pass (random) | +| unparseable and recovery; whole-file replacement (200 modules) | pass | — | +| disk-only edits of closed files; 2–3 files in one watcher event | pass | pass (random) | +| edits during the startup scan | pass | pass: OT sample + full OT ×2 seeds, 52–56 ops in the first 1.5 s | +| symlinked root (either side), symlinked subdir, other case (macOS) | pass: one-file path taken, file held once | — | +| buffer outside the filelist saved the first time, older/younger than the scan | pass | — | +| `.f` edit, `didChangeConfiguration` exclude | pass | — | +| **out-of-scope header created** (gitignored dir; unlisted in filelist mode) | **FAIL (F1)** | — | +| **file with an old birth time moved in after the scan** | **FAIL (F3)** | — | +| **`lucisv.toml` `[lint]` change, then a save that moves nothing** | **FAIL (F2)** in push and pull | — | +| **excluded buffer changed on disk** | **FAIL (F4)** | — | + +The same F1–F4 scripts pass against a 7408fac build (`outside-base.log`). + +**Random runs** (`oracle/rand_run.py`). Each step is one of: a mutation saved +through the editor or written to disk (insert, delete, duplicate or swap a +line; rename an identifier to another the workspace uses; add a signal, a +package member or a top line; rename a module or a port; a same-length +comment change; blank lines at the top), a no-op save, a create, a delete, a +rename, a checkout of 3 files, an open, a close, or an include toggle. A fresh +server comparison runs every N steps. + +| tree | seeds × steps (every) | answers compared | divergent checks | +|---|---|---:|---| +| corpus, pull, workspace scope | 1–4 × 500 (25) | 684 k (80 checks) | 0 | +| corpus, push, workspace / folder scope | 9 × 500, 8 × 500 (25) | 393 k with the next row (47 checks) | 0 | +| corpus, push | 7 × 200 (25) | | **1 at step 200 — F6, pre-existing** | +| OpenTitan sample (541 files: uart, i2c, spi_device, rv_timer, prim, prim_generic, tlul) | 11–13 × 500 (25) | 514 k (60 checks) | 0 | +| full OpenTitan `hw` (4 061 files) | 21 × 50 (50) | 6 538 | **1 — F6, pre-existing**; seed 21 also diverges at step 50 on 7408fac (248 answers) | +| full OpenTitan, buffers re-sent and re-saved before each check (F6 workaround) | 21 × 200 (50) | 30 k | 0 | + +**Findings.** + +- **F1 — MEDIUM, regression: a watcher `Created`/`Deleted` for a file the + scope cannot take leaves include edges stale.** + - Where: `state/watched.rs:39-49` classifies the file `Outside`, and + `server/index.rs:139` then does nothing. But + `includes.rs:351` (`found` → `path.is_file()`) resolves every held file's + `` `include`` against the disk, not the scope. A header that appears or + disappears outside the scope is exactly what an in-scope includer's edge + points at: a generated header under a gitignored `build/`, an unlisted + header in filelist mode (the normal case there), or a header in an + excluded directory. 7408fac re-scanned for every such event. + - Repro (`oracle/outside.py gitignored-header-created`): `.gitignore` holds + `gen/`; `rtl/a.sv` and `rtl/a_inc.svh` both `` `include "../gen/h.svh"``, + and `gen/h.svh` does not exist. Start the server in workspace scope, then + write `gen/h.svh` and send `didChangeWatchedFiles` with type Created. + `workspace/willRenameFiles gen/h.svh → …` now answers `null`. A fresh + server, and 7408fac, rewrite the include line in both `a.sv` and + `a_inc.svh`. + - Same in filelist mode (`filelist-header-created`: an `+incdir+` header + created after the scan; the includer's edit is missing). + - Also visible: second-hop reachability in `includes::reachable_from`, which + hover uses to pick the `` `define`` a file sees. The edges stay wrong until + the next whole rebuild. A user renaming the header in VS Code gets a rename + that leaves the include line pointing at the old name. +- **F2 — MEDIUM, regression: a save that moves no record no longer refreshes + diagnostics that depend on the lint configuration on disk.** + - Where: `server/index.rs:110` gates the generation bump and the republish + on `OneFile::Changed`. The `lucisv.toml` `[lint]` select/ignore/options and + the external waiver files are read from the disk at every lint + (`lint.rs` `Discovered`), and the watcher does not report `lucisv.toml` + (both commits). + - Before, saving any file made the edited config take effect. Now: + - push mode: the stale diagnostics stay; + - pull mode: `textDocument/diagnostic` with the previous result id answers + `"unchanged"`, because the result id is the generation, and the client + keeps the stale squiggles. + - Repro (`outside.py toml-lint-change`, `QA_PULL=0` and `=1`): a buffer with + `no-tabs`, `no-trailing-whitespace`, `wire-reg-mixup` and `unused-signal`. + Write `lucisv.toml` with `[lint] ignore = [those four]`, then + `didSave` the unchanged buffer plus the watcher echo. 71.1 still shows + four diagnostics (push), or `unchanged` (pull). 7408fac and a fresh server + show none (push), or `full []` (pull). + - This is exactly the "not in the record but user-visible" class the + Assumptions say does not exist. Waivers, `[lint.]` options and + `lineLength` from `lucisv.toml` behave the same way (same code path; not + run separately). +- **F3 — LOW–MEDIUM: the open-buffer add's age guard can be fooled; on macOS + it is routine.** + - Where: `state/incremental.rs:127-128` compares the file's **birth time** + with `scanned_at`. On APFS the birth time comes with the file: `mv` and + `ditto` keep it, `cp -p` copies it, and setting an mtime earlier than the + birth time (`touch -t`, `rsync -a`, `tar x`) pulls the birth time back too. + Measured: `touch -t 2020…; cp -p` gives a new file born in 2020. + - So a header unpacked or copied in after the scan, then opened and saved, + takes the one-file add. Other files' includes that were waiting for it are + not re-resolved: the exact edge the guard exists for. + - Repro (`moved-in-old-file`): filelist mode, an unlisted `late.svh` moved in + after the scan, opened, saved. `willRenameFiles` on it misses `rtl/a.sv`'s + include line; a fresh server and 7408fac have it. + - In practice this compounds F1, whose `Created` event was already dropped. + - Separately (informational): where `created()` is unsupported (several + Linux filesystems, see TODO §70) the guard always fails, which is sound + but turns the fast path off silently. +- **F4 — LOW, regression: an open buffer the index does not hold, changed on + disk, is no longer taken in.** + - Where: `watched.rs:42-44` → `Outside`. The Assumptions argue a rebuild + "would take the buffer's text, not the disk", but a rebuild also **adds** + every open buffer, and 7408fac's rescan did. + - Repro (`excluded-open-buffer`): an excluded `rtl/b.sv` opened after the + scan, then changed on disk with a watcher `Changed`. 21 answers differ + from a fresh server: references to `b` from `top.sv`, `b`'s completion + entry, call hierarchy. The buffer is taken in on its next save, so this + is the documented "opened after the scan" state lasting longer than + before. +- **F5 — LOW, cost not documented: an edit to a package most of the tree + imports costs more than the old whole pass.** + - A wildcard import reads the package's member table as one key, so any + member added or removed re-resolves every importer, and does it twice: + out against the old tables, in against the new. + - Measured (full OpenTitan over LSP, push, 10 buffers, medians of 5, + `reindex_one` line): + + | edit | 7408fac | 71.1 | + |---|---:|---:| + | `prim_mubi_pkg` member added (677 files) | 159 ms | **178 ms** | + | `prim_mubi_pkg` line at top | 157 ms | **171 ms** | + | `tlul_pkg` line at top | 155 ms | 142 ms | + + - The README lists "an edit above a widely used declaration" as the wide + case (prim_flop, 61 ms). A plain member add to a widely imported package + is the more common edit and is not listed; it is also slower than before. + Not a correctness problem; it belongs in Assumptions and in + `docs/perf/README.md`. +- **F6 — pre-existing (7408fac fails the same way), not this lane: + an open buffer's analysis can lose its latest `didChange`.** + - The server keeps showing the previous text's document symbols, semantic + tokens and diagnostics, while my client's text, the disk and a fresh + server agree with each other. + - Repros, deterministic: `QA_PULL=0 rand_run.py ~/.cache/lucisv-corpus + corpuspush 7 200 25` (71.1 fails at step 200; 7408fac on the same seed at + step 100), and `rand_run.py ~/.cache/lucisv-opentitan-full/hw + otfull 21 50 50` (both binaries, 248 answers). + - The notifications sent are well-formed (`didOpen` v1, `didChange` v2…v3, + saves). The losing `didChange` lands while the whole rescans that the + random creates and deletes trigger are in flight. A 10-iteration isolated + race (`oracle/race.py`) did not reproduce it. + - Re-sending and re-saving the buffers repairs every answer, so the index + itself is right. Recommend filing it separately. +- **Observations, not defects.** + - Recording the readers is always on in `IndexBuilder::finish`, so the CLI + and `lucisv_mcp` whole builds pay it too, with no update to use it for. + - `remove_one`'s `includers_of` compares the raw (as-resolved) spelling, + so on a case-insensitive disk an includer that wrote another case is not + re-scanned on removal (code reading only; no observable answer found). + - A burst of 2 000 watcher events for files in a gitignored build directory + now costs 0.2–0.3 s and no rescan, where 7408fac started 2 000 rescans. + +**Cost, re-measured.** Full OpenTitan `hw`, workspace scope, over LSP, push +mode, 10 buffers open. Medians of 5, on a machine busy with another lane and +Spotlight/file-provider work. + +| | 7408fac | 71.1 | +|---|---:|---:| +| warm startup scan (`scan finished`) | 1 064 ms | 1 140 ms (+76 ms; `absorb` 138 → 174 ms) | +| cold startup scan (one run each) | 2 673 ms | 2 179 ms (noise-dominated) | +| server RSS after settle (median of 3) | 456 MB | 448 MB (no measurable growth) | +| uart_tx comment at end: save / echo | 155 / 153 ms | 0.13 / 0.08 ms | +| uart_tx local signal | 169 / 169 ms | 15.1 / 0.06 ms | +| prim_flop local signal | 164 / 159 ms | 15.7 / 0.05 ms | +| prim_flop line at top | 157 / 159 ms | 88.8 / 0.02 ms | +| uart_reg_pkg member added | 161 / 156 ms | 27.1 / 0.32 ms | +| prim_assert local edit | 154 / 153 ms | 11.0 / 0.24 ms | +| new class `uvm_object` (a name ~150 DV files miss on) | 158 ms | 19.4 ms | +| new `` `define`` in prim_assert_standard_macros.svh | 157 ms | 20.2 ms | +| clk_rst_if line at top (195 users) | 155 ms | 34.7 ms | + +- The narrowing delivers the headline: the echo is free and a local edit + costs ~15 ms. My local-edit figures are 2–3× the dev's (5.2 ms), and + `prim_flop` line-at-top is 89 ms against the dev's 61; the push republish + and machine load are both in these numbers. +- The warm-scan increase (+76 ms, +7 %) is about three times the dev's +23 ms. + Both are small against what one save saves. + +**Not verified.** + +- No real VS Code was driven. The watcher echo, VS Code's spelling of events + under symlinked or case-variant roots, and the order of `didOpen` and + `Created` for "New File" are all replayed, not observed. +- I did not re-run the dev's 21 sabotage controls; my own negative control is + the silent edit. +- Linux (no birth time) was not run. + +**What I changed:** nothing in the source or tests. This QA log is the only +edit to the tree. + +### 2026-11-19 — QA agent (Opus 5.5), round 2: PASS WITH FINDINGS + +**Verdict: PASS WITH FINDINGS.** F1–F5 are fixed: every round-1 reproduction +now matches a fresh server. + +- In what my oracle could reach, I found no stale answer this lane causes. + Every divergence I did find also reproduces, in the same form, against a + 7408fac build. +- The new findings are two costs (R2-1, R2-2) and one measurement note + (R2-3), all LOW. +- The pre-existing defects are listed at the end for the next lane. + +Binary: `cargo build --release -p lucisv_server` on the fix-round tree, copied +to `scratchpad/qa711/lucisv-server-r2`. + +**Baseline.** + +- Full `tools/gates.sh` (not inside `guard.sh`): **PASS** on every step. + - fmt, clippy, build, docs 1/0, corpus 814/6 (the same six), node 37/0 + - suites: vlog_parser 521, vlog_semantic 435, vlog_refactor 743, + vlog_formatter 352, vlog_linter 672, lucisv_core 117, lucisv 143, + lucisv_server 1 990, lucisv_mcp 383 — all 0 failed +- Against round 1: vlog_semantic +1, lucisv_server +5. No `#[test]` was + deleted. +- Both `#[ignore]`d sweeps, release, guarded: pass (40.2 s). +- Test changes since round 1: + - `a_client_that_cannot_refresh_code_lenses_is_never_asked_to` saves a real + edit again and asserts the save moved the index (`member_in("sub", "w")`). + - `an_index_rebuild_moves_the_result_id_too` expects `full` after a no-op + save, which is stronger than round 1. + - Nothing is weaker. +- File sizes (non-blank, non-comment lines before the first `#[cfg(test)]`): + the largest touched file is `candidates.rs` at 435, then `record.rs` 358 and + `includes.rs` 327. Everything is under 600. + +**Oracle, re-run in full on the new binary**: the same scripts and the same +battery as round 1, plus `willRenameFiles` probes. + +| suite | result | +|---|---| +| `small.py`, 52 scenarios × workspace/folder scope × pull and push | 156 + 156 checks ok; only `NEGCTL-silent` diverges, as it must | +| `outside.py` (the F1–F4 reproductions and the rest of round 1's list), pull and push | 14/14 and 14/14 ok (round 1: 4 diverged) | +| `r2attack.py`, 21 cases, pull and push, against r2 **and** 7408fac | r2: 17 ok; 4 diverge — **identical in 7408fac** (pre-existing, below) | +| `f5.py`, sweep threshold: 11 trees × 7 steps | 77/77 ok | + +`f5.py` details: + +- Below the floor: `n50/k50`, ~18 k references. +- Just above the floor: `n60/k60`, ~21.7 k. +- Readers' share straddling 1/8: `n170` with `k` = 40, 45, 48, 50, 52, 56, 64. +- Far above: `n170/k170`. Far below: `n170/k5`. +- Each tree has two packages exporting `X`, so every importer of both is + ambiguous. The steps: member add, line at the top, the ambiguity removed + and restored, a member used everywhere removed, `X` removed from one + package, a filler edit. + +`r2attack.py` cases: + +- F1: include through a symlinked directory; target spelled in another case + (`../GEN/H.SVH` against `gen/h.svh`); the same basename in the own dir and + an `+incdir+` (create incdir, create own-dir so it wins, delete own-dir, + delete incdir, recreate own-dir, every step ok); a transitive header + created inside an out-of-scope header; a path with no extension; directory + events. +- F2: waiver file created, edited and deleted, each followed by a no-op save; + a nested `rtl/sub/lucisv.toml` followed by a no-op save of *another* file; + `didChangeConfiguration` of `lint.ignore`. +- F3: a file moved in by `mv`, `cp -p`, `rsync -a` and `tar x`, each with an + mtime of 2020, opened and saved with and without a watcher echo (8 cases); + a buffer opened before its file exists on disk, then written and saved. +- F4: an excluded buffer opened, changed on disk, closed, reopened, saved and + closed. + +**Random runs** (`oracle/rand_run2.py`): round 1's ops plus the event kinds +behind F1–F4. + +- `qa_gen/` (gitignored) headers created and deleted, and in-scope files + gaining an `` `include`` of them; `willRenameFiles` probes for those headers + are in the battery. +- `lucisv.toml` `[lint] ignore` rewritten, followed by a no-op save. +- A `cp -p` of a file dated 2020 into a random directory, opened and saved, + half the time without a watcher echo. +- Excluded `qa_excl/` files opened and changed on disk. + +The oracle needed two adjustments, and both apply equally to 7408fac: + +- `QA_FRESH_SAVE`: after its scan, the fresh server saves its own open + buffers. A buffer opened while the startup scan takes its work list is + documented as not taken in, which made the fresh side non-deterministic. +- Closing an excluded buffer was dropped from the op mix. That is pre-existing + P2 below, seen first in seeds 31–33. + +All seeds are new; 500 steps, checked every 25, unless noted. + +| tree | seeds | answers | result | +|---|---|---:|---| +| corpus, pull, workspace | 31, 32, 37, 33 (re-run after the close change) | 487 k + | 0 divergent | +| corpus, push, workspace | 34, 35 | 424 k (with the next row) | 0 | +| corpus, push, folder | 36 | | 0 | +| OpenTitan sample | 41, 43 | 364 k (with 42) | 0 | +| OpenTitan sample | 42 | | step 350: the saved buffer's own answers stale = **F6** (deterministic; 0 divergent over 500 steps with `QA_REPAIR`) | +| full OpenTitan, `QA_REPAIR`, symlinks copied as files | 51, 52 × 300 (check every 50) | 78 k | 0 | +| full OpenTitan, symlinks kept | 51 × 50 | | divergent = pre-existing P3 (7408fac diverges on the same seed, on another symlinked file) | + +**F6 is unchanged.** Corpus seed 7 (push) diverges at step 200 on the same 8 +answers as in round 1. In OpenTitan-sample seed 42 the losing `didChange` and +its save land between a `checkout x3` (a whole rescan) and a `create`; the +server logs no `reindex_one` for that save. That fits the dev's Handshakes +note: a change dropped while a whole rescan is in flight. An isolated loop +(`oracle/movedthenedit.py`, 15 iterations) did not reproduce it. + +**Cost re-measured** with `perf.py` and `startup.py`: full OpenTitan, +workspace scope, push, 10 buffers, medians of 5. The `reindex_one` line now +includes the republish. The machine was busy with my own runs and with +Spotlight indexing, and both binaries ran back to back under the same load. + +| edit | 7408fac save / echo | r2 save / echo | +|---|---:|---:| +| uart_tx comment at end | 165 / 178 ms | 0.9 / 0.9 ms | +| uart_tx local signal | 179 / 169 | 8.8 / 0.9 | +| prim_flop local signal | 178 / 174 | 10.0 / 0.8 | +| prim_flop line at top | 171 / 169 | 51.9 / 0.9 | +| uart_reg_pkg member added | 167 / 164 | 15.9 / 1.1 | +| prim_assert local edit | 164 / 171 | 5.0 / 1.1 | +| prim_mubi_pkg member added | 170 / 166 | **101** / 1.3 | +| prim_mubi_pkg line at top | 166 / 178 | 91.5 / 1.2 | +| tlul_pkg line at top | 166 / 167 | 73.5 / 1.3 | +| new class `uvm_object` | 169 / 169 | 9.1 / 1.2 | +| new `` `define`` in a macros header | 170 / 175 | 10.8 / 1.3 | +| clk_rst_if line at top | 164 / 166 | 21.2 / 1.4 | +| warm startup scan (medians of 5, alternating) | 1 259 ms | 1 363 ms (+104 ms, +8 %) | +| RSS after settle (median of 3) | 475 MB | 468 MB | + +No edit is slower than 7408fac. F5's package case is fixed: 101 ms against +170 ms at 7408fac. + +**Findings (round 2).** + +- **R2-1 — LOW, cost: one watcher notification costs ~0.24 ms per path named, + linearly.** + - Where: `server/notification.rs`'s watcher arm calls + `refresh_includes_naming` for every path, and `includes.rs:188` + (`refresh_naming`) walks every held file's include lines once per path. + Out-of-scope paths then also take `watched()`'s directory walk. + - Measured on full OpenTitan, one `didChangeWatchedFiles` naming N files + created in a gitignored directory: + + | N | 7408fac (one whole rescan) | r2 (no rescan) | + |---:|---:|---:| + | 1 000 | | 0.23 s | + | 2 500 | | 0.59 s | + | 5 000 | 0.75 s | **1.21 s** | + | 10 000 | | 2.52 s | + + - Not quadratic. Past ~3 000 paths in one event (a generator writing a + build tree), the cheap path costs more than the rescan it replaced, and + it blocks the queue. + - Repro: `oracle/genburst.py 5000 `. +- **R2-2 — LOW, cost: with many buffers open, the republish now dominates a + save.** Full OpenTitan, push, median of 5 (`oracle/manybuf.py`): + + | buffers | 7408fac no-op / local signal | r2 no-op / local signal | + |---:|---:|---:| + | 10 | 162 / 170 ms | 0.8 / 9.7 ms | + | 50 | 170 / 172 ms | 3.7 / 19.3 ms | + | 200 | 203 / 207 ms | 14.3 / **53.4** ms | + + - A no-op save re-sends ~0.07 ms a buffer. An edit that moves the index + clears every lint snapshot and re-lints ~0.2 ms a buffer, against ~5 ms of + index work. + - Still 4× faster than 7408fac at 200 buffers. The README's "~0.3 ms a + buffer" is the right order. +- **R2-3 — measurement note:** warm startup +104 ms (+8 %) on a loaded + machine, above the dev's stated +25 to +75 ms. Load-dependent, as the dev + says. + +**Pre-existing: reproduced on 7408fac identically, not this lane.** For the +next lane: + +- **P1** — a watcher event that names only a **directory** loses what is + inside it. + - `r2attack.py dir-create`: a header directory created → its includer's + edge is missing. + - `held-dir-delete`: a directory of held files deleted → the index keeps + them, 9 answers differ. + - A deleted header directory with only the directory named happens to + match. + - The dev's note ("a deleted directory is filtered out, edges stay stale, + same as 7408fac") is confirmed for both builds. + - What `git checkout` of a removed directory sends through VS Code's + watcher (one event per file, or the directory alone) I could not observe. + git unlinks file by file, so per-file events are the likely shape + (**unverified**). +- **P2** — an excluded or out-of-filelist buffer, once taken into the index, + **stays after `didClose`**. A fresh server without it open does not hold + it: `excluded-open-close` diverges on 20 answers after the close, in both + builds. F4 makes the take-in more frequent, since the one-file path now adds + such a buffer on any event. The close behaviour itself is 7408fac's. +- **P3** — **symlinked files.** OpenTitan's `top_englishbreakfast/rtl/*.sv` are + symlinks into `top_earlgrey/rtl/`. + - Whether a rebuild holds both spellings depends on whether the target is + an open buffer at scan time. + - `oracle/filelink.py` diverges in all six variants (via target or link × + editor/disk/open-only) on both builds. +- **F6** — unchanged; see above. The Handshakes note matches what I observed. + +**Not verified:** + +- no real VS Code (the watcher's shape for directory operations, the + "New File" event order, symlinked roots); +- Linux; +- that the sweep path actually ran in the `f5.py` trees near 1/8. Its + references count is not observable over LSP, so I bracketed it: + `k170`/`n60` are certainly above the floor and the eighth, `n50` and `k5` + certainly below, and every case passed. + +**What I changed:** nothing outside this QA log. + +## Review + +**Lead, 2026-11-19.** Accepted for 0.65.6, after a QA FAIL, a fix round, a QA pass and one more small round. + +- Step 1 mattered more than the design: an incremental path already existed, + and what the owner was seeing was the watcher echo doubling every save, + whole rescans for files the index could not hold, and a one-file path that + was still O(index). The dev measured before designing, and dropped two + things my brief asked for (the inverted word index, narrowing the + republish) because the measurements said they were not the cost. Right. +- Recording what each file READ — misses included — instead of inferring + readers from the names a file mentions is the decision that makes this + sound; the dev's negative controls show the name-based version breaking on + `extends` chains, re-exports and hierarchical paths. +- The first cut failed QA, properly: two shortcuts ("outside the scope does + nothing", "unchanged record sends nothing") were proven for the index and + assumed for the include graph and the diagnostics. The rule I gave for the + fix round stands for whoever touches this next: a shortcut may skip work + only when everything that work would have produced is provably unchanged. + F2's fix is the conservative one — every save republishes, as before this + lane — and that is deliberate. +- QA's fresh-server oracle is the evidence I accept this on, not the dev's + harness: it was built independently, it failed the first cut, and it + passes the final one. Round 3 (burst threshold, include batching, lint + width) was re-checked by the dev against QA's hand scenarios but not by QA + and not against new random seeds; I accept that for a change of that size, + and say so. +- I rebased the lane onto 0.65.5 myself; the formatter lane's three calls in + `server/notification.rs` survived, and its `lint.rs` request is taken here. +- Not verified: a real VS Code (the watcher's behaviour is from its + documentation), and Linux. +- Open, handed to lane 71.7 with reproductions: the out-of-order edit during + a rescan, directory-only watcher events, excluded buffers after close, + symlink spellings. diff --git a/docs/perf/README.md b/docs/perf/README.md index a04fdf3..f3e9f5f 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -1444,3 +1444,27 @@ A warm build is walk 210 ms + store read 87 ms + read/hash/decode 318 ms + merge 204 ms; a cold one parses instead (1 387 ms). The rows are not like-for-like with the server's (it scans in stages and answers during the scan); they sit side by side so a regression in either shows. + +### 2026-11-19 — localized reindex (TODO §71.1) + +What one save costs the index on the full OpenTitan `hw` tree (4 058 files, +scope `workspace`, 10 buffers open), measured over LSP with the real release +server and in-process with `state::tests::reindex_perf` (release, +`--test-threads=1`); medians, the machine shared with another lane's builds. +Details and the method: `docs/features/localized-reindex/README.md`. + +| | before (7408fac) | after | +|---|---:|---:| +| `reindex_one`, any edit, any file | 141–158 ms | — | +| …the watcher's echo of a save / an unchanged record | 153–176 ms, everything republished | 0.07–1.1 ms, nothing sent | +| …a local signal in a module (`uart_tx`, `prim_flop`) | 144–145 ms | 5.2 ms | +| …a package member added (`uart_reg_pkg`) | 148 ms | 11.7 ms | +| …a line above everything in `prim_flop.sv` (125 instantiating files) | 144 ms | 61 ms | +| watcher event for a `.sv` the scope cannot take | 746 ms whole rescan | 3.5 ms, nothing | +| whole merge (`absorb`, startup / cached rescan) | 135 / 165 ms | 158 / 189 ms | +| warm startup scan (fix round, QA's `perf.py`, two runs) | 1 113 / 1 124 ms | 1 171 / 1 148 ms | +| `prim_mubi_pkg` member added, 677 importers (fix round) | 162 ms | 92 ms | +| readers table | — | 13 806 keys, 69 222 entries | +| mention census, one lint pass (average / worst file) | 51 µs / 2.8 ms | unchanged | + +Probes: `tools/guard.sh -- cargo test --release -p lucisv_server reindex_perf -- --ignored --nocapture --test-threads=1`. diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index 0ec01dc..c093044 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -5,6 +5,16 @@ for you. The extension and its bundled language server share one version number; the full engineering notes live in the [project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md). +## 0.65.6 — 2026-11-19 + +- **Saving no longer re-indexes the workspace.** On a large project a save + used to cost a whole-index pass, twice (once for the save, once for VS + Code's file watcher). A typical edit now costs a few milliseconds, and a + save that changes nothing the index records costs nothing. +- **No more surprise "indexing" bar** for generated files, files outside the + filelist or folder scope, or files reached through a symlink. +- **The line-length warning follows your formatting style's width.** + ## 0.65.5 — 2026-11-19 - **Formatting styles, from a drop-down.** `lucisv.format.style` picks the diff --git a/editors/vscode/README.md b/editors/vscode/README.md index c13aa69..6333ea3 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view, then open a Verilog or SystemVerilog file. There is no separate server or CLI setup. -The current release is **0.65.5**. Its platform packages include +The current release is **0.65.6**. Its platform packages include `lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see [Agents (MCP)](#agents-mcp)): @@ -440,6 +440,13 @@ default): } ``` +## Release 0.65.6 highlights + +Version 0.65.6 makes saving cheap on large projects: the language server +updates only what an edit can reach instead of re-resolving the whole index — +on OpenTitan a typical save drops from about 160 ms (twice) to a few +milliseconds. + ## Release 0.65.5 highlights Version 0.65.5 adds named formatting styles — `google`, `lowrisc`, `ansi`, diff --git a/editors/vscode/package-lock.json b/editors/vscode/package-lock.json index 7048805..a204892 100644 --- a/editors/vscode/package-lock.json +++ b/editors/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "lucisv", - "version": "0.65.5", + "version": "0.65.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "lucisv", - "version": "0.65.5", + "version": "0.65.6", "license": "MIT", "dependencies": { "vscode-languageclient": "9.0.1" diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 6da95bc..c83c9a4 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -2,7 +2,7 @@ "name": "lucisv", "displayName": "lucisv — Verilog/SystemVerilog", "description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.", - "version": "0.65.5", + "version": "0.65.6", "publisher": "guoliangchen", "author": "Guoliang Chen", "license": "MIT",