diff --git a/TODO.md b/TODO.md index 9a8abe1..1d2a84d 100644 --- a/TODO.md +++ b/TODO.md @@ -661,6 +661,15 @@ section only tracks the milestones. cross-file, whole-edit-or-nothing verified by re-parse. - [x] **M3 `refactor-ports`** — add/remove/propagate module ports across the declaration and every instantiation (named/ordered/`.*`). + **Amended 2026-08-28** (`docs/features/refactor-ports/README.md`): a + `textDocument/codeAction` no longer reads the in-scope file set from + disk per cursor move. The engine is handed the cursor's module's own + fan-out through the index — definers, instantiation edges, reference + postings, open buffers — by one builder both the code action and the + three commands use, and the answer is asserted equal to the + whole-workspace one. Over opentitan a code action went 4.56 s → 7.1 ms + (2.93 s → 83 ms for a module instantiated in 36 files); it was the + request every queued definition and hover had been waiting behind. - [x] **M4 `refactor-instantiate`** — module hinting: instantiation skeleton completion from the definition, auto-connect, signature help. - [x] **M5 `completion-core`** — keyword + project-wide identifier @@ -1119,3 +1128,55 @@ Notebook sync, moniker (LSIF), inline value (debugger), document color, goto implementation, goto declaration (Verilog has no declaration/definition split lucisv models). Recorded here so the audit doesn't repeat. + +## 10. Performance wave (2026-08-28) — performance.md findings + +Source: `performance.md` (benchmark of every LSP action against +opentitan, 3 976 files). Tracking for the two-worktree parallel round; +each lane's dev ticks only its own lines. Lane file ownership is the +merge contract — a lane touches no file outside its list. + +### Done before the wave (trunk) + +- [x] `textDocument/codeAction` 3.1–4.6 s per cursor move → + 7.1 ms (83 ms at a 36-file fan-out): `Workspace::module_sources` + subset instead of `ws.sources()` — refactor-ports README, + 2026-08-28 work log + Review. + +### Lane A — rename family (worktree A; files: crates/vlog_refactor/*, +crates/lucisv_server/src/{rename.rs,file_ops.rs,state.rs,perf.rs}, +docs/features/{refactor-rename,file-operations}/README.md, +docs/perf/README.md) + +- [ ] `prepareRename` 2.5–3.0 s (F2 blocks everything) → buffer+index + answer, < 1 ms; refusal-by-refusal parity table in the README. +- [ ] `rename` 3.6–8.7 s → reference-postings fan-out subset with a + written sufficiency argument; verifier integrity proven. +- [ ] `willRenameFiles` same `ws.sources()` shape (file_ops.rs:120) → + include-graph/index-bounded subset. + +### Lane B — hot path + UX (worktree B; files: +crates/lucisv_server/src/{completion.rs,candidates.rs,nav.rs, +settings.rs,perf.rs}, crates/lucisv_server/tests/e2e.rs, +editors/vscode/package.json, docs/features/{completion-core, +references-nav,index-scope}/README.md, docs/perf/README.md) + +- [ ] `completion` 34–66 ms per keystroke (worst at 0–4 chars) → + profile, then < 5 ms with item-identical answers pinned. +- [ ] `documentHighlight` answered 0 results at every opentitan + position while references answered — root-cause and fix (or + prove the benchmark request wrong and correct performance.md). +- [ ] Default `lucisv.index.scopeDepth` 0 → 2 (folder scope indexed + exactly one file in opentitan's dv/tb layout; every cross-file + answer empty until a jump widens) — behavior change, CHANGELOG + callout at release. + +### Deferred, filed + +- [ ] codeAction lazy resolution (`codeAction/resolve`): make the offer + index-only (~0 ms regardless of fan-out), edits computed on + lightbulb click — kills the 83 ms worst case. Owner-approved + direction, after the wave. +- [ ] Rename over an index-stale workspace: Lane A must state the + staleness premise; if the verifier cannot catch a hidden + reference, the honesty gate is the lead's review call. diff --git a/crates/lucisv_server/src/perf.rs b/crates/lucisv_server/src/perf.rs index 944c37a..4a8ac72 100644 --- a/crates/lucisv_server/src/perf.rs +++ b/crates/lucisv_server/src/perf.rs @@ -577,3 +577,83 @@ fn what_a_jump_into_a_new_folder_costs_before_and_after() { } let _ = std::fs::remove_dir_all(&dir); } + +/// `cargo test --release -p lucisv_server perf::a_code_action -- --ignored --nocapture --test-threads=1` +#[test] +#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"] +fn a_code_action_at_an_instantiation_before_and_after() { + // The owner's instrumented session, on a workspace this repository + // generates for itself: `textDocument/codeAction` answered in 3.1 s + // against 0.01–0.44 ms for every other request. VS Code sends one on + // nearly every cursor move, the server is single-threaded, so a cursor + // resting on an instantiation — where F12 leaves it — held up every + // definition and hover behind it. + // + // Three numbers over the same workspace and the same cursor: + // + // * **before** — the whole-workspace answer: `sources()` plus the engine + // over every file, which is what the handler did until 2026-08-28; + // * **after** — the same answer from the module's own fan-out; + // * **`sources()` alone** — the workspace read on its own, which is the + // floor the before column cannot go under, and the cost `rename` and + // `prepare_rename` still pay (the follow-up recorded in + // `docs/features/refactor-ports/README.md`). + let (files, lines) = (500, 200); + let dir = std::env::temp_dir().join(format!("lucisv_perf_action_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let sub = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n"; + std::fs::write(dir.join("sub.sv"), sub).expect("write"); + // Three files instantiate `sub`; the rest have nothing to do with it. + for n in 0..3 { + std::fs::write( + dir.join(format!("top{n}.sv")), + format!("module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"), + ) + .expect("write"); + } + for n in 0..files { + std::fs::write( + dir.join(format!("f{n:04}.sv")), + generated_module(&format!("f{n:04}"), lines), + ) + .expect("write"); + } + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let path = dir.join("sub.sv"); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), sub.to_string()); + let offset = sub.find("input logic rst").expect("a port") as u32 + 12; + + let before = mean(3, || { + let sources = ws.sources(); + black_box(vlog_refactor::port_actions(&sources, black_box(&path), black_box(offset))); + }); + let after = mean(20, || { + black_box(crate::ports::code_actions(&ws, &uri, black_box(offset))); + }); + let read = mean(3, || { + black_box(ws.sources()); + }); + // What `textDocument/prepareRename` still costs on the same workspace — + // the number the follow-up in the feature README is filed with. Left + // alone deliberately: a rename must see every file that could name the + // symbol, and the postings-based subset for it is its own design + // discussion. + let prepare = mean(3, || { + let sources = ws.sources(); + let _ = + black_box(vlog_refactor::prepare_rename(&sources, black_box(&path), black_box(offset))); + }); + // A measurement of an answer that was not given is worthless. + assert_eq!(crate::ports::code_actions(&ws, &uri, offset).len(), 1); + eprintln!( + "codeAction on a port of a module instantiated in 3 of {} files ({lines} lines each): \ + whole workspace {before:?}, fan-out {after:?} \ + (`sources()` alone: {read:?}; prepareRename, untouched: {prepare:?})", + ws.index().files().len() + ); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/lucisv_server/src/ports.rs b/crates/lucisv_server/src/ports.rs index d7143c5..b75e7d9 100644 --- a/crates/lucisv_server/src/ports.rs +++ b/crates/lucisv_server/src/ports.rs @@ -17,7 +17,7 @@ #![allow(clippy::mutable_key_type)] use std::collections::HashMap; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use lsp_types::{ CodeAction, CodeActionKind, CodeActionOrCommand, Position, TextEdit, Uri, WorkspaceEdit, @@ -51,14 +51,17 @@ pub fn commands() -> Vec { pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; let Some(path) = doc.path.clone() else { return Vec::new() }; - // A code-action request arrives on every cursor move, and `sources()` - // reads the whole in-scope file set from disk. The engine's one-file - // question answers "there is nothing here" for almost every position - // without any of that. - if !vlog_refactor::may_have_port_action(&doc.text, offset) { + // 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 + // find something, it says which module, so the files handed to the engine + // are that module's own fan-out rather than every file in scope + // (`Workspace::module_sources`). + let modules = vlog_refactor::port_action_modules(&doc.text, offset); + if modules.is_empty() { return Vec::new(); } - let sources = ws.sources(); + let sources = ws.module_sources(&path, &modules); vlog_refactor::port_actions(&sources, &path, offset) .into_iter() .filter_map(|action| { @@ -84,7 +87,6 @@ pub fn execute( command: &str, arguments: &[Value], ) -> Result<(WorkspaceEdit, Vec), String> { - let sources = ws.sources(); let refactoring = match command { ADD_PORT => { let (_, path) = target(ws, arguments.first())?; @@ -93,10 +95,12 @@ pub fn execute( })?; match module_argument(arguments.get(1)) { ModuleArgument::Name(name) => { + let sources = ws.module_sources(&path, std::slice::from_ref(&name)); vlog_refactor::add_port(&sources, ModuleRef::Name(&name), decl)? } ModuleArgument::Position(position) => { let offset = offset_of(ws, arguments.first(), position)?; + let sources = sources_at(ws, &path, offset); vlog_refactor::add_port(&sources, ModuleRef::At { file: &path, offset }, decl)? } ModuleArgument::Missing => { @@ -109,11 +113,13 @@ pub fn execute( REMOVE_PORT => { let (_, path) = target(ws, arguments.first())?; let offset = position_argument(ws, arguments, REMOVE_PORT)?; + let sources = sources_at(ws, &path, offset); vlog_refactor::remove_port(&sources, &path, offset)? } PROPAGATE_PORTS => { let (_, path) = target(ws, arguments.first())?; let offset = position_argument(ws, arguments, PROPAGATE_PORTS)?; + let sources = sources_at(ws, &path, offset); vlog_refactor::propagate_ports(&sources, &path, offset)? } other => return Err(format!("`{other}` is not a lucisv command.")), @@ -121,6 +127,22 @@ pub fn execute( Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings)) } +/// The files a port refactoring **at a position** reads: the fan-out of every +/// module that position could name. +/// +/// A command's position is looser than a code action's — `lucisv.addPort` +/// takes one anywhere in the module it adds to — so the module the cursor sits +/// *inside* is asked for as well as the ones its port element or its +/// instantiation names. Both questions are the engine's own +/// (`vlog_refactor`), so the set cannot drift from what the engine will then +/// go looking for. +fn sources_at(ws: &Workspace, path: &Path, offset: u32) -> Vec<(PathBuf, String)> { + let Some(text) = ws.text_of(path) else { return ws.module_sources(path, &[]) }; + let mut modules = vlog_refactor::port_action_modules(&text, offset); + modules.extend(vlog_refactor::enclosing_module(&text, offset)); + ws.module_sources(path, &modules) +} + /// What the second argument of `lucisv.addPort` said. enum ModuleArgument { Name(String), @@ -357,6 +379,429 @@ mod tests { assert_eq!(edits_for(edit, &top_uri).len(), 2, "the connection and its comma"); } + // ------------------------------------------------------------------ + // the answer is the whole workspace's answer, computed over a subset + // ------------------------------------------------------------------ + + /// One action's title and the edits it carries, per file in path order. + type Shape = (String, Vec<(String, Vec)>); + + /// A code action as a comparable value: its title and every edit it + /// carries, per file in path order — the whole of what a client receives. + /// `WorkspaceEdit.changes` is a `HashMap`, so it is sorted here rather + /// than compared as it is stored. + fn shape(actions: &[CodeActionOrCommand]) -> Vec { + actions + .iter() + .map(|action| { + let CodeActionOrCommand::CodeAction(action) = action else { + return ("a command".to_string(), Vec::new()); + }; + let mut changes: Vec<(String, Vec)> = action + .edit + .as_ref() + .and_then(|edit| edit.changes.as_ref()) + .map(|changes| { + changes + .iter() + .map(|(uri, edits)| { + let edits = edits + .iter() + .map(|edit| format!("{:?}{}", edit.range, edit.new_text)) + .collect(); + (uri.as_str().to_string(), edits) + }) + .collect() + }) + .unwrap_or_default(); + changes.sort(); + (action.title.clone(), changes) + }) + .collect() + } + + /// What `code_actions` used to compute: the same engine call over every + /// in-scope file. The equivalence tests below assert the new answer + /// against this one rather than against a transcription of it. + fn whole_workspace_at(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { + let doc = ws.document(uri).expect("an open document"); + let path = doc.path.clone().expect("a saved file"); + let sources = ws.sources(); + vlog_refactor::port_actions(&sources, &path, offset) + .into_iter() + .filter_map(|action| { + let edit = workspace_edit(ws, &action.edit).ok()?; + Some(CodeActionOrCommand::CodeAction(CodeAction { + title: action.title, + kind: Some(CodeActionKind::new(REFACTOR_PORTS)), + edit: Some(edit), + ..Default::default() + })) + }) + .collect() + } + + /// A workspace of `noise` files that have nothing to do with `sub`, plus + /// `sub.sv` and three files that instantiate it. + fn crowded(tree: &Tree, noise: usize) -> Workspace { + tree.write("sub.sv", SUB); + for n in 0..3 { + tree.write( + &format!("top{n}.sv"), + &format!( + "module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n" + ), + ); + } + for n in 0..noise { + tree.write( + &format!("noise{n}.sv"), + &format!("module noise{n};\n logic a;\n wire b;\n assign b = a;\nendmodule\n"), + ); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + ws + } + + #[test] + fn a_code_action_answers_what_the_whole_workspace_would() { + let tree = Tree::new("equivalence"); + let mut ws = crowded(&tree, 40); + let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + let subset = code_actions(&ws, &sub_uri, offset); + assert_eq!(subset.len(), 1, "{subset:#?}"); + let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") }; + assert_eq!(action.title, "lucisv: remove port `rst` (updates 3 instantiations)"); + assert_eq!( + shape(&subset), + shape(&whole_workspace_at(&ws, &sub_uri, offset)), + "the subset must answer exactly what every file would have" + ); + } + + #[test] + fn the_files_a_code_action_reads_are_the_modules_own_fan_out() { + let tree = Tree::new("fanout"); + let mut ws = crowded(&tree, 40); + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + + assert_eq!(ws.sources().len(), 44, "the whole workspace"); + let read = ws.module_sources(&sub, &["sub".to_string()]); + let mut names: Vec = read + .iter() + .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) + .collect(); + names.sort(); + assert_eq!(names, ["sub.sv", "top0.sv", "top1.sv", "top2.sv"], "and not one noise file"); + } + + #[test] + fn an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen() { + let tree = Tree::new("unsaved"); + let mut ws = crowded(&tree, 20); + // A file the index knows as instantiating nothing, whose buffer now + // instantiates `sub`. No save, so no edge in the index. + let extra = tree.path.join("noise0.sv"); + let extra_uri = path_to_uri(&extra).expect("uri"); + let typed = "module noise0;\n logic c, r;\n sub u_new (.clk(c), .rst(r));\nendmodule\n"; + ws.set_document(extra_uri.clone(), typed.to_string()); + assert!( + ws.index() + .instantiations_of("sub") + .iter() + .all(|edge| ws.index().path(edge.file) != Some(extra.as_path())), + "the index has not seen the unsaved instantiation" + ); + + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + let subset = code_actions(&ws, &sub_uri, offset); + let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") }; + assert_eq!(action.title, "lucisv: remove port `rst` (updates 4 instantiations)"); + let edit = action.edit.as_ref().expect("an edit"); + assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too"); + assert_eq!(shape(&subset), shape(&whole_workspace_at(&ws, &sub_uri, offset))); + } + + #[test] + fn a_module_declared_twice_is_refused_through_the_subset_as_well() { + let tree = Tree::new("ambiguous"); + let mut ws = crowded(&tree, 10); + // A second declaration of `sub`, in a file nothing else names. + tree.write("clone.sv", SUB); + ws.rebuild_index(); + assert_eq!(ws.index().units("sub").len(), 2, "two declarations"); + + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + // Both definers are in the set, so the engine sees the ambiguity and + // refuses — which is no action, exactly as over the whole workspace. + assert!(ws + .module_sources(&sub, &["sub".to_string()]) + .iter() + .any(|(path, _)| path.ends_with("clone.sv"))); + assert!(code_actions(&ws, &sub_uri, offset).is_empty()); + assert!(whole_workspace_at(&ws, &sub_uri, offset).is_empty()); + } + + #[test] + fn a_command_computes_over_the_subset_and_answers_the_same() { + let tree = Tree::new("command"); + let mut ws = crowded(&tree, 40); + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + + let arguments = vec![ + serde_json::to_value(&sub_uri).expect("uri"), + Value::String("sub".into()), + Value::String("input logic cfg".into()), + ]; + let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds"); + let whole = + vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg") + .expect("adds"); + assert_eq!(warnings, whole.warnings); + assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit")); + assert_eq!(edit.changes.as_ref().expect("changes").len(), 4, "sub.sv and its three tops"); + } + + #[test] + fn qa_file_scope_instantiation_lands_in_the_subset() { + let tree = Tree::new("qa_filescope"); + let mut ws = crowded(&tree, 20); + // A file-scope (owner-less) instantiation of `sub` — illegal SV, but + // a tolerant parse still produces an Instantiation item, and the old + // whole-workspace engine would still edit it (collect_instantiations + // walks tree.items directly). It records no InstantiationEdge (edges_of + // requires an owner), so only the references_to half of rung 3 can + // possibly find it. + let filescope_path = tree.write("filescope.sv", "sub u_fs (.clk(c), .rst(r));\n"); + ws.rebuild_index(); + assert!( + ws.index() + .instantiations_of("sub") + .iter() + .all(|edge| ws.index().path(edge.file) != Some(filescope_path.as_path())), + "file-scope site records no edge, as documented" + ); + + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + + let read = ws.module_sources(&sub, &["sub".to_string()]); + let names: Vec = read + .iter() + .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) + .collect(); + assert!( + names.contains(&"filescope.sv".to_string()), + "file-scope instantiation site must be in the subset: {names:?}" + ); + + // And the whole-workspace engine really would have edited it, so + // omitting it from the subset would be a real divergence. + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + let whole = whole_workspace_at(&ws, &sub_uri, offset); + let CodeActionOrCommand::CodeAction(action) = &whole[0] else { panic!("an action") }; + let edit = action.edit.as_ref().expect("an edit"); + let fs_uri = path_to_uri(&filescope_path).expect("uri"); + assert_eq!( + edits_for(edit, &fs_uri).len(), + 2, + "the whole-workspace answer edits the file-scope site" + ); + + let subset = code_actions(&ws, &sub_uri, offset); + assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly"); + } + + #[test] + fn qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption() { + // The subset builder trusts the index for rungs 2/3, so a file that + // changed on disk with nothing telling the server (no rebuild_index, + // no didChange) is invisible to it — unlike the old `sources()` path, + // which re-reads the directory fresh every call. Attack: write a + // *second* definer of `sub` straight to disk, do NOT reindex, and + // fire a code action. Judged against invariant 1 (never corrupt), not + // against freshness: an answer that goes stale (or a refusal) is + // fine; an edit that is not internally verified would not be. + let tree = Tree::new("qa_stale_dup"); + let mut ws = crowded(&tree, 10); + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + // Sanity: before the duplicate exists anywhere, the subset offers the + // action normally. + assert_eq!(code_actions(&ws, &sub_uri, offset).len(), 1); + + // Write a duplicate declaration straight to disk, bypassing the + // server entirely (no rebuild_index, no set_document for this path). + tree.write("dupe.sv", SUB); + + // The index still knows only one definer, so the subset the server + // computes is unaware of the ambiguity and still offers the action. + assert_eq!(ws.index().units("sub").len(), 1, "the index has not been told"); + let subset = code_actions(&ws, &sub_uri, offset); + assert_eq!(subset.len(), 1, "stale, but not refused — the index has not seen dupe.sv"); + + // The critical assertion: whatever it produced must still be an + // honest, self-consistent, verified edit over the files it actually + // read — not corruption of a file it never looked at. `dupe.sv` + // itself must be untouched (never read, never in the edit) and the + // edit that *was* produced must still verify against what changed. + let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") }; + let dupe_uri = path_to_uri(&tree.path.join("dupe.sv")).expect("uri"); + let edit = action.edit.as_ref().expect("an edit"); + assert!( + edit.changes.as_ref().is_none_or(|c| !c.contains_key(&dupe_uri)), + "the unindexed duplicate must not be touched: {edit:?}" + ); + + // Once the index is told (rebuild_index, exactly what the watcher + // does on a save it's told about), parity is restored: the subset + // now sees the duplicate and refuses, exactly like the whole + // workspace always would have. + ws.rebuild_index(); + assert_eq!(ws.index().units("sub").len(), 2, "now indexed"); + assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "refuses once told"); + } + + #[test] + fn qa_generate_block_instantiation_lands_in_the_subset() { + let tree = Tree::new("qa_generate"); + let mut ws = crowded(&tree, 20); + let gen_path = tree.write( + "gen.sv", + "module gen;\n genvar i;\n generate\n for (i = 0; i < 2; i = i + 1) begin : g\n logic c, r;\n sub u_g (.clk(c), .rst(r));\n end\n endgenerate\nendmodule\n", + ); + ws.rebuild_index(); + assert!( + ws.index() + .instantiations_of("sub") + .iter() + .any(|edge| ws.index().path(edge.file) == Some(gen_path.as_path())), + "the generate-for body instantiation is a real edge" + ); + + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let read = ws.module_sources(&sub, &["sub".to_string()]); + let names: Vec = read + .iter() + .map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string()) + .collect(); + assert!(names.contains(&"gen.sv".to_string()), "{names:?}"); + + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + let subset = code_actions(&ws, &sub_uri, offset); + let whole = whole_workspace_at(&ws, &sub_uri, offset); + assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly"); + } + + #[test] + fn qa_escaped_module_name_instantiation_parity_with_whole_workspace() { + // Not a subset-specific question: does an escaped-identifier + // instantiation (`\sub$weird u1 (...)`) even resolve to the module it + // names, workspace-index-wise, so the subset builder's `units`/ + // `instantiations_of`/`references_to` lookups have anything to find? + // Attacking whether the *subset* diverges from the *whole-workspace* + // answer here, not whether escaped identifiers work at all (a + // pre-existing question this round did not touch). + let tree = Tree::new("qa_escaped"); + tree.write("esc.sv", "module esc;\n \\sub u_esc (.clk(c), .rst(r));\nendmodule\n"); + let mut ws = crowded(&tree, 10); + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + let offset = SUB.find("input logic rst").expect("rst") as u32 + 12; + + let subset = code_actions(&ws, &sub_uri, offset); + let whole = whole_workspace_at(&ws, &sub_uri, offset); + // Whichever way the parser/binder treats the escaped identifier + // `\sub ` (as `sub`, or as a distinct name), the subset and the + // whole-workspace computation must agree either way. + assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly"); + } + + #[test] + fn qa_add_port_by_position_still_fans_out_to_instantiation_files() { + // `a_command_computes_over_the_subset_and_answers_the_same` (the + // dev's own equivalence test) drives `lucisv.addPort` with a + // *module-name* argument. The *Position* argument takes a completely + // different path to the module (`sources_at` → `port_action_modules` + // + `enclosing_module`, rather than `module_sources` fed the name + // directly) and is exactly the code action's own code path + // (`ModuleArgument::Position` mirrors `ModuleRef::At`). Confirm it + // still reaches every instantiating file, not just the declaring one. + let tree = Tree::new("qa_add_by_position"); + let mut ws = crowded(&tree, 30); + let sub = tree.path.join("sub.sv"); + let sub_uri = path_to_uri(&sub).expect("uri"); + ws.set_document(sub_uri.clone(), SUB.to_string()); + + let arguments = vec![ + serde_json::to_value(&sub_uri).expect("uri"), + serde_json::to_value(Position { line: 0, character: 8 }).expect("position"), + Value::String("input logic cfg".into()), + ]; + let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds"); + assert_eq!(warnings.len(), 3, "one TODO warning per instantiating top: {warnings:?}"); + let changes = edit.changes.as_ref().expect("changes"); + assert_eq!(changes.len(), 4, "sub.sv and its three instantiating tops: {changes:?}"); + for n in 0..3 { + let top_uri = path_to_uri(&tree.path.join(format!("top{n}.sv"))).expect("uri"); + assert_eq!(edits_for(&edit, &top_uri).len(), 1, "top{n}.sv must gain the connection"); + } + + let whole = + vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg") + .expect("adds"); + assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit")); + } + + #[test] + fn qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled() { + // A module the index has never seen at all — not stale, genuinely + // absent, e.g. a brand-new buffer the user has not saved yet. Rung 2 + // (`index.units`) has nothing; only rung 1 (the request's own file) + // can supply it. The cursor sits in that same new buffer, so rung 1 + // must be enough on its own — and it must not panic or silently + // return no action just because the index is empty for this name. + let tree = Tree::new("qa_unsaved_new_module"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + assert!(ws.index().units("brandnew").is_empty(), "the index has never heard of it"); + + let text = "module brandnew (\n input logic a,\n input logic b\n);\nendmodule\n"; + let new_path = tree.path.join("brandnew.sv"); // never written to disk + let new_uri = path_to_uri(&new_path).expect("uri"); + ws.set_document(new_uri.clone(), text.to_string()); + + let offset = text.find("input logic b").expect("b") as u32 + 12; + let subset = code_actions(&ws, &new_uri, offset); + assert_eq!(subset.len(), 1, "{subset:#?}"); + let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") }; + assert_eq!(action.title, "lucisv: remove port `b` (no instantiation in scope)"); + assert_eq!(edits_for(action.edit.as_ref().expect("edit"), &new_uri).len(), 2); + } + #[test] fn an_unknown_command_is_declined() { let tree = Tree::new("unknown"); diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index b8cf665..3e34bb1 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -4,7 +4,7 @@ //! analysis is rebuilt on every change and the index only on save. use std::cell::RefCell; -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeSet, HashMap, HashSet}; use std::fs; use std::path::{Path, PathBuf}; use std::rc::Rc; @@ -1406,6 +1406,57 @@ impl Workspace { self.collect_sources(&mut |_| {}, HeldAnalyses::Unused).texts } + /// The in-scope files a port refactoring on `modules`, requested in `file`, + /// can read or write — [`Workspace::sources`] narrowed to the fan-out the + /// index already holds. + /// + /// A `textDocument/codeAction` arrives on every cursor move and + /// `sources()` reads the whole file set from disk, so a cursor resting on + /// an instantiation used to cost one workspace read per keystroke (3.1 s + /// on OpenTitan, and every queued request waited behind it). The index + /// knows who declares a module and who instantiates it, so the engine can + /// be handed those files and nothing else. Why the smaller set gives the + /// same answer is argued in `docs/features/refactor-ports/README.md`; the + /// four rungs are: + /// + /// * **the file the request names**, whatever else it is; + /// * **every file declaring one of `modules`** ([`WorkspaceIndex::units`]) + /// — all of them, so a name declared twice still refuses instead of + /// quietly picking the one definer that made it into the set; + /// * **every file that instantiates one** ([`WorkspaceIndex::instantiations_of`]) + /// or otherwise refers to one ([`WorkspaceIndex::references_to`]) — + /// between them, every file the plan can edit and every file whose + /// meaning the verifier could see move; + /// * **every open buffer**, because its unsaved text may add or remove an + /// instantiation the saved edges do not know about. + /// + /// Each file's text comes from the same place `collect_sources` takes it: + /// the open buffer when there is one, disk otherwise, and neither for a + /// buffer on the large-file fast path or a file over the size cap. + pub fn module_sources(&self, file: &Path, modules: &[String]) -> Vec<(PathBuf, String)> { + let mut wanted: BTreeSet = BTreeSet::new(); + wanted.insert(file.to_path_buf()); + for name in modules { + for def in self.index.units(name) { + wanted.extend(self.index.path(def.file).map(Path::to_path_buf)); + for site in self.index.references_to(def) { + wanted.extend(self.index.path(site.file).map(Path::to_path_buf)); + } + } + for edge in self.index.instantiations_of(name) { + wanted.extend(self.index.path(edge.file).map(Path::to_path_buf)); + } + } + wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone())); + wanted + .into_iter() + .filter_map(|path| { + let text = self.current_text(&path)?; + Some((path, text)) + }) + .collect() + } + /// Read every in-scope file, with open buffers overriding disk. /// /// This is where `lucisv.index.maxFileSize` applies, and it applies to the diff --git a/crates/vlog_refactor/src/lib.rs b/crates/vlog_refactor/src/lib.rs index 7a90587..6e26f76 100644 --- a/crates/vlog_refactor/src/lib.rs +++ b/crates/vlog_refactor/src/lib.rs @@ -40,8 +40,8 @@ pub use instantiate::{ PlanPort, Site, }; pub use ports::{ - add_port, may_have_port_action, port_actions, propagate_ports, remove_port, ModuleRef, - PortAction, + add_port, enclosing_module, may_have_port_action, port_action_modules, port_actions, + propagate_ports, remove_port, ModuleRef, PortAction, }; pub use rename::{prepare_rename, rename, RenameTarget}; diff --git a/crates/vlog_refactor/src/ports.rs b/crates/vlog_refactor/src/ports.rs index 1721afc..511cb66 100644 --- a/crates/vlog_refactor/src/ports.rs +++ b/crates/vlog_refactor/src/ports.rs @@ -155,29 +155,70 @@ pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Ve /// microseconds. It never says `false` where a refactoring would have /// succeeded: every one of the three starts by locating exactly one of these /// three constructs. +/// +/// Exactly [`port_action_modules`] asked for emptiness — one walk, two +/// readers, so the gate and the fan-out cannot come to disagree about which +/// positions carry an action. pub fn may_have_port_action(text: &str, offset: u32) -> bool { + !port_action_modules(text, offset).is_empty() +} + +/// Every module name a port refactoring at this position could act on: the +/// module an instantiation under the cursor names, or the module whose port +/// the cursor sits on. +/// +/// [`may_have_port_action`]'s own walk, saying *which* module it found rather +/// than only that it found one — which is what lets a server hand +/// [`port_actions`] the handful of files that module fans out to instead of +/// the whole workspace. Empty for exactly the positions the gate refuses. +pub fn port_action_modules(text: &str, offset: u32) -> Vec { let (tree, _) = parse_source_tolerant(text); let mut instantiations = Vec::new(); collect_instantiations(&tree.items, &mut instantiations); - let at_instantiation = instantiations.iter().any(|instantiation| { - instantiation.module_span.contains(offset) - || instantiation.instances.iter().any(|instance| instance.span.contains(offset)) - }); - if at_instantiation { - return true; + let named: Vec = instantiations + .iter() + .filter(|instantiation| { + instantiation.module_span.contains(offset) + || instantiation.instances.iter().any(|instance| instance.span.contains(offset)) + }) + .map(|instantiation| instantiation.module.clone()) + .collect(); + if !named.is_empty() { + return named; } let mut module = None; module_at(&tree.items, offset, &mut module); - let Some((module, _)) = module.and_then(|name| find_module(&tree, &name)) else { - return false; + let Some((name, (module, _))) = + module.and_then(|name| Some((name.clone(), find_module(&tree, &name)?))) + else { + return Vec::new(); }; if declared_ports(module).iter().any(|port| port.span.contains(offset)) { - return true; + return vec![name]; } - module.items.iter().any(|item| match &item.kind { + let on_body_declaration = module.items.iter().any(|item| match &item.kind { ItemKind::PortDecl(decl) => decl.declarators.iter().any(|d| d.span.contains(offset)), _ => false, - }) + }); + match on_body_declaration { + true => vec![name], + false => Vec::new(), + } +} + +/// The module whose declaration covers this offset — what +/// `ModuleRef::At { file, offset }` will resolve to. +/// +/// The fan-out question for the *command* path, which takes a position +/// anywhere in a module rather than on one of its ports: `lucisv.addPort` with +/// a `Position` names the module the cursor is inside, and a server working +/// out which files that refactoring needs has to name it the same way +/// `locate_module` will. +pub fn enclosing_module(text: &str, offset: u32) -> Option { + let (tree, _) = parse_source_tolerant(text); + let mut module = None; + module_at(&tree.items, offset, &mut module); + module } /// "updates 3 instantiations" / "updates 1 instantiation" / "no instantiation diff --git a/crates/vlog_refactor/tests/ports.rs b/crates/vlog_refactor/tests/ports.rs index 37ad32d..2a91c24 100644 --- a/crates/vlog_refactor/tests/ports.rs +++ b/crates/vlog_refactor/tests/ports.rs @@ -642,6 +642,41 @@ fn the_cheap_pre_check_says_yes_exactly_where_an_action_could_be_offered() { assert!(may_have_port_action(non_ansi, at(non_ansi, "input a") + 6), "a non-ANSI declaration"); } +#[test] +fn the_pre_check_names_the_module_whose_files_the_action_will_need() { + use vlog_refactor::{may_have_port_action, port_action_modules}; + let text = "module sub (\n input a,\n input b\n);\n wire c;\n assign c = a;\n other u1 (.x(c));\nendmodule\n"; + // On a port of `sub`, the module whose signature would change; on the + // instantiation, the module instantiated — never the one it is written in. + assert_eq!(port_action_modules(text, at(text, "input b") + 6), ["sub"]); + assert_eq!(port_action_modules(text, at(text, "u1")), ["other"]); + assert_eq!(port_action_modules(text, at(text, "other")), ["other"]); + assert!(port_action_modules(text, at(text, "assign")).is_empty()); + + let non_ansi = "module sub (a);\n input a;\nendmodule\n"; + assert_eq!(port_action_modules(non_ansi, at(non_ansi, "input a") + 6), ["sub"]); + + // The gate is this walk asked for emptiness, at every byte of the file. + for offset in 0..text.len() as u32 { + assert_eq!( + may_have_port_action(text, offset), + !port_action_modules(text, offset).is_empty(), + "at byte {offset}" + ); + } +} + +#[test] +fn the_enclosing_module_is_the_one_a_position_would_add_a_port_to() { + use vlog_refactor::enclosing_module; + let text = "module sub (input a);\n wire c;\nendmodule\n\nmodule top;\n sub u1 (.a(c));\nendmodule\n"; + // A position `lucisv.addPort` would take: inside the module, nowhere near + // a port element — which is exactly where `port_action_modules` is empty. + assert_eq!(enclosing_module(text, at(text, "wire c")).as_deref(), Some("sub")); + assert_eq!(enclosing_module(text, at(text, "sub u1")).as_deref(), Some("top")); + assert_eq!(enclosing_module(text, at(text, "\n\nmodule top") + 1), None, "between modules"); +} + // ---------------------------------------------------------------------- // what the preprocessor owns // ---------------------------------------------------------------------- diff --git a/docs/features/refactor-ports/README.md b/docs/features/refactor-ports/README.md index c7c85fa..4f47981 100644 --- a/docs/features/refactor-ports/README.md +++ b/docs/features/refactor-ports/README.md @@ -32,6 +32,9 @@ pub fn propagate_ports(files: &[(PathBuf, String)], file: &Path, offset: u32) pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Vec; pub fn may_have_port_action(text: &str, offset: u32) -> bool; +// added 2026-08-28, for the server's file-set question: +pub fn port_action_modules(text: &str, offset: u32) -> Vec; +pub fn enclosing_module(text: &str, offset: u32) -> Option; ``` `files`, `RefactorEdit`, `TextEdit` and the `Err(String)`-is-a-sentence @@ -339,14 +342,85 @@ neither is offered where the refactoring would be refused. They answer for the **start** of the requested range: a code action is about where the cursor is. A code-action request arrives on **every cursor move**, and computing an -answer means reading the whole in-scope file set and building an index — a -fifth of a second on a large workspace, on a single-threaded server. So the -engine exposes a cheap one-file question, `may_have_port_action(text, offset)`: -one parse of the buffer itself, no workspace and no I/O, answering "is this -position inside a port element, a non-ANSI port declaration, or an -instantiation?". The server asks it *before* materializing anything. It cannot -hide a refactoring: all three start by locating exactly one of those three -constructs. +answer used to mean reading the whole in-scope file set and building an index +— a fifth of a second on a large workspace, on a single-threaded server, and +2.9 s on OpenTitan's 3 976 files, with every queued definition and hover +waiting behind it. Two things keep that off the cursor path, and both are the +engine's own walk: + +- `may_have_port_action(text, offset)` — one parse of the buffer itself, no + workspace and no I/O, answering "is this position inside a port element, a + non-ANSI port declaration, or an instantiation?". The server asks it + *before* materializing anything. It cannot hide a refactoring: all three + refactorings start by locating exactly one of those three constructs. +- `port_action_modules(text, offset)` — the same walk saying *which* module it + found, so the server can hand the engine that module's own fan-out instead + of the workspace. `may_have_port_action` is this function asked for + emptiness (one walk, two readers), which is what keeps the gate and the + fan-out from ever disagreeing about which positions carry an action. + +### The file set a port action reads — why a subset is the same answer + +`Workspace::module_sources(file, modules)` (`lucisv_server/src/state.rs`) +builds the file set both `ports::code_actions` and `ports::execute` hand to the +engine. It is `sources()` narrowed to four rungs: + +1. **the file the request names** — the open buffer's text, as always; +2. **every file declaring one of `modules`** — `index.units(name)`; +3. **every file that instantiates one** — `index.instantiations_of(name)` — + **or otherwise refers to one** — `index.references_to(def)`; +4. **every open buffer**, whatever it contains. + +The answer is *equal* to the whole-workspace answer, and the argument is one +per way a file can influence the result: + +- **A file the plan can edit.** `plan_add`/`plan_remove` loop over the whole + scope, but `instantiation_edits`/`disconnection_edits` write nothing in a + file that does not textually contain the module name and parse an + instantiation of it under `collect_instantiations`. That census — module + bodies, packages, nested modules, generate regions (`if`/`for`/`case`), and + `bind` — is walk-for-walk the one `vlog_semantic::instantiations::sites` + performs to record the index's instantiation edges, so rung 3 names exactly + the files that could gain or lose a connection. `plan_propagate` edits the + cursor's file alone. **One gap**: `edges_of` drops a site with no owning + module — an instantiation written at *file scope*, illegal SystemVerilog a + tolerant parse still produces — and the engine would have edited it. Rung 3's + second half covers it: an instantiation's module name is a + `Target::Module` reference wherever it is written, so the file appears in + `references_to` even when it is nobody's edge. +- **A file that decides `locate_module`'s verdict.** Every one of them is in + rung 2, *all* of them, so a module declared twice still produces the "lucisv + will not guess which module's ports these are" refusal instead of quietly + picking the one definer that happened to be in the set. Rung 2 is the reason + the set is built from `units(name)` rather than from a single definition. +- **A file the verifier watches.** `check::watched_files` widens verification + to every file spelling the module name, edited or not, and compares each + one's declarations and resolutions before and after. For a file that is not + edited, "before" and "after" differ only if some *anchor* moved — and an + anchor is a local declaration (its own text, unchanged) or a def in the + rebuilt index (pre-shifted through the edits by `Shifts`, which is why an + insertion in the module's file does not read as a difference). An anchor + that could move is by construction a reference *into* the edited module or + its members — which is a `references_to` posting, rung 3. Every other file's + print is identical on both sides whether it is in the set or not, so + omitting it cannot turn a refusal into an offer. +- **A file the index has not seen.** An unsaved buffer's live text can add or + remove any of the above, and the edges are only as fresh as the last save — + so rung 4 takes every open buffer whole, exactly as `collect_sources` does. + +Everything else about the set is `collect_sources`'s rules unchanged: each +file's text is the open buffer's when there is one and disk otherwise, a +buffer on the large-file fast path contributes nothing, and a file over +`lucisv.index.maxFileSize` is not read. + +Pinned by four tests in `lucisv_server/src/ports.rs`, each asserting against +the whole-workspace computation rather than a transcription of it: +`a_code_action_answers_what_the_whole_workspace_would`, +`an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen`, +`a_module_declared_twice_is_refused_through_the_subset_as_well`, +`a_command_computes_over_the_subset_and_answers_the_same`, plus +`the_files_a_code_action_reads_are_the_modules_own_fan_out`, which asserts the +noise files really are absent (4 files read of 44). **Commands** (`workspace/executeCommand`, advertised in `executeCommandProvider`): @@ -390,7 +464,19 @@ engine's sentence verbatim, M2's precedent. - **A port refactoring is a rare, user-initiated request**, so re-parsing the in-scope files that mention the module (twice: once to plan, once to verify) is affordable. The substring prefilter M2 introduced keeps it to a handful of - files. Measured below. + files. Measured below. **Amended 2026-08-28**: a *code action* is not rare — + it arrives on every cursor move — so the files handed to the engine are the + module's fan-out rather than the workspace (above). +- **The index is the server's authority on where a module is declared and + instantiated.** The fan-out is read from it, so a port action sees the + workspace as far as the index describes it: a file changed on disk with + nothing telling this server, or a file a startup scan has not reached yet, + is a file the action does not read. That is the same rule every other + index-backed answer already lives by — definition, hover, references, the + code lens, the call hierarchy — and the file watcher is what keeps it true. + Before 2026-08-28 a port action re-read the whole scope from disk and was + the one answer in the server that could see further than the index; it no + longer is. - **Two spaces** are used for the one indentation lucisv has to invent (a body declaration in a module with no items at all). Every other insertion copies an indentation that is already in the file. @@ -436,6 +522,27 @@ engine's sentence verbatim, M2's precedent. - `warnings` are informational: an `Ok` with warnings is still safe to apply. - `PortAction.title` is user-facing text; the server does not rewrite it. +**Consumed from `vlog_semantic`, added 2026-08-28** (no change required): +`WorkspaceIndex::{instantiations_of, references_to}` — the incremental-index +edge and posting tables — are what make the file set a lookup instead of a +workspace read. The equality argument above leans on one property of theirs: +`edges_of` records the census `instantiations::sites` walks, which is the walk +`ports::collect_instantiations` performs. If either walk grows a node kind the +other does not, the fan-out stops being a superset of the editable files — +so **they must move together**. + +**Requested of `lucisv_server`'s rename surface (follow-up, not this round):** +`rename` and `prepare_rename` still call `ws.sources()` and run the engine +over every in-scope file. On the synthetic 504-file workspace the port probe +uses, `prepare_rename` costs **249 ms** (of which `sources()` alone is 14.5 +ms — the rest is the index build and the analyses over every file); +`textDocument/prepareRename` is sent when the user presses the rename key, not +per cursor move, so it does not block the way the code action did. The subset +for a rename is a *different* argument from this one — a rename must see every +file that could name the symbol, and the postings table +(`references_to`/`references_are_ambiguous`) is the candidate — so it is filed +here rather than guessed at now. + **Changed in `lucisv_server`** (protocol layer only): `code_action::wanted` is now `pub` so the port actions can honor the same `only` filter the lint actions do; `server.rs` gained the `workspace/executeCommand` arm and the port-action @@ -467,6 +574,11 @@ call inside the existing `textDocument/codeAction` arm; `main.rs` advertises - [x] `lucisv_server`: code actions, three commands, capabilities - [x] `may_have_port_action` — the one-file pre-check that keeps a cursor-move-frequency code-action request off the workspace walk +- [x] The file set a port action reads is the module's fan-out through the + index, not `sources()` (2026-08-28): `port_action_modules` / + `enclosing_module` in the engine, `Workspace::module_sources` in the + server, one builder for both callers, with the equality argument above + and five equivalence tests - [x] Conditional-compilation guard on both insertion paths: refuse inside an arm, warn when the list carries directives at all (QA HIGH #1) - [x] Preprocessor warnings on removal — macro-invocation arguments and @@ -652,6 +764,62 @@ still `Ok((6, 18))` in 0.36 s, so the guard false-refuses nothing in real RTL. One clippy-driven tidy while there: the header planner's arguments are now a `File { text, path, tokens }` struct rather than eight positional parameters. +**2026-08-28 — dev agent.** `textDocument/codeAction` no longer reads the +workspace per cursor move. The owner's instrumented session on OpenTitan +measured 3 111 ms and 3 015 ms for a code action against 0.01–0.44 ms for +every other request; VS Code sends one on nearly every cursor move and the +server is single-threaded, so a cursor resting on an instantiation — which is +exactly where F12 leaves it — held every queued definition and hover behind +it. That is the "goto definition is slow" report: the definition answered in +microseconds and stood in a three-second queue. + +What changed: + +- **`vlog_refactor::port_action_modules`** — `may_have_port_action`'s walk, + returning the module names it found instead of a bool, and + `may_have_port_action` is now that function asked for emptiness. One walk, + two readers, so the gate and the fan-out cannot drift; a byte-by-byte + equality test over a mixed file pins the two against each other. + **`vlog_refactor::enclosing_module`** is the same question for the command + path, where `lucisv.addPort` takes a position anywhere in a module — + `module_at` made public, which is precisely what `ModuleRef::At` resolves + with, so the server names the module the engine will name. +- **`Workspace::module_sources`** — the one file-set builder, used by + `ports::code_actions` and by all three commands through `ports::sources_at`. + Four rungs and the equality argument are written up under "The file set a + port action reads" above; the two decisions worth repeating here are that + **all** definers of the name go in (or an ambiguous module would stop + refusing) and that `references_to` goes in beside `instantiations_of` (or a + file-scope instantiation, which records no edge, would stop being edited). +- Both callers share the builder, so there is no second code path with a + second answer; `execute` computes the names per command shape rather than + materializing anything before it knows what it was asked. + +Measured, release: + +| | before | after | +|---|---|---| +| synthetic 504 files, cursor on a port instantiated in 3 of them | 725 ms | **0.41 ms** | +| OpenTitan (3 976 files), cursor on a port of `adc_ctrl_core`, action offered | 4.56 s | **7.1 ms** | +| OpenTitan, cursor on a `prim_fifo_sync` instantiation (36-file fan-out) | 2.93 s | **83 ms** | + +The last row is the honest ceiling: `prim_fifo_sync` is instantiated all over +OpenTitan, so its fan-out is 36 real files and the engine parses them twice +(plan, then verify) — 1.3 ms of that is reading them, the rest is the engine. +A module with a normal fan-out is the middle row. The synthetic probe is +`perf::a_code_action_at_an_instantiation_before_and_after`, which prints the +before column, the after column and `sources()` alone; the OpenTitan numbers +were taken with a throwaway probe against the local checkout and deleted, since +no test may depend on it. Both OpenTitan cursors were also checked for +*equality* against the whole-workspace computation — same titles, same edited +file counts — beside the five equivalence tests in the suite. + +Deliberately untouched: `rename`/`prepare_rename`'s `sources()` calls, filed as +a Handshake follow-up with its number (249 ms on the synthetic workspace). +Gates: `cargo fmt` clean, `cargo clippy --all-targets` clean, `cargo test` +green workspace-wide, `node editors/vscode/smoke.js` OK against the release +binary. + ## QA log **2026-08-24 — QA agent.** @@ -1179,8 +1347,87 @@ counts across all three QA passes are themselves evidence against scope creep. The one imprecision found (over-broad trailing-directive warning text) is cosmetic, safe-direction, and not blocking. +**2026-08-28 — QA agent.** Round on the codeAction-fan-out change: `Workspace::module_sources` replacing `ws.sources()` for `textDocument/codeAction` and the three port commands. Adversarial charter: find a file the whole-workspace computation would have edited (or that would change/refuse the answer) missing from the subset — refactoring correctness, invariant-1-adjacent. + +### Gates + +- `cargo fmt --all -- --check` — clean. +- `cargo clippy --all-targets` — clean, zero warnings, workspace-wide (one warning surfaced from a QA-added test — `map_or(true, …)` → `is_none_or(…)` — fixed directly, small and unambiguous). +- `cargo test --workspace` — green, **2482** passed, 0 failed, 0 measured (28 `#[ignore]`d perf probes not run) — includes the 6 permanent regression tests added this round (below). `lucisv_server`'s own unit suite: **1249** passed, 28 ignored. `vlog_refactor` unit: 72, `tests/ports.rs`: 52 (dev added 2: the byte-sweep pinning `may_have_port_action`/`port_action_modules` against each other, and `enclosing_module`'s own test). +- `node editors/vscode/smoke.js target/release/lucisv-server` — OK (had to pass the binary path explicitly; `lucisv-server` is not on `PATH` in this environment, not a project issue). +- Reproduced the synthetic perf claim exactly: `perf::a_code_action_at_an_instantiation_before_and_after` (`--release`) printed **724 ms → 409 µs**, `sources()` alone **14.4 ms**, `prepareRename` **250 ms** — matches the README's 725 ms / 0.41 ms / 14.5 ms / 249 ms table to the reported precision. +- Reproduced the OpenTitan claim's *shape* independently, with a throwaway probe (added to `perf.rs`, run, then reverted — not in the tree): cursor on a port of `adc_ctrl_core.sv` went **3.13 s → 3.17 ms**; cursor on a `prim_fifo_sync` instantiation (in `otp_ctrl.sv`, a different real fan-out site than the dev's) went **3.08 s → 84.6 ms** — both essentially the dev's numbers (4.56 s→7.1 ms; 2.93 s→83 ms) to within what a different instantiation site and a warm/cold FS cache would explain. Both probe cursors landed on offsets that produced 0 offered actions on *both* sides (an imprecise offset, not a bug), but the **parity held** (0 == 0) in both cases, which is the property that matters here. No test depends on the checkout, per the brief. + +### Attack angles from the brief, and what I found + +**1. Missing-file attacks — all held.** Wrote 4 new permanent regression tests attacking the exact scenarios the brief named, each asserting the subset's `code_actions`/`module_sources` answer against `whole_workspace_at` (the dev's own reference function) or `ws.sources()`: + +- `qa_file_scope_instantiation_lands_in_the_subset` (`crates/lucisv_server/src/ports.rs`) — an owner-less instantiation (`sub u_fs (.clk(c), .rst(r));` at file scope, no enclosing module) records **no** `InstantiationEdge` (confirmed directly: `edges_of` requires an owner), yet the file lands in `module_sources` and the subset's answer matches the whole-workspace one exactly. This is the dev's rung-3-second-half claim (`references_to` catching what `instantiations_of` structurally cannot) — verified empirically, not just by reading `resolve.rs`'s `named_at_file_scope`/`bind_instantiation` code path that makes it true. This was the brief's most specific, most load-bearing ask ("verify it actually lands in `references_to`") and it does. +- `qa_generate_block_instantiation_lands_in_the_subset` — an instantiation inside a `generate for` body is a real `InstantiationEdge` (confirmed) and its file is in the subset, subset == whole-workspace. +- `qa_escaped_module_name_instantiation_parity_with_whole_workspace` — an escaped-identifier instantiation (`` \sub u_esc (...) ``). Whatever the parser/binder does with the escape (resolve it to `sub` or treat it as a distinct name — did not chase which, since it is a pre-existing lexical question this round did not touch), the subset and whole-workspace answers agree. Framed as a parity check rather than a correctness check of escaping itself, since a bug there would be M1/M2-era and out of this round's scope. +- `qa_add_port_by_position_still_fans_out_to_instantiation_files` — the dev's own equivalence test (`a_command_computes_over_the_subset_and_answers_the_same`) only exercises `lucisv.addPort` with a **module-name** argument, which reaches `module_sources` directly. The **Position** argument goes through a different function (`sources_at`, used by all three commands and by nothing else previously tested at the command layer) — confirmed it still reaches all 3 instantiating files, matching `ws.sources()`'s answer byte-for-byte. +- Not separately tested as a new attack, but read and reasoned through carefully: `.*` connections, hierarchical-reference-only files, and macro-expanded module names. `.*` sites are structurally ordinary `Instantiation` nodes to `edges_of`/`collect_instantiations` (connection *style* plays no part in either census), so they get the same edge as a named-connection site — no special case to miss. A file whose only relationship to the module is a hierarchical reference to one of its ports (no instantiation) is not in scope for *either* the old or the new computation (neither `collect_instantiations` nor `edges_of` would ever find or edit it), so it cannot be a point of divergence. A macro-expanded module name is one opaque token to lucisv's non-preprocessing binder in both the old and new code paths equally (documented Assumption, unchanged) — not a regression this round could introduce. +- Did **not** separately verify a duplicate-module-name-under-macro or a nested-module-inside-a-package instantiation; ran out of budget. Low-risk: `collect_instantiations`/`edges_of` both explicitly walk `ItemKind::Package{items,..}` identically (confirmed by direct side-by-side read of both functions, `crates/vlog_semantic/src/instantiations.rs:68-105` vs `crates/vlog_refactor/src/ports.rs:489-518` — they are the same match arms in the same order, which is exactly the Handshake's "walk-for-walk" claim, verified by inspection rather than by a fresh test). + +**2. Refusal-parity attacks.** + +- Duplicate-definer-already-indexed: the dev's own `a_module_declared_twice_is_refused_through_the_subset_as_well` covers this (re-ran, passes). +- New module in an **unsaved buffer the index has never heard of at all** (not stale — genuinely absent): `qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled` — a module declared only in a brand-new, never-saved-to-disk buffer, with the cursor inside that same buffer. Rung 1 ("the file the request names") is what carries it, since rung 2 (`index.units`) is empty for a name the index has never indexed. Confirmed it still offers the action correctly (`lucisv: remove port \`b\` (no instantiation in scope)`), no panic, no silent no-op. +- **Index stale vs. disk — the one place I judged rather than just tested.** `qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption`: wrote a *second* definer of `sub` straight to the filesystem, bypassing the server (`fs::write`, no `rebuild_index`, no `set_document`). Confirmed: the subset computation, unaware of the new file, does **not** refuse — it offers the action as if the module were still uniquely declared, which is a real, observable divergence from `ws.sources()`'s always-fresh-from-disk answer (the old code path *would* have refused here). Judged against invariant 1, not against freshness, per the brief's own framing: this cannot corrupt anything, because the engine is handed exactly the files in the subset and has no I/O of its own — `dupe.sv` is never read and never appears in the produced edit (asserted directly). The worst case is a **stale-but-internally-consistent** answer (an edit that is fully verified against the files it actually saw), not a wrong-and-unverified one. This is exactly the trade-off the dev's own Assumptions section documents ("the index is the server's authority... a file changed on disk with nothing telling this server is a file the action does not read") and explicitly parallels every other index-backed LSP answer in the server (definition, hover, references). I agree with the dev's framing: this is a disclosed staleness trade-off, not a hidden safety gap, and does not violate "never corrupt code." Confirmed the parity is restored the moment the index is told (`rebuild_index()` → refuses, matching whole-workspace). + +**3. Gate ⟺ subset coherence — verified by direct code comparison, no divergence found.** `may_have_port_action` is now defined literally as `!port_action_modules(...).is_empty()` (`crates/vlog_refactor/src/ports.rs:159`), so the two cannot drift by construction; the only residual risk was a logic bug introduced while refactoring the original single-`bool` walk into a `Vec`-returning one. Diffed the two versions line-by-line: the only structural change is `.any(...)` → `.filter(...).map(...).collect()` over the same predicate, which is behavior-preserving (a multi-match, if the tolerant parser ever produced overlapping instantiation spans, would just widen the returned module list — still correctly non-empty, never a false negative). The dev's own new test (`the_pre_check_names_the_module_whose_files_the_action_will_need`, `crates/vlog_refactor/tests/ports.rs`) sweeps every byte offset of a mixed file and asserts `may_have_port_action(text, offset) == !port_action_modules(text, offset).is_empty()` — re-ran it, passes. No old-vs-new crafted-file attack found a gate-false position the old whole-workspace path would have offered an action for, because the "old path" *is* this same walk (`may_have_port_action` was never a separately-maintained function — it's the same code, just newly able to say which module). + +**4. Command parity — held**, including the position-argument case above (attack 1's `qa_add_port_by_position...` doubles as this). `REMOVE_PORT`/`PROPAGATE_PORTS` both go through `sources_at`, which unions `port_action_modules` (what the offset directly names — a port, or an instantiation's own module) with `enclosing_module` (the module the offset sits textually inside) — read `locate_module`'s `ModuleRef::At` (`ports.rs:379-413`) and `locate_port`/`plan_propagate`'s own module-name derivation to confirm `sources_at` always names a superset of what the engine will independently look up for each of the three commands; for `propagate_ports` specifically the extra `enclosing_module` name is unnecessary (the README says propagate only ever touches the cursor's own file) but harmless — it can only add files, never omit the one that matters. + +**5. Verifier integrity.** Read this one by construction rather than by attack: `check::watched_files` and the whole verifier only ever see the files handed to `Scope::build(files)` — the crate does no I/O of its own (Handshakes, unchanged this round). So "an edit corrupts a file outside the subset" is not reachable as a distinct failure mode in this design: the engine cannot write to, or even read, a file that was never in the set. The only failure mode a wrong subset can produce is the one attack angle 1 covers (a file that *should* have been edited is silently skipped) — which is why I put the budget there instead of trying to construct a doomed "verifier misses an out-of-subset corruption" scenario that the architecture rules out by construction. + +### Tests added (all permanent, all in `crates/lucisv_server/src/ports.rs`'s `mod tests`) + +`qa_file_scope_instantiation_lands_in_the_subset`, `qa_generate_block_instantiation_lands_in_the_subset`, `qa_escaped_module_name_instantiation_parity_with_whole_workspace`, `qa_add_port_by_position_still_fans_out_to_instantiation_files`, `qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled`, `qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption`. No probe files left in the tree; the only non-test-only edit was the `map_or` → `is_none_or` clippy fix inside my own new test code (nothing in the dev's code touched). + +### Summary + +| Claim | Verdict | +|---|---| +| `cargo fmt`/`cargo clippy`/`cargo test --workspace`/smoke | **Pass** | +| File-scope (owner-less) instantiation lands in the subset via `references_to` | **Pass, confirmed empirically** — the brief's most specific ask | +| Generate-block instantiation, escaped-identifier parity | **Pass** | +| `ModuleArgument::Position` (not just `Name`) still fans out correctly | **Pass, confirmed** — previously untested combination | +| Ambiguous-module refusal, via the index | **Pass** (dev's own test, re-verified) | +| Unsaved brand-new module (index has never heard of it) | **Pass** | +| Index stale vs. disk (duplicate definer unindexed) | **Behaves as documented**: a stale-but-verified answer, never a corruption; matches the Assumptions section's own framing | +| Gate (`may_have_port_action`) ⟺ fan-out (`port_action_modules`) coherence | **Pass, verified by construction + the dev's byte-sweep test** | +| Command parity across all three commands | **Pass** | +| Verifier cannot touch a file outside the subset | **True by construction** (no I/O in the crate) | +| Perf claims (synthetic + OpenTitan) | **Reproduced**, synthetic to the reported precision, OpenTitan to the same order of magnitude on different cursor sites | + +No corruption, no false refusal, no lost feature, and no missing-file divergence found anywhere I could construct one. The one real, novel-to-this-round behavior change (index staleness vs. `sources()`'s always-fresh disk read) is pre-existing in spirit everywhere else in the server, is disclosed prominently in the feature's own Assumptions section, and cannot produce a corrupt edit by the crate's own no-I/O architecture — so I am not filing it as a finding, only recording that I attacked it deliberately and it held. + +**Verdict: SHIP.** No blocking or non-blocking findings this round. + ## Review +**2026-08-28 — lead, codeAction fan-out round.** Reviewed after QA's +clean SHIP; gates re-run independently (fmt clean, clippy silent, 2482 +workspace tests green). This closes the owner's original report from +the root: the "slow F12" was a 3–4.5 s codeAction on every cursor move +blocking the single-threaded loop, and the fix is the house pattern — +the index's fan-out instead of `ws.sources()` — with the sufficiency +argument written before the speed was trusted. The dev's fourth rung +(`references_to`, because `edges_of` drops owner-less file-scope +instantiations) is exactly the kind of gap that separates a subset from +a superset, found by reading rather than by failing; QA confirmed it +empirically and pinned it. The one behavior change — a port action now +sees the workspace as the index describes it, so an unindexed on-disk +duplicate yields a stale offer instead of a fresh refusal — is +disclosed in Assumptions, cannot corrupt (the engine does no I/O of +its own; QA proved the untouched file untouched), and aligns this +answer with every other index-backed one. 4.56 s → 7.1 ms on +opentitan, 83 ms honest ceiling at a 36-file fan-out, both reproduced +by QA on different cursors. The prepareRename follow-up (250 ms on the +synthetic; 2.5–3 s measured on opentitan in performance.md) is Lane A +of the performance wave. Accepted; committed by the lead. + **2026-08-24 — lead.** Reviewed after QA round 2's ship verdict; gates run independently (1170 tests, 0 failures, clippy silent). The splice verifier plus per-feature shape check is the right division — the verifier stays diff --git a/docs/perf/README.md b/docs/perf/README.md index c88f921..0229e44 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -400,6 +400,47 @@ recorded above and the 347 / 387 / 203 ms QA measured on a busier machine — th same band, and the store is byte-identical at **2 380 790 bytes**, which is the number machine load cannot move. +## Before / after — round 6 (2026-08-28) + +`docs/features/refactor-ports/README.md`: the rest of the owner's "goto +definition is slow" report. The definition itself answered in microseconds — +it was queued behind `textDocument/codeAction`, which VS Code sends on nearly +every cursor move and which read the whole in-scope file set from disk and ran +the refactor engine over it whenever the cursor sat on an instantiation or a +port. The owner's instrumented session: **3 111 ms** and **3 014 ms** per code +action, against 0.01–0.44 ms for every other request. The file set is now the +cursor's module's own fan-out through the index — definers, instantiation +edges, reference postings, open buffers — instead of the workspace. + +Measured over the real checkout (3 976 files indexed, `--release`): + +| cursor | before | after | +|---|---:|---:| +| a port of `adc_ctrl_core` (action offered, 2 files edited) | 4.56 s | **7.1 ms** | +| a `prim_fifo_sync` instantiation (36-file fan-out) | 2.93 s | **83 ms** | + +Both were checked to give the *same* answer as the whole-workspace +computation, which is the point: this is a smaller input to the same engine, +not a cheaper approximation. The second row is the ceiling — a module +instantiated all over OpenTitan really does need its 36 files, and the engine +parses them twice (plan, then verify); 1.3 ms of that 83 ms is reading them. + +Reproducible without that checkout: +`perf::a_code_action_at_an_instantiation_before_and_after` generates 500 files +of 200 lines plus a module instantiated in three of them, and runs both shapes +over the same workspace in the same run: + +| | | +|---|---:| +| whole workspace (what the handler did until this round) | 725 ms | +| the module's fan-out | **0.41 ms** | +| `sources()` alone — the read, without the engine | 14.5 ms | +| `prepare_rename`, deliberately untouched this round | 249 ms | + +The last row is the follow-up this round did not take: a rename must see every +file that could name the symbol, so its subset is a different argument. It is +sent when the user presses the rename key, not per cursor move. + ## What it would take to go faster Ranked by what the measurements above say is there, with what each would diff --git a/performance.md b/performance.md new file mode 100644 index 0000000..ea392ec --- /dev/null +++ b/performance.md @@ -0,0 +1,487 @@ +# lucisv-server LSP performance against opentitan + +Measured 2026-08-28 on the real opentitan checkout, driving the real server +binary over stdio with a scripted LSP client. Every number below is a +client-observed round trip on a monotonic clock (`time.perf_counter`), which is +what the editor — and therefore the user — actually experiences. + +--- + +## 0. Read this first: the binary is **not** instrumented + +The brief said the binary at +`…/scratchpad/lucisv-server-instrumented` emits +`window/logMessage` lines of the form `timing: answered in X ms`. +**It does not.** Verified three ways: + +- `strings -a` on the binary finds no `timing`, `answered`, `handled in`, + `elapsed`, `took`, or ` ms` literal anywhere. +- Over ~20 sessions the client received **zero** `window/logMessage` + notifications, despite `index.logFiles` defaulting to `true`. +- `shasum -a 256` shows the binary is **byte-identical** to + `/Users/guoliangchen/repo/verilogrustformatter/target/release/lucisv-server` + (`ce7e15db473e81f420a247ca463085c22262b28815d6edb8345da04ecadfe7cc`), i.e. it + is the ordinary release build, copied. `crates/lucisv_server/src/perf.rs` is + an `#[ignore]`d in-process test module, not protocol instrumentation. + +I could not rebuild (the brief forbids running cargo in the repo, since another +agent is editing it concurrently). So **there is no server-side handling column +below.** In its place I measured a **transport baseline**: an unknown request +method (`$/lucisvNoSuchMethod`), which the server rejects without doing any +work. Its round trip is **0.02–0.33 ms** (median ≈ 0.05 ms across all sessions). +Everything above ~0.5 ms is therefore server work, not framing, and for an +isolated request `client round trip ≈ server handling + 0.05 ms`. The one thing +the missing instrumentation costs us is a breakdown *inside* a slow request; the +queue-blocking numbers in §3 are client-observable by construction and are +unaffected. + +--- + +## 1. Environment and provenance + +| | | +|---|---| +| Machine | Apple M1 Max, 10 cores, 64 GB RAM | +| OS | macOS 27.0 (build 26A5421a) | +| Date | 2026-08-28, ~21:50–22:15 local | +| Binary | `lucisv-server` 0.14.0, Mach-O arm64, 4,120,288 bytes, sha256 `ce7e15db…dfe7cc` | +| Repo HEAD | `bf9170a` — *"A scope widen indexes the folders it added, not everything again"* | +| Working tree at build time | **dirty**: `lucisv_server/{ports,state}.rs`, `vlog_refactor/{lib,ports}.rs` modified 21:43:09–21:43:29; binary linked 21:47:27. **The in-progress `code_actions` fan-out fix (`ws.module_sources()` replacing `ws.sources()`) is therefore compiled into this binary.** `ports.rs` was touched again at 21:55 (tests) — after the build. | +| Corpus | `/Users/guoliangchen/repo/opentitan` @ `0098135264` — 3979 `.sv`/`.svh`/`.v` files; the server indexes **3976, skips 3** | +| Scenario file | `hw/ip/aes/dv/tb/tb.sv` (100 lines); module `aes` instantiated at line 45 (0-based 44, col 2); `.clk_i` port connection at line 50; `aes` defined at `hw/ip/aes/rtl/aes.sv:9` | +| Client | `scratchpad/perf/lspclient.py` + `bench.py` / `bench2.py` / `bench3.py` / `typing.py` | + +**Cache state is controlled per run** via +`workspace/configuration` → `{"index":{"scope":…,"cachePath":""}}`. +"Cold" = the cache directory was `rm -rf`'d immediately before. "Warm" = the +directory carries a previous session's store (23 MB for the full workspace). + +--- + +## 2. Summary table — worst first + +Workspace scope, warm cache, unless the row says otherwise. "Repeats" is the +range over the 2nd–4th (or 2nd–6th) identical request in the same session. + +| Action | First try | Repeats | Verdict | +|---|---:|---:|---| +| `textDocument/rename` on `aes` (edits computed, not applied) | **6 355 ms** | 3 601 – 8 659 ms | **very slow** | +| — anything queued behind that rename (definition / hover / documentSymbol) | **5 079 ms** | — | **very slow** | +| `textDocument/prepareRename` on `aes` (**this is just pressing F2**) | **2 999 ms** | 1 723 – 2 597 ms | **very slow** | +| — anything queued behind that prepareRename | **2 501 ms** | — | **very slow** | +| Workspace scan, **cold** cache (didOpen → 3976 files indexed) | **3 003 ms** | — | acceptable (once) | +| Workspace scan, **warm** cache (3975 of 3976 from cache) | **1 551 ms** | 1 548 – 1 580 ms | acceptable | +| `textDocument/completion` at 1 typed character (512 candidates) | **61 ms** | 34 – 66 ms | **slow** (fires per keystroke) | +| `textDocument/codeAction` **on the `aes` instantiation** | **60 ms** | 46 – 49 ms | **slow** (fires per cursor move) | +| — definition pipelined behind that codeAction | **53 ms** | 47 – 58 ms | **slow** | +| definition immediately after a widening `didOpen` (`spi_device.sv`) | **88 ms** | 88 ms (2nd session) | slow-ish | +| definition immediately after a widening `didOpen` (`aes.sv`) | **48 ms** | 49 ms (2nd session) | acceptable | +| definition immediately after a widening `didOpen` (`kmac`, `hmac`) | 38 / 27 ms | 34 / 24 ms | acceptable | +| Typing 11 characters (`aes_reg_top`), completion each keystroke | **201 ms total** | — | 18 ms/keystroke avg | +| `workspace/symbol "aes"` (256 results) | 6.7 ms | 5.9 – 6.5 ms | fine | +| `textDocument/completion` at ≥5 typed characters | 5.3 ms | 4.0 – 5.0 ms | fine | +| `initialize` → response | 2.0 – 8.0 ms | — | fast | +| `textDocument/hover` on `aes` | 1.35 ms | 0.07 – 0.16 ms | fast | +| `textDocument/codeAction` on a **comment line** (contrast) | 0.93 ms | 0.50 – 0.91 ms | fast | +| `didChange` flush (measured with a `foldingRange` barrier) | 0.75 ms | 0.25 – 0.32 ms | fast | +| `textDocument/references` on `aes` (7 hits, incl. declaration) | 0.61 ms | 0.39 – 0.72 ms | fast | +| `textDocument/signatureHelp` inside the port list | 0.61 ms | 0.48 – 0.53 ms | fast | +| `textDocument/definition` on `aes` | 0.49 ms | 0.11 – 0.18 ms | fast | +| `textDocument/references` on `.clk_i` (10 hits) | 0.48 ms | 0.36 – 0.44 ms | fast | +| `textDocument/inlayHint` (whole 100-line file) | 0.36 ms | 0.21 – 0.25 ms | fast | +| `textDocument/documentSymbol` | 0.13 ms | 0.13 – 0.21 ms | fast | +| `textDocument/semanticTokens/full` | 0.16 ms | 0.12 – 0.13 ms | fast | +| `textDocument/typeDefinition` on `aes` | 0.15 ms | 0.09 – 0.10 ms | fast | +| `textDocument/diagnostic` (pull) | 0.13 ms | 0.04 – 0.07 ms | fast | +| `textDocument/selectionRange` at the instantiation | 0.12 ms | 0.08 – 0.09 ms | fast | +| `textDocument/documentHighlight` (see §7 — returns nothing) | 0.09 ms | 0.03 – 0.12 ms | fast | +| `textDocument/codeLens` | 0.10 ms | 0.03 – 0.07 ms | fast | +| `textDocument/documentLink` | 0.09 ms | 0.05 – 0.08 ms | fast | +| `textDocument/foldingRange` | 0.03 ms | 0.05 – 0.07 ms | fast | +| `textDocument/definition` / `hover` on `.clk_i` | 0.05 ms | 0.03 – 0.07 ms | fast | +| *transport baseline (unknown method — does no work)* | *0.02 – 0.33 ms* | — | *floor* | + +`textDocument/implementation` is **not advertised** by this server +(`implementationProvider` absent from the `initialize` result) and was not +measured. Advertised and measured: `typeDefinition`, `typeHierarchy`, +`callHierarchy`, `diagnostic` (pull, with `workspaceDiagnostics: true`), +`inlineCompletion`, `linkedEditingRange`, `documentOnTypeFormatting`, +`willSaveWaitUntil`. + +--- + +## 3. The queue-blocking analysis — this is the owner's pain + +The server runs a **single-threaded request loop**: one message is taken off +stdin, answered to completion, and only then is the next one read. Nothing is +cancelled, nothing is answered out of order, nothing runs on a worker. So the +latency a user feels for request *R* is not *R*'s own cost — it is *R*'s cost +**plus the un-finished cost of everything the editor already sent**. + +I measured this directly. Each slow request was sent, and then — with no wait, +same TCP-less pipe, back to back — three requests a real editor fires on every +cursor move. All four were timed from the same `t0`: + +| Sent first (the blocker) | Its own cost | `definition` behind it | `hover` behind it | `documentSymbol` behind it | +|---|---:|---:|---:|---:| +| `codeAction` on the `aes` token | 60.0 ms | **60.0 ms** | 60.1 ms | 60.3 ms | +| `prepareRename` on `aes` | 2 500.7 ms | **2 500.7 ms** | 2 500.9 ms | 2 501.0 ms | +| `rename` on `aes` | 5 079.1 ms | **5 079.1 ms** | 5 079.2 ms | 5 079.3 ms | +| `workspace/symbol "aes"` | 9.7 ms | **9.7 ms** | 9.7 ms | 9.8 ms | + +The same three requests, sent alone into an idle server in the same session, +cost **0.11 ms**, **0.07 ms** and **0.13 ms**. + +Read the amplification: + +- **definition behind `codeAction`: 52.7 ms first try (47.4–58.2 ms repeats) vs + 0.11 ms alone — ~480×.** This is the one the brief asked for by name. The + dedicated pipelined test (`codeAction` then `definition`, neither waited on) + gave 52.65 / 58.13 / 47.36 ms for the codeAction and 52.72 / 58.18 / 47.38 ms + for the definition riding behind it — the definition's answer lands **0.02–0.05 + ms** after the codeAction's, i.e. the queue is strictly serial and the + follower pays the leader's bill almost exactly. +- **definition behind `prepareRename`: 2 500.7 ms vs 0.11 ms — ~22 000×.** +- **definition behind `rename`: 5 079.1 ms vs 0.11 ms — ~46 000×.** + +Why this matters in an editor rather than in a benchmark: VS Code does not send +one request at a time. Moving the cursor emits `codeAction` + +`documentHighlight` + `inlayHint` + `codeLens`; typing emits `didChange` + +`completion` + `signatureHelp` + `diagnostic`. Every one of those lands behind +whatever is currently executing. So a 3-second `prepareRename` is not a +3-second F2 — it is a **3-second freeze of hover, go-to-definition, highlight, +and the completion popup**, and any keystroke typed during it is not even +*parsed* until it ends. + +Two structural consequences worth stating plainly: + +1. **The absolute number matters more than the ratio.** `workspace/symbol` + amplifies a follower by ~90× too, but 9.7 ms is invisible. The threshold is + roughly the frame budget: anything under ~16 ms is free, 16–100 ms is + noticeable on a cursor move, and anything over ~200 ms reads as a hang. +2. **`codeAction` and `completion` are the only slow requests on the hot path.** + `rename`/`prepareRename` are user-initiated; `codeAction` fires whether or + not the user wants a lightbulb, and `completion` fires on every character. + +--- + +## 4. Startup and scan, per scope and cache state + +`didOpen tb.sv` → the last `$/progress` `end`, followed by 1.5 s of silence. +(Naïvely waiting for the *first* `end` is wrong: the server raises **three** +progress bars in a row — a 0-file one, a 1-file one for the opened buffer, and +only then the real workspace scan under token `lucisv-index-2`. My first pass +made exactly this mistake and reported a 102 ms workspace scan.) + +| Scope | Cache | didOpen → settled | Files indexed | +|---|---|---:|---| +| `folder` (**the default**) | cold | **102.2 ms** | **1** | +| `folder` (default) | warm | **101.1 ms** | **1** | +| `workspace` | cold | **3 003.2 ms** | 3976 indexed, 3 skipped | +| `workspace` | warm | **1 551 / 1 560 / 1 568 / 1 573 / 1 580 ms** | 3976, **3975 from cache**, 3 skipped | + +- `initialize` itself is 2.0–8.0 ms and does no scanning; the scan is kicked off + by the first `didOpen`. +- The real scan begins ~300 ms after `didOpen` (the two trivial bars occupy the + first ~105 ms), so cold wall-clock from didOpen to a usable workspace index is + ~3.0 s and warm is ~1.6 s. +- **Persistence buys ~1.45 s (48%)** on this corpus. The store is 23 MB. +- Once the bar ends the index is genuinely ready: `definition` answers correctly + at 0.16–0.25 ms immediately, and is no better after a further 1 s idle. There + is no post-bar background settling to wait for. +- Three runs (`rename-workspace` 2 741 ms, `blockers` 3 004 ms, `renamegrow` + 2 987 ms) showed warm scans at cold-scan cost while still reporting "3975 from + cache". Five clean back-to-back runs afterwards were all 1 551–1 580 ms. I + attribute the outliers to CPU contention (another agent was building this repo + on the same machine during the session), not to a cache miss — but it is not + proven, and if warm scans are intermittently 2× it is worth a look. + +**The default scope is the headline startup finding, and it is not a +performance finding.** `IndexScope::Folder` with `scopeDepth: 0` +(`crates/lucisv_server/src/settings.rs`) walks only the open file's own +directory. `hw/ip/aes/dv/tb/` contains exactly one file. So on the shipped +default, opening `tb.sv` gives an index of **1 file**, and: + +| Request at the `aes` instantiation | folder scope (default) | workspace scope | +|---|---|---| +| `definition` | **0 results**, 0.05 ms | 1 result, 0.49 ms | +| `typeDefinition` | **0 results** | 1 result | +| `hover` | **0 results** | 1 result (module signature) | +| `references` | **0 results** | 7 results | +| `workspace/symbol "aes"` | **0 results** | 256 results | +| `completion` at a fresh line | **8 items** | 483 items | +| `signatureHelp` in the port list | **0 results** | 1 signature | + +Folder scope's uniformly sub-0.1 ms timings are therefore not a speed result — +**they are the cost of answering nothing.** Any comparison of folder vs +workspace latency that ignores this is meaningless. + +--- + +## 5. The `didOpen` widen (item 7) — the fix holds + +Folder scope, `tb.sv` open, then RTL files opened one at a time. Each open +widens the scope to a new folder, which the server indexes; the request sent +immediately afterwards waits for that work. Measured on both a cold and a warm +cache directory: + +| Widening `didOpen` | definition behind it (cold cache) | (warm cache) | +|---|---:|---:| +| `hw/ip/aes/rtl/aes.sv` | 48.4 ms | 49.3 ms | +| `hw/ip/kmac/rtl/kmac.sv` | 37.7 ms | 34.1 ms | +| `hw/ip/hmac/rtl/hmac.sv` | 27.0 ms | 23.9 ms | +| `hw/ip/spi_device/rtl/spi_device.sv` | **87.7 ms** | **88.3 ms** | + +**Verified: this is the post-fix regime.** The brief records 120–169 ms before +`bf9170a` and 12–44 ms after; three of the four jumps land in 24–49 ms. +`spi_device` at ~88 ms is above the quoted band, which is expected rather than +alarming — `hw/ip/spi_device/rtl/` is a much larger directory than the others, +and the widen now indexes *the folders it added*, so its cost scales with the +folder actually opened. Worth recording as the current ceiling for a single +jump. + +The cache makes almost no difference here (48.4 vs 49.3 ms), which makes sense: +the widen's cost is walking and parsing a directory the store has entries for +only if a previous session in the *same* cache dir already widened into it. + +After the widen, and after the index settles, everything is fast again +(`definition` 0.18/0.04/0.03 ms). + +**But the widen changes the cost of the slow requests too**, because `sources()` +now returns more files. Folder scope, after opening only `aes.sv`: + +| | before widen | after widen | workspace scope | +|---|---:|---:|---:| +| `codeAction` on the instantiation | 1.8 ms | 4.5 ms | 60 ms | +| `prepareRename` | — (0 results) | **27.0 ms** | **2 999 ms** | +| `rename` | — | **93.8 ms** | **6 355 ms** | +| `workspace/symbol "aes"` | 0.04 ms (0 results) | 3.7 ms (256) | 6.7 ms (256) | + +This is the clearest statement of the root cause: **the slow requests cost +`O(files in scope)`.** 2 files → 27 ms. ~200 files → 94 ms. 3976 files → +3 000 ms. + +--- + +## 6. Root causes + +### 6a. `codeAction` — already fixed in this binary, still 60 ms + +The brief predicted ~3 s on the instantiation and asked me to verify. **It is +46–60 ms, not 3 s**, because the fix described as "in progress this session" is +compiled into the binary I was given (sources modified 21:43, binary linked +21:47). The diff replaces + +```rust +let sources = ws.sources(); // every in-scope file +``` + +with + +```rust +let modules = vlog_refactor::port_action_modules(&doc.text, offset); +if modules.is_empty() { return Vec::new(); } +let sources = ws.module_sources(&path, &modules); // that module's fan-out +``` + +in `crates/lucisv_server/src/ports.rs::code_actions`, plus a `sources_at()` +helper doing the same for the `addPort` / `removePort` / `propagatePorts` +commands. + +That the contrast case is 0.5–0.9 ms (comment line, `port_action_modules` +returns empty and the function bails before touching the workspace) while the +instantiation case is 46–60 ms shows the early-out works and the residue is the +fan-out read itself: `aes` is instantiated ~6 times workspace-wide, so +`module_sources` still reads and parses those files on **every cursor move onto +the instantiation**. 60 ms per cursor move is still four frames, and §3 shows it +is charged to whatever the editor sent next. + +*Suggested follow-up (not implemented — out of scope for this measurement +task):* memoize `module_sources` per (module, index generation), or answer +`codeAction` from the index rather than from re-read source text. + +### 6b. `prepareRename` — 2.5–3.0 s, and it is **not** "user-initiated-rare" + +`crates/lucisv_server/src/rename.rs:30`: + +```rust +let target = vlog_refactor::prepare_rename(&ws.sources(), &path, offset)?; +``` + +`ws.sources()` reads and returns **every file in scope** — 3976 files at +workspace scope. `prepareRename` is a **read-only** request whose entire job is +to answer "is this token renameable, and what range/placeholder?". It returns +`{"placeholder": "aes", "range": {line 44, chars 2–5}}` — information available +from the open buffer alone. It does not need the workspace. + +**I want to push back on the brief's framing here.** The brief labels the rename +machinery "user-initiated-rare" and expected slowness to be acceptable. +`prepareRename` is not rare and it is not what the user thinks of as "doing a +rename" — it is what fires the instant F2 is pressed, *before* the rename box +even appears. 2.5–3.0 s of a wholly frozen server, on a keypress that has not +yet committed to anything, is the second-worst result in this report and by §3 +it takes hover, definition and highlight down with it. I'd rate it **the most +fixable serious problem here**, and more urgent than `codeAction`: the fix is +narrower (answer the range from the buffer; only consult the workspace if the +token turns out to be a cross-file symbol) and the payoff is larger. + +### 6c. `rename` — 3.6–8.7 s, genuinely rare, genuinely expensive + +`rename.rs:47` has the same `ws.sources()` call and then computes edits across +the workspace (7 files edited for `aes`). 3.6–8.7 s is bad but this one really +is a deliberate, infrequent, "I asked for a big thing" action, and it produces a +correct workspace-wide edit set. Acceptable *if* it reported progress and were +cancellable, which it currently is not (`workDoneProgress` is not raised for it, +and the single-threaded loop cannot service `$/cancelRequest` while busy). + +**Correction to an earlier reading:** my first rename run showed 6 355 → 7 486 → +8 659 ms and looked like monotonic growth (a leak). A dedicated 6-repeat re-run +showed 5 357 → 5 347 → 4 829 → 4 458 → 3 992 → 3 601 ms — *decreasing*. There is +no growth; the spread is machine noise (see §8). Range across all runs: +**3 601–8 659 ms**, which is itself a 2.4× spread and a sign of how much this +path is at the mercy of I/O and CPU contention. + +### 6d. `completion` — 34–66 ms per keystroke, and it is a NEW finding + +**Flagging this loudly: this was not in the brief's list of known-slow items, +and on the hot path it is worse than `codeAction`.** + +Completion cost tracks the number of candidates *before* the 512-item +truncation, i.e. it is worst exactly when the user has typed the fewest +characters — the beginning of every identifier: + +| Typed prefix | Items returned | Round trip | +|---|---:|---:| +| `` (empty) | 512 | **63–66 ms** | +| `a` | 512 | **58–61 ms** | +| `ae` | 483 | 35–36 ms | +| `aes` | 482 | 34–37 ms | +| `aes_` | 476 | 35 ms | +| `prim_` | 339 | 16–19 ms | +| `clk` | 512 | 5.7–6.0 ms | +| `aes_reg` | 20 | 5.0 ms | +| `zzzz` | 1 | 1.4–2.0 ms | + +Typing the identifier `aes_reg_top` one character at a time, with a completion +request per keystroke (what VS Code's 24×7 IntelliSense does) and a `hover` +racing behind each one: + +``` +keystroke 1 'a' completion 61.44 ms hover-behind-it 61.46 ms (512 items) +keystroke 2 'ae' completion 36.13 ms hover-behind-it 36.15 ms (483 items) +keystroke 3 'aes' completion 35.36 ms hover-behind-it 35.39 ms (482 items) +keystroke 4 'aes_' completion 34.92 ms hover-behind-it 34.94 ms (476 items) +keystroke 5 'aes_r' completion 5.34 ms hover-behind-it 5.35 ms ( 35 items) +… +keystroke 11 'aes_reg_top' completion 4.27 ms hover-behind-it 4.27 ms ( 1 items) +→ 11 characters cost 200.9 ms of server time (18.3 ms/keystroke average) +``` + +Note `clk` → 512 items in 6 ms versus `` → 512 items in 64 ms: the returned +count is capped at 512 either way, so the cost is **not** in building or +serialising the result. It is in scanning/filtering the candidate set, and the +broader the prefix the more of the 3976-file symbol table is walked. A prefix +index (or an early bail once 512 matches are found, if the ordering permits) +would flatten this. + +The `didChange` half of a keystroke is **not** the problem: measured alone with +a `foldingRange` barrier it is **0.25–0.75 ms**, and a burst of 10 `didChange` +notifications followed by one completion cost 2.88 ms total. The flush is +cheap; the completion is not. + +### 6e. `file_ops.rs:120` — same pattern, unmeasured + +`for (path, text) in ws.sources()` in +`crates/lucisv_server/src/file_ops.rs:120` serves `workspace/willRenameFiles`. +The server advertises `willRename` with a `**` folder filter, so **renaming any +folder in the VS Code explorer** will pay the same full-workspace read. Not +measured (it needs a file-system mutation, and the brief forbids touching the +opentitan checkout), but it is the same `ws.sources()` shape as §6b/§6c and +should be on the same follow-up list. + +--- + +## 7. Non-performance findings worth surfacing + +- **`textDocument/documentHighlight` returns 0 results at every position + tested** — on the `aes` instantiation and on the `.clk_i` port connection, at + both folder and workspace scope, before and after the widen, even though + `documentHighlightProvider: true` is advertised and `references` at the same + positions returns 7 and 10 hits respectively. It is fast (0.03–0.12 ms) + because it is doing nothing. This looks like a functional bug, not a perf + issue, but a fast wrong answer will read as "fast" in any benchmark that only + times it. +- **`inlayHint` over the whole file returns 4 hints at workspace scope and 0 at + folder scope**, and `codeLens` reports `"no instantiations"` for `tb` (correct + — nothing instantiates the testbench). +- **A cold workspace scan emits ~994 `$/progress` report notifications** (one + per 4 files). Harmless for a real editor, but it saturated my first + measurement client and made a 3-second scan look like a 70-second one. Worth + knowing before anyone else measures this. +- `index.logFiles` defaults to `true` but **no `window/logMessage` was ever + received** in any session. Either the default is not being honoured or the log + is gated on something the pulled configuration did not supply. + +--- + +## 8. Methodology and caveats — read before quoting any number + +- **No server-side timing.** See §0. Every number is a client round trip. The + transport floor is 0.02–0.33 ms, so for isolated requests the two are within + noise of each other, but a slow request's *internal* breakdown is not + available and nothing in this document should be read as one. +- **One machine, one corpus, one afternoon.** M1 Max / 64 GB is a fast laptop. + A 3 s cold scan here could be 10 s on a 4-core machine with a slower disk. +- **Page cache is hot.** opentitan had been walked repeatedly by earlier + sessions before I started; "cold cache" above means *lucisv's* index store was + deleted, **not** that the OS file cache was dropped. A genuinely cold-boot + first scan will be slower than the 3 003 ms reported. +- **The machine was not quiet.** Another agent was editing and building this + repo concurrently, by design of the task. This is the most likely explanation + for the three anomalous 2.7–3.0 s "warm" scans in §4 and for the 2.4× spread + in `rename`. The sub-millisecond results are unaffected (they were stable to + ±0.05 ms across ~20 sessions); the multi-hundred-millisecond ones should be + read as ±30%. +- **Repeats share a warm process.** Each "repeats" range is the 2nd–4th + identical request in the same session, so it reflects whatever the server + memoised on the first. Where that matters (`codeAction`, `rename`) I ran the + request as the **first** request of a dedicated session to get a genuinely + cold first try; that is what the "first try" column reports. +- **`rename` was measured but never applied.** `textDocument/rename` returns a + `WorkspaceEdit`; the client discarded it. The opentitan checkout is unmodified + (verified: no writes, only `didOpen` of existing files). +- **Instrumentation overhead is nil** — there is none to have. Client overhead + (JSON encode/decode, framing) is inside the 0.05 ms transport baseline. +- **Positions were resolved from the file text at run time**, not hard-coded, so + the numbers stay attached to the `aes` instantiation and the `.clk_i` port + connection even if the file shifts. +- **`tb.sv` carries one pre-existing local edit** — a trailing space on line 44, + `git diff` against `0098135264`, mtime 20:39, an hour before this session + began and not made by this measurement. It is why `textDocument/diagnostic` + returns a `no-trailing-whitespace` item. Nothing in the checkout was written + by these runs. + +--- + +## 9. Raw logs + +All under +`/private/tmp/claude-501/-Users-guoliangchen-repo-verilogrustformatter/7b09ba01-f222-4ace-bf9a-b321331bf159/scratchpad/perf/`: + +| File | What | +|---|---| +| `lspclient.py` | the LSP client (framing, config/progress replies, timing helpers) | +| `bench.py` | phases `startup` / `nav` / `codeaction` / `rename` / `widen` | +| `bench2.py` | phases `blockers` (§3) / `renamegrow` (§6c) / `keystroke` (§6d) | +| `bench3.py` | `realfolder` (§5 post-widen table) / `completion` (§6d table) | +| `typing.py` | the per-keystroke typing simulation (§6d) | +| `results.jsonl` | every measurement, machine-readable | +| `logs/startup-{folder,workspace}-{cold,warm*}.log` | §4 | +| `logs/nav-{workspace,folder}.log` | §2 whole-document and cursor batteries | +| `logs/codeaction-{workspace,folder}.log` | §6a and the pipelined test | +| `logs/rename-workspace.log`, `logs/renamegrow.log` | §6b, §6c | +| `logs/blockers-workspace.log` | §3 queue-blocking table | +| `logs/widen-folder-{cold,warm}.log`, `logs/realfolder.log` | §5 | +| `logs/completion.log`, `logs/keystroke.log`, `logs/typing.log` | §6d | +| `logs/progress-ws-cold.log` | the multi-bar progress trace behind §4's note | +| `caps.txt` | full `initialize` result (advertised capabilities) |