From 36733e2c7c1c91d536017cdc359a3597145b24cc Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Thu, 26 Nov 2026 19:29:02 -0800 Subject: [PATCH] Round 10: resumable discovery walk and faster whole rescans (#58, #64) #58: the discovery walk runs in 512-entry slices with requests drained between them (lucisv_core ResumableWalk, state/walking.rs); identities are read in one pass at landing. Proved equal to the one-shot walk. #64: the 40k rescan timing split is not reproducible; the store is kept across rescans, compaction streams, candidates are cheaper (-12% on 40k, answers and store byte-identical). Files topo #71-#74. Co-Authored-By: Claude Mythos 5.2 --- TODO.md | 6 +- crates/lucisv_core/src/walk.rs | 5 +- crates/lucisv_core/src/walk/resumable.rs | 246 ++++++++ .../lucisv_core/src/walk/resumable/tests.rs | 277 +++++++++ crates/lucisv_server/src/candidates.rs | 12 +- crates/lucisv_server/src/index_cache.rs | 116 +++- .../src/index_cache/reuse_tests.rs | 204 +++++++ crates/lucisv_server/src/scan_trace.rs | 18 +- crates/lucisv_server/src/server/index.rs | 57 +- crates/lucisv_server/src/server/tests/mod.rs | 2 + .../src/server/tests/qa_walking.rs | 161 ++++++ .../src/server/tests/scan_trace.rs | 5 +- .../lucisv_server/src/server/tests/walking.rs | 272 +++++++++ crates/lucisv_server/src/state/discover.rs | 84 +-- crates/lucisv_server/src/state/mod.rs | 4 + crates/lucisv_server/src/state/rescan.rs | 178 ++++-- crates/lucisv_server/src/state/scan.rs | 41 +- .../src/state/tests/interleave.rs | 6 + crates/lucisv_server/src/state/tests/mod.rs | 3 + .../src/state/tests/qa_walking.rs | 136 +++++ .../lucisv_server/src/state/tests/walking.rs | 441 ++++++++++++++ .../src/state/tests/walking_replace.rs | 80 +++ crates/lucisv_server/src/state/walking.rs | 244 ++++++++ crates/lucisv_server/src/state/watched.rs | 2 +- docs/features/server-scaling-r10/README.md | 536 ++++++++++++++++++ docs/topo.md | 14 +- tools/perf/bigtree.py | 102 ++++ tools/perf/rescan.py | 257 +++++++++ tools/perf/rescan_diff.py | 137 +++++ 29 files changed, 3520 insertions(+), 126 deletions(-) create mode 100644 crates/lucisv_core/src/walk/resumable.rs create mode 100644 crates/lucisv_core/src/walk/resumable/tests.rs create mode 100644 crates/lucisv_server/src/index_cache/reuse_tests.rs create mode 100644 crates/lucisv_server/src/server/tests/qa_walking.rs create mode 100644 crates/lucisv_server/src/server/tests/walking.rs create mode 100644 crates/lucisv_server/src/state/tests/qa_walking.rs create mode 100644 crates/lucisv_server/src/state/tests/walking.rs create mode 100644 crates/lucisv_server/src/state/tests/walking_replace.rs create mode 100644 crates/lucisv_server/src/state/walking.rs create mode 100644 docs/features/server-scaling-r10/README.md create mode 100644 tools/perf/bigtree.py create mode 100644 tools/perf/rescan.py create mode 100644 tools/perf/rescan_diff.py diff --git a/TODO.md b/TODO.md index 9749b7b..8d3f4b9 100644 --- a/TODO.md +++ b/TODO.md @@ -7476,7 +7476,7 @@ indexing, collide with each other and with §70's test files, and wait for - Wave 7 (lead, 2026-11-19): 71.3 shipped as 0.65.10, re-applied onto 0.65.8's message loop by hand and re-validated by a second QA round. Left open from it: - - [ ] The discovery walk at the start of every scan answers nothing while + - [x] The discovery walk at the start of every scan answers nothing while it runs: a late open in workspace scope still waits 62–86 ms for colour and a rescan holds colours 70–159 ms. Making the walk resumable needs its own identical-result proof (`state/discover.rs`). @@ -7498,8 +7498,10 @@ indexing, collide with each other and with §70's test files, and wait for - [ ] Whether a large open buffer is in the index depends on when it was opened, saved or scanned (predates the lane; 77–98 answers differ between a settled session and a fresh server on OpenTitan). - - [ ] The 40 000-file rescan after a delete takes either 12.3 s or + - [x] The 40 000-file rescan after a delete takes either 12.3 s or 14.5–15.5 s, on 0.65.10 and on this tree alike; cause not found. + (Round 10: not reproducible on a quiet machine — unimodal 7.4–7.8 s + over 39 runs; closed as such in topo §2.9-64, remainder in #71/#72.) ## 72. Sticky scroll pins the module instance (planned 2026-11-19, owner's order) diff --git a/crates/lucisv_core/src/walk.rs b/crates/lucisv_core/src/walk.rs index ef13ca2..bde2d48 100644 --- a/crates/lucisv_core/src/walk.rs +++ b/crates/lucisv_core/src/walk.rs @@ -7,6 +7,9 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; +mod resumable; +pub use resumable::ResumableWalk; + /// File extensions lucisv formats when walking a directory. pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"]; @@ -217,7 +220,7 @@ pub enum DirStatus { /// Tracks visited directories across one or more walks to ensure cycle termination /// and detect order divergence. -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct DirectoryTracker { visited: HashMap, has_conflict: bool, diff --git a/crates/lucisv_core/src/walk/resumable.rs b/crates/lucisv_core/src/walk/resumable.rs new file mode 100644 index 0000000..b747852 --- /dev/null +++ b/crates/lucisv_core/src/walk/resumable.rs @@ -0,0 +1,246 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! The directory walk of [`collect_files_tracked`](super::collect_files_tracked), +//! a slice at a time. +//! +//! The language server walks the whole workspace at the start of every scan, +//! and until TODO §71's last open item (`docs/features/server-scaling-r10`) +//! it did so in one call that held the workspace for 25–80 ms on OpenTitan +//! and ~260 ms on 40 000 files, answering nothing. This walk is the same +//! walk with its recursion turned into an explicit stack, so the caller can +//! stop it after a bounded number of entries, answer what is waiting, and +//! carry on from exactly where it stopped. +//! +//! **Same walk, not a similar one.** Every filesystem call the recursive walk +//! makes is made here in the same order with the same arguments — `enter`, +//! the directory's `.gitignore`, `read_dir`, then per entry the exclude test, +//! one `metadata`, the ignore test and either a descent or a hand-off — so on +//! a tree that does not change while it runs the two yield the same paths, +//! lengths and warnings in the same order and leave the tracker the same. +//! The module tests prove it for every slice size on trees built to exercise +//! every branch. On a tree that *does* change, each directory is seen as it +//! was when it was read, exactly as the recursive walk sees it; slicing only +//! widens the window. + +use std::path::{Path, PathBuf}; + +use super::{ + broken_link_reason, is_excluded, is_ignored, is_source, parse_gitignore, DirStatus, + DirectoryTracker, Ignore, Warning, GITIGNORE, +}; + +/// One directory being read: its entries still to visit, in name order, and +/// whether entering it pushed a `.gitignore` the walk must pop on leaving. +struct Frame { + entries: std::vec::IntoIter, + pushed: bool, +} + +/// A walk of one input, resumable between any two directory entries. +/// +/// A file is handed over with the `metadata` the walk read for it — the +/// length [`collect_files_with`](super::collect_files_with) hands over. +/// `None` for an input named rather than walked, exactly as there. Its +/// identity is not taken from it: two entries visited slices apart can see +/// one file as two, so a caller reads identities together after the walk. +/// +/// Built by [`ResumableWalk::new`], advanced by [`ResumableWalk::step`] until +/// it reports it is done. The tracker is the caller's and is passed to every +/// step, so several walks — or a walk and a one-shot one — can share one set +/// of directory identities exactly as [`collect_files_tracked`]'s callers do. +/// +/// [`collect_files_tracked`]: super::collect_files_tracked +pub struct ResumableWalk { + input: PathBuf, + exclude: Vec, + gitignore: bool, + ignores: Vec, + rel: Vec, + frames: Vec, + started: bool, + done: bool, + error: Option, +} + +impl ResumableWalk { + /// A walk of `input` that has not touched the filesystem yet. + pub fn new(input: &Path, exclude: Vec, gitignore: bool) -> ResumableWalk { + ResumableWalk { + input: input.to_path_buf(), + exclude, + gitignore, + ignores: Vec::new(), + rel: Vec::new(), + frames: Vec::new(), + started: false, + done: false, + error: None, + } + } + + /// Whether the walk has finished. + pub fn is_done(&self) -> bool { + self.done + } + + /// What [`collect_files_tracked`](super::collect_files_tracked) would have + /// returned as its error: `input` naming nothing at all. + pub fn error(&self) -> Option<&str> { + self.error.as_deref() + } + + /// Visit at most `budget` more entries — starting the walk and leaving a + /// directory count as one each — and report how many were visited; the + /// walk is over when [`ResumableWalk::is_done`] says so. A `budget` of 0 + /// is treated as 1, so every step makes progress. + pub fn step( + &mut self, + tracker: &mut DirectoryTracker, + budget: usize, + found: &mut dyn FnMut(PathBuf, Option<&std::fs::Metadata>), + warn: &mut dyn FnMut(Warning), + ) -> usize { + let budget = budget.max(1); + let mut visited = 0; + if !self.started { + self.started = true; + self.start(tracker, found, warn); + visited += 1; + } + while !self.done && visited < budget { + visited += 1; + self.next_entry(tracker, found, warn); + } + visited + } + + /// The first step: what the input is decides whether there is a walk. + fn start( + &mut self, + tracker: &mut DirectoryTracker, + found: &mut dyn FnMut(PathBuf, Option<&std::fs::Metadata>), + warn: &mut dyn FnMut(Warning), + ) { + let input = self.input.clone(); + if input.is_dir() { + self.open(&input, tracker, warn); + } else if input.is_file() { + found(input, None); + } else { + self.error = Some(format!("{}: no such file or directory", input.display())); + } + self.done = self.frames.is_empty(); + } + + /// `Walk::dir`'s first half: enter `dir`, push its ignore file, read it. + /// Returns whether a frame was pushed (the directory was entered). + fn open( + &mut self, + dir: &Path, + tracker: &mut DirectoryTracker, + warn: &mut dyn FnMut(Warning), + ) -> bool { + if !matches!(tracker.enter(dir), DirStatus::EnteredFirstTime) { + return false; + } + let pushed = self.push_ignore(dir, warn); + let entries = read_sorted(dir, warn); + self.frames.push(Frame { entries: entries.into_iter(), pushed }); + true + } + + /// One entry of the innermost directory, or leaving it when it has none. + fn next_entry( + &mut self, + tracker: &mut DirectoryTracker, + found: &mut dyn FnMut(PathBuf, Option<&std::fs::Metadata>), + warn: &mut dyn FnMut(Warning), + ) { + let Some(frame) = self.frames.last_mut() else { + self.done = true; + return; + }; + let Some(entry) = frame.entries.next() else { + return self.leave(); + }; + let path = entry.path(); + if is_excluded(&path, &self.exclude) { + return; + } + let Ok(meta) = std::fs::metadata(&path) else { + if is_source(&path) { + warn(Warning { path: path.clone(), message: broken_link_reason(&path) }); + } + return; + }; + self.rel.push(entry.file_name().to_string_lossy().into_owned()); + if !is_ignored(&self.ignores, &self.rel, meta.is_dir()) { + if meta.is_dir() { + if self.open(&path, tracker, warn) { + // The name stays on `rel` until this directory is left. + return; + } + } else if meta.is_file() && is_source(&path) { + found(path, Some(&meta)); + } + } + self.rel.pop(); + } + + /// `Walk::dir`'s second half: pop the ignore file, and the directory's + /// own name — which the root never had. + fn leave(&mut self) { + let Some(frame) = self.frames.pop() else { return }; + if frame.pushed { + self.ignores.pop(); + } + if self.frames.is_empty() { + self.done = true; + } else { + self.rel.pop(); + } + } + + /// `Walk::push_ignore`, word for word. + fn push_ignore(&mut self, dir: &Path, warn: &mut dyn FnMut(Warning)) -> bool { + let path = dir.join(GITIGNORE); + if !self.gitignore || !path.is_file() { + return false; + } + match std::fs::read_to_string(&path) { + Ok(text) => { + self.ignores.push(Ignore { base: self.rel.len(), rules: parse_gitignore(&text) }); + true + } + Err(e) => { + warn(Warning { path, message: e.to_string() }); + false + } + } + } +} + +/// `Walk::entries`' read: every entry of `dir` in path order, each error said. +fn read_sorted(dir: &Path, warn: &mut dyn FnMut(Warning)) -> Vec { + let read = match std::fs::read_dir(dir) { + Ok(read) => read, + Err(e) => { + warn(Warning { path: dir.to_path_buf(), message: e.to_string() }); + return Vec::new(); + } + }; + let mut entries = Vec::new(); + for entry in read { + match entry { + Ok(entry) => entries.push(entry), + Err(e) => warn(Warning { path: dir.to_path_buf(), message: e.to_string() }), + } + } + entries.sort_by_key(|e| e.path()); + entries +} + +#[cfg(test)] +mod tests; + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_core/src/walk/resumable/tests.rs b/crates/lucisv_core/src/walk/resumable/tests.rs new file mode 100644 index 0000000..fb6219b --- /dev/null +++ b/crates/lucisv_core/src/walk/resumable/tests.rs @@ -0,0 +1,277 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! The identical-result proof at the walk's own level: for every slice size, +//! and for slice sizes that change from step to step, the resumable walk +//! yields exactly what the recursive walk yields — the same events in the +//! same order, the same error, and the same tracker afterwards. + +use super::super::collect_files_tracked; +use super::*; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// What a walk said, in the order it said it. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Event { + Found(PathBuf, Option), + Warned(Warning), +} + +/// A scratch tree, removed on drop. +struct Tree { + path: PathBuf, +} + +impl Tree { + fn new(tag: &str) -> Tree { + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = + std::env::temp_dir().join(format!("lucisv-resumable-{}-{tag}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("create temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) { + let path = self.path.join(rel); + std::fs::create_dir_all(path.parent().expect("parent")).expect("create parent"); + std::fs::write(&path, text).expect("write"); + } + + #[cfg(unix)] + fn link(&self, rel: &str, target: &str) { + let path = self.path.join(rel); + std::fs::create_dir_all(path.parent().expect("parent")).expect("create parent"); + std::os::unix::fs::symlink(target, &path).expect("symlink"); + } +} + +impl Drop for Tree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +/// Every branch of the walk in one tree: nested `.gitignore` files with a +/// negation and a directory-only rule, an exclude pattern, non-source files, +/// empty directories, and — on unix — a cycle, two aliases of one directory +/// sorting before and after it, and a dangling source link. +fn busy_tree(tag: &str) -> Tree { + let tree = Tree::new(tag); + tree.write(".gitignore", "build/\n*_gen.sv\n"); + tree.write("a.sv", "module a;\nendmodule\n"); + tree.write("notes.txt", "x"); + tree.write("rtl/b.sv", "module b;\nendmodule\n"); + tree.write("rtl/b_gen.sv", "module bg;\nendmodule\n"); + tree.write("rtl/.gitignore", "!keep_gen.sv\nlocal/\n"); + tree.write("rtl/keep_gen.sv", "module k;\nendmodule\n"); + tree.write("rtl/local/hidden.sv", "module h;\nendmodule\n"); + tree.write("rtl/deep/er/c.svh", "`define C\n"); + tree.write("build/out.sv", "module o;\nendmodule\n"); + tree.write("skipme/s.sv", "module s;\nendmodule\n"); + tree.write("z_real/inc.vh", "`define Z\n"); + std::fs::create_dir_all(tree.path.join("empty/inner")).expect("empty dirs"); + #[cfg(unix)] + { + tree.link("rtl/loop", ".."); + tree.link("a_alias", "z_real"); + tree.link("zz_alias", "z_real"); + tree.link("rtl/gone.sv", "nowhere.sv"); + } + tree +} + +/// The recursive walk's events, error and tracker — the oracle. +fn one_shot(input: &Path, exclude: &[String], tracker: DirectoryTracker) -> Outcome { + let mut tracker = tracker; + let mut events = Vec::new(); + let error = { + let events = std::cell::RefCell::new(&mut events); + collect_files_tracked( + input.to_str().expect("utf-8 temp path"), + exclude, + true, + &mut tracker, + &mut |path, len| events.borrow_mut().push(Event::Found(path, len)), + &mut |w| events.borrow_mut().push(Event::Warned(w)), + ) + .err() + }; + Outcome { events, error, tracker, steps: 1 } +} + +/// What one walk produced. +#[derive(Debug, PartialEq, Eq)] +struct Outcome { + events: Vec, + error: Option, + tracker: DirectoryTracker, + /// How many `step` calls it took (not compared). + steps: usize, +} + +impl Outcome { + fn same_as(&self, other: &Outcome) -> bool { + self.events == other.events && self.error == other.error && self.tracker == other.tracker + } +} + +/// The resumable walk with the budget for each step chosen by `budget`. +fn sliced( + input: &Path, + exclude: &[String], + tracker: DirectoryTracker, + budget: &mut dyn FnMut() -> usize, +) -> Outcome { + let mut tracker = tracker; + let mut events = Vec::new(); + let mut walk = ResumableWalk::new(input, exclude.to_vec(), true); + let mut steps = 0; + loop { + steps += 1; + let events = std::cell::RefCell::new(&mut events); + let size = budget(); + let visited = walk.step( + &mut tracker, + size, + &mut |path, meta| events.borrow_mut().push(Event::Found(path, meta.map(|m| m.len()))), + &mut |w| events.borrow_mut().push(Event::Warned(w)), + ); + assert!(visited >= 1 && visited <= size.max(1), "{visited} of {size}"); + if walk.is_done() { + break; + } + assert!(steps < 100_000, "the walk makes progress"); + } + assert!(walk.is_done()); + Outcome { events, error: walk.error().map(str::to_string), tracker, steps } +} + +/// Every fixed slice size from 1 to one past the whole walk. +fn every_slice_size(input: &Path, exclude: &[String], tracker: DirectoryTracker) -> usize { + let oracle = one_shot(input, exclude, tracker.clone()); + let longest = sliced(input, exclude, tracker.clone(), &mut || 1).steps; + for size in 1..=longest + 1 { + let got = sliced(input, exclude, tracker.clone(), &mut || size); + assert!(got.same_as(&oracle), "slice size {size}:\n{got:#?}\nvs\n{oracle:#?}"); + } + longest +} + +#[test] +fn every_slice_size_walks_exactly_what_the_recursive_walk_walks() { + let tree = busy_tree("every"); + let exclude = vec!["skipme".to_string()]; + let entries = every_slice_size(&tree.path, &exclude, DirectoryTracker::new()); + // Premise: the walk is long enough for slicing to matter. + assert!(entries > 20, "{entries} steps"); + let oracle = one_shot(&tree.path, &exclude, DirectoryTracker::new()); + let found = oracle.events.iter().filter(|e| matches!(e, Event::Found(..))).count(); + assert!(found >= 5, "premise: the tree has files to find: {oracle:#?}"); +} + +#[test] +fn slice_sizes_that_change_between_steps_walk_the_same() { + // Property-style: 200 seeds of a small linear congruential generator pick + // each step's budget between 1 and 7. + let tree = busy_tree("random"); + let exclude = vec!["skipme".to_string()]; + let oracle = one_shot(&tree.path, &exclude, DirectoryTracker::new()); + for seed in 0..200u64 { + let mut state = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + let mut budget = || { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + 1 + ((state >> 33) % 7) as usize + }; + let got = sliced(&tree.path, &exclude, DirectoryTracker::new(), &mut budget); + assert!(got.same_as(&oracle), "seed {seed}"); + } +} + +#[test] +fn a_tracker_another_walk_already_filled_is_honoured_the_same_way() { + // The split startup: the head walk enters a folder first, then the rest + // walks the root with the same tracker — so a directory may already be + // visited, and an alias may be a precedence conflict. + let tree = busy_tree("shared"); + let mut tracker = DirectoryTracker::new(); + let _ = tracker.enter(&tree.path.join("z_real")); + let _ = tracker.enter(&tree.path.join("rtl")); + every_slice_size(&tree.path, &[], tracker.clone()); + #[cfg(unix)] + assert!( + one_shot(&tree.path, &[], tracker).tracker.has_conflict(), + "premise: a_alias sorts first" + ); +} + +#[test] +fn a_file_a_missing_path_and_an_entered_root_end_as_the_recursive_walk_does() { + let tree = busy_tree("inputs"); + every_slice_size(&tree.path.join("a.sv"), &[], DirectoryTracker::new()); + every_slice_size(&tree.path.join("nothing-here"), &[], DirectoryTracker::new()); + let mut entered = DirectoryTracker::new(); + let _ = entered.enter(&tree.path); + every_slice_size(&tree.path, &[], entered); + let missing = one_shot(&tree.path.join("nothing-here"), &[], DirectoryTracker::new()); + assert!(missing.error.is_some(), "premise: a missing input is an error"); +} + +#[test] +#[cfg(unix)] +fn unreadable_directories_and_ignore_files_are_said_at_the_same_point() { + use std::os::unix::fs::PermissionsExt; + let tree = busy_tree("unreadable"); + tree.write("locked/x.sv", "module x;\nendmodule\n"); + tree.write("shut/.gitignore", "*\n"); + tree.write("shut/y.sv", "module y;\nendmodule\n"); + let mode = |rel: &str, bits| { + std::fs::set_permissions(tree.path.join(rel), std::fs::Permissions::from_mode(bits)) + .expect("chmod") + }; + mode("locked", 0o000); + mode("shut/.gitignore", 0o000); + let refused = std::fs::read_dir(tree.path.join("locked")).is_err(); + every_slice_size(&tree.path, &[], DirectoryTracker::new()); + let oracle = one_shot(&tree.path, &[], DirectoryTracker::new()); + mode("locked", 0o755); + mode("shut/.gitignore", 0o644); + if refused { + let warned = oracle.events.iter().filter(|e| matches!(e, Event::Warned(..))).count(); + assert!(warned >= 2, "premise: both are said: {oracle:#?}"); + } else { + eprintln!("skipped premise: a mode-000 directory is readable by this user (root?)"); + } +} + +/// QA (2026-11-26): budgets at the edges, a root that is itself a symlink to +/// a directory, an ignored-then-negated directory with its own nested +/// `.gitignore`, and a deep chain — still the recursive walk's events. +#[test] +fn qa_edge_budgets_a_symlinked_root_a_negated_dir_and_a_deep_chain_walk_the_same() { + let tree = busy_tree("qa-edges"); + tree.write(".gitignore", "build/\n*_gen.sv\nvendor/\n!vendor/\n"); + tree.write("vendor/.gitignore", "*.svh\n!keep.svh\n"); + tree.write("vendor/v.sv", "module v;\nendmodule\n"); + tree.write("vendor/drop.svh", "`define D\n"); + tree.write("vendor/keep.svh", "`define K\n"); + let deep: String = (0..40).map(|n| format!("d{n}/")).collect(); + tree.write(&format!("{deep}leaf.sv"), "module leaf;\nendmodule\n"); + let oracle = one_shot(&tree.path, &[], DirectoryTracker::new()); + for budget in [0usize, usize::MAX] { + let got = sliced(&tree.path, &[], DirectoryTracker::new(), &mut || budget); + assert!(got.same_as(&oracle), "budget {budget}"); + } + every_slice_size(&tree.path, &[], DirectoryTracker::new()); + #[cfg(unix)] + { + let outside = Tree::new("qa-edges-link"); + let root = outside.path.join("root_link"); + std::os::unix::fs::symlink(&tree.path, &root).expect("symlink"); + every_slice_size(&root, &[], DirectoryTracker::new()); + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/candidates.rs b/crates/lucisv_server/src/candidates.rs index 4fb86ae..d48c375 100644 --- a/crates/lucisv_server/src/candidates.rs +++ b/crates/lucisv_server/src/candidates.rs @@ -147,10 +147,20 @@ impl Candidates { pub fn from_words(index: &WorkspaceIndex, words: HashMap>) -> Candidates { let mut out = Candidates::default(); out.take_index_tables(index); + // Sized once and counted without a copy per occurrence: on 40 000 + // files that is 3.5 M word occurrences and 140 k distinct words, and + // `entry(word.clone())` allocated a `String` for every one of the + // 3.5 M (`docs/features/server-scaling-r10/README.md`). + out.per_file.reserve(words.len()); for (path, words) in words { let words = insertable(words); for word in &words { - *out.word_files.entry(word.clone()).or_default() += 1; + match out.word_files.get_mut(word.as_str()) { + Some(files) => *files += 1, + None => { + out.word_files.insert(word.clone(), 1); + } + } } if !words.is_empty() { out.per_file.insert(path, words); diff --git a/crates/lucisv_server/src/index_cache.rs b/crates/lucisv_server/src/index_cache.rs index 97562f8..89364b3 100644 --- a/crates/lucisv_server/src/index_cache.rs +++ b/crates/lucisv_server/src/index_cache.rs @@ -66,7 +66,7 @@ const OS_DIR: [&str; 2] = ["lucisv", "index"]; /// header, a torn line, a record the checksum rejects, two lines for one path, /// a session's appends still unvacuumed — means the file and the render differ, /// and compaction is what makes them the same. -#[derive(Clone, Copy, Default)] +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] struct Load { /// Whether the first line was this build's own header. header: bool, @@ -122,6 +122,12 @@ pub struct IndexCache { /// What [`IndexCache::open`] read out of the store, which is what /// [`IndexCache::already_compact`] asks whether a rewrite would reproduce. load: Load, + /// The store file as it was when `entries`, `header_ok` and `load` were + /// exactly what [`IndexCache::open`] would read out of it — after a load, + /// after a compaction — and `None` once anything was appended. What lets + /// the next whole rescan keep this cache instead of reading the file + /// again ([`IndexCache::reopen`]). + synced: Option, /// What this cache's own work has cost since it was opened, for the /// startup breakdown (`docs/features/perf5-p4/README.md`). /// @@ -159,6 +165,7 @@ impl IndexCache { /// [`IndexCache::compact`] would write over it. pub fn open(dir: Option) -> IndexCache { let Some(dir) = dir else { return IndexCache::disabled() }; + let before = Stamp::of(&dir.join(FILE)); let bytes = std::fs::read(dir.join(FILE)).unwrap_or_default(); let mut lines = store_lines(&bytes).into_iter(); let header_ok = lines.next() == Some(header().as_bytes()); @@ -190,7 +197,33 @@ impl IndexCache { } } let work = Cell::new(CacheWork { opens: 1, ..CacheWork::default() }); - IndexCache { dir: Some(dir), entries, log: None, header_ok, load, work } + // Synced only when nothing moved the file while it was read. + let after = Stamp::of(&dir.join(FILE)); + let synced = before.filter(|_| before == after); + IndexCache { dir: Some(dir), entries, log: None, header_ok, load, synced, work } + } + + /// The cache a whole rescan opens on `dir`: this one, kept, when the + /// store file is still exactly the file it was synced with — else the + /// file read again ([`IndexCache::open`]). + /// + /// **The same cache either way.** Kept, its entries, header flag and load + /// counts are the ones a read of that file produces (`synced` is set only + /// when they are, and dropped by the first append); the file is judged + /// unchanged by its length, modification time and inode, so a record + /// another session appended, or a store it compacted and renamed over + /// ours, is read again. What is saved is the read: 44 MiB and ~65 ms on + /// OpenTitan, ~470 MiB and ~680 ms on 40 000 files, before a rescan's + /// first file (`docs/features/server-scaling-r10/README.md`). + pub fn reopen(self, dir: Option) -> IndexCache { + let file = dir.as_ref().map(|dir| dir.join(FILE)); + let unchanged = self.synced.is_some() && self.synced == file.as_deref().and_then(Stamp::of); + if self.dir.is_none() || self.dir != dir || !unchanged { + return IndexCache::open(dir); + } + let IndexCache { dir, entries, header_ok, load, synced, .. } = self; + let work = Cell::new(CacheWork::default()); + IndexCache { dir, entries, log: None, header_ok, load, synced, work } } /// What this cache has spent and moved since it was opened. @@ -412,26 +445,55 @@ impl IndexCache { } let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id())); let store = dir.join(FILE); - if std::fs::write(&tmp, self.render()).is_ok() { + // What the rewrite leaves out is dropped here too, so the entries + // held afterwards are exactly the file's. + self.entries.retain(|path, _| path.exists()); + self.synced = None; + if self.render_to(&tmp).is_ok() { if std::fs::rename(&tmp, &store).is_err() { let _ = std::fs::remove_file(&tmp); return; } self.header_ok = true; + let n = self.entries.len(); + self.load = Load { header: true, read: n, kept: n, ordered: true, ..Load::default() }; + self.synced = Stamp::of(&store); } } - /// The store's text: the header, then the live entries in path order, so - /// two sessions over the same workspace write byte-identical stores. - fn render(&self) -> String { + /// Write the store's text to `path`: the header, then the live entries in + /// path order, so two sessions over the same workspace write + /// byte-identical stores. + /// + /// **Streamed**, a record at a time through one buffer: the text used to + /// be built whole first, a second copy of every record — ~470 MiB on + /// 40 000 files — held beside the entries for the length of the write + /// (`docs/features/server-scaling-r10/README.md`). The bytes are the + /// same; [`IndexCache::render`] is that text, for the tests that pin it. + fn render_to(&self, path: &Path) -> std::io::Result<()> { + let mut out = std::io::BufWriter::with_capacity(1 << 20, File::create(path)?); + out.write_all(header().as_bytes())?; + out.write_all(b"\n")?; + for path in self.sorted_paths() { + let entry = &self.entries[path]; + write_line(&mut out, entry.content, &entry.facts)?; + } + out.flush() + } + + /// The entries' paths in the order the store is written in. + fn sorted_paths(&self) -> Vec<&PathBuf> { let mut paths: Vec<&PathBuf> = self.entries.keys().collect(); paths.sort(); + paths + } + + /// The store's text as [`IndexCache::render_to`] writes it. + #[cfg(test)] + fn render(&self) -> String { let mut text = header(); text.push('\n'); - for path in paths { - if !path.exists() { - continue; - } + for path in self.sorted_paths() { let entry = &self.entries[path]; text.push_str(&line(entry.content, &entry.facts)); text.push('\n'); @@ -440,7 +502,9 @@ impl IndexCache { } /// Append one record, opening the store on the first write of a session. + /// The cache is no longer what a read of the file gives. fn append(&mut self, record: &str) { + self.synced = None; if self.log.is_none() { self.log = self.open_log(); } @@ -475,6 +539,28 @@ impl IndexCache { } } +/// What a store file looked like: enough to tell that it is still the same +/// file with the same bytes — an append grows it, a rewrite renames a new +/// inode over it, and either moves the modification time. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +struct Stamp { + len: u64, + modified: Option, + inode: u64, +} + +impl Stamp { + /// The stamp of the file at `path`, or `None` when there is none. + fn of(path: &Path) -> Option { + let meta = std::fs::metadata(path).ok()?; + #[cfg(unix)] + let inode = std::os::unix::fs::MetadataExt::ino(&meta); + #[cfg(not(unix))] + let inode = 0; + Some(Stamp { len: meta.len(), modified: meta.modified().ok(), inode }) + } +} + /// What is at the top of the store on disk right now. enum Header { /// This build's header, whoever wrote it. @@ -562,6 +648,13 @@ fn line(content: u64, facts: &str) -> String { format!("{content:016x}\t{facts}\t{:016x}", content_hash(facts.as_bytes())) } +/// [`line`] and its newline, written straight to `out` — the same bytes. +fn write_line(out: &mut impl Write, content: u64, facts: &str) -> std::io::Result<()> { + write!(out, "{content:016x}\t")?; + out.write_all(facts.as_bytes())?; + writeln!(out, "\t{:016x}", content_hash(facts.as_bytes())) +} + /// One record read back — the hash and the path, with the facts left encoded. /// `None` for anything that is not a whole record whose facts still match /// their checksum, which includes the torn last line of a store whose writer @@ -672,6 +765,9 @@ fn os_cache_dir() -> Option { } } +#[cfg(test)] +mod reuse_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/lucisv_server/src/index_cache/reuse_tests.rs b/crates/lucisv_server/src/index_cache/reuse_tests.rs new file mode 100644 index 0000000..4765dec --- /dev/null +++ b/crates/lucisv_server/src/index_cache/reuse_tests.rs @@ -0,0 +1,204 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! The store kept across whole rescans ([`IndexCache::reopen`]) is the store +//! read again: same entries, same header flag, same load counts — kept only +//! while the file is the one it was synced with, read again the moment +//! anything else touched it. + +use super::*; + +/// A throwaway store directory with sources beside it, removed on drop. +struct Dir { + path: PathBuf, +} + +impl Dir { + fn new(tag: &str) -> Dir { + let path = + std::env::temp_dir().join(format!("lucisv-cache-reuse-{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("temp dir"); + Dir { path } + } + + /// A source on disk and its facts. + fn source(&self, name: &str) -> (PathBuf, String, FileFacts) { + let path = self.path.join(name); + let text = format!("module {};\nendmodule\n", name.trim_end_matches(".sv")); + std::fs::write(&path, &text).expect("write source"); + let facts = FileFacts::of(path.clone(), &text); + (path, text, facts) + } + + fn store(&self) -> Option { + Some(self.path.clone()) + } +} + +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +/// Everything a reader of the cache can tell apart. +fn state(cache: &IndexCache) -> String { + let mut entries: Vec = cache + .entries + .iter() + .map(|(path, entry)| format!("{path:?} {:016x} {}", entry.content, entry.facts)) + .collect(); + entries.sort(); + format!("{:?} {} {:?}\n{}", cache.dir, cache.header_ok, cache.load, entries.join("\n")) +} + +/// A cache over `dir` holding `names`, compacted as a whole rescan ends. +fn compacted(dir: &Dir, names: &[&str]) -> IndexCache { + let mut cache = IndexCache::open(dir.store()); + for name in names { + let (_, text, facts) = dir.source(name); + cache.record(&facts, &text); + } + cache.compact(); + cache +} + +#[test] +fn after_a_compaction_the_kept_cache_is_the_store_read_again() { + let dir = Dir::new("kept"); + let cache = compacted(&dir, &["a.sv", "b.sv", "c.sv"]); + let kept = cache.reopen(dir.store()); + assert_eq!(kept.work().opens, 0, "kept, not read"); + assert_eq!(state(&kept), state(&IndexCache::open(dir.store()))); + // And it compacts as the re-read one would: nothing to rewrite. + let mut kept = kept; + kept.compact(); + assert_eq!(kept.work().compactions, 0, "the store is already what a rewrite gives"); +} + +#[test] +fn a_file_gone_before_the_compaction_leaves_the_kept_cache_as_it_leaves_the_store() { + let dir = Dir::new("gone"); + let mut cache = IndexCache::open(dir.store()); + for name in ["a.sv", "b.sv"] { + let (_, text, facts) = dir.source(name); + cache.record(&facts, &text); + } + std::fs::remove_file(dir.path.join("b.sv")).expect("remove"); + cache.compact(); + let kept = cache.reopen(dir.store()); + assert_eq!(kept.work().opens, 0); + assert_eq!(state(&kept), state(&IndexCache::open(dir.store()))); + assert_eq!(kept.entry_count(), 1); +} + +#[test] +fn a_store_another_session_appended_to_is_read_again() { + let dir = Dir::new("appended"); + let cache = compacted(&dir, &["a.sv"]); + let mut other = IndexCache::open(dir.store()); + let (_, text, facts) = dir.source("z.sv"); + other.record(&facts, &text); + let reopened = cache.reopen(dir.store()); + assert_eq!(reopened.work().opens, 1, "read again"); + assert_eq!(state(&reopened), state(&IndexCache::open(dir.store()))); + assert_eq!(reopened.entry_count(), 2, "with the other session's record"); +} + +#[test] +fn a_store_another_session_compacted_over_ours_is_read_again() { + let dir = Dir::new("renamed"); + let cache = compacted(&dir, &["a.sv"]); + let mut other = IndexCache::open(dir.store()); + let (_, text, facts) = dir.source("b.sv"); + other.record(&facts, &text); + other.compact(); + let reopened = cache.reopen(dir.store()); + assert_eq!(reopened.work().opens, 1); + assert_eq!(state(&reopened), state(&IndexCache::open(dir.store()))); +} + +#[test] +fn our_own_append_since_the_compaction_reads_the_store_again() { + let dir = Dir::new("ownappend"); + let mut cache = compacted(&dir, &["a.sv"]); + let (_, text, facts) = dir.source("b.sv"); + cache.record(&facts, &text); + let reopened = cache.reopen(dir.store()); + assert_eq!(reopened.work().opens, 1); + assert_eq!(state(&reopened), state(&IndexCache::open(dir.store()))); +} + +#[test] +fn another_directory_or_no_directory_is_never_the_kept_cache() { + let dir = Dir::new("otherdir"); + let elsewhere = Dir::new("otherdir2"); + let cache = compacted(&dir, &["a.sv"]); + let moved = cache.reopen(elsewhere.store()); + assert_eq!(moved.work().opens, 1); + assert_eq!(moved.entry_count(), 0); + let off = compacted(&dir, &["a.sv"]).reopen(None); + assert_eq!(off.dir, None, "persistence off is the disabled cache"); + // A freshly opened store that nothing has touched is kept as well. + let opened = IndexCache::open(dir.store()); + let kept = opened.reopen(dir.store()); + assert_eq!(kept.work().opens, 0); + assert_eq!(state(&kept), state(&IndexCache::open(dir.store()))); +} + +#[test] +fn the_streamed_rewrite_writes_the_text_the_whole_render_was() { + // Byte for byte, with records long and short and a path that sorts + // between two others, against the old whole-text render. + let dir = Dir::new("streamed"); + let mut cache = IndexCache::open(dir.store()); + for name in ["b.sv", "a.sv", "ab.sv", "zz_long.sv"] { + let (_, text, facts) = dir.source(name); + cache.record(&facts, &text); + } + for k in 0..12 { + let big = dir.path.join(format!("big{k}.sv")); + let text: String = (0..2_000).map(|n| format!("module m{k}_{n}; endmodule\n")).collect(); + std::fs::write(&big, &text).expect("write"); + cache.record(&FileFacts::of(big, &text), &text); + } + cache.compact(); + let written = std::fs::read_to_string(dir.path.join(FILE)).expect("the store"); + assert_eq!(written, cache.render()); + assert!(written.len() > 1 << 20, "premise: more than the write buffer"); +} + +/// QA (2026-11-26): the one change the (length, mtime, inode) stamp cannot +/// see — the store rewritten in place to the same length with its mtime put +/// back (no lucisv writer does this; `cp -p` over it or a tool that restores +/// times would). The kept cache then differs from a fresh read, and this +/// pins why that is harmless: every entry is keyed by the hash of the bytes +/// its facts were read from, so the kept cache can only hit where a fresh +/// read misses (or the reverse), and every hit is the parse of those bytes. +#[test] +fn qa_an_in_place_same_length_rewrite_with_its_mtime_restored_is_kept_but_only_changes_hits() { + let dir = Dir::new("qa-inplace"); + let cache = compacted(&dir, &["a.sv"]); + let store = dir.path.join(FILE); + let before = std::fs::metadata(&store).expect("store"); + let mut bytes = std::fs::read(&store).expect("store bytes"); + // The second line is a.sv's record; its first field is the content hash, + // which the per-record checksum (of the facts) does not cover. + let at = bytes.iter().position(|b| *b == b'\n').expect("header") + 1; + bytes[at] = if bytes[at] == b'0' { b'1' } else { b'0' }; + { + let mut file = OpenOptions::new().write(true).open(&store).expect("open in place"); + file.write_all(&bytes).expect("rewrite in place"); + file.set_modified(before.modified().expect("mtime")).expect("restore mtime"); + } + let kept = cache.reopen(dir.store()); + let fresh = IndexCache::open(dir.store()); + assert_eq!(kept.work().opens, 0, "premise: the stamp did not see the rewrite"); + assert_ne!(state(&kept), state(&fresh), "premise: kept and fresh differ"); + let (path, text, facts) = dir.source("a.sv"); + let from_kept = kept.facts_for(&path, &text); + assert!(fresh.facts_for(&path, &text).is_none(), "the rewritten record is a miss"); + assert_eq!(from_kept.map(|f| f.encode()), Some(facts.encode()), "a kept hit is the parse"); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/scan_trace.rs b/crates/lucisv_server/src/scan_trace.rs index abcd624..90f3bea 100644 --- a/crates/lucisv_server/src/scan_trace.rs +++ b/crates/lucisv_server/src/scan_trace.rs @@ -208,6 +208,12 @@ pub struct ScanTrace { /// Whole rescans this scan asked for on its way out. One per `conflict`, /// and nothing else sets it. pub rescan_requested: usize, + /// Discovery holds of the workspace: `begin_scan`, and each walk slice + /// after it (`state/walking.rs`) — how many, and the longest in ms. + /// Measured whether or not the scan is traced, like `conflict`: it is the + /// number topo §2.9-58 asks about. + pub slices: usize, + pub slice_max_ms: f64, /// Sorting into index order and putting the user's own neighbourhood at /// the front ([`crate::scan_order`]). @@ -375,6 +381,12 @@ impl ScanTrace { }; } + /// One discovery hold of the workspace, begun at `from`, ended now. + pub fn saw_slice(&mut self, from: Instant) { + self.slices += 1; + self.slice_max_ms = self.slice_max_ms.max(millis(from)); + } + /// The clock a stage is timed from — `None`, and so free, when off. pub fn now(&self) -> Option { self.on.then(Instant::now) @@ -412,7 +424,7 @@ impl ScanTrace { read={:.2} lookup={:.2} decode={:.2} parse={:.2} encode={:.2} store_write={:.2} \ publish_absorb={:.2} publish_candidates={:.2} publish_includes={:.2} \ publish_overlay={:.2} gone={:.2} absorb={:.2} compact={:.2} candidates={:.2} \ - includes={:.2} overlay={:.2} total={:.2} since_start={:.2} ms", + includes={:.2} overlay={:.2} total={:.2} since_start={:.2} slice_max={:.2} ms", self.number, self.kind, self.read, @@ -443,6 +455,7 @@ impl ScanTrace { self.overlay_ms, self.total_ms, self.since_start_ms, + self.slice_max_ms, ) } @@ -455,7 +468,7 @@ impl ScanTrace { hits={} misses={} buffers={} \ records={} repeats={} decoded_kib={} written_kib={} opens={} compactions={} \ publishes={} published={} first_publish={:.2} overlays={} \ - conflict={} rescan_requested={}", + conflict={} rescan_requested={} slices={}", self.number, self.kind, self.read, @@ -478,6 +491,7 @@ impl ScanTrace { self.overlays, self.conflict, self.rescan_requested, + self.slices, ) } diff --git a/crates/lucisv_server/src/server/index.rs b/crates/lucisv_server/src/server/index.rs index dba60f2..5931b48 100644 --- a/crates/lucisv_server/src/server/index.rs +++ b/crates/lucisv_server/src/server/index.rs @@ -360,37 +360,31 @@ impl Server { let verbose = started.is_some(); let bar = self.begin_indexing(); let mut scan = self.watching(bar.as_ref(), |ws, watch| ws.begin_scan(watch, verbose)); - // A scan that has walked the user's own folders and owes itself the - // rest of the workspace **always** interleaves, whatever its work list - // says today: the whole point of leading with that neighbourhood is - // that the request waiting for it is answered the moment it is in - // (`docs/features/perf5r-first-answer/README.md`). - let interleave = scan.total() > INTERLEAVE_ABOVE || scan.discovery_pending(); - let total = scan.total(); - if started.is_some() { - // Whether it interleaves is said here because it is decided here, - // and because it is the answer to "why did my hover wait?" — a - // scan that does not interleave answers nothing until it is done. - let interleaving = if interleave { ", interleaved" } else { "" }; - let staged = if scan.discovery_pending() { " (the folder first)" } else { "" }; - self.timing(format!( - "scan started: {total} file{}{staged}{interleaving}", - plural(total) - )); - } + // A scan still walking its scope answers between the walk's slices + // whatever its size (`state/walking.rs`); once the walk lands, whether + // it goes on interleaving is decided exactly as it was decided when + // `begin_scan` resolved the whole scope in one call. + let mut interleave = scan.walking() || self.interleaves(&scan, started.is_some()); loop { + let walking = scan.walking(); // **No bar while the denominator can still grow.** The work list // is the neighbourhood so far, and a percentage against it would // fall to a twentieth of itself the moment the rest of the // workspace lands. The per-file log still runs — it names files, // not fractions — and the first percentage the client sees is the // first measured one (`docs/features/indexing-ux/README.md`). - let showing = if scan.discovery_pending() { None } else { bar.as_ref() }; + let showing = if walking || scan.discovery_pending() { None } else { bar.as_ref() }; let stepped = self.watching(showing, |workspace, watch| workspace.scan_step(&mut scan, watch)); if !stepped { break; } + if walking && !scan.walking() { + // The walk has landed. There was never a drain between the + // work list and its first file, and there is none here. + interleave = self.interleaves(&scan, started.is_some()); + continue; + } if interleave && self.answer_what_is_waiting(&mut scan) { // Nothing after this may speak to a client that has gone, the // timing line included. @@ -420,6 +414,31 @@ impl Server { warnings } + /// Whether a scan whose scope has landed answers messages between its + /// files, said in the `scan started` line when `verbose`. + /// + /// A scan that has walked the user's own folders and owes itself the + /// rest of the workspace **always** interleaves, whatever its work list + /// says today: the whole point of leading with that neighbourhood is that + /// the request waiting for it is answered the moment it is in + /// (`docs/features/perf5r-first-answer/README.md`). + fn interleaves(&mut self, scan: &Scan, verbose: bool) -> bool { + let interleave = scan.total() > INTERLEAVE_ABOVE || scan.discovery_pending(); + if verbose { + // Whether it interleaves is said here because it is decided here, + // and because it is the answer to "why did my hover wait?" — a + // scan that does not interleave answers nothing until it is done. + let total = scan.total(); + let interleaving = if interleave { ", interleaved" } else { "" }; + let staged = if scan.discovery_pending() { " (the folder first)" } else { "" }; + self.timing(format!( + "scan started: {total} file{}{staged}{interleaving}", + plural(total) + )); + } + interleave + } + /// The three `timing: scan …` lines the startup breakdown is read from — /// stages, counts and the sizes the scan left resident. /// diff --git a/crates/lucisv_server/src/server/tests/mod.rs b/crates/lucisv_server/src/server/tests/mod.rs index a718c1d..7f367c3 100644 --- a/crates/lucisv_server/src/server/tests/mod.rs +++ b/crates/lucisv_server/src/server/tests/mod.rs @@ -72,6 +72,7 @@ mod progress; mod pull_diagnostics; mod qa_generate_label; mod qa_rename_implicit; +mod qa_walking; mod references_scope; mod references_top_rooted; mod rename_generate_label; @@ -85,6 +86,7 @@ mod settings; mod startup; mod sync; mod tokens; +mod walking; mod watchers; /// A scratch workspace root, removed on drop. diff --git a/crates/lucisv_server/src/server/tests/qa_walking.rs b/crates/lucisv_server/src/server/tests/qa_walking.rs new file mode 100644 index 0000000..ea19359 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/qa_walking.rs @@ -0,0 +1,161 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! QA (server-scaling-r10, 2026-11-26): what arrives between two slices of a +//! rescan's walk that `walking.rs` does not script — a workspace folder +//! removed, two rescan requests in two different slices, a request that +//! must wait for the scan, and a shutdown. + +use super::super::probe; +use super::scan_ordering::{ask, created, note, ordering_tree, settle, A_TEXT}; +use super::*; + +/// How many progress bars a drained run of messages put up — one per scan. +fn bars(messages: &[Message]) -> usize { + messages.iter().cloned().filter_map(progress_step).filter(|(step, _)| *step == "begin").count() +} + +/// A workspace-scoped session over `roots` with `a/a.sv` of the first open +/// and one-entry walk slices. +fn sliced(roots: Vec) -> Session { + let mut session = Session::wide_with(roots.clone(), watching_progress()); + session.open(&roots[0].join("a/a.sv"), A_TEXT); + session.server.workspace.set_walk_slice(1); + let _ = (probe::take_counts(), probe::take_ahead(), session.drain()); + session +} + +/// The index's files, sorted. +fn files(session: &Session) -> Vec { + let mut files: Vec = + session.server.workspace.index().files().iter().map(|p| p.to_path_buf()).collect(); + files.sort(); + files +} + +fn folders_removed(removed: &Path) -> Message { + note( + DidChangeWorkspaceFolders::METHOD, + serde_json::json!({ "event": { "added": [], "removed": [{ + "uri": path_to_uri(removed).expect("uri"), "name": "second", + }] } }), + ) +} + +#[test] +fn qa_a_folder_removed_between_two_slices_converges_to_a_fresh_server_without_it() { + let first = ordering_tree("qawalkfolder1"); + let second = Tree::new("qawalkfolder2"); + for n in 0..30 { + second.package(&format!("s/q{n:02}.sv"), &format!("q{n:02}")); + } + for at in [1, 15, 40] { + let _ = std::fs::remove_file(first.path.join("z/new.sv")); + let mut session = sliced(vec![first.path.clone(), second.path.clone()]); + first.package("z/new.sv", "new"); + let mut script: Vec> = vec![Vec::new(); at - 1]; + script.push(vec![folders_removed(&second.path)]); + probe::script(script); + assert!(!session.batch(vec![created(&first.path.join("z/new.sv"))]), "no shutdown"); + assert!(probe::unarrived().is_empty(), "at {at}: arrived mid-scan"); + settle(&mut session); + session.server.flush_dirty(); + let _ = (probe::take_counts(), probe::take_ahead(), session.drain()); + let got = files(&session); + assert!(!got.iter().any(|p| p.starts_with(&second.path)), "at {at}: stale files kept"); + let mut fresh = Session::wide_with(vec![first.path.clone()], watching_progress()); + fresh.open(&first.path.join("a/a.sv"), A_TEXT); + fresh.server.reindex(); + settle(&mut fresh); + fresh.server.flush_dirty(); + let _ = (probe::take_counts(), probe::take_ahead(), fresh.drain()); + assert_eq!(got, files(&fresh), "at {at}"); + assert_eq!( + session.server.workspace.index().fingerprint(), + fresh.server.workspace.index().fingerprint(), + "at {at}" + ); + } +} + +#[test] +fn qa_two_rescan_requests_in_two_slices_owe_exactly_one_more_scan() { + let tree = ordering_tree("qawalktwice"); + let mut session = sliced(vec![tree.path.clone()]); + tree.package("z/new.sv", "new"); + tree.package("z/one.sv", "one"); + tree.package("z/two.sv", "two"); + let mut script: Vec> = vec![Vec::new(); 3]; + script.push(vec![created(&tree.path.join("z/one.sv"))]); + script.extend(vec![Vec::new(); 5]); + script.push(vec![created(&tree.path.join("z/two.sv"))]); + probe::script(script); + assert!(!session.batch(vec![created(&tree.path.join("z/new.sv"))]), "no shutdown"); + assert!(probe::unarrived().is_empty(), "both arrived mid-walk"); + settle(&mut session); + let drained = session.drain(); + assert_eq!(bars(&drained), 2, "the rescan and exactly one more"); + let got = files(&session); + for name in ["z/one.sv", "z/two.sv", "z/new.sv"] { + assert!(got.contains(&tree.path.join(name)), "{name} indexed"); + } + let _ = (probe::take_counts(), probe::take_ahead()); +} + +#[test] +fn qa_a_request_that_waits_for_the_scan_is_answered_exactly_once_after_it() { + let tree = ordering_tree("qawalkheld"); + let mut session = sliced(vec![tree.path.clone()]); + tree.package("z/new.sv", "new"); + let a = path_to_uri(&tree.path.join("a/a.sv")).expect("uri"); + let lens = + ask(41, CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": a } })); + probe::script([vec![], vec![lens]]); + assert!(!session.batch(vec![created(&tree.path.join("z/new.sv"))]), "no shutdown"); + assert!(probe::unarrived().is_empty()); + settle(&mut session); + let answered = session + .drain() + .into_iter() + .filter(|m| matches!(m, Message::Response(r) if r.id == RequestId::from(41))) + .count(); + assert_eq!(answered, 1, "held and answered once"); + let _ = (probe::take_counts(), probe::take_ahead()); +} + +#[test] +fn qa_a_shutdown_between_two_slices_is_held_once_and_not_answered_mid_walk() { + let tree = ordering_tree("qawalkshutdown"); + let mut session = sliced(vec![tree.path.clone()]); + tree.package("z/new.sv", "new"); + let shutdown = Message::Request(Request::new( + RequestId::from(77), + Shutdown::METHOD.to_string(), + Value::Null, + )); + probe::script([vec![], vec![shutdown]]); + // A rescan holds every request, `shutdown` included, until it ends — + // between files on trunk too — and the held batch then honours it once. + assert!(!session.batch(vec![created(&tree.path.join("z/new.sv"))]), "held, not honoured"); + assert!(probe::unarrived().is_empty(), "arrived mid-walk"); + let held = std::mem::take(&mut session.server.held); + assert!(held.iter().any(|m| matches!(m, Message::Request(r) if r.id == RequestId::from(77)))); + // Honouring it needs the `exit` handshake on the connection + // (`cancel.rs` shows the dance); what matters here is that it was held + // once, with nothing answered for it mid-walk. + let early = session + .drain() + .into_iter() + .filter(|m| matches!(m, Message::Response(r) if r.id == RequestId::from(77))) + .count(); + assert_eq!(early, 0, "not answered mid-walk"); + assert_eq!( + held.iter() + .filter(|m| matches!(m, Message::Request(r) if r.id == RequestId::from(77))) + .count(), + 1, + "held exactly once" + ); + let _ = (probe::take_counts(), probe::take_ahead()); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/server/tests/scan_trace.rs b/crates/lucisv_server/src/server/tests/scan_trace.rs index aae604a..29a523c 100644 --- a/crates/lucisv_server/src/server/tests/scan_trace.rs +++ b/crates/lucisv_server/src/server/tests/scan_trace.rs @@ -292,7 +292,10 @@ fn a_startup_scan_with_no_files_opens_no_store_and_a_warm_rescan_rewrites_none() assert_eq!(field(&warmed, "buffers"), "1", "premise: the buffer indexes itself"); assert_eq!(field(&warmed, "repeats"), "1", "and its record was already in the store"); assert_eq!(field(&warmed, "records"), "0", "so nothing was appended"); - assert_eq!(field(&warmed, "opens"), "1", "the store was read once, not twice"); + // The widen the `didOpen` ran read the store; this whole rescan keeps + // that read (`IndexCache::reopen`), so the session read it once, not + // twice, and this scan's own count is nothing. + assert_eq!(field(&warmed, "opens"), "0", "the store was read once, not twice"); assert_eq!(field(&warmed, "compactions"), "0", "and the rewrite would have been identical"); drop(warm); diff --git a/crates/lucisv_server/src/server/tests/walking.rs b/crates/lucisv_server/src/server/tests/walking.rs new file mode 100644 index 0000000..9cd8f4e --- /dev/null +++ b/crates/lucisv_server/src/server/tests/walking.rs @@ -0,0 +1,272 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! A rescan answers between the slices of its discovery walk, and whatever +//! arrives between two slices leaves the server where a fresh server over +//! the same final state starts (topo §2.9-58, `state/walking.rs`). + +use super::super::probe; +use super::scan_ordering::{ask, closed, created, note, opened, ordering_tree, settle, A_TEXT}; +use super::*; + +/// A watcher event saying `path` was deleted. +fn deleted(path: &Path) -> Message { + note( + DidChangeWatchedFiles::METHOD, + serde_json::json!({ "changes": [{ "uri": path_to_uri(path).expect("uri"), "type": 3 }] }), + ) +} + +/// The settings push that adds an exclude, keeping the workspace scope. +fn excluding_b() -> Message { + note( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { + "exclude": ["b"], "index": { "scope": "workspace" } + } } }), + ) +} + +/// How many progress bars a drained run of messages put up — one per scan. +fn bars(messages: Vec) -> usize { + messages.into_iter().filter_map(progress_step).filter(|(step, _)| *step == "begin").count() +} + +/// A workspace-scoped session with `a/a.sv` open and a walk slice of one +/// entry, so every rescan's walk is many slices. +fn sliced_session(tree: &Tree) -> (Session, Uri) { + let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress()); + let a = session.open(&tree.path.join("a/a.sv"), A_TEXT); + session.server.workspace.set_walk_slice(1); + tree.package("z/new.sv", "new"); + let _ = (probe::take_counts(), probe::take_ahead(), session.drain()); + (session, a) +} + +#[test] +fn a_buffer_local_request_is_answered_between_two_slices_of_a_rescans_walk() { + // The point of the round: a rescan used to answer nothing until its + // whole walk was done. Now the walk drains between slices, and a request + // its buffer can answer is answered there. + let tree = ordering_tree("walkanswers"); + let (mut session, a) = sliced_session(&tree); + let symbols = + ask(7, DocumentSymbolRequest::METHOD, serde_json::json!({ "textDocument": { "uri": a } })); + probe::script([vec![symbols]]); + assert!(!session.batch(vec![created(&tree.path.join("z/new.sv"))]), "no shutdown"); + assert!(probe::unarrived().is_empty(), "the request arrived mid-scan"); + let counts = probe::take_counts(); + let files = session.server.workspace.index().files().len(); + // Every interleave point past one per file is a drain between slices, + // and the first point — where the request arrived — is one of them. + assert!(counts.points > files + 10, "{} points for {files} files", counts.points); + assert_eq!(probe::take_ahead(), vec![RequestId::from(7)], "answered where it arrived"); + settle(&mut session); +} + +/// What the server holds once settled: the index, the include graph, the +/// completion words and every open buffer's text. +fn settled_state(session: &Session) -> String { + let ws = &session.server.workspace; + let mut out = ws.index().fingerprint(); + out.push_str(&ws.includes().fingerprint()); + out.push_str(&format!("{:?}\n", ws.candidates().words(""))); + let mut open: Vec = ws + .open_uris() + .into_iter() + .map(|uri| format!("{} {:?}", uri.as_str(), ws.document(&uri).map(|d| &d.text))) + .collect(); + open.sort(); + out.push_str(&open.join("\n")); + out +} + +/// One thing a client can send between two slices, and how to bring a fresh +/// server to the state it leaves: the same thing sent first, then the same +/// whole rescan. +struct Midway { + name: &'static str, + burst: fn(&Tree, &Uri) -> Vec, + /// Applied to the fresh server after it has opened `a/a.sv`. + fresh: fn(&mut Session, &Tree, &Uri), + /// Whether it must ask for one more scan wherever it arrives. + rescans: bool, +} + +fn midways() -> Vec { + vec![ + Midway { + name: "open", + burst: |tree, _| { + vec![opened( + &path_to_uri(&tree.path.join("b/b.sv")).expect("uri"), + "module bopen;\nendmodule\n", + )] + }, + fresh: |s, tree, _| { + s.open(&tree.path.join("b/b.sv"), "module bopen;\nendmodule\n"); + }, + rescans: false, + }, + Midway { + name: "edit", + burst: |_, a| vec![changed(a, 2, "module amod;\n logic t;\nendmodule\n")], + fresh: |s, _, a| { + s.batch(vec![changed(a, 2, "module amod;\n logic t;\nendmodule\n")]); + s.server.flush_dirty(); + }, + rescans: false, + }, + Midway { + name: "close", + burst: |_, a| vec![closed(a)], + fresh: |s, _, a| { + s.batch(vec![closed(a)]); + }, + rescans: false, + }, + Midway { + name: "settings", + burst: |_, _| vec![excluding_b()], + fresh: |s, _, _| { + s.batch(vec![excluding_b()]); + }, + rescans: true, + }, + Midway { + name: "watched create", + burst: |tree, _| { + tree.package("z/made_mid.sv", "made_mid"); + vec![created(&tree.path.join("z/made_mid.sv"))] + }, + fresh: |_, _, _| {}, + rescans: true, + }, + Midway { + name: "watched delete", + burst: |tree, _| { + let gone = tree.path.join("z/p003.sv"); + let _ = std::fs::remove_file(&gone); + vec![deleted(&gone)] + }, + fresh: |_, _, _| {}, + rescans: true, + }, + ] +} + +/// How many drains a rescan of `tree` takes between walk slices: every +/// interleave point past one per indexed file. +fn walk_drains(tree: &Tree) -> usize { + let (mut session, _) = sliced_session(tree); + assert!(!session.batch(vec![created(&tree.path.join("z/new.sv"))]), "no shutdown"); + let points = probe::take_counts().points; + points - session.server.workspace.index().files().len() +} + +/// Send `midway`'s burst at interleave point `at` of a rescan of a fresh +/// copy of the ordering tree, settle, and say what the server holds and how +/// many scans it ran. Points up to [`walk_drains`] are between walk slices, +/// later ones between files — the drains trunk already had. +fn delivered_at(midway: &Midway, at: usize, drains: usize, test: &str) -> (String, usize) { + let tree = ordering_tree(&format!("{test}{}{at}", midway.name.replace(' ', ""))); + let (mut session, a) = sliced_session(&tree); + // Points before `at` get nothing. The burst is built when the script is, + // so a disk change is made before the rescan starts and its event + // arrives between two slices. + let mut script: Vec> = vec![Vec::new(); at - 1]; + script.push((midway.burst)(&tree, &a)); + probe::script(script); + assert!(!session.batch(vec![created(&tree.path.join("z/new.sv"))]), "no shutdown"); + assert!(probe::unarrived().is_empty(), "{} at {at}: arrived mid-scan", midway.name); + settle(&mut session); + session.server.flush_dirty(); + let scans = bars(session.drain()); + let points = probe::take_counts().points; + let files = session.server.workspace.index().files().len(); + // The first scan's walk has `drains` drains, so a later point is a + // drain between files by construction. + if at <= drains { + assert!(points >= files + at, "{} at {at}: the burst landed in the walk", midway.name); + } + let _ = probe::take_ahead(); + (settled_state(&session), scans) +} + +/// A fresh server brought to `midway`'s final state: the same buffer open, +/// the same thing sent, then the whole rescan the sliced session ran. +fn fresh_state(midway: &Midway) -> String { + let tree = ordering_tree(&format!("walkfresh{}", midway.name.replace(' ', ""))); + tree.package("z/new.sv", "new"); + let _ = (midway.burst)(&tree, &path_to_uri(&tree.path.join("a/a.sv")).expect("uri")); + let mut fresh = Session::wide_with(vec![tree.path.clone()], watching_progress()); + let a = fresh.open(&tree.path.join("a/a.sv"), A_TEXT); + (midway.fresh)(&mut fresh, &tree, &a); + fresh.server.flush_dirty(); + fresh.server.reindex(); + settle(&mut fresh); + fresh.server.flush_dirty(); + let _ = (probe::take_counts(), probe::take_ahead()); + settled_state(&fresh).replace("walkfresh", "walkvsfresh") +} + +/// The first lines where two settled states part, for a failure message. +fn parting(got: &str, want: &str) -> Vec<(String, String)> { + got.lines() + .zip(want.lines()) + .filter(|(g, w)| g != w) + .take(3) + .map(|(g, w)| (g.chars().take(160).collect(), w.chars().take(160).collect())) + .collect() +} + +#[test] +fn anything_sent_between_two_slices_settles_where_the_same_message_between_files_does() { + // The reference is trunk's own interleaving: the same burst at a drain + // between two *files*, which this round did not touch. A message between + // two walk slices must leave exactly what that leaves — the first drain, + // one in the middle and the last one. + let drains = walk_drains(&ordering_tree("walkdrains")); + assert!(drains > 20, "premise: the walk is many slices ({drains})"); + for midway in midways() { + let (reference, reference_scans) = delivered_at(&midway, drains + 3, drains, "walkmid"); + if midway.rescans { + assert_eq!(reference_scans, 2, "{}: one more scan between files", midway.name); + } + let reference = reference.replace(&format!("{}", drains + 3), "AT"); + for at in [1, drains / 2, drains] { + let (got, scans) = delivered_at(&midway, at, drains, "walkmid"); + let got = got.replace(&format!("walkmid{}{at}/", midway.name.replace(' ', "")), ""); + let want = + reference.replace(&format!("walkmid{}AT/", midway.name.replace(' ', "")), ""); + // A close between files can owe a rescan (the scan had absorbed + // the buffer); between slices nothing is absorbed yet, so it never + // owes more scans than that — and what must rescan still does. + match midway.rescans { + true => assert_eq!(scans, 2, "{} at {at}: one more scan", midway.name), + false => { + assert!(scans <= reference_scans, "{} at {at}: {scans} scans", midway.name) + } + } + assert!(got == want, "{} at {at}: {:#?}", midway.name, parting(&got, &want)); + } + } +} + +#[test] +fn a_message_between_two_slices_settles_where_a_fresh_server_starts() { + // And against a fresh server: everything but an edit, whose completion + // words keep the text the rescan took with the buffer — between files + // too, on trunk (`docs/features/server-scaling-r10`, finding F1). + let drains = walk_drains(&ordering_tree("walkdrainsfresh")); + for midway in midways().into_iter().filter(|m| m.name != "edit") { + let tag = midway.name.replace(' ', ""); + let want = fresh_state(&midway).replace(&format!("walkvsfresh{tag}/"), ""); + for at in [1, drains] { + let (got, _) = delivered_at(&midway, at, drains, "walkvsfresh"); + let got = got.replace(&format!("walkvsfresh{tag}{at}/"), ""); + assert!(got == want, "{} at {at}: {:#?}", midway.name, parting(&got, &want)); + } + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/state/discover.rs b/crates/lucisv_server/src/state/discover.rs index dce25c3..8d2b4ce 100644 --- a/crates/lucisv_server/src/state/discover.rs +++ b/crates/lucisv_server/src/state/discover.rs @@ -49,6 +49,7 @@ use lucisv_core::walk::{ use crate::scan_trace::ScanTrace; use super::scan::{Analyzed, HeldAnalyses, IndexEvent, PendingDiscovery, Sources}; +use super::walking::Begun; use super::Workspace; /// One in-scope file, and the length whoever found it already knew. @@ -60,12 +61,17 @@ use super::Workspace; pub(super) struct Found { pub(super) path: PathBuf, pub(super) len: Option, + /// The file's identity when it was already read — a sliced walk reads + /// every walked file's in one pass when the walk ends + /// (`state/walking.rs`) — else `None`, and [`dedup_by_identity`] stats + /// the path for it. + pub(super) id: Option, } impl Found { /// A path nothing has stat'd. fn unmeasured(path: PathBuf) -> Found { - Found { path, len: None } + Found { path, len: None, id: None } } /// One path on its own, for a caller asking the cap about a single file @@ -118,7 +124,7 @@ pub(super) fn dedup_by_identity(files: Vec) -> (Vec, HashMap = HashMap::new(); let mut has_id: Vec = Vec::with_capacity(files.len()); for (i, found) in files.iter().enumerate() { - if let Some(id) = dir_id(&found.path) { + if let Some(id) = found.id.as_ref().cloned().or_else(|| dir_id(&found.path)) { has_id.push(true); if let Some(prev) = best.get_mut(&id) { if found.path < files[*prev].path { @@ -173,7 +179,7 @@ impl Workspace { trace: &mut ScanTrace, ) -> Sources { let scope = self.source_files(trace); - self.overlay_buffers(scope, watch, analyses, trace) + self.overlay_buffers(scope, self.client.max_file_size, watch, analyses, trace) } /// [`Workspace::collect_sources`] over one already-resolved scope — the @@ -181,15 +187,16 @@ impl Workspace { /// /// Split out because the two-phase startup resolves the scope twice (the /// user's own folders, then the rest of the workspace) and both halves owe - /// the buffers the same precedence. + /// the buffers the same precedence — and a sliced walk lands with the cap + /// it began under (`state/walking.rs`). pub(super) fn overlay_buffers( &self, scope: Scope, + cap: u64, watch: &mut dyn FnMut(IndexEvent), analyses: HeldAnalyses, trace: &mut ScanTrace, ) -> Sources { - let cap = self.client.max_file_size; let capping = trace.now(); let mut stats = 0usize; let (deduped, scope_by_id) = dedup_by_identity(scope.files); @@ -415,7 +422,7 @@ impl Workspace { &exclude, true, tracker, - &mut |path, len| out.push(Found { path, len }), + &mut |path, len| out.push(Found { path, len, id: None }), &mut |w| warn(w.to_string()), ); ScanTrace::add(&mut trace.walk_ms, walking); @@ -516,7 +523,7 @@ impl Workspace { &self, watch: &mut dyn FnMut(IndexEvent), trace: &mut ScanTrace, - ) -> (Sources, Option) { + ) -> Begun { // **The session's first scan only.** Every later whole rescan is one a // message asked for, and `must_wait`'s `answering_a_rescan` holds every // request for the whole of it — so leading with a folder buys no answer @@ -525,7 +532,7 @@ impl Workspace { // and it is the one this order is for // (`docs/features/perf5r-first-answer/README.md`). if trace.number > 1 || !self.splits_discovery() { - return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None); + return self.whole_scope(watch, trace); } // 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 @@ -536,7 +543,7 @@ impl Workspace { 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); + return self.whole_scope(watch, trace); } } } @@ -549,7 +556,7 @@ impl Workspace { // 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); + return self.whole_scope(watch, trace); } // Every path the neighbourhood walk named, before the cap has had a // say, plus any open non-large buffers: what the remaining walk must @@ -557,7 +564,8 @@ impl Workspace { let mut seen: HashSet = head.iter().map(|found| found.path.clone()).collect(); seen.extend(self.docs.values().filter(|doc| !doc.large).filter_map(|doc| doc.path.clone())); let scope = Scope { files: head, incdirs: Vec::new(), warnings }; - let sources = self.overlay_buffers(scope, watch, HeldAnalyses::Wanted, trace); + let cap = self.client.max_file_size; + let sources = self.overlay_buffers(scope, cap, watch, HeldAnalyses::Wanted, trace); seen.extend(sources.files.iter().cloned()); let mut seen_ids: HashMap = HashMap::new(); for path in &seen { @@ -572,16 +580,27 @@ impl Workspace { .or_insert_with(|| path.clone()); } } - ( - sources, - Some(PendingDiscovery { - roots: self.roots.clone(), - seen, - seen_ids, - tracker, - file_conflict: false, - }), - ) + let pending = PendingDiscovery { + roots: self.roots.clone(), + seen, + seen_ids, + tracker, + file_conflict: false, + walking: None, + }; + Begun::Resolved(Box::new((sources, Some(pending)))) + } + + /// The whole scope in one discovery: begun as a sliced walk when it is + /// one ([`Workspace::whole_scope_walk`]), else resolved here and now. + fn whole_scope(&self, watch: &mut dyn FnMut(IndexEvent), trace: &mut ScanTrace) -> Begun { + match self.whole_scope_walk(trace) { + Some(walking) => Begun::Walking(Box::new(walking)), + None => { + let sources = self.collect_sources(watch, HeldAnalyses::Wanted, trace); + Begun::Resolved(Box::new((sources, None))) + } + } } /// Whether some directory between `root` and `dir` holds a **second @@ -640,7 +659,7 @@ impl Workspace { &exclude, true, tracker, - &mut |path, len| out.push(Found { path, len }), + &mut |path, len| out.push(Found { path, len, id: None }), &mut |w| warn(w.to_string()), ); ScanTrace::add(&mut trace.walk_ms, walking); @@ -678,21 +697,18 @@ impl Workspace { /// 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. + /// + /// `walked` is that walk's output ([`Workspace::walk_the_rest`]), taken a + /// slice at a time so the published neighbourhood answers meanwhile. pub(super) fn rest_of_scope( &self, pending: &mut PendingDiscovery, + walked: Vec, canonical_ids: &mut HashMap, 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_tracked( - roots, - &mut pending.tracker, - &mut |w| warnings.push(w), - trace, - ); + ) -> (Vec, usize) { + let seen = &pending.seen; let mut open_ids: HashMap = HashMap::new(); for doc in self.docs.values().filter(|doc| !doc.large) { let Some(path) = doc.path.as_ref() else { continue }; @@ -713,7 +729,7 @@ impl Workspace { let mut skipped = 0usize; let mut files: Vec = Vec::new(); for found in walked { - if let Some(id) = dir_id(&found.path) { + if let Some(id) = found.id.as_ref().cloned().or_else(|| dir_id(&found.path)) { let dup = if !pending.seen_ids.is_empty() || !open_ids.is_empty() { pending.seen_ids.get(&id).or_else(|| open_ids.get(&id)) } else { @@ -750,7 +766,7 @@ impl Workspace { } ScanTrace::add(&mut trace.cap_ms, capping); trace.stats += stats; - (files, warnings, skipped) + (files, skipped) } } @@ -833,7 +849,7 @@ fn sibling_files(dirs: &[PathBuf], trace: &mut ScanTrace) -> Vec { // exactly as `is_file()` did. let Ok(meta) = fs::metadata(&path) else { continue }; if meta.is_file() { - out.push(Found { path, len: Some(meta.len()) }); + out.push(Found { path, len: Some(meta.len()), id: None }); } } } diff --git a/crates/lucisv_server/src/state/mod.rs b/crates/lucisv_server/src/state/mod.rs index 26d192f..505501f 100644 --- a/crates/lucisv_server/src/state/mod.rs +++ b/crates/lucisv_server/src/state/mod.rs @@ -40,6 +40,7 @@ mod scan; mod scope; mod sources; mod views; +mod walking; mod watched; #[cfg(test)] @@ -139,6 +140,9 @@ pub struct Workspace { /// was absorbed into the currently running scan, cleared at `begin_scan` /// and `finish_scan`. scan_absorbed: ScanAbsorbed, + /// Entries per discovery-walk slice when a test set it; `None` is + /// `walking::WALK_SLICE`. + walk_slice: Option, } /// Open-buffer paths and physical file identities absorbed into an active scan. diff --git a/crates/lucisv_server/src/state/rescan.rs b/crates/lucisv_server/src/state/rescan.rs index a606b87..004f192 100644 --- a/crates/lucisv_server/src/state/rescan.rs +++ b/crates/lucisv_server/src/state/rescan.rs @@ -13,11 +13,11 @@ use vlog_semantic::FileFacts; use super::discover::{dedup_by_identity, oversize}; use super::reconcile::WidenOverlay; -use super::scan::{self, IndexEvent, Scan, ScanKind}; +use super::scan::{self, IndexEvent, PendingDiscovery, Scan, ScanKind, Sources}; +use super::walking::Begun; use super::{StoreOpen, Workspace}; use crate::candidates::Candidates; use crate::includes::{self, IncludeGraph}; -use crate::index_cache::IndexCache; use crate::scan_order::{self, WorkList}; use crate::scan_trace::{CacheWork, ScanTrace}; #[cfg(test)] @@ -37,6 +37,7 @@ impl Workspace { /// is never stepped changes nothing but the view cache and the open cache /// handle. pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent), trace: bool) -> Scan { + let holding = std::time::Instant::now(); self.scan_absorbed.clear(); let mut trace = ScanTrace::opened(&mut self.scans, trace, "whole"); // A rescan says nothing about *which* file moved, so nothing held from @@ -47,17 +48,42 @@ impl Workspace { // The cap's skips are reported by `collect_sources` and counted here, // because the end message names them and the scan is what owns that // number now. - let mut counting = |event: IndexEvent<'_>, skipped: &mut usize| { - if matches!(event, IndexEvent::Skipped { .. }) { - *skipped += 1; - } - watch(event); - }; - let (mut scope, pending) = { - let mut count = |event: IndexEvent<'_>| counting(event, &mut skipped); + let begun = { + let mut count = |event: IndexEvent<'_>| { + skipped += usize::from(matches!(event, IndexEvent::Skipped { .. })); + watch(event); + }; self.first_scope(&mut count, &mut trace) }; ScanTrace::add(&mut trace.discovery_ms, discovering); + match begun { + Begun::Resolved(resolved) => { + let (scope, pending) = *resolved; + let mut scan = self.land_scope(trace, scope, pending, skipped); + scan.trace.saw_slice(holding); + scan + } + // The walk's first slice is taken here, so a walk that fits in one + // lands before this returns and the scan is what it always was. + Begun::Walking(walking) => { + let mut scan = Scan::begun_walking(trace, *walking); + self.walk_a_slice(&mut scan, watch, holding); + scan + } + } + } + + /// The scan a resolved scope begins: its work list with the user's own + /// neighbourhood at the front, the open buffers it took, and the store + /// it will read deferred to its first file. What `begin_scan` did after + /// the walk before the walk could be sliced, unchanged. + pub(super) fn land_scope( + &mut self, + mut trace: ScanTrace, + mut scope: Sources, + pending: Option, + skipped: usize, + ) -> Scan { let buffered = std::mem::take(&mut scope.buffered); let analyzed = std::mem::take(&mut scope.analyzed); let canonical_ids = std::mem::take(&mut scope.canonical_ids); @@ -110,6 +136,7 @@ impl Workspace { warnings: scope.warnings, at: 0, pending, + walking: None, staged: Vec::new(), staged_at: Vec::new(), words: HashMap::new(), @@ -265,6 +292,7 @@ impl Workspace { // A widen names the directories it is about to walk, so there is // never anything left to discover. pending: None, + walking: None, staged: Vec::new(), staged_at: Vec::new(), words: HashMap::new(), @@ -283,11 +311,29 @@ impl Workspace { /// the same call, and a bar whose percentage falls is worse than one that /// 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 { + /// + /// **A slice at a time** (`state/walking.rs`): each call walks `budget` + /// entries of the rest and reports "there is more" until the walk ends, + /// so the published neighbourhood answers between slices; the call that + /// ends it lands the files exactly as one call over the whole walk did. + fn discover_the_rest( + &mut self, + scan: &mut Scan, + watch: &mut dyn FnMut(IndexEvent), + budget: usize, + ) -> bool { let Some(mut pending) = scan.take_pending() else { return false }; + let slicing = std::time::Instant::now(); let discovering = scan.trace.now(); + let Some((walked, warnings)) = self.walk_the_rest(&mut pending, budget, &mut scan.trace) + else { + scan.pending = Some(pending); + ScanTrace::add(&mut scan.trace.discovery_ms, discovering); + scan.trace.saw_slice(slicing); + return true; + }; let mut skipped = 0usize; - let (files, warnings, walked_skips) = { + let (files, walked_skips) = { let mut counting = |event: IndexEvent<'_>| { if matches!(event, IndexEvent::Skipped { .. }) { skipped += 1; @@ -296,6 +342,7 @@ impl Workspace { }; self.rest_of_scope( &mut pending, + walked, &mut scan.canonical_ids, &mut counting, &mut scan.trace, @@ -315,6 +362,7 @@ impl Workspace { scan.skipped, scan.trace.cache, ); + scan.trace.saw_slice(slicing); true } @@ -330,7 +378,10 @@ impl Workspace { return; }; let opening = trace.now(); - self.cache = IndexCache::open(dir); + // Kept when the file is still the one this cache last matched — what + // the last whole rescan compacted it to — and read again otherwise + // ([`IndexCache::reopen`]). + self.cache = std::mem::take(&mut self.cache).reopen(dir); ScanTrace::add(&mut trace.cache_open_ms, opening); // The counters this scan is charged for start where the store it has // just opened does. A scan that never opens one keeps the baseline @@ -359,9 +410,16 @@ impl Workspace { /// contributes nothing, which is what a file `collect_sources` could not /// read used to do before the work list existed. pub fn scan_step(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool { + // Still walking: this step is the walk's next slice, indexing nothing + // (`state/walking.rs`). + if scan.walking() { + self.walk_a_slice(scan, watch, std::time::Instant::now()); + return true; + } let (done, total) = (scan.at, scan.work.len()); if done == total { - return self.discover_the_rest(scan, watch); + let budget = self.walk_budget(); + return self.discover_the_rest(scan, watch, budget); } scan.at += 1; // The first file of a scan is the first thing to ask the store @@ -380,40 +438,7 @@ impl Workspace { let text = source.as_str(); let held = scan.analyzed.facts.remove(&path); let known_words = scan.analyzed.words.remove(&path); - let facts = match held { - // An open buffer's own finished analysis comes first. It is the - // only source of facts that is right when the buffer has unsaved - // edits, which is precisely when the content-keyed cache below has - // nothing to offer. The record is written through all the same, so - // the next session starts from it. - Some(facts) => { - watch(IndexEvent::Analyzed { done, total, path: &path }); - scan.trace.buffers += 1; - self.cache.record(&facts, text); - facts - } - // The cache answers for the exact bytes about to be indexed, so a - // hit is the parse and not a guess at it. A miss — a new file, a - // changed one, a record this version cannot read — parses, and - // the result is written through immediately, which is what makes - // an interrupted scan resumable. - None => match self.cache.facts_for(&path, text) { - Some(facts) => { - scan.cached += 1; - watch(IndexEvent::Cached { done, total, path: &path }); - facts - } - None => { - watch(IndexEvent::Parsing { done, total, path: &path }); - let parsing = scan.trace.now(); - let facts = FileFacts::of(path.clone(), text); - ScanTrace::add(&mut scan.trace.parse_ms, parsing); - scan.trace.parse_bytes += text.len(); - self.cache.record(&facts, text); - facts - } - }, - }; + let facts = self.facts_of_step(scan, &path, text, held, (done, total), watch); // Read off the record rather than lexed here: since `FACTS_FORMAT` 13 // a file's identifier census *is* one of its facts, so a cached hit // brings its words with it and a parse harvested them from the tokens @@ -434,6 +459,54 @@ impl Workspace { true } + /// One step's record for `path`: the open buffer's own analysis when it + /// held one, else the persistent store's for these exact bytes, else a + /// parse — reported to `watch` as whichever it was. + fn facts_of_step( + &mut self, + scan: &mut Scan, + path: &Path, + text: &str, + held: Option, + (done, total): (usize, usize), + watch: &mut dyn FnMut(IndexEvent), + ) -> FileFacts { + match held { + // An open buffer's own finished analysis comes first. It is the + // only source of facts that is right when the buffer has unsaved + // edits, which is precisely when the content-keyed cache below has + // nothing to offer. The record is written through all the same, so + // the next session starts from it. + Some(facts) => { + watch(IndexEvent::Analyzed { done, total, path }); + scan.trace.buffers += 1; + self.cache.record(&facts, text); + facts + } + // The cache answers for the exact bytes about to be indexed, so a + // hit is the parse and not a guess at it. A miss — a new file, a + // changed one, a record this version cannot read — parses, and + // the result is written through immediately, which is what makes + // an interrupted scan resumable. + None => match self.cache.facts_for(path, text) { + Some(facts) => { + scan.cached += 1; + watch(IndexEvent::Cached { done, total, path }); + facts + } + None => { + watch(IndexEvent::Parsing { done, total, path }); + let parsing = scan.trace.now(); + let facts = FileFacts::of(path.to_path_buf(), text); + ScanTrace::add(&mut scan.trace.parse_ms, parsing); + scan.trace.parse_bytes += text.len(); + self.cache.record(&facts, text); + facts + } + }, + } + } + /// The work list in the order a scan walks it: the open buffers' own /// files, then the rest of the folders those buffers raise to, then /// everything else in path order ([`crate::scan_order`]). @@ -463,8 +536,15 @@ impl Workspace { /// walk this order postpones is exactly what makes the new folder /// nameable, so it happens here /// (`docs/features/perf5r-first-answer/README.md`). + /// + /// A scan still walking its scope has no work list to re-order: the + /// buffer this `didOpen` installed is overlaid, and the list ordered + /// round it, when the walk lands. pub fn open_next(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) { - self.discover_the_rest(scan, watch); + if scan.walking() { + return; + } + self.discover_the_rest(scan, watch, usize::MAX); self.reconcile_open_buffers_into(scan); let ordered = self.open_first(scan.remaining()); scan.reorder(ordered); diff --git a/crates/lucisv_server/src/state/scan.rs b/crates/lucisv_server/src/state/scan.rs index 355e2a4..64dfeb1 100644 --- a/crates/lucisv_server/src/state/scan.rs +++ b/crates/lucisv_server/src/state/scan.rs @@ -139,6 +139,9 @@ pub struct Scan { /// scope before it started, which is every scan but a workspace-scoped /// startup with a buffer already open. pub(super) pending: Option, + /// The whole scope's walk while it is still under way — see + /// [`super::walking`]. Every other field is empty until it lands. + pub(super) walking: Option, /// The records taken since the last publish, and which files of `work` /// they came from. Staged rather than merged because a merge is a pass /// over the whole index — see [`vlog_semantic::WorkspaceIndex::absorb`]. @@ -193,6 +196,8 @@ pub(super) struct PendingDiscovery { /// twice. Sharing the tracker restores that contract across the split. pub(super) file_conflict: bool, pub(super) tracker: lucisv_core::walk::DirectoryTracker, + /// The remaining walk while it is under way, holding the tracker. + pub(super) walking: Option, } /// How many records may be staged before another mid-scan publish is worth the @@ -222,6 +227,34 @@ pub(super) enum ScanKind { } impl Scan { + /// A whole scan whose scope is still being walked: nothing in it yet but + /// the walk and the trace ([`super::walking`]). + pub(super) fn begun_walking(trace: ScanTrace, walking: super::walking::Walking) -> Scan { + Scan { + kind: ScanKind::Whole, + work: Vec::new(), + head: 0, + buffered: HashMap::new(), + includes: HashMap::new(), + unread: Vec::new(), + paths: Vec::new(), + gone: Vec::new(), + analyzed: Analyzed::default(), + canonical_ids: HashMap::new(), + incdirs: Vec::new(), + warnings: Vec::new(), + at: 0, + pending: None, + walking: Some(walking), + staged: Vec::new(), + staged_at: Vec::new(), + words: HashMap::new(), + skipped: 0, + cached: 0, + trace, + } + } + /// How many files the size cap kept out of this scan. pub fn skipped(&self) -> usize { self.skipped @@ -255,7 +288,13 @@ impl Scan { /// buffer, or a folder covering the workspace) has `head` 0 and answers at /// the first one. pub fn neighbourhood_indexed(&self) -> bool { - self.at >= self.head + self.walking.is_none() && self.at >= self.head + } + + /// Whether this scan is still walking its scope: its work list is empty + /// and nothing it will index is known yet ([`super::walking`]). + pub fn walking(&self) -> bool { + self.walking.is_some() } /// Whether enough has been staged since the last publish for another one diff --git a/crates/lucisv_server/src/state/tests/interleave.rs b/crates/lucisv_server/src/state/tests/interleave.rs index c4ae096..9530027 100644 --- a/crates/lucisv_server/src/state/tests/interleave.rs +++ b/crates/lucisv_server/src/state/tests/interleave.rs @@ -34,6 +34,12 @@ fn the_publication_cadence_holds_a_publish_until_enough_has_been_staged() { ws.client.index_scope = IndexScope::Workspace; ws.adopt_roots(vec![tree.path.clone()]); let mut scan = ws.begin_scan(&mut |_| {}, false); + // 514 files are more than one walk slice, so the scope lands a step or + // two later (`state/walking.rs`); those steps stage nothing. + while scan.walking() { + assert!(ws.scan_step(&mut scan, &mut |_| {})); + assert!(!scan.publish_is_due(), "a walk slice stages nothing"); + } for taken in 1..scan::PUBLISH_EVERY { assert!(ws.scan_step(&mut scan, &mut |_| {}), "premise: file {taken} exists"); assert!(!scan.publish_is_due(), "{taken} staged is not yet a publish"); diff --git a/crates/lucisv_server/src/state/tests/mod.rs b/crates/lucisv_server/src/state/tests/mod.rs index dc033bb..8357280 100644 --- a/crates/lucisv_server/src/state/tests/mod.rs +++ b/crates/lucisv_server/src/state/tests/mod.rs @@ -28,10 +28,13 @@ mod large_file; mod lazy_read; mod open_buffers; mod persistence; +mod qa_walking; mod reindex_perf; mod settings; mod size_cap; mod views; +mod walking; +mod walking_replace; mod widen; fn uri(s: &str) -> Uri { diff --git a/crates/lucisv_server/src/state/tests/qa_walking.rs b/crates/lucisv_server/src/state/tests/qa_walking.rs new file mode 100644 index 0000000..88b5640 --- /dev/null +++ b/crates/lucisv_server/src/state/tests/qa_walking.rs @@ -0,0 +1,136 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! QA (server-scaling-r10, 2026-11-26): the identity a walked file carries is +//! the one its walk entry read, not one read after the walk. A file replaced +//! (new inode, same path — an atomic save, a `git checkout`) after the walk +//! visited it and before a symlink alias of it is visited leaves the two +//! with different identities, so the alias is no longer deduplicated. Trunk +//! read both identities together after the walk. +//! +//! **QA finding R10-QA1**: this test failed on the round-1 tree and passes +//! after the fix round (identities read in one pass in `Walking::finish`); +//! see the QA log of `docs/features/server-scaling-r10/README.md`. + +use super::*; + +#[cfg(unix)] +#[test] +fn qa_a_file_replaced_mid_walk_keeps_its_symlink_alias_deduplicated() { + let tree = Tree::new("qawalkreplace"); + tree.write("a.sv", "module amod;\nendmodule\n"); + std::os::unix::fs::symlink("a.sv", tree.path.join("b.sv")).expect("symlink"); + tree.write("c.sv", "module cmod;\nendmodule\n"); + let mut ws = Workspace::default(); + ws.set_client_settings(ClientSettings { + index_scope: IndexScope::Workspace, + index_scope_depth: 1, + ..Default::default() + }); + ws.adopt_roots(vec![tree.path.clone()]); + ws.set_walk_slice(1); + // Slice 1 (inside `begin_scan`) enters the root; slice 2 visits `a.sv`. + let mut scan = ws.begin_scan(&mut |_| {}, false); + assert!(scan.walking(), "premise: the walk is sliced"); + assert!(ws.scan_step(&mut scan, &mut |_| {})); + // Replaced: same path, same bytes, a new inode. + std::fs::remove_file(tree.path.join("a.sv")).expect("rm"); + tree.write("a.sv", "module amod;\nendmodule\n"); + while scan.walking() { + assert!(ws.scan_step(&mut scan, &mut |_| {})); + } + let work: Vec = scan + .work + .iter() + .map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()) + .collect(); + // What trunk's one-shot discovery lands on the tree as it now stands. + let mut fresh = Workspace::default(); + fresh.set_client_settings(ws.client.clone()); + fresh.adopt_roots(vec![tree.path.clone()]); + let oracle = fresh.begin_scan(&mut |_| {}, false); + let want: Vec = oracle + .work + .iter() + .map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()) + .collect(); + assert_eq!(work, want, "the alias b.sv must stay deduplicated against a.sv"); +} + +/// QA re-check (2026-11-26, fix round): alias shapes beyond +/// `walking_replace.rs`'s five — a chain `c -> b -> a`, two aliases of one +/// target in two directories (visited slices apart), and an alias whose +/// target lies outside the workspace root — with the target replaced after +/// every slice boundary, the last one included. Each must land trunk's +/// one-shot discovery of the final tree. +#[cfg(unix)] +#[test] +fn qa_recheck_alias_chains_split_aliases_and_outside_targets_land_trunks_discovery() { + use super::walking::{landed, one_shot_begin, sliced_begin, walk_tree, workspace}; + let outside = Tree::new("qarecheckoutside"); + type Setup = fn(&Tree, &Path); + let shapes: Vec<(&str, Setup, &str)> = vec![ + ( + "chain", + |tree, _| { + tree.write("d/a.sv", "module da;\nendmodule\n"); + std::os::unix::fs::symlink("a.sv", tree.path.join("d/b.sv")).expect("link"); + std::os::unix::fs::symlink("b.sv", tree.path.join("d/c.sv")).expect("link"); + }, + "d/a.sv", + ), + ( + "split aliases", + |tree, _| { + tree.write("d/a.sv", "module da;\nendmodule\n"); + std::os::unix::fs::symlink("../d/a.sv", tree.path.join("b/x_alias.sv")).expect("l"); + std::os::unix::fs::symlink("../d/a.sv", tree.path.join("z/y_alias.sv")).expect("l"); + }, + "d/a.sv", + ), + ( + "outside target", + |tree, outside| { + std::fs::write(outside.join("o.sv"), "module oo;\nendmodule\n").expect("w"); + std::fs::create_dir_all(tree.path.join("d")).expect("d"); + std::os::unix::fs::symlink(outside.join("o.sv"), tree.path.join("d/o1.sv")) + .expect("l"); + std::os::unix::fs::symlink(outside.join("o.sv"), tree.path.join("m/o2.sv")) + .expect("l"); + }, + "", + ), + ]; + for (name, setup, target) in shapes { + let tree = walk_tree(&format!("qarecheck{}", name.replace(' ', ""))); + setup(&tree, &outside.path); + let victim = match target { + "" => outside.path.join("o.sv"), + rel => tree.path.join(rel), + }; + let replace = |victim: &Path| { + let text = std::fs::read(victim).expect("read"); + std::fs::remove_file(victim).expect("rm"); + std::fs::write(victim, text).expect("rewrite"); + }; + let slices = sliced_begin( + &mut workspace(&tree, IndexScope::Workspace, Some(1)), + 0, + &mut |_| {}, + &mut Vec::new(), + ) + .1; + assert!(slices > 30, "premise: {name} ({slices} slices)"); + for at in 1..slices { + let mut ws = workspace(&tree, IndexScope::Workspace, Some(1)); + let (scan, _) = sliced_begin(&mut ws, at, &mut |_| replace(&victim), &mut Vec::new()); + let got = landed(&scan); + let want = landed(&one_shot_begin( + &mut workspace(&tree, IndexScope::Workspace, None), + &mut Vec::new(), + )); + assert_eq!(got, want, "{name} after slice {at}"); + } + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/state/tests/walking.rs b/crates/lucisv_server/src/state/tests/walking.rs new file mode 100644 index 0000000..f5bb221 --- /dev/null +++ b/crates/lucisv_server/src/state/tests/walking.rs @@ -0,0 +1,441 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! The sliced discovery walk against the one-shot discovery it replaces +//! (topo §2.9-58): at every slice size and at every slice boundary, with an +//! open, an edit, a close, a settings change or a file created or deleted +//! between two slices, the scan lands exactly the work list, order, buffers, +//! alias and symlink decisions, exclusions and skips the one-shot +//! discovery gives — and the same index once it is stepped to the end. + +use std::collections::HashMap; + +use super::*; +use crate::scan_trace::ScanTrace; +use crate::state::scan::{HeldAnalyses, Scan}; + +/// A workspace that exercises every discovery decision: nested folders, +/// `.gitignore` with a negation, a `lucisv.toml` exclude and a client one, a +/// file over the size cap, non-source files, and — on unix — two aliases of +/// one directory sorting before and after it, a cycle and a dangling link. +pub(super) fn walk_tree(tag: &str) -> Tree { + let tree = Tree::new(tag); + tree.write(".gitignore", "gen/\n*_tmp.sv\n"); + tree.write("lucisv.toml", "exclude = [\"vendor\"]\n"); + for dir in ["a", "b/deep", "c", "m/n/o", "z"] { + for n in 0..4 { + tree.package(&format!("{dir}/p{n}.sv"), &format!("{}_{n}", dir.replace('/', "_"))); + } + tree.write(&format!("{dir}/notes.txt"), "not a source\n"); + } + tree.write("a/x_tmp.sv", "module tmp;\nendmodule\n"); + tree.write("a/.gitignore", "!keep_tmp.sv\n"); + tree.write("a/keep_tmp.sv", "module keep;\nendmodule\n"); + tree.write("gen/made.sv", "module made;\nendmodule\n"); + tree.write("vendor/third.sv", "module third;\nendmodule\n"); + tree.write("c/skip_me.sv", "module skipped_by_client;\nendmodule\n"); + fat_package(&tree, "a/fat.sv", "fat", 4_000); + tree.write("shared/s.svh", "`define SHARED 1\n"); + #[cfg(unix)] + { + let link = |rel: &str, target: &str| { + std::os::unix::fs::symlink(target, tree.path.join(rel)).expect("symlink") + }; + link("0_alias", "shared"); + link("zz_alias", "shared"); + link("m/n/up", ".."); + link("c/gone.sv", "nowhere.sv"); + } + tree +} + +/// The settings every scan here runs under. The workspace rung raises the +/// open folders to the root, so its first scan is not split; the folder rung +/// stays in each folder, so its walk is three walks with one tracker. +fn walk_settings(scope: IndexScope) -> ClientSettings { + ClientSettings { + index_scope: scope, + index_scope_depth: if scope == IndexScope::Workspace { 1 } else { 0 }, + exclude: vec!["skip_me.sv".to_string()], + max_file_size: 1_000, + ..Default::default() + } +} + +/// A workspace over `tree` with buffers open: one in scope with unsaved +/// edits, one the excludes keep out, one spelled through an alias. +pub(super) fn workspace(tree: &Tree, scope: IndexScope, slice: Option) -> Workspace { + let mut ws = Workspace::default(); + ws.set_client_settings(walk_settings(scope)); + ws.adopt_roots(vec![tree.path.clone()]); + if let Some(entries) = slice { + ws.set_walk_slice(entries); + } + let edited = "package a_0;\n localparam K = 2;\nendpackage\n".to_string(); + ws.set_document(crate::uri::path_to_uri(&tree.path.join("a/p0.sv")).expect("uri"), edited); + open(&mut ws, tree, "vendor/third.sv"); + #[cfg(unix)] + open(&mut ws, tree, "zz_alias/s.svh"); + ws +} + +/// Everything discovery decided, as one comparable value. +pub(super) fn landed(scan: &Scan) -> String { + let sorted = |mut v: Vec| { + v.sort(); + v + }; + let buffered = sorted(scan.buffered.iter().map(|(p, t)| format!("{p:?}={t:?}")).collect()); + let facts = sorted(scan.analyzed.facts.keys().map(|p| format!("{p:?}")).collect()); + let words = sorted(scan.analyzed.words.iter().map(|(p, w)| format!("{p:?}={w:?}")).collect()); + // The spelling chosen for each identity; the `(dev, ino)` itself is the + // filesystem's, and a file deleted and written again gets a new one. + let ids = sorted(scan.canonical_ids.values().map(|p| format!("{p:?}")).collect()); + let pending = scan.pending.as_ref().map(|p| { + let seen = sorted(p.seen.iter().map(|s| format!("{s:?}")).collect()); + let seen_ids = sorted(p.seen_ids.values().map(|s| format!("{s:?}")).collect()); + format!("{seen:?} {seen_ids:?} {} {}", p.file_conflict, p.tracker.has_conflict()) + }); + format!( + "work {:?}\nhead {}\npaths {:?}\nbuffered {buffered:?}\nfacts {facts:?}\nwords {words:?}\n\ + ids {ids:?}\nincdirs {:?}\nwarnings {:?}\nskipped {}\npending {pending:?}\n", + scan.work, scan.head, scan.paths, scan.incdirs, scan.warnings, scan.skipped + ) +} + +/// The directories a walk of `ws`'s scope starts from right now. +fn walk_dirs(ws: &Workspace) -> Vec { + match ws.walks_the_workspace() { + true => ws.roots.clone(), + false => ws.scope_dirs(), + } +} + +/// Trunk's discovery over `dirs` with everything else as `ws` is now: the +/// recursive walk, the overlay, the landing — what a one-shot `begin_scan` +/// at the landing would begin if the scope's folders had not moved. +fn one_shot_begin_over(ws: &mut Workspace, dirs: &[PathBuf]) -> Scan { + ws.scan_absorbed.clear(); + let mut trace = ScanTrace::opened(&mut ws.scans, false, "whole"); + ws.views.borrow_mut().clear(); + let mut warnings = Vec::new(); + let files = ws.walked_files(dirs, &mut |w| warnings.push(w), &mut trace); + let scope = discover::Scope { files, incdirs: Vec::new(), warnings }; + let mut skipped = 0; + let cap = ws.client.max_file_size; + let sources = ws.overlay_buffers( + scope, + cap, + &mut |event| skipped += usize::from(matches!(event, IndexEvent::Skipped { .. })), + HeldAnalyses::Wanted, + &mut trace, + ); + ws.land_scope(trace, sources, None, skipped) +} + +/// Trunk's `begin_scan` for a scope resolved in one go: the recursive walk +/// of `collect_sources`, then the landing — the oracle. +pub(super) fn one_shot_begin(ws: &mut Workspace, events: &mut Vec) -> Scan { + ws.scan_absorbed.clear(); + let mut trace = ScanTrace::opened(&mut ws.scans, false, "whole"); + ws.views.borrow_mut().clear(); + let mut skipped = 0; + let sources = ws.collect_sources( + &mut |event| { + skipped += usize::from(matches!(event, IndexEvent::Skipped { .. })); + events.push(event_name(&event)); + }, + HeldAnalyses::Wanted, + &mut trace, + ); + ws.land_scope(trace, sources, None, skipped) +} + +fn event_name(event: &IndexEvent) -> String { + match event { + IndexEvent::Skipped { path, size, cap } => format!("skip {path:?} {size} {cap}"), + IndexEvent::Parsing { path, .. } => format!("parse {path:?}"), + IndexEvent::Cached { path, .. } => format!("cached {path:?}"), + IndexEvent::Analyzed { path, .. } => format!("buffer {path:?}"), + } +} + +/// A sliced scan: begun, then walked one step at a time with `between` +/// called after slice `at` — the moment a server would have answered. +pub(super) fn sliced_begin( + ws: &mut Workspace, + at: usize, + between: &mut dyn FnMut(&mut Workspace), + events: &mut Vec, +) -> (Scan, usize) { + let mut scan = ws.begin_scan(&mut |e| events.push(event_name(&e)), false); + let mut slices = 1; + while scan.walking() { + if slices == at { + between(ws); + } + assert!(ws.scan_step(&mut scan, &mut |e| events.push(event_name(&e)))); + slices += 1; + } + (scan, slices) +} + +/// Step `scan` to the end and say what the workspace then holds. +fn finished(ws: &mut Workspace, mut scan: Scan) -> String { + while ws.scan_step(&mut scan, &mut |_| {}) {} + let warnings = ws.finish_scan(scan); + format!("{}warnings {warnings:?}\n", everything(ws)) +} + +#[test] +fn every_slice_size_lands_the_scope_the_one_shot_walk_lands() { + for scope in [IndexScope::Workspace, IndexScope::Folder] { + let tree = walk_tree(&format!("walksizes{scope:?}")); + let mut oracle_ws = workspace(&tree, scope, None); + let mut oracle_events = Vec::new(); + let oracle = one_shot_begin(&mut oracle_ws, &mut oracle_events); + let oracle_landed = landed(&oracle); + let oracle_end = finished(&mut oracle_ws, oracle); + assert!(oracle_landed.contains("skipped 1\n"), "premise: the cap had a file to skip"); + let mut longest = 0; + for size in 1..400 { + let mut ws = workspace(&tree, scope, Some(size)); + let mut events = Vec::new(); + let (scan, slices) = sliced_begin(&mut ws, 0, &mut |_| {}, &mut events); + assert_eq!(landed(&scan), oracle_landed, "{scope:?}, slice size {size}"); + assert_eq!(events, oracle_events, "{scope:?}, slice size {size}"); + assert_eq!(finished(&mut ws, scan), oracle_end, "{scope:?}, slice size {size}"); + longest = longest.max(slices); + if slices == 1 { + break; + } + } + assert!(longest > 10, "premise: the smallest slices really split the walk ({longest})"); + } +} + +/// What one interleaved message does to a workspace, and whether the scan +/// that was walking when it came should see it. +struct Between { + name: &'static str, + apply: fn(&mut Workspace, &Tree), + landing_sees_it: bool, +} + +fn uri_of(tree: &Tree, rel: &str) -> Uri { + crate::uri::path_to_uri(&tree.path.join(rel)).expect("uri") +} + +fn messages() -> Vec { + vec![ + Between { + name: "open", + apply: |ws, tree| open(ws, tree, "z/p3.sv"), + landing_sees_it: true, + }, + Between { + name: "open excluded", + apply: |ws, tree| open(ws, tree, "gen/made.sv"), + landing_sees_it: true, + }, + Between { + name: "edit", + apply: |ws, tree| { + let text = "package a_0;\n localparam K = 3;\nendpackage\n".to_string(); + ws.set_document(uri_of(tree, "a/p0.sv"), text); + }, + landing_sees_it: true, + }, + Between { + name: "close", + apply: |ws, tree| ws.close_document(&uri_of(tree, "a/p0.sv")), + landing_sees_it: true, + }, + Between { + name: "settings", + apply: |ws, _| { + let mut moved = ws.client.clone(); + moved.exclude.push("b".to_string()); + moved.max_file_size = 0; + ws.set_client_settings(moved); + }, + landing_sees_it: false, + }, + ] +} + +#[test] +fn a_message_between_any_two_slices_lands_what_a_one_shot_walk_then_would() { + for scope in [IndexScope::Workspace, IndexScope::Folder] { + let tree = walk_tree(&format!("walkbetween{scope:?}")); + for message in messages() { + // The oracle: the message applied before a one-shot discovery + // when the landing is to see it, never applied when it is not — + // over the folders the scope had when the walk began, because an + // open that widens the folder scope asks for the next scan. + let mut oracle_ws = workspace(&tree, scope, None); + let dirs = walk_dirs(&oracle_ws); + if message.landing_sees_it { + (message.apply)(&mut oracle_ws, &tree); + } + let oracle = one_shot_begin_over(&mut oracle_ws, &dirs); + let oracle_landed = landed(&oracle); + let slices = sliced_begin( + &mut workspace(&tree, scope, Some(1)), + 0, + &mut |_| {}, + &mut Vec::new(), + ) + .1; + assert!( + slices > 10, + "premise: {} is tried at many boundaries ({slices})", + message.name + ); + for at in 1..slices { + let mut ws = workspace(&tree, scope, Some(1)); + let apply = message.apply; + let (scan, _) = + sliced_begin(&mut ws, at, &mut |ws| apply(ws, &tree), &mut Vec::new()); + assert_eq!( + landed(&scan), + oracle_landed, + "{scope:?} {} after slice {at}", + message.name + ); + } + } + } +} + +#[test] +fn a_file_created_or_deleted_mid_walk_is_seen_as_its_directory_was_read() { + // The one-shot walk's own race, widened: a directory read before the + // change shows the old tree, one read after it the new, so the files + // landed are exactly one of the two one-shot answers. The one window + // inside a directory: a file deleted after its directory was listed and + // before its own entry is visited is said as unreadable and not indexed + // — the recursive walk has the same window between `read_dir` and that + // entry's `metadata`, only narrower. Either way the watcher event asks + // the server for the next scan (`server/tests/walking.rs`). + // + // Identities are read once, after the walk (QA R10-QA1), so a file + // deleted after it was walked keeps its path and has no identity — the + // window trunk has between its walk and its post-walk `stat`s, as long + // as the walk. That one mixture is allowed: the identity line may come + // from the other tree than the rest. + for (name, rel, create) in [("create", "z/p9.sv", true), ("delete", "z/p2.sv", false)] { + let tree = walk_tree(&format!("walkdisk{name}")); + let change = |tree: &Tree| match create { + true => tree.package(rel, "z_9"), + false => fs::remove_file(tree.path.join(rel)).expect("remove"), + }; + let undo = |tree: &Tree| match create { + true => fs::remove_file(tree.path.join(rel)).expect("remove"), + false => tree.package(rel, "z_2"), + }; + let before = landed(&one_shot_begin( + &mut workspace(&tree, IndexScope::Workspace, None), + &mut Vec::new(), + )); + change(&tree); + let after = landed(&one_shot_begin( + &mut workspace(&tree, IndexScope::Workspace, None), + &mut Vec::new(), + )); + undo(&tree); + assert_ne!(before, after, "premise: the change is visible to discovery"); + let mut seen: HashMap = HashMap::new(); + let slices = sliced_begin( + &mut workspace(&tree, IndexScope::Workspace, Some(4)), + 0, + &mut |_| {}, + &mut Vec::new(), + ) + .1; + let vanished = format!("{}: ", tree.path.join(rel).display()); + for at in 1..slices { + let mut ws = workspace(&tree, IndexScope::Workspace, Some(4)); + let (scan, _) = sliced_begin(&mut ws, at, &mut |_| change(&tree), &mut Vec::new()); + let got = landed(&scan); + undo(&tree); + let (files, warnings) = (without(&got, &["warnings ", "ids "]), warnings_of(&got)); + let ids = line_of(&got, "ids "); + assert!( + ids == line_of(&before, "ids ") || ids == line_of(&after, "ids "), + "{name} after slice {at}: identities from neither tree" + ); + let outcome = [&before, &after] + .into_iter() + .position(|one| without(one, &["warnings ", "ids "]) == files) + .unwrap_or_else(|| { + panic!("{name} after slice {at}: a mixture\n{got}\nbefore\n{before}\nafter\n{after}") + }); + let expected = warnings_of([&before, &after][outcome]); + let extra: Vec<&String> = warnings.iter().filter(|w| !expected.contains(w)).collect(); + assert!( + extra.iter().all(|w| !create && w.starts_with(&vanished)), + "{name} after slice {at}: only the vanished file may be said: {extra:?}" + ); + *seen.entry(outcome == 1).or_default() += 1; + } + assert!(seen.len() == 2, "{name}: both outcomes occur across the boundaries: {seen:?}"); + } +} + +/// A landing with the lines starting with any of `prefixes` taken out. +fn without(landed: &str, prefixes: &[&str]) -> String { + let kept = landed.lines().filter(|l| !prefixes.iter().any(|p| l.starts_with(p))); + kept.collect::>().join("\n") +} + +/// The landing's line starting with `prefix`. +fn line_of<'a>(landed: &'a str, prefix: &str) -> &'a str { + landed.lines().find(|l| l.starts_with(prefix)).unwrap_or_default() +} + +fn warnings_of(landed: &str) -> Vec { + let line = landed.lines().find(|l| l.starts_with("warnings ")).unwrap_or_default(); + line.trim_start_matches("warnings [") + .trim_end_matches(']') + .split("\", \"") + .map(|w| w.trim_matches('"').to_string()) + .filter(|w| !w.is_empty()) + .collect() +} + +#[test] +fn a_split_startup_walks_the_rest_in_slices_and_lands_what_one_call_did() { + // A workspace-scoped first scan with a buffer open below the root leads + // with that folder and walks the rest after publishing it; that rest is + // sliced too, and lands what the unsliced rest lands. + let tree = walk_tree("walksplit"); + let run = |slice: Option| { + let mut ws = Workspace::default(); + let below = ClientSettings { index_scope_depth: 0, ..walk_settings(IndexScope::Workspace) }; + ws.set_client_settings(below); + ws.adopt_roots(vec![tree.path.clone()]); + if let Some(entries) = slice { + ws.set_walk_slice(entries); + } + open(&mut ws, &tree, "m/n/o/p1.sv"); + let mut scan = ws.begin_scan(&mut |_| {}, false); + assert!(!scan.walking() && scan.discovery_pending(), "premise: the discovery is split"); + let mut steps = 0; + while scan.discovery_pending() { + assert!(ws.scan_step(&mut scan, &mut |_| {})); + steps += 1; + } + (landed(&scan), steps, finished(&mut ws, scan)) + }; + let (whole, whole_steps, whole_end) = run(Some(usize::MAX)); + for size in [1, 2, 3, 5, 8, 13] { + let (got, steps, end) = run(Some(size)); + assert_eq!(got, whole, "slice size {size}"); + assert_eq!(end, whole_end, "slice size {size}"); + assert!(steps > whole_steps, "slice size {size} split the rest ({steps} steps)"); + } + // The default slice covers this little tree in one go, as before. + assert_eq!(run(None).0, whole); +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/state/tests/walking_replace.rs b/crates/lucisv_server/src/state/tests/walking_replace.rs new file mode 100644 index 0000000..4a35976 --- /dev/null +++ b/crates/lucisv_server/src/state/tests/walking_replace.rs @@ -0,0 +1,80 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! A file or a symlink replaced between two slices of the walk (QA R10-QA1): +//! identities are read in one pass when the walk ends, so the landing is +//! trunk's one-shot discovery of the tree as it then stands — at every slice +//! boundary, for each of the five ways a replacement can reach an alias. + +#![cfg(unix)] + +use super::walking::{landed, one_shot_begin, sliced_begin, walk_tree, workspace}; +use super::*; + +/// `d/a.sv`, its alias `d/b.sv -> a.sv`, and `d/c.sv`, beside the walk tree. +fn put_back(tree: &Tree) { + let d = tree.path.join("d"); + let _ = fs::remove_dir_all(&d); + tree.write("d/a.sv", "module da;\nendmodule\n"); + tree.write("d/c.sv", "module dc;\nendmodule\n"); + std::os::unix::fs::symlink("a.sv", d.join("b.sv")).expect("symlink"); +} + +/// One way of replacing part of `d/`. +type Replace = fn(&Tree); + +/// The five replacements, each applied to a tree in the `put_back` state. +fn replacements() -> Vec<(&'static str, Replace)> { + vec![ + ("replace the target", |tree| { + fs::remove_file(tree.path.join("d/a.sv")).expect("rm"); + tree.write("d/a.sv", "module da;\nendmodule\n"); + }), + ("replace the alias", |tree| { + fs::remove_file(tree.path.join("d/b.sv")).expect("rm"); + std::os::unix::fs::symlink("a.sv", tree.path.join("d/b.sv")).expect("symlink"); + }), + ("retarget the alias", |tree| { + fs::remove_file(tree.path.join("d/b.sv")).expect("rm"); + std::os::unix::fs::symlink("c.sv", tree.path.join("d/b.sv")).expect("symlink"); + }), + ("replace the target with a hard link", |tree| { + fs::remove_file(tree.path.join("d/a.sv")).expect("rm"); + fs::hard_link(tree.path.join("d/c.sv"), tree.path.join("d/a.sv")).expect("link"); + }), + ("delete and recreate the directory", put_back), + ] +} + +#[test] +fn a_replacement_between_any_two_slices_lands_trunks_discovery_of_the_final_tree() { + for (name, replace) in replacements() { + let tree = walk_tree(&format!("walkreplace{}", name.replace(' ', ""))); + put_back(&tree); + let slices = sliced_begin( + &mut workspace(&tree, IndexScope::Workspace, Some(1)), + 0, + &mut |_| {}, + &mut Vec::new(), + ) + .1; + assert!(slices > 30, "premise: {name} is tried at many boundaries ({slices})"); + for at in 1..slices { + put_back(&tree); + let mut ws = workspace(&tree, IndexScope::Workspace, Some(1)); + let (scan, _) = sliced_begin(&mut ws, at, &mut |_| replace(&tree), &mut Vec::new()); + let got = landed(&scan); + let want = landed(&one_shot_begin( + &mut workspace(&tree, IndexScope::Workspace, None), + &mut Vec::new(), + )); + assert_eq!(got, want, "{name} after slice {at}"); + assert_eq!( + got.matches("/d/").count(), + want.matches("/d/").count(), + "{name} after slice {at}: no alias indexed twice" + ); + } + } +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/state/walking.rs b/crates/lucisv_server/src/state/walking.rs new file mode 100644 index 0000000..cd011dc --- /dev/null +++ b/crates/lucisv_server/src/state/walking.rs @@ -0,0 +1,244 @@ +// Author: Guoliang Chen, a Senior Digital Design Engineer + +//! The discovery walk a slice at a time, so a scan answers between slices +//! (topo §2.9-58, `docs/features/server-scaling-r10/README.md`). +//! +//! Until this round `begin_scan` walked the whole scope in one call: 25–80 ms +//! on OpenTitan and ~260 ms on 40 000 files during which nothing was +//! answered — the last of the first-colour wait in workspace scope and of a +//! rescan's colour hold. [`Walking`] is that walk +//! ([`Workspace::walked_files_tracked`]) made resumable: the directories, +//! their excludes and the size cap are fixed when it begins, each +//! [`Workspace::scan_step`] advances it by [`WALK_SLICE`] entries, and the +//! step that finishes it lands the scope exactly as `begin_scan` would have. +//! +//! **What a slice may see change, and what then happens.** +//! * An open, edit or close between two slices is seen by the landing: the +//! buffers are overlaid when the walk ends, so the scan is the one a +//! one-shot `begin_scan` at that moment would have begun (proved by +//! `state/tests/walking.rs` at every slice boundary). +//! * A settings change is not: the scope was decided when the walk began, +//! and a change that moves it asks for the next scan (`rescan_wanted`), +//! exactly as it does while files are being stepped. +//! * A file created or deleted on disk is seen if its directory has not been +//! read yet and not if it has — the one-shot walk's own race, made wider — +//! and the watcher event for it asks for the next scan, which converges. +//! +//! A walk small enough to finish in the first slice lands inside `begin_scan` +//! itself, so a small tree's scan is the scan it always was. + +use std::path::PathBuf; + +use lucisv_core::config::Discovery; +use lucisv_core::walk::{dir_id, DirectoryTracker, ResumableWalk}; + +use super::discover::{dedup_by_identity, sort_found, Found, Scope}; +use super::scan::{HeldAnalyses, IndexEvent, PendingDiscovery, Scan, Sources}; +use super::Workspace; +use crate::scan_trace::ScanTrace; + +/// How many directory entries one slice of the walk visits. +/// +/// Measured, not picked: a walk entry costs ~5.4 µs on the 40 000-file tree +/// (263 ms over 48 691 entries, warm), so 512 entries is ~3 ms — under the +/// cost of indexing a handful of files, and the same work bound the scan's +/// other cadences use (`HEAD_WALK_MAX`, `PUBLISH_EVERY`). +pub(crate) const WALK_SLICE: usize = 512; + +/// One whole-scope walk in flight, and everything it was told when it began. +pub(crate) struct Walking { + /// Each directory still to walk with the excludes in force for it, + /// resolved when the walk began. + jobs: std::vec::IntoIter<(PathBuf, Vec)>, + current: Option, + tracker: DirectoryTracker, + out: Vec, + warnings: Vec, + /// `lucisv.index.maxFileSize` when the walk began. + cap: u64, +} + +impl Walking { + /// Visit up to `budget` entries; report whether the walk is done. + /// + /// The budget runs across directories: a walk of three small folders + /// finishes in one slice, as it finished in one call before. + fn step(&mut self, budget: usize, trace: &mut ScanTrace) -> bool { + let walking = trace.now(); + let mut left = budget.max(1); + while left > 0 { + if self.current.is_none() { + let Some((dir, exclude)) = self.jobs.next() else { break }; + trace.walk_dirs += 1; + self.current = Some(ResumableWalk::new(&dir, exclude, true)); + } + let Walking { current, out, warnings, tracker, .. } = self; + let Some(walk) = current.as_mut() else { break }; + left -= walk + .step( + tracker, + left, + &mut |path, meta| { + out.push(Found { path, len: meta.map(|m| m.len()), id: None }) + }, + &mut |w| warnings.push(w.to_string()), + ) + .min(left); + if walk.is_done() { + *current = None; + } + } + ScanTrace::add(&mut trace.walk_ms, walking); + self.current.is_none() && self.jobs.len() == 0 + } + + /// The walk's files in path order, one per identity — what + /// [`Workspace::walked_files_tracked`] returns — and its tracker. + /// + /// **Every identity is read here, in one back-to-back pass, after the + /// last slice** — never off a walk entry's own `metadata`. Entries are + /// visited slices apart, so a file replaced between the visit of it and + /// of its symlink alias would give the two different identities and the + /// alias would be indexed as a second file (QA R10-QA1). Read together, + /// they agree exactly as trunk's post-walk `stat`s agree. The ids are + /// carried on, so the overlay's dedup and the rest of a split discovery + /// reuse this pass instead of a second one. + fn finish(self, trace: &mut ScanTrace) -> (Vec, Vec, DirectoryTracker, u64) { + let sorting = trace.now(); + let mut out = self.out; + sort_found(&mut out); + for found in &mut out { + found.id = dir_id(&found.path); + } + let (out, _) = dedup_by_identity(out); + ScanTrace::add(&mut trace.sort_ms, sorting); + (out, self.warnings, self.tracker, self.cap) + } +} + +impl Workspace { + /// A walk of `dirs` that has not started, with each directory's excludes + /// resolved now — the inputs [`Workspace::walked_files_tracked`] reads as + /// it goes, read up front so nothing a slice answers can change them. + pub(crate) fn begin_walk( + &self, + dirs: &[PathBuf], + tracker: DirectoryTracker, + trace: &mut ScanTrace, + ) -> Walking { + let configuring = trace.now(); + let mut discovery = Discovery::new(true); + let jobs: Vec<(PathBuf, Vec)> = dirs + .iter() + .filter(|dir| dir.to_str().is_some()) + .map(|dir| (dir.clone(), self.walk_excludes(&mut discovery, dir))) + .collect(); + ScanTrace::add(&mut trace.config_ms, configuring); + Walking { + jobs: jobs.into_iter(), + current: None, + tracker, + out: Vec::new(), + warnings: Vec::new(), + cap: self.client.max_file_size, + } + } + + /// The whole scope's walk, when the scope is a walk: rung 2, or rung 3 + /// read recursively. `None` for a filelist and for the rootless flat read, + /// which `collect_sources` resolves in one go as before. + pub(super) fn whole_scope_walk(&self, trace: &mut ScanTrace) -> Option { + if self.filelist_path().is_some() { + return None; + } + let dirs = match self.walks_the_workspace() { + true => self.roots.clone(), + false if self.roots.is_empty() && self.client.index_scope_depth == 0 => return None, + false => self.scope_dirs(), + }; + Some(self.begin_walk(&dirs, DirectoryTracker::new(), trace)) + } + + /// One slice of `scan`'s walk, and the landing when it was the last. + /// + /// `slicing` is when the hold this slice belongs to began — the step's + /// start, or `begin_scan`'s for the first slice — and the trace keeps the + /// longest ([`ScanTrace::saw_slice`]). + pub(super) fn walk_a_slice( + &mut self, + scan: &mut Scan, + watch: &mut dyn FnMut(IndexEvent), + slicing: std::time::Instant, + ) { + let Some(mut walking) = scan.walking.take() else { return }; + let discovering = scan.trace.now(); + let budget = self.walk_budget(); + if !walking.step(budget, &mut scan.trace) { + scan.walking = Some(walking); + ScanTrace::add(&mut scan.trace.discovery_ms, discovering); + scan.trace.saw_slice(slicing); + return; + } + let (files, warnings, _, cap) = walking.finish(&mut scan.trace); + let mut skipped = 0usize; + let sources = { + let mut counting = |event: IndexEvent<'_>| { + skipped += usize::from(matches!(event, IndexEvent::Skipped { .. })); + watch(event); + }; + let scope = Scope { files, incdirs: Vec::new(), warnings }; + self.overlay_buffers(scope, cap, &mut counting, HeldAnalyses::Wanted, &mut scan.trace) + }; + ScanTrace::add(&mut scan.trace.discovery_ms, discovering); + let trace = std::mem::take(&mut scan.trace); + *scan = self.land_scope(trace, sources, None, skipped); + scan.trace.saw_slice(slicing); + } + + /// One slice of the rest of a split discovery's walk + /// ([`PendingDiscovery`]): `Some` with what it found once it is done. + pub(super) fn walk_the_rest( + &self, + pending: &mut PendingDiscovery, + budget: usize, + trace: &mut ScanTrace, + ) -> Option<(Vec, Vec)> { + let walking = match pending.walking.as_mut() { + Some(walking) => walking, + None => { + let tracker = std::mem::take(&mut pending.tracker); + pending.walking.insert(self.begin_walk(&pending.roots, tracker, trace)) + } + }; + if !walking.step(budget, trace) { + return None; + } + let walking = pending.walking.take()?; + let (files, warnings, tracker, _) = walking.finish(trace); + pending.tracker = tracker; + Some((files, warnings)) + } + + /// How many entries a slice visits: [`WALK_SLICE`], or what a test set. + pub(super) fn walk_budget(&self) -> usize { + self.walk_slice.unwrap_or(WALK_SLICE) + } + + /// Make every slice of every walk `entries` long — test-only, so the + /// identical-result proof can put a slice boundary everywhere. + #[cfg(test)] + pub(crate) fn set_walk_slice(&mut self, entries: usize) { + self.walk_slice = Some(entries); + } +} + +/// Whether `sources` came from a walk that is still under way — what +/// `first_scope` hands back when the whole scope is to be walked. +pub(super) enum Begun { + /// The scope is resolved; a split discovery's rest may still be owed. + Resolved(Box<(Sources, Option)>), + /// The scope is a walk, begun and not yet taken a step. + Walking(Box), +} + +// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/crates/lucisv_server/src/state/watched.rs b/crates/lucisv_server/src/state/watched.rs index 240e62b..04c2345 100644 --- a/crates/lucisv_server/src/state/watched.rs +++ b/crates/lucisv_server/src/state/watched.rs @@ -140,7 +140,7 @@ impl Workspace { let mut found = None; let take = &mut |file: PathBuf, len| { if file == path { - found = Some(Found { path: file, len }); + found = Some(Found { path: file, len, id: None }); } }; if collect_files_below(scope, dir, &excludes, true, take, &mut |_| {}).is_err() { diff --git a/docs/features/server-scaling-r10/README.md b/docs/features/server-scaling-r10/README.md new file mode 100644 index 0000000..a4b9641 --- /dev/null +++ b/docs/features/server-scaling-r10/README.md @@ -0,0 +1,536 @@ + + +# lucisv_core + lucisv_server scaling (Round 10) + +## Goal + +Close `docs/topo.md` §2.9 rows 58 and 64. **#58**: the discovery walk at the +front of every whole scan held `&mut Workspace` for its whole length (25–80 ms +on OpenTitan, ~390 ms on 40 000 files) and answered nothing meanwhile — the +last of the first-colour wait in workspace scope and of a rescan's colour +hold. Make it resumable, so the server answers between slices, with an +identical-result proof. **#64**: the 40 000-file rescan after a delete was +reported as taking either 12.3 s or 14.5–15.5 s; diagnose that with +measurements, write the cause down, fix what the diagnosis supports, and try +the candidate speed-ups the handoff lists, keeping only what measures. A +performance round: no new features, no client-visible change but timing, and +every answer, the discovered file set and the index store byte-identical to +trunk (`dc54b23`). + +## Assumptions + +- **The scope of a sliced walk is fixed when it begins.** Its directories, + each directory's excludes (`lucisv.toml` + `lucisv.exclude`) and the size + cap are read once, up front (`state/walking.rs` `begin_walk`). A settings + change between two slices does not move this scan; it asks for the next one + (`rescan_wanted`), exactly as a settings change between two *files* always + did. The open buffers are not fixed: they are overlaid when the walk lands, + so an open, an edit or a close between two slices is seen by this scan. +- **A file created or deleted on disk mid-walk** is seen if its directory + has not been read yet and not if it has (each directory as it was when it + was listed). One window inside a directory: a file deleted after its + directory was listed and before its own entry is visited is said as + unreadable (a walk warning) and not indexed — the recursive walk has the + same window between `read_dir` and that entry's `metadata`, only narrower. + In every case the watcher event for the change asks for the next scan, + which converges (proved: `state/tests/walking.rs`, + `server/tests/walking.rs`). That warning is the scope's first warning and + so can surface as a `window/showMessage` popup (`report_scope`), e.g. + `lucisv: : No such file or directory (os error 2)`; trunk has the + same race, slicing widens it by the drain time (R10-QA2, no code change). +- **Identities are read once, together, when the walk ends** (fix round, + R10-QA1). `Walking::finish` stats every walked file back to back after the + last slice and carries the result on `Found::id`; `dedup_by_identity`, the + overlay's dedup and `rest_of_scope` reuse that one pass instead of trunk's + two or three passes. Trunk's window — between a file's walk entry and its + post-walk `stat`, as long as the walk — is kept, widened only by the drain + time between slices; the round-1 scheme (identity off each entry's own + walk `metadata`) is **withdrawn**: entries visited slices apart could see one + replaced file as two, and a file-symlink alias was indexed twice. With it + goes the earlier claim that the round "closes the window in which a file + deleted after being walked kept its path but lost its identity": that + window is trunk's again (a deleted file can land in the work list with no + identity, as on trunk, and the watcher event's rescan converges). + `walk::meta_id` is removed. +- **The store kept across rescans is the store read again.** `IndexCache` + remembers the store file's (length, mtime, inode) whenever its entries, + header flag and load counts are exactly what `IndexCache::open` would read + from that file — after a load nothing moved, after a compaction — and + forgets it at the first append. A rescan keeps the cache only while the + file still has that stamp; another session's append (length), compaction + (rename → inode) or anything else that moves the mtime reads it again. The + store is content-keyed and never a correctness input, so even a stale kept + entry could only change a hit into a miss or back, never an answer. +- Timing method for every table: release build, the machine otherwise idle + (load ≤ 3 before each session, noted in the logs), trunk built from a + detached worktree at `dc54b23` with its own target dir, binaries run in + alternation, `N` ≥ 5 per cell, min / median / max reported. + +## Handshakes + +- **lucisv_core (new API, additive):** `walk::ResumableWalk` (`new`, `step` + — visits at most `budget` entries and returns how many, `is_done`, + `error`) and `DirectoryTracker: PartialEq + Eq`. (`walk::meta_id` from + round 1 is removed in the fix round.) The + recursive `collect_files*` walks are untouched; the CLI does not use the new + walk. +- **lucisv_server, internal:** `state::walking` (new) owns the sliced walk. + `Scan` gains `walking` and `walking()`; `neighbourhood_indexed()` is false + while walking; `Workspace::begin_scan` may return a scan still walking, which + `scan_step` advances a slice at a time (each step indexes nothing and + returns `true`). `server/index.rs` `scan_once` drains between walk slices + and decides "interleave or not" after the walk lands, exactly as before + (`Server::interleaves`). `discover::Found` gains `id`; `overlay_buffers` + takes the cap; `first_scope` returns `walking::Begun`; `rest_of_scope` + takes the walked files. `IndexCache::reopen` (new) replaces the bare + `open` in `open_store`; compaction streams (`render_to`). + `Candidates::from_words` counts without a clone per occurrence. +- **Trace (verbose only):** the `stages` line gains `slice_max` (the longest + discovery hold of the scan, ms) and the `counts` line gains `slices`. A + rescan that keeps the store reports `opens=0`. +- **Request to `vlog_semantic` (not done, out of this round's crates):** + `WorkspaceIndex::absorb` is 2.06–2.17 s of a 6.6 s rescan at 40 000 files + (32 %), the largest stage left; see the #64 tables. +- **Perf tooling (new):** `tools/perf/bigtree.py`, `rescan.py`, + `rescan_diff.py` — not yet listed in `tools/perf/README.md` (outside this + round's file list; a docs request for the lead). Any speed-up there is + `vlog_semantic`'s lane. + +## Status / TODO + +- [x] #58 resumable walk in `lucisv_core` (`walk/resumable.rs`), proved equal + to the recursive walk at every slice size and with varying slice sizes. +- [x] #58 sliced whole-scope walk and sliced rest-of-scope walk + (`state/walking.rs`), landing identical to trunk's one-shot discovery + at every slice size and boundary, with an open / edit / close / + settings change / create / delete between slices. +- [x] #58 server drains between slices; scripted mid-walk bursts settle + where the same burst between files does, and where a fresh server + starts. +- [x] #64 reproduce with the existing harness — rebuilt (`tools/perf/bigtree.py`, + `tools/perf/rescan.py`): **not reproduced**; see Diagnosis. +- [x] #64 cache reuse across rescans — kept (−0.7 s at 40k). +- [x] #64 streaming compaction — kept (−50 ms, −0.47 GB peak RSS at 40k). +- [x] #64 pre-sized candidates (and no clone per word occurrence) — kept (−60 ms at 40k). +- [ ] #64 `absorb` — not this round's crate; handshake request above. +- [x] Fix round: R10-QA1 (identities in one pass at landing; QA test passes + unmodified; five replacement cases vs trunk's one-shot), R10-QA3 + (`scan_step` 82 → 49 lines, `facts_of_step` 44), R10-QA4 (TODO §71 + wave-7 walk item ticked; wave-8 40k item left open — the cause was not + found, it was not reproducible), R10-QA6 (`rescan_diff.py` refuses a + non-store `--storage`), R10-QA5 (re-run below), R10-QA2 (Assumptions). +- [x] lifecycle_r2 debug ceiling — unchanged (nothing here touches the close + path; measured headroom recorded below). + +## Work log + +### 2026-11-26 — dev + +**#64 first: reproduce.** The 40k harness (`fast-actions`' `gen.py`, +`ab41.py`, `b3.py`) lived in a scratch directory and is gone, and `bench.py` +has no rescan phase. Rebuilt as `tools/perf/bigtree.py` (OpenTitan `hw/` +copied 10× under `c0/…c9/` with every declared unit name prefixed `cK_`, into +a scratch directory; 40 470 files) and `tools/perf/rescan.py` (one session: +startup, then per run delete the previous probe file → `didChangeWatchedFiles` +Deleted, create a new one → Created, which owes a whole rescan; `idle` waits +for the delete's update first, `busy` sends the create 50 ms later; every +rescan's `--verbose` stage / count / memory lines parsed into the row, RSS +sampled every 100 ms). All under `tools/guard.sh -m 8 -t 1200`. + +The table to reproduce is fast-actions' QA table (0.65.10 / lane, 40k, the +rescan as the server times it): idle 12.35–12.56 s; busy 12.31–12.32 or +14.58–15.09 s. + +**Result: the bimodality does not reproduce, on trunk or on 0.65.11.** +Server-timed whole rescan after a delete, 40 470 files, release, machine +idle (load 1.3–3.7), 3 rescans per session (a 4th is killed by the 8 GB +guard — see F2): + +| binary | mode | N | min | median | max | +|---|---|---:|---:|---:|---:| +| trunk `dc54b23` | busy (create 50 ms after the delete) | 12 | 7 422 ms | 7 540 ms | 7 626 ms | +| trunk `dc54b23` | idle (create after the delete's update) | 12 | 7 437 ms | 7 527 ms | 7 819 ms | +| 0.65.11 `cc1e2c8` | busy | 7 | 7 337 ms | 7 524 ms | 7 669 ms | +| 0.65.11 `cc1e2c8` | idle | 8 | 7 360 ms | 7 426 ms | 7 566 ms | +| trunk, 18 `yes` processes on 18 cores | busy | 6 | 9 279 ms | 9 756 ms | 10 021 ms | + +Every stage is unimodal too (trunk, 24 rescans): read 817–878, cache_open +672–712, lookup 385–388, decode 1 216–1 269, absorb 2 037–2 307, compact +676–707, candidates 603–635, discovery 363–381 ms. Max/min of the total is +≤ 1.05 on a quiet machine. What the evidence says about the reported +numbers: + +- They are 1.6–2.0× today's 7.5 s for the same binary family (0.65.11 + is as fast here as trunk), and fast-actions' README says its machine was + shared with other lanes' builds. Deliberate CPU contention (18 busy + processes) raises the rescan to 9.3–10.0 s but still does not split it + into two modes. **The cause of 12.3 vs 14.5–15.5 s is outside the code + as far as this machine can show** — host load / memory state at the time; + it cannot be reproduced here, and no fix is made for it. +- 0.65.11's delete really was slow (its "busy" wall time is 9.7–10.1 s + against 7.3–7.7 s for the rescan itself: the create waited behind a + ~2.3 s one-file delete); trunk's delete update is 35 ms (Round 2's + tombstones). The "busy" bimodality in the old table was therefore read + through a 2.3 s handler; that handler is gone. +- What *is* real and in the code: peak RSS of a 40k rescan is 6.8–7.9 GB and + grows across rescans (F2), which on a shared machine is the kind of state + that varies. Streaming compaction below takes 0.5–0.7 GB off that peak. + +**What the rescan costs (trunk, 40k, median of 12):** absorb 2 111 +(28 %), decode 1 237, read 870, compact 681, cache_open 676, candidates 617, +lookup 386, discovery 373, includes 76 ms. Each candidate in the handoff +was measured against the binary before it, alternating sessions, N = 6: + +| change | stage before → after (min–max) | rescan before → after (median) | peak RSS (median) | kept? | +|---|---|---|---|---| +| #58 sliced walk + identity from the walk's own `metadata` (identity part withdrawn in the fix round: sort back to ~50 ms at 40k, see below) | discovery 370–382 → 277–285 (sort 55→10, cap 50→5) | 7 585 → 7 510 ms | = | yes (#58) | +| cache reuse across rescans (`IndexCache::reopen`) | cache_open 673–702 → 0.0 | 7 516 → 6 809 ms | = | **yes** | +| streaming compaction (`render_to`) | compact 677–725 → 628–643 | 6 809 → 6 753 ms | 6.95 → 6.48 GB | **yes** | +| candidates: reserve + no clone per occurrence | candidates 615–632 → 549–583 | 6 682 → 6 637 ms | = | **yes** | +| `absorb` | 2 041–2 307 ms | — | — | not this round's crate (handshake) | + +**Final, trunk vs this tree (40k, idle, alternated, N = 6 each):** + +| | trunk | this tree | +|---|---|---| +| whole rescan (server) | 7 501 / 7 572 / 7 640 ms | **6 601 / 6 655 / 6 789 ms** (−12 %) | +| `documentSymbol` sent 5 ms after the create | 1 111 / 1 122 / 1 158 ms | **53 / 57 / 96 ms** | +| longest discovery hold | ≈ 386 ms (discovery + order, one hold) | **33 / 33 / 35 ms** (`slice_max`; the landing slice) — superseded by the fix round: 74 / 74 / 77 ms | +| peak RSS | 6.99 / 7.14 / 7.73 GB | **6.28 / 6.44 / 6.55 GB** | + +**#58 on OpenTitan-sized trees (min / median / max, N = 6):** + +| | trunk | this tree | +|---|---|---| +| `hw/` itself, settings-push rescan: discovery hold | 66.5 / 73.1 / 77.7 ms in one piece (+1 ms order) | **4.8 / 5.0 / 5.7 ms** longest of 24 slices — superseded by the fix round: 11.0 / 11.5 / 11.9 ms | +| `hw/` itself, whole rescan | 703 / 722 / 755 ms | **616 / 636 / 656 ms** | +| 4 047-file copy, `documentSymbol` 5 ms after a watched create | 107 / 109 / 119 ms | **5.3 / 5.5 / 6.3 ms** | +| 4 047-file copy, longest discovery hold | ≈ 37 ms + the store open 68–72 ms before the first drain | **3.8 / 3.9 / 4.0 ms** (12 slices), store kept — superseded by the fix round: 8.4 / 8.5 / 9.0 ms | +| 4 047-file copy, whole rescan | 749 / 760 / 776 ms | **653 / 667 / 688 ms** | + +(A settings push holds every request by design — `REACH` — so the `hw/` +rows measure the hold from the trace, not a probe; the corpus is never +written. The 40k landing slice — sort, cap, overlay, ordering — is the 33 ms; +everything before it is ≤ 3 ms slices of 512 entries.) + +**Identical-result proof (#58).** +- `lucisv_core` `walk/resumable/tests.rs`: on trees with nested + `.gitignore` + negation + directory-only rules, an exclude, a symlink + cycle, two aliases sorting before and after their target, a dangling + source link, empty directories, unreadable directory and ignore file, a + file input, a missing input and a pre-filled tracker (the split startup): + the event sequence (every found path with its length, every warning, in + order), the error and the final tracker equal the recursive walk's — for + **every** slice size from 1 to one past the walk, and for 200 seeds of + per-step sizes 1–7. +- `state/tests/walking.rs`: the landed scan (work list and order, head, + paths, buffered texts, analysed buffers and their words, canonical + spellings per identity, incdirs, warnings, skips, split-discovery state) + and the watch events equal **trunk's one-shot discovery** + (`collect_sources` → recursive walk → `land_scope`) for every slice size + 1…N in both the workspace and the folder rung, and the finished index / + completion tables / include graph too; an open, an open of an excluded + file, an edit, a close and a settings change applied after **every** + slice boundary land what the one-shot discovery lands with the message + applied first (settings: not applied — the scope is fixed at the start); + a create / delete mid-walk lands exactly the before- or after-tree + answer (both occur), with only the vanished file's own warning extra; a + split startup's rest walked in slices lands what one call lands. +- `server/tests/walking.rs`: through the real `process_batch`, a rescan + with 1-entry slices drains between slices (interleave points > files + 10) + and answers a buffer-local request there; open / edit / close / settings / + watched create / watched delete scripted at the first, middle and last + walk drain settle byte-identical (index, include graph, completion words, + buffers) to the same burst at a drain between *files* (trunk's own + interleaving), with settings / create / delete each owing exactly one more + scan; and all but the edit settle equal to a fresh server (F1). +- Existing suites unchanged except two expectations the round moves: + `interleave.rs` cadence test steps past the walk slices of its 514-file + tree first; `server/tests/scan_trace.rs` expects `opens=0` for the warm + rescan that keeps the widen's read. + +**Identical-result proof (#64).** `index_cache/reuse_tests.rs`: after a +compaction, after a compaction that dropped a gone file, and for a fresh +open, the kept cache equals `IndexCache::open` of the same file (entries, +hashes, encoded facts, header flag, load counts) and compacts to nothing; a +store another session appended to, compacted and renamed over ours, our own +append, another directory and persistence off are all read again; the +streamed rewrite is byte-identical to the whole-text render (> 1 MiB store). +**OpenTitan differential** (`tools/perf/rescan_diff.py`, cold store, +startup + 2 rescans, 94 answers: 5 `workspace/symbol`, the module hierarchy, +the outline, definition / hover / references at 8 cursors, each after every +scan): trunk and this tree **identical**, store 50 626 930 bytes, SHA-256 +`f268de99…81821` both. **40k differential** (startup + 1 rescan; trunk was +guard-killed at 8.68 GB with 2 rescans, this tree finished 2): 63 answers +identical, store 532 809 161 bytes, SHA-256 `8589460e…3d6d7` both (this +tree's store after 2 rescans: same hash). `git -C opentitan status +--porcelain` empty after every run. + +**lifecycle_r2:240 debug ceiling (100 ms).** Unchanged: the close path +(`remove_one`, `vlog_semantic`) is not touched and `absorb` did not get +faster in this round. Measured in isolation (`--test-threads=1`, debug, +3 runs): 8.66 / 8.67 / 8.73 ms per tombstoned close; the ceiling was raised +for loaded CI runs, so lowering it needs `absorb`/`remove_file` work first. + +**Findings (not fixed, out of scope or pre-existing):** +- **F1** (pre-existing on trunk): an edit arriving mid-scan to a buffer the + scan already took leaves the completion word table with the old text's + words (index correct). Reproduced on trunk `dc54b23` with an edit at the + 5th file drain: `only mid-scan ["s"]`, `only fresh ["t"]`. Same between + walk slices with this tree, so the walk test compares against trunk's + interleaving and excludes the edit from the fresh-server comparison. +- **F2**: on 40k files a server's RSS grows across rescans (3.9 GB settled → + 6.8 → 6.9 → 7.5 GB after 3 rescans on trunk; 4k: 0.52 → 1.04 GB over 6); + the 8 GB guard killed a 4th rescan (trunk, 0.65.11 twice, and this tree's + first cold-store session once). Not diagnosed (allocator retention vs a + table that grows); streaming compaction lowers the peak but not the + growth. +- **F3**: `begin_widen` (a `didOpen` into a new folder) still walks in one + call; it walks only the added folders. `filelist` scopes and the rootless + flat read are unchanged too. + +**Tests run (this tree):** `cargo fmt --all -- --check` clean; `cargo clippy +--workspace --all-targets` clean, no new `#[allow]`; guarded `cargo test -p +lucisv_core` 128 passed, `-p lucisv_server` 2 236 passed / 53 ignored, +`-p lucisv_mcp` 400 / 3 ignored, `-p lucisv` 162; with `LUCISV_OPENTITAN` +set (real runs): `lucisv_server --test opentitan_references --ignored` 2 +passed (11.9 s), `localized_reindex --ignored` 2 passed (36 s); +`tools/gates.sh --only cross` pass. + + +### 2026-11-26 — dev, fix round (lead's rulings on the QA log) + +**R10-QA1.** Chose the lead's default: every identity read in one +back-to-back pass after the last slice (`Walking::finish`), reused by the +overlay dedup and `rest_of_scope`, so the window is trunk's (walk length) +plus drain time and two walk entries can no longer disagree about one file. +No cheaper scheme was attempted: nothing short of reading the identities +together gives trunk's answer when an alias and its target are visited +slices apart. Proof: QA's `state/tests/qa_walking.rs` passes unmodified; +`state/tests/walking_replace.rs` (new) — replace the target, replace the +alias, retarget the alias, replace the target with a hard link, delete and +recreate the directory holding both — applied after **every** slice +boundary (1-entry slices, > 30 boundaries each) lands exactly trunk's +one-shot discovery (`collect_sources`) of the final tree, and no alias is +counted twice. `a_file_created_or_deleted_mid_walk…` now allows the one +mixture trunk itself has (a file deleted after it was walked: its path from +the old tree, its identity line from the new). + +**Landing hold, re-measured** (release, alternated, min / median / max of +`slice_max`; "round 1" = the identity-from-metadata build): + +| tree | round 1 | fix round | change | trunk (one hold) | +|---|---|---|---|---| +| OpenTitan `hw`, settings rescan, N=6 | 4.9 / 5.1 / 6.5 ms | 11.0 / 11.5 / 11.9 ms | +6.4 ms | 66.5–77.7 ms | +| 4 047-file copy, N=6 | 3.8 / 3.9 / 4.1 ms | 8.4 / 8.5 / 9.0 ms | +4.6 ms | ≈ 37 ms + 68–72 ms store open | +| 40 470 files, N=3 (guard allows 3) | 32.9 / 33.0 / 33.0 ms | 73.7 / 74.0 / 76.5 ms | +41 ms | ≈ 386 ms | + +The growth is the identity pass (`sort` stage: 0.8 → 7.4 ms on `hw`, +9.9 → 50.1 ms at 40k). The landing slice is now the longest hold of the walk +at every size; the earlier tables' "longest discovery hold" rows read these +numbers instead. Unchanged: buffer-local probe 5 ms after a create, 4k copy +4.7 / 5.0 / 7.5 ms (round 1 4.6 / 5.1 / 9.3), 40k 47 / 51 / 74 ms; whole +rescan `hw` 611 / 627 / 649 ms, 4k 651 / 662 / 683 ms, 40k 6 628 / 6 652 / +6 754 ms (N=3). + +**R10-QA5.** My round-1 `localized_reindex --ignored` run was a **silent +skip** for the OpenTitan sweep: I set `LUCISV_OPENTITAN` to the repo root, +and that test wants the `hw` directory. Re-run for real: +`LUCISV_OPENTITAN=/Users/lucio/repo/opentitan/hw tools/guard.sh -m 8 -t 1200 +-- cargo test --release -p lucisv_server --bin lucisv-server +localized_reindex -- --ignored --test-threads=1 --nocapture` → seed 21: 60 +steps over 278 files, 3 whole rescans; seed 22: 60 steps, 2 whole rescans; +corpus seeds 11–13: 60 steps over 860 files, 2/2/3 whole rescans; 2 passed in +44.4 s. `LUCISV_OPENTITAN=/Users/lucio/repo/opentitan … --test +opentitan_references -- --ignored` → 2 passed in 12.3 s (`aes`: 14 +references listing the three generated tops; folder scope 11). + +**Checks.** `cargo fmt --all -- --check` clean; `cargo clippy --workspace +--all-targets` clean; guarded `cargo test --all-targets`: `lucisv_core` 129 +passed, `lucisv_server` 2 243 passed / 53 ignored (QA's tests included), +`lucisv_mcp` 400 / 3, `lucisv` 162; `stamp_author.py --check` 0, new files' +stamps checked by hand; `tools/gates.sh --only cross` pass. OpenTitan `hw` +differential vs a fresh `dc54b23` worktree build: 94 answers identical, store +50 626 930 bytes, SHA-256 `f268de99…81821` both. Opentitan porcelain empty; +worktree and scratch trees removed. + +## QA log + +### 2026-11-26 — QA + +**Verdict: PASS with findings.** One Medium finding (R10-QA1) the lead should rule on before merge. No guard kills. + +**Baseline.** `cargo fmt --all -- --check` clean. `cargo clippy --workspace --all-targets` clean, including the QA tests. Guarded `cargo test -p lucisv_core` 128 (+1 QA) passed, `-p lucisv_server` all green before the QA tests went in, `-p lucisv_mcp` and `-p lucisv` green. `stamp_author.py --check` stamps nothing. I checked the header and footer stamps of every untracked file by hand and all are right; the three new `tools/perf/*.py` have no shebang, which matches `harness.py` / `lspclient.py`. Production lines are all ≤ 600 (`rescan.rs` 524, `discover.rs` 515, `index_cache.rs` 396, `walking.rs` 153, `resumable.rs` 171). The diff adds no `unwrap`/`expect`/`panic!`/`unsafe`/`#[allow]` to library paths. `tools/gates.sh --only cross` passes. + +**Walk equivalence.** I read `walk/resumable.rs` against `Walk::dir`/`entries`/`push_ignore`. The fs calls happen in the same order, `rel`/ignore push and pop match, read_dir errors are handled the same, and file input, missing input and a pre-entered root behave the same. It always terminates: each step consumes one entry or pops one frame, and budget 0 is treated as 1. I added `walk/resumable/tests.rs::qa_edge_budgets_a_symlinked_root_a_negated_dir_and_a_deep_chain_walk_the_same`, which covers budget 0 and `usize::MAX`, a root that is a symlink to a directory, an ignored-then-negated `vendor/` with its own nested `.gitignore`, and a 40-deep chain at every slice size. It passes. Both walks still exist: the recursive one is used by the head walk, the widen and `collect_files_below`. The core tests compare them on every branch tree, so drift would be caught. + +**State/server.** The `state/tests/walking.rs` oracle is rebuilt from the recursive `walked_files` plus the shared `overlay_buffers`/`land_scope`. It is not trunk's binary; the trunk binary comparison is `rescan_diff.py` (below). I added `server/tests/qa_walking.rs`, all passing: +- A workspace folder removed at walk drain 1/15/40 ends with no stale files and an index fingerprint identical to a fresh server over the remaining folder. +- Two watched creates in two different slices cost exactly one more scan, not two, and both files are indexed. +- A code lens sent mid-walk is held and answered exactly once. +- A `shutdown` sent mid-walk is held once and not answered mid-walk. This matches the between-files behaviour of a rescan. I did not drive the `exit` handshake. + +**R10-QA1 (Medium, new in this tree; not reproducible on trunk): a file replaced mid-walk breaks symlink-alias dedup.** +- Repro: `state/tests/qa_walking.rs::qa_a_file_replaced_mid_walk_keeps_its_symlink_alias_deduplicated` (left in, **FAILS**). Tree is `a.sv`, `b.sv -> a.sv`, `c.sv`, slice 1. After the slice that visits `a.sv`, `a.sv` is removed and rewritten with the same bytes and a new inode. +- Observed work list: `["a.sv","b.sv","c.sv"]`. Expected (one-shot discovery on the same tree): `["a.sv","c.sv"]`. +- Cause: `Found.id` comes from each entry's own walk `metadata` (`walking.rs:82`), and `dedup_by_identity` (`discover.rs:126`) prefers it. Two entries read at different moments can therefore disagree about one file. +- Trunk stats both paths back to back after the walk, so its window is microseconds. Here the window is any slice drain. +- Effect: the module is indexed twice under two paths. A watcher event for `a.sv` classifies as `Watched::Held` (`watched.rs:42`), a one-file reindex, so the duplicate lasts until the next whole rescan. That last point is from reading the code, not a server-level run. +- Trigger: an atomic save or a `git checkout` of a file that has a file-symlink alias, during a rescan's walk. + +**Low findings:** +- **R10-QA2: deleted-mid-walk warning becomes a popup.** The "deleted after listed, before visited" warning (Assumptions, second bullet) is user-visible. `report_scope` (`server/client.rs:239`) sends the first scope warning as a `window/showMessage` popup: `lucisv: : No such file or directory (os error 2)`. Trunk has the same race; slicing widens it by the drain time. +- **R10-QA3: `scan_step` grows past the function-size guideline.** `scan_step` (`state/rescan.rs:412`) is now 82 lines (trunk ~76), over CLAUDE.md's "investigate over 80". +- **R10-QA4: `TODO.md` not ticked.** The §71 items at `TODO.md:7479` (walk) and `:7501` (40k rescan) are still `[ ]`. CLAUDE.md asks the dev to tick completed items. +- **R10-QA5: the dev's OpenTitan sweep run was most likely a skip.** `localized_reindex::a_seeded_sweep_over_an_opentitan_sample_holds` reads `LUCISV_OPENTITAN` as the **`hw`** directory. With the repo root it prints `… not present — skipping` and passes (I saw this). With `LUCISV_OPENTITAN=/Users/lucio/repo/opentitan/hw` it ran for real: seeds 21/22, 278 files, 2–3 whole rescans each, passed, 42 s. The env contract differs from `opentitan_references`, which wants the root. +- **R10-QA6: `rescan_diff.py` can delete a mistyped directory.** It runs `shutil.rmtree(--storage)` without any guard. `lspclient.py:121` does the same, so the pattern pre-exists. + +**IndexCache::reopen.** No case where a kept cache gives a different answer. Every entry is keyed by the hash of the bytes it was parsed from, so a mismatch between kept and freshly opened can only turn a cache hit into a miss or the reverse. The stamp holds up against the cases I listed: +- another session's append (length changes); +- another session's compaction (rename gives a new inode; even when ext4 reuses that inode, the mtime also has to match); +- an append during `open` (before and after stamps differ); +- the store deleted (stamp is `None`, so the file is re-read); +- persistence off, or a different directory. + +The one gap is an in-place rewrite to the same length with the mtime restored. No lucisv writer does that; `cp -p` would. `index_cache/reuse_tests.rs::qa_an_in_place_same_length_rewrite_with_its_mtime_restored_is_kept_but_only_changes_hits` passes and pins it as harmless (the kept hit equals the parse; the fresh read is a miss). There is also a microsecond race in `compact_now` between the rename and `Stamp::of`: another session's append there would be in the stamp but not in the entries. That costs a miss only. + +**Streaming compaction** is still temp file plus rename, so it is atomic as before. A failed write leaves the `.tmp` file, exactly as trunk's `fs::write` did. `entries.retain(exists)` now prunes memory too, which can only cost a miss within the same session. The store is byte-identical to trunk: see the differential below. + +**Candidates.** `from_words` is the same count without the clone; the maps are std `HashMap` (random order) on both sides. I verified this by reading the code only: `rescan_diff.py` sends no completion query. + +**Differential (OpenTitan `hw`).** `rescan_diff.py`, trunk built in a scratch worktree at `dc54b23`, cold store, startup plus 2 rescans: 94 answers identical. Store 50 626 930 bytes, SHA-256 `f268de99…48581821` from both binaries, matching the dev's. + +**Timing** (release builds, binaries alternated, load 1.1–2.8; min / median / max): + +| | trunk | this tree | +|---|---|---| +| 4 047-file copy, whole rescan, N=12 | 725 / 751 / 771 ms | 624 / 653 / 724 ms | +| 4 047-file copy, `documentSymbol` 5 ms after the create | 111 / 113 / 124 ms | 3.6 / 7.4 / 15.1 ms | +| 4 047-file copy, `slice_max` | — | 3.9 / 4.3 / 4.7 ms (12 slices) | +| 4 047-file copy, `cache_open` | 68 / 70 / 73 ms | 0 (opens=0) | +| `hw` settings rescan, N=8 | 678 / 697 / 715 ms | 608 / 637 / 707 ms | +| `hw` `slice_max` | — | 5.1 / 5.6 / 6.7 ms (24 slices) | + +The dev's claims reproduce. The probe is a little slower than the 5.3–6.3 ms claimed: the first rescan of each session takes 14–15 ms. + +**F1** reproduces identically on trunk `dc54b23`. With an edit at file drain 5 and at drain 1, both trees give `only mid-scan ["s"] only fresh ["t"]` and an equal index. Mid-walk (slice 1, drain 1 and 3) this tree gives the same result. It is not new and not worse. + +**F2** (RSS after rescans 1→6, 4k copy, two sessions each): + +| | after rescan 1 | after rescan 6 | per rescan at the end | +|---|---|---|---| +| trunk | 751 / 748 MB | 1 058 / 1 048 MB | still about +50 MB | +| this tree | 676 / 671 MB | 779 / 773 MB | plateaus at about +2–5 MB | + +The kept cache does not make the growth worse; it improves it. + +**Ignored OpenTitan tests, real runs:** +- `opentitan_references --ignored`: 2 passed, 13.9 s, with real output (the three generated tops listed). +- `localized_reindex` corpus sweep: passed, seeds 11–13, 860 files. +- `localized_reindex` OpenTitan sweep: passed as above (with the `hw` env). +- `ordering_random::random_bursts_long_run`: passed, 84 s. + +**Tests run after the QA tests went in:** +- Full `lucisv_server` bin suite: 2 131 passed and 1 failed. The failure is R10-QA1 only. Cargo stopped at that target, so the integration tests did not re-run; they passed at baseline. +- The new `reuse_tests` QA test passes. + +**Not verified:** +- The 40k tree (skipped: its size is near the guard limit). +- The `exit` half of a mid-walk shutdown. +- R10-QA1's persistence through a real watcher event (code reading only). +- Non-unix behaviour beyond `cargo check`. + +**Housekeeping.** No guard kills. The scratch worktree and copied trees were removed, and `git -C opentitan status --porcelain` is empty. QA files added to the tree: `server/tests/qa_walking.rs`, `state/tests/qa_walking.rs` (failing on purpose, R10-QA1), plus one test each appended to `walk/resumable/tests.rs` and `index_cache/reuse_tests.rs`, and `mod qa_walking;` lines in both `tests/mod.rs`. + +### 2026-11-26 — QA, re-QA of the fix round + +**Verdict: PASS.** R10-QA1 is fixed. Only one nit is left, listed at the end. No guard kills. + +**a. Tests.** +- My `state/tests/qa_walking.rs::qa_a_file_replaced_mid_walk_keeps_its_symlink_alias_deduplicated` still has the setup, the replacement and the `assert_eq!(work, want, …)` I wrote, and it now passes. The only edit is mine: I changed its header comment from "FAILS" to "failed in round 1, passes now". +- Guarded `cargo test -p lucisv_server --all-targets`: green, with 2 134 in the bin target, 106 e2e, the grammar and ifdef tests, and 2 ignored OpenTitan tests. +- Guarded `cargo test -p lucisv_core --all-targets`: 129 passed. + +**b. Mutation check.** +- I put the round-1 scheme back in `state/walking.rs`: identity taken from each entry's own walk `metadata`, with `finish` filling only the missing ones. +- Under it, `walking_replace.rs::a_replacement_between_any_two_slices_lands_trunks_discovery_of_the_final_tree` fails ("replace the target after slice 36"), and so do my `qa_walking` test and my new re-check test ("chain after slice 36"). +- The test stops at its first failing case, so I did not see the other four of the five cases fail one by one. +- Restored by copying a backup back. `cmp` against the backup is identical, and SHA-1 is `5658017…eeb` before and after. Nothing else was mutated. + +**c. The single pass.** +- `Found::id` has one producer, `Walking::finish` (`walking.rs:111`). Every other `Found` is built with `id: None` and stat'd at dedup time, as on trunk. +- Overlay dedup and `rest_of_scope` run in the same call as `finish` (in `walk_a_slice` and `discover_the_rest`), so they use identities read in the same slice. Open buffers' identities are still stat'd at the overlay, back to back as on trunk. +- No identity read in an earlier slice is reused. A file replaced between trunk's second and third pass cannot give a worse answer here: those passes ran microseconds apart on trunk, and here they collapse into one pass of the same freshness. +- The loosened create/delete test (`walking.rs:311`, which lets the `ids` line come from the other tree): this is exactly the state trunk reaches when a file is deleted between its walk entry and the post-walk `stat`. It is in the work list with no identity, and `dedup_by_identity` keeps id-less files. + - As written, the assertion would also accept any "files from one tree, ids from the other" mix. With one changed file per case, the only reachable mix is the trunk one, so it forgives no real divergence today. +- `tools/gates.sh --only cross` passes. It is cargo-cached, but the current sources check. + +**d. Own attacks.** `state/tests/qa_walking.rs::qa_recheck_alias_chains_split_aliases_and_outside_targets_land_trunks_discovery` passes. It replaces the target after every slice boundary, including the last, for three shapes, and asserts the landing equals trunk's one-shot discovery of the final tree: +- an alias chain `c -> b -> a`; +- two aliases of one target in `b/` and `z/`, visited many slices apart; +- two aliases of a target outside the workspace root. + +It also fails under the mutation in b. A replacement *inside* the landing slice, between `finish` and the overlay, cannot be injected without a hook. That window is microseconds, the same as trunk's. + +**e. Timings and differential.** +- Landing hold, this tree only, N=6, load 2.5–2.9 (min / median / max): + +| tree | whole rescan | `slice_max` | `sort` | +|---|---|---|---| +| `hw` settings rescan | 602 / 619 / 640 ms | 9.9 / 10.4 / 11.4 ms | 5.6 / 6.1 / 7.1 ms | +| 4k copy | 644 / 658 / 666 ms | 7.7 / 8.3 / 9.0 ms | — | + + The 4k buffer-local probe was 4.0 / 8.6 / 15.0 ms. The dev's claims (11.5 and 8.5 ms) reproduce. +- `rescan_diff.py` on OpenTitan `hw`, against a fresh `dc54b23` scratch worktree build: 94 answers identical. Store 50 626 930 bytes, SHA-256 `f268de99…48581821`, the same from both binaries. +- `clear_store` refuses a directory holding a stray file (the file survives) and a non-directory path. It deletes a real store directory (`index-cache`, `.gitignore`, `index-cache..tmp`). +- `rescan.py` still empties `--storage` unguarded through `lspclient.py:121`. That is pre-existing and not in the brief. + +**f. Hygiene.** +- fmt, clippy (`--workspace --all-targets`) and `stamp_author.py --check` are all clean. `walking_replace.rs` has both stamps. +- Production lines: `rescan.rs` 535, `discover.rs` 515, `walking.rs` 155, `resumable.rs` 172, `walk.rs` 334. +- `scan_step` is 49 lines and `facts_of_step` 44. The only function over 80 is `begin_widen` at 125, which is pre-existing. +- `TODO.md:7479` is ticked and `:7501` left open. +- The README withdraws the identity-from-metadata claim in Assumptions, Handshakes and the round-1 table row. `meta_id` is gone from the code. + +**Nit:** the round-1 timing rows at README lines 198, 205 and 208 still show the round-1 holds (33 / 5.0 / 3.9 ms) with no inline mark. Only the fix-round paragraph says they are superseded. + +**Not verified:** the 40k tree; the other four `walking_replace` cases failing individually under the mutation; a replacement inside the landing slice. + +**Housekeeping:** the scratch worktree and trees were removed, and `git -C opentitan status --porcelain` is empty. The tree is as found apart from my QA test additions: the new re-check test and the comment edit in `state/tests/qa_walking.rs`, plus this entry. + +## Review + +**2026-11-26 — lead: accepted after one fix round and a re-QA.** + +- Delivered: §2.9 #58 (closed). The discovery walk is sliced, 512 entries at + a time, with requests answered between slices. QA's re-measurement agrees + with the dev's: longest discovery hold on OpenTitan `hw` ~10–11 ms against + 66–78 ms on trunk; a buffer-local request just after a watched create on + the 4 000-file copy ~8 ms against ~113 ms. +- §2.9 #64 is closed as **not reproducible**, not as fixed: 39 quiet-machine + runs across trunk and 0.65.11 are unimodal, and no cause was found in the + code. The rescan is 12 % faster on 40 000 files (store kept, streaming + compaction, candidates) with answers and store byte-identical to trunk on + OpenTitan `hw` (94 answers, dev and QA independently) and on 40k (dev + only, one rescan). +- Ruling on R10-QA1: the round-1 shortcut (identity off each walk entry) + indexed a replaced file twice through its alias. Identities are read in + one pass at landing again; the landing hold roughly doubled for it + (`hw` 5 → 11 ms, 40k 33 → 74 ms) and that price is accepted. QA's mutation + check shows the new tests catch the round-1 scheme. +- Accepted limits: a file deleted between being listed and being visited can + now more easily surface as a `window/showMessage` warning (R10-QA2, trunk's + race widened by the drain time); the loosened create/delete assertion is + wider than the one mixture trunk produces, harmless with one changed file + per case; `rescan.py` still empties `--storage` through `lspclient.py`. +- Filed, not fixed: #71 (`absorb`, `vlog_semantic`), #72 (memory growth + across rescans — the 40k fourth rescan hits the 8 GB guard on trunk too), + #73 (stale completion words after a mid-scan edit, already on trunk), #74 + (three walks still one-call). `lifecycle_r2.rs:240` stays at 100 ms. +- Process: the dev's first OpenTitan sweep of `localized_reindex` was a + silent skip (wrong meaning of `LUCISV_OPENTITAN`, now noted on #68); QA + caught it and both re-ran it for real. +- Not verified by anyone: Windows behaviour beyond the cross check; the 40k + tree by QA; a replacement inside the landing slice itself. + + diff --git a/docs/topo.md b/docs/topo.md index 42d205a..dbcc33c 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -43,8 +43,8 @@ lint rules (`8` error, `24` warning, `43` style); persisted facts codec TODO §55 (`state/` decomposition), call hierarchy, top-rooted paths, range/selection formatting, sticky scroll, auto-`end` and instantiation highlighting, the eight-item overnight queue (TODO §71), `instance-folding` (TODO §72), and Round 1–3 correctness, -ordering, index-lifecycle, and MCP hardening items. After Rounds 4–9, §2.9 keeps open handshakes `#58`, `#64`, `#67` (filed by Round 7) -and `#68–70` (filed by Round 8). +ordering, index-lifecycle, and MCP hardening items. After Rounds 4–10, §2.9 keeps open handshakes `#67` (filed by Round 7), +`#68–70` (filed by Round 8) and `#71–74` (filed by Round 10). See [repository-analysis.md](repository-analysis.md) for evidence and validation. Feature QA logs and TODO checkboxes remain the acceptance authority; remote artifact verification and manual editor acceptance were not repeated here. @@ -793,19 +793,23 @@ update the filing README(s) and this file. | ~~55~~ | ~~`crates/lucisv/tests/cli.rs:2149` (`a_stdin_buffer_reads_the_rule_options_too`) asserts only an empty stdout, no exit code (TODO §70)~~ — **closed 2026-11-26 by `cli-path-r5` (Round 5A):** strengthened `a_stdin_buffer_reads_the_rule_options_too` with explicit exit-code assertions (`0`/`1`) and added `run_check_stdin` config/`[lint] select/ignore` discovery tests. | linux-test-portability (Round 2) | ~~crates/lucisv (tests)~~ done | | ~~56~~ | ~~`crates/lucisv_mcp/tests/qa_m3.rs` uses `std::os::unix` with no `cfg`, so `cargo check --all-targets` for Windows fails (tests only; the `cross` gate checks binaries only) (TODO §70)~~ — **closed 2026-11-26 by `mcp-hardening-r3` (Round 3):** added portable `mode_bits` and gated Unix-only symlink/`PermissionsExt` tests in `qa_m3.rs` with `#[cfg(unix)]`; verified `cargo check --target x86_64-pc-windows-gnu --all-targets -p lucisv_mcp`. | linux-test-portability (Round 2) | ~~lucisv_mcp (tests)~~ done | | ~~57~~ | ~~**Releases are gated on macOS alone**: Linux runs the suite in `ci.yml` but the release does not wait for it, and Windows is compile-checked (`cross`), never executed (TODO §70)~~ — **closed 2026-11-26 by `ci-gates-r4` (Round 4A):** `.gitea/workflows/release.yml` splits into `preflight` (fail-fast tag/manifest/`CHANGELOG.md` check before `gates.sh`) → `linux` (`runs-on: linux-x64`: clippy + guarded `cargo test --workspace`) → `build-and-publish`. (Windows remains cross-compile checked via `cross`.) | linux-test-portability (Round 2) | ~~tools/ + CI (lead)~~ done | -| 58 | **The discovery walk at the start of every scan drains nothing** (25–80 ms on OpenTitan): what is left of the first-colour wait in workspace scope (62–86 ms late open) and the rescan hold (70–159 ms). Wanted: a resumable walk in `state/discover.rs` (it holds `&mut Workspace` throughout `begin_scan`), with its own identical-result proof (TODO §71 wave 7) | viewport-highlight (Handshake request 2) | lucisv_server (`state/discover.rs`) | +| ~~58~~ | ~~**The discovery walk at the start of every scan drains nothing** (25–80 ms on OpenTitan): what is left of the first-colour wait in workspace scope (62–86 ms late open) and the rescan hold (70–159 ms). Wanted: a resumable walk in `state/discover.rs` (it holds `&mut Workspace` throughout `begin_scan`), with its own identical-result proof (TODO §71 wave 7)~~ — **closed 2026-11-26 by `server-scaling-r10` (Round 10):** the walk is `lucisv_core::walk::ResumableWalk` driven by `state/walking.rs` in 512-entry slices with requests drained between them; identities are read in one pass at landing. Proved equal to the recursive walk and to the one-shot discovery at every slice size and under mid-walk messages and file replacement. Longest discovery hold on OpenTitan `hw` 66–78 ms → ~11 ms; 40 000 files ~386 ms → ~74 ms. Left one-call: `begin_widen`, filelist scopes, the rootless flat read (#74) | viewport-highlight (Handshake request 2) | lucisv_server (`state/discover.rs`) | | ~~59~~ | ~~**A `range` answered during a rescan always counts as a guess** (`Viewport::guessed`) and costs one refresh at settle even when nothing changed (TODO §71 wave 7)~~ — **closed 2026-11-26 by `lsp-viewport-folding-r9` (Round 9):** every range answer is remembered with its tokens (`server/viewport/painted.rs`, at most 32 ranges a buffer) and at the settle decision the same pure `tokens::range_answer` is re-run and compared, so a rescan that changed nothing draws no refresh. A range-only client past 32 ranges falls back to the old always-refresh behaviour until a whole answer or close. | viewport-highlight (QA) | ~~lucisv_server (`server/viewport.rs`)~~ done | | ~~60~~ | ~~**An edit in one file that changes how another open file colours sends no refresh** (a package type renamed) — as before this lane (TODO §71 wave 7)~~ — **closed 2026-11-26 by `lsp-viewport-folding-r9` (Round 9):** `Document::refresh_overlay` compares the old and new overlay on the projection colouring reads (`tokens::overlays_colour_alike`) and marks the buffer; one `workspace/semanticTokens/refresh` is sent when a marked open buffer re-classifies differently from what its client was sent. Measured on OpenTitan with 201 buffers open: about 1.8 ms per record-moving save, 26 ms when 188 buffers recolour. | viewport-highlight | ~~lucisv_server (`server/viewport.rs`)~~ done | | ~~61~~ | ~~**Inside the startup settings wait, the client's answer to the pull is applied ahead of an older settings push held with it** (`server/startup.rs`, `take_the_answer_out_of_held`); predates fast-actions; needs a client whose push and answer disagree in one burst (TODO §71 wave 8; fast-actions QA F1)~~ — **closed 2026-11-26 by `server-ordering-r1` (Round 1):** `take_the_answer_out_of_held` drains older `DidChangeConfiguration` pushes preceding the plucked pull answer while keeping newer pushes. | fast-actions (QA) | ~~lucisv_server (`server/startup.rs`)~~ done | | ~~62~~ | ~~**`tests/fast_actions_bursts.rs`'s oracle accepts an answer the reference gives after any later message of the round**: 2–9 % of injected stale answers pass when a later message restores the state; every mutation is still caught and the directed tests lack the weakness (TODO §71 wave 8; fast-actions QA F4)~~ — **closed 2026-11-26 by `server-ordering-r1` (Round 1):** `ahead::take_ahead_applied` records exact `applied_changes` and the oracle asserts `applied >= required` and `e == reference_at[applied]`. | fast-actions (QA) | ~~lucisv_server (tests)~~ done | | ~~63~~ | ~~**Whether a large open buffer is in the index depends on when it was opened, saved or scanned** — a fast-path buffer contributes nothing when open at scan or save time but keeps its disk record when opened after the scan; 77–98 answers differ between a settled session and a fresh server on OpenTitan. Predates fast-actions; wanted: always keep, or always drop, the disk record of a fast-path buffer at open, save, flip and scan alike (TODO §71 wave 8; fast-actions QA S2, Handshake request 8)~~ — **closed 2026-11-26 by `index-lifecycle-r2` (Round 2, owner decision 2):** standardized on always keeping the disk index record (subject to `maxFileSize`) across open, close, save, widen, scan, and threshold flips. | fast-actions (QA) | ~~lucisv_server (`state/`, `server/large_file.rs`)~~ done | -| 64 | **The 40 000-file rescan after a delete takes either 12.3 s or 14.5–15.5 s**, on 0.65.10 and 0.65.11 alike; cause not found (TODO §71 wave 8) | fast-actions | undiagnosed (lucisv_server scan) | +| ~~64~~ | ~~**The 40 000-file rescan after a delete takes either 12.3 s or 14.5–15.5 s**, on 0.65.10 and 0.65.11 alike; cause not found (TODO §71 wave 8)~~ — **closed 2026-11-26 by `server-scaling-r10` (Round 10):** **not reproducible** — 24 trunk runs and 15 runs of 0.65.11 on a quiet machine are unimodal (7.4–7.8 s, max/min ≤ 1.05), and forced CPU contention raises the time without splitting it; the old figures were taken on a machine shared with other lanes' builds. No cause in the code was found, so none was fixed. The round did cut the rescan itself: store kept across rescans, streaming compaction, cheaper candidates — 7.57 → 6.65 s median, answers and store byte-identical to trunk. What remains is filed as #71 and #72 | fast-actions | undiagnosed (lucisv_server scan) | | ~~65~~ | ~~**`ci.yml` runs `cargo test --workspace` bare in both jobs**, not through `tools/guard.sh` as CLAUDE.md's runaway guard asks of every `cargo test`; predates 0.65.9 for the macOS job, the Linux runner is resource-capped. Recorded, not judged (topo refresh 2026-11-19)~~ — **closed 2026-11-26 by `ci-gates-r4` (Round 4A):** `tools/guard.sh` uses POSIX `ps -Ao pid=,ppid=`, validates flags, closes fd 3, and wraps `cargo test --workspace` in both `checks` (`-m 8 -t 1800`) and `linux` (`-m 6 -t 1800`) jobs of `.gitea/workflows/ci.yml` (plus `linux` in `release.yml`). | topo refresh (draft discrepancy 10) | ~~CI (lead)~~ done | | ~~66~~ | ~~**The `cross` gate step reports `SKIPPED (no toolchain)` rather than failing** when `~/.rustup/toolchains/stable-aarch64-apple-darwin` is absent, so a green `gates.sh` on another machine does not prove the cross build (topo refresh 2026-11-19)~~ — **closed 2026-11-26 by `ci-gates-r4` (Round 4A):** `tools/gates.sh` fails missing cross toolchain by default (opt-in `--allow-skip-cross` only) and adds the `stamp` step (`python3 tools/stamp_author.py --check`) matching `ci.yml`. | topo refresh (draft discrepancy 11) | ~~tools/ (`gates.sh`, lead)~~ done | | 67 | **`lucisv_core::config::parse_array` splits `lucisv.toml` arrays at every comma, quoted or not**, so a glob such as `"**/{a,b}/*"` in `exclude` or a waiver path with a comma is cut in two. Rule options were given a quote-aware splitter in Round 7 (`vlog_linter/src/options/list.rs`); the config arrays want the same treatment and a regression. | linter-hardening-r7 (dev) | lucisv_core | -| 68 | **Three ignored OpenTitan tests fail on trunk when actually run** (they skip silently in 0.00 s unless `LUCISV_OPENTITAN` is set, so nobody saw): `vlog_refactor --test opentitan_top_rooted` (assertion at :110 and a stack overflow in `the_whole_tree_…`), `lucisv_mcp --test opentitan` (2 failures: earlgrey instance set at :209, navigation at :122), `vlog_refactor --test rename_bind -- --ignored` with `LUCISV_BIND_ROOT` (stack overflow). Identical before and after Round 8. Wanted: a diagnosis of each (the two overflows first), and a skip that says it skipped. | semantic-refactor-r8 (QA) | vlog_refactor / lucisv_mcp | +| 68 | **Three ignored OpenTitan tests fail on trunk when actually run** (they skip silently in 0.00 s unless `LUCISV_OPENTITAN` is set, so nobody saw): `vlog_refactor --test opentitan_top_rooted` (assertion at :110 and a stack overflow in `the_whole_tree_…`), `lucisv_mcp --test opentitan` (2 failures: earlgrey instance set at :209, navigation at :122), `vlog_refactor --test rename_bind -- --ignored` with `LUCISV_BIND_ROOT` (stack overflow). Identical before and after Round 8. Wanted: a diagnosis of each (the two overflows first), and a skip that says it skipped. Also (Round 10 QA): `LUCISV_OPENTITAN` means the repo root to `opentitan_references` and the `hw` directory to `localized_reindex`, so one setting silently skips the other | semantic-refactor-r8 (QA) | vlog_refactor / lucisv_mcp | | 69 | **An instance inside an interface's generate block is on the connection surface and listed as a workspace symbol; the interface's direct instances are neither** (`interface bus_if; leaf u_direct(); if (1) begin : g leaf u_inblk(); end endinterface`). Four entries on OpenTitan `hw/ip`. Wanted: one rule for both. | semantic-refactor-r8 (QA re-check) | vlog_semantic | | 70 | **`\\foo ` and `foo` are never treated as one identifier across files**: a rename of `foo` silently misses `u.\\foo ` written in another file, with no warning (IEEE 1800 §5.6.1 makes them the same name). Round 8 put escaped spellings in `FileFacts::words` as written; the pre-filter and the resolver still compare spellings. Same on trunk before Round 8. | semantic-refactor-r8 (QA) | vlog_semantic / vlog_refactor | +| 71 | **`absorb` is about a third of a whole rescan** (2.0–2.3 s of 6.65 s on 40 000 files) and was not touched by Round 10 because it is in `vlog_semantic`. Wanted: a measured speed-up with identical index output; then revisit the 100 ms debug ceiling at `lifecycle_r2.rs:240` | server-scaling-r10 (Handshake request) | vlog_semantic | +| 72 | **Resident memory grows across whole rescans**: on 40 000 files 3.9 → 6.8 → 6.9 → 7.5 GB, so the fourth rescan of one session is killed by the 8 GB guard (trunk and 0.65.11 alike); on a 4 000-file copy trunk grows ~50 MB per rescan, Round 10's tree levels off at 2–5 MB. Not diagnosed | server-scaling-r10 (F2) | undiagnosed (lucisv_server scan) | +| 73 | **An edit to a buffer the running scan already took leaves the completion word table with the old words** until the next scan; the index itself is right. Reproduces on `dc54b23` at a between-files drain, so it predates the sliced walk | server-scaling-r10 (F1) | lucisv_server (`candidates.rs`, scan) | +| 74 | **`begin_widen`, filelist scopes and the rootless flat read still walk in one call** (and `begin_widen` is 125 lines); only the whole-scope and rest-of-scope walks are sliced | server-scaling-r10 (F3) | lucisv_server (`state/`) | --- diff --git a/tools/perf/bigtree.py b/tools/perf/bigtree.py new file mode 100644 index 0000000..2e308c2 --- /dev/null +++ b/tools/perf/bigtree.py @@ -0,0 +1,102 @@ +# Author: Guoliang Chen, a Senior Digital Design Engineer + +"""Build the replicated OpenTitan tree the 40 000-file rescan is measured on. + +`docs/features/fast-actions/README.md` measured its 20k / 40k rows on copies +of OpenTitan `hw/` replicated 5 / 10 times under `c0/ ... c9/`, every module, +package, interface, program and class name declared anywhere prefixed `cK_` +in copy K, so that the copies do not collapse into one set of duplicate +definitions. That generator (`gen.py`) lived in a scratch directory and is +gone; this is its replacement, kept here so the tree can be rebuilt. + + python3 tools/perf/bigtree.py --opentitan ~/repo/opentitan --copies 10 \ + --out "$SCRATCH/ot10" + +Python 3 standard library only. **The corpus is only read**: every byte goes +to `--out`, which must not be inside the corpus or the repository, and which +is refused when it already exists (delete it yourself, so a typo cannot +delete anything else). Files whose text is not UTF-8 are copied as bytes. +""" + +import argparse +import os +import re +import sys + +EXTENSIONS = (".sv", ".v", ".svh", ".vh") +DECL = re.compile( + r"^\s*(?:virtual\s+)?(?:module|macromodule|package|interface|program|class)" + r"\s+(?:automatic\s+|static\s+)?([A-Za-z_][A-Za-z0-9_$]*)", + re.MULTILINE, +) +IDENT = re.compile(r"\b[A-Za-z_][A-Za-z0-9_]*\b") + + +def sources(hw): + """Every source file under `hw`, as paths relative to it, sorted.""" + found = [] + for base, dirs, files in os.walk(hw): + dirs.sort() + for name in sorted(files): + if name.endswith(EXTENSIONS): + found.append(os.path.relpath(os.path.join(base, name), hw)) + return found + + +def declared_names(hw, files): + """Every unit name any file declares — what each copy prefixes.""" + names = set() + for rel in files: + with open(os.path.join(hw, rel), "rb") as handle: + text = handle.read().decode("utf-8", "replace") + names.update(DECL.findall(text)) + return names + + +def renamed(text, names, prefix): + """`text` with every whole-word use of a declared name prefixed.""" + return IDENT.sub(lambda m: prefix + m.group(0) if m.group(0) in names else m.group(0), text) + + +def write_copy(hw, files, names, out, k): + prefix = "c%d_" % k + for rel in files: + target = os.path.join(out, "c%d" % k, rel) + os.makedirs(os.path.dirname(target), exist_ok=True) + with open(os.path.join(hw, rel), "rb") as handle: + raw = handle.read() + try: + data = renamed(raw.decode("utf-8"), names, prefix).encode("utf-8") + except UnicodeDecodeError: + data = raw + with open(target, "wb") as handle: + handle.write(data) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--opentitan", required=True) + parser.add_argument("--copies", type=int, default=10) + parser.add_argument("--out", required=True) + args = parser.parse_args() + hw = os.path.realpath(os.path.join(args.opentitan, "hw")) + out = os.path.realpath(args.out) + here = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..")) + for forbidden in (os.path.realpath(args.opentitan), here): + if out == forbidden or out.startswith(forbidden + os.sep): + sys.exit("bigtree: --out must be outside %s" % forbidden) + if os.path.exists(out): + sys.exit("bigtree: %s exists; remove it first" % out) + files = sources(hw) + names = declared_names(hw, files) + print("bigtree: %d files, %d declared names, %d copies" % (len(files), len(names), args.copies)) + for k in range(args.copies): + write_copy(hw, files, names, out, k) + print("bigtree: copy %d written" % k, flush=True) + print("bigtree: %d files under %s" % (len(files) * args.copies, out)) + + +if __name__ == "__main__": + main() + +# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/tools/perf/rescan.py b/tools/perf/rescan.py new file mode 100644 index 0000000..49dd78f --- /dev/null +++ b/tools/perf/rescan.py @@ -0,0 +1,257 @@ +# Author: Guoliang Chen, a Senior Digital Design Engineer + +"""The rescan after a delete, on a big tree, with the server's own breakdown. + +TODO §71 wave 8 left open: *the 40 000-file rescan after a delete takes either +12.3 s or 14.5–15.5 s*. The harness that saw it (`fast-actions`' `ab41.py`, +`b3.py`) lived in a scratch directory and is gone. This is the same loop, +kept, with every rescan's `--verbose` stage, count and memory lines parsed +into the row, so a slow rescan can be told from a fast one stage by stage: + + tools/guard.sh -m 8 -t 1200 -- python3 tools/perf/rescan.py \ + --server target/release/lucisv-server --tree "$SCRATCH/ot10" \ + --storage "$SCRATCH/store" --out "$SCRATCH/rescan.jsonl" \ + --label after --mode busy --runs 5 + +One session per invocation: initialize at workspace scope, open +`c0/ip/aes/rtl/aes_cipher_core.sv`, wait for the startup scan, then `--runs` +times: delete the previous probe file (a `didChangeWatchedFiles` *Deleted*, +which the server answers with a one-file update), create a new one (*Created*, +which owes a whole rescan) and wait for that rescan to finish. `--mode idle` +waits for the delete's update before sending the create; `--mode busy` sends +the create 50 ms after the delete, while the server is still inside it — +the two rows of the fast-actions table. + +The probe files are written into `--tree`, which must be a scratch copy +(`bigtree.py`), never the corpus. `--trigger settings` writes nothing at all +— each rescan is a settings push alternating a no-op exclude — so it is the +form to run on the read-only corpus itself (`--open` names the buffer, +relative to `--tree`). `--probe` sends a `documentSymbol` on the open buffer +5 ms after each trigger and records how long it waited: what a rescan holds +a buffer-local request for (topo §2.9-58). Python 3 standard library only. +""" + +import argparse +import json +import os +import re +import resource +import subprocess +import sys +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from lspclient import Session, uri # noqa: E402 + +OPEN = os.path.join("c0", "ip", "aes", "rtl", "aes_cipher_core.sv") +STAGE = re.compile(r"timing: scan (\d+) (stages|counts|memory) \((\w+)[^)]*\): (.*)") +PAIR = re.compile(r"(\w+)=([0-9.]+)") +FINISHED = "timing: scan finished:" + + +class Rss: + """The server's resident set, sampled every 100 ms by `ps` on a thread. + + The guard sums the whole tree and kills it at 8 GB; this says how close + each rescan came, and when in the rescan the peak was. + """ + + def __init__(self, pid): + self.pid = pid + self.samples = [] # (perf_counter, kib) + self.stopped = False + self.thread = threading.Thread(target=self.run, daemon=True) + self.thread.start() + + def run(self): + while not self.stopped: + out = subprocess.run(["ps", "-o", "rss=", "-p", str(self.pid)], + capture_output=True, text=True).stdout.strip() + if out: + self.samples.append((time.perf_counter(), int(out))) + time.sleep(0.1) + + def between(self, start, end): + """(peak KiB, KiB at `start`, KiB at `end`) over one window.""" + inside = [kib for at, kib in self.samples if start <= at <= end] + before = [kib for at, kib in self.samples if at <= start] + after = [kib for at, kib in self.samples if at >= end] + first = before[-1] if before else (inside[0] if inside else 0) + last = after[0] if after else (inside[-1] if inside else 0) + return (max(inside) if inside else 0), first, last + + +def watched(s, path, kind): + """One `didChangeWatchedFiles` naming `path` (1 created, 3 deleted).""" + s.notify("workspace/didChangeWatchedFiles", {"changes": [{"uri": uri(path), "type": kind}]}) + + +def wait_log(s, start, predicate, timeout=600.0): + """Block until a log line from index `start` on satisfies `predicate`.""" + deadline = time.time() + timeout + while time.time() < deadline: + s.drain() + for at in range(start, len(s.log_messages)): + if predicate(s.log_messages[at]): + return at, time.perf_counter() + time.sleep(0.002) + raise TimeoutError("no matching log line") + + +def finished(s, start): + """Wait for the next whole scan to finish and for its three trace lines. + + The `stages`/`counts`/`memory` lines follow `scan finished`, and taking + the window before they land would credit this rescan with the previous + one's breakdown. Returns (index of the finished line, its instant, the + lines of this rescan). + """ + at, done = wait_log(s, start, lambda t: t.startswith(FINISHED)) + last, _ = wait_log(s, at, lambda t: "memory (whole" in t) + return at, done, s.log_messages[start:last + 1] + + +def trace_of(lines): + """The stage/count/memory fields of the last whole scan in `lines`.""" + row = {} + for text in lines: + found = STAGE.search(text) + if not found or found.group(3) != "whole": + continue + for key, value in PAIR.findall(found.group(4)): + row["%s_%s" % (found.group(2), key)] = float(value) + return row + + +def probe_symbols(s, path): + """A `documentSymbol` on `path` sent 5 ms from now; returns its id.""" + time.sleep(0.005) + return s.send("textDocument/documentSymbol", {"textDocument": {"uri": uri(path)}}) + + +def probe_wait(s, rid): + """How long the probe waited: sent to the instant the reader thread + parsed its answer — not to whenever this script got round to asking.""" + sent = s.pending[rid][1] + deadline = time.time() + 600 + with s._cond: + while rid not in s._arrived and time.time() < deadline: + s._cond.wait(0.05) + arrived = s._arrived.get(rid, time.perf_counter()) + s.await_id(rid) + return (arrived - sent) * 1000.0 + + +def settings_rescan(s, k, rss, opened, probe): + """A settings push that owes a whole rescan and changes nothing else.""" + s.drain() + start = len(s.log_messages) + s.scope = {"index": {"scope": "workspace"}, "exclude": ["zz_no_such_%d" % (k % 2)]} + sent = time.perf_counter() + s.notify("workspace/didChangeConfiguration", {"settings": {"lucisv": s.scope}}) + rid = probe_symbols(s, opened) if probe else None + at, done, lines = finished(s, start) + row = {"k": k, "wall_ms": (done - sent) * 1000.0, "mode": "settings"} + if rid is not None: + row["probe_ms"] = probe_wait(s, rid) + s.drain() + time.sleep(0.25) + row["rss_peak_kib"], row["rss_before_kib"], row["rss_after_kib"] = rss.between(sent, done) + server_ms = re.search(r"in ([0-9.]+) ?(ms|s)\b", s.log_messages[at]) + if server_ms: + scale = 1000.0 if server_ms.group(2) == "s" else 1.0 + row["server_ms"] = float(server_ms.group(1)) * scale + row.update(trace_of(lines)) + return row + + +def one_rescan(s, tree, k, mode, rss, gap, opened, asked): + """Delete probe k-1 (if any), create probe k, time the rescan it owes.""" + probe = os.path.join(tree, "c0", "zz_probe_%d.sv" % k) + previous = os.path.join(tree, "c0", "zz_probe_%d.sv" % (k - 1)) + s.drain() + start = len(s.log_messages) + deleted_at = None + if os.path.exists(previous): + os.remove(previous) + deleted_at = time.perf_counter() + watched(s, previous, 3) + if mode == "idle": + wait_log(s, start, lambda t: "reindex_one(" in t or t.startswith(FINISHED)) + elif gap > 0: + time.sleep(gap) + with open(probe, "w", encoding="utf-8") as handle: + handle.write("module zz_probe_%d;\nendmodule\n" % k) + sent = time.perf_counter() + watched(s, probe, 1) + rid = probe_symbols(s, opened) if asked else None + at, done, lines = finished(s, start) + server_ms = re.search(r"in ([0-9.]+) ?(ms|s)\b", s.log_messages[at]) + row = {"k": k, "wall_ms": (done - sent) * 1000.0, "mode": mode, "gap": gap} + if rid is not None: + row["probe_ms"] = probe_wait(s, rid) + time.sleep(0.25) + row["rss_peak_kib"], row["rss_before_kib"], row["rss_after_kib"] = rss.between(sent, done) + if deleted_at is not None: + row["since_delete_ms"] = (done - deleted_at) * 1000.0 + if server_ms: + scale = 1000.0 if server_ms.group(2) == "s" else 1.0 + row["server_ms"] = float(server_ms.group(1)) * scale + row.update(trace_of(lines)) + row["reindex_one"] = [t for t in lines if "reindex_one(" in t] + return row + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--server", required=True) + parser.add_argument("--tree", required=True) + parser.add_argument("--storage", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--label", required=True) + parser.add_argument("--mode", choices=("idle", "busy"), default="busy") + parser.add_argument("--runs", type=int, default=5) + parser.add_argument("--first", type=int, default=0, help="first probe number") + parser.add_argument("--gap", type=float, default=0.05, + help="busy mode: seconds between the delete and the create") + parser.add_argument("--trigger", choices=("create", "settings"), default="create") + parser.add_argument("--open", default=OPEN, help="the buffer to open, under --tree") + parser.add_argument("--probe", action="store_true", + help="time a documentSymbol sent 5 ms after each trigger") + args = parser.parse_args() + tree = os.path.abspath(args.tree) + with Session(args.server, tree, args.storage, scope={"index": {"scope": "workspace"}}, + verbose=True) as s: + rss = Rss(s.proc.pid) + s.initialize() + opened = os.path.join(tree, args.open) + s.did_open(opened) + wait_log(s, 0, lambda t: t.startswith(FINISHED)) + s.wait_quiet(1.0) + for k in range(args.first, args.first + args.runs): + if args.trigger == "settings": + row = settings_rescan(s, k, rss, opened, args.probe) + else: + row = one_rescan(s, tree, k, args.mode, rss, args.gap, opened, args.probe) + row.update({"label": args.label, "pid_load": os.getloadavg()[0]}) + with open(args.out, "a", encoding="utf-8") as handle: + handle.write(json.dumps(row) + "\n") + print("%s %s k=%d server=%.0f wall=%.0f probe=%.1f rss %.0f -> peak %.0f -> %.0f MB" % ( + args.label, row["mode"], k, row.get("server_ms", -1), row["wall_ms"], + row.get("probe_ms", -1), + row["rss_before_kib"] / 1024, row["rss_peak_kib"] / 1024, + row["rss_after_kib"] / 1024), flush=True) + rss.stopped = True + last = os.path.join(tree, "c0", "zz_probe_%d.sv" % (args.first + args.runs - 1)) + if args.trigger == "create" and os.path.exists(last): + os.remove(last) + usage = resource.getrusage(resource.RUSAGE_CHILDREN) + print("children maxrss %.0f MB" % (usage.ru_maxrss / 1048576.0)) + + +if __name__ == "__main__": + main() + +# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com diff --git a/tools/perf/rescan_diff.py b/tools/perf/rescan_diff.py new file mode 100644 index 0000000..b7fef76 --- /dev/null +++ b/tools/perf/rescan_diff.py @@ -0,0 +1,137 @@ +# Author: Guoliang Chen, a Senior Digital Design Engineer + +"""What a session answers before and after its rescans, as hashes to diff +between two `lucisv-server` binaries — the differential behind +`docs/features/server-scaling-r10/README.md`. + + tools/guard.sh -m 8 -t 1200 -- python3 tools/perf/rescan_diff.py \ + --server target/release/lucisv-server --tree ~/repo/opentitan/hw \ + --open ip/aes/rtl/aes_cipher_core.sv --storage "$SCRATCH/diff-new" \ + --rescans 2 > "$SCRATCH/new.txt" + +One cold session at workspace scope (`--storage` is emptied first): the +startup scan, then `--rescans` whole rescans, each a settings push alternating +an exclude that names nothing — so every rescan reads the same tree and writes +nothing into it, and the corpus stays read-only. After the startup scan and +after every rescan it prints one line per answer — workspace symbols, the +module hierarchy, the open buffer's outline and every definition, hover and +reference answer at a few cursors — with the SHA-256 of the answer's JSON; +at the end the SHA-256 and size of the index store file. `--storage` is +emptied only when it is absent, empty or a lucisv store; anything else is +refused. Two binaries that +agree print the same lines. Python 3 standard library only. +""" + +import argparse +import hashlib +import json +import os +import re +import shutil +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from lspclient import Session, uri # noqa: E402 +from rescan import FINISHED, finished, wait_log # noqa: E402 + +QUERIES = ["aes", "prim_", "tl_", "u", "reg"] + + +def digest(value): + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()[:16] + + +def cursors(path, count=8): + """Up to `count` (line, character) positions on names worth asking about + in `path`: package references, instance names, ports and signals with an + underscore, the first of each, never inside a comment.""" + wanted = re.compile(r"\b(?:\w+_pkg|u_\w+|\w+_[io]|\w+_q|\w+_d)\b") + found, seen = [], set() + with open(path, encoding="utf-8", errors="replace") as handle: + for line_no, line in enumerate(handle): + code = line.split("//", 1)[0] + for match in wanted.finditer(code): + if match.group(0) in seen: + continue + seen.add(match.group(0)) + found.append((line_no, match.start() + 1)) + if len(found) >= count: + return found + return found + + +def answers(s, opened, step): + """Print one line per answer, `step` naming when it was asked.""" + asked = [("workspace/symbol", {"query": q}) for q in QUERIES] + asked.append(("lucisv/moduleHierarchy", {})) + asked.append(("textDocument/documentSymbol", {"textDocument": {"uri": uri(opened)}})) + for line, character in cursors(opened): + for method in ("textDocument/definition", "textDocument/hover", + "textDocument/references"): + params = {"textDocument": {"uri": uri(opened)}, + "position": {"line": line, "character": character}, + "context": {"includeDeclaration": True}} + asked.append((method, params)) + for method, params in asked: + _, message = s.request(method, params) + result = message.get("result", message.get("error")) + where = params.get("query", params.get("position", "")) + print("%s %s %s %s" % (step, method, json.dumps(where, sort_keys=True), digest(result))) + + +def clear_store(path): + """Empty `path` for a cold session — only when it is absent, empty, or + holds nothing but what a lucisv index store writes (`index-cache`, its + `.gitignore`, a leftover `index-cache..tmp`). Anything else is a + mistyped path and is refused rather than deleted.""" + if not os.path.exists(path): + return + if not os.path.isdir(path): + sys.exit("rescan_diff: --storage %s is not a directory; refusing to delete it" % path) + names = os.listdir(path) + store = lambda n: n in ("index-cache", ".gitignore") or ( + n.startswith("index-cache.") and n.endswith(".tmp")) + strangers = [n for n in names if not store(n)] + if strangers: + sys.exit("rescan_diff: --storage %s holds %s, not a lucisv store; refusing to delete it" + % (path, ", ".join(sorted(strangers)[:5]))) + shutil.rmtree(path) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--server", required=True) + parser.add_argument("--tree", required=True) + parser.add_argument("--open", required=True) + parser.add_argument("--storage", required=True) + parser.add_argument("--rescans", type=int, default=2) + args = parser.parse_args() + tree = os.path.abspath(args.tree) + clear_store(args.storage) + opened = os.path.join(tree, args.open) + with Session(args.server, tree, args.storage, scope={"index": {"scope": "workspace"}}, + verbose=True) as s: + s.initialize() + s.did_open(opened) + wait_log(s, 0, lambda t: t.startswith(FINISHED)) + s.wait_quiet(1.0) + answers(s, opened, "startup") + for k in range(args.rescans): + s.drain() + start = len(s.log_messages) + s.scope = {"index": {"scope": "workspace"}, "exclude": ["zz_no_such_%d" % (k % 2)]} + s.notify("workspace/didChangeConfiguration", {"settings": {"lucisv": s.scope}}) + finished(s, start) + s.wait_quiet(0.5) + answers(s, opened, "rescan%d" % k) + store = os.path.join(args.storage, "index-cache") + with open(store, "rb") as handle: + data = handle.read() + print("store %d %s" % (len(data), hashlib.sha256(data).hexdigest())) + + +if __name__ == "__main__": + main() + +# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com