From 097498da239b2a42aed7a7e568834634a59e2c62 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Fri, 28 Aug 2026 14:02:15 -0700 Subject: [PATCH] References stop sweeping the whole open buffer per request The open-document overlay loop in indexed_references did two index lookups and a scope walk for every reference in every open buffer. A spelled-name prefilter (sound: every Def is filed under exactly its own declared name, so a mismatched name can never match the target) plus a hoisted file_id take a 70k-reference open top from 3.2 ms to 110 us per request, both directions. In-file references and documentHighlight batch-convert spans through the walker (1.76 ms -> 1.18 ms / 917 us on a 10k-use signal). Answers byte-identical; the refactor-walk equivalence suite extended with a unit-vs-member same-spelling case. Measurements also acquitted references of the owner-reported direction asymmetry: the felt cost is the didOpen scope-widening rescan re-parsing open buffers (210 of 223 ms), filed as a Handshake for the next round. Co-Authored-By: Claude Fable 5 --- crates/lucisv_server/src/nav.rs | 392 ++++++++++++++++++++++++- crates/lucisv_server/src/perf.rs | 6 +- docs/features/references-nav/README.md | 344 +++++++++++++++++++++- 3 files changed, 735 insertions(+), 7 deletions(-) diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index f1dab56..194efe6 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -178,8 +178,22 @@ pub(crate) fn indexed_def_for_symbol<'a>( doc: &Document, symbol: &Symbol, ) -> Option<&'a Def> { - let path = doc.path.as_deref()?; - let file = ws.index().file_id(path)?; + let file = ws.index().file_id(doc.path.as_deref()?)?; + indexed_def_in_file(ws, doc, symbol, file) +} + +/// [`indexed_def_for_symbol`] with the document's own [`FileId`] already in +/// hand. +/// +/// Split out for `indexed_references`, which asks about every reference in one +/// buffer: the path lookup is a binary search whose comparisons are whole path +/// `cmp`s, and it answers the same thing for all of them. +fn indexed_def_in_file<'a>( + ws: &'a Workspace, + doc: &Document, + symbol: &Symbol, + file: vlog_semantic::FileId, +) -> Option<&'a Def> { let defs = if symbol.scope == doc.semantics.file_scope() { ws.index().units(&symbol.name) } else { @@ -218,9 +232,27 @@ fn indexed_references( for (_, doc) in ws.open_documents() { let Some(path) = doc.path.as_ref() else { continue }; + // Every reference in this buffer is answered against the same indexed + // file, so the path lookup — a binary search comparing whole paths — + // is taken once per buffer rather than once per reference. + let file = ws.index().file_id(path); for (id, reference) in doc.semantics.references().iter().enumerate() { + // A use can only name `target.def` if it spells the name that + // declaration declares, and `target.name` is exactly that name. + // One string compare replaces two index lookups and a scope walk + // for every *other* name in the buffer, which in a big top is all + // but a handful of them. The argument that this changes no answer + // is in `docs/features/references-nav/README.md`. The empty-span + // check below is deliberately *not* hoisted here: an ambiguous use + // aborts the whole collection whether or not it has a span. + if reference.name != target.name { + continue; + } let matches = match reference.resolved().and_then(|id| doc.semantics.symbol(id)) { - Some(symbol) => indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def), + Some(symbol) => { + file.and_then(|file| indexed_def_in_file(ws, doc, symbol, file)) + == Some(&target.def) + } None => match doc.external.get(vlog_semantic::ReferenceId(id as u32)) { Some(ExternalTarget::Resolved(def)) => def == &target.def, Some(ExternalTarget::Ambiguous(defs)) if defs.contains(&target.def) => { @@ -308,9 +340,14 @@ fn in_file_references( let Some(symbol_id) = symbol_at(&doc.semantics, offset) else { return Vec::new() }; let Some(target) = path_to_uri_or_self(ws, uri) else { return Vec::new() }; let positions = doc.positions(); + // `occurrences` sorts, so the spans arrive in the order a walker wants — + // the same batch conversion `locations` already does for the cross-file + // answer. A signal used ten thousand times in one file is an ordinary + // shape, and one-span-at-a-time conversion re-measures a line per span. + let mut walker = positions.walker(); occurrences(&doc.semantics, symbol_id, include_declaration) .into_iter() - .map(|span| Location { uri: target.clone(), range: positions.range(span) }) + .map(|span| Location { uri: target.clone(), range: walker.range(span) }) .collect() } @@ -332,11 +369,14 @@ pub fn document_highlights(doc: &Document, offset: u32) -> Option String { + let mut src = String::from( + "module top (\n input logic clk,\n input logic rst_n,\n \ + input logic [31:0] data_in,\n output logic [31:0] data_out\n);\n \ + wire acc;\n assign acc = rst_n;\n", + ); + for n in 0..blocks { + src.push_str(&format!( + " wire [31:0] w_{n};\n \ + assign w_{n} = data_in ^ {{32{{rst_n}}}} ^ {{32{{acc}}}};\n \ + reg [31:0] r_{n};\n always @(posedge clk) r_{n} <= w_{n};\n" + )); + } + for n in 0..instances { + src.push_str(&format!(" sub u_{n} (.clk(clk), .data_in(data_in));\n")); + } + src.push_str(" assign data_out = data_in;\nendmodule\n"); + src + } + + /// Both directions of a cross-file references request, with a big buffer + /// open — the owner's report of 2026-08-28, measured. + #[test] + #[ignore = "manual references-latency probe — see docs/features/references-nav/README.md"] + fn qa_references_latency_with_a_big_open_top() { + use std::hint::black_box; + + let dir = temp_dir("refs_big_top"); + let top_text = generated_top(10_000, 4); + let sub_path = dir.join("sub.sv"); + let top_path = dir.join("top.sv"); + fs::write(&sub_path, PROBE_SUB).expect("write"); + fs::write(&top_path, &top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let top_uri = path_to_uri(&top_path).expect("uri"); + let sub_uri = path_to_uri(&sub_path).expect("uri"); + ws.set_document(top_uri.clone(), top_text.clone()); + ws.set_document(sub_uri.clone(), PROBE_SUB.to_string()); + + let use_site = at(&top_text, "sub u_0"); + let declaration = at(PROBE_SUB, "sub"); + let local = top_text.rfind("<= w_").expect("a local use") as u32 + 3; + let common = top_text.rfind("{32{acc}}").expect("a use of acc") as u32 + 4; + let references_in_top = + ws.document(&top_uri).map(|doc| doc.semantics.references().len()).expect("top is open"); + + // The answers, before any timing: a measurement of a request that + // answered nothing is worthless. + assert_eq!(references(&ws, &top_uri, use_site, true).len(), 5, "declaration + 4 instances"); + assert_eq!(references(&ws, &sub_uri, declaration, true).len(), 5, "the same five"); + assert_eq!(definition(&ws, &top_uri, use_site).len(), 1); + assert_eq!(references(&ws, &top_uri, local, true).len(), 3, "one wire, in this file only"); + assert_eq!(references(&ws, &top_uri, common, true).len(), 10_002, "`acc`, everywhere"); + + let runs = 20; + let from_use = mean(runs, || { + black_box(references(&ws, &top_uri, black_box(use_site), true)); + }); + let from_declaration = mean(runs, || { + black_box(references(&ws, &sub_uri, black_box(declaration), true)); + }); + let to_definition = mean(runs, || { + black_box(definition(&ws, &top_uri, black_box(use_site))); + }); + let in_file = mean(runs, || { + black_box(references(&ws, &top_uri, black_box(local), true)); + }); + let in_file_common = mean(runs, || { + black_box(references(&ws, &top_uri, black_box(common), true)); + }); + let highlights = mean(runs, || { + let doc = ws.document(&top_uri).expect("open"); + black_box(document_highlights(doc, black_box(common))); + }); + + eprintln!( + "big open top ({} KB, {references_in_top} references): \ + references from the use site {from_use:?}, \ + from the declaration {from_declaration:?}, \ + definition from the use site {to_definition:?}, \ + references on a local wire used 3× (the in-file fallback) {in_file:?}, \ + on one used 10 001× {in_file_common:?}, \ + documentHighlight on that one {highlights:?}", + top_text.len() / 1000, + ); + let _ = fs::remove_dir_all(&dir); + } + + /// The other half of the owner's report: what jumping *into* a file costs + /// when the folder it lives in was not in the index's scope yet. + #[test] + #[ignore = "manual didOpen/scope-widening latency probe — see docs/features/references-nav/README.md"] + fn qa_didopen_latency_when_a_new_folder_widens_the_scope() { + use std::hint::black_box; + + let dir = temp_dir("didopen_scope"); + fs::create_dir_all(dir.join("rtl")).expect("rtl dir"); + fs::create_dir_all(dir.join("lib")).expect("lib dir"); + for n in 0..400 { + fs::write( + dir.join("rtl").join(format!("m{n}.sv")), + format!("module m{n};\n wire w;\n assign w = 1'b0;\nendmodule\n"), + ) + .expect("write"); + } + fs::write(dir.join("lib").join("sub.sv"), PROBE_SUB).expect("write"); + let top_text = generated_top(10_000, 4); + let top_path = dir.join("rtl").join("top.sv"); + fs::write(&top_path, &top_text).expect("write"); + + // The default rung: the folder scope. Nothing is in scope until a + // buffer is opened, so the first `didOpen` is itself a widening. + let mut ws = Workspace::default(); + ws.open_roots(vec![dir.clone()]); + let top_uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(top_uri.clone(), top_text.clone()); + ws.rebuild_index(); + let covered = ws.index().files().len(); + + // A `didOpen` the scope already covers: one `Document::new` and a + // publish, and `server.rs` runs no rescan at all. + let sibling = dir.join("rtl").join("m0.sv"); + let sibling_uri = path_to_uri(&sibling).expect("uri"); + let sibling_text = fs::read_to_string(&sibling).expect("read"); + let inside = mean(20, || { + ws.set_document(sibling_uri.clone(), sibling_text.clone()); + }); + + // A `didOpen` in a folder the scope does not cover: the same + // `Document::new`, and then the whole rescan `server.rs` runs when + // `scope_dirs()` moved — which re-reads and re-parses every file in + // the widened scope, the open big buffer included. + let sub_uri = path_to_uri(&dir.join("lib").join("sub.sv")).expect("uri"); + let widening = mean(5, || { + ws.set_document(sub_uri.clone(), PROBE_SUB.to_string()); + black_box(ws.rebuild_index()); + }); + let rescan = mean(5, || { + black_box(ws.rebuild_index()); + }); + // The same rescan with the big buffer closed, so its share of the + // rescan is a subtraction rather than a guess. + ws.close_document(&top_uri); + let without = mean(5, || { + black_box(ws.rebuild_index()); + }); + + eprintln!( + "didOpen with a {} KB buffer already open, {covered} files in scope: \ + a file the scope already covers {inside:?}; \ + one in a new folder (didOpen + rescan) {widening:?}; \ + the rescan alone {rescan:?}, and {without:?} with the big buffer closed", + top_text.len() / 1000, + ); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn include_declaration_drops_the_declaration_and_nothing_else() { let (dir, ws, uri) = instantiated("xrefs_nodecl", "sub.sv"); @@ -771,6 +1050,109 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + #[test] + fn a_same_named_port_in_another_open_buffer_is_a_different_symbol() { + // The name prefilter's risk case, asserted from both sides: two + // modules declare a port `clk`, both files are open, and each port's + // references are its own. A prefilter that let a spelling stand in for + // an identity would merge these two answers. + let dir = temp_dir("xrefs_same_name"); + let sub = "module sub (input logic clk);\nendmodule\n"; + let top = "module top;\n sub u_a (.clk(1'b0));\nendmodule\n"; + let other = "module other (input logic clk);\n wire w;\n assign w = clk;\nendmodule\n"; + for (name, text) in [("sub.sv", sub), ("top.sv", top), ("other.sv", other)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let mut uri_of = |name: &str, text: &str| { + let uri = path_to_uri(&dir.join(name)).expect("uri"); + ws.set_document(uri.clone(), text.to_string()); + uri + }; + let sub_uri = uri_of("sub.sv", sub); + uri_of("top.sv", top); + let other_uri = uri_of("other.sv", other); + + assert_eq!( + places(&references(&ws, &sub_uri, at(sub, "clk"), true)), + vec![("sub.sv".to_string(), 0), ("top.sv".to_string(), 1)], + "`sub`'s port: its declaration and the connection to it" + ); + assert_eq!( + places(&references(&ws, &other_uri, at(other, "clk"), true)), + vec![("other.sv".to_string(), 0), ("other.sv".to_string(), 2)], + "`other`'s port: its declaration and its own use" + ); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn two_packages_declaring_one_name_keep_their_references_apart() { + // The same attack through the member table rather than the port table: + // `p::WIDTH` and `q::WIDTH` spell one name and are two declarations, + // and the file using both is open. + let dir = temp_dir("xrefs_two_packages"); + let p = "package p;\n localparam WIDTH = 8;\nendpackage\n"; + let q = "package q;\n localparam WIDTH = 16;\nendpackage\n"; + let a = "module a;\n wire [p::WIDTH-1:0] x;\n wire [q::WIDTH-1:0] y;\nendmodule\n"; + for (name, text) in [("p.sv", p), ("q.sv", q), ("a.sv", a)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let a_uri = path_to_uri(&dir.join("a.sv")).expect("uri"); + ws.set_document(a_uri.clone(), a.to_string()); + let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri"); + ws.set_document(p_uri.clone(), p.to_string()); + + assert_eq!( + places(&references(&ws, &p_uri, at(p, "WIDTH"), true)), + vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)], + "`p`'s WIDTH only — `q::WIDTH` on the next line is another symbol" + ); + // And from the use side, the same set. + assert_eq!( + places(&references(&ws, &a_uri, at(a, "p::WIDTH") + 3, true)), + vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)] + ); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn every_in_file_occurrence_is_converted_against_its_own_line() { + // The in-file fallback converts its spans with one walker now. A + // walker handed an out-of-order span answers a stale column, so the + // shape that would catch it: many occurrences, each on a line with a + // wide character before it, plus one on the same line as another. + let mut text = String::from("module m;\n wire a;\n"); + for n in 0..20 { + text.push_str(&format!(" // é 🎉 {n}\n assign b{n} = a + a;\n")); + } + text.push_str("endmodule\n"); + let (ws, uri) = document(&text); + let found = references(&ws, &uri, at(&text, "wire a") + 5, true); + assert_eq!(found.len(), 41, "the declaration and two uses per block"); + + let doc = ws.document(&uri).expect("open"); + let positions = doc.positions(); + for location in &found { + let line = location.range.start.line as usize; + let offset = positions.offset(location.range.start); + assert_eq!( + text.get(offset as usize..offset as usize + 1), + Some("a"), + "line {line} must point at the name" + ); + assert_eq!(location.range.end.character, location.range.start.character + 1); + } + + // documentHighlight walks the same list and must agree with it. + let highlights = document_highlights(doc, at(&text, "wire a") + 5).expect("a symbol"); + let ranges: Vec<_> = highlights.iter().map(|h| h.range).collect(); + assert_eq!(ranges, found.iter().map(|l| l.range).collect::>()); + } + #[test] fn an_unsaved_open_buffer_replaces_its_saved_reference_postings() { let (dir, mut ws, uri) = instantiated("xrefs_unsaved_uses", "top.sv"); diff --git a/crates/lucisv_server/src/perf.rs b/crates/lucisv_server/src/perf.rs index 784202f..2cf6e31 100644 --- a/crates/lucisv_server/src/perf.rs +++ b/crates/lucisv_server/src/perf.rs @@ -58,7 +58,11 @@ fn generated_module(name: &str, lines: usize) -> String { /// The mean of `runs` runs. One run of a millisecond-scale operation is mostly /// scheduling noise; a mean of a handful is the number worth writing down. -fn mean(runs: u32, mut body: impl FnMut()) -> Duration { +/// +/// `pub(crate)` so the probes that live beside the code they measure — +/// `nav.rs`'s references-latency probes — time themselves the same way these +/// do, rather than each growing its own stopwatch. +pub(crate) fn mean(runs: u32, mut body: impl FnMut()) -> Duration { let start = Instant::now(); for _ in 0..runs { body(); diff --git a/docs/features/references-nav/README.md b/docs/features/references-nav/README.md index 2a6d569..4fbf1aa 100644 --- a/docs/features/references-nav/README.md +++ b/docs/features/references-nav/README.md @@ -116,10 +116,41 @@ standard capability both VS Code's built-in client and Neovim's `vim.lsp` consume on their own once it is advertised; no extension change was needed and none was made. -**Requested of other modules**: none. +**Requested of other modules (2026-08-28):** a scope-widening `didOpen` +re-parses every open buffer. `Workspace::collect_sources` +(`crates/lucisv_server/src/state.rs`) clones each open document's text into the +list the index is rebuilt from, so a rescan triggered by opening some *other* +file pays a full lex-and-parse of every buffer the user has open — measured at +**210 ms of a 223 ms rescan** for one 1.4 MB `top.sv`, against 13 ms for the +same 401-file scope with that buffer closed. Every open buffer already holds a +finished parse and `Semantics`; `FileFacts::of` re-does both from the text. +This is `index-scope` / `state.rs` territory, not this feature's, and the +2026-08-28 brief said measure it and stop — so it is written here rather than +changed. The obvious shape (an `IndexBuilder::add_facts` path fed from the +buffer's existing analysis instead of its text) is a real option and a separate +decision. ## Status / TODO +- [x] **References latency with a big buffer open (2026-08-28):** measure both + directions of a cross-file references request while a 1.4 MB, 40 000-line + `top.sv` is an open document, then fix what the numbers convict. Landed: + a **spelled-name prefilter** and a **hoisted `file_id`** in + `indexed_references`'s open-document overlay loop, and **walker-batched** + span conversion in the two in-file fallbacks. Release probes: + **3.20 ms → 110 µs** from the use site, **3.18 ms → 110 µs** from the + declaration (29×); the in-file fallback for a signal used 10 001 times, + **1.76 ms → 1.18 ms**, and `documentHighlight` on it **1.54 ms → 917 µs**. + No answer changes — the equivalence test against + `vlog_refactor::find_references` and the whole nav suite are untouched + and green. +- [ ] **Not this feature's to fix, measured and filed (2026-08-28):** the + owner-reported *asymmetry* is not in `references` at all — both + directions cost the same, before and after. What is expensive is the + `didOpen` that jumping into another folder's file triggers: **220 ms**, + of which **210 ms** is re-parsing the open big buffer during the + scope-widening rescan. See the work log and Handshakes. + - [x] **Indexed navigation performance (2026-08-27):** persist each file's externally reachable reference facts beside its declarations, merge them into declaration-to-occurrence postings in `WorkspaceIndex`, and route @@ -165,6 +196,147 @@ and none was made. ## Work log +### 2026-08-28 — references latency with a big buffer open + +The owner reported find-references from a *use site* in a big open `top.sv` +toward a module as "still very slow", and the same request from the module's +*declaration* toward its uses as fast. Both run the same +`indexed_references`, so the asymmetry was unexplained. Measured first. + +**The fixture.** Two `#[ignore]`d probes in `nav.rs`'s own test module, beside +the `qa_indexed_references_latency_over_a_large_workspace` probe that has been +there since 2026-08-27, and taken with `perf::mean` (now `pub(crate)`) so every +number in this repo is timed the same way. `generated_top(10_000, 4)` is a +40 000-line, 1 374 KB module of ordinary RTL blocks — a wire, an assign, a +register and its update — carrying **70 024 references**, four instantiations +of a small `sub`, and one local `acc` used by every block so the file also has +a *local* name with 10 001 occurrences. Both files are open documents; the +index is built over the directory. + +```text +cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored --nocapture --test-threads=1 +``` + +Machine: the one `docs/perf/README.md` records — Apple M1 Max, macOS 27.0, +`--release`. Means of 20 runs (5 for the rescan rows). + +| what | before | after | +|---|---|---| +| `references` from the **use site** in `top.sv`, `includeDeclaration` | **3.20 ms** | **110 µs** | +| `references` from the **declaration** in `sub.sv`, same | **3.18 ms** | **110 µs** | +| `definition` from the use site | 1.21 µs | 1.13 µs | +| `references` on a local wire used 3× (the in-file fallback) | 1.49 µs | 1.20 µs | +| `references` on a local wire used 10 001× | **1.76 ms** | **1.18 ms** | +| `documentHighlight` on that same wire | **1.54 ms** | **917 µs** | + +**Hypothesis 1 is convicted, and it is symmetric.** The open-document overlay +loop was the whole 3.2 ms: for every one of the 70 024 references in the open +buffer it ran either `indexed_def_for_symbol` — a `file_id` binary search whose +comparisons are whole-path `cmp`s, plus a `units`/`member` `BTreeMap` lookup, +plus a scope-and-owner chase — or a `doc.external` hash lookup, to discard all +but five of them. It cost that whichever end the cursor was on, which is the +first thing the measurement says: **the two directions are within 1 % of each +other, before and after.** The owner's asymmetry is not in `references`. + +**Hypothesis 2 registers, but only for a common local name.** The in-file +fallback and `documentHighlight` convert their spans one at a time with +`positions.range`, which re-measures a line per span. On three occurrences that +is 1.5 µs and invisible; on 10 001 it is 1.76 ms. Both now batch-convert with +`positions.walker()` over the already-sorted span list, exactly as `locations` +has done for the cross-file answer since this feature shipped — 1.5× and 1.7×. +The rest of those two figures is collecting, sorting and allocating 10 001 +spans, which is the answer's own size and not something to shave here. + +**Hypothesis 3 is where the felt latency actually is** — measured, and +deliberately not redesigned this round (see Handshakes). With the same 1.4 MB +buffer open and 401 files in scope: + +| `didOpen` | cost | +|---|---| +| a file the folder scope **already covers** | **8.4 µs** | +| a file in a **new folder** (`didOpen` + the rescan `server.rs` then runs) | **220 ms** | +| — the rescan alone | 223 ms | +| — the same rescan with the big buffer **closed** | **13 ms** | + +So the scope-widening rescan is 223 ms, and **210 ms of it is the open big +buffer**: `Workspace::collect_sources` clones every open document's text into +the source list and the index re-parses it, at full lex-and-parse cost, on a +rescan that was triggered by an entirely different file. That is the shape that +matches the owner's report: F12 or a references result *from* `top.sv` opens the +module's file, and when that file lives in a folder the folder scope had not +reached, the `didOpen` widens the scope and pays a whole rescan. The reverse +direction — standing on the declaration and listing its uses — opens nothing +new and pays nothing. Filed as a Handshake request against `index-scope` / +`state.rs`; no scope code was touched. + +**The prefilter, and why it changes no answer.** The new first line of the +overlay loop is `if reference.name != target.name { continue }`. It is sound +because *a `Def` in this index determines the name it is filed under*, and both +sides of the old comparison are filed under a name the code already has in +hand: + +- Every indexed `Def` is pushed into `units[name]` or `members[unit][name]` + under its own declaration's `name`, and both `facts_of` and `collect_members` + skip any declaration whose `name_span` is empty. A non-empty byte range in + one file is one identifier, spelling one name — so two different keys cannot + hold one `Def` value, and `target.def`'s key is `target.name` in both + `indexed_target` arms (the `Local` arm looks the def up *by* `symbol.name` + and stores that as `name`; the `External` arm stores the cursor reference's + own `name`, which is the only key `follow_one` looks a def up under). +- A reference that would have matched is filed under `reference.name`. In the + Local arm, a `Resolution::Resolved` comes from `lookup_local(name)` (or an + end label the binder checked spells the declaration's name), so + `symbol.name == reference.name`, and `indexed_def_in_file` looks up + `units[symbol.name]` / `members[owner][symbol.name]`. In the External arm, + `resolve_external` calls `follow_one(index, reference.name, path)`, which + only ever reads `units[reference.name]` or `member(unit, reference.name)`. + +So `def == target.def` implies `reference.name == target.name`, and skipping +the name-mismatched references skips only work whose answer was `false`. + +**The `Ambiguous` refusal survives it**, by the same step: the candidates in +`ExternalTarget::Ambiguous(defs)` all come out of the bucket keyed by +`reference.name`, so `defs.contains(&target.def)` can only be true for a +reference spelling `target.name` — which the prefilter always lets through. The +`name_span.is_empty()` guard was deliberately *not* hoisted into the prefilter +for the same reason: an ambiguous use aborts the whole collection whether or not +it has a span, and moving that check earlier would have been a real behaviour +change. + +**The hoist.** `indexed_def_for_symbol` is now two functions: the public one +(unchanged signature, still `hover.rs`'s) resolves the document's `FileId` and +calls `indexed_def_in_file`, which takes it as an argument. The overlay loop +takes the `file_id` once per open buffer instead of once per reference. + +**What is left at 110 µs** is the loop itself: 70 024 string comparisons plus +the iteration. Making that sublinear means a name-keyed reference side table in +`Semantics` — the shape `symbols_named` already has for declarations — which is +a `vlog_semantic` change this round's brief put out of scope. Not needed at +110 µs; worth naming as the next lever if a file ten times this size shows up. + +**Tests added** (permanent, all three green before and after the change, which +is the point — the prefilter must change cost and not answers): + +- `a_same_named_port_in_another_open_buffer_is_a_different_symbol` — two + modules declare a port `clk`, all three files open; each port's references + are its own. The prefilter's risk case, from both sides. +- `two_packages_declaring_one_name_keep_their_references_apart` — the same + attack through the member table: `p::WIDTH` and `q::WIDTH` used on adjacent + lines of one open file, asked from the declaration and from the use. +- `every_in_file_occurrence_is_converted_against_its_own_line` — 41 + occurrences over 40 lines each carrying a multi-byte and an astral character; + every reported range is checked to point at the name, and + `documentHighlight`'s ranges are asserted equal to `references`'. A walker + handed spans out of order would answer stale columns here. + +**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets` +zero warnings; `cargo test --workspace` **2 406 passed, 0 failed** (3 ignored +probes in `nav.rs`, one of them pre-existing). Files edited: +`crates/lucisv_server/src/nav.rs` and one `pub(crate)` on `perf::mean`. No new +dependencies, no `unsafe`, no `unwrap`/`expect` outside `#[cfg(test)]`, no new +`#[allow]`. `TODO.md` untouched — this round closes no backlog item; M7 is +already checked. Did not `git commit`/`git push`. + ### 2026-08-27 — indexed navigation performance - Began replacing the per-request `Workspace::sources()` + @@ -270,6 +442,158 @@ Files added: `crates/vlog_refactor/src/references.rs`, ## QA log +### 2026-08-28 — QA agent, references-latency round + +Adversarial charter: try to make the new spelled-name prefilter (`nav.rs:248`, +`indexed_references`) **change an answer**. Slower-but-right was already true; +only a changed answer is a defect this round. + +#### Soundness of the prefilter — traced by construction, not just trusted + +Read the dev's write-up's claim against the actual code that makes it true, +rather than the prose alone: + +- `Def` (`crates/vlog_semantic/src/workspace.rs:33`) derives `PartialEq` over + `(file, name_span, kind, detail_span)` — it carries no name at all. Its + identity is "this declaration, right here," so `def == target.def` can only + be decided by the site it points at, never by a spelling. +- Every `Decl` is filed under exactly one key, its own declared name: + `self.units.entry(decl.name.clone())...push(decl.def(file))` + (`workspace.rs:529`) and `self.members.entry(unit.clone())...entry(decl.name.clone())...push(decl.def(file))` + (`workspace.rs:535-540`). `decl.name` traces back to `Symbol.name` + (`Decl::of`, `workspace.rs:654`), and `Symbol.name`/the scope's `names` map + key are the same `name.to_string()` written in one `declare` call + (`bind.rs:141` and `bind.rs:151`) — so a `Def` cannot be filed under a name + it wasn't declared with, and cannot be filed under two names. +- `Scope::lookup_local` (`model.rs:215`) is a plain `HashMap` `get` — no case-folding, no normalization. Every + `Resolution::Resolved(id)` in `resolve.rs` comes from `lookup_local(&p.name)` + (or `Target::Declaration(id)`, an end label the binder already matched to + its opener's name). `Reference.name` is `p.name.clone()` at the exact + construction site (`lib.rs:78-79`). So a **locally** resolved reference's + `.name` is *definitionally* `symbol.name` — the prefilter reads the same + field the binder used to decide the match, not a second, potentially + divergent, source of truth. +- The **external** arm is the same shape one level up: `resolve_external` + (`workspace.rs:1097`) always calls `follow_paths(index, &reference.name, + paths)`, and `follow_one` (`workspace.rs:1132`) always queries + `index.units(name)` or `index.member(unit, name)` with that same `name` — + `path` only picks *which* table, never the key. So both `Resolved(def)` and + `Ambiguous(defs)` for a reference are always drawn from the bucket keyed by + that reference's own `.name`, which makes the dev's ambiguity-survives + argument mechanical rather than incidental: `defs.contains(&target.def)` + can only be true when `defs` came from the `target.name` bucket, which only + happens when `reference.name == target.name` — exactly what the prefilter + already let through. + +No escaped-identifier or case-folding attack survives this: the lexer +(`crates/vlog_parser/src/lexer.rs:304-318`) keeps an escaped identifier's +leading backslash in the token text (`\sub` and `sub` are different strings +at the token level already), and nothing between the lexer and +`Scope::names` ever folds case or strips it — so whatever the binder already +does or doesn't unify, the prefilter reads the identical field the binder +matched on. There is no code path where `reference.name` and the spelling the +binder used to resolve it can diverge, so there is no daylight for the +prefilter to exploit. Traced, not fuzzed — I did not find a construction +worth writing as a failing-if-regressed test beyond what's below, because the +invariant is enforced by there being exactly one string in play, not by a +check that could later be weakened unnoticed. + +**Verdict on the prefilter: sound, no answer-changing case found.** + +#### Attempts to break it anyway + +- **Port connection vs. declared name, member-table variant.** Extended the + attack beyond the dev's own two tests (`a_same_named_port_in_another_open_buffer_is_a_different_symbol`, + `two_packages_declaring_one_name_keep_their_references_apart`) with a name + that is a **unit in one file and a member in another** — `module W` and + `package p; localparam W = 4;` — plus a **live unsaved edit** to the file + using both (a second instantiation added post-open, never saved). Added as + `indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member` + (`nav.rs:662`), asserted equal to `vlog_refactor::find_references` on + `ws.sources()` (which itself overlays the unsaved edit) in both directions. + Passed first try — no answer conflation between the `units` and `members` + buckets, and the unsaved instantiation is correctly counted. +- **Walker ordering/multi-byte/astral attack** on the two newly-batched + conversion sites (`in_file_references` and `document_highlights`, now both + walker-based per `nav.rs:347` and `nav.rs:374`). The dev's own + `every_in_file_occurrence_is_converted_against_its_own_line` already covers + this shape well (41 occurrences over 40 lines, each preceded by a + multi-byte and an astral character, every reported range checked against + the actual byte); I did not find a shape it misses. The walker itself + (`crates/lucisv_server/src/convert.rs`, `PositionWalker`) is pre-existing, + general-purpose infrastructure (`locations()` has used it since the + 2026-08-27 round) with its own dedicated tests for out-of-order offsets, + ping-ponging between far-apart lines, and an empty document + (`the_walker_agrees_with_the_per_call_converter_on_every_shape`, + `a_walker_handed_offsets_out_of_order_still_answers_the_per_call_position`, + `a_walker_ping_ponged_between_two_far_apart_lines_still_answers_correctly`, + `a_walker_over_an_empty_document_answers_the_one_position_there_is`, all in + `convert.rs`) — so the only new risk this round is whether + `in_file_references`/`document_highlights` feed it spans in order, and they + do: both consume `occurrences()`, which sorts by `span.start` + (`nav.rs:413`) before the walker ever sees them. No out-of-order feed + exists on either path. +- **Ambiguous-abort still aborts.** Re-ran + `a_name_declared_in_two_files_degrades_references_to_the_in_file_answer` + (already in the suite, unmodified by the dev this round) and traced the + `Ambiguous(defs) if defs.contains(&target.def) => return None` arm + (`nav.rs:258-260`) by hand against the bucket argument above: an ambiguous + external use can only carry `target.def` in its candidate set when it + spells `target.name`, which is exactly when the prefilter lets it reach + this arm. Confirmed by construction, not just by the still-green test. +- **Equivalence, existing test.** `indexed_references_equal_the_refactor_walk_they_replace` + (`nav.rs:648`, pre-dating this round) still passes unmodified. + +#### Measurements reproduced (release, `--release`, this machine) + +``` +cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored --nocapture --test-threads=1 +``` + +| what | work log | reproduced here | +|---|---|---| +| references, use site | 110 µs | 109.8 µs | +| references, declaration | 110 µs | 108.9 µs | +| definition, use site | 1.13 µs | 0.82 µs | +| in-file, wire used 3× | 1.20 µs | 1.12 µs | +| in-file, wire used 10 001× | 1.18 ms | 1.17 ms | +| documentHighlight, same wire | 917 µs | 916 µs | +| didOpen, scope already covers | 8.4 µs | 7.3 µs | +| didOpen, new folder (+ rescan) | 220 ms | 214.6 ms | +| rescan alone | 223 ms | 217.7 ms | +| rescan, big buffer closed | 13 ms | 12.5 ms | + +All within the charter's 2-3× tolerance (most within 5%) — no contradiction +of the work log's order-of-magnitude claims. The pre-existing +`qa_indexed_references_latency_over_a_large_workspace` probe (2026-08-27, +untouched by this round) also still ran clean: 0.068 ms/request vs. 31.35 ms +for the old walk on this machine, consistent with that round's own numbers. + +#### Gates + +- `cargo fmt --all -- --check` — clean. +- `cargo clippy --all-targets --all-features` — clean, zero warnings (forced + re-check by `touch`ing the changed files first, not a cache hit). +- `cargo test --workspace` — **2 406 passed, 0 failed** before my addition, + matching the work log's count exactly; **2 407** after adding the one + permanent equivalence test above. 24 ignored across the workspace (3 in + `nav.rs`, one of those pre-existing, matching the work log). + +**All gates: pass, claims confirmed.** + +#### Verdict + +**SHIP.** No corruption, no answer change, no crash found under the +adversarial charter. The prefilter's soundness holds by construction (one +string, read by both the binder and the prefilter, never normalized or +duplicated anywhere in between), not merely by the tests passing. One +permanent regression test added +(`indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member`, +`nav.rs:662`) for the nastier unit/member name-collision case with a live +unsaved edit, requested by the round's brief; no other findings warranted a +fix or a new test. Review section left untouched. + ### 2026-08-24 — QA agent #### Gates @@ -522,6 +846,24 @@ correctness or safety issue in the shipped feature. ## Review +**2026-08-28 — lead, references-latency round.** Reviewed after QA's +clean SHIP; gates re-run independently (fmt clean, clippy silent, 2407 +workspace tests green). Measure-first discipline held: the probes were +written and their before-numbers recorded ahead of any fix, and they +convicted the overlay loop (H1) while acquitting `references` of the +owner-reported asymmetry — which the didOpen numbers (H3) explain +instead, correctly filed as a Handshake request rather than fixed +cross-scope. The prefilter comment in `indexed_references` points at +the soundness argument, QA traced that argument to the code +(single-key filing, no name normalization anywhere between lexer and +lookup), and the unit-vs-member equivalence test QA added is the +sharpest same-spelling case the design admits. The empty-span check +deliberately left unhoisted — so a spanless ambiguous use still aborts +— is the kind of detail that separates a fast loop from a subtly +different one; noted with approval. Accepted; the scope-widening +rescan follow-up (210 ms of re-parsing open buffers) is the next +round. + **2026-08-27 — lead, indexed-navigation performance round (external dev: codex).** Reviewed the full diff line-by-line and ran all three gates independently (fmt clean, clippy silent, 1155 server tests + workspace