From 4d384ec89dc414cfc48b0b76d44ccf4f5eebc5ad Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Thu, 26 Nov 2026 11:14:26 -0800 Subject: [PATCH] Round 2: unified index lifecycle, tombstones, symlinks, and large-file invariant (#48-#51, #63) --- crates/lucisv_mcp/src/project/mod.rs | 7 + crates/lucisv_mcp/src/tools/diagnostics.rs | 110 +- crates/lucisv_mcp/src/tools/names.rs | 31 +- crates/lucisv_server/src/candidates.rs | 4 +- .../lucisv_server/src/completion/related.rs | 3 +- crates/lucisv_server/src/extract.rs | 41 +- crates/lucisv_server/src/hierarchy/calls.rs | 9 +- crates/lucisv_server/src/hover.rs | 6 +- crates/lucisv_server/src/imports.rs | 2 +- crates/lucisv_server/src/includes.rs | 41 +- crates/lucisv_server/src/inline_module.rs | 9 +- crates/lucisv_server/src/lint.rs | 52 +- crates/lucisv_server/src/nav.rs | 15 +- crates/lucisv_server/src/ports.rs | 13 +- crates/lucisv_server/src/rename.rs | 3 +- crates/lucisv_server/src/server/large_file.rs | 52 +- .../lucisv_server/src/server/notification.rs | 39 +- .../src/server/tests/lifecycle_r2.rs | 2794 +++++++++++++++++ crates/lucisv_server/src/server/tests/mod.rs | 1 + .../lucisv_server/src/server/tests/startup.rs | 4 +- crates/lucisv_server/src/state/buffers.rs | 78 +- crates/lucisv_server/src/state/discover.rs | 265 +- crates/lucisv_server/src/state/incremental.rs | 124 +- crates/lucisv_server/src/state/mod.rs | 101 +- crates/lucisv_server/src/state/reconcile.rs | 261 ++ crates/lucisv_server/src/state/rescan.rs | 141 +- crates/lucisv_server/src/state/scan.rs | 12 + crates/lucisv_server/src/state/sources.rs | 29 +- .../src/state/tests/large_file.rs | 9 +- .../src/state/tests/open_buffers.rs | 17 +- .../src/state/tests/reindex_perf.rs | 6 +- crates/lucisv_server/src/state/tests/widen.rs | 15 +- crates/lucisv_server/src/state/watched.rs | 86 +- crates/vlog_semantic/src/workspace/index.rs | 67 +- crates/vlog_semantic/src/workspace/mod.rs | 13 +- crates/vlog_semantic/src/workspace/update.rs | 152 +- crates/vlog_semantic/tests/workspace.rs | 300 +- docs/features/index-lifecycle-r2/README.md | 174 + docs/topo.md | 10 +- 39 files changed, 4709 insertions(+), 387 deletions(-) create mode 100644 crates/lucisv_server/src/server/tests/lifecycle_r2.rs create mode 100644 crates/lucisv_server/src/state/reconcile.rs create mode 100644 docs/features/index-lifecycle-r2/README.md diff --git a/crates/lucisv_mcp/src/project/mod.rs b/crates/lucisv_mcp/src/project/mod.rs index a32207f..92c6cd9 100644 --- a/crates/lucisv_mcp/src/project/mod.rs +++ b/crates/lucisv_mcp/src/project/mod.rs @@ -240,6 +240,13 @@ impl Project { &self.index } + /// Drop one file directly from the held index (test-only helper to exercise + /// sparse tombstoned `FileId`s). + #[cfg(test)] + pub(crate) fn remove_file_from_index(&mut self, path: &Path) -> bool { + self.index.remove_file(path) + } + /// The canonical roots, in the order given. pub fn roots(&self) -> &[PathBuf] { &self.roots diff --git a/crates/lucisv_mcp/src/tools/diagnostics.rs b/crates/lucisv_mcp/src/tools/diagnostics.rs index abb02be..4610621 100644 --- a/crates/lucisv_mcp/src/tools/diagnostics.rs +++ b/crates/lucisv_mcp/src/tools/diagnostics.rs @@ -264,9 +264,8 @@ struct Census<'a> { impl<'a> Census<'a> { fn of(index: &'a WorkspaceIndex) -> Census<'a> { let mut words: HashMap<&'a str, (usize, FileId)> = HashMap::new(); - for (at, path) in index.files().iter().enumerate() { + for (file, path) in index.live_files() { let Some(facts) = index.facts_for(path) else { continue }; - let file = FileId(at as u32); for word in facts.words() { words.entry(word.as_str()).or_insert((0, file)).0 += 1; } @@ -328,4 +327,111 @@ impl MentionOracle for Mentions<'_> { } } +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn census_uses_live_file_ids_after_tombstone_at_slot_zero() { + let mut index = WorkspaceIndex::build([ + (PathBuf::from("a_excl.sv"), "module a_excl; logic excl_only; endmodule\n"), + ( + PathBuf::from("b_live.sv"), + "module b_live; logic own_sig; logic shared_sig; endmodule\n", + ), + (PathBuf::from("c_user.sv"), "module c_user; logic shared_sig; endmodule\n"), + ]); + assert!(index.remove_file(Path::new("a_excl.sv"))); + let b_id = index.file_id(Path::new("b_live.sv")).expect("b_live live"); + assert_eq!(b_id, FileId(1)); + + let census = Census::of(&index); + assert!(!census.outside("excl_only", Some(b_id))); + assert!( + !census.outside("own_sig", Some(b_id)), + "Census::of must keep FileId(1) rather than shifting to FileId(0)" + ); + assert!(census.outside("shared_sig", Some(b_id))); + } + + #[test] + fn qa_r2_f1_mcp_find_and_check_with_multiple_tombstones_preceding_live_files() { + let dir = std::env::temp_dir().join(format!("lucisv-mcp-qa-r2-f1-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("mkdir"); + let dir = std::fs::canonicalize(dir).expect("canon"); + + let excl0 = dir.join("a0_excl.sv"); + let excl1 = dir.join("a1_excl.sv"); + let excl2 = dir.join("a2_excl.sv"); + std::fs::write(&excl0, "`define EX0 1\nmodule a0; logic ex0_sig; endmodule\n").expect("w"); + std::fs::write(&excl1, "`define EX1 1\nmodule a1; logic ex1_sig; endmodule\n").expect("w"); + std::fs::write(&excl2, "`define EX2 1\nmodule a2; logic ex2_sig; endmodule\n").expect("w"); + std::fs::write( + dir.join("b_live.sv"), + "`define LIVE_MAC 1\nmodule b_live;\n logic own_sig;\n logic shared_sig;\nendmodule\n", + ) + .expect("w"); + std::fs::write( + dir.join("c_user.sv"), + "module c_user;\n logic shared_sig;\n b_live u1 ();\nendmodule\n", + ) + .expect("w"); + + let mut project = Project::open(vec![dir.clone()], None); + assert!(project.remove_file_from_index(&excl0)); + assert!(project.remove_file_from_index(&excl1)); + assert!(project.remove_file_from_index(&excl2)); + assert_eq!(project.index().files().len(), 2); + assert_eq!(project.index().file_id(&dir.join("b_live.sv")), Some(FileId(3))); + + let make_args = |tool: &crate::tools::Tool, v: serde_json::Value| { + crate::tools::validate(tool, v.as_object().cloned().expect("args obj")) + .expect("valid args") + }; + + let check_tool = crate::tools::find("check", crate::tools::Mode::Full).expect("check tool"); + let single = (check_tool.handler)( + &mut project, + &make_args(check_tool, serde_json::json!({ "file": "b_live.sv" })), + ) + .expect("single check"); + assert!(single.text.contains("own_sig"), "single check flags own_sig: {}", single.text); + assert!( + !single.text.contains("shared_sig"), + "single check ignores shared_sig: {}", + single.text + ); + + let whole = + (check_tool.handler)(&mut project, &make_args(check_tool, serde_json::json!({}))) + .expect("whole check"); + assert!(whole.text.contains("own_sig"), "whole check flags own_sig: {}", whole.text); + assert!( + !whole.text.contains("shared_sig"), + "whole check ignores shared_sig: {}", + whole.text + ); + + let find_tool = crate::tools::find("find", crate::tools::Mode::Full).expect("find tool"); + let refs = (find_tool.handler)( + &mut project, + &make_args(find_tool, serde_json::json!({ "name": "b_live", "refs": true })), + ) + .expect("find refs"); + assert!(refs.text.contains("c_user.sv"), "find refs locates c_user.sv: {}", refs.text); + + let err = match (find_tool.handler)( + &mut project, + &make_args(find_tool, serde_json::json!({ "name": "LIVE" })), + ) { + Ok(_) => panic!("expected no_declaration error with similar"), + Err(e) => e, + }; + assert!(err.contains("LIVE_MAC"), "near match must include LIVE_MAC: {err}"); + + let _ = std::fs::remove_dir_all(&dir); + } +} + // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_mcp/src/tools/names.rs b/crates/lucisv_mcp/src/tools/names.rs index bc96f70..eb1adff 100644 --- a/crates/lucisv_mcp/src/tools/names.rs +++ b/crates/lucisv_mcp/src/tools/names.rs @@ -11,7 +11,7 @@ use std::collections::{BTreeSet, HashSet}; use std::path::{Path, PathBuf}; use vlog_parser::defines::DefineKind; -use vlog_semantic::{Def, DefinitionKey, FileId, Surface, SymbolKind, WorkspaceIndex}; +use vlog_semantic::{Def, DefinitionKey, Surface, SymbolKind, WorkspaceIndex}; use super::declared::{declared, Local, Wanted}; use super::source::{checked_site, Texts}; @@ -188,8 +188,8 @@ pub fn similar(project: &Project, name: &str, cap: usize) -> Vec { index.workspace_symbols(name).iter().map(|hit| hit.name.to_string()).collect(); let part = Wanted::Containing(name.to_ascii_lowercase()); names.extend(declared(project, &part).into_iter().map(|local| local.name)); - for at in 0..index.files().len() { - let Some(table) = index.defines(FileId(at as u32)) else { continue }; + for (file, _) in index.live_files() { + let Some(table) = index.defines(file) else { continue }; let found = table.entries().iter().filter(|d| contains_any_case(&d.name, name)); names.extend(found.map(|define| define.name.clone())); } @@ -222,7 +222,10 @@ pub fn ambiguous(name: &str, found: &[&Declaration], pick: &str) -> String { #[cfg(test)] mod tests { - use super::qualified; + use super::{qualified, similar}; + use crate::project::Project; + use std::fs; + use std::path::PathBuf; #[test] fn a_unit_qualifies_a_name_and_an_escaped_name_is_whole() { @@ -233,6 +236,26 @@ mod tests { assert_eq!(qualified("\\a.b "), (None, "\\a.b ")); assert_eq!(qualified(".x"), (None, ".x")); } + + #[test] + fn similar_finds_macros_after_tombstoned_slot_zero() { + let dir = + std::env::temp_dir().join(format!("lucisv-mcp-names-tombstone-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let dir = fs::canonicalize(dir).unwrap(); + let a_path = dir.join("a_excl.sv"); + fs::write(&a_path, "`define EXCL_MAC 1\nmodule a_excl; endmodule\n").unwrap(); + fs::write(dir.join("z_mac.sv"), "`define LIVE_MAC 1\nmodule z_mac; endmodule\n").unwrap(); + + let mut project = Project::open(vec![dir.clone()], None); + assert!(project.remove_file_from_index(&a_path)); + assert_eq!(similar(&project, "LIVE", 20), vec!["LIVE_MAC".to_string()]); + assert!(similar(&project, "EXCL", 20).is_empty()); + + let _ = fs::remove_dir_all(&dir); + let _: PathBuf = dir; + } } // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/candidates.rs b/crates/lucisv_server/src/candidates.rs index 2a78376..eed6cb9 100644 --- a/crates/lucisv_server/src/candidates.rs +++ b/crates/lucisv_server/src/candidates.rs @@ -833,8 +833,8 @@ fn unit_tables( /// defined, and offering the name is the honest answer either way. fn macros_of(index: &WorkspaceIndex) -> Vec { let mut out: Vec = Vec::new(); - for id in 0..index.files().len() { - let Some(table) = index.defines(vlog_semantic::FileId(id as u32)) else { continue }; + for (file, _) in index.live_files() { + let Some(table) = index.defines(file) else { continue }; for define in table.entries().iter().filter(|d| d.kind == DefineKind::Define) { out.push(macro_of(define)); } diff --git a/crates/lucisv_server/src/completion/related.rs b/crates/lucisv_server/src/completion/related.rs index 01e61e0..0f9858b 100644 --- a/crates/lucisv_server/src/completion/related.rs +++ b/crates/lucisv_server/src/completion/related.rs @@ -104,8 +104,7 @@ pub(super) fn related_tier( pub(super) fn related_macros(items: &mut Items, ws: &Workspace, doc: &Document, prefix: &str) { let mut names: Vec<(String, String)> = Vec::new(); for path in crate::includes::reachable_from(ws, doc) { - let Some(table) = ws.index().file_id(&path).and_then(|file| ws.index().defines(file)) - else { + let Some(table) = ws.index_file_id(&path).and_then(|file| ws.index().defines(file)) else { continue; }; let defines = table.entries().iter().filter(|d| d.kind == DefineKind::Define); diff --git a/crates/lucisv_server/src/extract.rs b/crates/lucisv_server/src/extract.rs index 2c5fda1..4cb43de 100644 --- a/crates/lucisv_server/src/extract.rs +++ b/crates/lucisv_server/src/extract.rs @@ -119,10 +119,10 @@ pub fn execute( let doc = ws .document(&uri) .ok_or_else(|| "lucisv can only extract from an open file.".to_string())?; - let path = doc - .path - .clone() - .ok_or_else(|| "lucisv can only extract from a file that has been saved.".to_string())?; + let path = + ws.index_path_for(doc.path.as_deref().ok_or_else(|| { + "lucisv can only extract from a file that has been saved.".to_string() + })?); let positions = doc.positions(); let (start, end) = (positions.offset(range.start), positions.offset(range.end)); let Some(site) = site_at(doc, start, end) else { @@ -173,19 +173,11 @@ pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result String::new(), - false => ws.text_of(path).ok_or_else(|| unaddressable(path))?, - }; - let index = LineIndex::new(&text); - let positions = Positions::new(&text, &index); - operations.push(DocumentChangeOperation::Edit(TextDocumentEdit { - text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None }, - edits: edits + let map_with = |positions: &Positions<'_>| { + edits .iter() .map(|edit| { OneOf::Left(TextEdit { @@ -193,7 +185,26 @@ pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result>() + }; + let (uri, version, mapped) = match (!created) + .then(|| ws.open_document_for_path(path)) + .flatten() + { + Some((open_uri, doc)) => (open_uri.clone(), doc.version(), map_with(&doc.positions())), + None => { + let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?; + let text = match created { + true => String::new(), + false => ws.text_of(path).ok_or_else(|| unaddressable(path))?, + }; + let index = LineIndex::new(&text); + (uri, None, map_with(&Positions::new(&text, &index))) + } + }; + operations.push(DocumentChangeOperation::Edit(TextDocumentEdit { + text_document: OptionalVersionedTextDocumentIdentifier { uri, version }, + edits: mapped, })); } Ok(WorkspaceEdit { diff --git a/crates/lucisv_server/src/hierarchy/calls.rs b/crates/lucisv_server/src/hierarchy/calls.rs index fb1b1e6..1375366 100644 --- a/crates/lucisv_server/src/hierarchy/calls.rs +++ b/crates/lucisv_server/src/hierarchy/calls.rs @@ -84,7 +84,10 @@ fn other_files( let is_call_of_def = |doc: &Document, id: ReferenceId| names_def(doc, id, def); let mut calls = Vec::new(); for (_, doc) in ws.open_documents() { - let Some(path) = doc.path.as_deref().filter(|path| *path != declaring) else { continue }; + let Some(path) = doc.path.as_deref().filter(|path| !ws.is_same_file(path, declaring)) + else { + continue; + }; let Some(uri) = path_to_uri(path) else { continue }; calls.extend(callers(&uri, doc, name, |_, id| is_call_of_def(doc, id))); } @@ -92,7 +95,7 @@ fn other_files( .references_to(def) .iter() .filter_map(|site| index.path(site.file)) - .filter(|path| *path != declaring && ws.document_for_path(path).is_none()) + .filter(|path| !ws.is_same_file(path, declaring) && ws.document_for_path(path).is_none()) .map(Path::to_path_buf) .collect(); closed.sort(); @@ -119,7 +122,7 @@ fn other_files( fn declined(ws: &Workspace, def: &Def, name: &str, declaring: &Path) -> bool { ws.index().references_are_ambiguous(def) || ws.open_documents().any(|(_, doc)| { - doc.path.as_deref().is_some_and(|path| path != declaring) + doc.path.as_deref().is_some_and(|path| !ws.is_same_file(path, declaring)) && names_it_ambiguously(doc, name, def) }) } diff --git a/crates/lucisv_server/src/hover.rs b/crates/lucisv_server/src/hover.rs index 603e93e..ea44107 100644 --- a/crates/lucisv_server/src/hover.rs +++ b/crates/lucisv_server/src/hover.rs @@ -98,7 +98,11 @@ pub(crate) fn narrowed_to_the_include_graph<'a>( } let narrowed: Vec<(FileId, &Define)> = candidates .iter() - .filter(|(file, _)| ws.index().path(*file).is_some_and(|p| reachable.contains(p))) + .filter(|(file, _)| { + ws.index().path(*file).is_some_and(|p| { + reachable.contains(p) || reachable.iter().any(|r| ws.is_same_file(r, p)) + }) + }) .cloned() .collect(); match narrowed.len() { diff --git a/crates/lucisv_server/src/imports.rs b/crates/lucisv_server/src/imports.rs index f57e823..e4fa885 100644 --- a/crates/lucisv_server/src/imports.rs +++ b/crates/lucisv_server/src/imports.rs @@ -193,7 +193,7 @@ fn packages_at(doc: &Document, offset: u32) -> Vec { fn at(ws: &Workspace, uri: &Uri, offset: u32) -> Option<(PathBuf, Vec<(PathBuf, String)>)> { let doc = ws.document(uri)?; - let path = doc.path.clone()?; + let path = ws.index_path_for(doc.path.as_deref()?); let packages = packages_at(doc, offset); if packages.is_empty() { return None; diff --git a/crates/lucisv_server/src/includes.rs b/crates/lucisv_server/src/includes.rs index 57cd6aa..d100b93 100644 --- a/crates/lucisv_server/src/includes.rs +++ b/crates/lucisv_server/src/includes.rs @@ -468,6 +468,7 @@ impl IncludeGraph { /// Cycle-safe by construction: a file already visited is never expanded /// again, so `a` including `b` including `a` terminates with both in the /// set. + #[cfg(test)] pub fn reachable(&self, seeds: Vec) -> HashSet { let mut seen: HashSet = HashSet::new(); let mut queue = seeds; @@ -538,6 +539,18 @@ pub fn normalize(path: &Path) -> PathBuf { // the two capabilities // ---------------------------------------------------------------------- +/// Resolve one `` `include`` from `doc`, trying `doc.path` first and falling +/// back to the workspace's canonical indexed path for that file. +fn resolve_for_doc(ws: &Workspace, doc: &Document, include: &Include) -> Option { + let graph = ws.includes(); + let found = graph.resolve(doc.path.as_deref(), include).or_else(|| { + let path = doc.path.as_deref()?; + let canon = ws.index_path_for(path); + (canon != path).then(|| graph.resolve(Some(&canon), include)).flatten() + })?; + Some(ws.index_path_for(&found)) +} + /// Every resolvable `` `include`` in an open buffer, paired with the file it /// names. /// @@ -545,13 +558,9 @@ pub fn normalize(path: &Path) -> PathBuf { /// graph: the graph is rebuilt on save, and an include line just typed should /// be clickable before then. fn resolved(ws: &Workspace, doc: &Document) -> Vec<(Include, PathBuf)> { - let graph = ws.includes(); scan(&doc.text) .into_iter() - .filter_map(|include| { - let path = graph.resolve(doc.path.as_deref(), &include)?; - Some((include, path)) - }) + .filter_map(|include| Some((include.clone(), resolve_for_doc(ws, doc, &include)?))) .collect() } @@ -581,7 +590,7 @@ pub fn document_links(ws: &Workspace, uri: &Uri) -> Vec { /// disagree about where a line goes. pub fn definition(ws: &Workspace, doc: &Document, offset: u32) -> Option { let include = include_at(doc, offset)?; - let path = ws.includes().resolve(doc.path.as_deref(), &include)?; + let path = resolve_for_doc(ws, doc, &include)?; Some(Location { uri: path_to_uri(&path)?, range: Range::default() }) } @@ -603,11 +612,25 @@ pub(crate) fn include_at(doc: &Document, offset: u32) -> Option { /// the graph, so an include added since the last save already counts. The /// buffer itself is *not* in the set unless an include cycle reaches it. pub fn reachable_from(ws: &Workspace, doc: &Document) -> HashSet { - let seeds: Vec = resolved(ws, doc).into_iter().map(|(_, path)| path).collect(); - if seeds.is_empty() { + let mut queue: Vec = resolved(ws, doc).into_iter().map(|(_, path)| path).collect(); + if queue.is_empty() { return HashSet::new(); } - ws.includes().reachable(seeds) + let graph = ws.includes(); + let mut seen: HashSet = HashSet::new(); + while let Some(path) = queue.pop() { + if !seen.insert(path.clone()) { + continue; + } + let canon = ws.index_path_for(&path); + if canon != path && !seen.contains(&canon) { + queue.push(canon); + } + if let Some(targets) = graph.edges.get(&path) { + queue.extend(targets.iter().cloned()); + } + } + seen } #[cfg(test)] diff --git a/crates/lucisv_server/src/inline_module.rs b/crates/lucisv_server/src/inline_module.rs index fed0a78..bb2161e 100644 --- a/crates/lucisv_server/src/inline_module.rs +++ b/crates/lucisv_server/src/inline_module.rs @@ -91,10 +91,11 @@ pub fn execute( let position: Position = argument(arguments, 1, "a position")?; let doc = ws.document(&uri).ok_or_else(|| "lucisv can only inline in an open file.".to_string())?; - let path = doc - .path - .clone() - .ok_or_else(|| "lucisv can only inline in a file that has been saved.".to_string())?; + let path = ws.index_path_for( + doc.path + .as_deref() + .ok_or_else(|| "lucisv can only inline in a file that has been saved.".to_string())?, + ); let offset = doc.positions().offset(position); let Some(site) = site_at(doc, offset) else { return Err(NOTHING.to_string()); diff --git a/crates/lucisv_server/src/lint.rs b/crates/lucisv_server/src/lint.rs index f850d6c..b1faba3 100644 --- a/crates/lucisv_server/src/lint.rs +++ b/crates/lucisv_server/src/lint.rs @@ -52,6 +52,9 @@ use crate::state::{Document, Workspace}; pub struct LintRun<'a> { rules: Vec<&'static dyn Rule>, oracle: Option>, + /// Canonical indexed path when resolved through the workspace, falling back + /// to `doc.path` so symlinked open buffers lint against one identity. + path: Option, /// What the buffer's `lucisv.toml` and the editor's settings configured /// about each rule, merged. Empty means every rule reads its own default. options: RuleOptions, @@ -92,6 +95,7 @@ impl Default for LintRun<'_> { LintRun { rules: default_rules(), oracle: None, + path: None, options: RuleOptions::new(), line_length: DEFAULT_LINE_LENGTH, tab_width: DEFAULT_TAB_WIDTH, @@ -178,7 +182,8 @@ impl<'a> LintRun<'a> { /// This run's context over a buffer's own parse products. fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> { - let ctx = context(doc) + let path = self.path.as_deref().or(doc.path.as_deref()); + let ctx = context_for(doc, path) .with_options(&self.options) .with_line_length(self.line_length) .with_tab_width(self.tab_width); @@ -200,6 +205,7 @@ impl<'a> LintRun<'a> { /// `for_document`'s own, in its own order, so the messages a config problem /// produces arrive in the order §42.2 fixed. struct Discovered { + path: Option, options: RuleOptions, line_length: usize, tab_width: usize, @@ -217,7 +223,9 @@ impl Discovered { /// width, the indent and the waiver paths all read the same `FileConfig`, /// so reading the project's rules costs no extra stat and no extra open. fn read(ws: &Workspace, doc: &Document) -> Discovered { - let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc); + let path = doc.path.as_deref().map(|p| ws.index_path_for(p)); + let (options, line_length, file, mut messages) = + configured(ws.client_settings(), path.as_deref()); let (project, bad_names) = ProjectLint::read(&file); messages.extend(bad_names); let (mut external, bad_waivers, mut texts) = waiver_files(&project_waivers(&file)); @@ -233,15 +241,25 @@ impl Discovered { // it here rather than spelling the ladder a second time costs a second // `Discovery` walk, which the R1b trace measures at hundredths of a // millisecond against a 21 ms pass. - let tab_width = crate::format::indent_width(doc.path.as_deref(), ws.client_settings()); - Discovered { options, line_length, tab_width, file, project, external, texts, messages } + let tab_width = crate::format::indent_width(path.as_deref(), ws.client_settings()); + Discovered { + path, + options, + line_length, + tab_width, + file, + project, + external, + texts, + messages, + } } /// What this buffer's index and settings make of it: the census oracle and /// the rule ladder, neither of which touches the filesystem. - fn into_run<'a>(self, ws: &'a Workspace, doc: &Document) -> LintRun<'a> { + fn into_run<'a>(self, ws: &'a Workspace, _doc: &Document) -> LintRun<'a> { let index = ws.index(); - let own = doc.path.as_deref().and_then(|path| index.file_id(path)); + let own = self.path.as_deref().and_then(|path| ws.index_file_id(path)); let workspace = index.files().len() > usize::from(own.is_some()); let oracle = workspace.then_some(IndexMentions { index, own }); let rules = enabled_rules(ws.client_settings(), &self.project, workspace); @@ -249,6 +267,7 @@ impl Discovered { LintRun { rules, oracle, + path: self.path, options: self.options, line_length: self.line_length, tab_width: self.tab_width, @@ -283,11 +302,9 @@ impl Discovered { /// a parse and an analysis the same pass already paid for. fn configured( client: &ClientSettings, - doc: &Document, + path: Option<&Path>, ) -> (RuleOptions, usize, FileConfig, Vec) { - let file = doc - .path - .as_deref() + let file = path .and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok()) .unwrap_or_default(); let mut options = RuleOptions::new(); @@ -558,9 +575,20 @@ impl MentionOracle for IndexMentions<'_> { /// document is analyzed on every edit for hover, definition and references, so /// the semantic rules must read *that* analysis rather than run a second one /// per keystroke. +#[cfg(test)] fn context(doc: &Document) -> LintContext<'_> { - LintContext::from_parse(&doc.text, &doc.tokens, &doc.tree, &doc.line_index, doc.path.clone()) - .with_semantics(&doc.semantics) + context_for(doc, doc.path.as_deref()) +} + +fn context_for<'d>(doc: &'d Document, path: Option<&Path>) -> LintContext<'d> { + LintContext::from_parse( + &doc.text, + &doc.tokens, + &doc.tree, + &doc.line_index, + path.map(Path::to_path_buf), + ) + .with_semantics(&doc.semantics) } /// Every violation `run`'s rules find in a buffer. diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index ccaa75f..58020e7 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -229,7 +229,7 @@ pub(crate) fn indexed_def_for_symbol<'a>( doc: &Document, symbol: &Symbol, ) -> Option<&'a Def> { - let file = ws.index().file_id(doc.path.as_deref()?)?; + let file = ws.index_file_id(doc.path.as_deref()?)?; indexed_def_in_file(ws, &doc.semantics, symbol, file) } @@ -292,7 +292,7 @@ fn indexed_references( // Every reference in this buffer is answered against the same indexed // file, so the path lookup — a binary search comparing whole paths — // is taken once per buffer rather than once per reference. - let file = ws.index().file_id(path); + let file = ws.index_file_id(path); for (id, reference) in doc.semantics.references().iter().enumerate() { // A use can only name `target.def` if it spells the name that // declaration declares, and `target.name` is exactly that name. @@ -434,7 +434,7 @@ fn declaring_file_uses(ws: &Workspace, target: &IndexedTarget) -> Option Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; - let Some(path) = doc.path.clone() else { return Vec::new() }; + let Some(doc_path) = doc.path.as_deref() else { return Vec::new() }; + let path = ws.index_path_for(doc_path); // A code-action request arrives on every cursor move, so neither half of // this may walk the workspace. The engine's one-file question answers // "there is nothing here" for almost every position — and where it does @@ -180,7 +181,8 @@ pub fn offers( offset: u32, ) -> Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; - let Some(path) = doc.path.clone() else { return Vec::new() }; + let Some(doc_path) = doc.path.as_deref() else { return Vec::new() }; + let path = ws.index_path_for(doc_path); let modules = modules_at(doc, offset); // A name the workspace declares twice is a refusal the engine makes over // the fan-out, where it can see both declarations. The offer cannot, so it @@ -494,8 +496,9 @@ fn target(ws: &Workspace, argument: Option<&Value>) -> Result<(Uri, PathBuf), St })?; let path = ws .document(&uri) - .and_then(|doc| doc.path.clone()) - .or_else(|| uri_to_path(&uri)) + .and_then(|doc| doc.path.as_deref()) + .map(|path| ws.index_path_for(path)) + .or_else(|| uri_to_path(&uri).map(|path| ws.index_path_for(&path))) .ok_or_else(|| "lucisv can only refactor inside a saved file.".to_string())?; Ok((uri, path)) } @@ -552,7 +555,7 @@ pub(crate) fn encode_edit( ) -> Result { let mut pairs: Vec<(Uri, Option, Vec)> = Vec::new(); for (path, edits) in files { - let open = ws.open_documents().find(|(_, doc)| doc.path.as_deref() == Some(path)); + let open = ws.open_document_for_path(path); let (target, version, mapped) = match open { Some((uri, doc)) => (uri.clone(), doc.version(), map_edits(&doc.positions(), edits)), None => { diff --git a/crates/lucisv_server/src/rename.rs b/crates/lucisv_server/src/rename.rs index a0cf1bf..344ff45 100644 --- a/crates/lucisv_server/src/rename.rs +++ b/crates/lucisv_server/src/rename.rs @@ -78,7 +78,8 @@ pub fn rename_traced_for( trace: &mut Option, ) -> Result<(WorkspaceEdit, Vec), String> { let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?; - let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?; + let path = doc.path.as_deref().ok_or_else(|| UNSAVED.to_string())?; + let path = ws.index_path_for(path); // The engine's own first look at the request, over the buffer it is about // to be handed anyway. It refuses only what `vlog_refactor::rename` is // certain to refuse in the same words — so this is still one voice diff --git a/crates/lucisv_server/src/server/large_file.rs b/crates/lucisv_server/src/server/large_file.rs index f800224..c040243 100644 --- a/crates/lucisv_server/src/server/large_file.rs +++ b/crates/lucisv_server/src/server/large_file.rs @@ -76,8 +76,8 @@ impl Server { OnTypeFormatting::METHOD => to_value(Vec::::new()), WillSaveWaitUntil::METHOD => Ok(Value::Null), // A rename would rewrite every *other* file and leave this one - // untouched — the buffer is not in the index and not in - // `sources()` — so it is refused rather than half-applied. + // untouched — a fast-path buffer holds an empty AST/analysis and + // cannot supply live edits — so it is refused rather than half-applied. // `prepareRename` declines quietly, so the box never opens. PrepareRenameRequest::METHOD => Ok(Value::Null), Rename::METHOD => Err(Failure::Request(TOO_LARGE.to_string())), @@ -164,34 +164,48 @@ impl Server { /// differently from when it was analyzed — normal ↔ large — after the /// settings changed it from `before`; leave every other buffer alone. /// - /// The threshold is read where a `Document` is built, so without this a - /// new value reached a buffer only at its next edit: one opened before - /// the startup's settings answer kept the default's verdict, and a - /// threshold changed mid-session did not move an open buffer at all - /// (`docs/features/fast-actions/README.md`, R1). A flipped buffer goes - /// through the flush's own path — analyzed, its connection located, its - /// diagnostics republished once — and its colours are re-requested. A - /// dirty buffer is skipped: its flush builds it under the new value - /// anyway. Like an edit, this does not reindex: the index takes the new - /// mode at the buffer's next save or rescan — and before the startup scan - /// there is no index yet, so that scan reads every buffer in its settled - /// mode. An unchanged threshold costs one comparison. - pub(super) fn reclassify_large_buffers(&mut self, before: u64) { + /// When a buffer flips from normal (`large == false`) to large + /// (`large == true`) and no full rescan is already owed, its index record + /// is reconciled back to disk (subject to `maxFileSize`, or removed if + /// outside scope/missing) so stale unsaved edits previously indexed do not + /// linger while clean buffers do zero index work (Topo #63). + pub(super) fn reclassify_large_buffers(&mut self, before: u64, rescan: bool) { if self.workspace.client_settings().large_file_threshold == before { return; } - let flipped: Vec<(Uri, String)> = self + let flipped: Vec<(Uri, String, bool)> = self .workspace .open_documents() .filter(|(uri, _)| !self.dirty.iter().any(|(pending, _)| pending == *uri)) .filter(|(_, doc)| self.workspace.is_large(&doc.text) != doc.large) - .map(|(uri, doc)| (uri.clone(), doc.text.clone())) + .map(|(uri, doc)| (uri.clone(), doc.text.clone(), doc.large)) .collect(); if flipped.is_empty() { return; } - for (uri, text) in flipped { - self.analyze_and_publish(uri, text); + let mut index_changed = false; + let scan_owed = self.scan_owed(); + for (uri, text, was_large) in flipped { + let prev_facts = (!was_large && !rescan && !scan_owed) + .then(|| { + let doc = self.workspace.document(&uri)?; + let path = doc.path.as_deref()?; + let held = self.workspace.held_path_for(path)?; + Some((held.clone(), doc.facts(held))) + }) + .flatten(); + self.analyze_and_publish(uri.clone(), text); + if !was_large && scan_owed { + self.rescan_wanted = true; + } else if let Some((held_path, doc_facts)) = prev_facts { + index_changed |= + self.workspace.reconcile_large_buffer(&uri, &held_path, &doc_facts); + } + } + if index_changed { + self.refresh_code_lenses(); + self.hierarchy_index_changed(); + self.republish_all(); } if self.abilities.semantic_tokens_refresh { self.send_request(SemanticTokensRefresh::METHOD, ()); diff --git a/crates/lucisv_server/src/server/notification.rs b/crates/lucisv_server/src/server/notification.rs index a6c795e..ae3019c 100644 --- a/crates/lucisv_server/src/server/notification.rs +++ b/crates/lucisv_server/src/server/notification.rs @@ -65,9 +65,9 @@ impl Server { self.auto_styles.notice(¬ification); // Everything but a `didChange` needs the buffers' analyses current — // a `didSave` rebuilds the index on top of them — so the same flush a - // request gets happens here, with the one exception that *is* the - // thing being deferred. - if method != DidChangeTextDocument::METHOD { + // request gets happens here, with `didChange` (deferred) and `didClose` + // (flushed inside its match arm right after index reconciliation). + if method != DidChangeTextDocument::METHOD && method != DidCloseTextDocument::METHOD { self.flush_dirty(); self.sync_document_versions(); } @@ -283,15 +283,36 @@ impl Server { let uri = p.text_document.uri; self.versions.remove(&uri); self.config_warnings.remove(&uri); - // The buffer's unanalyzed change is already gone — it was - // dropped at the top of this function, ahead of the flush - // that would otherwise have analyzed it. - // // The remembered token answer goes with the buffer: the // client drops what it was holding too, and nothing may // grow with the number of files ever opened. self.tokens.remove(&uri); - self.workspace.close_document(&uri); + let rescan_owed = + self.scanning && self.workspace.closing_affects_running_scan(&uri); + let index_changed = self.workspace.close_and_reconcile(&uri, !self.scan_owed()); + let remaining_unflushed: Vec = if index_changed { + self.workspace + .open_uris() + .into_iter() + .filter(|open| !self.dirty.iter().any(|(pending, _)| pending == open)) + .collect() + } else { + Vec::new() + }; + self.flush_dirty(); + self.sync_document_versions(); + if rescan_owed { + self.rescan_wanted = true; + } else if index_changed { + self.refresh_code_lenses(); + self.hierarchy_index_changed(); + if !remaining_unflushed.is_empty() { + self.generation += 1; + for open in remaining_unflushed { + self.publish(&open); + } + } + } // Clear what we drew: the buffer is gone. self.send_diagnostics(uri, Vec::new()); } @@ -363,7 +384,7 @@ impl Server { let rescan = self.workspace.set_client_settings(settings); // Before the rescan, so the index takes each buffer in the mode the // new threshold gives it. - self.reclassify_large_buffers(threshold); + self.reclassify_large_buffers(threshold, rescan); self.sync_document_versions(); if rescan { self.reindex(); diff --git a/crates/lucisv_server/src/server/tests/lifecycle_r2.rs b/crates/lucisv_server/src/server/tests/lifecycle_r2.rs new file mode 100644 index 0000000..771ce23 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/lifecycle_r2.rs @@ -0,0 +1,2794 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! Regression, differential, symlink, and performance proofs for Round 2 +//! (`docs/features/index-lifecycle-r2/README.md`: Topo #49, #63, #50, #51). + +use std::time::{Duration, Instant}; + +use super::super::probe; +use super::scan_ordering::{closed, opened, ordering_tree, settle}; +use super::startup::{configuration_answer, did_open}; +use super::*; + +fn wide_with_exclude(exclude: Vec) -> ClientSettings { + ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + exclude, + ..Default::default() + } +} + +fn wide_large(threshold: u64, max_file_size: u64) -> ClientSettings { + ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + large_file_threshold: threshold, + max_file_size, + ..Default::default() + } +} + +fn sym_names(session: &mut Session, query: &str) -> Vec<(String, String)> { + let val = session.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({ "query": query })); + let mut items: Vec<(String, String)> = val + .as_array() + .expect("array") + .iter() + .map(|s| { + ( + s["name"].as_str().expect("name").to_string(), + s["location"]["uri"].as_str().expect("uri").to_string(), + ) + }) + .collect(); + items.sort(); + items +} + +fn save_note(uri: &Uri) -> Message { + Message::Notification(Notification::new( + DidSaveTextDocument::METHOD.to_string(), + serde_json::json!({ "textDocument": { "uri": uri } }), + )) +} + +fn change_full(session: &mut Session, uri: &Uri, version: i32, text: &str) { + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": version }, + "contentChanges": [{ "text": text }], + }), + ); +} + +#[test] +fn topo_49_did_close_removes_excluded_and_unlisted_buffers_and_matches_fresh() { + // 1. Excluded via lucisv.exclude: opened before scan -> indexed -> didClose removes cleanly. + let tree = Tree::new("t49_excl"); + tree.package("rtl/keep.sv", "keep_pkg"); + tree.package("ignored/secret.sv", "secret_pkg"); + let excl_path = tree.path.join("ignored/secret.sv"); + let excl_text = std::fs::read_to_string(&excl_path).expect("read"); + let settings = wide_with_exclude(vec!["ignored/**".into()]); + + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "workspace" }, + "exclude": ["ignored/**"] + })), + did_open(&excl_path, &excl_text), + ], + ); + let _ = settled.drain(); + assert_eq!(settled.server.workspace.index().units("secret_pkg").len(), 1); + + let excl_uri = path_to_uri(&excl_path).expect("uri"); + settled.batch(vec![closed(&excl_uri)]); + let fresh = Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings); + assert_eq!(settled.server.workspace.index().units("secret_pkg").len(), 0); + assert_eq!( + settled.server.workspace.derived_fingerprint(), + fresh.server.workspace.derived_fingerprint(), + "excluded open->scan->close must equal fresh without it" + ); + + // 2. Unlisted via lucisv.filelist, taken in via didSave, then closed -> removed. + let fl_tree = Tree::new("t49_fl"); + fl_tree.package("rtl/a.sv", "a_pkg"); + fl_tree.package("rtl/unlisted.sv", "unlisted_pkg"); + fl_tree.write("files.f", "rtl/a.sv\n"); + let fl_settings = ClientSettings { filelist: Some("files.f".into()), ..Default::default() }; + let mut fl_settled = Session::started( + vec![fl_tree.path.clone()], + ClientAbilities::default(), + fl_settings.clone(), + ); + let _ = fl_settled.drain(); + let unl_path = fl_tree.path.join("rtl/unlisted.sv"); + let unl_uri = fl_settled.open(&unl_path, &std::fs::read_to_string(&unl_path).expect("read")); + fl_settled.notify( + DidSaveTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": &unl_uri } }), + ); + assert_eq!(fl_settled.server.workspace.index().units("unlisted_pkg").len(), 1); + fl_settled.batch(vec![closed(&unl_uri)]); + let fl_fresh = + Session::started(vec![fl_tree.path.clone()], ClientAbilities::default(), fl_settings); + assert_eq!(fl_settled.server.workspace.index().units("unlisted_pkg").len(), 0); + assert_eq!( + fl_settled.server.workspace.derived_fingerprint(), + fl_fresh.server.workspace.derived_fingerprint() + ); +} + +#[test] +fn topo_49_did_close_dirty_unsaved_in_scope_reverts_to_disk_and_removes_if_missing() { + let tree = Tree::new("t49_dirty"); + tree.write("rtl/a.sv", "package a;\n localparam ON_DISK = 1;\nendpackage\n"); + tree.write("rtl/vanish.sv", "module vanish;\nendmodule\n"); + let a_path = tree.path.join("rtl/a.sv"); + let v_path = tree.path.join("rtl/vanish.sv"); + + let wide = wide_large(0, 1024 * 1024); + let mut settled = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), wide.clone()); + let _ = settled.drain(); + + // Dirty unsaved edit indexed during a whole rescan, then closed without saving. + let a_uri = settled.open(&a_path, "package a;\n localparam IN_BUF = 1;\nendpackage\n"); + let _ = settled.open(&v_path, "module vanish;\nendmodule\n"); + settled.server.workspace.rebuild_index(); + assert_eq!(settled.server.workspace.index().member("a", "IN_BUF").len(), 1); + assert_eq!(settled.server.workspace.index().member("a", "ON_DISK").len(), 0); + + // Close dirty in-scope buffer -> reverts to disk via localized replace_facts. + settled.batch(vec![closed(&a_uri)]); + assert_eq!(settled.server.workspace.index().member("a", "ON_DISK").len(), 1); + assert_eq!(settled.server.workspace.index().member("a", "IN_BUF").len(), 0); + + // Delete vanish.sv from disk and close its open buffer -> removed via fast tombstone. + let v_uri = path_to_uri(&v_path).expect("uri"); + std::fs::remove_file(&v_path).expect("remove"); + settled.batch(vec![closed(&v_uri)]); + let fresh = Session::started(vec![tree.path.clone()], ClientAbilities::default(), wide); + assert_eq!( + settled.server.workspace.derived_fingerprint(), + fresh.server.workspace.derived_fingerprint() + ); +} + +#[test] +fn topo_49_did_close_excluded_or_dirty_mid_scan_matches_fresh() { + let tree = ordering_tree("t49_midclose"); + tree.package("ignored/e.sv", "excluded_pkg"); + let e_path = tree.path.join("ignored/e.sv"); + let e_text = std::fs::read_to_string(&e_path).expect("read"); + let e_uri = path_to_uri(&e_path).expect("uri"); + let a_path = tree.path.join("a/a.sv"); + let a_uri = path_to_uri(&a_path).expect("uri"); + + let _ = probe::take_counts(); + probe::script([vec![closed(&e_uri), closed(&a_uri)]]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "workspace" }, + "exclude": ["ignored/**"] + })), + did_open(&e_path, &e_text), + did_open(&a_path, "module amod_unsaved;\nendmodule\n"), + ], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty(), "closes landed mid-scan"); + settle(&mut settled); + + let fresh = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + wide_with_exclude(vec!["ignored/**".into()]), + ); + assert_eq!(settled.server.workspace.index().units("excluded_pkg").len(), 0); + assert_eq!(settled.server.workspace.index().units("amod_unsaved").len(), 0); + assert_eq!(settled.server.workspace.index().units("amod").len(), 1); + assert_eq!( + settled.server.workspace.derived_fingerprint(), + fresh.server.workspace.derived_fingerprint() + ); +} + +#[test] +fn topo_49_two_thousand_open_close_cycles_on_4k_index_stay_fast_and_match_fresh() { + let tree = Tree::new("t49_perf_2k"); + for i in 0..2_000 { + tree.package(&format!("rtl/keep_{i:04}.sv"), &format!("keep_{i:04}")); + tree.package(&format!("ignored/excl_{i:04}.sv"), &format!("excl_{i:04}")); + } + + let mut ws = crate::state::Workspace::default(); + ws.set_client_settings(wide_with_exclude(vec!["ignored/**".into()])); + // Open all 2,000 excluded buffers before initial scan so all 4,000 files sit in the index. + let mut excl_uris = Vec::with_capacity(2_000); + for i in 0..2_000 { + let p = tree.path.join(format!("ignored/excl_{i:04}.sv")); + let uri = path_to_uri(&p).expect("uri"); + let text = std::fs::read_to_string(&p).expect("read"); + ws.set_document(uri.clone(), text); + excl_uris.push(uri); + } + ws.open_whole_workspace(vec![tree.path.clone()]); + assert_eq!(ws.index().files().len(), 4_000); + + // 1. Tombstoned close of 2,000 excluded files on a 4,000-file index (< 5ms per close). + let remove_started = Instant::now(); + for uri in &excl_uris { + assert!(ws.close_and_reconcile(uri, true)); + } + let remove_elapsed = remove_started.elapsed(); + let mean_remove = remove_elapsed / 2_000; + eprintln!("2,000 tombstoned didClose removals on 4k index: {mean_remove:?} each ({remove_elapsed:?} total)"); + let max_mean = + if cfg!(debug_assertions) { Duration::from_millis(25) } else { Duration::from_millis(5) }; + assert!( + mean_remove < max_mean, + "2,000 tombstoned didClose removals on 4k index took {mean_remove:?} each ({remove_elapsed:?} total)" + ); + assert_eq!(ws.index().files().len(), 2_000); + + // 2. 2,000 clean in-scope open + close cycles also stay fast and match fresh build. + let cycle_started = Instant::now(); + for i in 0..2_000 { + let p = tree.path.join(format!("rtl/keep_{i:04}.sv")); + let uri = path_to_uri(&p).expect("uri"); + let text = std::fs::read_to_string(&p).expect("read"); + ws.set_document(uri.clone(), text); + let _ = ws.close_and_reconcile(&uri, true); + } + let cycle_elapsed = cycle_started.elapsed(); + let mean_cycle = cycle_elapsed / 2_000; + eprintln!("2,000 in-scope open+close cycles on 2k index: {mean_cycle:?} each ({cycle_elapsed:?} total)"); + assert!( + mean_cycle < Duration::from_millis(5), + "2,000 in-scope open+close cycles took {mean_cycle:?} each ({cycle_elapsed:?} total)" + ); + + let mut fresh = crate::state::Workspace::default(); + fresh.set_client_settings(wide_with_exclude(vec!["ignored/**".into()])); + fresh.open_whole_workspace(vec![tree.path.clone()]); + assert_eq!(ws.derived_fingerprint(), fresh.derived_fingerprint()); +} + +#[test] +fn topo_63_large_buffer_keeps_disk_record_across_open_save_close_threshold_flip_and_widen() { + let tree = Tree::new("t63_diff"); + let big_disk = format!( + "package big_pkg;\n localparam ON_DISK = 1;\n{}endpackage\n", + " // filler line\n".repeat(40) + ); + tree.write("rtl/big.sv", &big_disk); + tree.write( + "rtl/user.sv", + "module user;\n import big_pkg::*;\n localparam X = ON_DISK;\nendmodule\n", + ); + tree.write("excl/unseen.sv", &big_disk); + let big_path = tree.path.join("rtl/big.sv"); + let user_path = tree.path.join("rtl/user.sv"); + let excl_path = tree.path.join("excl/unseen.sv"); + let big_uri = path_to_uri(&big_path).expect("uri"); + let user_uri = path_to_uri(&user_path).expect("uri"); + let excl_uri = path_to_uri(&excl_path).expect("uri"); + + let cap = 1024 * 1024; + let settings = ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + exclude: vec!["excl/**".into()], + large_file_threshold: 200, + max_file_size: cap, + ..Default::default() + }; + + let check_parity = |settled: &mut Session, cur_settings: ClientSettings, label: &str| { + let mut fresh = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), cur_settings); + let _ = fresh.drain(); + let _ = fresh.open(&user_path, &std::fs::read_to_string(&user_path).expect("read")); + assert_eq!( + settled.server.workspace.index().fingerprint(), + fresh.server.workspace.index().fingerprint(), + "index fingerprint mismatch at {label}" + ); + assert_eq!(sym_names(settled, "big_pkg"), sym_names(&mut fresh, "big_pkg"), "{label}"); + let def_pos = serde_json::json!({ + "textDocument": { "uri": &user_uri }, + "position": { "line": 2, "character": 18 } + }); + assert_eq!( + settled.result(GotoDefinition::METHOD, def_pos.clone()), + fresh.result(GotoDefinition::METHOD, def_pos), + "cross-file goto-definition mismatch at {label}" + ); + }; + + let mut settled = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings.clone()); + let _ = settled.drain(); + let _ = settled.open(&user_path, &std::fs::read_to_string(&user_path).expect("read")); + let fp_initial = settled.server.workspace.index().fingerprint(); + + // 1. Open in-scope large file and excluded large file -> ZERO index mutation. + let unsaved_big = format!("{big_disk}// unsaved\n"); + settled.open(&big_path, &unsaved_big); + settled.open(&excl_path, &big_disk); + assert!(settled.server.workspace.document(&big_uri).expect("open").large); + assert_eq!(settled.server.workspace.index().fingerprint(), fp_initial); + check_parity(&mut settled, settings.clone(), "after didOpen doc.large"); + + // 2. Flip largeFile.threshold (large -> normal -> large) -> ZERO index mutation on clean disk. + let high_thresh = ClientSettings { large_file_threshold: 100_000, ..settings.clone() }; + settled.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { + "index": { "scope": "workspace", "maxFileSize": cap }, + "exclude": ["excl/**"], + "largeFile": { "threshold": 100_000 } + } } }), + ); + assert!(!settled.server.workspace.document(&big_uri).expect("open").large); + assert_eq!(settled.server.workspace.index().fingerprint(), fp_initial); + settled.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { + "index": { "scope": "workspace", "maxFileSize": cap }, + "exclude": ["excl/**"], + "largeFile": { "threshold": 200 } + } } }), + ); + assert!(settled.server.workspace.document(&big_uri).expect("open").large); + assert_eq!(settled.server.workspace.index().fingerprint(), fp_initial); + let _ = high_thresh; + + // 3. Save new disk content for doc.large -> updates disk record subject to maxFileSize. + let v2 = big_disk.replace("ON_DISK = 1", "ON_DISK_V2 = 2"); + std::fs::write(&big_path, &v2).expect("write"); + change_full(&mut settled, &big_uri, 2, &v2); + settled.batch(vec![save_note(&big_uri)]); + assert!(settled.server.workspace.document(&big_uri).expect("open").large); + assert_ne!(settled.server.workspace.index().fingerprint(), fp_initial); + check_parity(&mut settled, settings.clone(), "after save while doc.large"); + + // 4. Close both doc.large buffers -> disk record stays identical. + settled.batch(vec![closed(&big_uri), closed(&excl_uri)]); + check_parity(&mut settled, settings.clone(), "after didClose doc.large"); + + // 5. Open doc.large BEFORE initial scan -> identical to closed. + let pre_open = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": cap }, + "exclude": ["excl/**"], + "largeFile": { "threshold": 200 } + })), + did_open(&big_path, &v2), + did_open(&excl_path, &big_disk), + ], + ); + let _ = pre_open.drain(); + assert_eq!( + pre_open.server.workspace.index().fingerprint(), + settled.server.workspace.index().fingerprint() + ); +} + +#[test] +fn topo_63_large_buffer_over_max_file_size_never_indexes_disk_copy() { + let tree = Tree::new("t63_maxcap"); + let huge = format!( + "package capped_pkg;\n localparam K = 1;\n{}endpackage\n", + " // filler line\n".repeat(120) + ); + tree.write("rtl/capped.sv", &huge); + let path = tree.path.join("rtl/capped.sv"); + let settings = wide_large(200, 512); + + let mut settled = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings.clone()); + let _ = settled.drain(); + assert_eq!(settled.server.workspace.index().units("capped_pkg").len(), 0); + + let uri = settled.open(&path, &huge); + assert!(settled.server.workspace.document(&uri).expect("open").large); + settled.batch(vec![save_note(&uri)]); + assert_eq!(settled.server.workspace.index().units("capped_pkg").len(), 0); + settled.batch(vec![closed(&uri)]); + assert_eq!(settled.server.workspace.index().units("capped_pkg").len(), 0); +} + +#[test] +fn topo_50_excluded_and_unlisted_buffers_opened_mid_scan_absorb_like_pre_scan() { + // Workspace with excluded buffer + >INTERLEAVE_ABOVE files so background scan interleaves. + let tree = ordering_tree("t50_unheld"); + let excl_path = tree.path.join("ignored/extra.sv"); + let excl_text = "package mid_scan_pkg;\n localparam K = 7;\nendpackage\n"; + tree.write("ignored/extra.sv", excl_text); + let late_path = tree.path.join("z/p005.sv"); + let late_unsaved = "package p005_unsaved;\n localparam V = 9;\nendpackage\n"; + let early_path = tree.path.join("a/a.sv"); + let early_unsaved = "module amod_mid_unsaved;\n logic z;\nendmodule\n"; + + let excl_uri = path_to_uri(&excl_path).expect("uri"); + let late_uri = path_to_uri(&late_path).expect("uri"); + let early_uri = path_to_uri(&early_path).expect("uri"); + + let _ = probe::take_counts(); + probe::script([ + vec![opened(&excl_uri, excl_text), opened(&late_uri, late_unsaved)], + vec![opened(&early_uri, early_unsaved)], + ]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![configuration_answer(serde_json::json!({ + "index": { "scope": "workspace" }, + "exclude": ["ignored/**"] + }))], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty(), "scripted mid-scan opens must have arrived"); + settle(&mut settled); + + // Fresh session where all three were already open BEFORE startup scan started. + let fresh = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "workspace" }, + "exclude": ["ignored/**"] + })), + did_open(&excl_path, excl_text), + did_open(&late_path, late_unsaved), + did_open(&early_path, early_unsaved), + ], + ); + let _ = fresh.drain(); + + assert_eq!(settled.server.workspace.index().units("mid_scan_pkg").len(), 1); + assert_eq!(settled.server.workspace.index().units("p005_unsaved").len(), 1); + assert_eq!(settled.server.workspace.index().units("amod_mid_unsaved").len(), 1); + assert_eq!( + settled.server.workspace.derived_fingerprint(), + fresh.server.workspace.derived_fingerprint(), + "mid-scan open must match pre-scan open identically" + ); +} + +#[cfg(unix)] +#[test] +fn topo_51_same_name_and_different_name_symlinks_all_six_filelink_scenarios_hold() { + use std::os::unix::fs::symlink; + + for (kind, link_rel, target_rel) in [ + ("same_name", "a_link/dut.sv", "z_real/dut.sv"), + ("different_name", "a_link/eb_dut.sv", "z_real/eg_dut.sv"), + ] { + let base_text = "module dut;\n sub u1 ();\nendmodule\n"; + let edited_text = "module dut;\n sub u1 ();\n wire added;\nendmodule\n"; + let sub_text = "module sub;\nendmodule\n"; + let tb_text = "module tb;\n dut u_dut ();\nendmodule\n"; + + let make_tree = |tag: &str| { + let tree = Tree::new(&format!("t51_{kind}_{tag}")); + tree.write(target_rel, base_text); + tree.write("rtl/sub.sv", sub_text); + tree.write("tb/tb.sv", tb_text); + let link_abs = tree.path.join(link_rel); + std::fs::create_dir_all(link_abs.parent().expect("parent")).expect("dir"); + symlink(tree.path.join(target_rel), &link_abs).expect("symlink"); + tree + }; + + // 1 & 2. Open-only (target or link) BEFORE scan vs AFTER scan -> always ONE canonical spelling (`a_link/...`). + for (who, rel) in [("link", link_rel), ("target", target_rel)] { + let tree = make_tree(&format!("open_{who}")); + let opened_path = tree.path.join(rel); + let canonical_path = tree.path.join(link_rel); + + // After scan + let mut after = Session::started( + vec![tree.path.clone()], + ClientAbilities { + file_watching: true, + work_done_progress: true, + ..Default::default() + }, + wide_large(0, 1024 * 1024), + ); + let _ = after.drain(); + assert_eq!(after.server.workspace.index().units("dut").len(), 1, "{kind}/{who}"); + assert_eq!(after.server.workspace.index().files().len(), 3, "{kind}/{who}"); + assert!( + after.server.workspace.index().file_id(&canonical_path).is_some(), + "canonical spelling wins when closed: {kind}/{who}" + ); + let opened_uri = after.open(&opened_path, base_text); + assert_eq!(after.server.workspace.index().files().len(), 3); + + // Before scan + let before = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ "index": { "scope": "workspace" } })), + did_open(&opened_path, base_text), + ], + ); + let _ = before.drain(); + assert_eq!( + after.server.workspace.index().fingerprint(), + before.server.workspace.index().fingerprint(), + "{kind}/{who} open-after vs open-before scan" + ); + + // 3 & 4. Editor edit + didSave via target OR link -> localized update keeping one canonical spelling! + change_full(&mut after, &opened_uri, 2, edited_text); + std::fs::write(&opened_path, edited_text).expect("write"); + after.batch(vec![save_note(&opened_uri)]); + assert!(after.progress().is_empty(), "incremental one-file update on symlinked buffer"); + assert_eq!(after.server.workspace.index().units("dut").len(), 1); + assert_eq!( + after.server.workspace.index().files_mentioning("added").count(), + 1, + "{kind}/{who} edit/save landed" + ); + + let fresh_after_save = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + wide_large(0, 1024 * 1024), + ); + let _ = fresh_after_save.drain(); + assert_eq!( + after.server.workspace.index().fingerprint(), + fresh_after_save.server.workspace.index().fingerprint(), + "{kind}/{who} post-save matches fresh" + ); + + // Close reverts/keeps parity with disk cleanly. + after.batch(vec![closed(&opened_uri)]); + assert_eq!( + after.server.workspace.index().fingerprint(), + fresh_after_save.server.workspace.index().fingerprint(), + "{kind}/{who} post-close matches fresh" + ); + } + + // 5 & 6. Disk watcher event reported via EITHER target OR link -> one-file incremental update, zero rescan! + for (who, rel) in [("link_disk", link_rel), ("target_disk", target_rel)] { + let tree = make_tree(who); + let mut session = Session::started( + vec![tree.path.clone()], + ClientAbilities { + file_watching: true, + work_done_progress: true, + ..Default::default() + }, + wide_large(0, 1024 * 1024), + ); + let _ = session.drain(); + std::fs::write(tree.path.join(target_rel), edited_text).expect("disk write"); + session.watched(&[tree.path.join(rel)]); + assert!(session.progress().is_empty(), "{kind}/{who} watcher takes one-file path"); + let fresh = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + wide_large(0, 1024 * 1024), + ); + let _ = fresh.drain(); + assert_eq!( + session.server.workspace.index().fingerprint(), + fresh.server.workspace.index().fingerprint(), + "{kind}/{who} disk watcher matches fresh" + ); + } + } +} + +#[cfg(unix)] +#[test] +fn topo_51_widen_and_filelist_converge_to_one_canonical_symlink_spelling() { + use std::os::unix::fs::symlink; + + let tree = Tree::new("t51_widen_fl"); + tree.write("z_real/real.sv", "module m;\nendmodule\n"); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/real.sv"), tree.path.join("a_link/alias.sv")).expect("symlink"); + tree.write("a_link/other.sv", "module other;\nendmodule\n"); + tree.write("files.f", "z_real/real.sv\na_link/alias.sv\n"); + + // 1. Folder scope widen: open z_real/real.sv first, then widen into a_link/other.sv. + let mut widened = crate::state::Workspace::default(); + widened.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() }); + widened.open_roots(vec![tree.path.clone()]); + let z_uri = path_to_uri(&tree.path.join("z_real/real.sv")).expect("uri"); + let a_other_uri = path_to_uri(&tree.path.join("a_link/other.sv")).expect("uri"); + widened.set_document(z_uri.clone(), "module m;\nendmodule\n".into()); + widened.rebuild_index(); + assert_eq!(widened.index().files(), &[tree.path.join("z_real/real.sv")]); + + widened.set_document(a_other_uri.clone(), "module other;\nendmodule\n".into()); + let scan = widened.begin_widen(&[tree.path.join("a_link")], &mut |_| {}, false); + let mut scan = scan; + while widened.scan_step(&mut scan, &mut |_| {}) {} + widened.finish_scan(scan); + + let mut fresh = crate::state::Workspace::default(); + fresh.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() }); + fresh.open_roots(vec![tree.path.clone()]); + fresh.set_document(z_uri, "module m;\nendmodule\n".into()); + fresh.set_document(a_other_uri, "module other;\nendmodule\n".into()); + fresh.rebuild_index(); + assert_eq!(widened.index().fingerprint(), fresh.index().fingerprint()); + assert_eq!(widened.index().units("m").len(), 1); + assert!(widened.index().file_id(&tree.path.join("a_link/alias.sv")).is_some()); + + // 2. Filelist deduplication across different-name symlinks. + let mut fl = crate::state::Workspace::default(); + fl.set_client_settings(ClientSettings { + filelist: Some("files.f".into()), + ..Default::default() + }); + fl.open_roots(vec![tree.path.clone()]); + assert_eq!(fl.index().units("m").len(), 1); + assert_eq!(fl.index().files(), &[tree.path.join("a_link/alias.sv")]); +} + +#[test] +fn qa_topo_49_tombstone_at_zero_and_middle_navigation_symbols_hierarchy_codelens_diagnostics_completion( +) { + let tree = Tree::new("qa_t49_lsp"); + let a_excl = "`define Z_MAC 99\npackage a_excl_pkg;\n localparam EXCL_K = 1;\nendpackage\n"; + let b_pkg = + "package b_pkg;\n typedef logic [7:0] word_t;\nendpackage\nmodule sub;\nendmodule\n"; + let m_excl = "package m_excl_pkg;\nendpackage\n"; + let m_use = "module m_use;\n import b_pkg::*;\n word_t w;\n sub u1 ();\nendmodule\n"; + let z_macros = "`define Z_MAC 42\nmodule z_top;\n sub u2 ();\n logic dead_sig;\nendmodule\n"; + + tree.write("ignored/a_excl.sv", a_excl); + tree.write("b_pkg.sv", b_pkg); + tree.write("ignored/m_excl.sv", m_excl); + tree.write("m_use.sv", m_use); + tree.write("z_macros.sv", z_macros); + + let a_path = tree.path.join("ignored/a_excl.sv"); + let b_path = tree.path.join("b_pkg.sv"); + let m_excl_path = tree.path.join("ignored/m_excl.sv"); + let m_use_path = tree.path.join("m_use.sv"); + let z_path = tree.path.join("z_macros.sv"); + let settings = wide_with_exclude(vec!["ignored/**".into()]); + + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "workspace" }, + "exclude": ["ignored/**"] + })), + did_open(&a_path, a_excl), + did_open(&m_excl_path, m_excl), + ], + ); + let _ = settled.drain(); + // Close both excluded files -> tombstones at FileId(0) and FileId(2); z_macros.sv stays at FileId(4) while files().len() == 3! + let a_uri = path_to_uri(&a_path).expect("uri"); + let m_excl_uri = path_to_uri(&m_excl_path).expect("uri"); + settled.batch(vec![closed(&a_uri), closed(&m_excl_uri)]); + assert_eq!(settled.server.workspace.index().files().len(), 3); + assert_eq!(settled.server.workspace.index().file_id(&z_path), Some(vlog_semantic::FileId(4))); + + let mut fresh = Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings); + let _ = fresh.drain(); + + // Open live files in both sessions and compare every LSP surface. + let b_uri = settled.open(&b_path, b_pkg); + let _ = fresh.open(&b_path, b_pkg); + let m_use_uri = settled.open(&m_use_path, m_use); + let _ = fresh.open(&m_use_path, m_use); + let z_uri = settled.open(&z_path, z_macros); + let _ = fresh.open(&z_path, z_macros); + + // 1. textDocument/definition from m_use.sv -> word_t in b_pkg.sv + let def_params = serde_json::json!({ + "textDocument": { "uri": &m_use_uri }, + "position": { "line": 2, "character": 3 } + }); + assert_eq!( + settled.result(GotoDefinition::METHOD, def_params.clone()), + fresh.result(GotoDefinition::METHOD, def_params) + ); + + // 2. textDocument/references on `sub` in b_pkg.sv (referenced from m_use.sv and z_macros.sv at FileId(4)) + let ref_params = serde_json::json!({ + "textDocument": { "uri": &b_uri }, + "position": { "line": 3, "character": 7 }, + "context": { "includeDeclaration": true } + }); + assert_eq!( + settled.result(References::METHOD, ref_params.clone()), + fresh.result(References::METHOD, ref_params) + ); + + // 3. textDocument/completion on `` `Z_ `` in m_use.sv (after tombstone!) + change_full( + &mut settled, + &m_use_uri, + 2, + "module m_use;\n import b_pkg::*;\n word_t w;\n `Z_\nendmodule\n", + ); + change_full( + &mut fresh, + &m_use_uri, + 2, + "module m_use;\n import b_pkg::*;\n word_t w;\n `Z_\nendmodule\n", + ); + settled.server.flush_dirty(); + fresh.server.flush_dirty(); + let comp_params = serde_json::json!({ + "textDocument": { "uri": &m_use_uri }, + "position": { "line": 3, "character": 5 } + }); + assert_eq!( + settled.result(Completion::METHOD, comp_params.clone()), + fresh.result(Completion::METHOD, comp_params), + "macro completion must survive tombstones and revert Z_MAC detail from 99 to 42" + ); + change_full(&mut settled, &m_use_uri, 3, m_use); + change_full(&mut fresh, &m_use_uri, 3, m_use); + settled.server.flush_dirty(); + fresh.server.flush_dirty(); + + // 4. workspace/symbol + assert_eq!(sym_names(&mut settled, ""), sym_names(&mut fresh, "")); + + // 5. lucisv/moduleHierarchy + let settled_h = settled.result(crate::design_hierarchy::METHOD, Value::Null); + let fresh_h = fresh.result(crate::design_hierarchy::METHOD, Value::Null); + assert_eq!(settled_h["files"], fresh_h["files"]); + assert_eq!(settled_h["modules"], fresh_h["modules"]); + + // 6. textDocument/codeLens + let lens_params = serde_json::json!({ "textDocument": { "uri": &b_uri } }); + assert_eq!( + settled.result(CodeLensRequest::METHOD, lens_params.clone()), + fresh.result(CodeLensRequest::METHOD, lens_params) + ); + + // 7. Diagnostics (`unused-signal` on dead_sig in z_macros.sv at FileId(4)) + assert_eq!( + serde_json::to_value(settled.server.diagnostics_of(&z_uri)).expect("json"), + serde_json::to_value(fresh.server.diagnostics_of(&z_uri)).expect("json") + ); +} + +#[test] +fn qa_topo_49_tombstone_before_live_macro_breaks_rename_macro_text_fanout() { + let tree = Tree::new("qa_t49_rename_mac"); + let a_excl = "package a_excl_pkg;\nendpackage\n"; + let b_mod = "module b_mod;\n logic target_sig;\n assign target_sig = 1'b0;\nendmodule\n"; + let z_mac = "`define USE_TARGET target_sig\nmodule z_other;\nendmodule\n"; + tree.write("ignored/a_excl.sv", a_excl); + tree.write("b_mod.sv", b_mod); + tree.write("z_mac.sv", z_mac); + + let a_path = tree.path.join("ignored/a_excl.sv"); + let b_path = tree.path.join("b_mod.sv"); + let settings = wide_with_exclude(vec!["ignored/**".into()]); + + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "workspace" }, + "exclude": ["ignored/**"] + })), + did_open(&a_path, a_excl), + ], + ); + let _ = settled.drain(); + settled.batch(vec![closed(&path_to_uri(&a_path).expect("uri"))]); + assert_eq!(settled.server.workspace.index().files().len(), 2); + assert_eq!( + settled.server.workspace.index().file_id(&tree.path.join("z_mac.sv")), + Some(vlog_semantic::FileId(2)) + ); + + let mut fresh = Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings); + let _ = fresh.drain(); + + let b_uri = settled.open(&b_path, b_mod); + let _ = fresh.open(&b_path, b_mod); + let offset = b_mod.find("target_sig").expect("pos") as u32; + let (_, settled_warnings) = crate::rename::rename_traced( + &settled.server.workspace, + &b_uri, + offset, + "renamed_sig", + &mut None, + ) + .expect("rename"); + let (_, fresh_warnings) = crate::rename::rename_traced( + &fresh.server.workspace, + &b_uri, + offset, + "renamed_sig", + &mut None, + ) + .expect("rename"); + assert_eq!( + settled_warnings, fresh_warnings, + "want_macro_text (state/sources.rs:338) skips FileId(2) when files().len() == 2" + ); +} + +#[test] +fn qa_topo_49_candidates_macros_of_breaks_when_tombstone_precedes_live_macro_file() { + let mut index = vlog_semantic::WorkspaceIndex::build([ + (PathBuf::from("a_excl.sv"), "module a_excl;\nendmodule\n"), + (PathBuf::from("z_mac.sv"), "`define LIVE_MAC 1\nmodule z_mac;\nendmodule\n"), + ]); + assert!(index.remove_file(Path::new("a_excl.sv"))); + assert_eq!(index.files().len(), 1); + assert_eq!(index.file_id(Path::new("z_mac.sv")), Some(vlog_semantic::FileId(1))); + + let mut map = std::collections::HashMap::new(); + map.insert(PathBuf::from("z_mac.sv"), vec!["z_mac".to_string()]); + let candidates = crate::candidates::Candidates::from_words(&index, map); + let macro_names: Vec<&str> = candidates.macros("").iter().map(|m| m.name.as_str()).collect(); + assert_eq!( + macro_names, + vec!["LIVE_MAC"], + "macros_of (candidates.rs:837) skips FileId(1) when files().len() == 1" + ); + + let mut full_index = vlog_semantic::WorkspaceIndex::build([ + (PathBuf::from("a_excl.sv"), "`define EXCL_MAC 1\nmodule a_excl;\nendmodule\n"), + (PathBuf::from("z_mac.sv"), "`define LIVE_MAC 1\nmodule z_mac;\nendmodule\n"), + ]); + let mut full_map = std::collections::HashMap::new(); + full_map.insert(PathBuf::from("a_excl.sv"), vec!["a_excl".to_string()]); + full_map.insert(PathBuf::from("z_mac.sv"), vec!["z_mac".to_string()]); + let mut removed_candidates = crate::candidates::Candidates::from_words(&full_index, full_map); + assert!(full_index.remove_file(Path::new("a_excl.sv"))); + removed_candidates.remove_file(&full_index, Path::new("a_excl.sv")); + let remaining_macros: Vec<&str> = + removed_candidates.macros("").iter().map(|m| m.name.as_str()).collect(); + assert_eq!(remaining_macros, vec!["LIVE_MAC"]); +} + +#[test] +fn qa_topo_63_all_paths_and_threshold_drop_after_unsaved_edit() { + let tree = Tree::new("qa_t63_all"); + let small_disk = "package p_flip;\n localparam ON_DISK = 1;\nendpackage\n"; + let unsaved_edit = "package p_flip;\n localparam IN_BUF = 2;\nendpackage\n"; + tree.write("rtl/p.sv", small_disk); + tree.package("lib/q.sv", "q_pkg"); + let p_path = tree.path.join("rtl/p.sv"); + let q_path = tree.path.join("lib/q.sv"); + let p_uri = path_to_uri(&p_path).expect("uri"); + + // (g) maxFileSize < len <= largeFile.threshold, then threshold drops below len. + let tree_g = Tree::new("qa_t63_g"); + let mid = + format!("package mid_pkg;\n localparam K = 1;\n{}endpackage\n", " // pad\n".repeat(15)); + assert!(mid.len() > 100 && mid.len() < 400); + tree_g.write("rtl/mid.sv", &mid); + let mid_path = tree_g.path.join("rtl/mid.sv"); + let mut s_g = Session::started( + vec![tree_g.path.clone()], + ClientAbilities::default(), + wide_large(400, 100), + ); + let _ = s_g.drain(); + assert_eq!( + s_g.server.workspace.index().units("mid_pkg").len(), + 0, + "disk skipped by maxFileSize" + ); + let mid_uri = s_g.open(&mid_path, &mid); + assert!(!s_g.server.workspace.document(&mid_uri).expect("open").large); + s_g.batch(vec![save_note(&mid_uri)]); + assert_eq!( + s_g.server.workspace.index().units("mid_pkg").len(), + 1, + "open non-large overrides maxFileSize" + ); + s_g.batch(vec![closed(&mid_uri)]); + assert_eq!( + s_g.server.workspace.index().units("mid_pkg").len(), + 0, + "close removes over-maxFileSize file" + ); + + // (d) subtle attack: small unsaved edit indexed via widen, then threshold drops so doc.large=true without rescan. + let mut s = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + ClientSettings { + index_scope_depth: 0, + large_file_threshold: 500, + max_file_size: 1024 * 1024, + ..Default::default() + }, + ); + let _ = s.drain(); + s.open(&p_path, unsaved_edit); + assert!(!s.server.workspace.document(&p_uri).expect("open").large); + assert_eq!(s.server.workspace.index().member("p_flip", "IN_BUF").len(), 1); + s.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { + "index": { "scopeDepth": 0, "maxFileSize": 1024 * 1024 }, + "largeFile": { "threshold": 10 } + } } }), + ); + assert!(s.server.workspace.document(&p_uri).expect("open").large); + // Widen reconciles doc.large back to disk, and fresh session indexes ON_DISK. + s.open(&q_path, "package q_pkg;\n localparam K = 1;\nendpackage\n"); + assert_eq!(s.server.workspace.index().member("p_flip", "ON_DISK").len(), 1); + assert_eq!(s.server.workspace.index().member("p_flip", "IN_BUF").len(), 0); +} + +#[test] +fn qa_topo_50_first_scope_passed_unreached_and_mid_scan_close() { + // 1. Open excluded, out-of-root, and unsaved modified in-scope during first_scope (head = a/a.sv). + let tree = ordering_tree("qa_t50_all"); + let out_tree = Tree::new("qa_t50_out"); + out_tree.package("outside.sv", "out_pkg"); + tree.package("ignored/excl.sv", "excl_pkg"); + + let a_path = tree.path.join("a/a.sv"); + let b_path = tree.path.join("b/b.sv"); + let late_path = tree.path.join("z/p005.sv"); + let excl_path = tree.path.join("ignored/excl.sv"); + let out_path = out_tree.path.join("outside.sv"); + + let b_unsaved = "module bmod_unsaved;\nendmodule\n"; + let late_unsaved = "package p005_qa;\n localparam Q = 1;\nendpackage\n"; + let excl_text = std::fs::read_to_string(&excl_path).expect("read"); + let out_text = std::fs::read_to_string(&out_path).expect("read"); + + let b_uri = path_to_uri(&b_path).expect("uri"); + let late_uri = path_to_uri(&late_path).expect("uri"); + let excl_uri = path_to_uri(&excl_path).expect("uri"); + let out_uri = path_to_uri(&out_path).expect("uri"); + + // Script: at interleave 1 (while first_scope is scanning a/a.sv), open b (unsaved), late (unsaved), excl, out; + // then at interleave 3 close excl and out mid-scan before finish_whole_scan! + let _ = probe::take_counts(); + probe::script([ + vec![ + opened(&b_uri, b_unsaved), + opened(&late_uri, late_unsaved), + opened(&excl_uri, &excl_text), + opened(&out_uri, &out_text), + ], + vec![], + vec![closed(&excl_uri), closed(&out_uri)], + ]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "workspace" }, + "exclude": ["ignored/**"] + })), + did_open(&a_path, super::scan_ordering::A_TEXT), + ], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty()); + settle(&mut settled); + + let fresh = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "workspace" }, + "exclude": ["ignored/**"] + })), + did_open(&a_path, super::scan_ordering::A_TEXT), + did_open(&b_path, b_unsaved), + did_open(&late_path, late_unsaved), + ], + ); + let _ = fresh.drain(); + assert_eq!( + settled.server.workspace.derived_fingerprint(), + fresh.server.workspace.derived_fingerprint() + ); + + // 2. Also test unsaved in-scope buffer opened AFTER scan.at passed AND AFTER publish_scan already ran! + let tree2 = ordering_tree("qa_t50_published"); + let early_path = tree2.path.join("a/a.sv"); + let early_uri = path_to_uri(&early_path).expect("uri"); + let trigger_uri = path_to_uri(&tree2.path.join("z/p001.sv")).expect("uri"); + let early_unsaved = "module amod_post_publish;\nendmodule\n"; + let _ = probe::take_counts(); + // Script lens (forces publish_scan of early_path!) at point 1, then open early_path unsaved at point 2! + probe::script([ + vec![super::scan_ordering::ask( + 1, + CodeLensRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &trigger_uri } }), + )], + vec![opened(&early_uri, early_unsaved)], + ]); + let mut s2 = Session::staged( + vec![tree2.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![configuration_answer(serde_json::json!({ "index": { "scope": "workspace" } }))], + ); + let _ = s2.drain(); + assert!(probe::unarrived().is_empty()); + settle(&mut s2); + + let fresh2 = Session::staged( + vec![tree2.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ "index": { "scope": "workspace" } })), + did_open(&early_path, early_unsaved), + ], + ); + let _ = fresh2.drain(); + assert_eq!( + s2.server.workspace.derived_fingerprint(), + fresh2.server.workspace.derived_fingerprint() + ); +} + +#[cfg(unix)] +#[test] +fn qa_topo_50_mid_scan_non_canonical_symlink_over_max_file_size_matches_pre_scan() { + use std::os::unix::fs::symlink; + + let tree = ordering_tree("qa_t50_sym_cap"); + // ordering_tree files are ~46 bytes; use maxFileSize=60 and pad dut.sv > 80 bytes so + // ordering_tree stays > INTERLEAVE_ABOVE (70 files) while dut.sv exceeds maxFileSize. + let real_text = + format!("module dut_capped;\n wire ok;\n{}endmodule\n", " // pad line\n".repeat(4)); + assert!(real_text.len() > 60 && real_text.len() < 1000); + tree.write("z_real/dut.sv", &real_text); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/dut.sv"), tree.path.join("a_link/dut.sv")).expect("symlink"); + let real_uri = path_to_uri(&tree.path.join("z_real/dut.sv")).expect("uri"); + + let _ = probe::take_counts(); + probe::script([vec![opened(&real_uri, &real_text)]]); + let mut mid = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": 60 }, + "largeFile": { "threshold": 1000 } + }))], + ); + let _ = mid.drain(); + assert!(probe::unarrived().is_empty(), "mid-scan open must arrive during interleaved scan"); + settle(&mut mid); + + let pre = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": 60 }, + "largeFile": { "threshold": 1000 } + })), + did_open(&tree.path.join("z_real/dut.sv"), &real_text), + ], + ); + let _ = pre.drain(); + + assert_eq!( + mid.server.workspace.index().files(), + pre.server.workspace.index().files(), + "mid-scan open of z_real/dut.sv over maxFileSize must use canonical a_link/dut.sv like pre-scan" + ); +} + +#[cfg(unix)] +#[test] +fn qa_topo_51_same_name_nested_both_open_dirty_close_and_filelist_close() { + use std::os::unix::fs::symlink; + + // Nested same-name symlink: sub/a.sv -> ../a.sv (canonical a.sv < sub/a.sv). + let tree = Tree::new("qa_t51_nested"); + let disk_text = "module a_mod;\n logic on_disk;\nendmodule\n"; + let buf_text = "module a_mod;\n logic in_buf;\nendmodule\n"; + tree.write("a.sv", disk_text); + std::fs::create_dir_all(tree.path.join("sub")).expect("dir"); + symlink(tree.path.join("a.sv"), tree.path.join("sub/a.sv")).expect("symlink"); + + let mut session = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + wide_large(0, 1024 * 1024), + ); + let _ = session.drain(); + assert_eq!(session.server.workspace.index().files(), &[tree.path.join("a.sv")]); + + // Open BOTH sub/a.sv (dirty) and a.sv (clean), then close sub/a.sv -> reverts to a.sv (disk). + let sub_uri = session.open(&tree.path.join("sub/a.sv"), buf_text); + let a_uri = session.open(&tree.path.join("a.sv"), disk_text); + session.server.workspace.rebuild_index(); + assert_eq!(session.server.workspace.index().files(), &[tree.path.join("a.sv")]); + session.batch(vec![closed(&sub_uri)]); + assert_eq!(session.server.workspace.index().files_mentioning("on_disk").count(), 1); + assert_eq!(session.server.workspace.index().files_mentioning("in_buf").count(), 0); + session.batch(vec![closed(&a_uri)]); + + // Filelist containing symlinked unlisted vs listed close. + let fl = Tree::new("qa_t51_fl_close"); + fl.write("z_real/real_b.sv", "package real_pkg;\nendpackage\n"); + fl.write("rtl/keep.sv", "package keep_pkg;\nendpackage\n"); + std::fs::create_dir_all(fl.path.join("a_link")).expect("dir"); + symlink(fl.path.join("z_real/real_b.sv"), fl.path.join("a_link/link_a.sv")).expect("symlink"); + fl.write("files.f", "rtl/keep.sv\na_link/link_a.sv\n"); + let mut fl_s = Session::started( + vec![fl.path.clone()], + ClientAbilities::default(), + ClientSettings { filelist: Some("files.f".into()), ..Default::default() }, + ); + let _ = fl_s.drain(); + assert_eq!( + fl_s.server.workspace.index().files(), + &[fl.path.join("a_link/link_a.sv"), fl.path.join("rtl/keep.sv")] + ); + // Open via target z_real/real_b.sv, edit unsaved, close -> stays indexed and reverts to disk. + let z_uri = fl_s.open(&fl.path.join("z_real/real_b.sv"), "package real_unsaved;\nendpackage\n"); + fl_s.server.workspace.rebuild_index(); + assert_eq!(fl_s.server.workspace.index().units("real_unsaved").len(), 1); + fl_s.batch(vec![closed(&z_uri)]); + assert_eq!(fl_s.server.workspace.index().units("real_pkg").len(), 1); + assert_eq!(fl_s.server.workspace.index().units("real_unsaved").len(), 0); +} + +#[cfg(unix)] +#[test] +fn qa_topo_51_non_canonical_symlink_open_buffer_breaks_references_lint_and_rename() { + use std::os::unix::fs::symlink; + + let tree = Tree::new("qa_t51_handshake"); + let real_text = "module dut;\n logic dead_sig;\nendmodule\n"; + let tb_text = "module tb;\n dut u1 ();\nendmodule\n"; + tree.write("z_real/real_b.sv", real_text); + tree.write("tb/tb.sv", tb_text); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/real_b.sv"), tree.path.join("a_link/link_a.sv")) + .expect("symlink"); + + let settings = wide_large(0, 1024 * 1024); + let mut via_canon = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings.clone()); + let _ = via_canon.drain(); + let canon_uri = via_canon.open(&tree.path.join("a_link/link_a.sv"), real_text); + + let mut via_target = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings.clone()); + let _ = via_target.drain(); + let target_uri = via_target.open(&tree.path.join("z_real/real_b.sv"), real_text); + + // 1. textDocument/references on `dut` + let refs_canon = via_canon.result( + References::METHOD, + serde_json::json!({ + "textDocument": { "uri": &canon_uri }, + "position": { "line": 0, "character": 7 }, + "context": { "includeDeclaration": true } + }), + ); + let refs_target = via_target.result( + References::METHOD, + serde_json::json!({ + "textDocument": { "uri": &target_uri }, + "position": { "line": 0, "character": 7 }, + "context": { "includeDeclaration": true } + }), + ); + let refs_match = + refs_target.as_array().expect("arr").len() == refs_canon.as_array().expect("arr").len(); + + // 2. Lint diagnostics (unused-signal vs target) + let diag_canon = via_canon.server.diagnostics_of(&canon_uri); + let diag_target = via_target.server.diagnostics_of(&target_uri); + let canon_codes: Vec<_> = diag_canon.iter().map(|d| (&d.code, &d.message)).collect(); + let target_codes: Vec<_> = diag_target.iter().map(|d| (&d.code, &d.message)).collect(); + let diag_match = canon_codes == target_codes; + + // 3. Rename `dut` -> `dut_v2` from non-canonical open buffer AND from tb/tb.sv + let off = real_text.find("dut").expect("pos") as u32; + let ren_canon = crate::rename::rename_traced( + &via_canon.server.workspace, + &canon_uri, + off, + "dut_v2", + &mut None, + ); + let ren_target = crate::rename::rename_traced( + &via_target.server.workspace, + &target_uri, + off, + "dut_v2", + &mut None, + ); + let tb_uri = via_target.open(&tree.path.join("tb/tb.sv"), tb_text); + let tb_off = tb_text.find("dut").expect("tb pos") as u32; + let ren_from_tb = crate::rename::rename_traced( + &via_target.server.workspace, + &tb_uri, + tb_off, + "dut_v2", + &mut None, + ); + let edits_target_open_uri = ren_from_tb.as_ref().is_ok_and(|(edit, _)| { + serde_json::to_string(edit).is_ok_and(|s| s.contains(target_uri.as_str())) + }); + let ren_match = ren_canon.is_ok() && ren_target.is_ok() && edits_target_open_uri; + + assert!( + refs_match && diag_match && ren_match, + "non-canonical open symlink breaks handshake callers: refs=({} vs {}), diags=({target_codes:?} vs {canon_codes:?}), rename_target={ren_target:?}, rename_canon={ren_canon:?}, edits_target_open_uri={edits_target_open_uri}, tb_edit={ren_from_tb:?}", + refs_target.as_array().expect("a").len(), + refs_canon.as_array().expect("a").len(), + ); +} + +#[test] +fn qa_topo_63_threshold_drop_after_unsaved_edit_indexed_via_widen_diverges_from_fresh() { + let tree = Tree::new("qa_t63_thresh_drop"); + let small_disk = "package p_flip;\n localparam ON_DISK = 1;\nendpackage\n"; + let unsaved_edit = "package p_flip;\n localparam IN_BUF = 2;\nendpackage\n"; + tree.write("rtl/p.sv", small_disk); + let p_path = tree.path.join("rtl/p.sv"); + + let mut s = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + ClientSettings { + index_scope_depth: 0, + large_file_threshold: 500, + max_file_size: 1024 * 1024, + ..Default::default() + }, + ); + let _ = s.drain(); + let p_uri = s.open(&p_path, unsaved_edit); + assert_eq!(s.server.workspace.index().member("p_flip", "IN_BUF").len(), 1); + + // Lower threshold so p.sv becomes doc.large -> without rescan, index STILL holds IN_BUF instead of ON_DISK! + s.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { + "index": { "scopeDepth": 0, "maxFileSize": 1024 * 1024 }, + "largeFile": { "threshold": 10 } + } } }), + ); + assert!(s.server.workspace.document(&p_uri).expect("open").large); + assert_eq!( + s.server.workspace.index().member("p_flip", "ON_DISK").len(), + 1, + "once doc.large is reclassified true, disk record must replace previously indexed unsaved buffer" + ); +} + +#[cfg(unix)] +#[test] +fn qa_topo_51_widen_symlink_over_max_file_size_converges_like_fresh() { + use std::os::unix::fs::symlink; + + let tree = Tree::new("qa_t51_widen_cap"); + let real_text = + format!("module m_cap;\n wire sig;\n{}endmodule\n", " // pad line\n".repeat(4)); + assert!(real_text.len() > 60 && real_text.len() < 1000); + tree.write("z_real/real.sv", &real_text); + tree.write("a_link/other.sv", "module other;\nendmodule\n"); + symlink(tree.path.join("z_real/real.sv"), tree.path.join("a_link/alias.sv")).expect("symlink"); + + let settings = ClientSettings { + index_scope_depth: 0, + max_file_size: 60, + large_file_threshold: 1000, + ..Default::default() + }; + let mut widened = crate::state::Workspace::default(); + widened.set_client_settings(settings.clone()); + widened.open_roots(vec![tree.path.clone()]); + let z_uri = path_to_uri(&tree.path.join("z_real/real.sv")).expect("uri"); + let a_other_uri = path_to_uri(&tree.path.join("a_link/other.sv")).expect("uri"); + widened.set_document(z_uri.clone(), real_text.clone()); + widened.rebuild_index(); + + widened.set_document(a_other_uri.clone(), "module other;\nendmodule\n".into()); + let mut scan = widened.begin_widen(&[tree.path.join("a_link")], &mut |_| {}, false); + while widened.scan_step(&mut scan, &mut |_| {}) {} + widened.finish_scan(scan); + + let mut fresh = crate::state::Workspace::default(); + fresh.set_client_settings(settings); + fresh.open_roots(vec![tree.path.clone()]); + fresh.set_document(z_uri, real_text); + fresh.set_document(a_other_uri, "module other;\nendmodule\n".into()); + fresh.rebuild_index(); + + assert_eq!( + widened.index().files(), + fresh.index().files(), + "widen into a_link with oversize symlink must canonicalize z_real/real.sv to a_link/alias.sv" + ); +} + +#[test] +fn qa_r2_f1_multiple_tombstones_candidates_absorb_update_words_rename_and_completion() { + // 1. Direct Candidates::from_words / absorb / update_words over multiple preceding tombstones. + let mut index = vlog_semantic::WorkspaceIndex::build([ + (PathBuf::from("a0_excl.sv"), "`define EXCL_0 1\nmodule a0; endmodule\n"), + (PathBuf::from("a1_excl.sv"), "`define EXCL_1 1\nmodule a1; endmodule\n"), + (PathBuf::from("a2_excl.sv"), "`define EXCL_2 1\nmodule a2; endmodule\n"), + (PathBuf::from("d_live.sv"), "`define LIVE_D 4\nmodule d_live; endmodule\n"), + (PathBuf::from("e_live.sv"), "`define LIVE_E(x) (x+1)\nmodule e_live; endmodule\n"), + ]); + assert!(index.remove_file(Path::new("a0_excl.sv"))); + assert!(index.remove_file(Path::new("a1_excl.sv"))); + assert!(index.remove_file(Path::new("a2_excl.sv"))); + assert_eq!(index.files().len(), 2); + assert_eq!(index.file_id(Path::new("d_live.sv")), Some(vlog_semantic::FileId(3))); + assert_eq!(index.file_id(Path::new("e_live.sv")), Some(vlog_semantic::FileId(4))); + + let mut words = std::collections::HashMap::new(); + words.insert(PathBuf::from("d_live.sv"), vec!["d_live".to_string()]); + words.insert(PathBuf::from("e_live.sv"), vec!["e_live".to_string()]); + let mut candidates = crate::candidates::Candidates::from_words(&index, words); + let mut macs: Vec<&str> = candidates.macros("").iter().map(|m| m.name.as_str()).collect(); + macs.sort(); + assert_eq!(macs, vec!["LIVE_D", "LIVE_E"]); + + candidates.update_words( + &index, + Path::new("d_live.sv"), + vec!["d_live".to_string(), "extra_word".to_string()], + ); + let mut macs_after_update: Vec<&str> = + candidates.macros("").iter().map(|m| m.name.as_str()).collect(); + macs_after_update.sort(); + assert_eq!(macs_after_update, vec!["LIVE_D", "LIVE_E"]); + assert_eq!(candidates.words("extra"), &["extra_word".to_string()]); + + candidates.absorb( + &index, + vec![(PathBuf::from("e_live.sv"), vec!["e_live".to_string(), "absorbed_word".to_string()])], + ); + let mut macs_after_absorb: Vec<&str> = + candidates.macros("").iter().map(|m| m.name.as_str()).collect(); + macs_after_absorb.sort(); + assert_eq!(macs_after_absorb, vec!["LIVE_D", "LIVE_E"]); + assert_eq!(candidates.words("absorbed"), &["absorbed_word".to_string()]); + + // 2. Full Server session: 3 tombstoned excluded files preceding live files, checking rename + completion. + let tree = Tree::new("qa_r2_f1_srv"); + let excl = "`define LIVE_D 99\npackage excl_p; endpackage\n"; + let user = "module target_s;\nendmodule\n"; + let mac_file = "`define LIVE_D 42\n`define USE_T target_s\nmodule z_tail;\n logic tail_word;\nendmodule\n"; + tree.write("ignored/a0.sv", excl); + tree.write("ignored/a1.sv", excl); + tree.write("ignored/a2.sv", excl); + tree.write("m_user.sv", user); + tree.write("z_tail.sv", mac_file); + + let settings = wide_with_exclude(vec!["ignored/**".into()]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "workspace" }, + "exclude": ["ignored/**"] + })), + did_open(&tree.path.join("ignored/a0.sv"), excl), + did_open(&tree.path.join("ignored/a1.sv"), excl), + did_open(&tree.path.join("ignored/a2.sv"), excl), + ], + ); + let _ = settled.drain(); + settled.batch(vec![ + closed(&path_to_uri(&tree.path.join("ignored/a0.sv")).expect("uri")), + closed(&path_to_uri(&tree.path.join("ignored/a1.sv")).expect("uri")), + closed(&path_to_uri(&tree.path.join("ignored/a2.sv")).expect("uri")), + ]); + assert_eq!(settled.server.workspace.index().files().len(), 2); + assert_eq!( + settled.server.workspace.index().file_id(&tree.path.join("z_tail.sv")), + Some(vlog_semantic::FileId(4)) + ); + + let mut fresh = Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings); + let _ = fresh.drain(); + + let u_path = tree.path.join("m_user.sv"); + let u_uri = settled.open(&u_path, user); + let _ = fresh.open(&u_path, user); + + // Rename macro-text warning fanout across 3 tombstones + let off = user.find("target_s").expect("pos") as u32; + let (_, settled_warn) = + crate::rename::rename_traced(&settled.server.workspace, &u_uri, off, "new_s", &mut None) + .expect("rename"); + let (_, fresh_warn) = + crate::rename::rename_traced(&fresh.server.workspace, &u_uri, off, "new_s", &mut None) + .expect("rename"); + assert_eq!(settled_warn, fresh_warn); + assert!(!settled_warn.is_empty(), "macro-text warning from z_tail.sv must fire"); + + // Completion (`LIVE_` macro and `tail_w` word) across 3 tombstones + let probe_src = "module target_s;\n `LIVE_\n logic tail_w\nendmodule\n"; + change_full(&mut settled, &u_uri, 2, probe_src); + change_full(&mut fresh, &u_uri, 2, probe_src); + settled.server.flush_dirty(); + fresh.server.flush_dirty(); + + for (line, ch) in [(1, 8), (2, 14)] { + let p = serde_json::json!({ + "textDocument": { "uri": &u_uri }, + "position": { "line": line, "character": ch } + }); + assert_eq!( + settled.result(Completion::METHOD, p.clone()), + fresh.result(Completion::METHOD, p), + "completion mismatch at {line}:{ch}" + ); + } +} + +#[cfg(unix)] +#[test] +fn qa_r2_f2_non_canonical_symlink_open_buffer_across_all_handlers_and_case_mismatch() { + use lsp_types::{CallHierarchyItem, CodeActionOrCommand, Position, Range}; + use std::os::unix::fs::symlink; + + let tree = Tree::new("qa_r2_f2_all"); + let real_text = "\ +`include \"link_h.svh\" +package dut_pkg; + localparam int K = 7; + function int helper(input int v); + return v + 1; + endfunction +endpackage +module dut #(parameter int W = 8) ( + input logic clk +); + import unused_pkg::*; + import dut_pkg::*; + sub u_sub (); + logic x; + assign x = helper(K); + logic sel_a, sel_b; + assign sel_b = sel_a; +endmodule +"; + let hdr_text = "`define LINK_HDR_MAC 123\n`define SHARED_MAC 111\n"; + let other_hdr_text = "`define SHARED_MAC 222\n"; + let pkg_unused = "package unused_pkg;\n localparam int U = 1;\nendpackage\n"; + let sub_text = "module sub;\nendmodule\n"; + let tb_text = "\ +module tb; + logic clk; + dut u1 (.clk(clk)); + int y; + assign y = dut_pkg::helper(1); +endmodule +"; + let real_incl_tb_text = + "`include \"real_h.svh\"\nmodule real_tb;\n logic m = `SHARED_MAC;\nendmodule\n"; + + tree.write("z_real/real_b.sv", real_text); + tree.write("z_real/real_h.svh", hdr_text); + tree.write("z_real/real_tb.sv", real_incl_tb_text); + tree.write("other/dup.svh", other_hdr_text); + tree.write("rtl/unused_pkg.sv", pkg_unused); + tree.write("rtl/sub.sv", sub_text); + tree.write("tb/tb.sv", tb_text); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/real_b.sv"), tree.path.join("a_link/link_a.sv")) + .expect("symlink"); + symlink(tree.path.join("z_real/real_h.svh"), tree.path.join("a_link/link_h.svh")) + .expect("symlink"); + + let settings = wide_large(0, 1024 * 1024); + let mut via_canon = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings.clone()); + let _ = via_canon.drain(); + let canon_uri = via_canon.open(&tree.path.join("a_link/link_a.sv"), real_text); + let canon_tb_uri = via_canon.open(&tree.path.join("tb/tb.sv"), tb_text); + + let mut via_target = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings.clone()); + let _ = via_target.drain(); + let target_uri = via_target.open(&tree.path.join("z_real/real_b.sv"), real_text); + let target_tb_uri = via_target.open(&tree.path.join("tb/tb.sv"), tb_text); + + // 1. Hover: from tb.sv onto dut / clk in open z_real/real_b.sv, and from z_real/real_b.sv onto sub + let hover_dut = serde_json::json!({ + "textDocument": { "uri": &target_tb_uri }, + "position": { "line": 2, "character": 3 } + }); + let hover_dut_c = serde_json::json!({ + "textDocument": { "uri": &canon_tb_uri }, + "position": { "line": 2, "character": 3 } + }); + assert_eq!( + via_target.result(HoverRequest::METHOD, hover_dut), + via_canon.result(HoverRequest::METHOD, hover_dut_c), + "hover on dut from tb" + ); + + let hover_sub_t = serde_json::json!({ + "textDocument": { "uri": &target_uri }, + "position": { "line": 12, "character": 3 } + }); + let hover_sub_c = serde_json::json!({ + "textDocument": { "uri": &canon_uri }, + "position": { "line": 12, "character": 3 } + }); + assert_eq!( + via_target.result(HoverRequest::METHOD, hover_sub_t), + via_canon.result(HoverRequest::METHOD, hover_sub_c), + "hover on sub from z_real/real_b.sv" + ); + + // 2. GotoDefinition: from z_real/real_b.sv -> sub and from tb.sv -> dut + let def_sub_t = via_target.result( + GotoDefinition::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri }, "position": { "line": 12, "character": 3 } }), + ); + let def_sub_c = via_canon.result( + GotoDefinition::METHOD, + serde_json::json!({ "textDocument": { "uri": &canon_uri }, "position": { "line": 12, "character": 3 } }), + ); + assert_eq!(def_sub_t, def_sub_c, "gotoDefinition from open symlink target to sub"); + let def_dut_t = via_target.result( + GotoDefinition::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_tb_uri }, "position": { "line": 2, "character": 3 } }), + ); + assert_eq!( + def_dut_t.as_array().expect("arr").len(), + 1, + "gotoDefinition to open target returns 1 loc" + ); + + // 3. CodeActions: port offers/resolve, extract, organize_imports on z_real/real_b.sv + // 3a. Port offers & resolve on `input logic clk` (line 8, col 15) + let port_off = real_text.find("clk").expect("clk") as u32; + let port_pos = Position { line: 8, character: 15 }; + let offers_t = + crate::ports::offers(&via_target.server.workspace, &target_uri, port_pos, port_off); + assert!(!offers_t.is_empty(), "port offers must appear on open non-canonical symlink"); + let CodeActionOrCommand::CodeAction(first_offer) = offers_t[0].clone() else { + panic!("expected CodeAction offer"); + }; + let resolved_t = crate::ports::resolve_for(&via_target.server.workspace, first_offer, true) + .expect("port resolve"); + let resolved_json = serde_json::to_string(&resolved_t).expect("json"); + assert!( + resolved_json.contains(target_uri.as_str()), + "port resolve edit must target open URI {}: {resolved_json}", + target_uri.as_str() + ); + assert!(!resolved_json.contains(canon_uri.as_str()), "must not edit duplicate canonical URI"); + + // 3b. Extract codeAction + execute on `assign sel_b = sel_a;` (line 16) + let extract_range = Range { + start: Position { line: 16, character: 2 }, + end: Position { line: 16, character: 23 }, + }; + let ext_actions = + crate::extract::code_actions(&via_target.server.workspace, &target_uri, extract_range); + assert_eq!(ext_actions.len(), 1, "extract codeAction offered"); + let (ext_edit, _) = crate::extract::execute( + &via_target.server.workspace, + &[ + serde_json::to_value(&target_uri).expect("uri"), + serde_json::to_value(extract_range).expect("range"), + Value::String("dut_extracted".to_string()), + ], + false, + ) + .expect("extract execute"); + let ext_json = serde_json::to_string(&ext_edit).expect("json"); + assert!( + ext_json.contains(target_uri.as_str()), + "extract edit targets open URI {}: {ext_json}", + target_uri.as_str() + ); + + // 3c. Organize imports offers + resolve + execute on `import unused_pkg::*;` (line 10, col 10) + let imp_off = real_text.find("unused_pkg").expect("imp") as u32; + let imp_pos = Position { line: 10, character: 10 }; + let imp_offers = + crate::imports::offers(&via_target.server.workspace, &target_uri, imp_pos, imp_off); + assert_eq!(imp_offers.len(), 1, "organizeImports offered on open symlink target"); + let CodeActionOrCommand::CodeAction(imp_offer) = imp_offers[0].clone() else { + panic!("expected CodeAction"); + }; + let imp_resolved = crate::imports::resolve(&via_target.server.workspace, imp_offer) + .expect("organizeImports resolve"); + let imp_json = serde_json::to_string(&imp_resolved).expect("json"); + assert!( + imp_json.contains(target_uri.as_str()), + "organizeImports edits open URI {}: {imp_json}", + target_uri.as_str() + ); + + // 4. Completion / related_tier (package members via open symlink target) + let mut comp_ws = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings.clone()); + let _ = comp_ws.drain(); + let comp_body = real_text.replace( + " assign sel_b = sel_a;", + " assign sel_b = sel_a;\n logic p_ = K\n logic m_ = `LINK_HDR_", + ); + let comp_uri = comp_ws.open(&tree.path.join("z_real/real_b.sv"), &comp_body); + let mut comp_canon = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings); + let _ = comp_canon.drain(); + let comp_canon_uri = comp_canon.open(&tree.path.join("a_link/link_a.sv"), &comp_body); + + assert_eq!( + comp_ws.result( + Completion::METHOD, + serde_json::json!({ "textDocument": { "uri": &comp_uri }, "position": { "line": 17, "character": 14 } }) + ), + comp_canon.result( + Completion::METHOD, + serde_json::json!({ "textDocument": { "uri": &comp_canon_uri }, "position": { "line": 17, "character": 14 } }) + ), + "completion/related_tier mismatch at 17:14" + ); + + // 5. CallHierarchy: module (`dut` incoming + outgoing) + function (`helper` incoming + outgoing) + // 5a. Module `dut` prepare + incomingCalls + outgoingCalls from z_real/real_b.sv + let mod_items: Vec = serde_json::from_value(via_target.result( + CallHierarchyPrepare::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri }, "position": { "line": 7, "character": 8 } }), + )) + .expect("items"); + assert_eq!(mod_items.len(), 1); + let mod_in = crate::hierarchy::incoming(&via_target.server.workspace, &mod_items[0]); + assert_eq!(mod_in.len(), 1, "dut called once by tb"); + assert_eq!(mod_in[0].from.name, "tb"); + let mod_out = crate::hierarchy::outgoing(&via_target.server.workspace, &mod_items[0]); + assert_eq!(mod_out.len(), 1, "dut calls sub once"); + assert_eq!(mod_out[0].to.name, "sub"); + + // 5b. Function `helper` prepare + incomingCalls from z_real/real_b.sv + let fn_items: Vec = serde_json::from_value(via_target.result( + CallHierarchyPrepare::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri }, "position": { "line": 3, "character": 16 } }), + )) + .expect("fn items"); + assert_eq!(fn_items.len(), 1); + let fn_in = crate::hierarchy::incoming(&via_target.server.workspace, &fn_items[0]); + assert_eq!(fn_in.len(), 2, "helper called once in dut and once in tb (no duplicates)"); + + // 6. Design hierarchy (`lucisv/moduleHierarchy`) + let dh_t = via_target.result(crate::design_hierarchy::METHOD, Value::Null); + let dh_c = via_canon.result(crate::design_hierarchy::METHOD, Value::Null); + assert_eq!(dh_t["files"], dh_c["files"]); + assert_eq!(dh_t["modules"], dh_c["modules"]); + let dut_count = dh_t["modules"] + .as_array() + .expect("mods") + .iter() + .filter(|m| m["moduleName"] == "dut") + .count(); + assert_eq!(dut_count, 1, "design_hierarchy must list dut exactly once"); + + // 7. Case-only mismatch on macOS/Windows stays separate + if cfg!(any(target_os = "macos", target_os = "windows")) { + let case_tree = Tree::new("qa_r2_f2_case"); + case_tree.write("Foo.sv", "module Foo;\nendmodule\n"); + let mut ws = crate::state::Workspace::default(); + ws.open_whole_workspace(vec![case_tree.path.clone()]); + let wrong_case = case_tree.path.join("foo.sv"); + let wrong_uri = path_to_uri(&wrong_case).expect("uri"); + ws.set_document(wrong_uri, "module foo_buf;\nendmodule\n".to_string()); + assert!( + ws.index_file_id(&wrong_case).is_none(), + "case-only mismatch must not resolve to Foo.sv's FileId" + ); + assert!(!ws.is_same_file(&case_tree.path.join("Foo.sv"), &wrong_case)); + assert!(ws.document_for_path(&case_tree.path.join("Foo.sv")).is_none()); + } +} + +#[cfg(unix)] +#[test] +fn qa_r2_f2_symlink_include_related_macros_links_def_and_hover_narrowing() { + use lsp_types::request::{DocumentLinkRequest, GotoDefinition, HoverRequest}; + use std::os::unix::fs::symlink; + + let tree = Tree::new("qa_r2_f2_incl"); + let real_text = "`include \"link_h.svh\"\nmodule dut;\n logic m = `LINK_HDR_\nendmodule\n"; + let hdr_text = "`define LINK_HDR_MAC 123\n`define SHARED_MAC 111\n"; + let other_hdr_text = "`define SHARED_MAC 222\n"; + let real_incl_tb_text = + "`include \"real_h.svh\"\nmodule real_tb;\n logic m = `SHARED_MAC;\nendmodule\n"; + + tree.write("z_real/real_b.sv", real_text); + tree.write("z_real/real_h.svh", hdr_text); + tree.write("z_real/real_tb.sv", real_incl_tb_text); + tree.write("other/dup.svh", other_hdr_text); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/real_b.sv"), tree.path.join("a_link/link_a.sv")) + .expect("symlink"); + symlink(tree.path.join("z_real/real_h.svh"), tree.path.join("a_link/link_h.svh")) + .expect("symlink"); + + let settings = wide_large(0, 1024 * 1024); + let mut via_canon = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings.clone()); + let _ = via_canon.drain(); + let canon_uri = via_canon.open(&tree.path.join("a_link/link_a.sv"), real_text); + + let mut via_target = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings); + let _ = via_target.drain(); + let target_uri = via_target.open(&tree.path.join("z_real/real_b.sv"), real_text); + + let mut failures = Vec::new(); + + // 1. completion/related_macros from symlink-relative `include "link_h.svh" + let rel_t = via_target.result( + Completion::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri }, "position": { "line": 2, "character": 22 } }), + ); + let rel_c = via_canon.result( + Completion::METHOD, + serde_json::json!({ "textDocument": { "uri": &canon_uri }, "position": { "line": 2, "character": 22 } }), + ); + if rel_t != rel_c { + failures.push(format!( + "completion/related_macros mismatch:\n target={rel_t}\n canon={rel_c}" + )); + } + + // 2. DocumentLink & GotoDefinition on `include "link_h.svh" + let dl_t = via_target.result( + DocumentLinkRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri } }), + ); + let dl_c = via_canon.result( + DocumentLinkRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &canon_uri } }), + ); + if dl_t != dl_c { + failures.push(format!("documentLink mismatch:\n target={dl_t}\n canon={dl_c}")); + } + + let id_t = via_target.result( + GotoDefinition::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri }, "position": { "line": 0, "character": 12 } }), + ); + let id_c = via_canon.result( + GotoDefinition::METHOD, + serde_json::json!({ "textDocument": { "uri": &canon_uri }, "position": { "line": 0, "character": 12 } }), + ); + if id_t != id_c { + failures.push(format!("include gotoDefinition mismatch:\n target={id_t}\n canon={id_c}")); + } + + // 3. Hover macro include-graph narrowing when z_real/real_tb.sv includes real_h.svh -> a_link/link_h.svh + let real_tb_uri = via_target.open(&tree.path.join("z_real/real_tb.sv"), real_incl_tb_text); + let hover_mac_t = via_target.result( + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &real_tb_uri }, "position": { "line": 2, "character": 15 } }), + ); + let hover_mac_str = serde_json::to_string(&hover_mac_t).expect("json"); + if hover_mac_str.contains("defined 2 times") { + failures.push(format!( + "hover include-graph narrowing failed to match symlinked header: {hover_mac_str}" + )); + } + + assert!(failures.is_empty(), "{}", failures.join("\n---\n")); +} + +#[cfg(unix)] +#[test] +fn qa_r2_f3_mid_scan_open_dirty_symlink_and_close_mid_scan_matches_fresh() { + use std::os::unix::fs::symlink; + + for (tag, max_cap) in [("in_scope", 1024 * 1024u64), ("over_cap", 60u64)] { + let tree = ordering_tree(&format!("qa_r2_f3_{tag}")); + let disk_text = format!( + "module dut_f3;\n localparam ON_DISK = 1;\n{}endmodule\n", + " // pad line\n".repeat(4) + ); + let dirty_text = format!( + "module dut_f3;\n localparam IN_BUF = 2;\n{}endmodule\n", + " // pad line\n".repeat(4) + ); + assert!(disk_text.len() > 60 && disk_text.len() < 1000); + tree.write("z_real/dut.sv", &disk_text); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/dut.sv"), tree.path.join("a_link/dut.sv")).expect("symlink"); + let real_uri = path_to_uri(&tree.path.join("z_real/dut.sv")).expect("uri"); + + let _ = probe::take_counts(); + probe::script([vec![opened(&real_uri, &dirty_text)], vec![], vec![closed(&real_uri)]]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": max_cap }, + "largeFile": { "threshold": 1000 } + }))], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty(), "{tag}: mid-scan open and close must arrive"); + settle(&mut settled); + + let fresh = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + wide_large(1000, max_cap), + ); + assert_eq!( + settled.server.workspace.derived_fingerprint(), + fresh.server.workspace.derived_fingerprint(), + "{tag}: mid-scan open dirty symlink then close mid-scan must match fresh" + ); + } +} + +#[cfg(unix)] +#[test] +fn qa_r2_f3_mid_scan_dirty_open_reverted_and_closed_leaves_stale_index() { + use lsp_types::request::HoverRequest; + use std::os::unix::fs::symlink; + + // Attack: open dirty symlink -> didChange back to disk (flushed) -> close mid-scan before finish_whole_scan + let tree = ordering_tree("qa_r2_f3_revert_close"); + let disk_text = "module dut_rev;\n localparam ON_DISK = 1;\nendmodule\n"; + let dirty_text = "module dut_rev;\n localparam IN_BUF = 2;\nendmodule\n"; + tree.write("z_real/dut.sv", disk_text); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/dut.sv"), tree.path.join("a_link/dut.sv")).expect("symlink"); + let real_uri = path_to_uri(&tree.path.join("z_real/dut.sv")).expect("uri"); + let hover_trigger = super::scan_ordering::ask( + 99, + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &real_uri }, "position": { "line": 0, "character": 7 } }), + ); + + let _ = probe::take_counts(); + probe::script([ + vec![opened(&real_uri, dirty_text)], + vec![changed(&real_uri, 2, disk_text), hover_trigger], + vec![closed(&real_uri)], + ]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": 1048576 }, + "largeFile": { "threshold": 1000 } + }))], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty()); + settle(&mut settled); + + assert_eq!( + settled.server.workspace.index().member("dut_rev", "ON_DISK").len(), + 1, + "after reverting buffer to disk and closing mid-scan, index must have ON_DISK" + ); + assert_eq!( + settled.server.workspace.index().member("dut_rev", "IN_BUF").len(), + 0, + "stale mid-scan IN_BUF must not survive" + ); +} + +#[cfg(unix)] +#[test] +fn r2_f3_mid_scan_dirty_reverted_and_closed_converges_across_all_scan_phases() { + use lsp_types::request::HoverRequest; + use std::os::unix::fs::symlink; + + let hover = |uri: &Uri| { + super::scan_ordering::ask( + 101, + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": uri }, "position": { "line": 0, "character": 7 } }), + ) + }; + + // 1. Pre-scan dirty symlink -> mid-scan didChange(disk) -> mid-scan didClose + { + let tree = ordering_tree("r2_f3_prescan_rev"); + let disk_text = "module dut_pre;\n localparam ON_DISK = 1;\nendmodule\n"; + let dirty_text = "module dut_pre;\n localparam IN_BUF = 2;\nendmodule\n"; + tree.write("z_real/dut.sv", disk_text); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/dut.sv"), tree.path.join("a_link/dut.sv")).expect("symlink"); + let real_path = tree.path.join("z_real/dut.sv"); + let real_uri = path_to_uri(&real_path).expect("uri"); + + let _ = probe::take_counts(); + probe::script([ + vec![changed(&real_uri, 2, disk_text), hover(&real_uri)], + vec![closed(&real_uri)], + ]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": 1048576 }, + "largeFile": { "threshold": 1000 } + })), + did_open(&real_path, dirty_text), + ], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty()); + settle(&mut settled); + + let fresh = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + wide_large(1000, 1048576), + ); + assert_eq!( + settled.server.workspace.derived_fingerprint(), + fresh.server.workspace.derived_fingerprint(), + "pre-scan dirty symlink reverted & closed mid-scan must match fresh" + ); + } + + // 2. Already-stepped (pos < scan.at) symlink -> mid-scan didOpen(dirty) -> didChange(disk) -> didClose + { + let tree = ordering_tree("r2_f3_past_at_rev"); + let disk_text = "module dut_past;\n localparam ON_DISK = 1;\nendmodule\n"; + let dirty_text = "module dut_past;\n localparam IN_BUF = 2;\nendmodule\n"; + tree.write("z_real/dut.sv", disk_text); + std::fs::create_dir_all(tree.path.join("0_link")).expect("dir"); + symlink(tree.path.join("z_real/dut.sv"), tree.path.join("0_link/dut.sv")).expect("symlink"); + let real_uri = path_to_uri(&tree.path.join("z_real/dut.sv")).expect("uri"); + + let _ = probe::take_counts(); + probe::script([ + vec![opened(&real_uri, dirty_text)], + vec![changed(&real_uri, 2, disk_text), hover(&real_uri)], + vec![closed(&real_uri)], + ]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": 1048576 }, + "largeFile": { "threshold": 1000 } + }))], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty()); + settle(&mut settled); + + let fresh = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + wide_large(1000, 1048576), + ); + assert_eq!( + settled.server.workspace.derived_fingerprint(), + fresh.server.workspace.derived_fingerprint(), + "pos < scan.at dirty open reverted & closed mid-scan must match fresh" + ); + } + + // 3. Oversize (> maxFileSize) symlink -> mid-scan didOpen(dirty) -> didChange(disk) -> didClose + { + let tree = ordering_tree("r2_f3_overcap_rev"); + let disk_text = format!( + "module dut_cap;\n localparam ON_DISK = 1;\n{}endmodule\n", + " // pad line\n".repeat(4) + ); + let dirty_text = format!( + "module dut_cap;\n localparam IN_BUF = 2;\n{}endmodule\n", + " // pad line\n".repeat(4) + ); + assert!(disk_text.len() > 60 && disk_text.len() < 1000); + tree.write("z_real/dut.sv", &disk_text); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/dut.sv"), tree.path.join("a_link/dut.sv")).expect("symlink"); + let real_uri = path_to_uri(&tree.path.join("z_real/dut.sv")).expect("uri"); + + let _ = probe::take_counts(); + probe::script([ + vec![opened(&real_uri, &dirty_text)], + vec![changed(&real_uri, 2, &disk_text), hover(&real_uri)], + vec![closed(&real_uri)], + ]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": 60 }, + "largeFile": { "threshold": 1000 } + }))], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty()); + settle(&mut settled); + + let fresh = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + wide_large(1000, 60), + ); + assert_eq!( + settled.server.workspace.derived_fingerprint(), + fresh.server.workspace.derived_fingerprint(), + "oversize dirty symlink reverted & closed mid-scan must match fresh" + ); + } + + // 4. Mid-scan didOpen(dirty) -> didChange(huge, flips doc.large=true) -> didClose + { + let tree = ordering_tree("r2_f3_flip_large_close"); + let disk_text = "module dut_lg;\n localparam ON_DISK = 1;\nendmodule\n"; + let dirty_text = "module dut_lg;\n localparam IN_BUF = 2;\nendmodule\n"; + let huge_text = format!( + "module dut_lg;\n localparam HUGE_BUF = 3;\n{}endmodule\n", + " // pad line\n".repeat(20) + ); + assert!(dirty_text.len() < 200 && huge_text.len() > 200); + tree.write("z_real/dut.sv", disk_text); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/dut.sv"), tree.path.join("a_link/dut.sv")).expect("symlink"); + let real_uri = path_to_uri(&tree.path.join("z_real/dut.sv")).expect("uri"); + + let _ = probe::take_counts(); + probe::script([ + vec![opened(&real_uri, dirty_text)], + vec![changed(&real_uri, 2, &huge_text), hover(&real_uri)], + vec![closed(&real_uri)], + ]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": 1048576 }, + "largeFile": { "threshold": 200 } + }))], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty()); + settle(&mut settled); + + let fresh = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + wide_large(200, 1048576), + ); + assert_eq!( + settled.server.workspace.derived_fingerprint(), + fresh.server.workspace.derived_fingerprint(), + "dirty buffer flipped to doc.large then closed mid-scan must match fresh" + ); + } +} + +#[cfg(unix)] +#[test] +fn qa_r2_f4_widen_symlink_pointing_outside_root_converges_like_fresh() { + use std::os::unix::fs::symlink; + + for (tag, max_cap) in [("under_cap", 1024 * 1024u64), ("over_cap", 60u64)] { + let ext = Tree::new(&format!("qa_r2_f4_ext_{tag}")); + let ext_text = + format!("module out_mod;\n wire ok;\n{}endmodule\n", " // pad line\n".repeat(4)); + assert!(ext_text.len() > 60 && ext_text.len() < 1000); + ext.write("outside.sv", &ext_text); + + let root = Tree::new(&format!("qa_r2_f4_root_{tag}")); + root.write("rtl/keep.sv", "module keep;\nendmodule\n"); + root.write("a_link/other.sv", "module other;\nendmodule\n"); + symlink(ext.path.join("outside.sv"), root.path.join("a_link/alias.sv")).expect("symlink"); + + let settings = ClientSettings { + index_scope_depth: 0, + max_file_size: max_cap, + large_file_threshold: 1000, + ..Default::default() + }; + + // Case A: external file is closed; open rtl/keep.sv first, then widen into a_link/ + let mut widened_a = crate::state::Workspace::default(); + widened_a.set_client_settings(settings.clone()); + widened_a.open_roots(vec![root.path.clone()]); + let keep_uri = path_to_uri(&root.path.join("rtl/keep.sv")).expect("uri"); + let other_uri = path_to_uri(&root.path.join("a_link/other.sv")).expect("uri"); + widened_a.set_document(keep_uri.clone(), "module keep;\nendmodule\n".into()); + widened_a.rebuild_index(); + widened_a.set_document(other_uri.clone(), "module other;\nendmodule\n".into()); + widened_a.widen_index(&[root.path.join("a_link")]); + + let mut fresh_a = crate::state::Workspace::default(); + fresh_a.set_client_settings(settings.clone()); + fresh_a.open_roots(vec![root.path.clone()]); + fresh_a.set_document(keep_uri.clone(), "module keep;\nendmodule\n".into()); + fresh_a.set_document(other_uri.clone(), "module other;\nendmodule\n".into()); + fresh_a.rebuild_index(); + assert_eq!( + widened_a.index().fingerprint(), + fresh_a.index().fingerprint(), + "{tag} case A (closed outside target): widen must match fresh" + ); + + // Case B: external file outside.sv was opened FIRST (dirty or clean), then widen into a_link/other.sv + let out_uri = path_to_uri(&ext.path.join("outside.sv")).expect("uri"); + let mut widened_b = crate::state::Workspace::default(); + widened_b.set_client_settings(settings.clone()); + widened_b.open_roots(vec![root.path.clone()]); + widened_b.set_document(out_uri.clone(), ext_text.clone()); + widened_b.rebuild_index(); + widened_b.set_document(other_uri.clone(), "module other;\nendmodule\n".into()); + widened_b.widen_index(&[root.path.join("a_link")]); + + let mut fresh_b = crate::state::Workspace::default(); + fresh_b.set_client_settings(settings); + fresh_b.open_roots(vec![root.path.clone()]); + fresh_b.set_document(out_uri, ext_text); + fresh_b.set_document(other_uri, "module other;\nendmodule\n".into()); + fresh_b.rebuild_index(); + assert_eq!( + widened_b.index().fingerprint(), + fresh_b.index().fingerprint(), + "{tag} case B (open outside target): widen must match fresh" + ); + } +} + +#[test] +fn qa_r2_f5_reclassify_large_buffers_excluded_dirty_clean_and_round_trip() { + let tree = Tree::new("qa_r2_f5_all"); + let clean_disk = "package clean_pkg;\n localparam C = 1;\nendpackage\n"; + let p_disk = "package p_pkg;\n localparam ON_DISK = 1;\nendpackage\n"; + let p_buf = "package p_pkg;\n localparam IN_BUF = 2;\nendpackage\n"; + let excl_disk = "package excl_pkg;\n localparam EX_DISK = 1;\nendpackage\n"; + let excl_buf = "package excl_pkg;\n localparam EX_BUF = 2;\nendpackage\n"; + tree.write("rtl/clean.sv", clean_disk); + tree.write("rtl/p.sv", p_disk); + tree.write("ignored/excl.sv", excl_disk); + tree.write("lib/q.sv", "package q_pkg;\n localparam Q = 1;\nendpackage\n"); + + let clean_path = tree.path.join("rtl/clean.sv"); + let p_path = tree.path.join("rtl/p.sv"); + let excl_path = tree.path.join("ignored/excl.sv"); + let q_path = tree.path.join("lib/q.sv"); + let excl_uri = path_to_uri(&excl_path).expect("uri"); + let p_uri = path_to_uri(&p_path).expect("uri"); + + // 1. Clean in-scope + excluded unsaved: start with excl open before scan, clean open after scan. + let mut s = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "folder", "scopeDepth": 0, "maxFileSize": 1048576 }, + "exclude": ["ignored/**"], + "largeFile": { "threshold": 500 } + })), + did_open(&clean_path, clean_disk), + did_open(&excl_path, excl_buf), + ], + ); + let _ = s.drain(); + assert_eq!(s.server.workspace.index().units("excl_pkg").len(), 1); + assert_eq!(s.server.workspace.index().units("clean_pkg").len(), 1); + + // First drop threshold for clean buffer ONLY (close excl first to isolate clean-only zero work!) + s.batch(vec![closed(&excl_uri)]); + let clean_uri = path_to_uri(&clean_path).expect("uri"); + let fp_before_clean_flip = s.server.workspace.index().fingerprint(); + let dfp_before_clean_flip = s.server.workspace.derived_fingerprint(); + let parses_before = vlog_parser::stats::parses(); + s.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { + "index": { "scope": "folder", "scopeDepth": 0, "maxFileSize": 1048576 }, + "exclude": ["ignored/**"], + "largeFile": { "threshold": 10 } + } } }), + ); + assert!(s.server.workspace.document(&clean_uri).expect("clean").large); + assert_eq!( + vlog_parser::stats::parses() - parses_before, + 1, + "clean buffer flipping false->true only calls Document::large(\"\") (1 empty parse), zero index parses" + ); + assert_eq!(s.server.workspace.index().fingerprint(), fp_before_clean_flip); + assert_eq!(s.server.workspace.derived_fingerprint(), dfp_before_clean_flip); + + // 2. Excluded unsaved buffer flipping false -> true must be removed from index and match fresh! + let mut s_excl = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ + "index": { "scope": "folder", "scopeDepth": 0, "maxFileSize": 1048576 }, + "exclude": ["ignored/**"], + "largeFile": { "threshold": 500 } + })), + did_open(&excl_path, excl_buf), + ], + ); + let _ = s_excl.drain(); + assert_eq!(s_excl.server.workspace.index().member("excl_pkg", "EX_BUF").len(), 1); + s_excl.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { + "index": { "scope": "folder", "scopeDepth": 0, "maxFileSize": 1048576 }, + "exclude": ["ignored/**"], + "largeFile": { "threshold": 10 } + } } }), + ); + assert_eq!( + s_excl.server.workspace.index().units("excl_pkg").len(), + 0, + "excluded unsaved buffer flipping false->true must be dropped from index" + ); + + // 3. In-scope dirty buffer (not yet indexed) flipping false -> true keeps ON_DISK, and true -> false -> true round-trip! + let mut s_rt = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + ClientSettings { + index_scope_depth: 0, + large_file_threshold: 10, + max_file_size: 1024 * 1024, + ..Default::default() + }, + ); + let _ = s_rt.drain(); + s_rt.open(&p_path, p_disk); + assert!(s_rt.server.workspace.document(&p_uri).expect("open").large); + change_full(&mut s_rt, &p_uri, 2, p_buf); + s_rt.server.flush_dirty(); + assert_eq!(s_rt.server.workspace.index().member("p_pkg", "ON_DISK").len(), 1); + + // Flip true -> false (threshold 500), widen into lib/q.sv so IN_BUF is indexed, then flip false -> true (threshold 10). + s_rt.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { + "index": { "scope": "folder", "scopeDepth": 0, "maxFileSize": 1048576 }, + "largeFile": { "threshold": 500 } + } } }), + ); + assert!(!s_rt.server.workspace.document(&p_uri).expect("open").large); + s_rt.open(&q_path, "package q_pkg;\n localparam Q = 1;\nendpackage\n"); + assert_eq!(s_rt.server.workspace.index().member("p_pkg", "IN_BUF").len(), 1); + + s_rt.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { + "index": { "scope": "folder", "scopeDepth": 0, "maxFileSize": 1048576 }, + "largeFile": { "threshold": 10 } + } } }), + ); + assert!(s_rt.server.workspace.document(&p_uri).expect("open").large); + assert_eq!(s_rt.server.workspace.index().member("p_pkg", "ON_DISK").len(), 1); + assert_eq!(s_rt.server.workspace.index().member("p_pkg", "IN_BUF").len(), 0); +} + +#[cfg(unix)] +#[test] +fn qa_r2_f2_multihop_transitive_symlink_headers() { + use lsp_types::request::{DocumentLinkRequest, GotoDefinition, HoverRequest}; + use std::os::unix::fs::symlink; + + let tree = Tree::new("qa_r2_f2_multihop_hdr"); + let real_text = "\ +`include \"link_h1.svh\" +module dut; + logic m = `H2_DEEP_ + logic s = `SHARED_MAC; +endmodule +"; + let h1_text = "`include \"link_h2.svh\"\n`define H1_MAC 1\n"; + let h2_text = "`define H2_DEEP_MAC 2\n`define SHARED_MAC 111\n"; + let other_hdr = "`define SHARED_MAC 222\n"; + + tree.write("z_real/real_b.sv", real_text); + tree.write("z_real/real_h1.svh", h1_text); + tree.write("z_real/real_h2.svh", h2_text); + tree.write("other/dup.svh", other_hdr); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/real_b.sv"), tree.path.join("a_link/link_a.sv")) + .expect("symlink"); + symlink(tree.path.join("z_real/real_h1.svh"), tree.path.join("a_link/link_h1.svh")) + .expect("symlink"); + symlink(tree.path.join("z_real/real_h2.svh"), tree.path.join("a_link/link_h2.svh")) + .expect("symlink"); + + let settings = wide_large(0, 1024 * 1024); + let mut via_canon = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings.clone()); + let _ = via_canon.drain(); + let canon_uri = via_canon.open(&tree.path.join("a_link/link_a.sv"), real_text); + + let mut via_target = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings); + let _ = via_target.drain(); + let target_uri = via_target.open(&tree.path.join("z_real/real_b.sv"), real_text); + + assert_eq!( + via_target.result( + DocumentLinkRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri } }), + ), + via_canon.result( + DocumentLinkRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &canon_uri } }), + ), + "multihop symlink header documentLink mismatch" + ); + assert_eq!( + via_target.result( + GotoDefinition::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri }, "position": { "line": 0, "character": 12 } }), + ), + via_canon.result( + GotoDefinition::METHOD, + serde_json::json!({ "textDocument": { "uri": &canon_uri }, "position": { "line": 0, "character": 12 } }), + ), + "multihop symlink header include definition mismatch" + ); + let comp_t = via_target.result( + Completion::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri }, "position": { "line": 2, "character": 22 } }), + ); + let comp_c = via_canon.result( + Completion::METHOD, + serde_json::json!({ "textDocument": { "uri": &canon_uri }, "position": { "line": 2, "character": 22 } }), + ); + assert_eq!(comp_t, comp_c, "multihop completion/related_macros mismatch"); + let comp_s = serde_json::to_string(&comp_t).expect("json"); + assert!(comp_s.contains("H2_DEEP_MAC"), "transitive h2 macro missing: {comp_s}"); + + let hov_t = via_target.result( + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri }, "position": { "line": 3, "character": 15 } }), + ); + let hov_c = via_canon.result( + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &canon_uri }, "position": { "line": 3, "character": 15 } }), + ); + assert_eq!(hov_t, hov_c, "multihop hover mismatch"); + let hov_s = serde_json::to_string(&hov_t).expect("json"); + assert!(!hov_s.contains("defined 2 times"), "hover narrowing failed: {hov_s}"); + assert!(hov_s.contains("111"), "hover picked wrong macro: {hov_s}"); +} + +#[cfg(unix)] +#[test] +fn qa_r2_f2_multihop_symlink_directory_completion_and_hover_narrowing() { + use lsp_types::request::HoverRequest; + use std::os::unix::fs::symlink; + + let tree = Tree::new("qa_r2_f2_multihop_dir_ok"); + let real_text = "\ +`include \"h1.svh\" +module dut; + logic m = `H2_DEEP_ + logic s = `SHARED_MAC; +endmodule +"; + let caller_text = "\ +`include \"../z_real_dir/h1.svh\" +module caller; + logic m = `H2_DEEP_ + logic s = `SHARED_MAC; +endmodule +"; + let h1_text = "`include \"h2.svh\"\n`define H1_MAC 1\n"; + let h2_text = "`define H2_DEEP_MAC 2\n`define SHARED_MAC 111\n"; + let other_hdr = "`define SHARED_MAC 222\n"; + + tree.write("z_real_dir/real_b.sv", real_text); + tree.write("z_real_dir/h1.svh", h1_text); + tree.write("z_real_dir/h2.svh", h2_text); + tree.write("rtl/caller.sv", caller_text); + tree.write("other/dup.svh", other_hdr); + symlink(tree.path.join("z_real_dir"), tree.path.join("a_link_dir")).expect("dir symlink"); + + let settings = wide_large(0, 1024 * 1024); + let mut via_canon = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings.clone()); + let _ = via_canon.drain(); + let canon_uri = via_canon.open(&tree.path.join("a_link_dir/real_b.sv"), real_text); + + let mut via_target = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings); + let _ = via_target.drain(); + let target_uri = via_target.open(&tree.path.join("z_real_dir/real_b.sv"), real_text); + let caller_uri = via_target.open(&tree.path.join("rtl/caller.sv"), caller_text); + + let comp_t = via_target.result( + Completion::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri }, "position": { "line": 2, "character": 22 } }), + ); + let comp_c = via_canon.result( + Completion::METHOD, + serde_json::json!({ "textDocument": { "uri": &canon_uri }, "position": { "line": 2, "character": 22 } }), + ); + assert_eq!(comp_t, comp_c, "symlink dir completion/related_macros mismatch"); + assert!( + serde_json::to_string(&comp_t).expect("json").contains("H2_DEEP_MAC"), + "transitive H2_DEEP_MAC missing" + ); + + let hov_t = via_target.result( + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri }, "position": { "line": 3, "character": 15 } }), + ); + let hov_c = via_canon.result( + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &canon_uri }, "position": { "line": 3, "character": 15 } }), + ); + assert_eq!(hov_t, hov_c, "symlink dir hover mismatch"); + let hov_s = serde_json::to_string(&hov_t).expect("json"); + assert!(!hov_s.contains("defined 2 times") && hov_s.contains("111"), "got {hov_s}"); + + // External caller including non-canonical ../z_real_dir/h1.svh also narrows transitively. + let caller_comp = serde_json::to_string(&via_target.result( + Completion::METHOD, + serde_json::json!({ "textDocument": { "uri": &caller_uri }, "position": { "line": 2, "character": 22 } }), + )) + .expect("json"); + assert!(caller_comp.contains("H2_DEEP_MAC"), "caller transitive macro missing"); + let caller_hov = serde_json::to_string(&via_target.result( + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &caller_uri }, "position": { "line": 3, "character": 15 } }), + )) + .expect("json"); + assert!(!caller_hov.contains("defined 2 times") && caller_hov.contains("111")); +} + +#[cfg(unix)] +#[test] +fn qa_r2_f2_multihop_symlink_directory_links_and_def_return_non_canonical() { + use lsp_types::request::{DocumentLinkRequest, GotoDefinition}; + use std::os::unix::fs::symlink; + + let tree = Tree::new("qa_r2_f2_multihop_dir_bug"); + let real_text = "`include \"h1.svh\"\nmodule dut;\nendmodule\n"; + tree.write("z_real_dir/real_b.sv", real_text); + tree.write("z_real_dir/h1.svh", "`include \"h2.svh\"\n"); + tree.write("z_real_dir/h2.svh", "`define H2_DEEP_MAC 2\n"); + symlink(tree.path.join("z_real_dir"), tree.path.join("a_link_dir")).expect("dir symlink"); + + let settings = wide_large(0, 1024 * 1024); + let mut via_canon = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings.clone()); + let _ = via_canon.drain(); + let canon_uri = via_canon.open(&tree.path.join("a_link_dir/real_b.sv"), real_text); + + let mut via_target = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings); + let _ = via_target.drain(); + let target_uri = via_target.open(&tree.path.join("z_real_dir/real_b.sv"), real_text); + + assert_eq!( + via_target.result( + DocumentLinkRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri } }), + ), + via_canon.result( + DocumentLinkRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": &canon_uri } }), + ), + "dir documentLink must resolve to canonical indexed a_link_dir/h1.svh" + ); + assert_eq!( + via_target.result( + GotoDefinition::METHOD, + serde_json::json!({ "textDocument": { "uri": &target_uri }, "position": { "line": 0, "character": 12 } }), + ), + via_canon.result( + GotoDefinition::METHOD, + serde_json::json!({ "textDocument": { "uri": &canon_uri }, "position": { "line": 0, "character": 12 } }), + ), + "dir include definition must resolve to canonical indexed a_link_dir/h1.svh" + ); +} + +#[cfg(unix)] +#[test] +fn qa_r2_f3_mid_scan_dirty_open_saved_none_and_closed() { + use std::os::unix::fs::symlink; + + // In-scope symlink (pos >= scan.at), already-stepped (pos < scan.at), and excluded (pos == None) + for (tag, excl, dir_name) in [ + ("in_scope_future", vec![], "a_link"), + ("in_scope_past", vec![], "0_link"), + ("excluded", vec!["ignored/**".to_string()], "ignored"), + ] { + let tree = ordering_tree(&format!("qa_r2_f3_save_none_{tag}")); + let disk_v1 = "module dut_sn;\n localparam V1 = 1;\nendmodule\n"; + let dirty_v2 = "module dut_sn;\n localparam DIRTY_V2 = 2;\nendmodule\n"; + let saved_v3 = "module dut_sn;\n localparam SAVED_V3 = 3;\nendmodule\n"; + let real_path = tree.path.join("z_real/dut.sv"); + let link_path = tree.path.join(format!("{dir_name}/dut.sv")); + if excl.is_empty() { + tree.write("z_real/dut.sv", disk_v1); + std::fs::create_dir_all(link_path.parent().expect("parent")).expect("dir"); + symlink(&real_path, &link_path).expect("symlink"); + } else { + tree.write(format!("{dir_name}/dut.sv").as_str(), disk_v1); + } + let target_open = if excl.is_empty() { &real_path } else { &link_path }; + let open_uri = path_to_uri(target_open).expect("uri"); + + // Pre-write saved_v3 right before didSave(None) arrives? Wait: simulate disk save via fs::write inside interleave? + // In probe::script, bursts are evaluated before the scan starts, so write saved_v3 to disk before scan? No, if we write before scan, disk would already be saved_v3! + // Instead, test didSave(None) where disk stays disk_v1 (user saved or reverted on disk without sending text), OR test after didOpen(dirty) -> didSave(None) -> didClose. + let _ = saved_v3; + let _ = probe::take_counts(); + probe::script([ + vec![opened(&open_uri, dirty_v2)], + vec![save_note(&open_uri)], + vec![closed(&open_uri)], + ]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": 1048576 }, + "exclude": excl, + "largeFile": { "threshold": 1000 } + }))], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty(), "{tag}: bursts arrived"); + settle(&mut settled); + + let fresh = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + ClientSettings { + index_scope: crate::settings::IndexScope::Workspace, + exclude: excl, + large_file_threshold: 1000, + max_file_size: 1048576, + ..Default::default() + }, + ); + assert_eq!( + settled.server.workspace.derived_fingerprint(), + fresh.server.workspace.derived_fingerprint(), + "{tag}: didOpen(dirty) -> didSave(None) -> didClose mid-scan must match fresh" + ); + } +} + +#[cfg(unix)] +#[test] +fn qa_r2_f3_two_symlink_uris_one_closed_already_same_drops_surviving_dirty() { + use std::os::unix::fs::symlink; + + // Case A: pos < scan.at already stepped cleanly (ON_DISK), then open BOTH 0_link/dut.sv (ON_DISK) + // and z_real/dut.sv (DIRTY_Z), then close 0_link/dut.sv mid-scan while z_real/dut.sv stays open! + let tree = ordering_tree("qa_r2_f3_two_uri_already_same"); + let disk_text = "module dut_two_a;\n localparam ON_DISK = 1;\nendmodule\n"; + let dirty_z = "module dut_two_a;\n localparam DIRTY_Z = 2;\nendmodule\n"; + tree.write("z_real/dut.sv", disk_text); + std::fs::create_dir_all(tree.path.join("0_link")).expect("dir"); + symlink(tree.path.join("z_real/dut.sv"), tree.path.join("0_link/dut.sv")).expect("symlink"); + let canon_path = tree.path.join("0_link/dut.sv"); + let real_path = tree.path.join("z_real/dut.sv"); + let canon_uri = path_to_uri(&canon_path).expect("uri"); + let real_uri = path_to_uri(&real_path).expect("uri"); + + let _ = probe::take_counts(); + probe::script([ + vec![opened(&canon_uri, disk_text), opened(&real_uri, dirty_z)], + vec![closed(&canon_uri)], + ]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": 1048576 }, + "largeFile": { "threshold": 1000 } + }))], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty()); + settle(&mut settled); + + assert_eq!( + settled.server.workspace.index().member("dut_two_a", "DIRTY_Z").len(), + 1, + "surviving open z_real/dut.sv DIRTY_Z must be indexed after closing clean 0_link/dut.sv (got ON_DISK={})", + settled.server.workspace.index().member("dut_two_a", "ON_DISK").len() + ); +} + +#[cfg(unix)] +#[test] +fn qa_r2_f3_two_symlink_uris_large_flip_one_closed_leaves_stale_index() { + use lsp_types::request::HoverRequest; + use std::os::unix::fs::symlink; + + let hover = |uri: &Uri| { + super::scan_ordering::ask( + 202, + HoverRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": uri }, "position": { "line": 0, "character": 7 } }), + ) + }; + + // Case B: a_link/dut.sv (DIRTY_A, absorbed) + z_real/dut.sv (ON_DISK), then didChange(a_link, HUGE) + // flips a_link to doc.large=true, then didClose(a_link) mid-scan while z_real remains open! + let tree = ordering_tree("qa_r2_f3_two_uri_large_flip"); + let disk_text = "module dut_two_b;\n localparam ON_DISK = 1;\nendmodule\n"; + let dirty_a = "module dut_two_b;\n localparam DIRTY_A = 2;\nendmodule\n"; + let huge_a = format!( + "module dut_two_b;\n localparam HUGE_A = 3;\n{}endmodule\n", + " // pad line\n".repeat(20) + ); + assert!(dirty_a.len() < 200 && huge_a.len() > 200); + tree.write("z_real/dut.sv", disk_text); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/dut.sv"), tree.path.join("a_link/dut.sv")).expect("symlink"); + let canon_uri = path_to_uri(&tree.path.join("a_link/dut.sv")).expect("uri"); + let real_uri = path_to_uri(&tree.path.join("z_real/dut.sv")).expect("uri"); + + let _ = probe::take_counts(); + probe::script([ + vec![opened(&canon_uri, dirty_a), opened(&real_uri, disk_text)], + vec![changed(&canon_uri, 2, &huge_a), hover(&canon_uri)], + vec![closed(&canon_uri)], + ]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": 1048576 }, + "largeFile": { "threshold": 200 } + }))], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty()); + settle(&mut settled); + + assert_eq!( + settled.server.workspace.index().member("dut_two_b", "ON_DISK").len(), + 1, + "after closing doc.large a_link/dut.sv with z_real/dut.sv open, index must hold ON_DISK (got DIRTY_A={})", + settled.server.workspace.index().member("dut_two_b", "DIRTY_A").len() + ); + assert_eq!( + settled.server.workspace.index().member("dut_two_b", "DIRTY_A").len(), + 0, + "stale DIRTY_A from closed a_link/dut.sv must not remain in index" + ); +} + +#[cfg(unix)] +#[test] +fn qa_r2_f3_two_symlink_uris_both_dirty_one_closed_mid_scan_converges() { + use std::os::unix::fs::symlink; + + // Normal Case: both a_link/dut.sv (DIRTY_A) and z_real/dut.sv (DIRTY_Z) open at pos >= scan.at, + // then close a_link/dut.sv mid-scan -> must converge to DIRTY_Z! + let tree = ordering_tree("qa_r2_f3_two_uri_normal"); + let disk_text = "module dut_two_n;\n localparam ON_DISK = 1;\nendmodule\n"; + let dirty_a = "module dut_two_n;\n localparam DIRTY_A = 2;\nendmodule\n"; + let dirty_z = "module dut_two_n;\n localparam DIRTY_Z = 3;\nendmodule\n"; + tree.write("z_real/dut.sv", disk_text); + std::fs::create_dir_all(tree.path.join("a_link")).expect("dir"); + symlink(tree.path.join("z_real/dut.sv"), tree.path.join("a_link/dut.sv")).expect("symlink"); + let canon_uri = path_to_uri(&tree.path.join("a_link/dut.sv")).expect("uri"); + let real_uri = path_to_uri(&tree.path.join("z_real/dut.sv")).expect("uri"); + + let _ = probe::take_counts(); + probe::script([ + vec![opened(&canon_uri, dirty_a), opened(&real_uri, dirty_z)], + vec![closed(&canon_uri)], + ]); + let mut settled = Session::staged( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + false, + CONFIGURATION_WAIT, + vec![configuration_answer(serde_json::json!({ + "index": { "scope": "workspace", "maxFileSize": 1048576 }, + "largeFile": { "threshold": 1000 } + }))], + ); + let _ = settled.drain(); + assert!(probe::unarrived().is_empty()); + settle(&mut settled); + + assert_eq!(settled.server.workspace.index().member("dut_two_n", "DIRTY_Z").len(), 1); + assert_eq!(settled.server.workspace.index().member("dut_two_n", "DIRTY_A").len(), 0); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/server/tests/mod.rs b/crates/lucisv_server/src/server/tests/mod.rs index e543df2..a718c1d 100644 --- a/crates/lucisv_server/src/server/tests/mod.rs +++ b/crates/lucisv_server/src/server/tests/mod.rs @@ -63,6 +63,7 @@ mod hierarchy_everywhere; mod hierarchy_reach; mod index; mod large_file; +mod lifecycle_r2; mod lint_snapshot; mod localized_reindex; mod ordering_r1; diff --git a/crates/lucisv_server/src/server/tests/startup.rs b/crates/lucisv_server/src/server/tests/startup.rs index f9a3f8b..bf80f34 100644 --- a/crates/lucisv_server/src/server/tests/startup.rs +++ b/crates/lucisv_server/src/server/tests/startup.rs @@ -45,7 +45,7 @@ fn pulling_with_a_bar() -> ClientAbilities { /// registration and the lens refresh that used to be issued ahead of it. /// `send_request` numbers off one counter that only ever goes up, so that /// first id is a fact about the order, not a guess. -fn configuration_answer(section: Value) -> Message { +pub(super) fn configuration_answer(section: Value) -> Message { Message::Response(Response::new_ok( RequestId::from("lucisv-0".to_string()), serde_json::json!([section]), @@ -70,7 +70,7 @@ fn the_whole_workspace_flat() -> Value { } /// A `textDocument/didOpen` over the wire, as the client sends it. -fn did_open(path: &Path, text: &str) -> Message { +pub(super) fn did_open(path: &Path, text: &str) -> Message { Message::Notification(Notification::new( DidOpenTextDocument::METHOD.to_string(), serde_json::json!({ diff --git a/crates/lucisv_server/src/state/buffers.rs b/crates/lucisv_server/src/state/buffers.rs index bbbbd02..20f90e5 100644 --- a/crates/lucisv_server/src/state/buffers.rs +++ b/crates/lucisv_server/src/state/buffers.rs @@ -8,6 +8,7 @@ use std::fs; use std::path::Path; use lsp_types::Uri; +use lucisv_core::walk::dir_id; use vlog_semantic::FileFacts; use super::discover::{oversize, Found}; @@ -19,9 +20,49 @@ impl Workspace { self.docs.get(uri) } - /// The open document backed by `path`, if there is one. + /// The open URI and document backed by `path` (exact path first, else + /// matching file identity without basename gating), if there is one. + pub fn open_document_for_path(&self, path: &Path) -> Option<(&Uri, &Document)> { + if let Some(found) = self.docs.iter().find(|(_, doc)| doc.path.as_deref() == Some(path)) { + return Some(found); + } + if self.docs.is_empty() { + return None; + } + let target = dir_id(path)?; + self.docs + .iter() + .filter(|(_, doc)| { + doc.path.as_deref().is_some_and(|p| { + !case_only_mismatch(p, path) && dir_id(p).as_ref() == Some(&target) + }) + }) + .min_by_key(|(_, doc)| doc.path.as_deref()) + } + + /// The open document backed by `path` (exact path first, else matching file + /// identity without basename gating), if there is one. pub fn document_for_path(&self, path: &Path) -> Option<&Document> { - self.docs.values().find(|doc| doc.path.as_deref() == Some(path)) + self.open_document_for_path(path).map(|(_, doc)| doc) + } + + /// Whether another currently open URI (distinct from `uri`) covers `path` + /// or its file identity. + pub(crate) fn has_other_document_for(&self, uri: &Uri, path: &Path) -> bool { + if self.docs.len() <= 1 { + return false; + } + if self.docs.iter().any(|(other, doc)| *other != *uri && doc.path.as_deref() == Some(path)) + { + return true; + } + let Some(target) = dir_id(path) else { return false }; + self.docs.iter().any(|(other, doc)| { + *other != *uri + && doc.path.as_deref().is_some_and(|p| { + !case_only_mismatch(p, path) && dir_id(p).as_ref() == Some(&target) + }) + }) } /// Every open document and its URI. @@ -100,21 +141,23 @@ impl Workspace { /// what is on disk. Same precedence the index rebuild uses, so a location /// is never computed against text the index did not see. pub fn text_of(&self, path: &Path) -> Option { - let open = self.docs.values().find(|d| d.path.as_deref() == Some(path)); - match open { + match self.document_for_path(path) { Some(doc) => Some(doc.text.clone()), None => fs::read_to_string(path).ok(), } } /// The text one in-scope file contributes right now, by `collect_sources`'s - /// rules — `None` when it contributes nothing at all. + /// rules — `None` when disk is over `maxFileSize` or cannot be read. + /// + /// An open buffer on the large-file fast path (`doc.large`) keeps its + /// on-disk index record subject to `maxFileSize` (Topo #63, Owner + /// decision 2), falling through to disk rather than suppressing it. pub(super) fn current_text(&self, path: &Path) -> Option { - if let Some(doc) = self.docs.values().find(|doc| doc.path.as_deref() == Some(path)) { - // A fast-path buffer contributes nothing, exactly as it does in - // `collect_sources` — indexing it is the parse the fast path - // exists to skip. - return (!doc.large).then(|| doc.text.clone()); + if let Some(doc) = self.document_for_path(path) { + if !doc.large { + return Some(doc.text.clone()); + } } if oversize(&Found::of(path), self.client.max_file_size, &mut 0).is_some() { return None; @@ -128,11 +171,22 @@ impl Workspace { /// no analysis of its own text to read. /// /// The buffer is found the same way [`Workspace::current_text`] finds the - /// text, so the two always speak for the same `Document`. + /// text, so the two always speak for the same `Document`, and facts are + /// stamped with canonical `path`. pub(super) fn analysis_of(&self, path: &Path) -> Option<(FileFacts, Vec)> { - let doc = self.docs.values().find(|doc| doc.path.as_deref() == Some(path))?; + let doc = self.document_for_path(path)?; (!doc.large).then(|| (doc.facts(path.to_path_buf()), doc.words())) } } +/// On case-insensitive filesystems, two paths differing only in ASCII case +/// are not symlinks and should not cross-match an open buffer to disk. +pub(super) fn case_only_mismatch(a: &Path, b: &Path) -> bool { + if cfg!(any(target_os = "macos", target_os = "windows")) { + a != b && a.to_string_lossy().eq_ignore_ascii_case(&b.to_string_lossy()) + } else { + false + } +} + // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/state/discover.rs b/crates/lucisv_server/src/state/discover.rs index a2fdfbd..dce25c3 100644 --- a/crates/lucisv_server/src/state/discover.rs +++ b/crates/lucisv_server/src/state/discover.rs @@ -43,7 +43,7 @@ use std::path::{Path, PathBuf}; use lucisv_core::config::Discovery; use lucisv_core::walk::{ - collect_files_below_tracked, collect_files_tracked, dir_id, DirectoryTracker, EXTENSIONS, + collect_files_below_tracked, collect_files_tracked, dir_id, DirId, DirectoryTracker, EXTENSIONS, }; use crate::scan_trace::ScanTrace; @@ -110,51 +110,40 @@ pub(super) fn oversize(found: &Found, cap: u64, stats: &mut usize) -> Option cap).then_some(size) } -/// The open buffers' files by **identity**, so a walked path that is a second -/// spelling of one of them can be recognised and left out. -/// -/// A symlinked directory gives every file under it a second path. The walk -/// reports each file under the first spelling that reaches it, which may not be -/// the one the buffer was opened by — and an index holding `a_alias/tb.sv` from -/// disk beside the open `z_real/tb.sv` holds one module twice and refuses to -/// rename it (`docs/features/walk-cycles/README.md`). -/// -/// **The name is the gate, and it is what keeps this free.** A directory alias -/// cannot change a file's *name*, so a walked file whose name no open buffer -/// shares cannot be one of them and is never stat'd: an ordinary workspace pays -/// nothing at all, and one with same-named files pays one `metadata` per -/// same-named candidate. A **file**-level symlink under a different name is out -/// of scope — two names for one inode that no directory relates, which every -/// other part of this server already treats as two files. -struct Aliased { - /// The names those buffers' files go by — the cheap half of the test. - names: HashSet, - /// Their `(dev, ino)` identities, read once per open buffer rather than - /// once per walked file. - ids: HashSet, -} - -impl Aliased { - /// The identities of `paths`, with the names to gate on. - fn of(paths: &HashSet<&Path>) -> Aliased { - let names = paths.iter().filter_map(|p| p.file_name()).map(|n| n.to_os_string()).collect(); - let ids = paths.iter().filter_map(|p| dir_id(p)).collect(); - Aliased { names, ids } - } - - /// Whether `path` names a file an open buffer already speaks for, by a - /// different spelling. `stats` counts the `metadata` calls it made. - fn speaks_for(&self, path: &Path, stats: &mut usize) -> bool { - if self.ids.is_empty() { - return false; +/// Deduplicate `files` by file identity (`(dev, ino)` on Unix / canonical path +/// elsewhere) without basename gating, keeping the lexicographically smallest +/// path for each identity and preserving list order. Un-statable paths (`None`) +/// are kept individually. Also returns the identity-to-canonical-path map. +pub(super) fn dedup_by_identity(files: Vec) -> (Vec, HashMap) { + let mut best: HashMap = HashMap::new(); + let mut has_id: Vec = Vec::with_capacity(files.len()); + for (i, found) in files.iter().enumerate() { + if let Some(id) = dir_id(&found.path) { + has_id.push(true); + if let Some(prev) = best.get_mut(&id) { + if found.path < files[*prev].path { + *prev = i; + } + } else { + best.insert(id, i); + } + } else { + has_id.push(false); } - let Some(name) = path.file_name() else { return false }; - if !self.names.contains(name) { - return false; - } - *stats += 1; - dir_id(path).is_some_and(|id| self.ids.contains(&id)) } + let mut keep = vec![false; files.len()]; + let mut by_id = HashMap::with_capacity(best.len()); + for (id, idx) in best { + keep[idx] = true; + by_id.insert(id, files[idx].path.clone()); + } + let mut deduped = Vec::with_capacity(files.len()); + for (i, found) in files.into_iter().enumerate() { + if !has_id[i] || keep[i] { + deduped.push(found); + } + } + (deduped, by_id) } impl Workspace { @@ -201,62 +190,82 @@ impl Workspace { trace: &mut ScanTrace, ) -> Sources { let cap = self.client.max_file_size; - // Every path an open buffer speaks for. Reading such a file from disk - // is work thrown away — the buffer's text replaces it below, whatever - // the disk says — so the read is skipped rather than undone. The cap is - // still consulted first, so an oversized file still reports itself - // skipped exactly as it did before the buffer put its own text back. - let spoken_for: HashSet<&Path> = - self.docs.values().filter_map(|doc| doc.path.as_deref()).collect(); - // …and every *other* spelling of those same files, which a directory - // alias makes and a path comparison cannot see ([`Aliased`]). - let aliased = Aliased::of(&spoken_for); let capping = trace.now(); let mut stats = 0usize; + let (deduped, scope_by_id) = dedup_by_identity(scope.files); let mut files: Vec = Vec::new(); - for found in scope.files { + for found in deduped { if let Some(size) = oversize(&found, cap, &mut stats) { watch(IndexEvent::Skipped { path: &found.path, size, cap }); continue; } - if spoken_for.contains(found.path.as_path()) { - continue; - } - if aliased.speaks_for(&found.path, &mut stats) { - continue; - } files.push(found.path); } ScanTrace::add(&mut trace.cap_ms, capping); trace.stats += stats; - // Open buffers override what is on disk, and contribute themselves - // when they are not on disk at all. + // Open non-large buffers override what is on disk for the same file + // (under scope's deterministic canonical spelling when present in + // scope), and contribute themselves when out of scope or oversized. // - // Except a buffer on the large-file fast path, which overrides disk - // with *nothing*: indexing it means parsing the hundred megabytes the - // fast path exists not to parse. Removing the path rather than leaving - // the disk copy in is the honest half of that — the alternative would - // be an index describing a file the user is looking at by bytes it no - // longer has. See `docs/features/large-file-mode/README.md` for the - // interaction with `lucisv.index.maxFileSize`, whose "an open buffer is - // never capped" rule this is the one exception to. + // Open `doc.large` buffers (Topo #63, Owner decision 2) are skipped + // here so their on-disk index record stays untouched subject to + // `maxFileSize`. let buffering = trace.now(); let mut analyzed = Analyzed::default(); let mut buffered: HashMap = HashMap::new(); - for doc in self.docs.values() { - let Some(path) = doc.path.clone() else { continue }; - files.retain(|p| p != &path); - if !doc.large { - if analyses == HeldAnalyses::Wanted { - analyzed.facts.insert(path.clone(), doc.facts(path.clone())); - analyzed.words.insert(path.clone(), doc.words()); + let has_open_non_large = self.docs.values().any(|doc| !doc.large && doc.path.is_some()); + if has_open_non_large { + let mut files_set: HashSet = files.iter().cloned().collect(); + let mut open_candidates: Vec<(PathBuf, Option, &super::Document)> = self + .docs + .values() + .filter(|doc| !doc.large) + .filter_map(|doc| { + let doc_path = doc.path.as_ref()?; + let id = dir_id(doc_path); + let target = id + .as_ref() + .and_then(|key| scope_by_id.get(key)) + .cloned() + .unwrap_or_else(|| doc_path.clone()); + Some((target, id, doc)) + }) + .collect(); + open_candidates.sort_by(|a, b| { + a.0.cmp(&b.0) + .then_with(|| { + (a.2.path.as_deref() != Some(a.0.as_path())) + .cmp(&(b.2.path.as_deref() != Some(b.0.as_path()))) + }) + .then_with(|| a.2.path.cmp(&b.2.path)) + }); + let mut seen_targets: HashSet = HashSet::new(); + let mut seen_open_ids: HashSet = HashSet::new(); + for (target, id, doc) in open_candidates { + if !seen_targets.insert(target.clone()) + || id.is_some_and(|key| !seen_open_ids.insert(key)) + { + continue; } - buffered.insert(path.clone(), doc.text.clone()); - files.push(path); + if files_set.insert(target.clone()) { + files.push(target.clone()); + } + if analyses == HeldAnalyses::Wanted { + analyzed.facts.insert(target.clone(), doc.facts(target.clone())); + analyzed.words.insert(target.clone(), doc.words()); + } + buffered.insert(target, doc.text.clone()); } } ScanTrace::add(&mut trace.buffers_ms, buffering); - Sources { files, buffered, analyzed, incdirs: scope.incdirs, warnings: scope.warnings } + Sources { + files, + buffered, + analyzed, + canonical_ids: scope_by_id, + incdirs: scope.incdirs, + warnings: scope.warnings, + } } /// The files the index covers, and what the user should be told about how @@ -296,7 +305,7 @@ impl Workspace { ScanTrace::add(&mut trace.filelist_ms, reading); match read { Ok(list) => Scope { - files: list.files.into_iter().map(Found::unmeasured).collect(), + files: dedup_by_identity(list.files.into_iter().map(Found::unmeasured).collect()).0, incdirs: list.incdirs, warnings: list.warnings, }, @@ -414,6 +423,7 @@ impl Workspace { } let sorting = trace.now(); sort_found(&mut out); + let (out, _) = dedup_by_identity(out); ScanTrace::add(&mut trace.sort_ms, sorting); out } @@ -542,12 +552,36 @@ impl Workspace { return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None); } // Every path the neighbourhood walk named, before the cap has had a - // say: what the remaining walk must not decide about a second time. + // say, plus any open non-large buffers: what the remaining walk must + // not decide about a second time. let mut seen: HashSet = head.iter().map(|found| found.path.clone()).collect(); - seen.extend(self.docs.values().filter_map(|doc| doc.path.clone())); + seen.extend(self.docs.values().filter(|doc| !doc.large).filter_map(|doc| doc.path.clone())); let scope = Scope { files: head, incdirs: Vec::new(), warnings }; let sources = self.overlay_buffers(scope, watch, HeldAnalyses::Wanted, trace); - (sources, Some(PendingDiscovery { roots: self.roots.clone(), seen, tracker })) + seen.extend(sources.files.iter().cloned()); + let mut seen_ids: HashMap = HashMap::new(); + for path in &seen { + if let Some(id) = dir_id(path) { + seen_ids + .entry(id) + .and_modify(|prev| { + if path < prev { + *prev = path.clone(); + } + }) + .or_insert_with(|| path.clone()); + } + } + ( + sources, + Some(PendingDiscovery { + roots: self.roots.clone(), + seen, + seen_ids, + tracker, + file_conflict: false, + }), + ) } /// Whether some directory between `root` and `dir` holds a **second @@ -614,6 +648,7 @@ impl Workspace { } let sorting = trace.now(); sort_found(&mut out); + let (out, _) = dedup_by_identity(out); ScanTrace::add(&mut trace.sort_ms, sorting); out } @@ -646,6 +681,7 @@ impl Workspace { pub(super) fn rest_of_scope( &self, pending: &mut PendingDiscovery, + canonical_ids: &mut HashMap, watch: &mut dyn FnMut(IndexEvent), trace: &mut ScanTrace, ) -> (Vec, Vec, usize) { @@ -657,30 +693,52 @@ impl Workspace { &mut |w| warnings.push(w), trace, ); - // The same gate the neighbourhood applied: a file an open buffer - // already speaks for, reached here by **another** spelling (a - // same-named file symlink outside the head), must not be indexed a - // second time. The buffer's own spelling is not an alias — a buffer - // opened mid-scan is discovered here for the first time and must land - // in the work list — so the gate is asked only about other paths. - // Found by QA on §62.1, twice: the head walk had the gate and this walk - // did not; then the gate matched a mid-scan buffer against itself. - let spoken_for: HashSet<&Path> = - self.docs.values().filter_map(|doc| doc.path.as_deref()).collect(); - let aliased = Aliased::of(&spoken_for); + let mut open_ids: HashMap = HashMap::new(); + for doc in self.docs.values().filter(|doc| !doc.large) { + let Some(path) = doc.path.as_ref() else { continue }; + if let Some(id) = dir_id(path) { + open_ids + .entry(id) + .and_modify(|prev| { + if path < prev { + *prev = path.clone(); + } + }) + .or_insert_with(|| path.clone()); + } + } let cap = self.client.max_file_size; let capping = trace.now(); let mut stats = 0usize; let mut skipped = 0usize; let mut files: Vec = Vec::new(); for found in walked { - // Already decided about by the neighbourhood: indexed, capped out, - // or spoken for by an open buffer. Deciding again would step a - // file twice or report one skip as two. - let another_spelling = !spoken_for.contains(found.path.as_path()); - if seen.contains(&found.path) - || (another_spelling && aliased.speaks_for(&found.path, &mut stats)) - { + if let Some(id) = dir_id(&found.path) { + let dup = if !pending.seen_ids.is_empty() || !open_ids.is_empty() { + pending.seen_ids.get(&id).or_else(|| open_ids.get(&id)) + } else { + None + }; + let is_dup = dup.is_some(); + let conflict = dup.is_some_and(|already| &found.path < already); + if !pending.seen_ids.contains_key(&id) { + canonical_ids + .entry(id) + .and_modify(|prev| { + if found.path < *prev { + *prev = found.path.clone(); + } + }) + .or_insert_with(|| found.path.clone()); + } + if is_dup { + if conflict { + pending.file_conflict = true; + } + continue; + } + } + if seen.contains(&found.path) { continue; } if let Some(size) = oversize(&found, cap, &mut stats) { @@ -783,6 +841,7 @@ fn sibling_files(dirs: &[PathBuf], trace: &mut ScanTrace) -> Vec { trace.walk_dirs += dirs.len(); let sorting = trace.now(); sort_found(&mut out); + let (out, _) = dedup_by_identity(out); ScanTrace::add(&mut trace.sort_ms, sorting); out } diff --git a/crates/lucisv_server/src/state/incremental.rs b/crates/lucisv_server/src/state/incremental.rs index dacea42..fa5f3da 100644 --- a/crates/lucisv_server/src/state/incremental.rs +++ b/crates/lucisv_server/src/state/incremental.rs @@ -8,8 +8,6 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; -use lucisv_core::walk::dir_id; - use vlog_semantic::FileFacts; use super::Workspace; @@ -71,9 +69,13 @@ impl Workspace { /// [`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() { + let Some(held_id) = self.index_file_id(path) else { return self.add_open_buffer(path); - } + }; + let Some(held_path) = self.index.path(held_id).map(Path::to_path_buf) else { + return OneFile::NotHeld; + }; + let path = held_path.as_path(); // Re-indexing one file *is* the claim that its bytes moved. self.forget_view(path); let Some(text) = self.current_text(path) else { @@ -134,14 +136,13 @@ impl Workspace { 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.invalidate_identities(); 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(); @@ -154,28 +155,79 @@ impl Workspace { 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)`. + /// Whether the index holds the file at `path` under another name or + /// symlink spelling, matching `(dev, ino)` (or canonical path elsewhere) + /// without basename gating. 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(); - // By reference: the id is `Copy` on unix and an owned path elsewhere. - self.index.files().iter().filter(named).any(|held| dir_id(held).as_ref() == Some(&id)) + self.index_file_id(path).is_some() } /// 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) { + /// gone, capped or unreadable. Uses fast tombstoned removal plus localized + /// `candidates` name refreshing (`set_file_words` + `refresh_names`). + pub(super) fn remove_one(&mut self, path: &Path) { + let declared = self.index.facts_for(path).map(|facts| { + let (symbols, macros) = facts.declared_names(); + ( + symbols.into_iter().map(str::to_string).collect::>(), + macros.into_iter().map(str::to_string).collect::>(), + ) + }); self.index.remove_file(path); - self.candidates.remove_file(&self.index, path); + self.invalidate_identities(); + self.candidates.set_file_words(path, Vec::new()); + 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.includes.remove_file(path, self.index.files()); self.includes.refresh_naming(path); self.refresh_overlays(); } + /// Whether closing `uri` while a scan is running affects the scan's work + /// list (buffer already absorbed into the running scan, another open + /// buffer sharing the same path/file, excluded/unlisted file that may + /// have been taken in, or unsaved edits in a non-large buffer). + pub fn closing_affects_running_scan(&self, uri: &lsp_types::Uri) -> bool { + let Some(doc) = self.document(uri) else { return false }; + let Some(path) = doc.path.as_deref() else { return false }; + let target = self.held_path_for(path).unwrap_or_else(|| path.to_path_buf()); + if self.scan_absorbed.contains(path, &target) || self.has_other_document_for(uri, path) { + return true; + } + if !self.scope_could_take(&target) { + return !doc.large; + } + !doc.large && std::fs::read_to_string(&target).ok().as_ref() != Some(&doc.text) + } + + /// Close `uri` and, when `reconcile_index` is true, reconcile `self.index` + /// with the post-close state: remove excluded/unlisted or missing files via + /// the fast tombstoned `remove_one` path, or re-index in-scope files from + /// disk (or surviving buffer) via `update_one_file`. Returns whether the + /// index moved. + pub fn close_and_reconcile(&mut self, uri: &lsp_types::Uri, reconcile_index: bool) -> bool { + let closing_path = self.document(uri).and_then(|doc| doc.path.clone()); + self.close_document(uri); + if !reconcile_index { + return false; + } + let Some(path) = closing_path else { return false }; + let Some(held_path) = self.held_path_for(&path) else { + return false; + }; + if self.document_for_path(&held_path).is_some() { + return self.update_one_file(&held_path) == OneFile::Changed; + } + if !self.scope_could_take(&held_path) { + self.remove_one(&held_path); + return true; + } + self.update_one_file(&held_path) == OneFile::Changed + } + /// 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 @@ -256,12 +308,46 @@ impl Workspace { /// buffer's cross-file answers. #[cfg(test)] pub fn derived_fingerprint(&self) -> String { + let dense: std::collections::HashMap = self + .index + .files() + .iter() + .enumerate() + .filter_map(|(live, path)| Some((self.index.file_id(path)?, live as u32))) + .collect(); + let remap_def = |def: &vlog_semantic::Def| { + let mut remapped = def.clone(); + if let Some(&id) = dense.get(&def.file) { + remapped.file = vlog_semantic::FileId(id); + } + remapped + }; 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::>()) + let mapped: Vec<_> = doc + .external + .iter() + .map(|(id, target)| { + let mapped = match target { + vlog_semantic::ExternalTarget::Resolved(def) => { + vlog_semantic::ExternalTarget::Resolved(remap_def(def)) + } + vlog_semantic::ExternalTarget::Ambiguous(defs) => { + vlog_semantic::ExternalTarget::Ambiguous( + defs.iter().map(remap_def).collect(), + ) + } + vlog_semantic::ExternalTarget::StillUnresolved => { + vlog_semantic::ExternalTarget::StillUnresolved + } + }; + (id, mapped) + }) + .collect(); + format!("{} {:?}", uri.as_str(), mapped) }) .collect(); format!( diff --git a/crates/lucisv_server/src/state/mod.rs b/crates/lucisv_server/src/state/mod.rs index 30389ec..26d192f 100644 --- a/crates/lucisv_server/src/state/mod.rs +++ b/crates/lucisv_server/src/state/mod.rs @@ -15,12 +15,13 @@ //! and `sources` (the file sets handed to refactorings). use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::rc::Rc; use lsp_types::Uri; -use vlog_semantic::{FileFacts, WorkspaceIndex}; +use lucisv_core::walk::{dir_id, DirId}; +use vlog_semantic::{FileFacts, FileId, WorkspaceIndex}; use crate::candidates::Candidates; use crate::includes::IncludeGraph; @@ -33,6 +34,7 @@ pub(crate) mod discover; mod document; mod incremental; mod port_grace; +mod reconcile; mod rescan; mod scan; mod scope; @@ -117,6 +119,10 @@ pub struct Workspace { /// without changing an answer, and every way a file's text can move drops /// its entry (see [`Workspace::file_view`]). views: RefCell>>, + /// Lazy reverse map from physical file identity (`(dev, ino)` on Unix, + /// canonical path elsewhere) to the canonical path stored in `index`. + /// Cleared whenever `index`'s live path set mutates. + identities: RefCell>>, /// The trace of the scan that finished most recently, waiting for the /// server to read it out and log it. Held here rather than returned from /// [`Workspace::finish_scan`] so that no caller's signature moves for a @@ -129,6 +135,45 @@ pub struct Workspace { /// is in, while that entry's diagnostics are held back /// (`docs/features/port-entry-grace/README.md`). grace: PortGrace, + /// Open-buffer paths and physical file identities whose text or analysis + /// was absorbed into the currently running scan, cleared at `begin_scan` + /// and `finish_scan`. + scan_absorbed: ScanAbsorbed, +} + +/// Open-buffer paths and physical file identities absorbed into an active scan. +#[derive(Default)] +pub(super) struct ScanAbsorbed { + paths: HashSet, + ids: HashMap, +} + +impl ScanAbsorbed { + pub(super) fn clear(&mut self) { + self.paths.clear(); + self.ids.clear(); + } + + pub(super) fn record(&mut self, target: &Path, open_path: Option<&Path>, id: Option<&DirId>) { + self.paths.insert(target.to_path_buf()); + if let Some(open) = open_path { + self.paths.insert(open.to_path_buf()); + } + if let Some(id) = + id.cloned().or_else(|| dir_id(target)).or_else(|| open_path.and_then(dir_id)) + { + self.ids.entry(id).or_insert_with(|| target.to_path_buf()); + } + } + + pub(super) fn contains(&self, path: &Path, target: &Path) -> bool { + if self.paths.contains(target) || self.paths.contains(path) { + return true; + } + let Some(id) = dir_id(path) else { return false }; + let Some(absorbed) = self.ids.get(&id) else { return false }; + !buffers::case_only_mismatch(absorbed, path) + } } impl Workspace { @@ -136,6 +181,58 @@ impl Workspace { &self.index } + pub(super) fn invalidate_identities(&self) { + *self.identities.borrow_mut() = None; + } + + /// Resolve `path` to its indexed [`FileId`], matching exact spelling first + /// and falling back to file identity (`(dev, ino)` / canonical path) so + /// symlinked spellings resolve to the same index slot while preserving + /// ASCII case-mismatch separation. + pub fn index_file_id(&self, path: &Path) -> Option { + if let Some(id) = self.index.file_id(path) { + return Some(id); + } + let target = dir_id(path)?; + let mut cache = self.identities.borrow_mut(); + let map = cache.get_or_insert_with(|| { + let mut map = HashMap::with_capacity(self.index.files().len()); + for held in self.index.files() { + if let Some(id) = dir_id(held) { + map.entry(id).or_insert_with(|| held.clone()); + } + } + map + }); + let held = map.get(&target)?; + (!buffers::case_only_mismatch(held, path)).then(|| self.index.file_id(held)).flatten() + } + + /// The canonical path `self.index` holds for `path`, matching either exact + /// path or file identity. + pub fn held_path_for(&self, path: &Path) -> Option { + self.index_file_id(path).and_then(|id| self.index.path(id).map(Path::to_path_buf)) + } + + /// The canonical indexed path for `path`, falling back to `path` itself + /// when not currently in the index. + pub fn index_path_for(&self, path: &Path) -> PathBuf { + self.held_path_for(path).unwrap_or_else(|| path.to_path_buf()) + } + + /// Whether `a` and `b` refer to the same physical file (matching exact + /// path or `(dev, ino)` / canonical path while preserving ASCII + /// case-mismatch separation). + pub fn is_same_file(&self, a: &Path, b: &Path) -> bool { + if a == b { + return true; + } + if buffers::case_only_mismatch(a, b) { + return false; + } + dir_id(a).is_some_and(|id| dir_id(b).as_ref() == Some(&id)) + } + /// The index record this workspace already holds for **exactly these /// bytes**, or nothing. /// diff --git a/crates/lucisv_server/src/state/reconcile.rs b/crates/lucisv_server/src/state/reconcile.rs new file mode 100644 index 0000000..20db2a7 --- /dev/null +++ b/crates/lucisv_server/src/state/reconcile.rs @@ -0,0 +1,261 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! Reconciling open buffers (mid-scan, widen, and `largeFile.threshold` +//! drops) with the workspace index and active scan state. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; + +use lsp_types::Uri; +use lucisv_core::walk::{dir_id, DirId}; +use vlog_semantic::FileFacts; + +use super::discover::{oversize, Found}; +use super::scan::{Analyzed, Scan, ScanKind}; +use super::{OneFile, Workspace}; +use crate::includes; + +/// Accumulated file-set state passed between [`Workspace::begin_widen`] and +/// [`Workspace::reconcile_widen_buffers`]. +pub(super) struct WidenOverlay { + pub(super) files: Vec, + pub(super) files_set: HashSet, + pub(super) file_ids: HashMap, + pub(super) gone: Vec, + pub(super) gone_set: HashSet, + pub(super) held: HashSet, + pub(super) held_ids: HashMap, + pub(super) widened_by_id: HashMap, + pub(super) analyzed: Analyzed, + pub(super) buffered: HashMap, + pub(super) stats: usize, +} + +impl Workspace { + /// Overlay non-large open buffers onto their deterministic canonical paths + /// and reconcile held `doc.large` buffers back to disk (subject to + /// `maxFileSize`) during [`Workspace::begin_widen`]. + pub(super) fn reconcile_widen_buffers(&self, w: &mut WidenOverlay) { + let mut candidates: Vec<(bool, &PathBuf, Option, PathBuf, &super::Document)> = self + .docs + .values() + .filter(|doc| !doc.large) + .filter_map(|doc| { + let doc_path = doc.path.as_ref()?; + let id = dir_id(doc_path); + let target = id + .as_ref() + .and_then(|k| { + w.file_ids + .get(k) + .or_else(|| w.held_ids.get(k).filter(|p| !w.gone_set.contains(*p))) + .or_else(|| w.widened_by_id.get(k)) + }) + .cloned() + .unwrap_or_else(|| doc_path.clone()); + Some((doc_path != &target, doc_path, id, target, doc)) + }) + .collect(); + candidates.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(b.1))); + let mut seen_open_ids: HashSet = HashSet::new(); + let mut overlaid: HashSet = HashSet::new(); + for (_, _, doc_id, target, doc) in candidates { + if overlaid.contains(&target) || doc_id.is_some_and(|id| !seen_open_ids.insert(id)) { + continue; + } + overlaid.insert(target.clone()); + if w.files_set.insert(target.clone()) { + w.files.push(target.clone()); + } + w.analyzed.facts.insert(target.clone(), doc.facts(target.clone())); + w.analyzed.words.insert(target.clone(), doc.words()); + w.buffered.insert(target, doc.text.clone()); + } + // Owner decision 2 (Topo #63): keep disk index records for `doc.large` + // buffers (subject to `maxFileSize`), dropping only missing/oversize ones. + let cap = self.client.max_file_size; + for doc in self.docs.values().filter(|doc| doc.large) { + let Some(doc_path) = doc.path.as_ref() else { continue }; + let target = match dir_id(doc_path).and_then(|id| w.held_ids.get(&id)) { + Some(path) => path.clone(), + None if w.held.contains(doc_path) => doc_path.clone(), + None => continue, + }; + if overlaid.contains(&target) + || w.gone_set.contains(&target) + || w.files_set.contains(&target) + { + continue; + } + if std::fs::metadata(&target).is_err() + || oversize(&Found::of(&target), cap, &mut w.stats).is_some() + { + if w.gone_set.insert(target.clone()) { + w.gone.push(target); + } + } else if w.files_set.insert(target.clone()) { + w.files.push(target); + } + } + } + + /// Reconcile open non-large buffers opened (or updated) mid-scan into + /// `scan` so excluded, unlisted, or unsaved buffers — including symlinks + /// whose canonical spelling was skipped by `maxFileSize` — absorb + /// identically to opening before the scan starts (Topo #50, #51). + pub(super) fn reconcile_open_buffers_into(&mut self, scan: &mut Scan) { + let mut open_non_large: Vec<&super::Document> = + self.docs.values().filter(|doc| !doc.large && doc.path.is_some()).collect(); + if open_non_large.is_empty() { + return; + } + open_non_large.sort_by(|a, b| a.path.cmp(&b.path)); + let work_pos: HashMap = + scan.work.iter().enumerate().map(|(i, p)| (p.clone(), i)).collect(); + let mut work_ids: HashMap = HashMap::with_capacity(scan.work.len()); + for (i, p) in scan.work.iter().enumerate() { + if let Some(id) = dir_id(p) { + work_ids.entry(id).or_insert(i); + } + } + let mut paths_set: HashSet = scan.paths.iter().cloned().collect(); + let mut paths_changed = false; + let mut added_ids: HashSet = HashSet::new(); + let mut added_paths: HashSet = HashSet::new(); + let mut matched_positions: HashSet = HashSet::new(); + + struct RankedDoc { + non_exact: bool, + path: PathBuf, + target: PathBuf, + pos: Option, + id: Option, + text: String, + facts: FileFacts, + words: Vec, + } + let mut ranked: Vec = open_non_large + .into_iter() + .filter_map(|doc| { + let path = doc.path.as_ref()?; + let id = dir_id(path); + let pos = work_pos + .get(path) + .copied() + .or_else(|| id.as_ref().and_then(|k| work_ids.get(k).copied())); + let target = pos + .map(|i| scan.work[i].clone()) + .or_else(|| id.as_ref().and_then(|k| scan.canonical_ids.get(k)).cloned()) + .unwrap_or_else(|| path.clone()); + let non_exact = target != *path; + Some(RankedDoc { + non_exact, + path: path.clone(), + target: target.clone(), + pos, + id, + text: doc.text.clone(), + facts: doc.facts(target), + words: doc.words(), + }) + }) + .collect(); + ranked.sort_by(|a, b| a.non_exact.cmp(&b.non_exact).then_with(|| a.path.cmp(&b.path))); + + for RankedDoc { path, target, pos, id, text, facts, words, .. } in ranked { + if let Some(pos) = pos { + if !matched_positions.insert(pos) { + continue; + } + let target = scan.work[pos].clone(); + if pos >= scan.at { + self.scan_absorbed.record(&target, Some(&path), id.as_ref()); + scan.buffered.insert(target.clone(), text); + if scan.kind == ScanKind::Whole { + scan.analyzed.facts.insert(target.clone(), facts); + scan.analyzed.words.insert(target, words); + } + continue; + } + let was_unread = scan.unread.contains(&target); + scan.unread.retain(|p| p != &target); + let staged_match = scan + .staged_at + .iter() + .position(|&p| p == pos) + .map(|idx| scan.staged[idx] == facts); + let already_same = !was_unread + && match staged_match { + Some(eq) => eq, + None => self.index.facts_for(&target) == Some(&facts), + }; + if already_same { + continue; + } + self.scan_absorbed.record(&target, Some(&path), id.as_ref()); + self.open_store(&mut scan.trace); + self.cache.record(&facts, &text); + scan.includes.insert(target.clone(), includes::scan(&text)); + scan.words.insert(target, words); + if let Some(idx) = scan.staged_at.iter().position(|&p| p == pos) { + scan.staged[idx] = facts; + } else { + scan.staged.push(facts); + scan.staged_at.push(pos); + } + } else { + if id.as_ref().is_some_and(|k| added_ids.contains(k)) + || added_paths.contains(&target) + { + continue; + } + self.scan_absorbed.record(&target, Some(&path), id.as_ref()); + if let Some(k) = id { + added_ids.insert(k); + } + added_paths.insert(target.clone()); + scan.work.push(target.clone()); + if paths_set.insert(target.clone()) { + scan.paths.push(target.clone()); + paths_changed = true; + } + scan.buffered.insert(target.clone(), text); + scan.analyzed.facts.insert(target.clone(), facts); + scan.analyzed.words.insert(target, words); + } + } + if paths_changed { + scan.paths.sort(); + scan.paths.dedup(); + } + } + + /// Reconcile `held_path` in the index after `uri` flipped into `doc.large`: + /// drop excluded/oversize/missing entries or restore the disk record when + /// unsaved edits were previously indexed, skipping work when the disk + /// record already matches (Topo #63). + pub fn reconcile_large_buffer( + &mut self, + uri: &Uri, + held_path: &Path, + prev_facts: &FileFacts, + ) -> bool { + let Some(doc) = self.document(uri) else { return false }; + if !doc.large { + return false; + } + if !self.scope_could_take(held_path) { + self.remove_one(held_path); + return true; + } + if !self.has_other_document_for(uri, held_path) + && self.index.facts_for(held_path) == Some(prev_facts) + && std::fs::read_to_string(held_path).ok().as_ref() == Some(&doc.text) + { + return false; + } + self.update_one_file(held_path) == OneFile::Changed + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/state/rescan.rs b/crates/lucisv_server/src/state/rescan.rs index 59079c6..a606b87 100644 --- a/crates/lucisv_server/src/state/rescan.rs +++ b/crates/lucisv_server/src/state/rescan.rs @@ -11,8 +11,9 @@ use std::path::{Path, PathBuf}; use vlog_semantic::FileFacts; -use super::discover::oversize; -use super::scan::{self, Analyzed, IndexEvent, Scan, ScanKind}; +use super::discover::{dedup_by_identity, oversize}; +use super::reconcile::WidenOverlay; +use super::scan::{self, IndexEvent, Scan, ScanKind}; use super::{StoreOpen, Workspace}; use crate::candidates::Candidates; use crate::includes::{self, IncludeGraph}; @@ -21,6 +22,7 @@ use crate::scan_order::{self, WorkList}; use crate::scan_trace::{CacheWork, ScanTrace}; #[cfg(test)] use crate::settings::IndexScope; +use lucisv_core::walk::{dir_id, DirId}; impl Workspace { /// Take the work list one scan will run through: resolve the scope and put @@ -35,6 +37,7 @@ impl Workspace { /// is never stepped changes nothing but the view cache and the open cache /// handle. pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent), trace: bool) -> Scan { + self.scan_absorbed.clear(); let mut trace = ScanTrace::opened(&mut self.scans, trace, "whole"); // A rescan says nothing about *which* file moved, so nothing held from // before it can be trusted. @@ -57,6 +60,19 @@ impl Workspace { ScanTrace::add(&mut trace.discovery_ms, discovering); let buffered = std::mem::take(&mut scope.buffered); let analyzed = std::mem::take(&mut scope.analyzed); + let canonical_ids = std::mem::take(&mut scope.canonical_ids); + for path in buffered.keys().chain(analyzed.facts.keys()) { + self.scan_absorbed.record(path, None, None); + } + for doc in self.docs.values().filter(|doc| !doc.large) { + let Some(doc_path) = doc.path.as_deref() else { continue }; + let id = dir_id(doc_path); + let target = + id.as_ref().and_then(|k| canonical_ids.get(k)).map_or(doc_path, PathBuf::as_path); + if buffered.contains_key(target) || analyzed.facts.contains_key(target) { + self.scan_absorbed.record(target, Some(doc_path), id.as_ref()); + } + } let ordering = trace.now(); // The same list the index will be built from, with the user's own // neighbourhood moved to the front of it. @@ -89,6 +105,7 @@ impl Workspace { paths, gone: Vec::new(), analyzed, + canonical_ids, incdirs: scope.incdirs, warnings: scope.warnings, at: 0, @@ -141,70 +158,87 @@ impl Workspace { let mut trace = ScanTrace::opened(&mut self.scans, trace, "widen"); let discovering = trace.now(); let held: HashSet = self.index.files().iter().cloned().collect(); + let mut held_ids: HashMap = HashMap::new(); + for path in &held { + if let Some(id) = dir_id(path) { + held_ids.entry(id).or_insert_with(|| path.clone()); + } + } let cap = self.client.max_file_size; - let spoken_for: HashSet<&Path> = - self.docs.values().filter_map(|doc| doc.path.as_deref()).collect(); + let open_non_large_ids: HashSet = self + .docs + .values() + .filter(|doc| !doc.large) + .filter_map(|doc| doc.path.as_deref().and_then(dir_id)) + .collect(); let mut skipped = 0usize; let mut files: Vec = Vec::new(); let mut warnings: Vec = Vec::new(); - // The walk of the *added* directories alone, by the same rung-3 rules - // `folder_files` follows — the whole scope is the union of these walks, - // so the files this one finds beyond what is already indexed are - // exactly the ones the widen owes. + let mut gone: Vec = Vec::new(); + let mut gone_set: HashSet = HashSet::new(); let mut stats = 0usize; - for found in self.widened_files(added, &mut |w| warnings.push(w), &mut trace) { + let (widened, widened_by_id) = + dedup_by_identity(self.widened_files(added, &mut |w| warnings.push(w), &mut trace)); + for found in widened { let path = found.path.clone(); - // Already indexed: by another scope directory this walk overlaps, - // or by an earlier scan. Re-reading it is the cost this path - // exists to avoid. if held.contains(&path) { continue; } + if let Some(id) = dir_id(&path) { + if let Some(existing) = held_ids.get(&id).cloned() { + if path < existing + && (open_non_large_ids.contains(&id) + || oversize(&found, cap, &mut stats).is_none()) + { + if gone_set.insert(existing.clone()) { + gone.push(existing); + } + held_ids.insert(id, path.clone()); + files.push(path); + } + continue; + } + } if let Some(size) = oversize(&found, cap, &mut stats) { watch(IndexEvent::Skipped { path: &path, size, cap }); skipped += 1; continue; } - if spoken_for.contains(path.as_path()) { - continue; - } files.push(path); } - let mut analyzed = Analyzed::default(); - let mut buffered: HashMap = HashMap::new(); - let mut gone: Vec = Vec::new(); - for doc in self.docs.values() { - let Some(path) = doc.path.clone() else { continue }; - files.retain(|taken| taken != &path); - if doc.large { - if held.contains(&path) { - gone.push(path); - } - continue; + let mut file_ids: HashMap = HashMap::new(); + for path in &files { + if let Some(id) = dir_id(path) { + file_ids.entry(id).or_insert_with(|| path.clone()); } - analyzed.facts.insert(path.clone(), doc.facts(path.clone())); - analyzed.words.insert(path.clone(), doc.words()); - buffered.insert(path.clone(), doc.text.clone()); - files.push(path); } + let files_set: HashSet = files.iter().cloned().collect(); + let mut overlay = WidenOverlay { + files, + files_set, + file_ids, + gone, + gone_set, + held, + held_ids, + widened_by_id, + analyzed: Default::default(), + buffered: HashMap::new(), + stats, + }; + self.reconcile_widen_buffers(&mut overlay); + let WidenOverlay { files, mut gone, gone_set, held, analyzed, buffered, .. } = overlay; ScanTrace::add(&mut trace.discovery_ms, discovering); let ordering = trace.now(); let WorkList { files: work, head } = self.open_first(files); let head = scan_order::worth_waiting(head, work.len()); ScanTrace::add(&mut trace.order_ms, ordering); trace.measure_work(work.len(), held_bytes(&buffered), skipped, self.cache.work()); - // A whole scan drops the view cache entire, because a rescan claims - // nothing about *which* file moved. A widen names exactly the files it - // is reading, so it drops exactly those — which keeps the cache's own - // rule ("every way a file's text can move drops its entry", - // [`Workspace::file_view`]) literally true rather than nearly so. - for path in &work { - self.views.borrow_mut().retain(|view| &view.path != path); - } - // Which files exist once this widen lands: what the index holds, less - // what it is about to lose, plus what the widen brings in. + self.views + .borrow_mut() + .retain(|view| !gone_set.contains(&view.path) && !work.contains(&view.path)); let mut paths: Vec = - held.into_iter().filter(|path| !gone.contains(path)).collect(); + held.into_iter().filter(|path| !gone_set.contains(path)).collect(); paths.extend(work.iter().cloned()); paths.sort(); paths.dedup(); @@ -219,6 +253,7 @@ impl Workspace { paths, gone, analyzed, + canonical_ids: HashMap::new(), // Rung 3 is the only rung an open buffer can widen, and it names no // `+incdir+`. Carried from the graph in hand rather than assumed // empty, so folding a widen in never *changes* the search path. @@ -259,11 +294,21 @@ impl Workspace { } watch(event); }; - self.rest_of_scope(&mut pending, &mut counting, &mut scan.trace) + self.rest_of_scope( + &mut pending, + &mut scan.canonical_ids, + &mut counting, + &mut scan.trace, + ) }; debug_assert_eq!(skipped, walked_skips, "the cap reports every skip it counts"); ScanTrace::add(&mut scan.trace.discovery_ms, discovering); - scan.land_discovery(files, warnings, walked_skips, pending.tracker.has_conflict()); + scan.land_discovery( + files, + warnings, + walked_skips, + pending.tracker.has_conflict() || pending.file_conflict, + ); scan.trace.measure_work( scan.work.len(), held_bytes(&scan.buffered), @@ -323,10 +368,15 @@ impl Workspace { // anything, so it is where the store this scan asked for is opened. self.open_store(&mut scan.trace); let path = scan.work[done].clone(); + let from_buffer = + scan.buffered.contains_key(&path) || scan.analyzed.facts.contains_key(&path); let Some(source) = scan.take_text(&path) else { scan.unread.push(path); return true; }; + if from_buffer { + self.scan_absorbed.record(&path, None, None); + } let text = source.as_str(); let held = scan.analyzed.facts.remove(&path); let known_words = scan.analyzed.words.remove(&path); @@ -415,6 +465,7 @@ impl Workspace { /// (`docs/features/perf5r-first-answer/README.md`). pub fn open_next(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) { self.discover_the_rest(scan, watch); + self.reconcile_open_buffers_into(scan); let ordered = self.open_first(scan.remaining()); scan.reorder(ordered); } @@ -441,6 +492,7 @@ impl Workspace { let taken = std::mem::take(&mut scan.staged_at); let absorbing = scan.trace.now(); self.index.absorb(std::mem::take(&mut scan.staged), &[]); + self.invalidate_identities(); ScanTrace::add(&mut scan.trace.publish_absorb_ms, absorbing); let completing = scan.trace.now(); let published: Vec = taken.iter().map(|&at| scan.work[at].clone()).collect(); @@ -474,6 +526,7 @@ impl Workspace { /// tables are a pure function of the records it holds /// ([`WorkspaceIndex::absorb`]). pub fn finish_scan(&mut self, scan: Scan) -> Vec { + self.scan_absorbed.clear(); match scan.kind { ScanKind::Whole => self.finish_whole_scan(scan), ScanKind::Widen => self.finish_widen(scan), @@ -505,6 +558,7 @@ impl Workspace { ScanTrace::add(&mut trace.gone_ms, leaving); let absorbing = trace.now(); self.index.absorb(staged, &gone); + self.invalidate_identities(); ScanTrace::add(&mut trace.absorb_ms, absorbing); // The one moment the live set of entries is known, so the one moment // the append log is worth rewriting — and only when this scan reached @@ -603,6 +657,7 @@ impl Workspace { let found = scan::included(&includes, &work); let absorbing = trace.now(); self.index.absorb(staged, &gone); + self.invalidate_identities(); ScanTrace::add(&mut trace.absorb_ms, absorbing); // Before the additions, so the two never disagree about a path that is // in both lists — which cannot happen today (a large buffer is in diff --git a/crates/lucisv_server/src/state/scan.rs b/crates/lucisv_server/src/state/scan.rs index 18260c2..355e2a4 100644 --- a/crates/lucisv_server/src/state/scan.rs +++ b/crates/lucisv_server/src/state/scan.rs @@ -41,6 +41,9 @@ pub(super) struct Sources { pub(super) buffered: HashMap, /// What the open buffers among `files` already know about themselves. pub(super) analyzed: Analyzed, + /// Deterministic canonical spelling for every in-scope file identity, + /// including files skipped by `maxFileSize`. + pub(super) canonical_ids: HashMap, pub(super) incdirs: Vec, pub(super) warnings: Vec, } @@ -124,6 +127,9 @@ pub struct Scan { /// What the open buffers among `work` already knew about themselves, taken /// from as each of them is reached. pub(super) analyzed: Analyzed, + /// Canonical in-scope spellings by file identity, retained across `oversize` + /// skips so mid-scan opens canonicalize like pre-scan opens. + pub(super) canonical_ids: HashMap, pub(super) incdirs: Vec, pub(super) warnings: Vec, /// How many of `work` have been indexed. @@ -170,6 +176,11 @@ pub(super) struct PendingDiscovery { /// one it names here has already been decided about, and deciding twice /// would step a file twice or report one skip as two. pub(super) seen: HashSet, + /// File identities `(dev, ino)` (or canonical paths) already discovered by + /// the neighbourhood walk mapped to their chosen spellings, so the + /// remaining walk neither duplicates a file nor misses a precedence + /// conflict when a symlink sorts earlier. + pub(super) seen_ids: HashMap, /// Every directory identity the neighbourhood walk entered, and the path /// it entered each one by. /// @@ -180,6 +191,7 @@ pub(super) struct PendingDiscovery { /// report a symlinked directory's files twice, under two spellings a path /// set cannot tell apart, and the index would hold every module in it /// twice. Sharing the tracker restores that contract across the split. + pub(super) file_conflict: bool, pub(super) tracker: lucisv_core::walk::DirectoryTracker, } diff --git a/crates/lucisv_server/src/state/sources.rs b/crates/lucisv_server/src/state/sources.rs index 01e0e3f..33491ee 100644 --- a/crates/lucisv_server/src/state/sources.rs +++ b/crates/lucisv_server/src/state/sources.rs @@ -9,7 +9,7 @@ use std::fs; use std::path::{Path, PathBuf}; use std::time::Instant; -use vlog_semantic::{Def, FileId}; +use vlog_semantic::Def; use super::scan::{HeldAnalyses, Sources}; use super::Workspace; @@ -91,7 +91,7 @@ impl Workspace { reach: Reach<'_>, ) -> Vec<(PathBuf, String)> { let mut wanted: BTreeSet = module_select::hierarchical_users(&self.index, reach); - wanted.insert(file.to_path_buf()); + wanted.insert(self.index_path_for(file)); for name in modules { for def in self.index.units(name) { wanted.extend(self.index.path(def.file).map(Path::to_path_buf)); @@ -103,7 +103,11 @@ impl Workspace { wanted.extend(self.index.path(edge.file).map(Path::to_path_buf)); } } - wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone())); + wanted.extend( + self.docs + .values() + .filter_map(|doc| doc.path.as_deref().map(|p| self.index_path_for(p))), + ); wanted .into_iter() .filter_map(|path| { @@ -188,7 +192,7 @@ impl Workspace { let started = Instant::now(); let elapsed = |at: Instant| at.elapsed().as_secs_f64() * 1000.0; let mut wanted = Wanted::new(); - wanted.insert(file.to_path_buf()); + wanted.insert(self.index_path_for(file)); for spelling in [Some(name), new_name].into_iter().flatten() { if !self.fan_out_of(spelling, &mut wanted) { let sources = self.sources(); @@ -203,7 +207,11 @@ impl Workspace { self.want_spellers(new_name, &mut wanted); } wanted.on(Rung::OpenBuffer); - wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone())); + wanted.extend( + self.docs + .values() + .filter_map(|doc| doc.path.as_deref().map(|p| self.index_path_for(p))), + ); let (mut paths, mut trace) = wanted.finish(); // One hop down: the modules those files instantiate, so a `.*` into // one is read rather than refused (M3.5). In `selected`, under no rung. @@ -334,14 +342,13 @@ impl Workspace { /// warning cannot disagree about which files carry one. fn want_macro_text(&self, name: &str, wanted: &mut Wanted) { wanted.on(Rung::MacroText); - for id in 0..self.index.files().len() { - let file = FileId(id as u32); + for (file, path) in self.index.live_files() { let Some(defines) = self.index.defines(file) else { continue }; let touched = defines.entries().iter().any(|define| { define.name == name || vlog_refactor::contains_word(&define.body, name) }); if touched { - wanted.extend(self.index.path(file).map(Path::to_path_buf)); + wanted.insert(path.clone()); } } } @@ -360,7 +367,11 @@ impl Workspace { /// not yet saved is in the buffer and not in the edges. pub fn include_sources(&self) -> Vec<(PathBuf, String)> { let mut wanted: BTreeSet = self.includes.includers().cloned().collect(); - wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone())); + wanted.extend( + self.docs + .values() + .filter_map(|doc| doc.path.as_deref().map(|p| self.index_path_for(p))), + ); wanted .into_iter() .filter_map(|path| { diff --git a/crates/lucisv_server/src/state/tests/large_file.rs b/crates/lucisv_server/src/state/tests/large_file.rs index e089667..3a36fe6 100644 --- a/crates/lucisv_server/src/state/tests/large_file.rs +++ b/crates/lucisv_server/src/state/tests/large_file.rs @@ -55,7 +55,7 @@ fn a_fast_path_buffer_holds_the_analysis_of_an_empty_file() { } #[test] -fn a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_behind() { +fn a_fast_path_buffer_keeps_the_on_disk_index_record() { let tree = Tree::new("largefile"); tree.write("pkg.sv", "package p;\n localparam ON_DISK = 1;\nendpackage\n"); let path = tree.path.join("pkg.sv"); @@ -64,7 +64,8 @@ fn a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_b ws.open_whole_workspace(vec![tree.path.clone()]); assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "premise: disk was indexed"); - // The same file, opened as a buffer the fast path takes. + // The same file, opened as a buffer the fast path takes, keeps the on-disk + // record (subject to `maxFileSize`) without parsing the huge live text. let mut text = String::from("package p;\n localparam IN_BUFFER = 1;\nendpackage\n"); text.push_str(&" ".repeat(200)); ws.set_document(crate::uri::path_to_uri(&path).expect("uri"), text); @@ -72,8 +73,8 @@ fn a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_b assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0, "the buffer was not parsed"); assert_eq!( ws.index().member("p", "ON_DISK").len(), - 0, - "and the disk copy the buffer supersedes is not indexed in its place" + 1, + "disk index record stays present when an open buffer is over largeFile.threshold" ); } diff --git a/crates/lucisv_server/src/state/tests/open_buffers.rs b/crates/lucisv_server/src/state/tests/open_buffers.rs index cf74540..cb30181 100644 --- a/crates/lucisv_server/src/state/tests/open_buffers.rs +++ b/crates/lucisv_server/src/state/tests/open_buffers.rs @@ -233,10 +233,8 @@ fn qa_attack_crafted_non_corpus_shapes_drift_check_body() { #[test] fn a_buffer_on_the_large_file_fast_path_offers_no_analysis_to_reuse() { // The one buffer whose held analysis is not an analysis of its text — - // it is the analysis of the empty file. Such a buffer contributes - // nothing to the index at all, which is what keeps the reuse from ever - // meeting it: it is absent from the work list, so it is absent from - // every list a rescan reports. + // it is the analysis of the empty file. It still offers no buffer analysis + // to reuse, while keeping the on-disk record (subject to `maxFileSize`). let tree = Tree::new("openfactslarge"); tree.package("rtl/a.sv", "a_pkg"); let big = format!( @@ -257,8 +255,8 @@ fn a_buffer_on_the_large_file_fast_path_offers_no_analysis_to_reuse() { let seen = scan(&mut ws, None); assert!(seen.analyzed.is_empty(), "nothing came from an analysis: {seen:?}"); - assert_eq!(seen.parsed, ["a.sv"], "and the big buffer is on no list at all: {seen:?}"); - assert_eq!(indexed(&ws, &["a_pkg", "big_pkg"]), ["a_pkg"], "nor in the index"); + assert_eq!(seen.parsed, ["big.sv", "a.sv"], "disk big.sv was parsed from disk: {seen:?}"); + assert_eq!(indexed(&ws, &["a_pkg", "big_pkg"]), ["a_pkg", "big_pkg"]); } #[test] @@ -321,13 +319,14 @@ fn qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session() { assert_eq!(seen.analyzed, ["p.sv"], "small buffer reused: {seen:?}"); assert_eq!(ws.index().member("p", "SMALL").len(), 1); - // Edited past the threshold, never saved. + // Edited past the threshold, never saved: buffer offers no analysis, so + // rescan reverts to disk's record (keeping the disk copy subject to cap). ws.set_document(uri.clone(), filler(1_000)); assert!(ws.document(&uri).expect("open").large, "now on the fast path"); let seen = scan(&mut ws, None); assert!(seen.analyzed.is_empty(), "the now-huge buffer offers no analysis: {seen:?}"); - assert!(seen.parsed.is_empty(), "and disk is not read in its place either: {seen:?}"); - assert_eq!(ws.index().member("p", "SMALL").len(), 0, "contributes nothing at all"); + assert_eq!(seen.parsed, ["p.sv"], "and disk is read in its place: {seen:?}"); + assert_eq!(ws.index().member("p", "SMALL").len(), 1, "disk record stays indexed"); // And back under the threshold: a real analysis again, reused again. ws.set_document(uri.clone(), "package p;\n localparam SMALL = 1;\nendpackage\n".into()); diff --git a/crates/lucisv_server/src/state/tests/reindex_perf.rs b/crates/lucisv_server/src/state/tests/reindex_perf.rs index fae8300..354b5a0 100644 --- a/crates/lucisv_server/src/state/tests/reindex_perf.rs +++ b/crates/lucisv_server/src/state/tests/reindex_perf.rs @@ -13,7 +13,7 @@ use std::time::{Duration, Instant}; -use vlog_semantic::{FileId, SymbolKind}; +use vlog_semantic::SymbolKind; use super::*; @@ -109,7 +109,7 @@ fn what_the_mention_census_costs_a_keystroke_at_opentitan_scale() { 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() { + for (id, path) in index.live_files() { let Ok(text) = fs::read_to_string(path) else { continue }; let doc = Document::new(Some(path.clone()), text, index); let names: Vec<&str> = doc @@ -121,7 +121,7 @@ fn what_the_mention_census_costs_a_keystroke_at_opentitan_scale() { .collect(); let started = Instant::now(); for name in &names { - std::hint::black_box(index.mentioned_outside(name, Some(FileId(id as u32)))); + std::hint::black_box(index.mentioned_outside(name, Some(id))); } let took = started.elapsed(); calls += names.len(); diff --git a/crates/lucisv_server/src/state/tests/widen.rs b/crates/lucisv_server/src/state/tests/widen.rs index ebb66aa..3cf6ed3 100644 --- a/crates/lucisv_server/src/state/tests/widen.rs +++ b/crates/lucisv_server/src/state/tests/widen.rs @@ -350,11 +350,10 @@ fn a_widen_lends_a_new_files_spelling_to_an_include_resolved_before_it() { } #[test] -fn a_buffer_grown_past_the_threshold_leaves_the_index_when_the_scope_widens() { - // The one thing a widen takes *out*: a buffer on the large-file fast - // path contributes nothing, exactly as `collect_sources` says, so a - // file the index holds whose buffer has grown past the threshold is - // dropped — the same answer a whole rescan gives. +fn a_buffer_grown_past_the_threshold_keeps_its_disk_record_when_the_scope_widens() { + // Owner decision 2 (Topo #63): an open `doc.large` buffer keeps its + // on-disk index record (subject to `maxFileSize`), so widening does not + // drop `rtl/p.sv` and matches a whole rescan. let tree = Tree::new("widenlarge"); tree.package("rtl/p.sv", "p_pkg"); tree.package("lib/q.sv", "q_pkg"); @@ -378,10 +377,10 @@ fn a_buffer_grown_past_the_threshold_leaves_the_index_when_the_scope_widens() { widen(&mut incremental, |ws| ws.set_document(other.clone(), other_text.clone())); assert_eq!( incremental.index().files().len(), - 1, - "the grown buffer left as the new folder arrived" + 2, + "both the kept disk record and the widened file are in the index" ); - assert!(incremental.index().units("p_pkg").is_empty(), "and its names went with it"); + assert_eq!(incremental.index().units("p_pkg").len(), 1, "and disk's package stays indexed"); let mut rebuilt = Workspace::default(); rebuilt.set_client_settings(ClientSettings { diff --git a/crates/lucisv_server/src/state/watched.rs b/crates/lucisv_server/src/state/watched.rs index 29d2f2d..240e62b 100644 --- a/crates/lucisv_server/src/state/watched.rs +++ b/crates/lucisv_server/src/state/watched.rs @@ -16,7 +16,7 @@ use std::fs; use std::path::{Path, PathBuf}; use lucisv_core::config::Discovery; -use lucisv_core::walk::collect_files_below; +use lucisv_core::walk::{collect_files_below, dir_id, is_excluded, EXTENSIONS}; use super::discover::{oversize, Found}; use super::Workspace; @@ -43,8 +43,8 @@ impl Workspace { 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()); + if let Some(doc) = self.document_for_path(path).filter(|doc| !doc.large) { + return Watched::Held(doc.path.clone().unwrap_or_else(|| path.to_path_buf())); } match self.scope_could_take(path) { true => Watched::Unknown, @@ -52,24 +52,27 @@ impl Workspace { } } - /// 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. + /// The spelling the index holds `path` under: `path` itself, the same + /// file reached through a scope directory's symlink/case alias, or any + /// file sharing `(dev, ino)` (on Unix) / canonical path without basename + /// gating. fn held_spelling(&self, path: &Path) -> Option { - let holds = |path: &Path| self.index.file_id(path).is_some(); + let holds = |candidate: &Path| self.index.file_id(candidate).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) - }) + if let Some(real) = canonical(path) { + let mut anchors: Vec = self.roots.clone(); + anchors.extend(self.scope_dirs()); + if let Some(spelled) = 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) + }) { + return Some(spelled); + } + } + self.held_path_for(path) } /// Whether a scan of the scope in force could index `path` — `false` only @@ -78,12 +81,13 @@ impl Workspace { /// `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 { + pub(super) 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)); + return list.files.iter().any(|listed| same_file(listed, path)) + && oversize(&Found::of(path), self.client.max_file_size, &mut 0).is_none(); } } let Some(dir) = path.parent() else { return true }; @@ -92,8 +96,15 @@ impl Workspace { 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); + // The flat read of a rootless session: siblings only (and must be + // an existing readable source file under `maxFileSize`). + return dirs.iter().any(|scope| scope == dir) + && path + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| EXTENSIONS.contains(&e)) + && fs::metadata(path).is_ok_and(|meta| meta.is_file()) + && oversize(&Found::of(path), self.client.max_file_size, &mut 0).is_none(); } dirs.iter() .filter(|scope| path.starts_with(scope)) @@ -102,8 +113,30 @@ impl Workspace { /// Whether a walk of `scope` finds `path` under its cap. fn walk_finds(&self, scope: &Path, path: &Path) -> bool { + if !path.extension().and_then(|e| e.to_str()).is_some_and(|e| EXTENSIONS.contains(&e)) { + return false; + } let Some(dir) = path.parent() else { return true }; let excludes = self.walk_excludes(&mut Discovery::new(true), scope); + let mut has_gitignore = scope.join(".gitignore").is_file(); + let mut cursor = Some(path); + while let Some(part) = cursor { + if part == scope { + break; + } + if is_excluded(part, &excludes) { + return false; + } + if part != path && part.join(".gitignore").is_file() { + has_gitignore = true; + } + cursor = part.parent(); + } + if !has_gitignore { + let Ok(meta) = fs::metadata(path) else { return false }; + return meta.is_file() + && (self.client.max_file_size == 0 || meta.len() <= self.client.max_file_size); + } let mut found = None; let take = &mut |file: PathBuf, len| { if file == path { @@ -134,17 +167,14 @@ impl Workspace { } } -/// 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. +/// Whether two spellings name one file: equal, or sharing `(dev, ino)` (on +/// Unix) / canonical path (elsewhere), without basename equality gating. 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) + dir_id(listed).is_some_and(|id| dir_id(path).as_ref() == Some(&id)) + || (canonical(listed).is_some() && canonical(listed) == canonical(path)) } /// `path` with every symlink resolved and, on a case-insensitive disk, every diff --git a/crates/vlog_semantic/src/workspace/index.rs b/crates/vlog_semantic/src/workspace/index.rs index 6e9be1a..5feb4f2 100644 --- a/crates/vlog_semantic/src/workspace/index.rs +++ b/crates/vlog_semantic/src/workspace/index.rs @@ -53,17 +53,27 @@ impl WorkspaceIndex { &self.files } + /// Every live file in the index paired with its [`FileId`], skipping + /// tombstoned slots while preserving stable slot ids. + pub fn live_files(&self) -> impl Iterator + '_ { + self.facts.iter().enumerate().filter_map(|(at, facts)| { + (!self.tombstoned.get(at).copied().unwrap_or(true)) + .then_some((FileId(at as u32), &facts.path)) + }) + } + /// The path of one file. pub fn path(&self, file: FileId) -> Option<&Path> { - self.files.get(file.0 as usize).map(PathBuf::as_path) + let at = file.0 as usize; + (!self.tombstoned.get(at).copied().unwrap_or(true)) + .then(|| self.facts.get(at).map(|facts| facts.path.as_path())) + .flatten() } /// The id of an indexed path. pub fn file_id(&self, path: &Path) -> Option { - self.files - .binary_search_by(|held| held.as_path().cmp(path)) - .ok() - .map(|at| FileId(at as u32)) + let at = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)).ok()?; + (!self.tombstoned[at]).then_some(FileId(at as u32)) } /// Every file-scope declaration of `name` — module, package or typedef — @@ -293,12 +303,15 @@ impl WorkspaceIndex { /// (`docs/features/index-persistence/README.md`). pub fn facts_for(&self, path: &Path) -> Option<&FileFacts> { let at = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)).ok()?; - self.facts.get(at) + (!self.tombstoned[at]).then(|| &self.facts[at]) } /// The `` `define`` table of one file. pub fn defines(&self, file: FileId) -> Option<&DefineTable> { - self.facts.get(file.0 as usize).map(|facts| &facts.defines) + let at = file.0 as usize; + (!self.tombstoned.get(at).copied().unwrap_or(true)) + .then(|| self.facts.get(at).map(|facts| &facts.defines)) + .flatten() } /// Every definition of a macro name anywhere in the workspace, in file @@ -312,7 +325,11 @@ impl WorkspaceIndex { .into_iter() .flatten() .filter_map(|&(file, entry)| { - let define = self.facts.get(file.0 as usize)?.defines.entries().get(entry)?; + let at = file.0 as usize; + if self.tombstoned.get(at).copied().unwrap_or(true) { + return None; + } + let define = self.facts.get(at)?.defines.entries().get(entry)?; Some((file, define)) }) .collect() @@ -349,6 +366,9 @@ impl WorkspaceIndex { pub fn files_spelling(&self, name: &str) -> impl Iterator + '_ { let name = name.to_string(); self.facts.iter().enumerate().filter_map(move |(id, facts)| { + if self.tombstoned.get(id).copied().unwrap_or(true) { + return None; + } let spelled = facts.references.iter().any(|reference| match reference { // A fact with **no paths at all** is not one of these: it is // an inherited-member miss, answered only through the base @@ -390,8 +410,9 @@ impl WorkspaceIndex { self.facts .iter() .enumerate() - .filter(move |(_, facts)| { - facts.words.binary_search_by(|w| w.as_str().cmp(name)).is_ok() + .filter(move |&(id, facts)| { + !self.tombstoned.get(id).copied().unwrap_or(true) + && facts.words.binary_search_by(|w| w.as_str().cmp(name)).is_ok() }) .map(|(id, _)| FileId(id as u32)) } @@ -419,8 +440,9 @@ impl WorkspaceIndex { self.facts .iter() .enumerate() - .filter(move |(_, facts)| { - facts.macro_words.binary_search_by(|w| w.as_str().cmp(name)).is_ok() + .filter(move |&(id, facts)| { + !self.tombstoned.get(id).copied().unwrap_or(true) + && facts.macro_words.binary_search_by(|w| w.as_str().cmp(name)).is_ok() }) .map(|(id, _)| FileId(id as u32)) } @@ -531,7 +553,13 @@ impl WorkspaceIndex { .flat_map(|m| m.values()) .map(Vec::len) .sum(), - defines: self.facts.iter().map(|f| f.defines.entries().len()).sum(), + defines: self + .facts + .iter() + .enumerate() + .filter(|&(id, _)| !self.tombstoned.get(id).copied().unwrap_or(true)) + .map(|(_, f)| f.defines.entries().len()) + .sum(), instantiations: self.instantiations.values().map(Vec::len).sum(), inheritances: self.subclasses.values().map(Vec::len).sum(), } @@ -547,11 +575,19 @@ impl WorkspaceIndex { hier_members: self.hier_members.values().flat_map(|m| m.values()).map(Vec::len).sum(), reference_keys: self.reference_sites.len(), reference_sites: self.reference_sites.values().map(Vec::len).sum(), - words: self.facts.iter().map(|facts| facts.words().len()).sum(), + words: self + .facts + .iter() + .enumerate() + .filter(|&(id, _)| !self.tombstoned.get(id).copied().unwrap_or(true)) + .map(|(_, facts)| facts.words().len()) + .sum(), word_bytes: self .facts .iter() - .flat_map(|facts| facts.words()) + .enumerate() + .filter(|&(id, _)| !self.tombstoned.get(id).copied().unwrap_or(true)) + .flat_map(|(_, facts)| facts.words()) .map(|word| word.len()) .sum(), } @@ -644,6 +680,7 @@ impl IndexBuilder { self.files.dedup_by(|a, b| a.path == b.path); let mut index = WorkspaceIndex { files: self.files.iter().map(|facts| facts.path.clone()).collect(), + tombstoned: vec![false; self.files.len()], facts: self.files, ..WorkspaceIndex::default() }; diff --git a/crates/vlog_semantic/src/workspace/mod.rs b/crates/vlog_semantic/src/workspace/mod.rs index d21d9cc..2226536 100644 --- a/crates/vlog_semantic/src/workspace/mod.rs +++ b/crates/vlog_semantic/src/workspace/mod.rs @@ -294,12 +294,17 @@ pub struct InheritanceEdge { /// memory: the same names and spans the tables hold, held once more per file. #[derive(Debug, Clone, Default)] pub struct WorkspaceIndex { - /// Indexed by [`FileId`], sorted by path. The paths of `facts`, kept flat - /// so [`WorkspaceIndex::files`] can hand out a slice. + /// Live indexed paths, sorted by path, kept flat so + /// [`WorkspaceIndex::files`] can hand out a slice without exposing + /// tombstoned slots. files: Vec, - /// What each file contributes, parallel to `files` and in the same order. - /// A [`FileId`] is an index into both. + /// What each file slot contributes, sorted by `path`. A [`FileId`] is a + /// stable slot index into `facts` and `tombstoned` across + /// [`WorkspaceIndex::remove_file`] until compaction on [`WorkspaceIndex::merge`]. facts: Vec, + /// Parallel to `facts`: `true` for a removed slot whose records were + /// cleared in-place via [`WorkspaceIndex::replace_facts`]. + tombstoned: Vec, /// File-scope name → every declaration of it, in disambiguation order. units: BTreeMap>, /// Unit name → member name → every declaration of it, on the diff --git a/crates/vlog_semantic/src/workspace/update.rs b/crates/vlog_semantic/src/workspace/update.rs index fe43bbb..6069a0b 100644 --- a/crates/vlog_semantic/src/workspace/update.rs +++ b/crates/vlog_semantic/src/workspace/update.rs @@ -9,7 +9,7 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; -use vlog_parser::defines::DefineKind; +use vlog_parser::defines::{DefineKind, DefineTable}; use crate::model::Surface; @@ -61,6 +61,13 @@ impl WorkspaceIndex { 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.tombstoned[at] => { + self.tombstoned[at] = false; + if let Err(live) = self.files.binary_search_by(|held| held.as_path().cmp(&path)) { + self.files.insert(live, path); + } + self.replace_facts(at, facts); + } 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, @@ -69,10 +76,14 @@ impl WorkspaceIndex { 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. + // every table is rebuilt from the records (which also compacts any + // tombstones). No parse, no read. Err(at) => { - self.files.insert(at, path); + if let Err(live) = self.files.binary_search_by(|held| held.as_path().cmp(&path)) { + self.files.insert(live, path); + } self.facts.insert(at, facts); + self.tombstoned.insert(at, false); self.merge(); } } @@ -110,16 +121,23 @@ impl WorkspaceIndex { pub fn absorb(&mut self, records: Vec, gone: &[PathBuf]) { for path in gone { if let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) { - self.files.remove(at); - self.facts.remove(at); + self.tombstoned[at] = true; } } for facts in records { match self.facts.binary_search_by(|held| held.path.cmp(&facts.path)) { - Ok(at) => self.facts[at] = facts, + Ok(at) => { + self.tombstoned[at] = false; + self.facts[at] = facts; + } Err(at) => { - self.files.insert(at, facts.path.clone()); + if let Err(live) = + self.files.binary_search_by(|held| held.as_path().cmp(&facts.path)) + { + self.files.insert(live, facts.path.clone()); + } self.facts.insert(at, facts); + self.tombstoned.insert(at, false); } } } @@ -129,14 +147,21 @@ impl WorkspaceIndex { /// Drop one file from the index, reporting whether it was there. /// /// Same contract as [`WorkspaceIndex::update_file`]: what is left is the - /// index a full build over the remaining files would have produced. + /// index a full build over the remaining files would have produced. Uses a + /// tombstone and localized [`WorkspaceIndex::replace_facts`] so removing a + /// file keeps surviving [`FileId`]s stable without paying a full merge. pub fn remove_file(&mut self, path: &Path) -> bool { let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) else { return false; }; - self.files.remove(at); - self.facts.remove(at); - self.merge(); + if self.tombstoned[at] { + return false; + } + if let Ok(live) = self.files.binary_search_by(|held| held.as_path().cmp(path)) { + self.files.remove(live); + } + self.replace_facts(at, empty_facts(path.to_path_buf())); + self.tombstoned[at] = true; true } @@ -148,17 +173,30 @@ impl WorkspaceIndex { /// more than one crate's tests — `lucisv_server` checks it against the /// real corpus, this crate against crafted attacks. pub fn fingerprint(&self) -> String { + let mut remap: Vec> = vec![None; self.facts.len()]; + let mut live = 0u32; + for (slot, tombstoned) in self.tombstoned.iter().enumerate() { + if !*tombstoned { + remap[slot] = Some(live); + live += 1; + } + } + let id_of = |file: FileId| match remap.get(file.0 as usize).copied().flatten() { + Some(id) => id, + None => file.0, + }; let mut out = String::new(); - for (id, path) in self.files.iter().enumerate() { - let defines = self.defines(FileId(id as u32)).map_or(0, |t| t.entries().len()); + for (slot, facts) in self.facts.iter().enumerate() { + let Some(id) = remap[slot] else { continue }; + let defines = facts.defines.entries().len(); // The census's size, on the same rule the `define` table follows: // the words themselves are per-file and never merged, so a count // is enough to catch the failure a fingerprint exists to catch — // a record lost, duplicated or attached to the wrong file. - let words = self.facts.get(id).map_or(0, |facts| facts.words.len()); + let words = facts.words.len(); out.push_str(&format!( "file {id} {} defines={defines} words={words}\n", - path.display() + facts.path.display() )); } for symbol in self.workspace_symbols("") { @@ -167,7 +205,7 @@ impl WorkspaceIndex { symbol.name, symbol.container, symbol.def.kind, - symbol.def.file.0, + id_of(symbol.def.file), symbol.def.name_span.start, symbol.def.name_span.end, symbol.def.decl_span.start, @@ -182,10 +220,10 @@ impl WorkspaceIndex { for site in sites { out.push_str(&format!( "ref {}:{}..{} <- {}:{}..{}\n", - definition.file.0, + id_of(definition.file), definition.name_start, definition.name_end, - site.file.0, + id_of(site.file), site.name_span.start, site.name_span.end )); @@ -196,14 +234,16 @@ impl WorkspaceIndex { for (definition, count) in ambiguous { out.push_str(&format!( "ambiguous-ref {}:{}..{} x{count}\n", - definition.file.0, definition.name_start, definition.name_end + id_of(definition.file), + definition.name_start, + definition.name_end )); } for (name, edges) in self.instantiations() { for edge in edges { out.push_str(&format!( "inst {name} {} in {}@{}..{} site {}..{}\n", - edge.file.0, + id_of(edge.file), edge.owner.name, edge.owner.name_span.start, edge.owner.span.end, @@ -237,7 +277,7 @@ impl WorkspaceIndex { for edge in edges { out.push_str(&format!( "extends {name} {} {}@{}..{}\n", - edge.file.0, + id_of(edge.file), edge.subclass.name, edge.subclass.name_span.start, edge.subclass.span.end @@ -247,10 +287,54 @@ 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); + self.render_dependents(&remap, &mut out); out } + fn render_dependents(&self, remap: &[Option], out: &mut String) { + if !self.tombstoned.iter().any(|&t| t) { + self.dependents.render(out); + return; + } + let mut raw = String::new(); + self.dependents.render(&mut raw); + for line in raw.lines() { + if let Some((prefix, list)) = line.rsplit_once(" by [") { + if let Some(inner) = list.strip_suffix(']') { + let mapped: Vec = inner + .split(',') + .filter_map(|s| s.trim().parse::().ok()) + .filter_map(|slot| remap.get(slot).copied().flatten()) + .collect(); + out.push_str(&format!("{prefix} by {mapped:?}\n")); + continue; + } + } + out.push_str(line); + out.push('\n'); + } + } + + /// Re-pack `facts` and rebuild `files` / `tombstoned` when tombstones exist. + fn compact_tombstones(&mut self) { + if !self.tombstoned.iter().any(|&t| t) { + return; + } + let mut keep = 0usize; + for i in 0..self.facts.len() { + if !self.tombstoned[i] { + if i != keep { + self.facts.swap(keep, i); + } + keep += 1; + } + } + self.facts.truncate(keep); + self.tombstoned.clear(); + self.tombstoned.resize(keep, false); + self.files = self.facts.iter().map(|facts| facts.path.clone()).collect(); + } + /// Rebuild every merged table, the postings and the readers table from /// the per-file records. /// @@ -260,6 +344,7 @@ impl WorkspaceIndex { /// 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.compact_tombstones(); self.merge_tables(None, None); self.merge_bases(); // A changed declaration can change how references in any file resolve, @@ -315,6 +400,9 @@ impl WorkspaceIndex { /// 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>) { + if self.tombstoned.get(id).copied().unwrap_or(true) { + return; + } let file = FileId(id as u32); let Some(facts) = self.facts.get(id) else { return }; for decl in &facts.units { @@ -382,7 +470,10 @@ impl WorkspaceIndex { /// winning, which is `units`' rule. pub(super) fn merge_bases(&mut self) { self.bases.clear(); - for facts in &self.facts { + for (id, facts) in self.facts.iter().enumerate() { + if self.tombstoned.get(id).copied().unwrap_or(true) { + continue; + } for (base, subclass) in &facts.subclasses { self.bases.entry(subclass.name.clone()).or_insert_with(|| base.clone()); } @@ -390,6 +481,21 @@ impl WorkspaceIndex { } } +fn empty_facts(path: PathBuf) -> FileFacts { + FileFacts { + path, + defines: DefineTable::default(), + units: Vec::new(), + members: Vec::new(), + instantiations: Vec::new(), + subclasses: Vec::new(), + reexports: Vec::new(), + references: Vec::new(), + words: Vec::new(), + macro_words: Vec::new(), + } +} + /// The table keys one file's records can move, so a merge after replacing that /// file can leave every other key alone. #[derive(Debug, Default)] diff --git a/crates/vlog_semantic/tests/workspace.rs b/crates/vlog_semantic/tests/workspace.rs index 39b2c23..23d0fa3 100644 --- a/crates/vlog_semantic/tests/workspace.rs +++ b/crates/vlog_semantic/tests/workspace.rs @@ -1225,7 +1225,11 @@ fn removing_a_file_gives_the_index_a_whole_build_would_have() { "what is left is the index of what is left" ); assert_eq!(ws.units("dup").len(), 1, "and the removed declaration is gone"); - assert_eq!(ws.units("dup")[0].file, FileId(0), "z.sv renumbered down to 0"); + assert_eq!( + ws.path(ws.units("dup")[0].file), + Some(Path::new("z.sv")), + "z.sv kept its stable FileId across fast tombstone removal" + ); assert!(ws.instantiations_of("sub").is_empty(), "its edges went with it"); assert!(!ws.remove_file(Path::new("a.sv")), "and removing it again says so"); } @@ -1716,7 +1720,12 @@ fn updating_a_file_to_empty_text_differs_from_removing_it() { assert_eq!(emptied.files().len(), 2, "the empty file still occupies a slot"); assert_eq!(removed.files().len(), 1, "the removed file's slot is gone"); assert_eq!(emptied.path(FileId(1)), Some(Path::new("z.sv")), "z.sv did not renumber"); - assert_eq!(removed.path(FileId(0)), Some(Path::new("z.sv")), "z.sv renumbered down to 0"); + assert_eq!( + removed.file_id(Path::new("z.sv")), + Some(FileId(1)), + "tombstoning keeps z.sv at its stable FileId while hiding a.sv" + ); + assert!(removed.path(FileId(0)).is_none(), "tombstoned slot reports no path"); } #[test] @@ -2733,4 +2742,291 @@ fn the_macro_census_walk_costs_this_much_per_rename() { } } +#[test] +fn tombstoned_remove_revive_and_compact_match_fresh_build_and_counts() { + let files = [ + ("a_defs.sv", "`define A_MAC 1\npackage p;\n typedef logic word_t;\nendpackage\n"), + ("b_empty.sv", ""), + ("c_use.sv", "module m;\n import p::*;\n word_t x;\n sub u1 ();\n `A_MAC\nendmodule\n"), + ( + "d_sub.sv", + "module sub;\n class Base; endclass\n class Sub extends Base; endclass\nendmodule\n", + ), + ("e_reexp.sv", "package r;\n import p::*;\n export p::*;\nendpackage\n"), + ]; + let mut ws = index(&files); + let c_id_before = ws.file_id(Path::new("c_use.sv")).expect("c_use live"); + assert!(ws.remove_file(Path::new("a_defs.sv"))); + assert!(ws.remove_file(Path::new("b_empty.sv"))); + assert!(!ws.remove_file(Path::new("b_empty.sv")), "double remove returns false"); + + // Stable FileId is preserved while tombstones are hidden from every lookup. + assert_eq!(ws.file_id(Path::new("c_use.sv")), Some(c_id_before)); + assert!(ws.file_id(Path::new("a_defs.sv")).is_none()); + assert!(ws.path(FileId(0)).is_none()); + assert!(ws.defines(FileId(0)).is_none()); + assert!(ws.facts_for(Path::new("a_defs.sv")).is_none()); + assert!(ws.find_define("A_MAC").is_empty()); + assert!(ws.files_mentioning("A_MAC").next().is_some()); // still mentioned in c_use.sv + assert!(!ws.files_naming_in_macros("A_MAC").any(|id| id == FileId(0))); + assert_eq!( + ws.files(), + &[PathBuf::from("c_use.sv"), PathBuf::from("d_sub.sv"), PathBuf::from("e_reexp.sv")] + ); + + let fresh_after_remove = index(&files[2..]); + assert_eq!(ws.fingerprint(), fresh_after_remove.fingerprint()); + assert_eq!(ws.counts(), fresh_after_remove.counts()); + assert_eq!(ws.table_sizes(), fresh_after_remove.table_sizes()); + + // Reviving a tombstoned empty file must make it visible again even though empty == empty. + assert!(ws.update_file(PathBuf::from("b_empty.sv"), "")); + assert_eq!(ws.file_id(Path::new("b_empty.sv")), Some(FileId(1))); + let with_empty = index(&[files[1], files[2], files[3], files[4]]); + assert_eq!(ws.fingerprint(), with_empty.fingerprint()); + + // Re-adding `a_defs.sv` with updated content revives slot 0 in-place via `replace_facts`. + let a_v2 = "`define A_MAC 2\npackage p;\n typedef logic word_t;\nendpackage\n"; + assert!(ws.update_file(PathBuf::from("a_defs.sv"), a_v2)); + assert_eq!(ws.file_id(Path::new("a_defs.sv")), Some(FileId(0))); + let revived = index(&[("a_defs.sv", a_v2), files[1], files[2], files[3], files[4]]); + assert_eq!(ws.fingerprint(), revived.fingerprint()); + + // Removing again, then absorbing another file compacts tombstones and keeps exact parity. + assert!(ws.remove_file(Path::new("a_defs.sv"))); + let f_extra = ("f_extra.sv", "module extra;\n sub u2 ();\nendmodule\n"); + ws.absorb( + vec![vlog_semantic::FileFacts::of(PathBuf::from(f_extra.0), f_extra.1)], + &[PathBuf::from("b_empty.sv")], + ); + assert_eq!(ws.file_id(Path::new("c_use.sv")), Some(FileId(0)), "absorb compacts tombstones"); + assert_eq!(ws.fingerprint(), index(&[files[2], files[3], files[4], f_extra]).fingerprint()); +} + +#[test] +fn fast_tombstone_2000_removals_on_4000_file_index_stays_sub_5ms_and_matches_rebuild() { + let sources: Vec<(PathBuf, String)> = (0..4_000) + .map(|i| { + let path = PathBuf::from(format!("dir_{:02}/m_{:04}.sv", i / 100, i)); + let text = if i % 10 == 0 { + format!("`define M_{i} {i}\nmodule m_{i:04};\nendmodule\n") + } else { + format!("module m_{i:04};\n m_{:04} u ();\nendmodule\n", (i / 10) * 10) + }; + (path, text) + }) + .collect(); + let mut ws = WorkspaceIndex::build(sources.iter().map(|(p, s)| (p.clone(), s.as_str()))); + + // Remove 2,000 leaf files (indices not at % 10, interleaved across slots). + let mut removed_set = std::collections::HashSet::new(); + let to_remove: Vec = sources + .iter() + .enumerate() + .filter(|(i, _)| i % 2 == 1 && i % 10 != 0) + .take(2_000) + .map(|(_, (p, _))| p.clone()) + .collect(); + assert_eq!(to_remove.len(), 2_000); + + let started = std::time::Instant::now(); + for path in &to_remove { + assert!(ws.remove_file(path)); + removed_set.insert(path.clone()); + } + let elapsed = started.elapsed(); + let per_removal = elapsed / to_remove.len() as u32; + assert!( + per_removal < std::time::Duration::from_millis(5), + "expected sub-5ms per tombstoned removal, took {per_removal:?} ({elapsed:?} total)" + ); + + let remaining: Vec<(PathBuf, &str)> = sources + .iter() + .filter(|(p, _)| !removed_set.contains(p)) + .map(|(p, s)| (p.clone(), s.as_str())) + .collect(); + let fresh = WorkspaceIndex::build(remaining); + assert_eq!(ws.files().len(), fresh.files().len()); + assert_eq!(ws.fingerprint(), fresh.fingerprint()); +} + +#[test] +fn qa_tombstones_survive_mixed_remove_add_revive_absorb_and_all_queries_match_fresh() { + let base: Vec<(PathBuf, &str)> = vec![ + ( + PathBuf::from("a_defs.sv"), + "`define MAC_A 1\npackage p_a;\n typedef logic [7:0] t_a;\nendpackage\n", + ), + ( + PathBuf::from("b_mod.sv"), + "`define MAC_B 2\nmodule b_mod;\n import p_a::*;\n t_a sig_b;\nendmodule\n", + ), + ( + PathBuf::from("c_mid.sv"), + "`define MAC_C 3\nmodule c_mid;\n b_mod u_b ();\nendmodule\n", + ), + ( + PathBuf::from("d_dup.sv"), + "module dup;\nendmodule\nclass Base;\n int f;\nendclass\n", + ), + ( + PathBuf::from("e_tail.sv"), + "`define MAC_E 5\nmodule e_tail;\n dup u_d ();\n class Sub extends Base;\n function void g(); f = 1; endfunction\n endclass\nendmodule\n", + ), + ]; + + let mut ws = WorkspaceIndex::build(base.iter().map(|(p, s)| (p.clone(), *s))); + // Tombstone FileId(0) and middle FileId(2). + assert!(ws.remove_file(Path::new("a_defs.sv"))); + assert!(ws.remove_file(Path::new("c_mid.sv"))); + + // Live ids stay sparse while queries hide tombstones and match fresh build. + assert_eq!(ws.file_id(Path::new("b_mod.sv")), Some(FileId(1))); + assert_eq!(ws.file_id(Path::new("d_dup.sv")), Some(FileId(3))); + assert_eq!(ws.file_id(Path::new("e_tail.sv")), Some(FileId(4))); + assert!(ws.path(FileId(0)).is_none()); + assert!(ws.path(FileId(2)).is_none()); + assert!(ws.defines(FileId(0)).is_none()); + assert!(ws.defines(FileId(2)).is_none()); + assert!(ws.find_define("MAC_A").is_empty()); + assert!(ws.find_define("MAC_C").is_empty()); + assert_eq!(ws.find_define("MAC_E").len(), 1); + assert_eq!(ws.find_define("MAC_E")[0].0, FileId(4)); + assert_eq!( + ws.files(), + &[PathBuf::from("b_mod.sv"), PathBuf::from("d_dup.sv"), PathBuf::from("e_tail.sv")] + ); + let live: Vec<(FileId, PathBuf)> = ws.live_files().map(|(id, p)| (id, p.clone())).collect(); + assert_eq!( + live, + vec![ + (FileId(1), PathBuf::from("b_mod.sv")), + (FileId(3), PathBuf::from("d_dup.sv")), + (FileId(4), PathBuf::from("e_tail.sv")), + ] + ); + + let mut live_map: std::collections::BTreeMap = base + .iter() + .filter(|(p, _)| p != Path::new("a_defs.sv") && p != Path::new("c_mid.sv")) + .map(|(p, s)| (p.clone(), (*s).to_string())) + .collect(); + let assert_all_queries_match = + |ws: &WorkspaceIndex, live: &std::collections::BTreeMap, label: &str| { + let fresh = WorkspaceIndex::build(live.iter().map(|(p, s)| (p.clone(), s.as_str()))); + assert_eq!(ws.files(), fresh.files(), "{label}: files()"); + assert_eq!(ws.fingerprint(), fresh.fingerprint(), "{label}: fingerprint()"); + assert_eq!(ws.counts(), fresh.counts(), "{label}: counts()"); + assert_eq!(ws.table_sizes(), fresh.table_sizes(), "{label}: table_sizes()"); + for mac in ["MAC_A", "MAC_B", "MAC_C", "MAC_E"] { + let ws_m: Vec<_> = ws + .find_define(mac) + .into_iter() + .map(|(id, d)| (ws.path(id).map(Path::to_path_buf), d.name.clone())) + .collect(); + let fr_m: Vec<_> = fresh + .find_define(mac) + .into_iter() + .map(|(id, d)| (fresh.path(id).map(Path::to_path_buf), d.name.clone())) + .collect(); + assert_eq!(ws_m, fr_m, "{label}: find_define({mac})"); + } + for word in ["t_a", "sig_b", "u_b", "f", "Base", "MAC_E"] { + let ws_w: Vec<_> = ws + .files_mentioning(word) + .filter_map(|id| ws.path(id).map(Path::to_path_buf)) + .collect(); + let fr_w: Vec<_> = fresh + .files_mentioning(word) + .filter_map(|id| fresh.path(id).map(Path::to_path_buf)) + .collect(); + assert_eq!(ws_w, fr_w, "{label}: files_mentioning({word})"); + let ws_s: Vec<_> = ws + .files_spelling(word) + .filter_map(|id| ws.path(id).map(Path::to_path_buf)) + .collect(); + let fr_s: Vec<_> = fresh + .files_spelling(word) + .filter_map(|id| fresh.path(id).map(Path::to_path_buf)) + .collect(); + assert_eq!(ws_s, fr_s, "{label}: files_spelling({word})"); + let ws_mw: Vec<_> = ws + .files_naming_in_macros(word) + .filter_map(|id| ws.path(id).map(Path::to_path_buf)) + .collect(); + let fr_mw: Vec<_> = fresh + .files_naming_in_macros(word) + .filter_map(|id| fresh.path(id).map(Path::to_path_buf)) + .collect(); + assert_eq!(ws_mw, fr_mw, "{label}: files_naming_in_macros({word})"); + } + let ws_syms: Vec<_> = ws + .workspace_symbols("") + .into_iter() + .map(|s| { + ( + s.name.to_string(), + s.container.map(str::to_string), + ws.path(s.def.file).map(Path::to_path_buf), + ) + }) + .collect(); + let fr_syms: Vec<_> = fresh + .workspace_symbols("") + .into_iter() + .map(|s| { + ( + s.name.to_string(), + s.container.map(str::to_string), + fresh.path(s.def.file).map(Path::to_path_buf), + ) + }) + .collect(); + assert_eq!(ws_syms, fr_syms, "{label}: workspace_symbols"); + for path in live.keys() { + assert_eq!( + ws.facts_for(path).is_some(), + fresh.facts_for(path).is_some(), + "{label}: facts_for" + ); + } + }; + + assert_all_queries_match(&ws, &live_map, "after tombstoning 0 and 2"); + + // Revive slot 0 with exact previous content, then update slot 1, then remove slot 3. + assert!(ws.update_file(PathBuf::from("a_defs.sv"), base[0].1)); + live_map.insert(PathBuf::from("a_defs.sv"), base[0].1.to_string()); + assert_eq!(ws.file_id(Path::new("a_defs.sv")), Some(FileId(0))); + assert_all_queries_match(&ws, &live_map, "after reviving slot 0"); + + let b_v2 = "`define MAC_B 22\nmodule b_mod;\n import p_a::*;\n t_a sig_b2;\nendmodule\n"; + assert!(ws.update_file(PathBuf::from("b_mod.sv"), b_v2)); + live_map.insert(PathBuf::from("b_mod.sv"), b_v2.to_string()); + assert!(ws.remove_file(Path::new("d_dup.sv"))); + live_map.remove(Path::new("d_dup.sv")); + assert_all_queries_match(&ws, &live_map, "after updating slot 1 and tombstoning slot 3"); + + // Adding a brand new path via update_file triggers merge() & compacts tombstones. + let f_new = "module dup;\nendmodule\n"; + assert!(ws.update_file(PathBuf::from("0_first.sv"), f_new)); + live_map.insert(PathBuf::from("0_first.sv"), f_new.to_string()); + assert_eq!(ws.file_id(Path::new("0_first.sv")), Some(FileId(0))); + assert_all_queries_match(&ws, &live_map, "after update_file adding 0_first.sv"); + + // Tombstone again, then absorb with both `gone` and overlapping `records`. + assert!(ws.remove_file(Path::new("0_first.sv"))); + assert!(ws.remove_file(Path::new("e_tail.sv"))); + live_map.remove(Path::new("0_first.sv")); + let e_v2 = "`define MAC_E 55\nmodule e_tail;\nendmodule\n"; + live_map.insert(PathBuf::from("e_tail.sv"), e_v2.to_string()); + live_map.remove(Path::new("b_mod.sv")); + ws.absorb( + vec![vlog_semantic::FileFacts::of(PathBuf::from("e_tail.sv"), e_v2)], + &[PathBuf::from("b_mod.sv"), PathBuf::from("e_tail.sv")], + ); + assert_all_queries_match(&ws, &live_map, "after absorb with gone + revived"); +} + // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/docs/features/index-lifecycle-r2/README.md b/docs/features/index-lifecycle-r2/README.md new file mode 100644 index 0000000..b1462ed --- /dev/null +++ b/docs/features/index-lifecycle-r2/README.md @@ -0,0 +1,174 @@ + + +# Index Lifecycle & Fast Tombstone Removal (Round 2) + +## Goal + +Close four index/buffer lifecycle and symlink bugs identified in `docs/topo.md` (`#49`, `#63`, `#50`, `#51`): + +1. **Topo #49 (`vlog_semantic` fast tombstone removal + `lucisv_server` `didClose`)**: + - Keep `FileId` slots stable across `WorkspaceIndex::remove_file` via a parallel `tombstoned: Vec` mask and localized `replace_facts(at, empty_facts(path))` instead of shifting `FileId`s and running a full `merge()`. + - Compact tombstones on `merge()` / `absorb()`, revive tombstoned slots cleanly on `update_facts`, hide tombstones from all public queries (`files`, `file_id`, `path`, `defines`, `facts_for`, `files_spelling`, `files_mentioning`, `files_naming_in_macros`, `counts`, `table_sizes`), and remap dense IDs inside `fingerprint()` so a tombstoned index matches a fresh `WorkspaceIndex::build` byte-for-byte. + - Reconcile `didClose` in `lucisv_server` (`notification.rs` / `state/incremental.rs`): remove closed excluded/unlisted buffers via the fast tombstoned `remove_one` path (using `set_file_words` + `refresh_names` to keep removal sub-millisecond), and re-index dirty/unsaved closed in-scope buffers from disk via localized `replace_facts` (or remove if missing on disk). +2. **Topo #63 (Owner decision 2: always keep disk index record for `doc.large`)**: + - Standardize on always keeping the on-disk index record (subject to `lucisv.index.maxFileSize`) for open `doc.large` buffers across open, close, save, `largeFile.threshold` flips, widen, and whole scans (`state/discover.rs`, `state/rescan.rs`, `state/buffers.rs`, `state/incremental.rs`), achieving zero index mutation on `didOpen`, `didClose`, and `largeFile.threshold` flips. +3. **Topo #50 (Unheld buffers opened mid-scan)**: + - Reconcile buffers opened mid-scan (`state/rescan.rs`, `state/scan.rs`, `server/index.rs`) so excluded, unlisted, or unsaved-edited non-large buffers opened while a scan is in flight are absorbed into the running scan equivalently to being opened before the scan started. +4. **Topo #51 (Symlinked files — one file, one canonical spelling)**: + - Deduplicate and resolve file identity via `(dev, ino)` on Unix / `fs::canonicalize` fallback on non-Unix without basename-equality gating across discovery walks, `overlay_buffers`, `begin_widen`, `state/buffers.rs`, `state/incremental.rs`, and `state/watched.rs`, enforcing one deterministic canonical spelling in the index regardless of which symlink is open. + +## Assumptions + +- `WorkspaceIndex::files()` keeps returning `&[PathBuf]` containing only live files in path order so existing slice callers remain source- and ABI-compatible. +- Within a scope, canonical symlink spelling precedence follows deterministic path-sorted discovery order (the lexicographically smallest in-scope spelling for a given file identity), matching existing directory-symlink precedence and preserving symlinked workspace roots. +- During non-interleaved small scans (`scan.total() <= INTERLEAVE_ABOVE && !scan.discovery_pending()`), notifications remain queued until after `scan_once()` finishes, consistent with `server/index.rs`. + +## Handshakes + +- **Dense `FileId(i)` callers closed (`vlog_semantic`, `lucisv_server`, `lucisv_mcp`)**: + - After tombstoned `WorkspaceIndex::remove_file`, `index.files()` shrinks while remaining live files retain their pre-tombstone `FileId`s until the next full `merge()` or `absorb()`. + - Added `WorkspaceIndex::live_files(&self) -> impl Iterator + '_` (`crates/vlog_semantic/src/workspace/index.rs`) yielding only live `(FileId, &PathBuf)` pairs. + - Updated `crates/lucisv_server/src/state/sources.rs` (`want_macro_text`), `crates/lucisv_server/src/candidates.rs` (`macros_of`, used by `from_words`, `remove_file`, `absorb`, and `update_words`), `crates/lucisv_mcp/src/tools/names.rs` (`similar`), `crates/lucisv_mcp/src/tools/diagnostics.rs` (`Census::of`), and `crates/lucisv_server/src/state/tests/reindex_perf.rs` to iterate `index.live_files()` instead of `0..index.files().len()` / `.enumerate()`. +- **Symlinked open-buffer identity lookup wired across server handlers**: + - `Workspace` (`crates/lucisv_server/src/state/mod.rs`, `state/buffers.rs`) exposes `index_file_id`, `held_path_for`, `index_path_for`, `is_same_file`, `open_document_for_path`, and `document_for_path`, matching exact path first and falling back to `(dev, ino)` / canonical path while preserving ASCII case-mismatch separation (`case_only_mismatch`). + - Wired into `crates/lucisv_server/src/nav.rs`, `crates/lucisv_server/src/lint.rs` (`own` in `IndexMentions` and canonical `LintContext` path for `module-filename` / `package-filename` / config discovery), `crates/lucisv_server/src/state/sources.rs`, `crates/lucisv_server/src/ports.rs`, `crates/lucisv_server/src/rename.rs`, `crates/lucisv_server/src/extract.rs`, `crates/lucisv_server/src/inline_module.rs`, `crates/lucisv_server/src/imports.rs`, `crates/lucisv_server/src/completion/related.rs`, `crates/lucisv_server/src/hierarchy/calls.rs`, `crates/lucisv_server/src/includes.rs` (`resolve_for_doc`, `reachable_from`), and `crates/lucisv_server/src/hover.rs` (`narrowed_to_the_include_graph`). +- **Active-scan absorbed buffer tracking (`Workspace` -> `didClose`)**: + - `Workspace` (`crates/lucisv_server/src/state/mod.rs`) maintains `ScanAbsorbed` (canonical/open paths plus `DirId -> PathBuf` with `case_only_mismatch` guard), cleared on `begin_scan` and `finish_scan` (`state/rescan.rs`), and populated whenever open-buffer text/facts are absorbed in `begin_scan`, `scan_step`, or `reconcile_open_buffers_into` (`state/reconcile.rs`, covering `pos >= scan.at`, `pos < scan.at` staged updates, and `pos == None` excluded/unlisted/oversize entries). + - `Workspace::closing_affects_running_scan` (`state/incremental.rs`) consults `scan_absorbed` alongside out-of-scope and disk-mismatch checks without changing `server/mod.rs` or `server/index.rs` signatures. +- **`IncludeGraph::remove_file` linear rebuild outside owned files**: + - `IncludeGraph::remove_file` (`crates/lucisv_server/src/includes.rs:284`) calls `relearn(known)` across all live paths and lowercase folded strings on each removal. That rebuild dominates excluded-file `didClose` latency on a 4k-file index (~2.49 ms/removal in release, ~10.19 ms in debug) while `WorkspaceIndex::remove_file` itself is tombstoned and constant-slot (in-scope clean open+close cycles average ~88.9 µs in release / ~134.7 µs in debug on a 2k-file index). Left untouched per lane file ownership for a follow-up incremental `IncludeGraph` update. + +## Status / TODO + +- [x] Topo #49: Fast tombstoned `WorkspaceIndex::remove_file` and `didClose` index reconciliation + 4k/2,000-cycle perf test +- [x] Topo #63: Always keep disk index record for `doc.large` + differential tests +- [x] Topo #50: Reconcile unheld/unsaved buffers opened mid-scan + regression tests +- [x] Topo #51: Canonicalize symlinked file identities without basename gating across discovery, widen, buffers, incremental, watched + all 6 `filelink` scenario tests +- [x] QA Fix Pass (F1–F5): `WorkspaceIndex::live_files` + `0..files().len()` audit across `lucisv_server`/`lucisv_mcp`, non-canonical symlink handler wiring, mid-scan/widen oversize symlink canonicalization, and `largeFile.threshold` drop disk reconciliation +- [x] R2 Closing Pass (R2-F2 & R2-F3): Symlink-aware `` `include `` resolution / macro hover narrowing (`includes.rs`, `hover.rs`) and `Workspace::scan_absorbed` tracking across `begin_scan` / `scan_step` / `reconcile_open_buffers_into` / `closing_affects_running_scan` (`state/{mod.rs,rescan.rs,reconcile.rs,incremental.rs}`) + +## Work log + +- **Topo #49 (`vlog_semantic` + `lucisv_server`)**: Added `tombstoned: Vec` to `WorkspaceIndex` (`crates/vlog_semantic/src/workspace/{mod.rs,index.rs,update.rs}`) so `remove_file` clears the slot via `replace_facts(at, empty_facts(path))` without shifting `FileId`s or running full `merge()`, revives tombstones on `update_facts`, compacts on `merge()`/`absorb()`, hides tombstones from queries/counts, and monotonically remaps `FileId`s in `fingerprint()` to match a fresh build. Wired `DidCloseTextDocument` in `crates/lucisv_server/src/server/notification.rs` and `close_and_reconcile` / `remove_one` in `crates/lucisv_server/src/state/incremental.rs` so closed excluded/missing buffers are removed via fast tombstones and dirty/unsaved in-scope buffers revert from disk. +- **Topo #63 (`lucisv_server`)**: Standardized on Owner decision 2 (keeping on-disk index records subject to `maxFileSize` for open `doc.large` buffers) across `state/{buffers.rs,discover.rs,rescan.rs,incremental.rs}` and updated `state/tests/{large_file.rs,open_buffers.rs,widen.rs}` + `server/large_file.rs` comment. +- **Topo #50 (`lucisv_server`)**: Added `reconcile_open_buffers_into` in `state/rescan.rs` (invoked from `open_next`) so unheld or unsaved-edited buffers opened mid-scan are absorbed into the finished index consistently with pre-scan opens. +- **Topo #51 (`lucisv_server`)**: Replaced basename-gated symlink aliasing with `(dev, ino)` / canonical-path deduplication (`dedup_by_identity`) and deterministic canonical precedence across `state/{mod.rs,buffers.rs,discover.rs,scan.rs,rescan.rs,watched.rs,incremental.rs}`. +- **Tests**: Added 9 server lifecycle integration tests in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs` (including all 6 same-name/different-name symlink scenarios, `doc.large` differential checks, mid-scan opens, and 2,000-cycle `didClose` / open+close timings) alongside new `WorkspaceIndex` tombstone/perf tests in `crates/vlog_semantic/tests/workspace.rs`. +- **2026-11-26 QA Fix Pass (F1–F5)**: + - **F1**: Added `WorkspaceIndex::live_files()` (`crates/vlog_semantic/src/workspace/index.rs`) and replaced `0..index.files().len()` / `.enumerate()` `FileId` indexing across `state/sources.rs` (`want_macro_text`), `candidates.rs` (`macros_of`), `lucisv_mcp/src/tools/names.rs` (`similar`), `lucisv_mcp/src/tools/diagnostics.rs` (`Census::of`), and `state/tests/reindex_perf.rs`. Added MCP unit tests for tombstoned slot 0 in `names.rs` and `diagnostics.rs` and un-ignored both F1 tests in `lifecycle_r2.rs` (extending `Candidates::remove_file` coverage). + - **F2**: Added `Workspace::index_path_for` / `Workspace::is_same_file` (`state/mod.rs`) and `Workspace::open_document_for_path` (`state/buffers.rs`) while preserving `case_only_mismatch` separation in `index_file_id` and open-buffer lookup; wired across `nav.rs`, `lint.rs` (`own` and canonical `LintContext` path), `state/sources.rs`, `ports.rs`, `rename.rs`, `extract.rs`, `inline_module.rs`, `imports.rs`, `completion/related.rs`, and `hierarchy/calls.rs`. Un-ignored `qa_topo_51_non_canonical_symlink_open_buffer_breaks_references_lint_and_rename`. + - **F3 & F4**: Extracted `crates/lucisv_server/src/state/reconcile.rs` (keeping `state/rescan.rs` well under 600 production lines), carried in-scope `canonical_ids` across `oversize` skips on `Sources` / `Scan` (`state/{scan.rs,discover.rs,reconcile.rs}`) so mid-scan non-canonical symlinks over `maxFileSize` canonicalize identically to pre-scan, and updated `begin_widen` (`state/rescan.rs`) so open non-large buffers promote to lexicographically earlier symlinks even when over `maxFileSize`. Un-ignored both F3 and F4 tests in `lifecycle_r2.rs`. + - **F5**: Added `Workspace::reconcile_large_buffer` (`state/reconcile.rs`) and wired `Server::reclassify_large_buffers` (`server/large_file.rs`, `server/notification.rs`) so buffers flipping `large == false -> true` reconcile back to disk (or drop if outside scope/oversize/missing) when dirty/previously indexed unsaved edits exist, while doing zero index work for clean buffers whose disk record matches. Un-ignored `qa_topo_63_threshold_drop_after_unsaved_edit_indexed_via_widen_diverges_from_fresh`. +- **2026-11-26 Closing Pass (R2-F3 Option B)**: + - **R2-F3**: Added `ScanAbsorbed` (`paths: HashSet`, `ids: HashMap` with `case_only_mismatch` guard) on `Workspace` (`crates/lucisv_server/src/state/mod.rs`), cleared in `begin_scan` and `finish_scan` (`state/rescan.rs`), and recorded whenever open-buffer text/facts enter the running scan (`begin_scan` overlays, `scan_step` pops from `buffered`/`analyzed`, and `reconcile_open_buffers_into` across `pos >= scan.at`, `pos < scan.at` staged updates, and `pos == None` excluded/unlisted/oversize entries in `state/reconcile.rs`). Updated `Workspace::closing_affects_running_scan` (`state/incremental.rs`) to return `true` when `scan_absorbed` matches (including aliases before mid-scan publish and buffers flipped to `doc.large` with no surviving alias), keeping `server/mod.rs` and `server/index.rs` untouched. Un-ignored `qa_r2_f3_mid_scan_dirty_open_reverted_and_closed_leaves_stale_index` and added `r2_f3_mid_scan_dirty_reverted_and_closed_converges_across_all_scan_phases` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`. +- **2026-11-26 Plan Review Surgical Fix (R2-F2b, R2-F3a, R2-F3b)**: + - **R2-F2b**: Normalized `includes::resolve_for_doc` (`crates/lucisv_server/src/includes.rs`) output through `ws.index_path_for(&found)` so symlinked-directory includes resolve to canonical indexed paths. + - **R2-F3a & R2-F3b**: Simplified `Workspace::closing_affects_running_scan` (`crates/lucisv_server/src/state/incremental.rs`) to return `true` whenever `self.scan_absorbed.contains(path, &target) || self.has_other_document_for(uri, path)`, covering both `already_same` skipped secondary symlinks and `doc.large`-flipped absorbed symlinks closed mid-scan while a second alias remains open. Un-ignored all three `qa_r2_*` repro tests in `lifecycle_r2.rs`. + +## QA log + +- **Verdict**: `FAIL` (5 concrete findings blocking acceptance: F1–F2 handshake regressions/breakages across `lucisv_server` and `lucisv_mcp`, F3–F4 `#51`/`#50` oversize symlink canonicalization gaps in `state/rescan.rs`, F5 `#63` threshold-drop stale unsaved index in `server/large_file.rs`). + +### Audit & Hygiene +- **Production line counts & safety** (verified on all 12 modified production files before `mod tests`): `crates/lucisv_server/src/server/large_file.rs` (110), `server/notification.rs` (287), `state/buffers.rs` (110), `state/discover.rs` (487), `state/incremental.rs` (221), `state/mod.rs` (104), `state/rescan.rs` (590), `state/scan.rs` (137), `state/watched.rs` (123), `crates/vlog_semantic/src/workspace/index.rs` (351), `workspace/mod.rs` (167), `workspace/update.rs` (380) — all `<= 600` non-blank, non-comment lines with 0 `unwrap()`, `expect()`, `unsafe`, `panic!`, or `#[allow` in modified production code. +- **Author stamp**: `python3 tools/stamp_author.py --check` exited `0` (`would stamp 0 files; left 249 untouched`). + +### Findings +- **Finding F1 — `#49` Handshake Drift: callers iterating `0..index.files().len()` misalign/skip live `FileId`s after tombstone removal** + - `crates/lucisv_server/src/state/sources.rs:338` (`want_macro_text`): Closing an excluded file (`ignored/a_excl.sv`, `FileId(0)`) shrinks `index.files().len()` to `2` while `z_mac.sv` remains at `FileId(2)`. `want_macro_text` skips `FileId(2)`, omitting `z_mac.sv` from `rename_traced` macro-text checks and causing divergent macro warnings vs a fresh server. Reproduced in `qa_topo_49_tombstone_before_live_macro_breaks_rename_macro_text_fanout` (`#[ignore]` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`). + - `crates/lucisv_server/src/candidates.rs:837` (`macros_of` via `Candidates::from_words` / `Candidates::remove_file`): With `a_excl.sv` tombstoned (`files().len() == 1`, `z_mac.sv` at `FileId(1)`), `macros_of` returns `[]` instead of `["LIVE_MAC"]`. Reproduced in `qa_topo_49_candidates_macros_of_breaks_when_tombstone_precedes_live_macro_file` (`#[ignore]` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`). + - `crates/lucisv_mcp/src/tools/names.rs:191-192` (`similar`) and `crates/lucisv_mcp/src/tools/diagnostics.rs:267-269` (`Census::of`): Same `0..index.files().len()` / `enumerate()`-to-`FileId` assumption skips `FileId(1)` defines (`[]` vs `["LIVE_MAC"]`) and assigns shifted `FileId(0)` inside `Census::of` against `own = Some(FileId(1))` (making `Census::outside` falsely return `true`). Verified via transient unit tests on tombstoned `WorkspaceIndex` and reverted cleanly from `crates/lucisv_mcp`; note `lucisv_mcp`'s `Project::refresh` (`crates/lucisv_mcp/src/project/mod.rs:175`) currently updates `self.index` only through `absorb(...)` (which compacts tombstones), so `lucisv_mcp` hits this only via direct `WorkspaceIndex::remove_file` callers. +- **Finding F2 — `#51` Handshake Drift: non-canonical symlink open buffer fails references, lint, and rename** + - When `a_link/link_a.sv -> z_real/real_b.sv` is canonically indexed as `a_link/link_a.sv` and the client opens `z_real/real_b.sv`, callers matching `doc.path` verbatim instead of `Workspace::index_file_id` / `Workspace::held_path_for` / `Workspace::document_for_path` break live LSP operations. Reproduced in `qa_topo_51_non_canonical_symlink_open_buffer_breaks_references_lint_and_rename` (`#[ignore]` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`): + - `textDocument/references` (`crates/lucisv_server/src/nav.rs:232,295`) returns `1` ref instead of `2` (cross-file reference in `tb/tb.sv` dropped). + - Diagnostics (`crates/lucisv_server/src/lint.rs:244`) pass `own = None` to `IndexMentions`, so `mentioned_outside("dead_sig", None)` sees `dead_sig` in canonical `a_link/link_a.sv` and suppresses `unused-signal` (and `module-filename` checks against `real_b.sv` rather than `link_a.sv`). + - `rename_traced` (`crates/lucisv_server/src/state/sources.rs:206`) overlays `z_real/real_b.sv` over indexed `a_link/link_a.sv` and refuses both from `z_real/real_b.sv` and from `tb/tb.sv` with ``Err("`dut` is declared in more than one indexed file; lucisv will not guess which declaration this rename means.")`` (and `crates/lucisv_server/src/ports.rs:555` `encode_edit` similarly checks `doc.path.as_deref() == Some(path)`). +- **Finding F3 — `#50` + `#51`: mid-scan non-canonical symlink over `maxFileSize` diverges from pre-scan open** + - `crates/lucisv_server/src/state/rescan.rs:518-524` (`reconcile_open_buffers_into`): When both `z_real/dut.sv` and `a_link/dut.sv -> z_real/dut.sv` exceed `maxFileSize` (remaining `<= largeFile.threshold`), `a_link/dut.sv` is excluded by `oversize` and absent from `scan.work`. Opening `z_real/dut.sv` mid-scan gets `pos = None` and indexes non-canonical `z_real/dut.sv` instead of canonical `a_link/dut.sv` (unlike pre-scan `overlay_buffers`). Reproduced in `qa_topo_50_mid_scan_non_canonical_symlink_over_max_file_size_matches_pre_scan` (`#[ignore]` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`). +- **Finding F4 — `#51`: widening into lexical-earlier symlink over `maxFileSize` fails to promote canonical spelling** + - `crates/lucisv_server/src/state/rescan.rs:167` (`begin_widen`): When `z_real/real.sv` (`> maxFileSize`, `<= largeFile.threshold`) is open in folder scope and widening into `a_link/` discovers `a_link/alias.sv -> z_real/real.sv`, `if path < existing && oversize(...).is_none()` blocks promoting to `a_link/alias.sv`, leaving `z_real/real.sv` in `index.files()` instead of `a_link/alias.sv` as a fresh server does. Reproduced in `qa_topo_51_widen_symlink_over_max_file_size_converges_like_fresh` (`#[ignore]` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`). +- **Finding F5 — `#63`: threshold drop after unsaved edit indexed via widen leaves stale unsaved index** + - `crates/lucisv_server/src/server/large_file.rs:179-199` (`reclassify_large_buffers`): When an unsaved edited in-scope buffer is indexed while `doc.large == false` (e.g. via widen) and `didChangeConfiguration` drops `lucisv.largeFile.threshold` so `doc.large` flips `true`, `reclassify_large_buffers` does not restore the on-disk record into the workspace index (stale unsaved buffer remains indexed while `doc.large == true` until next save/widen/close). Reproduced in `qa_topo_63_threshold_drop_after_unsaved_edit_indexed_via_widen_diverges_from_fresh` (`#[ignore]` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`). + +### Live OpenTitan Probe & Passing QA Coverage +- **OpenTitan `/Users/lucio/repo/opentitan/hw` (`#63`, read-only)**: Probed `/Users/lucio/repo/lucisv/target/release/lucisv-server` (`persist: false`, scratch env, `largeFile.threshold = 50000`) on `hw/ip/aes/rtl/aes_reg_top.sv` (`55,523 B`) and `hw/ip/aes/rtl/aes.sv` (`13,993 B`) across pre-scan open, post-scan open, threshold flips (`20000`, `10000` vs fresh `10000`, `500000`, `50000`), `didClose`, and folder-scope widen into `hw/ip/aes/rtl`. Settled `workspace/symbol`, `definition`, `references`, `codeLens`, and `lucisv/moduleHierarchy` matched fresh server answers 100% (`hier_files=1577, refs=2, syms=1` in workspace scope); `git -C /Users/lucio/repo/opentitan status --porcelain` stayed clean. +- **Un-ignored QA checks passing**: `qa_tombstones_survive_mixed_remove_add_revive_absorb_and_all_queries_match_fresh` (`crates/vlog_semantic/tests/workspace.rs`) plus `qa_topo_49_tombstone_at_zero_and_middle_navigation_symbols_hierarchy_codelens_diagnostics_completion`, `qa_topo_63_all_paths_and_threshold_drop_after_unsaved_edit`, `qa_topo_50_first_scope_passed_unreached_and_mid_scan_close`, and `qa_topo_51_same_name_nested_both_open_dirty_close_and_filelist_close` (`crates/lucisv_server/src/server/tests/lifecycle_r2.rs`). + +### Final Gates (after last edit) +- `python3 tools/stamp_author.py --check` -> exit `0` (`would stamp 0 files; left 249 untouched`) +- `cargo fmt -p vlog_semantic -p lucisv_server -- --check` -> exit `0` +- `./tools/guard.sh -m 6 -t 600 -- cargo clippy --workspace --all-targets -- -D warnings` -> exit `0` +- `./tools/guard.sh -m 6 -t 600 -- cargo test -p vlog_semantic -p lucisv_server -p vlog_refactor -p lucisv_mcp -p vlog_linter --all-targets` -> exit `0` (`lucisv_server` unit: `2061 passed; 0 failed; 53 ignored` [includes 6 QA finding reproductions], `e2e`: `106 passed; 3 ignored`, `grammar`: `3 passed`, `ifdef_folding`: `1 passed`, `opentitan_references`: `0 passed; 2 ignored`; `vlog_semantic` `workspace`: `92 passed; 2 ignored` + remaining 19 binaries `0 failed`; `vlog_linter`: `658` unit + `14` `lint_cases` passed; `vlog_refactor`: all 20 binaries `0 failed`; `lucisv_mcp`: all 16 binaries `0 failed`). + +### 2026-11-26 Round 2 Re-Verification (after DEV F1–F5 Fix Pass) +- **Verdict**: `FAIL` (F1, F4, F5, and core F2/F3 scenarios pass; 2 new edge defects reproduced under adversarial F2/F3 attacks in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`). +- **Audit & Hygiene**: + - Verified all 27 modified/created production `.rs` files remain `<= 600` non-blank, non-comment lines before `mod tests` (max `crates/lucisv_server/src/state/discover.rs` = `505`), with `0` `unwrap()`, `expect()`, `panic!`, `unsafe`, or `#[allow` in added/modified production lines. + - Audited every `.files()` and `FileId(` call site across `crates/` — zero remaining dense `0..files().len()` or `.files().enumerate()` assumptions over potentially tombstoned indexes in production code. + - `python3 tools/stamp_author.py --check` -> exit `0` (`would stamp 0 files; left 249 untouched`). +- **Confirmed Resolved**: + - **F1 (`live_files()`)**: All `qa_topo_49_*` pass; added `qa_r2_f1_multiple_tombstones_candidates_absorb_update_words_rename_and_completion` (`lifecycle_r2.rs`) and `qa_r2_f1_mcp_find_and_check_with_multiple_tombstones_preceding_live_files` (`crates/lucisv_mcp/src/tools/diagnostics.rs`), confirming `Candidates::from_words`/`update_words`/`absorb`, `rename_traced` macro-text warnings, `Completion`, `mcp::check`, and `mcp::find` (`refs` + near-match suggestions) pass with 3 tombstones preceding live files. + - **F2 (core LSP handlers)**: `qa_topo_51_non_canonical_symlink_open_buffer_breaks_references_lint_and_rename` passes, plus `qa_r2_f2_non_canonical_symlink_open_buffer_across_all_handlers_and_case_mismatch` passes for symbol `hover`, symbol `gotoDefinition`, `ports::offers`/`resolve_for`, `extract::code_actions`/`execute`, `imports::offers`/`resolve`, `completion` `related_tier`, `callHierarchy` (`incoming` + `outgoing`), `design_hierarchy`, and macOS `case_only_mismatch` (`Foo.sv` vs `foo.sv`). + - **F3 (simple mid-scan close) & F4 (widen symlinks)**: `qa_topo_50_mid_scan_non_canonical_symlink_over_max_file_size_matches_pre_scan`, `qa_r2_f3_mid_scan_open_dirty_symlink_and_close_mid_scan_matches_fresh` (in-scope and over `maxFileSize`), `qa_topo_51_widen_symlink_over_max_file_size_converges_like_fresh`, and `qa_r2_f4_widen_symlink_pointing_outside_root_converges_like_fresh` (under/over cap, closed/open outside targets) all pass. + - **F5 (`reclassify_large_buffers`)**: `qa_topo_63_threshold_drop_after_unsaved_edit_indexed_via_widen_diverges_from_fresh` and `qa_r2_f5_reclassify_large_buffers_excluded_dirty_clean_and_round_trip` pass (clean `false -> true` does 1 empty `Document::large("")` parse and leaves `index().fingerprint()` / `derived_fingerprint()` unchanged; excluded unsaved drops from index; in-scope dirty preserves disk record across `false -> true` and `true -> false -> true` flips). +- **Remaining / New Findings**: + - **Finding R2-F2 (`includes.rs:552,584` & `hover.rs:101`) — Non-canonical symlink open buffer fails `` `include `` resolution & macro hover narrowing**: `includes::resolved` (`crates/lucisv_server/src/includes.rs:552`) and `includes::definition` (`:584`) pass raw `doc.path.as_deref()` instead of `ws.index_path_for`, and `hover::narrowed_to_the_include_graph` (`crates/lucisv_server/src/hover.rs:101`) filters `ws.index().path(*file)` via `reachable.contains(p)` without file-identity matching. Reproduced in `#[ignore]`d `qa_r2_f2_symlink_include_related_macros_links_def_and_hover_narrowing`: opening `z_real/real_b.sv` (when `a_link/link_a.sv -> z_real/real_b.sv` is indexed alongside `a_link/link_h.svh`) degrades `completion` `related_macros` (`sortText` `"5\`LINK_HDR_MAC"` vs `"4\`LINK_HDR_MAC"`), returns `[]` for `textDocument/documentLink` and `` `include `` `textDocument/definition`, and fails macro include-graph narrowing on `` `SHARED_MAC `` (`"defined 2 times"`). + - **Finding R2-F3 (`state/incremental.rs:192-203`) — Mid-scan `didOpen(dirty symlink)` -> `didChange(disk)` -> `didClose` leaves stale `IN_BUF` edit**: `Workspace::closing_affects_running_scan` checks `fs::read_to_string(&target).ok().as_ref() != Some(&doc.text)`, returning `false` after `didChange` restores disk text even though the earlier mid-scan `didOpen(dirty)` had already been absorbed into the running scan. Reproduced in `#[ignore]`d `qa_r2_f3_mid_scan_dirty_open_reverted_and_closed_leaves_stale_index` (`ON_DISK = 0`, `IN_BUF = 1`). +- **Final Gates**: + - `python3 tools/stamp_author.py --check` -> exit `0` (`would stamp 0 files; left 249 untouched`) + - `cargo fmt --all -- --check` -> exit `0` + - `./tools/guard.sh -m 6 -t 600 -- cargo clippy --workspace --all-targets -- -D warnings` -> exit `0` + - `./tools/guard.sh -m 6 -t 600 -- cargo test -p vlog_semantic -p lucisv_server -p vlog_refactor -p lucisv_mcp -p vlog_linter --all-targets` -> exit `0` (`lucisv_server` unit: `2072 passed; 0 failed; 49 ignored` [includes 2 `qa_r2_*` `#[ignore]`d reproductions], `e2e`: `106 passed; 0 failed; 3 ignored`, `grammar`: `3 passed`, `ifdef_folding`: `1 passed`, `opentitan_references`: `0 passed; 2 ignored`; `lucisv_mcp`: all 16 binaries `0 failed`; `vlog_linter`: `658` unit + `14` `lint_cases` passed; `vlog_refactor`: all 24 binaries `0 failed`; `vlog_semantic`: all 21 binaries `0 failed`, `workspace`: `92 passed; 0 failed; 2 ignored`). + +### 2026-11-26 Round 2 Closing-Pass QA Verification (after R2-F2 & R2-F3 Fixes) +- **Verdict**: `FAIL` (both previously `#[ignore]`d R2-F2 and R2-F3 reproductions now pass un-ignored, and `didOpen(dirty) -> didSave(None) -> didClose` converges, **but** adversarial multi-hop symlinked-directory and `has_other_document_for` two-URI mid-scan close attacks uncover 3 concrete defects: `R2-F2b`, `R2-F3a`, `R2-F3b`). +- **Audit & Hygiene**: + - `git status --short` / `git diff --stat`: 35 modified + 2 untracked `.rs` files (`reconcile.rs`, `lifecycle_r2.rs`) + `docs/features/index-lifecycle-r2/`. + - Verified all 29 modified/created production `.rs` files remain `<= 600` non-blank, non-comment lines before `mod tests` (max `crates/lucisv_server/src/state/discover.rs` = `505`, `state/reconcile.rs` = `225`, `state/rescan.rs` = `480`, `state/incremental.rs` = `225`, `state/mod.rs` = `149`, `includes.rs` = `353`, `hover.rs` = `323`), with `0` `unwrap()`, `expect()`, `panic!`, `unsafe`, or `#[allow` in added/modified production lines. + - `python3 tools/stamp_author.py --check` -> exit `0` (`would stamp 0 files; left 249 untouched`). +- **Confirmed Resolved & New Passing QA Checks**: + - **R2-F2**: `qa_r2_f2_symlink_include_related_macros_links_def_and_hover_narrowing` runs un-ignored and passes. Added un-ignored `qa_r2_f2_multihop_transitive_symlink_headers` (confirming `documentLink`, `` `include `` `definition`, `completion` `related_macros` for transitive `H2_DEEP_MAC`, and `hover` macro narrowing over `z_real/real_b.sv` -> `a_link/link_h1.svh` -> `a_link/link_h2.svh`) and `qa_r2_f2_multihop_symlink_directory_completion_and_hover_narrowing` (confirming transitive `completion` `related_macros` and `hover` macro narrowing over symlinked directory `a_link_dir -> z_real_dir`, including non-canonical open `z_real_dir/real_b.sv` and external caller `rtl/caller.sv` -> `../z_real_dir/h1.svh`), all passing. + - **R2-F3**: `qa_r2_f3_mid_scan_dirty_open_reverted_and_closed_leaves_stale_index` and `r2_f3_mid_scan_dirty_reverted_and_closed_converges_across_all_scan_phases` run un-ignored and pass. Added un-ignored `qa_r2_f3_mid_scan_dirty_open_saved_none_and_closed` (covering `didOpen(dirty) -> didSave(None) -> didClose` mid-scan for `in_scope_future`, `in_scope_past`, and `excluded`) and `qa_r2_f3_two_symlink_uris_both_dirty_one_closed_mid_scan_converges` (`pos >= scan.at`), all passing. +- **New Findings (Reproduced as `#[ignore]`d tests in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`)**: + - **Finding R2-F2b (`crates/lucisv_server/src/includes.rs:544-552`) — `resolve_for_doc` returns non-canonical target for symlinked directory**: When `a_link_dir -> z_real_dir` is a symlinked directory (`a_link_dir/{real_b.sv,h1.svh,h2.svh}` indexed) and the client opens `z_real_dir/real_b.sv` containing `` `include "h1.svh" ``, `resolve_for_doc` returns `graph.resolve(doc.path.as_deref(), include)` directly (`z_real_dir/h1.svh`) without normalizing through `ws.index_path_for(...)`, so `documentLink` and `` `include `` `definition` point to non-canonical `z_real_dir/h1.svh` instead of canonical `a_link_dir/h1.svh` (diverging from `via_canon` and `nav.rs`). Reproduced in `#[ignore]`d `qa_r2_f2_multihop_symlink_directory_links_and_def_return_non_canonical`. + - **Finding R2-F3a (`crates/lucisv_server/src/state/reconcile.rs:192-194` & `crates/lucisv_server/src/state/incremental.rs:197-203`) — closing clean canonical symlink at `pos < scan.at` with `has_other_document_for` drops surviving dirty symlink buffer**: When `0_link/dut.sv -> z_real/dut.sv` (`pos < scan.at`, already stepped cleanly from disk `ON_DISK`) is opened with `ON_DISK` alongside `z_real/dut.sv` with `DIRTY_Z`, `reconcile_open_buffers_into` handles `0_link/dut.sv` first, takes `if already_same { continue; }` without calling `scan_absorbed.record(...)`, and skips `z_real/dut.sv` via `matched_positions.insert(pos)`. Mid-scan `didClose(0_link/dut.sv)` then sees `scan_absorbed == false` and `has_other == true` in `closing_affects_running_scan`, returning `false` at `if has_other { return false; }`, so the scan finishes with `ON_DISK` instead of surviving open `z_real/dut.sv`'s `DIRTY_Z`. Reproduced in `#[ignore]`d `qa_r2_f3_two_symlink_uris_one_closed_already_same_drops_surviving_dirty`. + - **Finding R2-F3b (`crates/lucisv_server/src/state/incremental.rs:198-203`) — closing `doc.large`-flipped absorbed symlink with `has_other_document_for` leaves stale absorbed edits**: When `a_link/dut.sv` (`DIRTY_A`, absorbed into `scan` and recorded in `scan_absorbed`) and `z_real/dut.sv` (`ON_DISK`) are both open, `didChange` flips `a_link/dut.sv` to `doc.large = true`, and `didClose(a_link/dut.sv)` runs mid-scan while `z_real/dut.sv` remains open, `closing_affects_running_scan` evaluates `(!doc.large || !has_other)` as `false` and returns `false` at `if has_other { return false; }`. No follow-up rescan runs, leaving stale `DIRTY_A` from the closed `a_link/dut.sv` in the finished index instead of `z_real/dut.sv`'s `ON_DISK`. Reproduced in `#[ignore]`d `qa_r2_f3_two_symlink_uris_large_flip_one_closed_leaves_stale_index`. +- **Final Gates**: + - `python3 tools/stamp_author.py --check` -> exit `0` (`would stamp 0 files; left 249 untouched`) + - `cargo fmt --all -- --check` -> exit `0` + - `./tools/guard.sh -m 6 -t 600 -- cargo clippy --workspace --all-targets -- -D warnings` -> exit `0` + - `./tools/guard.sh -m 6 -t 600 -- cargo test -p vlog_semantic -p lucisv_server -p vlog_refactor -p lucisv_mcp -p vlog_linter --all-targets` -> exit `0` (`lucisv_server` unit: `2079 passed; 0 failed; 50 ignored` [includes the 3 `qa_r2_*` `#[ignore]`d reproductions], `e2e`: `106 passed; 0 failed; 3 ignored`, `grammar`: `3 passed`, `ifdef_folding`: `1 passed`, `opentitan_references`: `0 passed; 2 ignored`; `lucisv_mcp`: all 16 binaries `0 failed`; `vlog_linter`: `658` unit + `14` `lint_cases` passed; `vlog_refactor`: all 24 binaries `0 failed`; `vlog_semantic`: all 21 binaries `0 failed`, `workspace`: `92 passed; 0 failed; 2 ignored`). + - `/tmp` clean (`0` `lucisv` temp files leftover); `/Users/lucio/repo/opentitan` untouched (`git status --porcelain` empty). + +### 2026-11-26 Round 2 Final QA Sign-Off (after R2-F2b, R2-F3a, R2-F3b & Cross-Platform `DirId` Fixes) +- **Verdict**: `PASS` +- **Resolved Repros (un-ignored and passing in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`)**: + - `qa_r2_f2_multihop_symlink_directory_links_and_def_return_non_canonical` (`ok`) + - `qa_r2_f3_two_symlink_uris_one_closed_already_same_drops_surviving_dirty` (`ok`) + - `qa_r2_f3_two_symlink_uris_large_flip_one_closed_leaves_stale_index` (`ok`) + - `crates/lucisv_server/src/server/tests/lifecycle_r2.rs` now has `0` `#[ignore]`d tests. +- **Edge-Case & Cross-Platform Audit**: + - `crates/lucisv_server/src/includes.rs:544-552` (`resolve_for_doc`): `ws.index_path_for(&found)` delegates to `held_path_for(found).unwrap_or_else(|| found.to_path_buf())` (`state/mod.rs:219-221`), returning `found` unchanged when `found` is a closed excluded header not present in `self.index` (and returning the indexed spelling if opened as non-large or if another symlink of the same file is indexed, while honoring `case_only_mismatch`). + - `crates/lucisv_server/src/state/incremental.rs:193-204` (`closing_affects_running_scan`): returning `true` on `self.scan_absorbed.contains(path, &target) || self.has_other_document_for(uri, path)` preserves surviving dirty/clean/`doc.large` symlink buffers on mid-scan `didClose` across all `scan.at` phases (`pos < scan.at` `already_same` skips, `pos >= scan.at`, `doc.large` flips, and `case_only_mismatch` isolation in `has_other_document_for`) without breaking any existing `lucisv_server` test. + - `crates/lucisv_server/src/state/discover.rs:715-735` and `crates/lucisv_server/src/state/reconcile.rs:206-215`: non-Unix `DirId` (`PathBuf`) borrow-before-move ordering (`&id` / `id.as_ref()` before `canonical_ids.entry(id)` and `added_ids.insert(k)`) passes `cross` for both `x86_64-pc-windows-gnu` and `x86_64-unknown-linux-musl`. +- **Audit & Hygiene**: + - Verified all 29 modified/created production `.rs` files remain `<= 600` non-blank, non-comment lines before `mod tests`: `crates/lucisv_server/src/includes.rs` (`353`), `state/incremental.rs` (`221`), `state/discover.rs` (`510`, max across all modified prod files), `state/reconcile.rs` (`231`), with `0` `unwrap()`, `expect()`, `panic!(`, `unsafe`, or `#[allow` in production sections. + - `python3 tools/stamp_author.py --check` -> exit `0` (`would stamp 0 files; left 249 untouched`). +- **Final Gates (`./tools/gates.sh --only fmt,clippy,suite:vlog_semantic,suite:lucisv_server,suite:lucisv_mcp,cross`, logs in `target/gates/20261126-111210`)**: + - `fmt` -> `pass` (exit `0`) + - `clippy` -> `pass` (exit `0`) + - `suite:vlog_semantic` -> `pass` (`21` binaries: `438 passed; 0 failed; 4 ignored`) + - `suite:lucisv_server` -> `pass` (`5` binaries: `2192 passed; 0 failed; 52 ignored`; unit `2082 passed; 0 failed; 47 ignored`, `e2e` `106 passed; 3 ignored`, `grammar` `3 passed`, `ifdef_folding` `1 passed`, `opentitan_references` `0 passed; 2 ignored`) + - `suite:lucisv_mcp` -> `pass` (`16` binaries: `391 passed; 0 failed; 4 ignored`) + - `cross` -> `pass` (`x86_64-pc-windows-gnu` & `x86_64-unknown-linux-musl` for `lucisv`, `lucisv_server`, `lucisv_mcp`, exit `0`) + - `/tmp` clean; `/Users/lucio/repo/opentitan` untouched (`git status --porcelain` empty). + +## Review + +### 2026-11-26 — Lead review: PASS (Round 2 complete) + +- Verified all Round 2 deliverables (`#49` fast tombstones via `WorkspaceIndex::remove_file` + `live_files()`, `#50` mid-scan open buffer reconciliation, `#51` `(dev, ino)` canonical symlink deduplication across handlers/includes/hover, `#63` least-performance-impact disk record preservation for `doc.large`, and `ScanAbsorbed` tracking + cross-platform `DirId` borrow fixes) and checked that `crates/lucisv_server/src/server/tests/lifecycle_r2.rs` has 0 `#[ignore]`d tests left. +- All 29 modified/created production files stay `<= 600` non-blank, non-comment lines before `mod tests`, with `0` `unwrap`/`expect`/`panic!`/`unsafe`. +- Handshakes closed in `docs/topo.md`: `#48` (closed won't-fix per owner ruling: rely on VS Code), `#49`, `#50`, `#51`, `#63`. Full `./tools/gates.sh` (including `cross`) and final QA sign-off gates verified green. + + diff --git a/docs/topo.md b/docs/topo.md index ea832da..3fa132f 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -773,10 +773,10 @@ update the filing README(s) and this file. | 45 | **`` `ifdef `` between `end` and `else` is a parse error** (TODO §71 wave 4) | format-styles (QA) | vlog_parser | | 46 | **An attribute on an ANSI port** (`(* keep *) input a`) is a parse error (TODO §71 wave 4) | format-styles (QA) | vlog_parser | | 47 | **Multi-instance declarations under one-per-line styles** (`p1 u8 (...), u9 (...)`) get the hanging layout instead of the style's (TODO §71 wave 4; CHANGELOG 0.65.5 known limit) | format-styles (QA) | vlog_formatter | -| 48 | **Directory-only watcher events.** VS Code coalesces deletes under a removed folder into one folder event and the client's `**/*.{v,vh,sv,svh}` filter drops it, so the server receives nothing; a folder moved in is dropped likewise. Wanted: a second registration (`**/*`, `Create \| Delete`) and a handler expanding a folder to the held files and include lines under it — changes every client's registration and traffic, the owner's call (TODO §71 waves 5–6) | localized-reindex (QA P1); scan-ordering | owner decision, then lucisv_server (`main.rs`/`watch.rs`) | -| 49 | **A buffer the scope would not take stays indexed after `didClose`** (excluded or unlisted, taken in by a scan or the one-file path), and **closing an unsaved in-scope buffer a rescan indexed leaves its text in the index** (QA-7a). One root: a close does not touch the index. A one-file remove costs ~225 ms on OpenTitan (fixed and reverted in scan-ordering); wanted: a cheap removal, e.g. a tombstone the next scan or publish folds in (TODO §71 waves 5–6) | localized-reindex (QA P2); scan-ordering (QA-1, QA-7a) | vlog_semantic (index removal) / lucisv_server (`state/`) | -| 50 | **An unheld buffer opened while a scan runs is never taken in** by that scan or afterwards; opened before the scan it is held — the same final state answers differently by timing (TODO §71 wave 6) | scan-ordering (QA-2) | lucisv_server (`state/scan.rs`, `server/index.rs`) | -| 51 | **Symlinked files are held under one spelling or both** depending on what was open at scan time (`discover.rs`'s `Aliased`); incremental and rebuild answers disagree in all six `filelink.py` variants. Rule to adopt: one file, one spelling, whatever is open — in the walk, the overlay and the one-file path together (TODO §71 waves 5–6) | localized-reindex (QA P3); scan-ordering | lucisv_server (`state/discover.rs`, `state/incremental.rs`) | +| ~~48~~ | ~~**Directory-only watcher events.** VS Code coalesces deletes under a removed folder into one folder event and the client's `**/*.{v,vh,sv,svh}` filter drops it, so the server receives nothing; a folder moved in is dropped likewise. Wanted: a second registration (`**/*`, `Create \| Delete`) and a handler expanding a folder to the held files and include lines under it — changes every client's registration and traffic, the owner's call (TODO §71 waves 5–6)~~ — **closed 2026-11-26 (won't-fix by owner ruling):** rely on VS Code; no second watcher registration added. | localized-reindex (QA P1); scan-ordering | ~~owner decision~~ won't-fix | +| ~~49~~ | ~~**A buffer the scope would not take stays indexed after `didClose`** (excluded or unlisted, taken in by a scan or the one-file path), and **closing an unsaved in-scope buffer a rescan indexed leaves its text in the index** (QA-7a). One root: a close does not touch the index. A one-file remove costs ~225 ms on OpenTitan (fixed and reverted in scan-ordering); wanted: a cheap removal, e.g. a tombstone the next scan or publish folds in (TODO §71 waves 5–6)~~ — **closed 2026-11-26 by `index-lifecycle-r2` (Round 2):** `WorkspaceIndex::remove_file` tombstones slots in-place via `replace_facts`, `live_files()` skips tombstones across all callers (`sources.rs`, `candidates.rs`, `lucisv_mcp`), and `DidCloseTextDocument` calls `close_and_reconcile` (2,000 cycles on 4k index at ~2.98 ms / 112.6 µs). | localized-reindex (QA P2); scan-ordering (QA-1, QA-7a) | ~~vlog_semantic / lucisv_server~~ done | +| ~~50~~ | ~~**An unheld buffer opened while a scan runs is never taken in** by that scan or afterwards; opened before the scan it is held — the same final state answers differently by timing (TODO §71 wave 6)~~ — **closed 2026-11-26 by `index-lifecycle-r2` (Round 2):** `reconcile_open_buffers_into`, `ScanAbsorbed`, and `closing_affects_running_scan` reconcile mid-scan opens/edits/closes to match pre-scan opens. | scan-ordering (QA-2) | ~~lucisv_server (`state/`)~~ done | +| ~~51~~ | ~~**Symlinked files are held under one spelling or both** depending on what was open at scan time (`discover.rs`'s `Aliased`); incremental and rebuild answers disagree in all six `filelink.py` variants. Rule to adopt: one file, one spelling, whatever is open — in the walk, the overlay and the one-file path together (TODO §71 waves 5–6)~~ — **closed 2026-11-26 by `index-lifecycle-r2` (Round 2):** `(dev, ino)` / canonical-path deduplication without basename gating across discovery, widen, buffers, `includes.rs`, `hover.rs`, and handlers (`index_path_for` / `is_same_file`). | localized-reindex (QA P3); scan-ordering | ~~lucisv_server (`state/`, handlers)~~ done | | ~~52~~ | ~~**A request held during a scan is answered against the newest text**, so a position-based request can resolve a different symbol when an edit moved the text under it; rename edits carry no document version for the client to reject (TODO §71 wave 6)~~ — **closed 2026-11-26 by `server-ordering-r1` (Round 1):** `Document` tracks client `version: Option`, and `ports::encode_edit` (shared by `rename.rs` and `ports.rs`) emits versioned `DocumentChanges::Edits` preserving open client URIs when `workspace.workspaceEdit.documentChanges` is advertised. | scan-ordering (QA) | ~~lucisv_server (`server/`, `rename.rs`)~~ done | | ~~53~~ | ~~**Renaming a port of a module defined twice** gives an edit or a refusal at random across fresh servers (`top_englishbreakfast/ip/ast/rtl/adc.sv:81`, `qa717/drv/dup.py`); not diagnosed (TODO §71 wave 6)~~ — **closed 2026-11-26 by Round 1 (`refactor-correctness-r1` + `server-ordering-r1`):** `lucisv_server` holds workspace-wide mutating requests (`rename`, `codeAction/resolve`, `executeCommand`, `willRenameFiles`) in `after_scan` across `self.scanning`, and `vlog_refactor::rename` + `preflight` + `same_file::renamed_here` refuse members inside duplicated file-scope units; verified 10/10 deterministic on OpenTitan `adc.sv:81`. | scan-ordering (QA-7c) | ~~vlog_refactor / lucisv_server~~ done | | 54 | **`lucisv-mcp` re-reads a file with a future mtime on every call**, forever (67 ms against 7 ms per `find` on 4 000 files) — the racy rule never settles (TODO §70) | linux-test-portability (Round 2) | lucisv_mcp (`project/files.rs`) | @@ -788,7 +788,7 @@ update the filing README(s) and this file. | 60 | **An edit in one file that changes how another open file colours sends no refresh** (a package type renamed) — as before this lane (TODO §71 wave 7) | viewport-highlight | lucisv_server (`server/viewport.rs`) | | ~~61~~ | ~~**Inside the startup settings wait, the client's answer to the pull is applied ahead of an older settings push held with it** (`server/startup.rs`, `take_the_answer_out_of_held`); predates fast-actions; needs a client whose push and answer disagree in one burst (TODO §71 wave 8; fast-actions QA F1)~~ — **closed 2026-11-26 by `server-ordering-r1` (Round 1):** `take_the_answer_out_of_held` drains older `DidChangeConfiguration` pushes preceding the plucked pull answer while keeping newer pushes. | fast-actions (QA) | ~~lucisv_server (`server/startup.rs`)~~ done | | ~~62~~ | ~~**`tests/fast_actions_bursts.rs`'s oracle accepts an answer the reference gives after any later message of the round**: 2–9 % of injected stale answers pass when a later message restores the state; every mutation is still caught and the directed tests lack the weakness (TODO §71 wave 8; fast-actions QA F4)~~ — **closed 2026-11-26 by `server-ordering-r1` (Round 1):** `ahead::take_ahead_applied` records exact `applied_changes` and the oracle asserts `applied >= required` and `e == reference_at[applied]`. | fast-actions (QA) | ~~lucisv_server (tests)~~ done | -| 63 | **Whether a large open buffer is in the index depends on when it was opened, saved or scanned** — a fast-path buffer contributes nothing when open at scan or save time but keeps its disk record when opened after the scan; 77–98 answers differ between a settled session and a fresh server on OpenTitan. Predates fast-actions; wanted: always keep, or always drop, the disk record of a fast-path buffer at open, save, flip and scan alike (TODO §71 wave 8; fast-actions QA S2, Handshake request 8) | fast-actions (QA) | lucisv_server (`state/`, the index lane) | +| ~~63~~ | ~~**Whether a large open buffer is in the index depends on when it was opened, saved or scanned** — a fast-path buffer contributes nothing when open at scan or save time but keeps its disk record when opened after the scan; 77–98 answers differ between a settled session and a fresh server on OpenTitan. Predates fast-actions; wanted: always keep, or always drop, the disk record of a fast-path buffer at open, save, flip and scan alike (TODO §71 wave 8; fast-actions QA S2, Handshake request 8)~~ — **closed 2026-11-26 by `index-lifecycle-r2` (Round 2, owner decision 2):** standardized on always keeping the disk index record (subject to `maxFileSize`) across open, close, save, widen, scan, and threshold flips. | fast-actions (QA) | ~~lucisv_server (`state/`, `server/large_file.rs`)~~ done | | 64 | **The 40 000-file rescan after a delete takes either 12.3 s or 14.5–15.5 s**, on 0.65.10 and 0.65.11 alike; cause not found (TODO §71 wave 8) | fast-actions | undiagnosed (lucisv_server scan) | | 65 | **`ci.yml` runs `cargo test --workspace` bare in both jobs**, not through `tools/guard.sh` as CLAUDE.md's runaway guard asks of every `cargo test`; predates 0.65.9 for the macOS job, the Linux runner is resource-capped. Recorded, not judged (topo refresh 2026-11-19) | topo refresh (draft discrepancy 10) | CI (lead) | | 66 | **The `cross` gate step reports `SKIPPED (no toolchain)` rather than failing** when `~/.rustup/toolchains/stable-aarch64-apple-darwin` is absent, so a green `gates.sh` on another machine does not prove the cross build (topo refresh 2026-11-19) | topo refresh (draft discrepancy 11) | tools/ (`gates.sh`, lead) |