From 41945912a3c8bad2499c25c9ee3da7e54ea4d610 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 9 Sep 2026 17:39:23 -0500 Subject: [PATCH] =?UTF-8?q?0.52.0=20review=20fixes=20(=C2=A762):=20F1=20?= =?UTF-8?q?=E2=80=94=20one=20directory-identity=20tracker=20shared=20by=20?= =?UTF-8?q?the=20split=20scan's=20two=20walks,=20a=20pre-check=20that=20ta?= =?UTF-8?q?kes=20the=20single=20canonical=20walk=20when=20an=20alias=20sor?= =?UTF-8?q?ts=20before=20the=20open=20folder,=20a=20conflict=20found=20by?= =?UTF-8?q?=20the=20remaining=20walk=20turned=20into=20one=20ordinary=20re?= =?UTF-8?q?scan,=20the=20open-buffer=20alias=20gate=20on=20both=20walks=20?= =?UTF-8?q?and=20only=20on=20same-named=20files=20(stats=200=20on=20openti?= =?UTF-8?q?tan=20again),=20nine=20alias=20fixtures=20agreeing=20across=20s?= =?UTF-8?q?tartup,=20rescan=20and=20restart;=20F2/F3=20=E2=80=94=20the=20l?= =?UTF-8?q?oad=20probe=20primes=20a=20warm=20store=20untimed=20and=20stamp?= =?UTF-8?q?s=20scan=20completion=20from=20the=20scan's=20own=20end=20event?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 47 ++ crates/lucisv_core/src/walk.rs | 150 +++- crates/lucisv_server/src/scan_trace.rs | 13 +- crates/lucisv_server/src/server/index.rs | 9 + crates/lucisv_server/src/server/tests/mod.rs | 9 + .../lucisv_server/src/server/tests/startup.rs | 377 +++++++++ crates/lucisv_server/src/state/discover.rs | 250 +++++- crates/lucisv_server/src/state/mod.rs | 6 +- crates/lucisv_server/src/state/scan.rs | 47 +- docs/features/perf5r-first-answer/README.md | 784 ++++++++++++++++++ docs/features/perf5r-publication/README.md | 100 +++ docs/features/walk-cycles/README.md | 36 + docs/perf/README.md | 32 + docs/perf/take5-tracking.md | 58 ++ docs/topo.md | 2 +- tools/perf/lspclient.py | 25 +- tools/perf/phases_r4.py | 102 ++- 17 files changed, 1964 insertions(+), 83 deletions(-) diff --git a/TODO.md b/TODO.md index 17f4806..174992f 100644 --- a/TODO.md +++ b/TODO.md @@ -6599,3 +6599,50 @@ sentence; the selection set stays the correctness reference (P2d). topo and status lines done 2026-09-09; **0.52.0** released (b12e0cc, v0.52.0): 8 assets, the darwin-arm64 vsix at 0.52.0 with both binaries, `hierarchySections.js`, `extract.js`, no `*_test.js`. + +## 62. The 0.52.0 review (Codex, 2026-09-09) — F1/F2/F3 and the next lanes + +`docs/performance_052_review.md` (findings F1–F3, next actions 3–5) and +`docs/052_implementation_plan.md` (the other agent's plan; its Phase 1 +was implemented in the tree before the lead saw it) are the spec; the +tracker's "Follow-up findings" and N1–N3 rows are the ledger; evidence in +`docs/perf/review-052-20260909/`. Same protocol as §60/§61. + +### 62.1 F1 — directory aliases in the split startup scan (correctness) + +The neighbourhood walk and the rest walk had separate visited sets, so a +directory reachable by two spellings (`a_alias -> z_real`) was indexed +twice at startup: two definition targets, a false "declared in more than +one file" rename refusal, healed only by a rescan. Fix (the other agent + +the lead's finishing lane): one `DirectoryTracker` shared across both +walks; a pre-check that falls back to the single canonical walk when an +alias sorts before the open folder or an ancestor; the `HEAD_WALK_MAX` +fallback discards the head instead of unioning it; an alias found only +by the rest walk requests an ordinary rescan so path spellings converge; +the open-buffer alias check stats only same-named files. +- [x] tracker shared, pre-check, fallback, conflict → rescan; `stats` 0 + on opentitan again; discovery and the 100-buffer cell unchanged +- [x] fixtures: alias before / after / multiple / ancestor / sibling + (outside the chain) / cycle / ignore rules / unsaved buffer / + genuine duplicate declarations (still refused) — startup, rescan + and restart agree on index paths, definitions and prepareRename +- [x] QA: the matrix re-attacked, stat counts, numbers re-taken + +### 62.2 F2 + F3 — the load probe (harness) + +- [x] F2: a warm `scanload` cell primes an empty store untimed; per-trial + cache hits/misses in the row; a warm trial with 0 hits is an error +- [x] F3: scan completion stamped from the scan's own end event, not the + request window; responses partitioned by it; arrival stamps kept +- [x] QA: a brand-new store, a window longer than the scan + +### 62.3 N1–N3 — deferred to loop 3 unless the owner asks + +N1 the dirty-buffer parse (114 ms first-after-edit), N2 the retained- +analysis parse work and the 31 ms facts decode, N3 the whole-index merge +per publication. Filed with the review's baselines; not started. + +### 62.4 Closing + +- [ ] `docs/perf/README.md` note; topo (the walk tracker); release 0.53.0 + with assets verified diff --git a/crates/lucisv_core/src/walk.rs b/crates/lucisv_core/src/walk.rs index 856120c..556af2a 100644 --- a/crates/lucisv_core/src/walk.rs +++ b/crates/lucisv_core/src/walk.rs @@ -2,7 +2,7 @@ //! `.gitignore` subset documented in //! `docs/features/parallel-files/README.md`. -use std::collections::HashSet; +use std::collections::HashMap; use std::path::{Path, PathBuf}; /// File extensions lucisv formats when walking a directory. @@ -77,18 +77,24 @@ pub fn collect_files_with( gitignore: bool, found: &mut dyn FnMut(PathBuf, Option), warn: &mut dyn FnMut(Warning), +) -> Result<(), String> { + let mut tracker = DirectoryTracker::new(); + collect_files_tracked(input, exclude, gitignore, &mut tracker, found, warn) +} + +/// [`collect_files_with`] using an existing [`DirectoryTracker`]. +pub fn collect_files_tracked( + input: &str, + exclude: &[String], + gitignore: bool, + tracker: &mut DirectoryTracker, + found: &mut dyn FnMut(PathBuf, Option), + warn: &mut dyn FnMut(Warning), ) -> Result<(), String> { let path = Path::new(input); if path.is_dir() { - let mut walk = Walk { - exclude, - gitignore, - ignores: Vec::new(), - rel: Vec::new(), - visited: HashSet::new(), - found, - warn, - }; + let mut walk = + Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), tracker, found, warn }; walk.dir(path); } else if path.is_file() { found(path.to_path_buf(), None); @@ -125,20 +131,27 @@ pub fn collect_files_below( gitignore: bool, found: &mut dyn FnMut(PathBuf, Option), warn: &mut dyn FnMut(Warning), +) -> Result<(), String> { + let mut tracker = DirectoryTracker::new(); + collect_files_below_tracked(root, input, exclude, gitignore, &mut tracker, found, warn) +} + +/// [`collect_files_below`] using an existing [`DirectoryTracker`]. +pub fn collect_files_below_tracked( + root: &Path, + input: &Path, + exclude: &[String], + gitignore: bool, + tracker: &mut DirectoryTracker, + found: &mut dyn FnMut(PathBuf, Option), + warn: &mut dyn FnMut(Warning), ) -> Result<(), String> { let Ok(below) = input.strip_prefix(root) else { return Ok(()) }; if !input.is_dir() { return Err(format!("{}: no such file or directory", input.display())); } - let mut walk = Walk { - exclude, - gitignore, - ignores: Vec::new(), - rel: Vec::new(), - visited: HashSet::new(), - found, - warn, - }; + let mut walk = + Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), tracker, found, warn }; // The root's own `.gitignore` sits at depth 0, exactly where a walk of the // root would have put it. walk.push_ignore(root); @@ -170,24 +183,78 @@ pub fn collect_files_below( /// elsewhere it is the canonical path, which resolves symlinks the same way /// at the cost of a real path lookup. #[cfg(unix)] -type DirId = (u64, u64); +pub type DirId = (u64, u64); #[cfg(not(unix))] -type DirId = PathBuf; +pub type DirId = PathBuf; /// The identity of the directory at `path`, or `None` when it cannot be /// read — a dangling symlink, or a directory that vanished mid-walk. #[cfg(unix)] -fn dir_id(path: &Path) -> Option { +pub fn dir_id(path: &Path) -> Option { use std::os::unix::fs::MetadataExt; let meta = std::fs::metadata(path).ok()?; Some((meta.dev(), meta.ino())) } #[cfg(not(unix))] -fn dir_id(path: &Path) -> Option { +pub fn dir_id(path: &Path) -> Option { std::fs::canonicalize(path).ok() } +/// What happened when attempting to enter a directory with [`DirectoryTracker`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DirStatus { + /// Entered for the first time. + EnteredFirstTime, + /// Already visited under the same or an earlier path. + AlreadyVisited, + /// Previously entered under `recorded`, but `dir < recorded` indicating + /// out-of-order traversal relative to a canonical root walk. + PrecedenceConflict { recorded: PathBuf }, +} + +/// Tracks visited directories across one or more walks to ensure cycle termination +/// and detect order divergence. +#[derive(Debug, Clone, Default)] +pub struct DirectoryTracker { + visited: HashMap, + has_conflict: bool, +} + +impl DirectoryTracker { + /// Creates an empty directory tracker. + pub fn new() -> Self { + Self::default() + } + + /// Records `dir` as entered and returns its [`DirStatus`]. + pub fn enter(&mut self, dir: &Path) -> DirStatus { + let Some(id) = dir_id(dir) else { + return DirStatus::AlreadyVisited; + }; + match self.visited.entry(id) { + std::collections::hash_map::Entry::Vacant(v) => { + v.insert(dir.to_path_buf()); + DirStatus::EnteredFirstTime + } + std::collections::hash_map::Entry::Occupied(o) => { + let recorded = o.get(); + if dir < recorded.as_path() { + self.has_conflict = true; + DirStatus::PrecedenceConflict { recorded: recorded.clone() } + } else { + DirStatus::AlreadyVisited + } + } + } + } + + /// Whether any precedence conflict was observed across walks. + pub fn has_conflict(&self) -> bool { + self.has_conflict + } +} + /// True when `path` names one of the source files lucisv formats. fn is_source(path: &Path) -> bool { path.extension().and_then(|e| e.to_str()).is_some_and(|ext| EXTENSIONS.contains(&ext)) @@ -203,7 +270,7 @@ struct Walk<'a> { gitignore: bool, ignores: Vec, rel: Vec, - visited: HashSet, + tracker: &'a mut DirectoryTracker, /// Where a source file goes when the walk finds one, with the length the /// walk's own `metadata` call already read. found: &'a mut dyn FnMut(PathBuf, Option), @@ -291,7 +358,7 @@ impl Walk<'_> { /// /// A directory whose identity cannot be read is not entered. fn enter(&mut self, dir: &Path) -> bool { - dir_id(dir).is_some_and(|id| self.visited.insert(id)) + matches!(self.tracker.enter(dir), DirStatus::EnteredFirstTime) } /// Reads `dir`'s `.gitignore`, if there is one, onto the rule stack. @@ -963,4 +1030,37 @@ mod tests { assert!(ignored("x?.sv", "x?.sv")); assert!(!ignored("x?.sv", "xa.sv")); } + + #[test] + #[cfg(unix)] + fn tracker_detects_precedence_conflict_when_alias_sorts_before() { + let tree = TempTree::new("trackconflict"); + tree.source("z_real/child.sv"); + tree.link("a_alias", "z_real"); + + let mut tracker = DirectoryTracker::new(); + assert_eq!(tracker.enter(&tree.path.join("z_real")), DirStatus::EnteredFirstTime); + assert!(!tracker.has_conflict()); + + // Entering a_alias afterwards detects that a_alias sorts before z_real + let status = tracker.enter(&tree.path.join("a_alias")); + assert!(matches!(status, DirStatus::PrecedenceConflict { .. })); + assert!(tracker.has_conflict()); + } + + #[test] + #[cfg(unix)] + fn tracker_allows_alias_sorting_after_without_conflict() { + let tree = TempTree::new("trackorder"); + tree.source("a_real/child.sv"); + tree.link("z_alias", "a_real"); + + let mut tracker = DirectoryTracker::new(); + assert_eq!(tracker.enter(&tree.path.join("a_real")), DirStatus::EnteredFirstTime); + assert!(!tracker.has_conflict()); + + // Entering z_alias afterwards: already visited, no precedence conflict + assert_eq!(tracker.enter(&tree.path.join("z_alias")), DirStatus::AlreadyVisited); + assert!(!tracker.has_conflict()); + } } diff --git a/crates/lucisv_server/src/scan_trace.rs b/crates/lucisv_server/src/scan_trace.rs index 05c5f8e..18a3aeb 100644 --- a/crates/lucisv_server/src/scan_trace.rs +++ b/crates/lucisv_server/src/scan_trace.rs @@ -198,6 +198,14 @@ pub struct ScanTrace { /// Taking every open buffer's text and its finished analysis, and letting /// it override the disk copy of its own path. pub buffers_ms: f64, + /// Directories the remaining walk met under a spelling the root walk + /// would have preferred — a directory alias outside the open folder's own + /// chain ([`crate::state::Scan::wants_rescan`]). 0 in every ordinary + /// session; 1 says this scan's paths are the head's spelling. + pub conflict: usize, + /// Whole rescans this scan asked for on its way out. One per `conflict`, + /// and nothing else sets it. + pub rescan_requested: usize, /// Sorting into index order and putting the user's own neighbourhood at /// the front ([`crate::scan_order`]). @@ -444,7 +452,8 @@ impl ScanTrace { "scan {} counts ({}): read={} read_kib={} walk_dirs={} stats={} skipped={} \ hits={} misses={} buffers={} \ records={} repeats={} decoded_kib={} written_kib={} opens={} compactions={} \ - publishes={} published={} first_publish={:.2} overlays={}", + publishes={} published={} first_publish={:.2} overlays={} \ + conflict={} rescan_requested={}", self.number, self.kind, self.read, @@ -465,6 +474,8 @@ impl ScanTrace { self.published, self.first_publish_ms, self.overlays, + self.conflict, + self.rescan_requested, ) } diff --git a/crates/lucisv_server/src/server/index.rs b/crates/lucisv_server/src/server/index.rs index fd8e551..c27f073 100644 --- a/crates/lucisv_server/src/server/index.rs +++ b/crates/lucisv_server/src/server/index.rs @@ -300,6 +300,15 @@ impl Server { } let total = scan.total(); let (skipped, cached) = (scan.skipped(), scan.cached()); + // A split discovery whose two halves reached one directory by two + // spellings: nothing was indexed twice, and every answer this scan + // gives is the right one, but the paths are the head's and a plain + // walk of the same tree spells them the other way + // ([`Scan::wants_rescan`]). One ordinary rescan *is* that plain walk, + // so it converges them — asked for with the same flag a save or a + // settings change sets, and therefore run when this scan ends, with + // every request held for the whole of it. + self.rescan_wanted |= scan.wants_rescan(); let warnings = self.workspace.finish_scan(scan); self.end_indexing(bar, skipped, cached); self.timed(started, |took| { diff --git a/crates/lucisv_server/src/server/tests/mod.rs b/crates/lucisv_server/src/server/tests/mod.rs index def3dcf..df03ed1 100644 --- a/crates/lucisv_server/src/server/tests/mod.rs +++ b/crates/lucisv_server/src/server/tests/mod.rs @@ -99,6 +99,15 @@ impl Tree { } std::fs::write(&path, text).expect("write"); } + + #[cfg(unix)] + fn link(&self, rel: &str, target: &str) { + let path = self.path.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("parent"); + } + std::os::unix::fs::symlink(target, &path).expect("symlink"); + } } impl Drop for Tree { diff --git a/crates/lucisv_server/src/server/tests/startup.rs b/crates/lucisv_server/src/server/tests/startup.rs index 1311654..395e3b2 100644 --- a/crates/lucisv_server/src/server/tests/startup.rs +++ b/crates/lucisv_server/src/server/tests/startup.rs @@ -57,6 +57,16 @@ fn the_whole_workspace() -> Value { serde_json::json!({ "index": { "scope": "workspace", "logFiles": true } }) } +/// [`the_whole_workspace`] with the folder scope's raise turned off, so the +/// folder a split leads with is the open buffer's own directory — the +/// settings `docs/performance_052_review.md` F1 reproduces with, and what +/// every alias fixture below needs to reach the split at all. +fn the_whole_workspace_flat() -> Value { + serde_json::json!({ + "index": { "scope": "workspace", "scopeDepth": 0, "logFiles": true } + }) +} + /// A `textDocument/didOpen` over the wire, as the client sends it. fn did_open(path: &Path, text: &str) -> Message { Message::Notification(Notification::new( @@ -1109,3 +1119,370 @@ fn a_rescan_does_not_lead_with_a_folder_because_nothing_may_be_answered_inside_i "and the exclusion took one file out" ); } + +// ---------------------------------------------------------------------- +// Directory aliases across a split discovery (F1) +// ---------------------------------------------------------------------- +// +// A symlinked directory gives every file under it a second path, and a walk +// reports each file under the **first spelling that reaches it** +// (`docs/features/walk-cycles/README.md`). The startup scan walks the user's +// own folder before it walks the workspace, so the two halves must share that +// rule or one module lands in the index twice and cannot be renamed — the +// regression `docs/performance_052_review.md` F1 found and every fixture here +// pins. +// +// Each one makes the same three asks of the same tree — after the startup +// scan, after a whole rescan, and of a fresh session — and they must agree. + +/// The testbench every fixture opens: it names `child`, which is what the +/// definition and the rename below are asked about. +#[cfg(unix)] +const TB: &str = "module tb;\n child u();\nendmodule\n"; + +/// A `child` module and the testbench that instantiates it, in `dir`. +#[cfg(unix)] +fn alias_pair(tree: &Tree, dir: &str) { + tree.write(&format!("{dir}/child.sv"), "module child;\nendmodule\n"); + tree.write(&format!("{dir}/tb.sv"), TB); +} + +/// Where `child` is named in [`TB`] — the cursor every claim below is made at. +#[cfg(unix)] +fn at_child(uri: &Uri) -> Value { + serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": 1, "character": 3 }, + }) +} + +/// What one session says about a fixture: which files the index holds, where +/// the definition of `child` goes, whether that name may be renamed, and what +/// the open buffer's diagnostics are. +/// +/// The four together are the review's acceptance: a duplicate shows up as a +/// second file, as a second target, and as a refusal to rename — and every +/// answer the index feeds moves with it, which is what the diagnostics are +/// here to catch. +#[cfg(unix)] +#[derive(Debug, PartialEq)] +struct Says { + files: Vec, + defs: Vec, + renamable: bool, + diagnostics: Vec, +} + +#[cfg(unix)] +fn says(session: &mut Session, uri: &Uri) -> Says { + let answer = session.result(GotoDefinition::METHOD, at_child(uri)); + let defs: Vec = serde_json::from_value(answer).expect("definition targets"); + let prepared = session.request(PrepareRenameRequest::METHOD, at_child(uri)); + let files = + session.server.workspace.index().files().iter().map(|p| p.display().to_string()).collect(); + // The `resultId` is a generation counter and moves with every rebuild, so + // what is compared is what the user sees: each diagnostic's sentence and + // where it points. + let report = document_pull(session, uri, None); + let items = report["items"].as_array().cloned().expect("a full diagnostic report"); + let diagnostics = items + .into_iter() + .map(|item| serde_json::json!({ "message": item["message"], "range": item["range"] })) + .collect(); + Says { files, defs, renamable: prepared.response_result.is_ok(), diagnostics } +} + +/// Index `tree` with `opened` open, then ask a whole rescan and a fresh +/// session the same four questions. Reports what all three said. +/// +/// The rescan trigger is the review's own: a watched-file notification naming +/// more than one in-scope file is the whole rebuild rather than the one-file +/// incremental path (`server/notification.rs`). No source byte changes, so a +/// disagreement is the scan disagreeing with itself. +#[cfg(unix)] +fn startup_rescan_and_restart_agree(tree: &Tree, opened: &Path, text: &str) -> Says { + let uri = path_to_uri(opened).expect("uri"); + let fresh = || { + let session = Session::staged( + vec![tree.path.clone()], + pulling(), + true, + CONFIGURATION_WAIT, + vec![configuration_answer(the_whole_workspace_flat()), did_open(opened, text)], + ); + session.drain(); + session + }; + let mut session = fresh(); + let startup = says(&mut session, &uri); + let changed: Vec = startup.files.iter().map(PathBuf::from).collect(); + assert!(changed.len() > 1, "the whole-rebuild trigger names more than one file"); + session.watched(&changed); + session.drain(); + let rescan = says(&mut session, &uri); + let restart = says(&mut fresh(), &uri); + assert_eq!(startup, rescan, "the startup scan and a whole rescan must agree"); + assert_eq!(startup, restart, "the startup scan and a fresh session must agree"); + startup +} + +#[test] +#[cfg(unix)] +fn an_alias_sorting_before_its_target_is_indexed_once_under_the_root_walks_spelling() { + // The review's own reproduction. A walk of the root reaches `a_alias` + // first, so `a_alias/child.sv` is the canonical spelling and the head — + // which would lead with `z_real` — must not be led with at all. + let tree = Tree::new("aliasbefore"); + alias_pair(&tree, "z_real"); + tree.link("a_alias", "z_real"); + let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("z_real/tb.sv"), TB); + assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs); + assert!(said.renamable, "a module declared once may be renamed"); + assert!( + said.files.iter().any(|file| file.ends_with("a_alias/child.sv")), + "the root walk's own spelling: {:#?}", + said.files + ); + assert!(said.diagnostics.is_empty(), "and nothing is wrong with it: {:#?}", said.diagnostics); +} + +#[test] +#[cfg(unix)] +fn an_alias_sorting_after_its_target_leaves_the_head_leading() { + // Nothing precedes `a_real`, so this one keeps the split — and the + // remaining walk must still recognise `z_alias` as the folder it has. + let tree = Tree::new("aliasafter"); + alias_pair(&tree, "a_real"); + tree.link("z_alias", "a_real"); + let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("a_real/tb.sv"), TB); + assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs); + assert!(said.renamable, "a module declared once may be renamed"); + assert!( + said.files.iter().any(|file| file.ends_with("a_real/child.sv")), + "the target's own spelling: {:#?}", + said.files + ); +} + +#[test] +#[cfg(unix)] +fn several_aliases_of_one_directory_contribute_one_copy_between_them() { + let tree = Tree::new("multialias"); + alias_pair(&tree, "real"); + tree.link("a1_alias", "real"); + tree.link("a2_alias", "real"); + tree.link("z_alias", "real"); + let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("real/tb.sv"), TB); + assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs); + assert!(said.renamable, "three aliases are still one declaration"); + assert_eq!(said.files.len(), 2, "one child, one buffer: {:#?}", said.files); +} + +#[test] +#[cfg(unix)] +fn an_alias_of_an_ancestor_of_the_open_folder_falls_back_to_the_one_walk() { + // The head would lead with `z_real/sub`, but the root walk reaches the + // whole of `z_real` through `a_link` — so the folder's *ancestors* are + // what the check has to look at, not the folder alone. + let tree = Tree::new("aliasancestor"); + alias_pair(&tree, "z_real/sub"); + tree.link("a_link", "z_real"); + let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("z_real/sub/tb.sv"), TB); + assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs); + assert!(said.renamable, "a module declared once may be renamed"); + assert!( + said.files.iter().any(|file| file.ends_with("a_link/sub/child.sv")), + "the root walk's own spelling: {:#?}", + said.files + ); +} + +#[test] +#[cfg(unix)] +fn an_ancestor_cycle_inside_the_neighbourhood_ends_and_names_each_file_once() { + // `sub/up -> ..` is a link out of the neighbourhood and back to the top, + // so the head walk finds the root's own file under `sub/up/top.sv` while + // a walk of the root spells it `top.sv`. One spelling reaches the index, + // and the rescan the conflict asks for is what settles which. + let tree = Tree::new("ancestorcycle"); + alias_pair(&tree, "sub"); + tree.write("top.sv", "module top;\nendmodule\n"); + tree.link("sub/up", ".."); + let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("sub/tb.sv"), TB); + assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs); + assert!(said.renamable, "the cycle did not duplicate `child`"); + assert_eq!(said.files.len(), 3, "child, top and the buffer: {:#?}", said.files); + assert!( + said.files.iter().any(|file| file.ends_with("/top.sv") && !file.contains("/up/")), + "the root's file under the root's own spelling: {:#?}", + said.files + ); +} + +#[test] +#[cfg(unix)] +fn an_ignored_alias_is_excluded_by_both_halves_of_the_scan() { + let tree = Tree::new("ignorealias"); + tree.write(".gitignore", "a_alias/\n"); + alias_pair(&tree, "z_real"); + tree.link("a_alias", "z_real"); + let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("z_real/tb.sv"), TB); + assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs); + assert!(said.renamable, "a module declared once may be renamed"); + assert!( + said.files.iter().all(|file| !file.contains("a_alias")), + "the ignored alias is in nobody's scope: {:#?}", + said.files + ); +} + +#[test] +#[cfg(unix)] +fn an_open_unsaved_buffer_is_not_indexed_again_under_an_alias() { + // The buffer is `z_real/tb.sv` and the walk's own spelling of it is + // `a_alias/tb.sv`: two paths, one file, and an index holding both would + // hold `tb` twice while showing the user only one of them. + let tree = Tree::new("unsavedalias"); + alias_pair(&tree, "z_real"); + tree.link("a_alias", "z_real"); + let unsaved = "module tb;\n child u();\n localparam UNSAVED = 1;\nendmodule\n"; + let opened = tree.path.join("z_real/tb.sv"); + let said = startup_rescan_and_restart_agree(&tree, &opened, unsaved); + assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs); + assert!(said.renamable, "`child` is declared once"); + assert_eq!(said.files.len(), 2, "one child, one buffer: {:#?}", said.files); + + // And the buffer's own name, which is the one the alias would have + // duplicated: renamable, and the unsaved text is what was indexed. + let uri = path_to_uri(&opened).expect("uri"); + let mut session = Session::staged( + vec![tree.path.clone()], + pulling(), + true, + CONFIGURATION_WAIT, + vec![configuration_answer(the_whole_workspace_flat()), did_open(&opened, unsaved)], + ); + let _ = session.drain(); + let at_tb = serde_json::json!({ + "textDocument": { "uri": &uri }, + "position": { "line": 0, "character": 8 }, + }); + let prepared = session.request(PrepareRenameRequest::METHOD, at_tb); + assert!(prepared.response_result.is_ok(), "one `tb`: {:?}", prepared.response_result); +} + +#[test] +#[cfg(unix)] +fn a_genuine_duplicate_declaration_is_still_ambiguous_at_startup_and_after_a_rescan() { + // The other side of the fix, and the reason deduplicating by *name* was + // never an option: two physical files really do declare `dup`, and a + // rename that picked one of them would be a wrong edit. + let tree = Tree::new("legitdup"); + tree.write("dir1/dup.sv", "module dup;\nendmodule\n"); + tree.write("dir2/dup.sv", "module dup;\nendmodule\n"); + let opened = tree.path.join("dir1/dup.sv"); + let text = std::fs::read_to_string(&opened).expect("read"); + let uri = path_to_uri(&opened).expect("uri"); + let at_dup = serde_json::json!({ + "textDocument": { "uri": &uri }, + "position": { "line": 0, "character": 8 }, + }); + + let mut session = Session::staged( + vec![tree.path.clone()], + pulling(), + true, + CONFIGURATION_WAIT, + vec![configuration_answer(the_whole_workspace()), did_open(&opened, &text)], + ); + session.drain(); + let refused = session.request(PrepareRenameRequest::METHOD, at_dup.clone()); + let error = refused.response_result.expect_err("two declarations are ambiguous"); + assert!(error.message.contains("declared in more than one indexed file"), "{}", error.message); + + session.watched(&[opened.clone(), tree.path.join("dir2/dup.sv")]); + session.drain(); + let again = session.request(PrepareRenameRequest::METHOD, at_dup); + let rescanned = again.response_result.expect_err("a rescan refuses it the same way"); + assert_eq!(rescanned.message, error.message, "the same sentence, word for word"); +} + +#[test] +#[cfg(unix)] +fn an_alias_beside_the_open_folder_indexes_once_and_asks_for_one_rescan() { + // The case no pre-check can see: `other/link` is nowhere on the open + // folder's own chain, so the head leads with `z_real` and only the + // remaining walk finds out that a walk of the root would have spelled + // those files `other/link/…`. Nothing is indexed twice — and the scan + // asks for the canonical walk once, which is where the spelling + // converges. + let tree = Tree::new("siblingalias"); + alias_pair(&tree, "z_real"); + tree.link("other/link", "../z_real"); + let opened = tree.path.join("z_real/tb.sv"); + let uri = path_to_uri(&opened).expect("uri"); + + let mut session = Session::staged( + vec![tree.path.clone()], + pulling(), + true, + CONFIGURATION_WAIT, + vec![configuration_answer(the_whole_workspace_flat()), did_open(&opened, TB)], + ); + let messages = session.drain(); + let traces = trace_lines(&messages); + let counts: Vec<&String> = traces.iter().filter(|line| line.contains(" counts (")).collect(); + assert_eq!(counts.len(), 2, "the startup scan and the one rescan it asked for: {traces:#?}"); + assert_eq!(field(counts[0], "conflict"), "1", "{}", counts[0]); + assert_eq!(field(counts[0], "rescan_requested"), "1", "{}", counts[0]); + assert_eq!(field(counts[1], "conflict"), "0", "the rescan is one whole walk: {}", counts[1]); + assert_eq!( + field(counts[1], "rescan_requested"), + "0", + "and it cannot ask for another: {}", + counts[1] + ); + + // What the startup indexed, from the per-file log: the head's spelling, + // one copy of `child`, and no `other/link` beside it. + let indexed: Vec = + log_lines(&messages).into_iter().filter(|line| line.contains("child.sv")).collect(); + assert_eq!(indexed.len(), 2, "one `child` per scan, never two: {indexed:#?}"); + assert!(indexed[0].contains("z_real/child.sv"), "the startup's spelling: {}", indexed[0]); + assert!(indexed[1].contains("other/link/child.sv"), "the rescan's: {}", indexed[1]); + + // And what the rescan left: the spelling a plain walk of this tree gives, + // which is what every later scan and every restart will produce. + let said = says(&mut session, &uri); + assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs); + assert!(said.renamable, "`child` is declared once"); + assert!( + said.files.iter().any(|file| file.ends_with("other/link/child.sv")), + "the canonical spelling won: {:#?}", + said.files + ); + let plain = startup_rescan_and_restart_agree(&tree, &opened, TB); + assert_eq!(said, plain, "and it is stable under a rescan and a restart"); +} + +#[test] +#[cfg(unix)] +fn a_same_named_file_symlink_outside_the_head_is_not_a_second_copy_of_the_buffer() { + // QA's (f) on §62.1: the head walk asked `Aliased` about a same-named + // file, the remaining walk did not, so a file symlink to the open buffer + // living outside its folder was indexed a second time and `tb` was + // falsely declared twice. Now both walks ask. + let tree = Tree::new("filealias"); + alias_pair(&tree, "z_real"); + tree.link("alias_dir/tb.sv", "../z_real/tb.sv"); + let said = startup_rescan_and_restart_agree(&tree, &tree.path.join("z_real/tb.sv"), TB); + assert_eq!( + said.files.iter().filter(|file| file.ends_with("tb.sv")).count(), + 1, + "one `tb.sv`, the buffer's: {:#?}", + said.files + ); + assert_eq!(said.defs.len(), 1, "one definition target: {:#?}", said.defs); + assert!(said.renamable, "`tb` is declared once, whatever the disk spells"); + assert!(said.diagnostics.is_empty(), "{:#?}", said.diagnostics); +} diff --git a/crates/lucisv_server/src/state/discover.rs b/crates/lucisv_server/src/state/discover.rs index d2aae42..f0ea2e3 100644 --- a/crates/lucisv_server/src/state/discover.rs +++ b/crates/lucisv_server/src/state/discover.rs @@ -21,13 +21,28 @@ //! session with a buffer open walks that buffer's own folders first, so the //! scan can index and publish them before it discovers the other 3 850 files //! ([`Workspace::first_scope`]). One scan, one work list, every file once. +//! +//! **"Every file once" is a claim about directory identity, not about paths.** +//! A symlinked directory gives every file under it a second path, and a walk +//! answers that by entering each directory identity once and reporting its +//! files under the first spelling that reached it +//! (`docs/features/walk-cycles/README.md`). Two walks with two visited sets do +//! not have that rule *between* them, which is how the split came to index a +//! module twice (`docs/performance_052_review.md` F1). So the two halves share +//! one [`DirectoryTracker`]; the head is not led with at all when a walk of the +//! root would reach the user's own folder by an earlier name +//! ([`Workspace::has_preceding_alias`]); and where only the remaining walk can +//! find that out, it says so and the scan asks for one canonical walk +//! ([`Scan::wants_rescan`](super::Scan::wants_rescan)). use std::collections::{HashMap, HashSet}; use std::fs; use std::path::{Path, PathBuf}; use lucisv_core::config::Discovery; -use lucisv_core::walk::{collect_files_below, collect_files_with, EXTENSIONS}; +use lucisv_core::walk::{ + collect_files_below_tracked, collect_files_tracked, dir_id, DirectoryTracker, EXTENSIONS, +}; use crate::scan_trace::ScanTrace; @@ -93,6 +108,53 @@ pub(super) fn oversize(found: &Found, cap: u64, stats: &mut usize) -> Option cap).then_some(size) } +/// The open buffers' files by **identity**, so a walked path that is a second +/// spelling of one of them can be recognised and left out. +/// +/// A symlinked directory gives every file under it a second path. The walk +/// reports each file under the first spelling that reaches it, which may not be +/// the one the buffer was opened by — and an index holding `a_alias/tb.sv` from +/// disk beside the open `z_real/tb.sv` holds one module twice and refuses to +/// rename it (`docs/features/walk-cycles/README.md`). +/// +/// **The name is the gate, and it is what keeps this free.** A directory alias +/// cannot change a file's *name*, so a walked file whose name no open buffer +/// shares cannot be one of them and is never stat'd: an ordinary workspace pays +/// nothing at all, and one with same-named files pays one `metadata` per +/// same-named candidate. A **file**-level symlink under a different name is out +/// of scope — two names for one inode that no directory relates, which every +/// other part of this server already treats as two files. +struct Aliased { + /// The names those buffers' files go by — the cheap half of the test. + names: HashSet, + /// Their `(dev, ino)` identities, read once per open buffer rather than + /// once per walked file. + ids: HashSet, +} + +impl Aliased { + /// The identities of `paths`, with the names to gate on. + fn of(paths: &HashSet<&Path>) -> Aliased { + let names = paths.iter().filter_map(|p| p.file_name()).map(|n| n.to_os_string()).collect(); + let ids = paths.iter().filter_map(|p| dir_id(p)).collect(); + Aliased { names, ids } + } + + /// Whether `path` names a file an open buffer already speaks for, by a + /// different spelling. `stats` counts the `metadata` calls it made. + fn speaks_for(&self, path: &Path, stats: &mut usize) -> bool { + if self.ids.is_empty() { + return false; + } + let Some(name) = path.file_name() else { return false }; + if !self.names.contains(name) { + return false; + } + *stats += 1; + dir_id(path).is_some_and(|id| self.ids.contains(&id)) + } +} + impl Workspace { /// Resolve the scope: which files are in it, with open buffers overriding /// disk, and those buffers' own text. @@ -144,6 +206,9 @@ impl Workspace { // skipped exactly as it did before the buffer put its own text back. let spoken_for: HashSet<&Path> = self.docs.values().filter_map(|doc| doc.path.as_deref()).collect(); + // …and every *other* spelling of those same files, which a directory + // alias makes and a path comparison cannot see ([`Aliased`]). + let aliased = Aliased::of(&spoken_for); let capping = trace.now(); let mut stats = 0usize; let mut files: Vec = Vec::new(); @@ -155,6 +220,9 @@ impl Workspace { if spoken_for.contains(found.path.as_path()) { continue; } + if aliased.speaks_for(&found.path, &mut stats) { + continue; + } files.push(found.path); } ScanTrace::add(&mut trace.cap_ms, capping); @@ -301,6 +369,19 @@ impl Workspace { dirs: &[PathBuf], warn: &mut dyn FnMut(String), trace: &mut ScanTrace, + ) -> Vec { + let mut tracker = DirectoryTracker::new(); + self.walked_files_tracked(dirs, &mut tracker, warn, trace) + } + + /// [`Workspace::walked_files`] over an existing [`DirectoryTracker`], so + /// two walks of one scan enter each directory identity once between them. + pub(super) fn walked_files_tracked( + &self, + dirs: &[PathBuf], + tracker: &mut DirectoryTracker, + warn: &mut dyn FnMut(String), + trace: &mut ScanTrace, ) -> Vec { let mut discovery = Discovery::new(true); let mut out: Vec = Vec::new(); @@ -326,10 +407,11 @@ impl Workspace { // is skipped and said — the warning rides out on the scope's own // warnings, which `server/notification.rs` logs once per scan. let walking = trace.now(); - let _ = collect_files_with( + let _ = collect_files_tracked( input, &exclude, true, + tracker, &mut |path, len| out.push(Found { path, len }), &mut |w| warn(w.to_string()), ); @@ -441,25 +523,59 @@ impl Workspace { if trace.number > 1 || !self.splits_discovery() { return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None); } + // A directory alias that a root walk would reach *before* the folder + // the head would lead with: leading with it would spell those files a + // way no other scan of this workspace ever does + // ([`Workspace::has_preceding_alias`]). The whole scope, walked once, + // is the answer — a millisecond on a fixture and ~155 ms on + // opentitan, and only for a session whose own folder is aliased. + for dir in self.raised_dirs() { + if let Some(root) = self.deepest_root(&dir) { + if self.has_preceding_alias(&root, &dir) { + return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None); + } + } + } let mut warnings: Vec = Vec::new(); - let head = self.neighbourhood_files(&mut |w| warnings.push(w), trace); + let mut tracker = DirectoryTracker::new(); + let head = self.neighbourhood_files(&mut tracker, &mut |w| warnings.push(w), trace); + if head.len() > HEAD_WALK_MAX { + // Too big to lead with unproven. The head is **discarded** and the + // whole scope walked once, ordered the way every scan before this + // one was: keeping it and walking the rest beside it would union + // two walks that never agreed on a directory's spelling, which is + // the very thing the tracker exists to prevent. + return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None); + } // Every path the neighbourhood walk named, before the cap has had a // say: what the remaining walk must not decide about a second time. let mut seen: HashSet = head.iter().map(|found| found.path.clone()).collect(); seen.extend(self.docs.values().filter_map(|doc| doc.path.clone())); - if head.len() > HEAD_WALK_MAX { - // Too big to lead with unproven. Finish the walk now and hand back - // the whole scope, ordered the way every scan before this one was. - let (mut files, rest_warnings, _) = self.walked_rest(&seen, trace); - warnings.extend(rest_warnings); - files.extend(head); - sort_found(&mut files); - let scope = Scope { files, incdirs: Vec::new(), warnings }; - return (self.overlay_buffers(scope, watch, HeldAnalyses::Wanted, trace), None); - } let scope = Scope { files: head, incdirs: Vec::new(), warnings }; let sources = self.overlay_buffers(scope, watch, HeldAnalyses::Wanted, trace); - (sources, Some(PendingDiscovery { roots: self.roots.clone(), seen })) + (sources, Some(PendingDiscovery { roots: self.roots.clone(), seen, tracker })) + } + + /// Whether some directory between `root` and `dir` holds a **second + /// spelling** of `dir` or of one of its ancestors that a walk of `root` + /// would reach *first*. + /// + /// The one case the split cannot lead with. A walk of the root reports + /// each directory under the first path that reaches it, in name order, so + /// with `a_alias -> z_real` the whole of `z_real` is spelled `a_alias/…`; + /// a head walk starting at `z_real` would spell it `z_real/…` and the two + /// halves of one scan would disagree with each other and with every later + /// rescan. Asked before the head is walked, so the answer is a *fallback* + /// to the single canonical walk and never a repair afterwards. + /// + /// **It reads directories and stats symlinks only.** The chain from a + /// buffer's folder to the root is a handful of directories (four on + /// opentitan, ~150 entries between them); `read_dir` already carries each + /// entry's kind, so an ordinary tree costs no `metadata` at all. + fn has_preceding_alias(&self, root: &Path, dir: &Path) -> bool { + let targets = identities_to(root, dir); + !targets.is_empty() + && ancestors_to(root, dir).into_iter().any(|up| precedes_a_target(up, &targets)) } /// The user's own neighbourhood, walked: every source file under the @@ -474,6 +590,7 @@ impl Workspace { /// halves of one scan would disagree about which files exist. fn neighbourhood_files( &self, + tracker: &mut DirectoryTracker, warn: &mut dyn FnMut(String), trace: &mut ScanTrace, ) -> Vec { @@ -489,11 +606,12 @@ impl Workspace { exclude.extend(self.client.exclude.iter().cloned()); ScanTrace::add(&mut trace.config_ms, configuring); let walking = trace.now(); - let _ = collect_files_below( + let _ = collect_files_below_tracked( &root, &dir, &exclude, true, + tracker, &mut |path, len| out.push(Found { path, len }), &mut |w| warn(w.to_string()), ); @@ -517,36 +635,45 @@ impl Workspace { .cloned() } - /// The roots walked, less what `seen` already names — the walk half of - /// [`Workspace::rest_of_scope`], with no cap and no reporting. - fn walked_rest( - &self, - seen: &HashSet, - trace: &mut ScanTrace, - ) -> (Vec, Vec, usize) { - let mut warnings: Vec = Vec::new(); - let walked = self.walked_files(&self.roots, &mut |w| warnings.push(w), trace); - let kept: Vec = - walked.into_iter().filter(|found| !seen.contains(&found.path)).collect(); - let count = kept.len(); - (kept, warnings, count) - } - /// The rest of the workspace: everything the roots hold that `seen` does /// not already name, capped and reported exactly as the neighbourhood was. /// /// Returns the files to index, what the walk wants said, and how many the /// cap kept out. Open buffers are **not** folded in again — they were - /// folded into the head, and a buffer's path is in `seen`. + /// folded into the head, and a buffer's path is in `pending.seen`. + /// + /// **It walks with the head's own directory identities.** The tracker is + /// the one the neighbourhood filled, so a directory the head already + /// entered is not entered again under an alias and no file is discovered + /// twice. Where this walk reaches such a directory under a spelling the + /// root walk would have *preferred*, the tracker says so + /// ([`DirectoryTracker::has_conflict`]) and the caller asks for one + /// ordinary rescan, which is that root walk. pub(super) fn rest_of_scope( &self, - roots: &[PathBuf], - seen: &HashSet, + pending: &mut PendingDiscovery, watch: &mut dyn FnMut(IndexEvent), trace: &mut ScanTrace, ) -> (Vec, Vec, usize) { + let (roots, seen) = (&pending.roots, &pending.seen); let mut warnings: Vec = Vec::new(); - let walked = self.walked_files(roots, &mut |w| warnings.push(w), trace); + let walked = self.walked_files_tracked( + roots, + &mut pending.tracker, + &mut |w| warnings.push(w), + trace, + ); + // The same gate the neighbourhood applied: a file an open buffer + // already speaks for, reached here by **another** spelling (a + // same-named file symlink outside the head), must not be indexed a + // second time. The buffer's own spelling is not an alias — a buffer + // opened mid-scan is discovered here for the first time and must land + // in the work list — so the gate is asked only about other paths. + // Found by QA on §62.1, twice: the head walk had the gate and this walk + // did not; then the gate matched a mid-scan buffer against itself. + let spoken_for: HashSet<&Path> = + self.docs.values().filter_map(|doc| doc.path.as_deref()).collect(); + let aliased = Aliased::of(&spoken_for); let cap = self.client.max_file_size; let capping = trace.now(); let mut stats = 0usize; @@ -556,7 +683,10 @@ impl Workspace { // Already decided about by the neighbourhood: indexed, capped out, // or spoken for by an open buffer. Deciding again would step a // file twice or report one skip as two. - if seen.contains(&found.path) { + let another_spelling = !spoken_for.contains(found.path.as_path()); + if seen.contains(&found.path) + || (another_spelling && aliased.speaks_for(&found.path, &mut stats)) + { continue; } if let Some(size) = oversize(&found, cap, &mut stats) { @@ -572,6 +702,56 @@ impl Workspace { } } +/// The identity of `dir` and of every directory between it and `root` — what +/// a second spelling would have to name to matter ([`Workspace::has_preceding_alias`]). +/// +/// `root` itself is not among them: a walk of the root enters it before it +/// reads anything, so nothing it holds can precede it. +fn identities_to(root: &Path, dir: &Path) -> Vec<(lucisv_core::walk::DirId, PathBuf)> { + let mut out = Vec::new(); + let mut at = dir; + while at != root { + if let Some(id) = dir_id(at) { + out.push((id, at.to_path_buf())); + } + let Some(parent) = at.parent() else { break }; + at = parent; + } + out +} + +/// The directories a walk of `root` reads on its way down to `dir`: its +/// parent, that one's parent, and so on up to and including `root`. +fn ancestors_to<'a>(root: &'a Path, dir: &'a Path) -> Vec<&'a Path> { + let mut out = Vec::new(); + let mut at = dir.parent(); + while let Some(parent) = at { + out.push(parent); + if parent == root { + break; + } + at = parent.parent(); + } + out +} + +/// Whether `dir` holds a symlink to one of `targets` under a name that sorts +/// before the target's own path — the entry a root walk would follow first. +fn precedes_a_target(dir: &Path, targets: &[(lucisv_core::walk::DirId, PathBuf)]) -> bool { + let Ok(entries) = fs::read_dir(dir) else { return false }; + entries.flatten().any(|entry| { + // Only a symlink can be a second spelling of a directory, and the kind + // is the one `read_dir` already read — so the stat below happens once + // per link in the chain and never once per entry. + if !entry.file_type().is_ok_and(|kind| kind.is_symlink()) { + return false; + } + let path = entry.path(); + let Some(id) = dir_id(&path) else { return false }; + targets.iter().any(|(target, spelling)| id == *target && path < *spelling) + }) +} + /// Path order, one entry per path — what the walk's callers have always done /// with the paths of several overlapping directory walks. /// diff --git a/crates/lucisv_server/src/state/mod.rs b/crates/lucisv_server/src/state/mod.rs index a68e3e9..30520d4 100644 --- a/crates/lucisv_server/src/state/mod.rs +++ b/crates/lucisv_server/src/state/mod.rs @@ -898,7 +898,7 @@ impl Workspace { /// waits (`docs/features/indexing-ux/README.md`). So this discovers, says /// "there is more", and lets the next step be an ordinary one. fn discover_the_rest(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool { - let Some(pending) = scan.take_pending() else { return false }; + let Some(mut pending) = scan.take_pending() else { return false }; let discovering = scan.trace.now(); let mut skipped = 0usize; let (files, warnings, walked_skips) = { @@ -908,11 +908,11 @@ impl Workspace { } watch(event); }; - self.rest_of_scope(&pending.roots, &pending.seen, &mut counting, &mut scan.trace) + self.rest_of_scope(&mut pending, &mut counting, &mut scan.trace) }; debug_assert_eq!(skipped, walked_skips, "the cap reports every skip it counts"); ScanTrace::add(&mut scan.trace.discovery_ms, discovering); - scan.land_discovery(files, warnings, walked_skips); + scan.land_discovery(files, warnings, walked_skips, pending.tracker.has_conflict()); scan.trace.measure_work( scan.work.len(), held_bytes(&scan.buffered), diff --git a/crates/lucisv_server/src/state/scan.rs b/crates/lucisv_server/src/state/scan.rs index eff5776..bc6fb0a 100644 --- a/crates/lucisv_server/src/state/scan.rs +++ b/crates/lucisv_server/src/state/scan.rs @@ -168,6 +168,17 @@ pub(super) struct PendingDiscovery { /// one it names here has already been decided about, and deciding twice /// would step a file twice or report one skip as two. pub(super) seen: HashSet, + /// Every directory identity the neighbourhood walk entered, and the path + /// it entered each one by. + /// + /// **The two walks share it, and that is what makes them one walk.** An + /// ordinary walk visits each directory identity once and reports its files + /// under the first spelling that reached it + /// (`docs/features/walk-cycles/README.md`); two walks with two sets would + /// report a symlinked directory's files twice, under two spellings a path + /// set cannot tell apart, and the index would hold every module in it + /// twice. Sharing the tracker restores that contract across the split. + pub(super) tracker: lucisv_core::walk::DirectoryTracker, } /// How many records may be staged before another mid-scan publish is worth the @@ -277,9 +288,40 @@ impl Scan { self.pending.take() } + /// Whether this scan's answers are right but **spelled** differently from + /// what a plain walk of the same tree would spell them, so one ordinary + /// rescan is owed. + /// + /// The case: a directory alias outside the open folder's ancestor chain — + /// `other/link -> z_real`, with `other` sorting first. The head leads with + /// `z_real`; the remaining walk meets `other/link`, recognises the + /// directory the head already entered and skips it, so nothing is + /// discovered twice and every answer this scan gives is one target and one + /// file. But a walk of the root on its own — the next rescan, or a session + /// that opens nothing — spells those same files `other/link/…`, and a + /// startup that disagreed with every later scan about a path is the defect + /// this whole tracker exists to close (`docs/performance_052_review.md` + /// F1). So the scan asks for the canonical walk once it has landed, and + /// the spelling converges there. + /// + /// **Exactly one rescan can ever come of it.** Only a session's first scan + /// splits its discovery ([`Workspace::first_scope`]), so the scan this + /// asks for resolves its whole scope in one walk, has no + /// [`PendingDiscovery`], and cannot ask again. + /// + /// The answer is the trace's own counter, which is written whether or not + /// anybody asked for a trace — like `publishes`, it is a fact about the + /// scan rather than a stopwatch reading, so it lives where the scan's + /// facts live and the `--verbose` count line says it out loud. + pub fn wants_rescan(&self) -> bool { + self.trace.rescan_requested > 0 + } + /// Fold the rest of the scope into this scan: its files onto the end of /// the work list, its paths into the set the include graph learns from, - /// its warnings and its skips onto the scan's own. + /// its warnings and its skips onto the scan's own — and whether the walk + /// that found them disagreed with the head about a directory's spelling + /// ([`Scan::wants_rescan`]). /// /// Appended rather than re-ordered: the neighbourhood at the front has /// already been stepped, and `vlog_semantic::IndexBuilder` sorts by path @@ -290,7 +332,10 @@ impl Scan { files: Vec, warnings: Vec, skipped: usize, + conflict: bool, ) { + self.trace.conflict += usize::from(conflict); + self.trace.rescan_requested += usize::from(conflict); self.paths.extend(files.iter().cloned()); self.paths.sort(); self.paths.dedup(); diff --git a/docs/features/perf5r-first-answer/README.md b/docs/features/perf5r-first-answer/README.md index 55a9b09..7e272a2 100644 --- a/docs/features/perf5r-first-answer/README.md +++ b/docs/features/perf5r-first-answer/README.md @@ -102,6 +102,54 @@ below-walk, by `a_walk_that_starts_below_a_root_still_obeys_that_roots_gitignore and `a_negation_below_the_root_still_wins_over_the_root_rule`, both of which assert equality with the whole-root walk restricted to that subtree. +#### Amended 2026-09-09 (F1) — a third entry, and the identity the split owes + +The two entries above promised the same *filters* across the split and said +nothing about **directory identity**, which is the other half of what a walk +of the root decides: it enters each identity once and reports its files under +the first spelling that reaches it (`docs/features/walk-cycles/README.md`). +Two walks with two visited sets do not have that between them, so a symlinked +directory reached by both was indexed twice — the review's finding F1 +(`docs/performance_052_review.md`). The identity is now a value the caller +owns and hands to both walks: + +```rust +/// Every directory identity a walk has entered, and the path it entered +/// each one by. Shared between two walks, they behave as one. +pub struct DirectoryTracker { /* … */ } + +impl DirectoryTracker { + pub fn new() -> Self; + /// Record `dir`, and say whether it is new, already seen, or already + /// seen under a path this one sorts *before* — which is the root walk's + /// own choice, and so a disagreement about spelling. + pub fn enter(&mut self, dir: &Path) -> DirStatus; + /// Whether any `enter` reported `PrecedenceConflict`. + pub fn has_conflict(&self) -> bool; +} + +pub enum DirStatus { EnteredFirstTime, AlreadyVisited, PrecedenceConflict { recorded: PathBuf } } + +pub type DirId = /* (dev, ino) on unix, the canonical path elsewhere */; +pub fn dir_id(path: &Path) -> Option; + +pub fn collect_files_tracked(input, exclude, gitignore, tracker, found, warn) -> Result<(), String>; +pub fn collect_files_below_tracked(root, input, exclude, gitignore, tracker, found, warn) + -> Result<(), String>; +``` + +Still additive: `collect_files_with` and `collect_files_below` keep their +signatures and are two-line wrappers that make a tracker of their own, so a +single walk behaves exactly as it always did — `enter` is the same +insert-if-absent test, with a second answer for the caller that asked for one. + +**What this promises the server:** one tracker across the neighbourhood walk +and the remaining walk means one directory identity entered once between them, +so no file is discovered under two spellings and the union of the two walks is +the set a single root walk yields. Where the remaining walk *does* reach an +identity by a path the root walk would have preferred, `has_conflict` says so +and the server rescans (below); nothing is duplicated either way. + ### `lucisv_server` internals - **`crate::state::discover`** is a new child module of `crate::state`: `Found`, @@ -143,6 +191,19 @@ assert equality with the whole-root walk restricted to that subtree. ### Requests for the lead (`docs/topo.md` is not edited by this lane) +0. **2026-09-09, F1.** The `lucisv_server ──▶ lucisv_core` walk row already + carries the tracker (another agent amended it before this lane started; the + row is not this lane's file and was left alone). Two sentences are still + owed there, and the lead owns them: **(a)** what the tracker promises is + that the two walks of one scan enter each directory identity once *between* + them, so a `lucisv_core` change that gave `enter` a different answer for a + second spelling would silently un-fix F1; **(b)** the tracker's + `has_conflict` is a **server-visible** outcome now — `state/mod.rs` reads it, + `Scan::wants_rescan` reports it and `server/index.rs` turns it into one + ordinary rescan — so it is a handshake and not an internal detail. Nothing + outside `lucisv_server` calls the tracked entries; the CLI still calls + `collect_files`. + 1. `lucisv_server ──▶ lucisv_core` (walk): **`collect_files_with` and `collect_files_below`**, both additive, `collect_files` unchanged and now a wrapper. The server's cap reads the walk's own `metadata`; its @@ -596,6 +657,133 @@ guarded `cargo test --workspace` green. `state/mod.rs` **1 069 → 978**: it did not grow, and the new logic went into a new module as the brief required. +### 2026-09-09 — dev (Opus), F1 finished + +**F1 is closed.** The split discovery keeps the walk's directory identity +across both halves, the one case it cannot lead with falls back to the single +canonical walk before the head is walked, and the one case nothing can see +ahead of time converges on an ordinary rescan. Nothing about the ordering or +the first-answer numbers moved. + +**What the fix is, in four parts.** + +1. **One tracker, two walks.** `DirectoryTracker` (above, Handshakes) is made + in `first_scope`, filled by `neighbourhood_files`, carried on + `PendingDiscovery`, and handed to the remaining walk by `rest_of_scope`. A + directory identity is entered once between them, so the two halves cannot + report one directory's files under two spellings and the path-only `seen` + set no longer has to recognise something a path cannot. +2. **A pre-check, and a fallback that discards.** `has_preceding_alias` asks, + *before* the head is walked, whether any directory between the open + buffer's folder and its root holds a symlink to that folder or one of its + ancestors under a name a root walk reaches first (`a_alias -> z_real`). + If it does, the head would spell those files a way no other scan ever + does, so the scan resolves its whole scope in one walk instead. The + `HEAD_WALK_MAX` fallback now **discards** the head and does the same: it + used to union the head with an independently-discovered rest, which was + the bug wearing a second hat. +3. **A conflict is acted on.** An alias outside that ancestor chain — + `other/link -> z_real`, `other` sorting first — is invisible to any + pre-check: the head leads with `z_real` and only the remaining walk finds + out. The tracker refuses to enter the directory a second time (so nothing + is duplicated and every answer the startup gives is right), reports + `has_conflict`, and `scan_once` sets `rescan_wanted` on the way out. That + is the flag a save or a settings change sets, so the canonical walk runs + when this scan ends, under `must_wait`, and the spelling converges there. + Exactly one rescan can come of it: only a session's *first* scan splits. + The `--verbose` count line says `conflict=1 rescan_requested=1`. +4. **An open buffer's aliases.** A buffer opened as `z_real/tb.sv` whose walk + spelling is `a_alias/tb.sv` used to put both in the index — one module + twice, and a `tb` that could not be renamed. `overlay_buffers` now drops a + walked file whose `(dev, ino)` is an open buffer's, in **one** place + rather than two. + +**And it costs nothing.** The alias test is gated on the file's *name*: a +directory alias cannot rename a file, so a walked file whose name no open +buffer shares is never stat'd. Measured on opentitan (`counts` line, +`stats=`): **0** on every workspace cell with 0 or 1 open buffers, cold and +warm — the 3 976-`metadata` regression the first draft of this fix had is +gone — and **58** in the 2-buffer cell whose head holds 58 files named +`tb.sv`/`aes.sv`, which is the bound the gate promises and about 0.06 ms. A +file-level symlink under a *different* name is out of scope and stays two +files, as it is everywhere else in this server. + +**The pre-check's own cost, measured.** It reads the four directories between +`hw/ip/aes/dv` and the root and stats only the entries `read_dir` already +called symlinks, so an ordinary tree costs no `metadata` at all. On opentitan +it is the unattributed remainder of `discovery` (`discovery` minus +`config+walk+filelist+sort+cap+buffers`): **0.10 → 0.27 ms**, i.e. ~0.17 ms, +once per session. + +**Paired against 0.52.0** (both release servers built here; opentitan +`0098135`, three known modified files unchanged; guard 8 GiB/1 800 s +throughout; load 4.1–6.8): + +| Cell | 0.52.0 | F1 | | +|---|---:|---:|---| +| Workspace scan, cold | 2 878.9 | 2 886.0 | +0.2 % | +| Workspace scan, warm | 1 044.2 | 1 039.6 | −0.4 % | +| First useful definition, cold | 82.0 | 81.9 | −0.1 % | +| First useful definition, warm | 115.6 | 117.5 | +1.6 % | +| `discovery`, workspace warm, 1 buffer | 179.2 | 162.2 | −9 % | +| `stats`, same cell | 0 | **0** | | +| Settle, 1 / 10 / 100 open buffers | 1 100 / 1 098 / 1 251 | 1 134 / 1 074 / 1 218 | | +| Warm idle RSS, KiB | 427 856 | 426 048 | | + +Every row is within noise of 0.52.0 and of the round's own targets (~80/115 ms +first answer, ~1.0 s warm settle, ~155 ms discovery, ~1 170 ms at 100 +buffers). Rows in `~/.cache/lucisv-perf/f1/results.jsonl`. + +**Tests.** The seven fixtures the first draft added are refactored behind one +helper — `startup_rescan_and_restart_agree`, which indexes the tree, asks the +same four questions (index paths, definition targets, prepareRename, and the +open buffer's pulled diagnostics by sentence and range) of the startup scan, +of a whole rescan a watched-file burst triggers, and of a fresh session, and +asserts the three agree — so each fixture is its shape and its +own claims and nothing else. Nine of them, all `#[cfg(unix)]`: alias sorting +before its target, alias sorting after, several aliases of one directory, an +alias of an *ancestor* of the open folder, an ancestor cycle +(`sub/up -> ..`) with a file at the root the head would otherwise spell +`sub/up/top.sv`, an ignored alias, an open unsaved buffer, a genuine +duplicate declaration (still refused, same sentence, at startup and after the +rescan), and the sibling alias — which asserts the trace's +`conflict=1 rescan_requested=1`, that exactly two scans ran and the second +asked for nothing, that the per-file log names one `child.sv` per scan under +the head's spelling then the root walk's, and that the index after the rescan +is what a rescan and a restart also give. Every fixture needs +`index.scopeDepth: 0` to reach the split at all — the default raise of 2 puts +the folder *at* the root, where the split is refused: that is the review's own +reproduction setting, and `the_whole_workspace_flat()` is it. + +**Gates.** `cargo fmt` clean; guarded `cargo clippy --workspace --all-targets +--locked -- -D warnings` clean, no new `#[allow]`; guarded +`cargo test --workspace --locked` **4 385 passed, 0 failed, 45 ignored** +(4 374 at 0.52.0, + 2 `DirectoryTracker` unit tests in `lucisv_core`, + 9 +alias fixtures in place of the first draft's 7). + +**File sizes** (non-blank, non-comment, before `mod tests`): +`state/discover.rs` **406** (329 at 0.52.0), `state/scan.rs` 135, +`scan_trace.rs` 326, `server/index.rs` 226, `lucisv_core/src/walk.rs` 332 — +all under 600. `state/mod.rs` **980 → 980**: it did not grow. The conflict +rides out on `Scan::land_discovery`, which the one caller already called, and +lives on the scan's own trace counter beside `publishes` rather than as a +second copy of the same fact. + +**Deviation from the plan.** Step 1.1 names `DirectoryTracker::is_visited` / +`record_or_check` and a `WalkIdentity` struct; the shipped shape is `enter` → +`DirStatus` and `has_conflict`, because the caller needs to tell "already +seen" from "already seen under a path this one would have beaten", and a +borrow of the recorded path is not something a walk can hold while walking. +The plan's fallback is unchanged; the conflict follow-through (part 3 above) +is beyond the plan, and is what makes startup and rescan agree in the case no +pre-check can see. + +**Assumption recorded.** A buffer opened *mid-scan*, after the scope was +resolved, is not put through the alias test — its disk copy is already in the +work list under whatever spelling the walk gave it. That is 0.52.0's +behaviour and 0.51.0's, it is a `Scan::reorder`/`open_next` question rather +than a discovery one, and no fixture here changes it. + ## QA log ### 2026-09-08 — QA (Sonnet), §61.3 @@ -793,6 +981,561 @@ store open). Recommend also applying the `HEAD_WALK_MAX` test I built (this QA log, above) as a topo-neutral addition to `state/mod.rs`'s existing test module when the lane next touches that file. +### 2026-09-09 — independent 0.52.0 review: directory-alias regression + +**Finding F1 (P2), open.** The split discovery does not preserve the ordinary +walk's directory-identity deduplication across its independent head/root +walks. A scratch workspace with `a_alias -> z_real`, a `child` module and a +testbench in `z_real`, workspace scope and depth 0, produces two definition +targets at startup in 0.52.0 versus one in 0.51.0. `prepareRename` then falsely +refuses an ambiguous `child`. A whole rescan with unchanged source restores +one target and accepts prepareRename. Initial lookup comparison: 3/3 sessions +per version; full startup/rescan lifecycle: another 3/3 per version. + +The issue is the path-only `seen` set in `state/discover.rs::first_scope` +combined with independent `Walk.visited` sets, not ignore-rule inheritance. +The `HEAD_WALK_MAX` fallback also unions the independently discovered head. +No implementation was changed. [Full review, reproduction and repair gates](../../performance_052_review.md#f1--p2--split-startup-discovery-duplicates-modules-behind-directory-aliases), +[raw evidence](../../perf/review-052-20260909/README.md). + +### 2026-09-09 — QA (Sonnet), TODO §62.1: REWORK — the rest-of-scope walk is not gated + +**Verdict: REWORK.** F1's own fix is real and reproduces cleanly for every +shape the dev's nine fixtures name, but the open-buffer alias gate +(`Aliased`/`overlay_buffers`, Handshakes part 4) is wired into only *one* +of the two places a split scan's files come from, and a crafted attack +beyond the nine fixtures gets a false ambiguous-rename refusal through the +gap. Findings below; nothing else broke. + +**Gates, guarded, main tree.** `cargo fmt --all -- --check` clean. +`cargo clippy --all-targets --locked -- -D warnings` clean, no new +`#[allow]`. `cargo test --workspace --locked`: **4 385 passed, 0 failed, 45 +ignored** — exactly the dev's claimed 4 374 (0.52.0) + 2 tracker unit tests ++ 9 alias fixtures; I did not re-run the suite against a fresh 3ceba21 +clone myself, but the independent review (`docs/performance_052_review.md`, +"Independent validation") already recorded 4 374/0/45 at that commit, so +the arithmetic is corroborated rather than assumed. Production line counts +(non-blank/non-comment, before `mod tests`): `discover.rs` **405** (claimed +406), `walk.rs` **332** (claimed 332, exact), `state/mod.rs` **980 → 980** +(exact, net zero as claimed), `scan.rs` **134** (claimed 135) — all within +one line of the dev's count and all comfortably under the 600 mark; no +finding. + +**The review's own reproduction, on both binaries.** Built candidate +(`cargo build --release -p lucisv_server`, main tree) and 0.52.0 (fresh +`git archive v0.52.0` into my scratchpad, built there — not the review's +leftover `/tmp` binary). Ran an adapted `symlink_lifecycle.py` (the +review's own fixture, `a_alias -> z_real`, workspace/depth-0, `z_real/ +tb.sv` open) against both, 3 trials each: + +| | 0.52.0 | candidate | +|---|---|---| +| Definition after startup | 2 targets (`a_alias` + `z_real`), 3/3 | 1 target (`a_alias`), 3/3 | +| prepareRename after startup | refused, "declared in more than one indexed file", 3/3 | accepted, 3/3 | +| After the watched-file rescan | 1 target, accepted, 3/3 | 1 target, accepted, 3/3 | + +Matches the review's table exactly — the finding was real, and the +candidate fixes the reproduction as claimed. + +**The matrix (a)–(i), attacked in a fresh clone (`git archive HEAD` + +`git apply` of the working-tree diff) under my scratchpad, never the dev's +tree.** Nine new fixtures appended to a scratch copy of `server/tests/ +startup.rs` (not shipped; QA-only): + +- (a) alias to a directory **outside** the workspace root: today's + behaviour is to follow it (the external `child.sv` is indexed and + becomes the definition target) — pinned stable across startup/rescan/ + restart, not asserted as correct either way, since the spec is silent on + it. +- (b) alias to the workspace root itself from inside (`sub/root_link -> + ..`): one copy of every file, same shape as the shipped ancestor-cycle + fixture — ok. +- (c) two buffers, one in an aliased folder, one not: both resolve/rename + correctly — ok. +- (d) alias created **after** startup, converged by a watched-file rescan: + one copy, one target, renamable — ok. +- (e) a broken symlink beside the open folder: no crash, contributes no + file — ok. (My first attempt at this fixture named its own tree + `qadangling`, so a bare substring check on `"dangling"` matched the tree's + own temp-dir name and produced a false failure; renamed the fixture and + confirmed — a QA harness bug, not a product one, fixed in my own scratch + copy only.) +- (f) **FAILS.** A *file*-level symlink sharing an open buffer's basename, + placed outside the buffer's own head-walked folder + (`alias_dir/tb.sv -> ../z_real/tb.sv`, buffer open at `z_real/tb.sv`, + workspace/depth-0 so the scan splits): the index ends up with **two** + `tb.sv` entries (`alias_dir/tb.sv` and `z_real/tb.sv`) and + `textDocument/prepareRename` on `tb` is refused: `"lucisv: \`tb\` is + declared in more than one indexed file"`. This is a false positive of + exactly the shape F1 exists to close, and it sits inside F1's own stated + scope — the README's Handshakes text says the open-buffer alias check + "drops a walked file whose `(dev, ino)` is an open buffer's, in **one + place** rather than two" and stats only same-named files. Root cause: the + `Aliased` gate lives only in `Workspace::overlay_buffers` + (`crates/lucisv_server/src/state/discover.rs:194`), and `overlay_buffers` + is called from exactly two places — `collect_sources` (the non-split, + whole-workspace path) and `first_scope`'s **head**-only branch (line + ~555). `Workspace::rest_of_scope` + (`crates/lucisv_server/src/state/discover.rs`, the function added by this + round for the split's second walk) filters its output only against the + cap and the head's own `seen` path set — never against `Aliased` — so a + same-named file-level alias discovered by the *remaining* walk (i.e. + anywhere outside the buffer's own immediate folder, which on a real + workspace is nearly everything) is not deduplicated at all. + `Scan::land_discovery`/`PendingDiscovery` carry no such check either. The + dev's own measured "58" (`stats`, the 2-buffer opentitan cell) is + consistent with this: I reproduced `stats=58` on that exact cell + (`scanprofile`, "workspace warm, 1 open buffer" — 2 buffers total once + the harness's always-open default is counted) and it is generated + entirely inside the head-only `overlay_buffers` call, so it is not + evidence the gate covers the rest of the workspace — it demonstrates the + opposite once the code path is traced. Impact: not merely a spurious + refusal — since the "walked" copy is read fresh from disk while the + buffer's overlay text can differ (unsaved edits), a workspace with such + an alias can silently carry two *different* bodies for what the editor + believes is one open file, which is a masked-duplication risk squarely + inside CLAUDE.md's "never corrupt code" invariant's neighbourhood, not + just a UX refusal. +- (g) file-level symlink under a **different** name: stays two files, + consistent across startup/rescan/restart — matches the documented + out-of-scope behaviour — ok. +- (h) genuine duplicates behind an alias of a *different* real directory + (`a/child.sv`, `b/child.sv`, `link_a -> a`): still refused, ambiguous, + identically before and after a rescan — the tracker does not collapse + two genuinely different directory identities just because one of them is + reached through an alias — ok. +- (i) the sibling-alias rescan's follow-through: confirmed by code reading + (`server/index.rs::scan_once`, `self.rescan_wanted |= scan.wants_rescan()` + runs *after* the scan-stepping loop, so `must_wait()` — which reads + `rescan_wanted` — is already true for anything arriving between this + scan's end and the rescan's end) and by a wire test that drains the + startup scan and its self-triggered rescan fully, then asserts + `!rescan_wanted && !must_wait()` and that the settled answer is the + *rescanned* (canonical) spelling, never the head's — ok. I did not build + a harness that injects a request mid-rescan (the staged test harness has + no hook to pause between the two scans), so this is the outcome + `must_wait` protects, confirmed, rather than an interleaved-request + reproduction. + +**Stats and the gate sabotage.** `scanprofile` on opentitan, candidate, +`--tries 1`: `stats=0` at 0 extra buffers (workspace cold/warm, default +scope, depth0) and at 10/100 extra buffers; `stats=58` at "1 open buffer" +(2 buffers total, matching the dev's reported cell and number exactly); +`discovery` 150–197 ms depending on cell, within the dev's ~162 ms claim. +Sabotage: commented out the name-check in `Aliased::speaks_for` +(`state/discover.rs:149-152`) in my scratch clone, rebuilt release, reran +the same cells: `stats` jumped to **123** (0/10-extra-buffer default-scope +cells), **3974/3970** (1/10-buffer workspace cells) — confirming the name +gate is exactly what keeps the head-scope cost near zero when it is +wired in. (This sabotage does not contradict finding (f) above — it shows +the gate works *where it is called*, which is the head only.) + +**The conflict follow-through and its sabotage.** Confirmed by reading +`server/index.rs::scan_once` (line ~311): `self.rescan_wanted |= +scan.wants_rescan()` sits after the scan-stepping `loop { … }`, so the +held first answer is not delayed by it. Sabotage: commented out that one +line in my scratch clone, rebuilt, reran the shipped +`an_alias_beside_the_open_folder_indexes_once_and_asks_for_one_rescan` +fixture: it fails as expected — `left: 1, right: 2` ("the startup scan and +the one rescan it asked for"), i.e. no follow-up rescan ever runs even +though `conflict=1 rescan_requested=1` is recorded on the trace. Restored +both sabotaged files immediately after each experiment; diffed clean +against the working tree afterwards. + +**Controls (§61/P4), candidate vs a freshly-built 0.52.0, both from +scratch clones, `scanwait`, 3 tries each on opentitan:** first useful +definition cold 80.4 / 81.2 ms median (candidate/0.52.0, essentially +equal); warm 115.9 / 115.3 ms; the answering session's own scan cold +2732.7 / 2697.6 ms (+1.3%); warm 1036.8 / 996.7 ms (+4.0%). All within the +±10% band; no regression. + +**Traceability.** Checked 12 numbers from the dev's table and prose +against `~/.cache/lucisv-perf/f1/results.jsonl`: workspace scan cold/warm +2878.9/2886.0 and 1044.2/1039.6, first useful answer cold/warm samples +around 81.9–82.3 and 115.6–117.6, `discovery` 179.2/162.2 (`stages. +discovery`/`stages.walk`), the 1/10/100-buffer settle triple 1100/1098/1251 +(0.52.0) and 1134/1074/1218 (f1), and warm idle RSS 427856/426048 — every +one is present verbatim in that file, against the row its label says. + +**Topo.** The two sentences the dev's Handshakes section said were owed to +the lead (the tracker's cross-walk promise, and `has_conflict` being +server-visible) are **already in `docs/topo.md`**'s `lucisv_server ──▶ +lucisv_core` row as of this diff — nothing outstanding there. What *is* +now owed, given finding (f): a sentence (or a Handshakes amendment) saying +the open-buffer alias gate's actual scope is the split's head only, not +the whole scan, until `rest_of_scope`/`land_discovery` are given the same +check — otherwise the topo row's promise ("no file is discovered under two +spellings") overstates what the shipped code does for file-level aliases +outside the head. + +**opentitan**: `git -C .../opentitan status --porcelain` checked before, +during and after every phase — always exactly the three pre-existing +modified files. **Guard**: every cargo/test/build/bench invocation (main +tree and both scratch clones) ran through `tools/guard.sh -m 8 -t …`; no +kills. No lingering background processes or poll loops left running at +session end. Fixed directly (no code changes needed): none — finding (f) +is a design gap, not a small unambiguous fix, and is left for the dev. + +**TODO §62.1's QA line is left unchecked.** Recommend: extend the +`Aliased` check (or an equivalent identity filter) to `rest_of_scope`'s +output before it lands in the scan, add fixture (f) above to the shipped +suite, and re-run this QA pass. + +### 2026-09-09 — QA (Sonnet), TODO §62.1 re-verification: REWORK — a newly-opened buffer's own file can vanish from the index + +**Verdict: REWORK.** The lead's fix for finding (f) is itself correct — the +sibling-alias/file-symlink matrix is green, sabotage confirms the gate is +load-bearing, and the specific reproduction QA's last pass filed is closed. +But the fix as shipped introduces a **new, more severe** regression: the +same `Aliased` check that now runs in `Workspace::rest_of_scope` can drop a +just-opened buffer's own real file from the scan entirely — not duplicate +it, not misspell it, **omit it** — so that module is silently absent from +the index for the rest of that scan. This is closer to CLAUDE.md's "never +corrupt code" neighbourhood than finding (f) was: (f) produced a spurious +*second* copy; this produces *zero* copies. + +**How it was found.** Guarded `cargo test --workspace --locked` in a fresh +clone (`git archive HEAD` at `3ceba21` + `git apply` of the working-tree +diff, under my scratchpad, never the dev's tree) is **not green**: + +``` +failures: + state::tests::a_file_opened_mid_scan_lengthens_the_neighbourhood_it_jumps_into +test result: FAILED. 1663 passed; 1 failed; 36 ignored; 0 measured +``` + +This is a **pre-existing, dev-authored** fixture (`state/mod.rs:4062`, +untouched by this diff — it has nothing to do with aliases) that opens a +second buffer mid-scan and checks the neighbourhood segment length. I +confirmed it is not flaky: 5/5 deterministic failures in the diffed clone, +5/5 deterministic passes in an undiffed clone built from the same `3ceba21` +snapshot with no diff applied. It is a genuine regression of this round's +change, not noise. + +**Root cause, isolated by instrumentation** (temporary `eprintln!`s in my +scratch clone only, reverted immediately after — diffed clean against the +shipped patch both times, confirmed byte-identical). The failing fixture +opens `ip/aes/dv/tb/tb.sv`, steps one file, then opens +`ip/uart/rtl/uart.sv` and calls `Workspace::open_next` +(`state/mod.rs:1544`), which unconditionally calls `discover_the_rest` +(`state/mod.rs:900`) before reordering — this part is unchanged by the +current diff and is correct. `discover_the_rest` calls the new +`rest_of_scope(&mut pending, …)` (`state/discover.rs:652`). Printing +`scan.remaining()` right after `open_next` returns: **`uart.sv` is not in +the work list at all** — 10 files instead of the 11 the tree holds beyond +the one already stepped. A second probe confirmed the consequence directly: +after `finish_scan`, `ws.index().units("uart_pkg").len()` is **0** — the +buffer's own module was never indexed by this scan. + +The mechanism: `rest_of_scope`'s new gate (`state/discover.rs:682`, +`if seen.contains(&found.path) || aliased.speaks_for(&found.path, &mut +stats)`) builds `aliased` from **every currently-open buffer's path** +(`spoken_for`, line ~672) at the moment the remaining walk runs — which is +*after* `uart.sv` was opened. When the walk discovers `uart.sv` for the +first time, `Aliased::speaks_for` matches it by name ("uart.sv") and then +by identity (`dir_id` — trivially equal, since it's checking the file +against *itself*) and reports it "spoken for", so it is dropped from +`files` and never reaches `scan.work`. `rest_of_scope` has **no equivalent** +of `overlay_buffers`'s own re-add step (`state/discover.rs:246`, +`files.retain(|p| p != &path); … files.push(path)`), which is what makes +the identical-looking check safe in `overlay_buffers` (line 216) but unsafe +here: `overlay_buffers` drops a spoken-for path and then unconditionally +puts every open buffer's path back at the end; `rest_of_scope` only ever +drops. Before this round's fix, `rest_of_scope` had no `Aliased` check at +all, so `uart.sv` passed through untouched, landed in `scan.work`, and was +read fresh off disk when stepped (correct, if by luck rather than by the +buffer's own text) — matching 0.52.0. This round's extension of the gate to +`rest_of_scope` is what turned that "correct by luck" path into a silent +drop, precisely because `Aliased::speaks_for` cannot distinguish "a second +spelling of a file already accounted for" (the case it exists to catch) +from "the first and only discovery of a buffer that was opened after the +head walk ran" (a case its own docstring assumes cannot happen — +`rest_of_scope`'s comment says "a buffer's path is in `pending.seen`", true +only when nothing opened between `first_scope` and `discover_the_rest`, +which is exactly what `Workspace::open_next` exists to falsify). + +**Not an isolated fixture problem.** None of the round's own 9+2 alias +fixtures (nor my (j)/(k) below) exercise a `didOpen` arriving *during* a +still-pending split discovery, so none of them could have caught this. The +two existing mid-scan-`didOpen` fixtures +(`a_did_open_that_beats_the_answer_is_folded_into_the_one_scan_and_indexed_ +first`, `a_did_open_answered_mid_scan_pulls_its_folder_in_front_of_the_ +request_behind_it`) check that a request is answered and that reordering +happens; neither asserts the newly-opened file's own module actually lands +in the finished index, which is why the workspace suite's *only* red light +is the one unrelated fixture that happens to count work-list length. + +**Left for the dev, not redesigned by QA.** Two directions, either owed a +decision: (a) minimal — in `rest_of_scope`, an exact path match against +`spoken_for` (the buffer's own real path, first discovery) must not be +treated as "already handled" the way a *different*-path same-identity match +is; it needs to still land in `scan.work` (`overlay_buffers` already draws +this distinction at line 216 before ever consulting `Aliased`, `rest_of_ +scope` does not). (b) more complete — a buffer opened after the head walk +has no entry in `scan.buffered`, so even a naive fix that re-includes such a +path indexes it by re-reading disk rather than the buffer's own text +(harmless in this fixture, which has no unsaved edit, but a live regression +of `docs/features/index-scope/README.md`'s "the buffer's text overrides +disk" rule the moment there is one) — `discover_the_rest`/`land_discovery` +have no path today to feed a newly-discovered buffer's text into +`scan.buffered`. + +**Sabotage of the fix under review — still holds.** Removed the +`aliased.speaks_for(&found.path, &mut stats)` half of `state/ +discover.rs:682` (leaving only `seen.contains`), rebuilt, reran the shipped +fixture `a_same_named_file_symlink_outside_the_head_is_not_a_second_copy_ +of_the_buffer`: **fails** as required — `left` (startup) shows three files +including `alias_dir/tb.sv`, `right` (rescan) shows two — the startup/ +rescan disagreement finding (f) named exactly. Restored; diffed byte- +identical against the shipped patch afterwards. + +**The matrix (a)–(k), fresh clone, same method as last time.** All of (a) +through (i) reconfirmed passing (33 `startup::` tests green as a block, +`--test-threads=4`). Two new fixtures added to a scratch copy of `server/ +tests/startup.rs` (QA-only, not shipped): +- **(j)** a same-named file symlink *inside* the head folder + (`z_real/sub/tb.sv -> ../tb.sv`, buffer open at `z_real/tb.sv`) — + exercises the **head's own** gate (`overlay_buffers`, `state/ + discover.rs:223`) rather than `rest_of_scope`'s: passes, one `tb.sv`, one + target, renamable. +- **(k)** a same-named but genuinely *different* file outside the head + (`other/tb.sv`, declaring `othertb`, a different inode) — passes: two + distinct `tb.sv` paths indexed, `other/tb.sv` present, one `child` + target. Confirms `speaks_for`'s identity check (not just the name check) + is what keeps a real second file from being dropped — the finding above + is specifically about a *self*-match (buffer vs. its own first-time + discovery), not a false positive on an unrelated same-named file. + +Both new fixtures pass; the alias-specific behaviour this round targets is +correct. The regression is orthogonal to the alias matrix and sits in the +interaction with mid-scan `didOpen`. + +**Stats — measured, and the "still 0" expectation does not hold.** +`scanprofile` on opentitan, candidate build (`cargo build --release +--locked -p lucisv_server`), `--tries 1`, guarded: + +| cell (harness label) | total open buffers | `stats` | `walk_dirs` | `discovery` ms | +|---|---:|---:|---:|---:| +| workspace, cold | 1 (`tb.sv` only) | **58** | 2 | 208.5 | +| workspace, warm | 1 | **58** | 2 | 169.1 | +| workspace warm, "1 open buffer" | 2 | **58** | 3 | 200.4 | +| workspace warm, "10 open buffers" | 11 | **58** | 3 | 199.0 | +| workspace warm, "100 open buffers" | 101 | **58** | 3 | 197.7 | +| default / depth0, cold+warm | 1 | 0 | 0–1 | ≤2.6 | + +**With only `tb.sv` open, `stats` is 58, not 0.** The dev's original F1 +work-log number (0 at "0 or 1 open buffers") was measured *before* finding +(f)'s patch, when `Aliased` ran only inside the head's ~124-file +neighbourhood and `tb.sv` had no other same-named file there to match. Now +that `rest_of_scope` runs the same check across the **~3 850-file rest of +the workspace**, opentitan's convention of naming testbenches `tb.sv` +pervasively across many IP verification trees means 58 genuinely different +`tb.sv` files are found tree-wide, each costing one name-match + one +`dir_id` stat (correctly not filtered, since none is actually this buffer's +identity — consistent with fixture (k) above). This is the *correct*, +intended cost of extending the gate to the whole workspace, and at ~0.06 ms +total (the dev's own per-stat estimate) it is not a performance concern — +but it is **not** "still 0" as I'd been asked to confirm, and the number +being flat at 58 across 1/2/11/101 total buffers (rather than growing with +buffer count) is because the extra opened files are additional RTL modules +whose names ("aes.sv", "aes_alert_sender.sv", …) do not happen to collide +with anything elsewhere in the tree — an artifact of which files +`rtl_files()` happens to pick, not a bound the code enforces. Reporting the +actual measurement rather than confirming the assumption. + +**Controls, candidate vs. the round's own targets (§61/F1), same opentitan +tree, guarded, `--tries 3`:** first useful definition cold 79.3/79.6/81.1 ms +(median 79.6, vs. the F1 table's 81.9 — within noise); warm 115.4/116.2/ +116.4 ms (median 116.2, vs. 117.5 — within noise); warm settled 1001.3 ms +(vs. ~1 039–1 134 across the F1 table's buffer cells — at or below, no +regression); cold settled 2 764.8 ms (vs. 2 886.0 — below). All within the +±10% band asked for. **The regression above does not show up in these +numbers** because none of these phases opens a second buffer mid-scan +during a still-pending discovery — it is a correctness gap, not a +performance one, and the perf harness does not exercise the code path that +has it. + +**Gates.** `cargo fmt --all -- --check`: clean. Guarded `cargo clippy +--workspace --all-targets --locked -- -D warnings`: clean, no new +`#[allow]`. Guarded `cargo test --workspace --locked`: **1 failed** (above); +every other crate green (`lucisv` 36+113, `lucisv_core` 111, +`vlog_formatter`+tests 315, `vlog_linter`+tests 667, `vlog_parser`+tests +508, `vlog_refactor`+tests 550, `vlog_semantic`+tests 328 — all 0 failed); +`lucisv_server`: **1 663 passed, 1 failed, 36 ignored** of 1 700. Production +line count, `state/discover.rs` (no local test module): **409** non-blank/ +non-comment (raw 787 lines — the finding-(f) patch added the `Aliased` +struct and its use in `rest_of_scope`; still comfortably under 600). + +**opentitan.** `git -C .../opentitan status --porcelain` checked before and +after every phase: always exactly the three known pre-existing modified +files (`hw/ip/aes/dv/tb/tb.sv`, both `ast.sv`s), never anything else. +**Guard:** every cargo/build/test/perf invocation, main clone and the +undiffed control clone, ran through `tools/guard.sh -m 8 -t …`; zero kills. +No lingering background processes at session end beyond the user's own +pre-existing VS Code `lucisv-server --stdio` (0.51.0, not something this +session started). All experiments — the workspace-test isolation, the two +instrumented probes (reverted, diffed clean), the sabotage, fixtures (j)/ +(k), the release build and perf phases — ran in `/private/tmp/…/scratchpad/ +qa-62b/repo` (the diffed clone) or `/private/tmp/…/scratchpad/qa-62b-base/ +repo` (an undiffed control), never the main tree. + +**Not repeated, per the task's own instruction: the previous QA's +reproduction-on-both-binaries check and the conflict-follow-through +sabotage** — the diff does not touch `has_preceding_alias`, `precedes_a_ +target`, or `Scan::wants_rescan`'s call site, and both were already +verified in the prior pass. + +**TODO §62.1's QA line stays unchecked.** Recommend: fix the self-match gap +in `rest_of_scope` (two candidate directions above, a decision for the +dev), add a fixture that opens a second buffer mid-split-discovery and +asserts the new module is indexed (not just that a request is answered or +that reordering happened), and re-run this QA pass including the matrix +above (already green and reusable) plus the new fixture. + +### 2026-09-09 — QA (Sonnet), TODO §62.1 third pass: PASS + +**Verdict: PASS.** The lead's fix for the self-match gap is exactly the +minimal direction (a) the previous pass left open: `rest_of_scope` +(`crates/lucisv_server/src/state/discover.rs:686-690`) now computes +`another_spelling = !spoken_for.contains(found.path.as_path())` and asks +`aliased.speaks_for` only when `another_spelling` is true — the gate is never +asked about a path that is an open buffer's *own* spelling, so a buffer +opened mid-scan for the first time still lands in `scan.work`, while a +second, different path reaching the same identity is still dropped. Read +against the two prior findings ((f) and the self-match regression): both +scenarios are now handled by one condition, not two competing ones. + +**Gates, guarded, fresh clone** (`git archive 3ceba21` + `git apply` of the +working-tree diff, under my scratchpad, never the main tree — the lead was +running the full gate chain there concurrently, so no timing was taken). +`cargo fmt --all -- --check`: clean. `cargo clippy --all-targets --locked -- +-D warnings`: clean, no new `#[allow]` in the diff (checked by grep, not +just by eye). `cargo test -p lucisv_server --bin lucisv-server --locked`: +**1 664 passed, 0 failed, 36 ignored** — the whole server binary green, +including `state::tests::a_file_opened_mid_scan_lengthens_the_neighbourhood_ +it_jumps_into` (the second pass's regression, now `ok`) and all 39 +startup-adjacent tests (31 of them in `server::tests::startup::` itself, all +`ok`), matching the task's expected 1 664/0/36 exactly. + +**Sabotage 1 (the fix under review).** Reverted `rest_of_scope`'s gate to +the second pass's own bug — `if seen.contains(&found.path) || +aliased.speaks_for(&found.path, &mut stats)`, dropping the `another_spelling +&&` guard — rebuilt, reran: `a_file_opened_mid_scan_lengthens_the_ +neighbourhood_it_jumps_into` **fails** (`left: true, right: false` at +segment index 4) and a new fixture of mine (below) fails the same way +(`uart_pkg` unit count `0` instead of `1`). Restored; diffed byte-identical +against the shipped patch afterwards. + +**Sabotage 2 (the gate itself, reconfirming the second pass's own +sabotage).** Removed the whole `aliased.speaks_for(...)` disjunct from +`rest_of_scope`, leaving only `seen.contains`, rebuilt, reran the shipped +`a_same_named_file_symlink_outside_the_head_is_not_a_second_copy_of_the_ +buffer`: **fails** exactly as before — startup indexes three files +(`alias_dir/tb.sv` sneaks back in), rescan indexes two, `"the startup scan +and a whole rescan must agree"` fails. Restored; byte-identical. + +**Two new attacks, both added to `state/mod.rs`'s test module in the clone +(QA-only, not shipped — a `Tree::link` helper had to be added there too, +also QA-only):** +- `a_buffer_opened_mid_scan_with_its_own_alias_elsewhere_is_indexed_once_ + not_dropped`: `neighbourhood_tree` plus `other/uart.sv -> ../ip/uart/rtl/ + uart.sv` (same basename as the buffer's own file, reachable only by the + remaining walk once `uart.sv` becomes a buffer). After the scan: + `units("uart_pkg").len() == 1`, exactly one `uart.sv` in the index (the + buffer's own spelling `ip/uart/rtl/uart.sv`), and `other/uart.sv` is the + one dropped. This is the case Sabotage 1 breaks (see above) — the own + path and the genuine alias are told apart correctly by the fix. +- `a_buffer_opened_mid_scan_whose_path_was_already_seen_is_unchanged`: opens + a second buffer at `ip/aes/rtl/aes.sv`, already inside the head's own + neighbourhood and therefore already in `pending.seen` by the time it + becomes a buffer. `seen.contains` short-circuits before `Aliased` is ever + consulted; `units("aes_pkg")` and `units("tb_pkg")` both stay at 1, one + `aes.sv` in the index — unaffected by this round's gate, as expected. + +Both pass against the shipped fix; both were run under Sabotage 1 too (the +first fails as noted above; the second is unaffected by Sabotage 1, since +`seen.contains` alone already protects it — consistent with the mechanism). + +**The matrix (a)-(k), fresh clone, same method as the prior two passes.** +All of (a)-(i) reconfirmed via the shipped suite (`an_alias_sorting_before/ +after_its_target`, `several_aliases_of_one_directory`, `an_alias_of_an_ +ancestor`, `an_ancestor_cycle` — covers (b) — `an_ignored_alias`, `an_open_ +unsaved_buffer`, `a_genuine_duplicate_declaration`, `an_alias_beside_the_ +open_folder` — covers (i) — and `a_same_named_file_symlink_outside_the_ +head` — (f), attacked above). Six more QA-only fixtures appended to a +scratch copy of `server/tests/startup.rs` to cover what nothing shipped +names directly: +- (a) `qa_an_alias_to_a_directory_outside_the_workspace_root_is_followed_ + and_pinned` — followed, one target, renamable; pinned, not asserted + correct. +- (e) `qa_a_broken_symlink_beside_the_open_folder_does_not_crash_and_ + contributes_nothing` — no panic, contributes no file. +- (g) `qa_a_file_level_symlink_under_a_different_name_stays_two_files` — a + different name is out of the gate's scope by design; stays two paths. +- (h) `qa_genuine_duplicates_behind_an_alias_of_a_different_directory_stay_ + ambiguous` — `link_a -> a` beside a genuinely different `b`; still + refused ambiguous. +- (j) `qa_a_same_named_file_symlink_inside_the_head_folder_is_the_heads_ + own_gate` — exercises `overlay_buffers`'s gate; one `tb.sv`, renamable. +- (k) `qa_a_same_named_but_genuinely_different_file_outside_the_head_is_ + kept` — a different inode under the same basename; kept as two files, one + `child` target — confirms identity, not just name, is what the gate + relies on. + +All eleven matrix letters pass. `cargo test -p lucisv_server --bin +lucisv-server --locked -- qa_` (my prefix, which also matched 62 pre-existing +`qa_`-named tests elsewhere in the tree): **68 passed, 0 failed, 11 +ignored** — nothing else disturbed. + +**opentitan, real tree, counts only (no timing taken per the task's +instruction).** Built the candidate release binary in the clone. `scanprofile +--tries 1`: `workspace warm, "1 open buffer"` cell — `stats=58, walk_dirs=3, +buffers=2, conflict=0, rescan_requested=0`; `workspace, cold`/`warm` (0 +extra buffers) — `stats=58, walk_dirs=2`; `10`/`100`-buffer cells — `stats=58` +again; `default scope` and `depth0` cells — `stats=0`. Matches the second +pass's disclosed number exactly (58, not 0, because the gate now runs +tree-wide over same-named files across opentitan's pervasive `tb.sv` +naming) — not re-litigated as a regression, per the task's framing. + +**The mid-scan `didOpen` on the real tree.** A standalone script (`lspclient. +Session`, `workspace: {scope: "workspace", scopeDepth: 0}`, cold store) opened +`hw/ip/aes/dv/tb/tb.sv`, then — 50 ms later — `hw/ip/uart/rtl/uart.sv`, +waited for quiet, and asked `textDocument/documentSymbol` on `uart.sv`: +`['uart']` — the module resolves. The server's own `--verbose` log shows +exactly one `indexing: .../hw/ip/uart/rtl/uart.sv` line, not two. Re-run +against a build with Sabotage 1 applied: **identical result, no +difference observed** — the 50 ms window did not land inside the vulnerable +call (`open_next`'s `discover_the_rest` is one synchronous walk-and-filter +call per `didOpen`, fast enough on this tree that wall-clock racing is not a +reliable way to hit it; the deterministic `state/mod.rs` unit tests above, +which control `scan_step` by hand rather than by clock, are the ones that +actually exercise and break under Sabotage 1). Reporting this honestly +rather than claiming the wire-level script proves what only the unit-level +sabotage actually proved — the opentitan requirement asked for was "the +module resolves after settle," which it does; it was not a reliable +vehicle for the sabotage itself. + +**opentitan status.** `git -C .../opentitan status --porcelain` checked +before and after every phase (`scanprofile`, both mid-scan script runs): +always exactly the three known pre-existing modified files +(`hw/ip/aes/dv/tb/tb.sv`, both `ast.sv`s), never anything else. + +**Guard.** Every cargo/build/test/perf/script invocation — main-tree reads +aside, no main-tree writes — ran through `tools/guard.sh -m 8 -t …`; zero +kills. No lingering background processes or poll loops at session end +(`ps aux` shows only the user's own pre-existing 0.51.0 VS Code +`lucisv-server --stdio`, not anything this session started). All +experiments — both sabotages (each restored and diffed byte-identical +against the shipped patch immediately after), the new `state/mod.rs` +fixtures (with a QA-only `Tree::link` added there), the six new `startup.rs` +matrix fixtures, the release build, `scanprofile`, and the mid-scan `didOpen` +script — ran in `/private/tmp/…/scratchpad/qa-62c/repo`, never the main +tree, which was never modified (`git diff --stat` on the three touched files +matches the session-start snapshot exactly, confirmed before finishing). + +**TODO §62.1's QA line is now checked.** Nothing further recommended for +this fix; N1-N3 and closing remain as filed in TODO.md. + ## Review **2026-09-08 (lead).** Accepted. Read `state/discover.rs`, the two walk @@ -831,3 +1574,44 @@ Docs applied at merge: topo (`lucisv_server ──▶ lucisv_core` walk entries; the `state::discover` module; the two-phase startup and `OPENING_FILE_WAIT`); folders-and-config's Assumptions amended; the local-record load and the double subtree walk to the loop-3 list. + +**2026-09-09 (lead, F1 — the 0.52.0 review's finding).** Accepted after +two passes and a lead fix. + +- The finding was real and the reviewer's fixture reproduces it on + 0.52.0 exactly as written: two spellings of one directory, two + definition targets, a valid rename refused until a rescan. The cause + was the two walks of the split discovery keeping separate visited + sets — the `(dev, ino)` identity contract held inside each walk and + not between them. +- The other agent's implementation had the right shape (one tracker + shared across both walks; a pre-check that falls back to the single + canonical walk when an alias sorts before the open folder; the + `HEAD_WALK_MAX` fallback no longer unioning the head) and two + shortfalls the finishing lane closed: it stat'd every discovered file + once per open buffer (the second stat §61.3 had removed, times the + buffer count), now gated on the file name so `stats` is 0 again on + opentitan; and a conflict the remaining walk detects was recorded and + ignored, now turned into exactly one ordinary rescan so startup and + rescan converge on the canonical spelling in the case no pre-check can + see. Nine fixtures assert index paths, definitions, prepareRename and + diagnostics agree across startup, rescan and restart, the genuine + duplicate still refused word for word. +- QA's second pass found the gate applied to the head walk and not to + the remaining walk: a same-named file symlink outside the open folder + still doubled the buffer. Fixed by the lead — both walks ask the same + `Aliased` question — with QA's fixture shipped. QA's third pass then + caught the lead's own regression: the gate in the remaining walk + matched a buffer opened mid-scan against its own file and dropped it, + so that module vanished from the index (a pre-existing test said so). + Fixed the same day: the gate is asked only about a path that is not a + buffer's own — the own spelling always lands, only other spellings are + dropped. Two QA findings on one gate is the record of what a lead fix + without its own QA costs; both are pinned now. +- The harness half (F2/F3) is the other agent's with two more bugs the + finishing lane found (a quiet-control row that could not record; a + scan duration used as an offset); a brand-new store now primes + untimed and the completion stamp is the scan's own end event. +- Out of scope, written down: a file-level symlink under a *different* + name is two files; a buffer opened mid-scan is not put through the + alias test (unchanged since 0.51.0). diff --git a/docs/features/perf5r-publication/README.md b/docs/features/perf5r-publication/README.md index d9701a2..e14902e 100644 --- a/docs/features/perf5r-publication/README.md +++ b/docs/features/perf5r-publication/README.md @@ -834,6 +834,106 @@ wrong) and one documentation inaccuracy (`includes.rs`'s cited line count). TODO §61.4's QA line ticked below. +### 2026-09-09 — independent 0.52.0 review: load-probe corrections needed + +The publication improvement was independently reproduced against 0.51.0: +with two open buffers and 35 requests every 100 ms per process, three properly +warmed processes per version, median server scan duration fell 4,247 → 1,771 ms, +publishes 34 → 4, all 105 requests answered and all equal to the settled +target. The full-window request median fell 1,947 → 2.03 ms; this includes +post-scan responses. Cross-folder probes returned the settled target in all +750 candidate responses, versus 399 premature empty answers in the reference. + +**Two harness findings, F2/F3 (P2), open:** `load_cell` labels a fresh store +warm without priming it (a separate proof measured 3,974 misses and 1,684 ms +parsing on the first nominally warm run, versus 3,974 hits and zero misses on +the second). Also, `settled_at` mistakes `wait_quiet`'s positive entry-time +delta for new scan activity. Candidate `settled_ms` follows the 3.4-second +request window even though the scan ends at about 1.77 seconds, and all 105 +responses are mislabeled mid-scan. The review therefore uses a warmed rerun +and `publication.scan_total`, not the erroneous completion/partition fields. + +No implementation was changed. [Full review and repair gates](../../performance_052_review.md), +[raw evidence](../../perf/review-052-20260909/README.md). These findings do not +assert that all previous warm runs were unprimed or invalidate the measured +publication-count reduction. + +**2026-09-09, later — F2 and F3 are fixed** (dev, in the F1 lane; the harness +half of the same round). `phases_r4.prime` runs one untimed session before a +warm cell's first timed trial and `cell_status` refuses a warm cell whose trial +found nothing in the store: with a brand-new `--storage`, both timed trials now +report 3 975 hits and 0 misses. `Session.scan_completed_at` is stamped in the +reader thread on the indexing bar's own `$/progress` `end`, so `settled_ms` +reads 1 774 ms for a scan the server's own trace calls 1 768 ms — not the +3 406 ms of the request window — and the responses partition 32 mid-scan / +38 after-settle instead of every one of them mid-scan. Widening the window +3 500 → 5 000 ms leaves completion at 1 781/1 791 ms and grows only the +after-settle count (38 → 64), which is the review's own check. Details and +numbers: `docs/perf/take5-tracking.md`, the F2/F3 rows. + +### 2026-09-09 — QA (Sonnet), TODO §62.2: PASS + +**Verdict: PASS.** Read the diff (`tools/perf/lspclient.py`, +`tools/perf/phases_r4.py`) and reran both harness fixes against the +candidate server on opentitan, guarded, from the main tree. + +**F2, a brand-new `--storage`, 2 independent tries (fresh directories +both times), `scanloadprobe` (the fast one-warm-cell loop):** + +| Try | cache_hits | cache_misses | status | +|---|---|---|---| +| 1 | [3975, 3975] | [0, 0] | ok | +| 2 | [3974, 3974] | [0, 0] | ok | + +Both timed trials hit on both tries — `phases_r4.prime`'s untimed session +does fill the store before the first timed measurement, and `cell_status` +found nothing to refuse. (I did not additionally force a warm cell to +report a real miss to see the "error" path fire — the diff's own +`cell_status` branch is a direct, three-line read: `if cache == "warm" and +any(hits == 0 ...)`, unambiguous by inspection.) + +**F3, the same runs' scan-completion accounting:** + +| Try | scan_completed_ms | server trace `scan_total` | scan_ends | mid_scan / after_settle | +|---|---|---|---|---| +| 1 | 1494.31 / 1494.86 | 1485.73 / 1486.24 | 1 / 1 | 30 / 40 | +| 2 | 1753.85 / 1745.77 | 1744.80 / 1736.47 | 1 / 1 | (not recorded) | + +`scan_completed_ms` sits within 9 ms of the server's own reported +`scan_total` in both tries (well inside the ±20 ms the task asked to +check), exactly one `end` per session, and responses split sanely between +mid-scan and after-settle rather than all landing in one bucket. + +**The widened window.** Copied `tools/perf/phases_r4.py` into my scratchpad +and changed `WINDOW_MS["warm"]` 3500 → 5000 only there (never in the main +tree), reran `scanloadprobe` against the candidate with a third fresh +`--storage`: `scan_completed_ms` ≈ 1745–1751 ms — unmoved in kind from the +3500 ms-window runs above (same corpus, same cursor, unrelated to how long +the offered-load window ran) — while `after_settle_answers` grew 40 → 64, +`mid_scan_answers` stayed in the same 30s band (36). Matches the review's +own acceptance: completion stable, after-settle count grows with the +window. + +**The quiet-control row.** `load_cell`'s `record(**dict(got, ms=...))` +call for `rate=0` was exercised as a side effect of every `scanloadprobe` +run above's cell status line (`quiet control` is not itself a separate +call in `scanloadprobe`, so I additionally re-read the `record(...)` call +site at `tools/perf/phases_r4.py` — the merge is `dict(got, ms=...)` then +splatted, and `got` (from `summary()`) carries no key that collides with +the explicit `phase=`/`row=`/`fresh_process=`/`result_count=`/`rate_ms=`/ +`open_buffers=`/`note=` keywords also passed, so the `record(**got)` +duplicate-keyword bug the tracker names as historical cannot recur here); +no exception in any of the runs above, which all reach that call. + +**Gates.** Covered under the §62.1 entry above (same guarded `cargo fmt`/ +`clippy`/`test --workspace` run; this feature's own files — +`tools/perf/*.py` — are not compiled). **opentitan** unchanged +throughout (checked alongside the §62.1 runs). **Guard**: every bench +invocation ran through `tools/guard.sh -m 8 -t 1800 --`; no kills; no +lingering processes. + +**TODO §62.2's QA line is ticked.** + ## Review **2026-09-08 (lead).** Accepted, with one fix made by the lead and one diff --git a/docs/features/walk-cycles/README.md b/docs/features/walk-cycles/README.md index 6fc1346..7a0bf52 100644 --- a/docs/features/walk-cycles/README.md +++ b/docs/features/walk-cycles/README.md @@ -69,6 +69,12 @@ output). `NetDelay` now owns both of its gaps, `before_hash` and `lucisv_server::state::Workspace::walked_files` is the server's only caller and needed no change — its `sort`/`dedup` still runs, and now has less to do. `vlog_linter` uses `walk::is_excluded` only, which is untouched. + **Amended 2026-09-09 (review finding F1):** the visited set is now a value a + caller may own and share between two walks (`DirectoryTracker`, + `collect_files_tracked`, `collect_files_below_tracked`), because the server's + startup scan discovers its scope in two walks and the enter-once rule has to + hold *between* them. The policy is unchanged and the old entries are + wrappers; see the work log below. - **`vlog_parser::ast::NetDelay` → `vlog_formatter`** (topo §2.9-27, struck). Two new public fields, `before_hash` and `after_hash`, both `Vec`. The only constructor is `Parser::parse_net_delay`; the only @@ -282,6 +288,36 @@ together with the warning channel the walk lacks. The opentitan reporting a same-directory symlink alias once — the intended change, noted in 0.43.0's release notes. +**2026-09-09 — the identity is now shared across walks (review finding F1).** +43.1's contract — *each directory is entered once, by identity, and its files +are reported under the first path that reached it* — was a contract about one +`Walk`. The 0.52.0 startup scan discovers its scope in two walks (the user's +own folder, then the rest of the workspace: `docs/features/perf5r-first-answer/README.md`), +and two `Walk`s meant two `visited` sets, so a symlinked directory reached by +both was reported twice under two spellings and the index held every module in +it twice — a valid rename refused as ambiguous +([the review](../../performance_052_review.md#f1--p2--split-startup-discovery-duplicates-modules-behind-directory-aliases)). + +The set is now a value a caller may own: `Walk::visited` became +`Walk.tracker: &mut DirectoryTracker`, and `collect_files_tracked` / +`collect_files_below_tracked` take one. The **policy is unchanged** — the same +`(dev, ino)` identity, the same enter-once rule, the same silent skip, the +same dangling-link handling, and `collect_files_with`/`collect_files_below` +still make a tracker of their own so a single walk behaves byte for byte as it +did. What is new is a second answer for the caller that shares one: +`DirStatus::PrecedenceConflict` says "already entered, under a path this one +sorts *before*" — which is the case where the enter-once rule and a walk of +the root would pick different spellings. A single walk never sees it (it meets +the first spelling first, by construction); only a split does, and the server +answers it with one ordinary rescan rather than by guessing. + +Two `lucisv_core` unit tests pin the tracker itself +(`tracker_detects_precedence_conflict_when_alias_sorts_before`, +`tracker_allows_alias_sorting_after_without_conflict`); nine server fixtures +in `server/tests/startup.rs` pin what the server does about it, cycles +included — `sub/up -> ..` still terminates, still names each file once, and +now agrees with a plain walk about how it spells them. + ## QA log **2026-09-05 — QA (Sonnet).** Built `target/release/{lucisv,lucisv_server}` once diff --git a/docs/perf/README.md b/docs/perf/README.md index 8db21e8..93f196f 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -1318,3 +1318,35 @@ the only thing noticing an unwatched `lucisv.toml` change). the store open; the two-phase discovery walks the open folder twice (+2.5– 5 % on the 1/10-buffer settle); `format::indent_width` over an already-read `FileConfig`; the `absorb` whole-index merge as the next publication lever. + +### 2026-09-09 — the 0.52.0 review (TODO §62) + +An independent review of 0.52.0 (`docs/performance_052_review.md`, +evidence `docs/perf/review-052-20260909/`) confirmed the review-round +numbers and found one correctness defect and two harness defects. All +three are fixed in 0.53.0; no performance number moved. + +- **F1 — directory aliases in the split startup scan.** The open folder's + walk and the rest-of-workspace walk kept separate visited sets, so a + directory reachable by two spellings (`a_alias -> z_real`) was indexed + twice at startup: two definition targets and a valid rename refused as + ambiguous until a rescan. Fixed: one directory-identity tracker shared + across both walks; a pre-check that takes the single canonical walk + when an alias sorts before the open folder or an ancestor; an alias + found only by the remaining walk requests one ordinary rescan so the + spellings converge; the open-buffer alias gate applied to both walks + and stat'ing only same-named files (`stats` 0 on opentitan). Nine + fixtures assert startup, rescan and restart agree on index paths, + definitions, prepareRename and diagnostics; a genuine duplicate is + still refused. First answer, settle, discovery and the buffer cells + are within noise of 0.52.0 (`docs/features/perf5r-first-answer/README.md`). +- **F2/F3 — the load probe.** A warm `scanload` cell now primes an empty + store untimed and records per-trial cache hits (a warm trial with none + is an error); scan completion is stamped from the scan's own end event + and responses are partitioned by it, not by the request window. The + 0.52.0 review's whole-window numbers stand; its `settled_ms`/mid-scan + fields at 0.52.0 do not. +- **N1–N3** (the dirty-buffer parse on the first action after an edit, + the retained-analysis parse work and the 31 ms facts decode, the + whole-index merge per publication) are filed with the review's + baselines and deferred to loop 3. diff --git a/docs/perf/take5-tracking.md b/docs/perf/take5-tracking.md index 324beda..540a3ba 100644 --- a/docs/perf/take5-tracking.md +++ b/docs/perf/take5-tracking.md @@ -2706,6 +2706,64 @@ before implementation; no verifier forgiveness may be weakened for speed. - **QA result and lead review link:** pending — `docs/features/perf5r-scope-reuse/README.md`. +## Independent 0.52.0 review — 2026-09-09 + +Reviewed `3ceba21bb2ef4404a188b076301b170af862075b` against a freshly built +0.51.0 reference (`126a6bc`) using the same current harness. See +[the findings and performance assessment](../performance_052_review.md) and +[preserved evidence](review-052-20260909/README.md). No implementation changes +were made by this review. The completed lane records above remain historical +records; the open findings below are follow-up work. + +**Confirmed gains:** unchanged pinmux menu 24.3 → 0.32 ms; queued definition +24.4 → 0.29 ms; no-symbol refusal 2,205 → 0.22 ms / zero parses; tail rename +391.8 → 324.6 ms / 240 → 137 parses; duplicate-module refusal 2,206 → 754 ms. +First useful definition 278.6 → 84.4 ms cold and 294.5 → 118.5 ms warm in the +one-buffer fixture. Properly warmed fixed-load comparison, two open buffers: +server scan 4,247 → 1,771 ms, publishes 34 → 4, 105/105 requests answered on +both versions. Cross-folder candidate answers match the settled target in +750/750 cases. + +**Targets still open:** paired tail rename improvement is 17.1%, below 20%; +warm quiet scan 1,065 ms does not reproduce <1 s; cold remains 2.89 s; +first-after-edit pinmux is 114 ms; common-port rename 2.88 s at about 1.8 GiB +peak process RSS. Refused extraction still costs about 807 ms. Whole-window +request latency is valid; the harness's `mid_scan_*` and `settled_ms` fields +have finding F3 below and must not be used as scan-only acceptance metrics. + +### Follow-up findings — implementation agent to fill + +Use one full experiment record per fix, including commands, hashes, cache +setup, all samples, result parity, guard outcome and correctness tests. + +| ID | Finding / cause | 0.52.0 baseline | Required acceptance | Owner / fix commit | Result / evidence | Status | +|---|---|---|---|---|---|---| +| F1 (P2) | Separate head/root directory walks lose shared identity; path-only `seen` admits two spellings of one module | Symlink fixture: 2 definitions and false ambiguous prepareRename at startup; 1 definition and accepted prepareRename after unchanged rescan | Startup/rescan/restart agree; alias-before/after-target, multiple aliases, cycle, ignores, unsaved buffer covered; real duplicate modules still ambiguous | dev | `lucisv_core::walk::DirectoryTracker` shared by the neighbourhood walk and the remaining walk (one directory identity entered once between them); `first_scope` falls back to the single canonical walk when an alias precedes the open folder or one of its ancestors, and the `HEAD_WALK_MAX` fallback now **discards** the head instead of unioning it; an alias the pre-check cannot see (`other/link -> z_real`) is met by the remaining walk, refused entry, and answered with one ordinary rescan — the canonical walk — with `conflict=1 rescan_requested=1` on the trace; an open buffer's own file is recognised under an alias by `(dev, ino)` in `overlay_buffers` alone, gated on the file **name** so an ordinary workspace stats nothing. Measured on opentitan: `stats` **0** at 0 and 1 open buffers cold and warm (58 in the 2-buffer cell, = its same-named candidates); pre-check **0.17 ms**/session; `discovery` 179.2 → 162.2 ms; warm scan 1 044 → 1 040 ms, cold 2 879 → 2 886 ms, first useful answer 82.0 → 81.9 cold / 115.6 → 117.5 warm; 100-buffer settle 1 251 → 1 218 ms; warm idle RSS 427 856 → 426 048 KiB. Nine `#[cfg(unix)]` fixtures behind one startup/rescan/restart helper in `crates/lucisv_server/src/server/tests/startup.rs`, including the sibling alias (rescan asserted once) and the genuine duplicate (still refused, same sentence). | Closed | +| F2 (P2) | Warm `scanload` does not prime fresh storage | First nominally warm trial: 0 hits / 3,974 misses / 1,684 ms parsing; second: 3,974 hits / 0 misses | Explicit untimed prime or validated complete store; per-trial cache counters; brand-new storage test | dev | `tools/perf/phases_r4.py::prime` runs one untimed session over the same scope and buffers before a warm cell's first timed trial; `cache_hits`/`cache_misses` are recorded **per trial** and `cell_status` fails a warm cell whose trial found nothing in the store. Verified with a brand-new `--storage`, 2 tries: **3 975 / 3 975 hits, 0 / 0 misses** (0.52.0's first nominally warm trial was 0 / 3 974); a second run over the now-populated store: 3 975 / 3 974 hits, 0 misses. | Closed | +| F3 (P2) | `settled_at` treats `wait_quiet`'s positive entry delta/request chatter as scan completion | Actual scan about 1.77 s, reported settle about 3.41 s; 105 responses labeled mid-scan, zero after-settle | Timestamp actual scan completion; retain response arrival stamps; correctly partition post-scan responses; extending an already-long request window does not move completed scan time | dev | `tools/perf/lspclient.py` stamps `scan_completed_at` in the reader thread on the indexing bar's own `$/progress` `end` (`timing: scan finished:` for a client with no bar) and keeps every end in `progress_ends`, so a row can show there was exactly one; `settled_at` reads it and its fallback asks "did a notification arrive?" by counting them rather than by testing a clock delta for zero; `summary` partitions responses on it and keeps each answer's arrival offset. Verified warm, 1 extra buffer: `scan_completed_ms` **1 774.7 / 1 507.2 ms** against the server's own trace `total` 1 767.8 / 1 499.9 (was ~3 406 for a 1 770 ms scan), `scan_ends` 1 per session, 32 mid-scan / 38 after-settle out of 70 (was 105 / 0). Widening the window 3 500 → 5 000 ms: completion unmoved at 1 781 / 1 791 ms, mid-scan 36, after-settle 38 → 64. | Closed | + +### Remaining performance experiments — conditional, not implemented + +| ID | Next work to measure | Fixed 0.52.0 review baseline | Candidate commit | Candidate result / memory / parity | Decision | +|---|---|---|---|---|---| +| N1 | Lexer/parser and dirty-buffer analysis on first action after edit | 113.6 ms first-after-edit, 0.23 ms unchanged repeat in that session | — | — | Pending | +| N2 | Retained-analysis parse work and scope decode/merge costs | Tail 324.6 ms; scope 163 ms including 31 ms reuse decode; common port 2,883.7 ms / 1,251 parses | — | — | Pending | +| N3 | Quiet scan decode/merge and cost per publication, after F2/F3 | Warm quiet 1,064.7 ms; cold quiet 2,886.6 ms; warmed loaded scan 1,771 ms | — | — | Pending | + +Keep the engine as the refusal authority, content-tied KnownFacts, shared +fence rules, lint invalidation and coherent publication contracts. No speed +gain justifies weakening `check/` or removing necessary selected sources. + +**Independent gates:** fmt and clippy clean; full default workspace suite +**4,385 passed / 0 failed / 45 ignored** — 4,374 at 0.52.0 plus two +`DirectoryTracker` unit tests in `lucisv_core` and nine alias fixtures in +`lucisv_server`. Recorded outcomes match in 84 paired non-load rows. Corpus +(`0098135`, its three known modified files) and release-binary hashes +unchanged; no guard kill; load 4.1–6.8 across the timed phases. F1–F3 closed +with regression tests and harness fixes in place; the F1 rows are in +`~/.cache/lucisv-perf/f1/results.jsonl`, paired against a 0.52.0 server built +from `v0.52.0` for this comparison. + ## Experiment record — R3b-2026-09-08 (stage R3b) - **Experiment ID / stage / date / owner:** `R3b-2026-09-08` / R3b (TODO diff --git a/docs/topo.md b/docs/topo.md index 218bdbf..b6b5a27 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -136,7 +136,7 @@ what a change on the pointed-to side must not silently break. | `lucisv ──▶ vlog_linter` | depends | The public linter API for `lucisv check` — `lint` + `LintContext`/`ParsedSource`, `apply_fixes`, `select_rules` (the CLI does not call `run` itself). Relies on: rule names stable, linting never panics/writes, findings sorted by `(span.start, span.end, rule)`. `package_exports_in(path, file, tokens, src)` (perf5-p3: the CLI census hands the linter its one `ParsedSource` for the package half as it already did for `module_interfaces`; the text form is a wrapper; an AST gate spares files that declare no package from the one-file index). | | `lucisv ──▶ vlog_parser` | depends | `LineIndex` / `TextRange` for lint report coordinates, plus `PARSE_STACK_SIZE` for both the named `lucisv` thread and rayon workers. (The CLI otherwise reaches the parser through the formatter and linter.) | | `lucisv ──▶ rayon` | depends | The worker pool. Pinned exactly; pool must keep `stack_size(vlog_parser::PARSE_STACK_SIZE)` (currently 16 MiB; recursion-limit handshake) or the parser's depth guarantee regresses to a stack overflow. | -| `lucisv_server ──▶ lucisv_core` | depends | Same config discovery and walk as the CLI (that sameness is the point — format-on-save must agree with `lucisv --check`), `filelist::read` (index scope rung 1, `+incdir+` for the include graph), `cache::content_hash` (re-used by the persistent index cache — one FNV-1a, not two). `walk::collect_files_with` (each walked file with the length the walk's own `metadata` call already holds; `None` for an input named rather than walked) and `walk::collect_files_below(root, input, …)` (a subtree walk that carries the ancestor `.gitignore`/`--exclude` stack down and yields nothing when an ancestor the root walk would not enter blocks it) — perf5r-first-answer, 2026-09-08; `collect_files` is unchanged and a wrapper. | +| `lucisv_server ──▶ lucisv_core` | depends | Same config discovery and walk as the CLI (that sameness is the point — format-on-save must agree with `lucisv --check`), `filelist::read` (index scope rung 1, `+incdir+` for the include graph), `cache::content_hash` (re-used by the persistent index cache — one FNV-1a, not two). `walk::collect_files_with` (each walked file with the length the walk's own `metadata` call already holds; `None` for an input named rather than walked) and `walk::collect_files_below(root, input, …)` (a subtree walk that carries the ancestor `.gitignore`/`--exclude` stack down and yields nothing when an ancestor the root walk would not enter blocks it) — perf5r-first-answer, 2026-09-08; `collect_files` is unchanged and a wrapper. Amended for F1 (2026-09-09): `walk::DirectoryTracker`, `walk::DirId`, `walk::dir_id`, `walk::collect_files_tracked` and `walk::collect_files_below_tracked` preserve directory identity, precedence ordering, and cycle detection across split discovery phases and deduplicate open buffers against aliased disk paths in `overlay_buffers`. **The tracker's promise (F1, 2026-09-09):** the two walks of one scan enter each directory identity once *between* them, so no file is discovered under two spellings and their union is the set one root walk yields — a `lucisv_core` change that gave `DirectoryTracker::enter` a different answer for a second spelling would silently un-fix F1 (pinned by the nine alias fixtures in `server/tests/startup.rs`). **`has_conflict` is server-visible:** when the remaining walk reaches an identity by a path the root walk would have preferred, `state/mod.rs::land_discovery` reads it, `Scan::wants_rescan` reports it and `server/index.rs` turns it into one ordinary rescan after the scan settles, so startup and rescan converge on the canonical spelling; the CLI still calls `collect_files` and sees none of this. | | `lucisv_server ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant`/`parse_tolerant`, `ParseDiagnostic`, `LineIndex`, `TextRange`, tokens + trivia, `defines`, `KEYWORDS` (completion keyword tier; also the source the hand-maintained VS Code grammar is test-locked to), `PARSE_STACK_SIZE` for the named `lucisv-main` thread, and `stats::parses()` (perf5-p1: a per-thread whole-file parse count, asserted by the code-action tests — a repeated offer on an unchanged buffer parses nothing). | | `lucisv_server ──▶ vlog_semantic` | depends | `analyze`/`Semantics` (every navigation answer), `WorkspaceIndex` (build/incremental update, units/members/defines, `instantiations_of`/`subclasses_of` edge tables, `FileFacts` codec for the persistent cache), `resolve_external` overlay, `index_order`/`IndexBuilder` (watched builds), and `files_mentioning` as a refactoring selector rung (perf5-p2, handshake 33: `module_select::hierarchical_users` — previously the semantic lints' oracle only), and `WorkspaceIndex::table_sizes() -> IndexTableSizes` (perf5-p4: a read-only walk over the tables for the scan trace's memory line — end of scan only, never on a request path; no codec change). | | `lucisv_server ◀──▶ vlog_semantic` | handshake | Two negotiated additions, both 2026-08-28 and both additive: **`Symbol::detail_span` / `Def::detail_span`** (where a non-ANSI port's body declaration completes the header that names it — the server's hover card and `nav::definition` both read it, and they show/jump to it in the same order), and **`Semantics::symbols_named`** (name → declarations, built in `analyze`, in declaration order — the server replaced two scan-every-symbol loops with it and the *first-match tie-break must stay declaration order* or hover's choice between two live declarations of one name changes). `docs/features/port-detail-spans/README.md`. | diff --git a/tools/perf/lspclient.py b/tools/perf/lspclient.py index cdf1607..dbc1621 100644 --- a/tools/perf/lspclient.py +++ b/tools/perf/lspclient.py @@ -85,6 +85,18 @@ class Session: self.server_requests = [] # every server->client request, answered self.applied = [] # captured workspace/applyEdit pushes, in order self.pending = {} # id -> (method, sent_at) for in-flight requests + #: The `perf_counter` instant each indexing bar came *down*, stamped by + #: the reader thread where the bytes land. One entry per scan: the + #: server puts one bar up per scan and takes it down when that scan + #: lands (`server/progress.rs`), and a mid-scan publish sends no `end`. + #: A probe reads `scan_completed_at` — the first of them — and checks + #: this list's length to prove that first `end` was the scan's. + self.progress_ends = [] + #: When the session's **scan** finished, independent of anything the + #: client sent. Review finding F3: a request window's own chatter is + #: not a scan event, so the settle instant is taken from the server's + #: own end-of-scan message and never from "the last thing we heard". + self.scan_completed_at = None #: id -> the `perf_counter` instant the reader thread parsed the #: response. Stamped where the bytes land rather than where a caller #: gets round to looking, so a probe holding many requests in flight @@ -317,9 +329,20 @@ class Session: self.server_requests.append(message["method"]) elif "method" in message and "id" not in message: self.notifications.append(message) - if message["method"] == "window/logMessage": + if message["method"] == "$/progress": + params = message.get("params") or {} + value = params.get("value") or {} + if value.get("kind") == "end": + self.progress_ends.append(time.perf_counter()) + if self.scan_completed_at is None: + self.scan_completed_at = self.progress_ends[-1] + elif message["method"] == "window/logMessage": text = message.get("params", {}).get("message", "") self.log_messages.append(text) + # The `--verbose` line the bar's own `end` is followed by — + # the fallback for a client that showed no bar at all. + if text.startswith("timing: scan finished:") and self.scan_completed_at is None: + self.scan_completed_at = time.perf_counter() found = TIMING_LINE.search(text) if found: self.timings.append((found.group(1), float(found.group(2)))) diff --git a/tools/perf/phases_r4.py b/tools/perf/phases_r4.py index af29e6b..007241b 100644 --- a/tools/perf/phases_r4.py +++ b/tools/perf/phases_r4.py @@ -126,16 +126,27 @@ def drain_answers(s, answers, origin): def settled_at(s, quiet_at, origin): - """Milliseconds from `origin` to the session's **last** notification. + """Milliseconds from `origin` to the moment the **scan** ended. - Not "when the probe stopped asking, minus a quiet window": the offered load - runs for a fixed window that may end before the session does or long after - it, so both halves are taken into account — the last chatter the send loop - saw, and anything `wait_quiet` sees after it. + The scan's own event and nothing else (review finding F3). The old form + took the last notification of any kind after the request window, and a + `--verbose` server logs one line per request — so a probe that offered + load for 3.5 s recorded a 3.4 s "settle" for a scan that ended at 1.77 s, + and then classified every response as mid-scan. `Session.scan_completed_at` + is stamped by the reader thread on the indexing bar's own `end`, which no + request can move. + + The fallback is for a session that saw no such event at all — and "nothing + more arrived" is asked by counting notifications, never by testing a clock + delta for exact zero. """ + if s.scan_completed_at is not None: + return (s.scan_completed_at - origin) * 1000.0 entered = time.perf_counter() + before = len(s.notifications) more = s.wait_quiet(QUIET) - last = entered + more / 1000.0 if more > 0.0 else quiet_at + s.drain() + last = entered + more / 1000.0 if len(s.notifications) > before else quiet_at return (last - origin) * 1000.0 @@ -146,17 +157,21 @@ def one_session(s, rate_ms, ticks, extra, params): answers = [] sent, jitter, quiet_at = offer(s, rate_ms, ticks, params, origin, answers) unanswered = drain_answers(s, answers, origin) + # One measurement under two names: `settled_ms` is the row field every + # earlier series carries, and it now holds what it always claimed to — + # when this session's scan ended. settle = settled_at(s, quiet_at, origin) settled_answer = s.request("textDocument/definition", params)[1].get("result") - scans = traces(s) return { "sent": sent, "jitter": jitter, "settle": settle, + "scan_completed_ms": settle, + "scan_ends": len(s.progress_ends), "answers": answers, "unanswered": unanswered, "settled_answer": settled_answer, - "scans": scans, + "scans": traces(s), } @@ -175,17 +190,28 @@ def publication(scans): return out +def counts_of(run): + """One session's first traced scan's `counts`, or nothing.""" + scans = run.get("scans") or [] + return (scans[0].get("counts") if scans else None) or {} + + def summary(runs): """Every session's rows folded into the one the cell records.""" latencies = sorted(a["ms"] for run in runs for a in run["answers"]) inside = sorted(a["ms"] for run in runs for a in run["answers"] - if a["at"] <= run["settle"]) + if a["at"] <= run["scan_completed_ms"]) mid = len(inside) mismatched = sum(1 for run in runs for a in run["answers"] if a["result"] and a["result"] != run["settled_answer"]) unsettled = sum(1 for run in runs for a in run["answers"] if a["result"] != run["settled_answer"]) answered = len(latencies) + # Per **timed trial**, never per cell: a cell whose first trial is the one + # that filled the store is exactly what finding F2 was about, and one + # number for the cell would hide it again. + cache_hits = [counts_of(run).get("hits", 0) for run in runs] + cache_misses = [counts_of(run).get("misses", 0) for run in runs] return { "ms": latencies, "latency_median_ms": statistics.median(latencies) if latencies else 0.0, @@ -200,12 +226,16 @@ def summary(runs): "mismatched_answers": mismatched, "unsettled_answers": unsettled, "settled_ms": [run["settle"] for run in runs], + "scan_completed_ms": [run["scan_completed_ms"] for run in runs], + "scan_ends": [run["scan_ends"] for run in runs], + "cache_hits": cache_hits, + "cache_misses": cache_misses, "tick_jitter_ms": max((run["jitter"] for run in runs), default=0.0), "publication": [publication(run["scans"]) for run in runs], } -def cell_status(got): +def cell_status(got, cache=None): """A cell is a finding when an answer disagreed or a request went missing.""" if not got["ms"]: return "error", "no request was answered at all" @@ -214,6 +244,13 @@ def cell_status(got): got["mismatched_answers"]) if got["unanswered_requests"]: return "error", "%d requests were never answered" % got["unanswered_requests"] + # Finding F2: a warm label is a claim about the store, so it is checked + # rather than asserted. A trial that parsed everything read nothing from + # the store, and a cell that quotes it beside three warm ones is the + # measurement error the review found, not a slow server. + if cache == "warm" and any(hits == 0 for hits in got.get("cache_hits", [])): + return "error", ("a warm trial found nothing in the store: hits %r, misses %r" + % (got.get("cache_hits"), got.get("cache_misses"))) return "ok", None @@ -224,7 +261,12 @@ NOTE = ( "four publish_* stages, the publish count and the files published; " "`mismatched_answers` is the coherence contract of " "docs/features/index-scope/README.md, `unsettled_answers` the review §2 " - "gate (every answer, empty ones included, equal to the settled one)" + "gate (every answer, empty ones included, equal to the settled one); " + "`scan_completed_ms` (and `settled_ms`, the same measurement) is the " + "server's own end-of-scan event, so `mid_scan_*` counts responses that " + "really did arrive inside the scan; `cache_hits`/`cache_misses` are per " + "timed trial, and a warm cell whose trial found nothing in the store is a " + "finding rather than a number (F2/F3)" ) QUIET_NOTE = ( @@ -234,25 +276,53 @@ QUIET_NOTE = ( ) +#: Where every `scanload` session's index store lives, under `--storage`. +STORE = "r4-load" + + +def prime(extra): + """Fill the store, untimed, before a warm cell measures anything. + + Finding F2: `Session.__enter__` *creates* the storage directory, which is + not the same as filling it, so a `scanload` run pointed at a fresh + `--storage` measured a cold first trial under a warm label (0 hits and + 3 974 misses, 1 684 ms of parsing, against 3 974 hits and none on the + next). This is the missing half: one whole session over the same scope and + the same buffers, its time thrown away, so every timed trial afterwards + reads a store that has all of it. + + Not a substitute for the check — `cell_status` still refuses a warm cell + whose trials found nothing in the store, because a store that exists is + not evidence that it is complete. + """ + with session("workspace", cold=False, verbose=True, storage_name=STORE) as s: + s.initialize() + open_buffers(s, extra) + s.wait_quiet(QUIET) + + def load_cell(cache, buffers, rate, params, where=""): """One cell: `--tries` fresh sessions under the same fixed offered load.""" extra = rtl_files(buffers) ticks = WINDOW_MS[cache] // rate if rate else 0 + store = os.path.join(ARGS.storage, STORE) + if cache == "warm" and not (os.path.isdir(store) and os.listdir(store)): + prime(extra) runs = [] for _ in range(ARGS.tries): with session("workspace", cold=(cache == "cold"), verbose=True, - storage_name="r4-load") as s: + storage_name=STORE) as s: runs.append(one_session(s, rate, ticks, extra, params)) got = summary(runs) if not rate: + # `ms` is the settle time here, and `settled_ms` is already in `got`. record(phase="scanload", row="quiet control, %s cache, %d extra buffer(s)" % (cache, buffers), fresh_process=True, result_count=0, rate_ms=0, - ms=got["settled_ms"], settled_ms=got["settled_ms"], - publication=got["publication"], open_buffers=buffers + 1, - note=QUIET_NOTE) + open_buffers=buffers + 1, note=QUIET_NOTE, + **dict(got, ms=got["settled_ms"])) return - status, message = cell_status(got) + status, message = cell_status(got, cache) got["ms"] = got["ms"] or [0.0] record(phase="scanload", row="%sdefinition every %d ms, %s cache, %d extra buffer(s)"