diff --git a/TODO.md b/TODO.md index b5a85c0..b520573 100644 --- a/TODO.md +++ b/TODO.md @@ -4706,6 +4706,14 @@ in 0.49.0. Take 4's findings are in the loop-3 list above. ASTs was refused as a memory trade (1 805 trees against a 200 MiB peak); and a test pinning `harvest_one`'s lex-only path when neither census half is wanted (needs a `Job` constructor for tests). +- **perf take 5 P4b (§60.4) filed:** the first useful answer after a + staged startup is ~250 ms cold / ~275 warm (correct in every session) + against the old race's 84 / 208 — the gap is the workspace walk in + front of the open buffer's folder (`discovery` 158 ms warm: the walk + plus one `fs::metadata` per file, which `lucisv_core::walk::collect_files` + already stat'd and could hand on), then `cache_open` 89 ms; warm settle + ~1.04–1.10 s against the plan's < 1 s, the rest being the store open + the refused reuse would remove. Sections after §46 are planned when reached. ## 45. Small items, round 4 (planned 2026-09-05) — topo §2.9-29, 30, 17, 22 @@ -6026,21 +6034,138 @@ semantic build/facts owners. Serialized after 60.1–60.3. compaction); plus: why the configured rescan does not interleave navigation (fix if routing, file if not), and the trace helpers moved out of `state.rs` -- [ ] P4b if ruled: warm < 1 s / cold < 2.3 s / idle RSS −15% as +- [x] P4b if ruled: warm < 1 s / cold < 2.3 s / idle RSS −15% as investigation goals; interrupted-store recovery, coherent index/candidate/include prefix, content-based freshness, the 16 MiB parser stack on any new thread, §46's open path — all preserved and pinned + (2026-09-08; `docs/features/perf5-p4/README.md` §P4b, experiment + `P4b-2026-09-08`). **(a) + (b1) shipped, (b2) refused, the + interleaving question answered and filed.** Measured against a + same-window control built from HEAD: **warm settle 1 326.85 → + 1 137.66 ms, −14.3 %**; cold −1.1 % (unchanged, as predicted); + **warm idle RSS −15.3 %**, the one goal §P4a had ruled out — it is + the two 44.3 MiB render buffers, not the encoded-facts retention. + The store is left byte- **and mtime-**identical across two warm + sessions where HEAD rewrote the same 46 486 433 bytes each time. + `mismatched_answers` 0, the scope ladder answers identically in all + eight cells, §46's `didOpen` path −3.3 %. **Warm < 1 s missed** and + needs the refused (b2): `cache_open` is still paid twice, 181.7 ms. + **One deviation reported**: `IndexCache::record` now skips a record + the store already holds, without which (a) fires in no session that + has a buffer open. **One regression named**: the warm first useful + answer is bimodal, 117 ms or the whole configured rescan, because + removing the empty scan's 181 ms removed the head start the + `didOpen` used to win its race with the configuration answer — the + `must_wait` order contract, filed for the lead with the narrow fix. + **Closed 2026-09-08 by the P4b2 line below**, and not by that narrow + fix: the lead ruled the plan's own sentence instead +- [x] P4b2 (the lead's ruling on that regression, 2026-09-08): **stage the + initial scan until configuration arrives**, with a bounded fallback + for clients that never answer, rootless and scope precedence intact + (`docs/features/perf5-p4/README.md` §P4b2, experiment + `P4b-staged-2026-09-08`; new `server/startup.rs`). + `Server::started` sends `workspace/configuration` first and waits up + to `CONFIGURATION_WAIT` (2 s) on `recv_timeout` — no poll, no + busy-wait — then runs **one** startup scan at the answered scope. + The empty default-scope scan and the widen behind it are gone; a + `didOpen` in the window is folded into that scan (its file first in + the work list) and a request is held and answered *inside* it. + Paired against the previous P4b release: **warm settled 1 181.34 → + 1 097.98 ms, −7.1 %**, and on the shipped binary re-run **1 190.48 → + 1 037.31 ms, −12.9 %** (the two runs bracket the ≤ ~1.06 s target); + cold −4.0 % / −2.5 %; `scopeDepth 0` −89.2 % cold / + −72.6 % warm; 1/10/100 open buffers −28.4 / −26.8 / −21.0 %; warm + `cache_open` **183.70 → 91.91 ms** — the refused (b2)'s saving, + arriving without store reuse; warm idle RSS −5.8 %; store byte- and + mtime-identical; all 24 scope answers identical; `didOpen` pinmux + −6.3 %; `mismatched_answers` 0. **The `scanserve` "queued behind the + configured rescan" mode is gone for the startup case.** **One + regression, filed:** the first useful answer is now unimodal but + **empty** — 293–411 ms with result count 0, because `begin_scan`'s + discovery (292.74 ms warm) is the floor and the first drain + publishes the open buffer alone; the fix is an `open_first` ordering + change in `state.rs`, which this lane holds calls-only (Handshake + 11). **One defect found by measuring and fixed**: a settings answer + stranded in `held` behind a request cost the whole bound +- [x] P4b3 (P4b2's empty first useful answer, closed — Handshake 11 + granted, 2026-09-08): **the read is lazy and the order is the + user's** (`docs/features/perf5-p4/README.md` §P4b3, experiment + `P4b-lazy-2026-09-08`; new `crate::scan_order`, `state.rs` split + into `state/mod.rs` + `state/scan.rs` as a pure move). + `collect_sources` resolves the scope and reads **nothing** off + disk; `scan_step` reads a file's text when it indexes it, takes the + hash, the parse, the words and the `` `include`` lines out of that + one read, and drops it — proved read-once by a thread-local counter + in the shape of `vlog_parser::stats::parses`. The work list leads + with the open buffers and the folders they raise to, and a held + request — or one behind a mid-scan `didOpen` — waits for that + folder (`Server::head_owed`, a fifth `must_wait` clause) before it + is answered. **The first useful answer is result count 1 in twelve + sessions of twelve**, where P4b2 was 0 in twelve of twelve, and + faster: cold 287.40 → **249.00 ms (−13.4 %)**, warm 332.68 → + **277.37 (−16.6 %)**. `work_kib` **34 973 → 0–16**; idle RSS + **−7.0 % cold / −7.2 % warm**, peak still equal to idle; + `discovery` **227 → 158 ms** warm with a new `read` stage at 86; + `includes` **42 → 8.6 ms**. Settled unchanged within noise + (−5.2 % / −3.0 % in `scan`, +0.9 % / +1.9 % in `scanprofile`, both + quoted); all 24 scope answers identical; the persistent store + **byte-identical** from both binaries; `mismatched_answers` 0; + §46's `didOpen` untouched. **The latency target is missed and now + explained: the first useful answer is walk-bound** — `discovery` is + 158 ms of pure scope walk, 58 % of the warm answer, and + `cache_open` is another 89 (the refused (b2)). The §P0 REF's + 84/208 ms was answered off a 124-file *folder* scan that never + walked the workspace. **One defect found by measuring**: the + ordering alone left five sessions of six empty, because the client + answers the settings pull from its own reader thread and beats the + editor's `didOpen` — hence the drain rule +- [x] QA (P4b2): re-take the paired numbers; attack the bound (an answer + at the deadline, twice, an error, a `null`), the window + (`shutdown`, `didClose`, a folder change, a filelist push, a burst + putting a request in front of the answer), + `take_the_answer_out_of_held`'s reordering and the rootless path; + rule on the empty first useful answer — **answered by P4b3 above** +- [x] QA (P4b3): re-take the paired numbers, in particular the + twelve-of-twelve result count and the walk-bound floor; attack the + lazy read (a file deleted, truncated or replaced between the walk + and its own step — the `unread` path, the skip count, and whether + the file really leaves the index), the read-once counter (does any + path read a file twice), the ordering (rootless, `untitled:`, a + filelist scope, a capped buffer, 100 buffers, and + `worth_waiting`'s edges), the drain rule (a `didClose` mid-scan, a + `shutdown` behind a `didOpen`, two `didOpen`s in one burst, a + cancel behind a held request, and whether `head_owed` can be left + true with no scan running), and the include graph and completion + tables against a text-built pair on a tree with duplicate + spellings and `+incdir+`s +- [ ] the walk, filed by P4b3 for the next lane: `discovery` is 158 ms of + scope walk plus one `fs::metadata` per file for the size cap, and + it is the floor under every first useful answer. Two things to + measure before building anything — the cap taking its size from the + walk's own metadata (`lucisv_core::walk::collect_files` is not + P4b3's file: a handshake request) and handing the first folder to + `scan_step` before the walk has finished the workspace - [x] QA (P4a only, 2026-09-08: gates green, 4272/4272, no behaviour change verified by hunk review and by running both binaries — 44/44 identical result_counts and identical scan file-counts; instrument cost and every table number reproduced independently; docs/features/perf5-p4/README.md QA log. P4b still needs the lead's ruling and is unimplemented) +- [x] QA (P4b): re-take the paired numbers on the same binary against the + same-window HEAD control; re-attack the six clauses of the + compaction skip and the deferred open (the dev's own attacks are in + the work log); rule on the one deviation + (`IndexCache::record`'s early return) and on whether the bimodal + warm first answer is acceptable while the interleaving finding is + open ### 60.5 Closing -- [ ] P5 stays deferred unless a stage's measurement reopens it (lead) +- [x] P5 stays deferred unless a stage's measurement reopens it (lead) + — 2026-09-08: nothing reopened it; the first-after-edit row after + P1 is inside the frame, and no user command still blocks navigation + for a whole scan on the startup path - [ ] `docs/perf/README.md` entry with the accepted numbers; topo edges/handshakes for every contract amended; the plan's status line updated; a release cut from the clean tree with its assets diff --git a/crates/lucisv_server/src/candidates.rs b/crates/lucisv_server/src/candidates.rs index 8c647d4..7d2d4f0 100644 --- a/crates/lucisv_server/src/candidates.rs +++ b/crates/lucisv_server/src/candidates.rs @@ -108,23 +108,49 @@ impl Candidates { /// here, exactly as every file used to be. The two produce the same words /// because they are the same function over the same tokens /// ([`words_of_tokens`]). + /// + /// Test-only since 2026-09-08: a scan holds every file's words and no + /// file's text, so it calls [`Candidates::from_words`]. This is that call + /// with the lex in front of it, which is what a test building tables from + /// a fixture's text wants and what makes the two one function. + #[cfg(test)] pub fn build( index: &WorkspaceIndex, sources: &[(PathBuf, String)], mut known: HashMap>, ) -> Candidates { + let words = sources + .iter() + .map(|(path, text)| { + let words = known.remove(path).unwrap_or_else(|| words_in(text)); + (path.clone(), words) + }) + .collect(); + Candidates::from_words(index, words) + } + + /// [`Candidates::build`] for a caller that already holds **every** file's + /// words — the form a scan uses. + /// + /// Since 2026-09-08 a scan reads a file's text at the step that indexes it + /// and drops it again, so there is no text left to lex when the tables are + /// built at the end. There never was any lexing to do: since `FACTS_FORMAT` + /// 13 a file's identifier census is one of its facts, so a scan already has + /// the words of every file it stepped, cached or parsed, and `build`'s + /// `known` covered the whole list. This is that call without the text it + /// no longer reads (`docs/features/perf5-p4/README.md` §P4b3). + /// + /// Order-independent: the word counts are a sum and `words` is sorted at + /// the end, so a map is as good as a list here. + pub fn from_words(index: &WorkspaceIndex, words: HashMap>) -> Candidates { let mut out = Candidates::default(); out.take_index_tables(index); - for (path, text) in sources { - let words = match known.remove(path) { - Some(words) => words, - None => words_in(text), - }; + for (path, words) in words { for word in &words { *out.word_files.entry(word.clone()).or_default() += 1; } if !words.is_empty() { - out.per_file.insert(path.clone(), words); + out.per_file.insert(path, words); } } out.words = out.word_files.keys().cloned().collect(); diff --git a/crates/lucisv_server/src/includes.rs b/crates/lucisv_server/src/includes.rs index 1580ab8..87701c9 100644 --- a/crates/lucisv_server/src/includes.rs +++ b/crates/lucisv_server/src/includes.rs @@ -116,14 +116,39 @@ pub struct IncludeGraph { impl IncludeGraph { /// Scan every in-scope file for its `` `include``s and resolve them. + /// + /// Test-only since 2026-09-08: the scan that used to hold every file's + /// text no longer does, and calls [`IncludeGraph::from_includes`] with the + /// lines it read at each file's own step. This is that call with the scan + /// in front of it — which is what makes it the right thing for a test to + /// build a graph from a fixture with, and the two provably one function. + #[cfg(test)] pub fn build(sources: &[(PathBuf, String)], incdirs: Vec) -> IncludeGraph { + let scanned: Vec<(PathBuf, Vec)> = + sources.iter().map(|(path, text)| (path.clone(), scan(text))).collect(); + let borrowed: Vec<(&Path, &[Include])> = + scanned.iter().map(|(path, found)| (path.as_path(), found.as_slice())).collect(); + IncludeGraph::from_includes(&borrowed, incdirs) + } + + /// [`IncludeGraph::build`] for a caller that has already read each file's + /// `` `include`` lines off its text — the form a scan uses. + /// + /// Since 2026-09-08 a scan reads a file's text at the step that indexes it + /// and drops it again, so the text is not there to be scanned when the + /// graph is built at the end; [`scan`] runs once per file, at that step, + /// and the lines it found are what arrives here + /// (`docs/features/perf5-p4/README.md` §P4b3). The two entries are the + /// same function over the same lines — `build` is this one with the scan + /// in front of it — so a graph built either way is the same graph. + pub fn from_includes(sources: &[(&Path, &[Include])], incdirs: Vec) -> IncludeGraph { let mut graph = IncludeGraph { incdirs, ..IncludeGraph::default() }; // Learned before the edges: `resolve` consults both tables, and an edge // resolved against a half-filled one would be keyed inconsistently. - let paths: Vec = sources.iter().map(|(path, _)| path.clone()).collect(); + let paths: Vec = sources.iter().map(|(path, _)| path.to_path_buf()).collect(); graph.relearn(&paths); - for (path, text) in sources { - graph.rescan_edges(path, text); + for (path, found) in sources { + graph.rescan_found(path, found); } graph.respell(); graph @@ -151,9 +176,11 @@ impl IncludeGraph { self.respell(); } - /// [`IncludeGraph::update_file`] for a batch of files, with the `+incdir+`s - /// the scope resolves to right now — the form a scan publishing what it - /// has indexed so far uses. + /// [`IncludeGraph::update_file`] for a batch of files whose `` `include`` + /// lines have already been read, with the `+incdir+`s the scope resolves + /// to right now — the form a scan publishing what it has indexed so far + /// uses. The lines come from the step that indexed each file, for the + /// reason [`IncludeGraph::from_includes`] gives. /// /// `known` is the scan's whole work list rather than the files it has /// reached, so the known-file and folded-spelling tables are complete from @@ -162,11 +189,16 @@ impl IncludeGraph { /// `relearn` for the batch, for the same reason /// [`Candidates::absorb`](crate::candidates::Candidates::absorb) re-derives /// its index tables once. - pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]) { + pub fn absorb_includes( + &mut self, + incdirs: &[PathBuf], + known: &[PathBuf], + batch: &[(&Path, &[Include])], + ) { self.incdirs = incdirs.to_vec(); self.relearn(known); - for (path, text) in batch { - self.rescan_edges(path, text); + for (path, found) in batch { + self.rescan_found(path, found); } self.respell(); } @@ -183,8 +215,14 @@ impl IncludeGraph { /// each one lands. A file that includes nothing holds no entry at all, /// which is what keeps `raw` a set of edges rather than a set of files. fn rescan_edges(&mut self, path: &Path, text: &str) { + self.rescan_found(path, &scan(text)); + } + + /// [`IncludeGraph::rescan_edges`] with the file's `` `include`` lines + /// already in hand: where the disk says each one lands, held. + fn rescan_found(&mut self, path: &Path, found: &[Include]) { let targets: Vec = - scan(text).iter().filter_map(|include| self.found(Some(path), include)).collect(); + found.iter().filter_map(|include| self.found(Some(path), include)).collect(); match targets.is_empty() { true => self.raw.remove(path), false => self.raw.insert(path.to_path_buf(), targets), diff --git a/crates/lucisv_server/src/index_cache.rs b/crates/lucisv_server/src/index_cache.rs index 1e5a726..d057138 100644 --- a/crates/lucisv_server/src/index_cache.rs +++ b/crates/lucisv_server/src/index_cache.rs @@ -54,6 +54,45 @@ const VERSION: &str = env!("CARGO_PKG_VERSION"); /// The subdirectory of the OS cache directory this server's stores live in. const OS_DIR: [&str; 2] = ["lucisv", "index"]; +/// What one load of the store found — the numbers that decide whether the file +/// on disk is *already* the file a compaction would write. +/// +/// [`IndexCache::render`] writes this build's header and then one line per +/// path in path order, so a store this build compacted and nothing has +/// appended to since comes back with every line kept, no line dropped, no path +/// named twice and the paths ascending. Anything else — another version's +/// 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)] +struct Load { + /// Whether the first line was this build's own header. + header: bool, + /// Record lines the store held below the header. + read: usize, + /// Of those, the ones that became an entry of their own. + kept: usize, + /// Lines that were not a record this build can use. + dropped: usize, + /// Lines naming a path an earlier line had already named. + duplicates: usize, + /// Whether the paths arrived strictly ascending, the order `render` writes + /// them in. + ordered: bool, +} + +impl Load { + /// Whether these lines are exactly the lines [`IndexCache::render`] would + /// write from the entries they produced. + fn canonical(&self) -> bool { + self.header + && self.ordered + && self.dropped == 0 + && self.duplicates == 0 + && self.kept == self.read + } +} + /// What one entry asserts: a file with exactly this content contributed /// exactly these facts. struct Entry { @@ -78,6 +117,9 @@ pub struct IndexCache { /// False for a missing store — which the first write claims — and for one /// from another version, which the first write replaces wholesale. header_ok: bool, + /// What [`IndexCache::open`] read out of the store, which is what + /// [`IndexCache::already_compact`] asks whether a rewrite would reproduce. + load: Load, /// What this cache's own work has cost since it was opened, for the /// startup breakdown (`docs/features/perf5-p4/README.md`). /// @@ -108,24 +150,45 @@ impl IndexCache { /// whose tail was cut inside a multi-byte character costs the record that /// was torn and no other. Reading the whole buffer as text would have /// rejected all of it for one bad byte at the end. + /// + /// The load is *counted* as well as performed — lines read, kept, dropped + /// and duplicated, and whether the paths arrived in order — because those + /// five numbers are what say whether the file already is what + /// [`IndexCache::compact`] would write over it. pub fn open(dir: Option) -> IndexCache { let Some(dir) = dir else { return IndexCache::disabled() }; 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()); let mut entries = HashMap::new(); + let mut load = Load { header: header_ok, ordered: true, ..Load::default() }; if header_ok { + let mut previous: Option = None; for line in lines { - let Ok(line) = std::str::from_utf8(line) else { continue }; - if let Some((path, entry)) = parse_entry(line) { - // A later record for a path wins: the log is appended to - // as a rescan goes, so the last one written is the one - // that describes the file as the server last saw it. - entries.insert(path, entry); + load.read += 1; + let Ok(line) = std::str::from_utf8(line) else { + load.dropped += 1; + continue; + }; + let Some((path, entry)) = parse_entry(line) else { + load.dropped += 1; + continue; + }; + if let Some(previous) = &previous { + load.ordered &= *previous < path; + } + previous = Some(path.clone()); + // A later record for a path wins: the log is appended to + // as a rescan goes, so the last one written is the one + // that describes the file as the server last saw it. + match entries.insert(path, entry) { + Some(_) => load.duplicates += 1, + None => load.kept += 1, } } } - IndexCache { dir: Some(dir), entries, log: None, header_ok, work: Cell::default() } + let work = Cell::new(CacheWork { opens: 1, ..CacheWork::default() }); + IndexCache { dir: Some(dir), entries, log: None, header_ok, load, work } } /// What this cache has spent and moved since it was opened. @@ -195,6 +258,16 @@ impl IndexCache { /// the checksum of the facts it was written with) for the same reasons it /// rejects any other malformed record. That is the whole crash-safety /// argument, and it is why records are one line each. + /// + /// **A record the store already holds is not written again.** An open + /// buffer is indexed from its own analysis on every scan and its record is + /// written through with it, so a warm session appends a line for every + /// open buffer that is byte-identical to the line already in the store — + /// a duplicate the next load collapses, at the price of making the store + /// non-canonical and so owing [`IndexCache::compact`] a full rewrite. The + /// test is the exact one: same path, same content hash, same encoded + /// facts. Anything that differs by a byte is a new record and is appended + /// as it always was. pub fn record(&mut self, facts: &FileFacts, text: &str) { if self.dir.is_none() { return; @@ -204,6 +277,11 @@ impl IndexCache { let content = content_hash(text.as_bytes()); let mut work = self.work.get(); work.encode_ns += elapsed_ns(encoding); + if self.holds(facts.path(), content, &encoded) { + work.repeats += 1; + self.work.set(work); + return; + } let writing = Instant::now(); self.append(&line(content, &encoded)); work.write_ns += elapsed_ns(writing); @@ -225,17 +303,68 @@ impl IndexCache { /// Atomic and silent: written to a temporary file and renamed, and a /// failure anywhere leaves the previous store standing. A cache that could /// fail a rescan would be worse than no cache. + /// + /// **Skipped when the rewrite would reproduce the file byte for byte** + /// ([`IndexCache::already_compact`]). A warm session whose every file hit + /// the store appends nothing, so the store it loaded is the store it would + /// write, and rewriting 44 MiB to produce the same 44 MiB was 182 ms of a + /// 1.33 s start (`docs/features/perf5-p4/README.md`, §P4b (a)). pub fn compact(&mut self) { let before = self.store_bytes(); let compacting = Instant::now(); - self.compact_now(); + let rewriting = !self.already_compact(); + if rewriting { + self.compact_now(); + } let mut work = self.work.get(); work.compact_ns += elapsed_ns(compacting); + work.compactions += usize::from(rewriting); work.store_before = before; work.store_after = self.store_bytes(); self.work.set(work); } + /// Whether the store on disk is already exactly what [`IndexCache::render`] + /// would write over it. + /// + /// Four things have to hold, and any one of them failing compacts as + /// before: + /// + /// * the store was **loaded canonical** — this build's header, every line + /// a record this build can read, no path named twice, the paths + /// ascending ([`Load::canonical`]); + /// * **nothing has been appended since**, so no line is out of order and + /// no path has a second one; + /// * **no entry's file is gone**, because `render` drops those; + /// * there is a directory to write in at all. + /// + /// **Crash safety is untouched.** A session that appended nothing left the + /// store exactly as it found it, so what is on disk is already the + /// compacted file and there is no half-written state a rewrite would + /// resolve; skipping it only means the append log — which has no appends — + /// stays as it is. The existence sweep is the one part that costs + /// anything, one `stat` per entry, against the whole-store render and + /// write it stands in for. + fn already_compact(&self) -> bool { + self.dir.is_some() + && self.load.canonical() + && self.work.get().records == 0 + && self.entries.keys().all(|path| path.exists()) + } + + /// Whether the store already holds exactly this record — the same path, + /// the same content hash and the same encoded facts, byte for byte. + /// + /// Only exactly that counts. A record whose facts differ by a byte under + /// the same hash is still written, because the line on disk and the facts + /// in hand would then disagree and the store must say what this session + /// last saw. + fn holds(&self, path: &Path, content: u64, encoded: &str) -> bool { + self.entries + .get(path) + .is_some_and(|entry| entry.content == content && entry.facts == encoded) + } + /// The store file's size on disk, or 0 when there is no store. fn store_bytes(&self) -> u64 { let Some(dir) = self.dir.as_ref() else { return 0 }; @@ -797,6 +926,221 @@ mod tests { } } + /// A store two files were recorded into and then compacted — this build's + /// header and one line per path in path order, which is what every + /// session after a whole rescan finds on disk. + fn compacted_store(dir: &TempDir) -> (PathBuf, PathBuf) { + let one = dir.file("a.sv", M); + let two = dir.file("b.sv", M); + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.record(&facts(&one, M), M); + cache.record(&facts(&two, M), M); + cache.compact(); + assert_eq!(cache.work().compactions, 1, "premise: the store was written"); + (one, two) + } + + /// The store's bytes and its modification time — "not rewritten" as + /// something a test can see rather than infer. + fn store_stamp(dir: &TempDir) -> (Vec, std::time::SystemTime) { + let path = dir.path.join(FILE); + let bytes = std::fs::read(&path).expect("read store"); + let stamp = std::fs::metadata(&path).expect("meta").modified().expect("mtime"); + (bytes, stamp) + } + + /// Rewrite the store's record lines, keeping this build's header. + fn rewrite_records(dir: &TempDir, records: &[String]) { + let mut text = header(); + for record in records { + text.push('\n'); + text.push_str(record); + } + text.push('\n'); + std::fs::write(dir.path.join(FILE), text).expect("write store"); + } + + /// The store's record lines, header excluded. + fn records_of(dir: &TempDir) -> Vec { + dir.store_text().lines().skip(1).map(str::to_string).collect() + } + + #[test] + fn a_canonical_store_nothing_appended_to_is_not_rewritten() { + // §P4b (a): a warm session hits the store for every file, appends + // nothing, and would rewrite 44 MiB to produce the same 44 MiB — + // 182 ms of a 1.33 s start. What is on disk is already what `render` + // writes, so the rewrite is skipped and the file is not touched at + // all: not its bytes, not even its modification time. + let dir = TempDir::new("alreadycompact"); + let (one, _) = compacted_store(&dir); + let before = store_stamp(&dir); + + let mut warm = IndexCache::open(Some(dir.path.clone())); + assert!(warm.facts_for(&one, M).is_some(), "premise: a warm session that only reads"); + warm.compact(); + + assert_eq!(warm.work().compactions, 0, "the rewrite would have been byte-identical"); + assert_eq!(store_stamp(&dir), before, "so the store was not touched"); + // And what is on disk is still a store: the next session reads it. + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); + } + + #[test] + fn a_record_the_store_already_holds_is_not_appended_again() { + // An open buffer is indexed from its own analysis on *every* scan and + // its record is written through with it, so a warm session would + // append a byte-identical duplicate for each open buffer — which + // costs the store its canonical shape and so owes the next scan a + // whole 44 MiB rewrite. The same record is a no-op; a changed one is + // not (`docs/features/perf5-p4/README.md`, §P4b (a)). + let dir = TempDir::new("repeatrecord"); + let (one, _) = compacted_store(&dir); + let before = store_stamp(&dir); + + let mut warm = IndexCache::open(Some(dir.path.clone())); + warm.record(&facts(&one, M), M); + assert_eq!(warm.work().records, 0, "nothing was appended"); + assert_eq!(warm.work().repeats, 1, "and the store was already holding it"); + assert_eq!(store_stamp(&dir), before, "so the store on disk did not move"); + warm.compact(); + assert_eq!(warm.work().compactions, 0, "which leaves it canonical"); + assert_eq!(store_stamp(&dir), before); + + // One byte of difference and the record is written exactly as before. + let edited = "module m;\n sub u ();\n wire w;\nendmodule\n"; + warm.record(&facts(&one, edited), edited); + assert_eq!(warm.work().records, 1, "different bytes are a new record"); + assert_eq!(warm.work().repeats, 1); + warm.compact(); + assert_eq!(warm.work().compactions, 1, "and the rewrite is owed again"); + assert_eq!( + IndexCache::open(Some(dir.path.clone())).facts_for(&one, edited), + Some(facts(&one, edited)), + "the newer record is what the next session reads" + ); + } + + #[test] + fn a_store_with_two_lines_for_one_path_is_compacted() { + // The growth bound the skip must not cost: a session that saved a + // file appended a second line for its path, and only a rewrite folds + // the two back into one. + let dir = TempDir::new("dupline"); + let (one, _) = compacted_store(&dir); + let mut records = records_of(&dir); + let repeat = records[0].clone(); + records.push(repeat); + rewrite_records(&dir, &records); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.compact(); + + assert_eq!(cache.work().compactions, 1, "a duplicated path is not canonical"); + assert_eq!(records_of(&dir).len(), 2, "one line per path again"); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); + } + + #[test] + fn a_store_with_a_line_this_build_cannot_read_is_compacted() { + // A record dropped at load — a torn append, bit rot, a checksum that + // no longer matches — means the file on disk holds a line `render` + // would not write, so the store is not canonical and the rewrite is + // what removes it. + let dir = TempDir::new("droppedline"); + let (one, _) = compacted_store(&dir); + let mut records = records_of(&dir); + records.push(format!("{}\tnot a record at all\t{:016x}", "0".repeat(16), 0)); + rewrite_records(&dir, &records); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.compact(); + + assert_eq!(cache.work().compactions, 1, "a dropped line is not canonical"); + assert_eq!(records_of(&dir).len(), 2, "the unreadable line is gone"); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); + } + + #[test] + fn a_store_whose_records_are_out_of_path_order_is_compacted() { + // `render` writes paths sorted, so a store that arrives unsorted was + // not written by a compaction of this shape and rewriting it is not a + // no-op — even though every line in it is a good record. + let dir = TempDir::new("unsorted"); + let (one, _) = compacted_store(&dir); + let mut records = records_of(&dir); + records.reverse(); + rewrite_records(&dir, &records); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.compact(); + + assert_eq!(cache.work().compactions, 1, "an unsorted store is not canonical"); + let sorted: Vec = records_of(&dir); + assert_eq!(sorted.len(), 2); + assert!(sorted[0] < sorted[1], "path order restored: {sorted:?}"); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); + } + + #[test] + fn a_session_that_recorded_one_file_compacts() { + // The moment an append happens the store on disk is no longer the + // store `render` would write — the appended line is out of order at + // best and a second line for its path at worst — so the rewrite is + // owed exactly as it always was. + let dir = TempDir::new("appended"); + let (one, _) = compacted_store(&dir); + let third = dir.file("c.sv", M); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + assert!(cache.facts_for(&one, M).is_some(), "the other two still hit"); + cache.record(&facts(&third, M), M); + cache.compact(); + + assert_eq!(cache.work().compactions, 1, "a session that appended must rewrite"); + assert_eq!(records_of(&dir).len(), 3); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&third, M).is_some()); + } + + #[test] + fn a_store_holding_a_file_that_is_gone_is_compacted() { + // `render` drops an entry whose file no longer exists, so a store + // holding one is not what a rewrite would produce — and the rewrite + // is what prunes it, exactly as before. + let dir = TempDir::new("goneentry"); + let (one, two) = compacted_store(&dir); + std::fs::remove_file(&two).expect("remove"); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.compact(); + + assert_eq!(cache.work().compactions, 1, "a gone file must still be pruned"); + assert_eq!(records_of(&dir).len(), 1, "the vanished file's line is gone"); + assert!(IndexCache::open(Some(dir.path.clone())).facts_for(&one, M).is_some()); + } + + #[test] + fn a_store_from_another_version_is_replaced_even_by_a_session_that_wrote_nothing() { + // The header is the one line the skip may never leave standing: its + // records were dropped at load, so a session that keeps it leaves a + // store nobody can read on disk for ever. + let dir = TempDir::new("foreignheader"); + let file = dir.file("m.sv", M); + let encoded = facts(&file, M).encode().expect("encodes"); + let foreign = format!( + "lucisv-index-cache\t{CACHE_FORMAT}\t{FACTS_FORMAT}\t0.0.0-not-this-build\n{}\n", + line(content_hash(M.as_bytes()), &encoded) + ); + std::fs::write(dir.path.join(FILE), foreign).expect("write"); + + let mut cache = IndexCache::open(Some(dir.path.clone())); + cache.compact(); + + assert_eq!(cache.work().compactions, 1, "another version's header is not canonical"); + let text = dir.store_text(); + assert_eq!(text, format!("{}\n", header()), "replaced with this build's own: {text}"); + } + #[test] fn a_record_whose_facts_no_longer_decode_is_a_miss_not_a_failure() { // The line is well-formed as far as the store is concerned — hash, diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 67849fb..5c52709 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -41,6 +41,7 @@ mod perf; mod ports; mod rename; mod rename_trace; +mod scan_order; mod scan_trace; mod selection; mod server; diff --git a/crates/lucisv_server/src/scan_order.rs b/crates/lucisv_server/src/scan_order.rs new file mode 100644 index 0000000..5994efc --- /dev/null +++ b/crates/lucisv_server/src/scan_order.rs @@ -0,0 +1,193 @@ +//! What order a scan walks its work list in, and how much of that order a +//! request answered mid-scan is owed. +//! +//! A scan indexes every in-scope file, and [`vlog_semantic::IndexBuilder`] +//! sorts its records by path inside `finish`, so **no insertion order can +//! reach the finished index**. What the order decides is what the *prefix* of +//! a scan holds — which file the progress bar names first, and what a request +//! answered between two files can see (`docs/features/scan-interleave`). +//! +//! Three groups, in this order: +//! +//! 1. the **open buffers' own files** — the ones the user is looking at; +//! 2. every other file under those buffers' **raised scope directories** — +//! the neighbourhood `docs/features/index-scope/README.md`'s folder rung +//! would have indexed for them; +//! 3. everything else, in path order. +//! +//! Group 1 was the whole of `Workspace::open_first` until 2026-09-08, and on +//! its own it made the first useful answer of a workspace-scoped session +//! *empty*: a definition sent with the opening `didOpen` was answered off a +//! prefix holding that one buffer and the alphabet after it, and the module it +//! named lives in the folder next door. Group 2 is that folder +//! (`docs/features/perf5-p4/README.md` §P4b3). + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; + +use vlog_semantic::index_order; + +/// A scan's work list, ordered, with the length of its head segment. +pub struct WorkList { + /// Every file the scan will index, in the order it will index them. + pub files: Vec, + /// How many files at the front of `files` are the user's own + /// neighbourhood — groups 1 and 2 above. + /// + /// **0 means there is no neighbourhood worth waiting for**: no buffer is + /// open, none of them has a folder in scope, or the folders cover so much + /// of the work list that "the user's own folder" and "the workspace" are + /// the same wait. See [`work_list`]. + pub head: usize, +} + +/// The user's own file. +const OWN: u8 = 0; +/// A file under one of the folders the user's own files raise to. +const FOLDER: u8 = 1; +/// Everything else. +const TAIL: u8 = 2; + +/// Order `files` open-buffers-first, then their folders, then the rest. +/// +/// `open` is every open buffer's own path and `folders` the directories those +/// buffers raise to (`Workspace::raised`). Both may be empty, and an empty +/// `folders` is the ordering this function had before 2026-09-08. +/// +/// The head is reported raw; [`worth_waiting`] is what bounds it, because the +/// bound is against the **whole** scan and this function may be ordering only +/// what is left of one. +pub fn work_list(files: Vec, open: &[PathBuf], folders: &[PathBuf]) -> WorkList { + // Asked of `vlog_semantic` rather than re-derived here, so the count a + // scan reports is the count the index will hold: sorted by path, one entry + // per path. + let ordered = index_order(files.into_iter().map(|path| (path, ()))); + let own: HashSet<&Path> = open.iter().map(PathBuf::as_path).collect(); + let mut ranked: Vec<(u8, PathBuf)> = + ordered.into_iter().map(|(path, ())| (rank(&path, &own, folders), path)).collect(); + // Stable, so each group keeps the path order `index_order` sorted it into. + ranked.sort_by_key(|(rank, _)| *rank); + let head = ranked.iter().take_while(|(rank, _)| *rank < TAIL).count(); + WorkList { files: ranked.into_iter().map(|(_, path)| path).collect(), head } +} + +/// `pending` — the files a held request would wait for — or **0** when that is +/// too many to wait for in a scan of `total` files. +/// +/// A request held for the startup scan waits for the whole neighbourhood +/// before it is answered ([`WorkList::head`]), which is a good trade only +/// while the neighbourhood is a small part of the scan: a buffer opened from a +/// workspace *root* raises to that root, and waiting for "its folder" would be +/// waiting for the entire scan and answering nothing at all until it ended. So +/// a neighbourhood that is not a minority of the workspace is no +/// neighbourhood — the ordering still applies, and the drain falls back to the +/// first interleave point exactly as it did before. +/// +/// **`pending` is what is left to wait for, not where the segment ends.** A +/// `didOpen` can arrive at any point of a scan, and re-ordering puts its +/// folder next: 124 files is 124 files of waiting whether the scan has done +/// none of the workspace or nine tenths of it. +pub fn worth_waiting(pending: usize, total: usize) -> usize { + match pending * 2 > total { + true => 0, + false => pending, + } +} + +/// Which of the three groups `path` belongs to. +fn rank(path: &Path, own: &HashSet<&Path>, folders: &[PathBuf]) -> u8 { + if own.contains(path) { + return OWN; + } + match folders.iter().any(|folder| path.starts_with(folder)) { + true => FOLDER, + false => TAIL, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn paths(names: &[&str]) -> Vec { + names.iter().map(PathBuf::from).collect() + } + + fn names(list: &WorkList) -> Vec { + list.files.iter().map(|p| p.display().to_string()).collect() + } + + #[test] + fn with_nothing_open_the_list_is_path_order_and_there_is_no_head() { + let list = work_list(paths(&["/w/z.sv", "/w/a.sv", "/w/m.sv"]), &[], &[]); + assert_eq!(names(&list), ["/w/a.sv", "/w/m.sv", "/w/z.sv"]); + assert_eq!(list.head, 0, "nothing is waited for when nothing is open"); + } + + #[test] + fn the_open_buffer_leads_then_its_folder_then_the_rest() { + let list = work_list( + paths(&[ + "/w/other/far.sv", + "/w/ip/aes/rtl/aes.sv", + "/w/ip/aes/dv/tb.sv", + "/w/other/near.sv", + ]), + &paths(&["/w/ip/aes/dv/tb.sv"]), + &paths(&["/w/ip/aes"]), + ); + assert_eq!( + names(&list), + ["/w/ip/aes/dv/tb.sv", "/w/ip/aes/rtl/aes.sv", "/w/other/far.sv", "/w/other/near.sv"], + "the buffer, then its folder, then the rest in path order" + ); + assert_eq!(list.head, 2, "the buffer and its folder are what a held request waits for"); + } + + #[test] + fn a_folder_that_is_most_of_the_workspace_is_not_a_head_to_wait_for() { + // A buffer opened from the workspace root raises to the root, so + // "its folder" is the whole scan. The order is unchanged; the drain + // falls back to the first interleave point. + let files = paths(&["/w/a.sv", "/w/b.sv", "/w/c.sv"]); + let list = work_list(files, &paths(&["/w/a.sv"]), &paths(&["/w"])); + assert_eq!(names(&list), ["/w/a.sv", "/w/b.sv", "/w/c.sv"]); + assert_eq!(list.head, 3, "the ranking itself says the whole list is the folder"); + assert_eq!(worth_waiting(list.head, 3), 0, "and that is no head at all"); + } + + #[test] + fn exactly_half_is_still_a_head_and_one_more_is_not() { + assert_eq!(worth_waiting(2, 4), 2, "two of four is a minority"); + assert_eq!(worth_waiting(3, 4), 0, "three of four is not"); + assert_eq!(worth_waiting(0, 4), 0, "and nothing is nothing"); + } + + #[test] + fn the_bound_is_against_the_whole_scan_and_not_against_what_is_left() { + // The `didOpen` that names a folder can arrive at any point of a scan. + // Measured against the tail alone, a 124-file folder would stop being + // worth waiting for once 3 700 of a 3 976-file workspace were done — + // which is exactly when it costs least. + assert_eq!(worth_waiting(124, 3_976), 124, "124 files of 3 976, at any point of it"); + } + + #[test] + fn a_path_handed_over_twice_is_one_file() { + let list = work_list(paths(&["/w/a.sv", "/w/a.sv", "/w/b.sv"]), &[], &[]); + assert_eq!(names(&list), ["/w/a.sv", "/w/b.sv"]); + } + + #[test] + fn an_open_buffer_outside_the_scope_still_lends_its_folder() { + // The buffer's own file is not in the work list — it is over the size + // cap, say — but the folder it raised is still the neighbourhood. + let list = work_list( + paths(&["/w/ip/aes/rtl/aes.sv", "/w/other/far.sv"]), + &paths(&["/w/ip/aes/dv/huge.sv"]), + &paths(&["/w/ip/aes"]), + ); + assert_eq!(names(&list), ["/w/ip/aes/rtl/aes.sv", "/w/other/far.sv"]); + assert_eq!(list.head, 1); + } +} diff --git a/crates/lucisv_server/src/scan_trace.rs b/crates/lucisv_server/src/scan_trace.rs index f77ff31..9ab9a0b 100644 --- a/crates/lucisv_server/src/scan_trace.rs +++ b/crates/lucisv_server/src/scan_trace.rs @@ -14,8 +14,46 @@ //! grepping an output channel, and `tools/perf/phases_p4.py`, which turns //! them into schema-2 rows. +use std::cell::Cell; use std::time::Instant; +use vlog_semantic::WorkspaceIndex; + +thread_local! { + static READS: Cell = const { Cell::new(0) }; +} + +/// How many source files this thread has read off disk for a scan. +/// +/// A work counter, not a timer, and modelled on `vlog_parser::stats::parses` +/// for the same reason: the claim a scan makes since 2026-09-08 is that it +/// reads each file's bytes **exactly once** — the content hash, the parse and +/// the `` `include`` scan all come out of that one read — and the honest way +/// to prove that is to count the reads. A stopwatch would be a flake; a count +/// is not. +/// +/// Per thread, because `cargo test` runs tests in parallel and a process-wide +/// counter would be adding up every other test's scans. Monotone and never +/// reset, so a caller measures a delta. +/// +/// Only a test asks — this is a bin crate, so nothing outside it can — while +/// [`count_read`] is **unconditional**: one non-atomic add per file is noise +/// beside the read it counts, and gating the increment as well would mean the +/// path under test and the shipped path were not the same code. +#[cfg(test)] +pub fn source_reads() -> u64 { + READS.with(Cell::get) +} + +/// Count one file read off disk — see [`source_reads`]. +pub fn count_read() { + READS.with(|reads| reads.set(reads.get() + 1)); +} + +use crate::candidates::Candidates; +use crate::includes::IncludeGraph; +use crate::index_cache::IndexCache; + /// What the persistent store's own work cost, counted inside /// [`crate::index_cache::IndexCache`] because that is where it happens. /// @@ -41,10 +79,19 @@ pub struct CacheWork { pub misses: usize, /// Records written through. pub records: usize, + /// Write-throughs the store already held, byte for byte, and so did not + /// append again — one per open buffer on a warm scan (§P4b (a)). + pub repeats: usize, /// Encoded bytes handed to `FileFacts::decode`. pub decoded_bytes: usize, /// Encoded bytes appended to the log. pub written_bytes: usize, + /// Times the store was read off disk. One per whole rescan that reached a + /// file — a scan whose work list is empty opens nothing (§P4b (b1)). + pub opens: usize, + /// Times the store was actually rewritten. Zero when the rewrite would + /// have reproduced the file byte for byte (§P4b (a)). + pub compactions: usize, /// The store file's size before and after a compaction, in bytes. pub store_before: u64, pub store_after: u64, @@ -63,8 +110,11 @@ impl CacheWork { hits: self.hits.saturating_sub(before.hits), misses: self.misses.saturating_sub(before.misses), records: self.records.saturating_sub(before.records), + repeats: self.repeats.saturating_sub(before.repeats), decoded_bytes: self.decoded_bytes.saturating_sub(before.decoded_bytes), written_bytes: self.written_bytes.saturating_sub(before.written_bytes), + opens: self.opens.saturating_sub(before.opens), + compactions: self.compactions.saturating_sub(before.compactions), store_before: self.store_before, store_after: self.store_after, } @@ -112,15 +162,30 @@ pub struct ScanTrace { pub number: u32, // -- discovery ------------------------------------------------------ - /// Resolving the scope, walking it and reading every file's text. + /// Resolving the scope, walking it, asking the size cap about each file + /// and taking every open buffer's text. **Not** reading the files: since + /// 2026-09-08 that happens at the step that indexes each one, and is + /// `read_ms` below (`docs/features/perf5-p4/README.md` §P4b3). pub discovery_ms: f64, - /// Sorting into index order and moving the open buffers to the front. + /// Sorting into index order and putting the user's own neighbourhood at + /// the front ([`crate::scan_order`]). pub order_ms: f64, /// Reading the persistent store off disk. pub cache_open_ms: f64, - /// Files whose text the scan holds, and how many bytes that is. + /// Reading one file's text off disk, at the step that indexes it, summed + /// over the scan. An open buffer's text is not read and not timed here: + /// the scan took it when the work list was. + pub read_ms: f64, + /// Files the scan will read, known when the work list is taken — and the + /// bytes it has read so far, which only equals the whole list once the + /// scan has finished. pub read: usize, pub read_bytes: usize, + /// The bytes the scan **holds** for its whole life: the open buffers' + /// texts, taken with the work list because their facts were. Every other + /// file's text lives from its own step to the end of it, which is what + /// `work_kib` on the memory line reports. + pub work_bytes: usize, /// Files the size cap kept out. pub skipped: usize, /// Entries the store held when it was opened, and their encoded bytes. @@ -170,11 +235,104 @@ impl ScanTrace { ScanTrace { on, started: on.then(Instant::now), ..ScanTrace::default() } } + /// A trace for a scan that is starting, numbered so a session's lines can + /// be told apart — or an inert one when nobody asked for a trace. + /// + /// `scans` is the session's own count of scans so far and is advanced + /// here, so a line's number is the number of the scan that prints it. + /// `since_start_ms` is left for the server to stamp: how long the process + /// had been alive is the server's own knowledge, not the workspace's. + pub fn opened(scans: &mut u32, on: bool, kind: &'static str) -> ScanTrace { + *scans = scans.saturating_add(1); + ScanTrace { kind, number: *scans, ..ScanTrace::new(on) } + } + /// Whether anything below will be recorded. pub fn on(&self) -> bool { self.on } + /// The work list's size, the bytes the scan will hold for as long as it + /// runs, and the store counters this scan is measured from. + /// + /// `held` is what the scan is carrying — the open buffers' texts — and not + /// the work list's own bytes, which are read a file at a time and let go + /// again ([`ScanTrace::saw_read`]). + /// + /// `cache` is the baseline [`ScanTrace::landed`] subtracts: a widen + /// inherits the store the previous scan opened, so the counters on it are + /// the session's and not this scan's. A whole scan that opens one of its + /// own resets the baseline when it does. + pub fn measure_work(&mut self, files: usize, held: usize, skipped: usize, cache: CacheWork) { + if !self.on { + return; + } + self.read = files; + self.work_bytes = held; + self.skipped = skipped; + self.cache = cache; + } + + /// One file's text, read at the step that indexes it. + pub fn saw_read(&mut self, bytes: usize, from: Option) { + if !self.on { + return; + } + ScanTrace::add(&mut self.read_ms, from); + self.read_bytes += bytes; + } + + /// Close this trace: the tables the finished scan left behind, measured. + /// + /// Every size below is a walk, so all of them are behind [`ScanTrace::on`] + /// and none of them happens in a session that did not ask for a trace. + pub fn landed( + &mut self, + overlays: usize, + cache: &IndexCache, + index: &WorkspaceIndex, + candidates: &Candidates, + includes: &IncludeGraph, + ) { + if !self.on { + return; + } + // Read first, before a single size below is walked: describing a scan + // is not part of the scan, and charging the walks to `total_ms` would + // make the trace inflate the very number it exists to explain. + self.total_ms = self.elapsed_ms(); + self.overlays = overlays; + self.cache = cache.work().since(self.cache); + // At the *end*, so the store's retention is what the finished scan + // leaves resident rather than what it started from — the two differ + // by every record a cold scan wrote. + self.cache_entries = cache.entry_count(); + self.cache_bytes = cache.encoded_bytes(); + let tables = index.table_sizes(); + let counts = index.counts(); + let (units, macros, words, word_bytes) = candidates.sizes(); + let (include_edges, include_known) = includes.sizes(); + self.sizes = TableSizes { + index_files: counts.files, + unit_names: tables.unit_names, + unit_defs: tables.unit_defs, + members: tables.members, + hier_members: tables.hier_members, + reference_keys: tables.reference_keys, + reference_sites: tables.reference_sites, + defines: counts.defines, + instantiations: counts.instantiations, + fact_words: tables.words, + fact_word_bytes: tables.word_bytes, + candidate_units: units, + candidate_macros: macros, + candidate_words: words, + candidate_word_bytes: word_bytes, + include_edges, + include_known, + }; + } + /// The clock a stage is timed from — `None`, and so free, when off. pub fn now(&self) -> Option { self.on.then(Instant::now) @@ -208,7 +366,7 @@ impl ScanTrace { let c = &self.cache; format!( "scan {} stages ({}, {} files): discovery={:.2} order={:.2} cache_open={:.2} \ - lookup={:.2} decode={:.2} parse={:.2} encode={:.2} store_write={:.2} \ + 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", @@ -218,6 +376,7 @@ impl ScanTrace { self.discovery_ms, self.order_ms, self.cache_open_ms, + self.read_ms, nanos(c.lookup_ns), nanos(c.decode_ns), self.parse_ms, @@ -244,8 +403,8 @@ impl ScanTrace { let c = &self.cache; format!( "scan {} counts ({}): read={} read_kib={} skipped={} hits={} misses={} buffers={} \ - records={} decoded_kib={} written_kib={} publishes={} published={} \ - first_publish={:.2} overlays={}", + records={} repeats={} decoded_kib={} written_kib={} opens={} compactions={} \ + publishes={} published={} first_publish={:.2} overlays={}", self.number, self.kind, self.read, @@ -255,8 +414,11 @@ impl ScanTrace { c.misses, self.buffers, c.records, + c.repeats, kib(c.decoded_bytes), kib(c.written_bytes), + c.opens, + c.compactions, self.publishes, self.published, self.first_publish_ms, @@ -297,7 +459,7 @@ impl ScanTrace { kib(s.candidate_word_bytes), s.include_edges, s.include_known, - kib(self.read_bytes), + kib(self.work_bytes), ) } } diff --git a/crates/lucisv_server/src/server/client.rs b/crates/lucisv_server/src/server/client.rs index 5f51c25..8a15b4c 100644 --- a/crates/lucisv_server/src/server/client.rs +++ b/crates/lucisv_server/src/server/client.rs @@ -304,7 +304,7 @@ impl Server { } /// One line for a request the order contract makes wait, naming which of - /// [`Server::must_wait`]'s three clauses held it. + /// [`Server::must_wait`]'s four clauses held it. /// /// The question this answers is the one a slow-looking editor raises: /// "was that request slow, or was it never started?". Silent for anything @@ -315,11 +315,12 @@ impl Server { } let Message::Request(request) = message else { return }; self.timing(format!( - "{} HELD behind a rescan (answering={}, wanted={}, already held={})", + "{} HELD behind a rescan (answering={}, wanted={}, already held={}, staging={})", request.method, self.answering_a_rescan, self.rescan_wanted, - self.held.len() + self.held.len(), + self.staging )); } } diff --git a/crates/lucisv_server/src/server/index.rs b/crates/lucisv_server/src/server/index.rs index 9c02eed..1ed0f37 100644 --- a/crates/lucisv_server/src/server/index.rs +++ b/crates/lucisv_server/src/server/index.rs @@ -28,8 +28,10 @@ impl Server { /// or a file the client renamed or deleted. pub(super) fn reindex(&mut self) { // A rescan asked for by a message this scan answered is *this* scan's - // successor, not a scan inside it. See `scan_until_settled`. - if self.scanning { + // successor, not a scan inside it — and one asked for before the + // startup scan has begun is that scan itself. See + // `scan_until_settled` and [`Server::scan_owed`]. + if self.scan_owed() { self.rescan_wanted = true; return; } @@ -84,8 +86,9 @@ impl Server { // bytes a moment later. One more scan when this one ends is the whole // answer, and it is the same flag every other mid-scan trigger sets. // `true` because the caller's fallback — a whole rebuild, right now — - // is exactly what must not happen. - if self.scanning { + // is exactly what must not happen. Same for the startup's + // configuration wait, whose scan reads this file from disk anyway. + if self.scan_owed() { self.rescan_wanted = true; return true; } @@ -122,7 +125,12 @@ impl Server { /// sets, and it is what keeps the coalescing rule one rule /// (`docs/features/scan-interleave/README.md`). pub(super) fn reindex_widened(&mut self, added: Vec) { - if self.scanning { + // Before the startup scan has begun there is nothing to widen *into*: + // that scan resolves the scope afresh, the buffer this `didOpen` just + // installed is already in it, and `open_first` puts the buffer at the + // head of its work list. So the widen is folded into the one scan + // rather than run as a second one (`server/startup.rs`). + if self.scan_owed() { self.rescan_wanted = true; return; } @@ -211,6 +219,8 @@ impl Server { }; self.answering_a_rescan = false; self.scanning = false; + // A neighbourhood can only be owed by a scan, and there is none now. + self.head_owed = false; warnings } @@ -314,25 +324,76 @@ impl Server { /// to and no reason to go on scanning, so it stops the scan the same way a /// `shutdown` does. fn answer_what_is_waiting(&mut self, scan: &mut Scan) -> bool { - let mut batch = Vec::new(); + // Nothing may be answered off a prefix that does not yet hold the + // folder the user is working in: a definition into the file next door + // would be `[]` (`docs/features/perf5-p4/README.md` §P4b3). + self.head_owed = !scan.neighbourhood_indexed(); + let mut batch = self.waiting_for_this_scan(); while let Ok(message) = self.queue.try_recv() { batch.push(message); } if batch.is_empty() { return false; } - let opened = opened_in(&batch); + // A `didOpen` in this burst names a folder the work list has not been + // ordered around yet, so the requests behind it in the burst are owed + // that ordering before they are answered — which is exactly what the + // widen this `didOpen` used to trigger made them wait for. The flag is + // set *before* the batch is applied, so `must_wait` holds them; it is + // recomputed below once the new head segment is known. + let opened = !opened_in(&batch).is_empty(); + self.head_owed |= opened; self.workspace.publish_scan(scan); self.stopped = !matches!(self.process_batch(batch), Ok(false)); - // The file the user has just opened is the one they are looking at, so - // it is indexed next rather than when the alphabet reaches it — the - // open-first rule, for a file opened after the work list was taken. - for path in opened { - scan.index_next(&path); + // The files the user has just opened, and the folders around them, are + // what they are looking at, so they are indexed next rather than when + // the alphabet reaches them — the open-first rule, for buffers opened + // after the work list was taken. + if opened { + self.workspace.open_next(scan); + self.head_owed = !scan.neighbourhood_indexed(); } self.stopped } + /// What the startup's configuration wait set aside, when this scan is the + /// one those messages were waiting for. + /// + /// **Not an exemption from the order contract — the other side of it.** A + /// request that arrives before the startup scan has begun is held for the + /// same reason one arriving *during* it is answered: there is no index at + /// all to answer it from, and the scan it is waiting for is the server's + /// own startup, with nothing queued ahead of it and — being the session's + /// first — an empty `gone` set. So the startup scan answers it exactly as + /// it answers a message that turns up while it runs, off the same + /// published prefix. + /// + /// A scan a **message** asked for takes nothing: its held messages are + /// queued behind the message that asked for it, and answering them off a + /// half-updated index is precisely the trade + /// `docs/features/scan-interleave/README.md`'s decision 2 refuses. Same + /// for a scan with a further rescan already wanted — the requests behind + /// that ask are owed its effect. + /// + /// **And not at the very first file.** A prefix holding the user's own + /// buffer and nothing else answers a definition in the file next door with + /// `[]` — coherent, and useless, which is what §P4b2 measured + /// (`docs/features/perf5-p4/README.md`). So the startup scan takes what it + /// was handed once it has stepped the user's whole neighbourhood + /// ([`Server::head_owed`], from [`Scan::neighbourhood_indexed`]); the + /// `publish_scan` in [`Server::answer_what_is_waiting`] is what then makes + /// that neighbourhood answerable, in the same call. A scan with no + /// neighbourhood — nothing open, or a folder covering the workspace — says + /// so with `head` 0 and drains at the first file exactly as before. + /// Requests arriving *after* that are answered at every interleave point, + /// as they always were. + fn waiting_for_this_scan(&mut self) -> Vec { + if self.answering_a_rescan || self.rescan_wanted || self.head_owed { + return Vec::new(); + } + std::mem::take(&mut self.held) + } + /// Publish a new completed hierarchy revision after any index mutation. pub(super) fn hierarchy_index_changed(&mut self) { self.hierarchy_revision = self.hierarchy_revision.saturating_add(1); diff --git a/crates/lucisv_server/src/server/mod.rs b/crates/lucisv_server/src/server/mod.rs index ab1c383..904d7c3 100644 --- a/crates/lucisv_server/src/server/mod.rs +++ b/crates/lucisv_server/src/server/mod.rs @@ -44,10 +44,9 @@ use lsp_server::{Connection, Message, RequestId}; use lsp_types::notification::{Cancel, Notification as _}; use lsp_types::{SemanticToken, Uri}; -use crate::settings::ClientSettings; use crate::state::Workspace; -use batch::{burst, cancelled_in, cancelled_response, forward}; +use batch::{burst, cancelled_in, cancelled_response}; mod batch; mod client; @@ -59,6 +58,7 @@ mod large_file; mod notification; mod progress; mod semantic_tokens; +mod startup; #[cfg(test)] mod tests; @@ -192,6 +192,24 @@ pub struct Server { /// another one, and this is what turns that into the flag below rather /// than a scan inside a scan. scanning: bool, + /// Whether the startup scan is still *owed* — the window between the + /// `workspace/configuration` request that opens a session and the answer + /// that decides the scope its one scan runs at + /// (`server/startup.rs`). Nothing has been indexed yet, so a rescan + /// trigger in this window is folded into the scan that is about to run + /// rather than run as a scan of its own, and every request waits for it — + /// there is nothing to answer one from. Never true again after + /// construction. + staging: bool, + /// Whether the scan now running still owes the user's own neighbourhood — + /// their open buffers and the folders those raise to, which + /// [`crate::scan_order`] puts at the head of its work list. Until it has + /// been indexed there is nothing worth answering a request off: the prefix + /// holds the alphabet rather than what the user is looking at, and §P4b2 + /// measured what that answers, which is `[]` + /// (`docs/features/perf5-p4/README.md`). False whenever no scan is + /// running, and false during a scan with no neighbourhood to wait for. + head_owed: bool, /// A rescan asked for while a scan was running. Coalesced: any number of /// requests is one more scan when this one ends, whatever asked for them. rescan_wanted: bool, @@ -270,137 +288,6 @@ struct TokenAnswer { } impl Server { - /// The server, with its first index built. - /// - /// The startup scan runs at the **default** settings — including the - /// folder scope — because neither settings door can deliver anything - /// before `initialized`; a client whose `lucisv.index.scope` differs pays - /// one extra rescan when its settings land, exactly as `lucisv.exclude` - /// has always cost one. - pub fn new( - connection: Connection, - roots: Vec, - abilities: ClientAbilities, - storage: Option, - verbose: bool, - ) -> Server { - Server::started( - connection, - roots, - abilities, - ClientSettings::default(), - storage, - verbose, - Vec::new(), - ) - } - - /// [`Server::new`] with a client's settings already in hand — the seam the - /// tests start a session from. Only a test has any settings this early: - /// one whose subject is not the scope says so here rather than driving a - /// `didChangeConfiguration` and then reasoning about the extra rescan it - /// buys. - /// - /// `queued` is what the client had already sent when the server was built - /// — the opening burst, put straight onto the queue the startup scan - /// drains. Empty for [`Server::new`]; a test fills it because racing the - /// forwarder thread for it would make the test a coin toss rather than a - /// check. - fn started( - connection: Connection, - roots: Vec, - abilities: ClientAbilities, - client: ClientSettings, - storage: Option, - verbose: bool, - queued: Vec, - ) -> Server { - // Started before the first scan, not in `run`: the scan below answers - // whatever the client has already sent, and it can only do that off a - // queue that is already being filled. - let (forwarded, queue) = forward(&connection); - for message in queued { - let _ = forwarded.send(message); - } - let mut server = Server { - connection, - workspace: Workspace::default(), - config_warnings: HashSet::new(), - lint_config_problems: std::cell::RefCell::default(), - said_lint_names: Vec::new(), - abilities, - watchers: None, - registrations: 0, - request_ids: 0, - pending: HashMap::new(), - generation: 0, - hierarchy_revision: 0, - tokens: HashMap::new(), - token_results: 0, - indexings: 0, - dirty: Vec::new(), - queue, - scanning: false, - rescan_wanted: false, - answering_a_rescan: false, - stopped: false, - held: Vec::new(), - verbose, - born: std::time::Instant::now(), - }; - // Nothing has been built yet, so there is no rebuild to owe: the - // `true` this returns for a non-default `client` is the rebuild that - // is about to happen anyway. - let _ = server.workspace.set_client_settings(client); - // Before the first build, because it is one rung of the ladder that - // decides where that build reads its cache from - // (`docs/features/index-persistence/README.md`). - server.workspace.set_storage_path(storage); - // The earliest legal moment for anything server-initiated: `main` - // builds this only after `initialize_finish`, which returns once the - // client's `initialized` notification has arrived — and consumes it, - // so the loop below never sees one to hang these off instead. The - // first index build is the slowest one of the session, so it gets the - // same bar every later rescan gets. - // - // And it answers messages while it runs, which is what stops the first - // request of a session waiting out the whole scan - // (`docs/features/scan-interleave/README.md`). Everything below it is - // therefore reached with the client's opening burst already handled — - // and skipped altogether if that burst shut the server down. - server.workspace.adopt_roots(roots); - let warnings = server.scan_until_settled(false); - if server.stopped { - return server; - } - server.hierarchy_index_changed(); - // A buffer can now be *opened* during the startup scan, and what was - // published for it then was computed against a half-built index. This - // is the same debt a rescan pays at the end of `reindex`, owed here - // for the first time because before this round no buffer could exist - // at this point. Nothing at all is sent when nothing is open, which is - // every session whose client did not get a `didOpen` in edgeways. - if !server.workspace.open_uris().is_empty() { - server.refresh_code_lenses(); - server.generation += 1; - for uri in server.workspace.open_uris() { - server.publish(&uri); - } - } - server.report_scope(warnings); - server.register_watchers(); - // The pull half of the settings model. Asked here because this is the - // same moment the watchers are registered — the earliest legal one — - // and answered later, in the loop: the settings therefore arrive - // *after* the first index build, exactly as a pushed - // `didChangeConfiguration` always has (it cannot arrive before - // `initialized` either). A pulled `lucisv.exclude` or `lucisv.filelist` - // costs one extra rescan when it lands; nothing is stale in between, - // it is simply the default scope until the client answers. - server.request_configuration(); - server - } - /// Receive until the client shuts us down or the channel closes. /// /// One blocking receive, then everything already queued behind it, then @@ -535,7 +422,7 @@ impl Server { /// setting or an added workspace folder before a go-to-definition. Those /// four ask for a rescan, and "applied" for them means the rescan has /// **run**: one message at a time, the server would have finished it - /// before ever taking the request. Three clauses, one rule: + /// before ever taking the request. Four clauses, one rule: /// /// * `answering_a_rescan` — this scan is one a message asked for, so /// every request that arrives while it runs arrived *after* that @@ -543,7 +430,19 @@ impl Server { /// * `rescan_wanted` — a message in this very burst has just asked for /// one, and the requests behind it in the burst are owed the same; /// * `held` — a request is already waiting, and answering a newer one - /// ahead of it would reorder them just as badly. + /// ahead of it would reorder them just as badly; + /// * `staging` — the startup scan has not begun, because the settings + /// that decide its scope are still in flight. There is no index at all + /// to answer from, so a request waits for that scan — and is answered + /// *inside* it, mid-way, exactly as one arriving while it runs is + /// ([`Server::waiting_for_this_scan`]); + /// * `head_owed` — the scan running has not yet reached the end of the + /// user's own folder. There *is* an index, but the part of it a request + /// is asking about is the part not built yet, and answering off the + /// alphabet's prefix returns `[]` rather than an answer. A request + /// behind a `didOpen` is owed that `didOpen`'s effect on the scan + /// order, which is the same rule the other four state + /// ([`Server::head_owed`]). /// /// What is left answered mid-scan is exactly what is queued behind /// *nothing*: the opening burst of a session, whose scan is the server's @@ -551,7 +450,23 @@ impl Server { /// the round is about, and it is the one a user feels /// (`docs/features/scan-interleave/README.md`). fn must_wait(&self) -> bool { - self.answering_a_rescan || self.rescan_wanted || !self.held.is_empty() + self.answering_a_rescan + || self.rescan_wanted + || !self.held.is_empty() + || self.staging + || self.head_owed + } + + /// Whether a scan is running or already owed — the two states in which a + /// rescan trigger records that one more scan is wanted instead of running + /// one itself. + /// + /// The second is the startup's configuration wait (`server/startup.rs`): + /// the scan it is waiting for has not begun, and when it does it will + /// resolve the scope afresh and read every file in it, so anything asked + /// for now is satisfied by it. + fn scan_owed(&self) -> bool { + self.scanning || self.staging } /// Whether the installed index covers the whole scope with no indexing diff --git a/crates/lucisv_server/src/server/startup.rs b/crates/lucisv_server/src/server/startup.rs new file mode 100644 index 0000000..190a311 --- /dev/null +++ b/crates/lucisv_server/src/server/startup.rs @@ -0,0 +1,310 @@ +//! What a session does before its message loop: ask the client for its +//! settings, wait a bounded moment for the answer, and run **one** startup +//! scan at the scope that answer decided. +//! +//! Before 2026-09-08 the order was the other way round — scan at the +//! defaults, then ask — and a client whose `lucisv.index.scope` differs from +//! the default folder scope (which is every VS Code session that sets one) +//! paid a whole second scan when the answer landed. With no buffer open the +//! first of those scans indexes **zero files**, so what it bought was the +//! round-trip wait and nothing else; §P4b then made it cost 0.15 ms instead +//! of 181 ms, which turned the head start it had accidentally been giving the +//! opening `didOpen` into a genuine race and made the first useful answer of +//! a warm session bimodal. Staging removes the scan rather than the race: +//! there is one scan, it runs at the settings the client actually wants, and +//! the opening burst is answered *inside* it exactly as +//! `docs/features/scan-interleave/README.md` has always answered the startup +//! scan's own arrivals. +//! +//! The bound below is what a client that advertised +//! `workspace/configuration` and then never answers costs: after it, the scan +//! runs at the defaults exactly as it used to, and an answer that turns up +//! afterwards is an ordinary settings change with an ordinary rescan behind +//! it. See `docs/features/perf5-p4/README.md` §P4b2 and +//! `docs/features/folders-and-config/README.md`. + +use std::collections::{HashMap, HashSet}; +use std::time::{Duration, Instant}; + +use lsp_server::{Connection, Message}; + +use super::batch::{burst, forward}; +use super::{ClientAbilities, Pending, Server}; +use crate::settings::ClientSettings; +use crate::state::Workspace; + +/// How long a startup waits for the client's `workspace/configuration` +/// answer before scanning at the defaults. +/// +/// **Not a budget — a bound on a client that never answers.** The round trip +/// itself is single-digit milliseconds: §P4a measured the whole of it, +/// including the empty scan that used to run in front of it, at 27–85 ms, and +/// with that scan gone what is left is the client's own reply. Two seconds is +/// therefore two orders of magnitude of slack for a slow client, and still +/// short enough that a client which advertised the capability and then says +/// nothing does not leave a workspace unindexed. +pub(super) const CONFIGURATION_WAIT: Duration = Duration::from_secs(2); + +/// Everything a session starts with that is not the connection or the roots. +/// +/// One struct rather than six more parameters: `started` is the seam every +/// test starts a session from, and the two fields only a test ever sets +/// ([`Startup::queued`] and [`Startup::wait`]) would otherwise be positional +/// arguments nobody can read at the call site. +pub(super) struct Startup { + /// What the client said it can do, read once at `initialize`. + pub(super) abilities: ClientAbilities, + /// Settings already in hand. Only a test has any this early: one whose + /// subject is not the scope says so here rather than driving a + /// `didChangeConfiguration` and then reasoning about the extra rescan it + /// buys. + pub(super) client: ClientSettings, + /// `initializationOptions.storagePath` — where the persistent index cache + /// goes. + pub(super) storage: Option, + /// `--verbose`: whether every operation says how long it took. + pub(super) verbose: bool, + /// What the client had already sent when the server was built — the + /// opening burst, put straight onto the queue the wait and the startup + /// scan drain. Empty for [`Server::new`]; a test fills it because racing + /// the forwarder thread for it would make the test a coin toss rather + /// than a check. + pub(super) queued: Vec, + /// How long to wait for the settings answer before scanning at the + /// defaults. [`CONFIGURATION_WAIT`] in a real session; a test says what + /// it means to test, and `Duration::ZERO` is the client that never + /// answers. + pub(super) wait: Duration, +} + +impl Server { + /// The server, with its first index built. + /// + /// The startup scan runs at the settings the client answered a + /// `workspace/configuration` with — asked first thing and waited for, up + /// to [`CONFIGURATION_WAIT`]. A client that cannot be asked, or that does + /// not answer inside the bound, gets the scan at the **defaults** + /// (including the folder scope) exactly as every client did before + /// 2026-09-08, and pays one extra rescan if its settings land later. + pub fn new( + connection: Connection, + roots: Vec, + abilities: ClientAbilities, + storage: Option, + verbose: bool, + ) -> Server { + let startup = Startup { + abilities, + client: ClientSettings::default(), + storage, + verbose, + queued: Vec::new(), + wait: CONFIGURATION_WAIT, + }; + Server::started(connection, roots, startup) + } + + /// A server that owns nothing yet: no index, no settings, no roots — only + /// its connection, what the client can do, and the queue its messages are + /// already arriving on. + /// + /// The forwarder starts here rather than in `run` because both the + /// settings wait and the startup scan answer whatever the client has + /// already sent, and they can only do that off a queue that is already + /// being filled. `queued` is what a test says the client had sent by then. + fn empty( + connection: Connection, + abilities: ClientAbilities, + verbose: bool, + queued: Vec, + ) -> Server { + let (forwarded, queue) = forward(&connection); + for message in queued { + let _ = forwarded.send(message); + } + Server { + connection, + workspace: Workspace::default(), + config_warnings: HashSet::new(), + lint_config_problems: std::cell::RefCell::default(), + said_lint_names: Vec::new(), + abilities, + watchers: None, + registrations: 0, + request_ids: 0, + pending: HashMap::new(), + generation: 0, + hierarchy_revision: 0, + tokens: HashMap::new(), + token_results: 0, + indexings: 0, + dirty: Vec::new(), + queue, + scanning: false, + head_owed: false, + staging: false, + rescan_wanted: false, + answering_a_rescan: false, + stopped: false, + held: Vec::new(), + verbose, + born: Instant::now(), + } + } + + /// [`Server::new`] with everything spelled out — the seam the tests start + /// a session from. + pub(super) fn started( + connection: Connection, + roots: Vec, + startup: Startup, + ) -> Server { + let Startup { abilities, client, storage, verbose, queued, wait } = startup; + let mut server = Server::empty(connection, abilities, verbose, queued); + // Nothing has been built yet, so there is no rebuild to owe: the + // `true` this returns for a non-default `client` is the rebuild that + // is about to happen anyway. + let _ = server.workspace.set_client_settings(client); + // Before the first build, because it is one rung of the ladder that + // decides where that build reads its cache from + // (`docs/features/index-persistence/README.md`). + server.workspace.set_storage_path(storage); + server.workspace.adopt_roots(roots); + // The earliest legal moment for anything server-initiated: `main` + // builds this only after `initialize_finish`, which returns once the + // client's `initialized` notification has arrived — and consumes it, + // so the loop below never sees one to hang these off instead. + server.stage_for_configuration(wait); + if server.stopped { + return server; + } + // The first index build is the slowest one of the session, so it gets + // the same bar every later rescan gets. And it answers messages while + // it runs — the ones the wait above set aside included — which is what + // stops the first request of a session waiting out the whole scan + // (`docs/features/scan-interleave/README.md`). Everything below it is + // therefore reached with the client's opening burst already handled — + // and skipped altogether if that burst shut the server down. + let warnings = server.scan_until_settled(false); + if server.stopped { + return server; + } + server.hierarchy_index_changed(); + // A buffer can be *opened* before or during the startup scan, and what + // was published for it then was computed against a half-built index. + // This is the same debt a rescan pays at the end of `reindex`, owed + // here for the first time because before scan-interleave no buffer + // could exist at this point. Nothing at all is sent when nothing is + // open, which is every session whose client did not get a `didOpen` + // in edgeways. + if !server.workspace.open_uris().is_empty() { + server.refresh_code_lenses(); + server.generation += 1; + for uri in server.workspace.open_uris() { + server.publish(&uri); + } + } + server.report_scope(warnings); + server.register_watchers(); + server + } + + /// Ask the client for its settings and hold everything until they arrive, + /// so the one startup scan runs at the scope the client actually wants. + /// + /// Silent for a client that never advertised `workspace/configuration`: + /// that one is only ever *pushed* settings, so there is nothing to wait + /// for and the scan runs at the defaults immediately, byte for byte as it + /// always has. + /// + /// [`Server::staging`] is what makes the window safe. While it is set, + /// every rescan trigger a message pulls — a `didOpen` that widened the + /// scope, a pushed setting, a save — records that one more scan is wanted + /// instead of running one, and [`Server::must_wait`] holds every request. + /// Clearing `rescan_wanted` afterwards is not dropping those asks: the + /// scan about to run is the session's **first**, it resolves the scope + /// afresh and reads every file in it from disk, and it runs at the + /// settings that have just landed — so it is what every one of them was + /// asking for. + fn stage_for_configuration(&mut self, wait: Duration) { + if !self.abilities.configuration { + return; + } + self.staging = true; + self.request_configuration(); + self.await_configuration(wait); + self.staging = false; + self.rescan_wanted = false; + } + + /// Read the client's messages until it answers the settings pull, the + /// bound runs out, or it goes away. + /// + /// **The bound is observed on the receive itself.** `recv_timeout` with + /// whatever is left of it blocks in the transport, wakes on the next + /// message, and returns `Timeout` at the deadline — so there is no poll, + /// no busy-wait and no clock the loop has to be woken to read. A client + /// that answers late is not stranded: its answer arrives in `run` as an + /// ordinary `Message::Response`, goes through the same `configured` → + /// `apply_settings` it always did, and costs the one rescan a settings + /// change has always cost — under the order contract, held requests and + /// all. + fn await_configuration(&mut self, wait: Duration) { + if wait.is_zero() { + return; + } + let asked = Instant::now(); + while self.pending.values().any(|p| matches!(p, Pending::Configuration(_))) { + let Some(left) = wait.checked_sub(asked.elapsed()) else { return }; + let Ok(message) = self.queue.recv_timeout(left) else { return }; + let batch = burst(&self.queue, message); + // A `shutdown` in the burst has already been through + // `handle_shutdown` by the time this returns `Ok(true)`; + // `started` then returns without scanning at all. + self.stopped = !matches!(self.process_batch(batch), Ok(false)); + if self.stopped { + return; + } + self.take_the_answer_out_of_held(); + } + } + + /// Apply a settings answer that a held request took down with it. + /// + /// **Measured, not theorised** (2026-09-08): without this, one warm + /// session in three waited the whole two-second bound and then rescanned, + /// because `process_batch` moves *everything behind* a request that must + /// wait into `held` — the rule that keeps a burst's arrival order intact + /// across the wait — and the client's answer to the pull can be in that + /// burst behind the editor's opening `textDocument/definition`. Left + /// there, the loop above sees the pull still outstanding and blocks until + /// the bound, which is the opposite of what staging is for. + /// + /// Reordering it is sound because that rule is about the **client's** + /// message stream. The answer to a request the *server* sent is not part + /// of it: the client replies to a pull from wherever it handles + /// server-initiated requests, and no ordering promise ties that reply to a + /// request the editor happened to send at the same moment. Only a + /// `Pending::Configuration` answer is taken — everything else in `held`, + /// requests included, keeps its place and its order. + fn take_the_answer_out_of_held(&mut self) { + let waiting = std::mem::take(&mut self.held); + let mut answers = Vec::new(); + for message in waiting { + match message { + Message::Response(response) + if matches!( + self.pending.get(&response.id), + Some(Pending::Configuration(_)) + ) => + { + answers.push(response); + } + kept => self.held.push(kept), + } + } + for answer in answers { + self.response(answer); + } + } +} diff --git a/crates/lucisv_server/src/server/tests/mod.rs b/crates/lucisv_server/src/server/tests/mod.rs index 8578a8d..5e535d9 100644 --- a/crates/lucisv_server/src/server/tests/mod.rs +++ b/crates/lucisv_server/src/server/tests/mod.rs @@ -10,6 +10,7 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; +use std::time::Duration; use lsp_server::{Notification, Request, Response}; use lsp_types::notification::{ @@ -39,7 +40,9 @@ use serde_json::Value; use super::batch::{is_shutdown, widen_of, Widen}; use super::progress::{reports, MAX_REPORTS}; +use super::startup::{Startup, CONFIGURATION_WAIT}; use super::*; +use crate::settings::ClientSettings; use crate::uri::path_to_uri; use crate::{design_hierarchy, diagnostics, format, lens, pairs, ports}; @@ -58,6 +61,7 @@ mod requests; mod scan; mod scan_trace; mod settings; +mod startup; mod sync; mod tokens; mod watchers; @@ -88,7 +92,11 @@ impl Tree { } fn write(&self, rel: &str, text: &str) { - std::fs::write(self.path.join(rel), text).expect("write"); + let path = self.path.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("parent"); + } + std::fs::write(&path, text).expect("write"); } } @@ -160,8 +168,21 @@ impl Session { // this module counts the messages a session produces, and the // timing lines are tested where they are observable as protocol // traffic — `tests/e2e.rs`, against the real binary and its flag. - let server = - Server::started(server_end, roots, abilities, settings, storage, false, Vec::new()); + // + // `wait: ZERO` is the client that never answers the settings pull: + // the request goes out and the startup scan runs at what this + // harness already put in `settings`, which is what every session in + // this module was before the startup was staged. The staging itself + // is tested in `startup.rs`, where the answer is queued. + let startup = Startup { + abilities, + client: settings, + storage, + verbose: false, + queued: Vec::new(), + wait: Duration::ZERO, + }; + let server = Server::started(server_end, roots, startup); Session { server, client } } @@ -188,10 +209,46 @@ impl Session { for message in on_the_wire { client.sender.send(message).expect("the client's wire traffic"); } - let server = Server::started(server_end, roots, abilities, settings, None, false, queued); + let startup = Startup { + abilities, + client: settings, + storage: None, + verbose: false, + queued, + wait: Duration::ZERO, + }; + let server = Server::started(server_end, roots, startup); Session { server, client } } + /// A session whose startup is **staged**: the settings pull goes out + /// first and the startup scan waits `wait` for the answer + /// (`server/startup.rs`). `queued` is what the client had already sent + /// when the server was built — the answer among it, for a client that + /// answers. + /// + /// The settings start at the defaults, which is the whole point: what a + /// staged session indexes is what the *answer* said, not what a test put + /// in ahead of it. + fn staged( + roots: Vec, + abilities: ClientAbilities, + verbose: bool, + wait: Duration, + queued: Vec, + ) -> Session { + let (server_end, client) = Connection::memory(); + let startup = Startup { + abilities, + client: ClientSettings::default(), + storage: None, + verbose, + queued, + wait, + }; + Session { server: Server::started(server_end, roots, startup), client } + } + /// [`Session::wide`] against a client that spawned the server with /// `--verbose` — the only sessions that are ever told what a scan spent /// its time on (`docs/features/perf5-p4/README.md`). @@ -201,15 +258,15 @@ impl Session { ..Default::default() }; let (server_end, client) = Connection::memory(); - let server = Server::started( - server_end, - roots, - ClientAbilities::default(), - wide, + let startup = Startup { + abilities: ClientAbilities::default(), + client: wide, storage, - true, - Vec::new(), - ); + verbose: true, + queued: Vec::new(), + wait: Duration::ZERO, + }; + let server = Server::started(server_end, roots, startup); Session { server, client } } diff --git a/crates/lucisv_server/src/server/tests/scan.rs b/crates/lucisv_server/src/server/tests/scan.rs index c80c53e..90461e3 100644 --- a/crates/lucisv_server/src/server/tests/scan.rs +++ b/crates/lucisv_server/src/server/tests/scan.rs @@ -17,7 +17,7 @@ fn workspace_of(tag: &str, files: usize) -> Tree { } /// A `workspace/symbol` request over the wire, by id. -fn symbol_request(id: i32, query: &str) -> Message { +pub(super) fn symbol_request(id: i32, query: &str) -> Message { Message::Request(Request::new( RequestId::from(id), WorkspaceSymbolRequest::METHOD.to_string(), @@ -28,7 +28,7 @@ fn symbol_request(id: i32, query: &str) -> Message { /// Where the indexing bar's `end` sits among everything the server said, /// and where the response to `id` sits. `None` for either if it never /// came. -fn positions(messages: &[Message], id: i32) -> (Option, Option) { +pub(super) fn positions(messages: &[Message], id: i32) -> (Option, Option) { let ended = messages.iter().position(|message| { matches!(message, Message::Notification(n) if n.method == Progress::METHOD && n.params["value"]["kind"] == "end") diff --git a/crates/lucisv_server/src/server/tests/scan_trace.rs b/crates/lucisv_server/src/server/tests/scan_trace.rs index 02382a8..e6cc1fa 100644 --- a/crates/lucisv_server/src/server/tests/scan_trace.rs +++ b/crates/lucisv_server/src/server/tests/scan_trace.rs @@ -7,7 +7,7 @@ use super::*; /// A tree of `files` one-package files. -fn trace_tree(tag: &str, files: usize) -> Tree { +pub(super) fn trace_tree(tag: &str, files: usize) -> Tree { let tree = Tree::new(tag); for n in 0..files { tree.package(&format!("t{n:03}.sv"), &format!("t{n:03}")); @@ -16,7 +16,7 @@ fn trace_tree(tag: &str, files: usize) -> Tree { } /// Every `timing: scan …` line the server has said since the last drain. -fn scan_lines(session: &Session) -> Vec { +pub(super) fn scan_lines(session: &Session) -> Vec { session .logged() .into_iter() @@ -28,13 +28,13 @@ fn scan_lines(session: &Session) -> Vec { /// Whether a log line is one of a scan's three trace lines — `timing: scan /// …` — rather than the `scan started`/`scan finished` pair the /// verbose-timing feature already had. -fn is_trace_line(text: &str) -> bool { +pub(super) fn is_trace_line(text: &str) -> bool { let Some(rest) = text.strip_prefix("timing: scan ") else { return false }; rest.split_whitespace().next().is_some_and(|word| word.parse::().is_ok()) } /// The one line of `lines` whose prefix says it is that kind. -fn line_of(lines: &[String], kind: &str) -> String { +pub(super) fn line_of(lines: &[String], kind: &str) -> String { lines .iter() .find(|line| line.contains(&format!(" {kind} ("))) @@ -43,7 +43,7 @@ fn line_of(lines: &[String], kind: &str) -> String { } /// The value of `key=` on a `key=value` line, as text. -fn field<'a>(line: &'a str, key: &str) -> &'a str { +pub(super) fn field<'a>(line: &'a str, key: &str) -> &'a str { let at = line.find(&format!("{key}=")).unwrap_or_else(|| panic!("no {key} on {line}")); let rest = &line[at + key.len() + 1..]; rest.split_whitespace().next().unwrap_or("") @@ -135,6 +135,11 @@ fn the_stages_add_up_to_the_scan_they_describe() { let named = [ "discovery", "order", + // Since 2026-09-08 a scan reads a file's text at the step that indexes + // it, so what `discovery` used to spend on reading the whole scope is + // this stage instead — and a list without it accounts for a fifth of + // the scan (`docs/features/perf5-p4/README.md` §P4b3). + "read", "cache_open", "lookup", "decode", @@ -184,3 +189,100 @@ fn a_rescan_is_a_second_scan_with_its_own_three_lines() { let counts = line_of(&second, "counts"); assert_eq!(field(&counts, "read"), "7", "the exclusion is one file fewer"); } + +/// A `--verbose` session at the **default** settings, against a client that +/// cannot be asked for its settings at all — the shape every pre-2026-08-27 +/// editor starts in, and the one the startup staging leaves untouched +/// (`server/startup.rs`). There is nothing to wait for, so the startup scan +/// runs immediately at the defaults: with no buffer open its folder scope is +/// empty and so is its work list. +fn verbose_default(roots: Vec, storage: Option) -> Session { + let (server_end, client) = Connection::memory(); + let startup = Startup { + abilities: ClientAbilities::default(), + client: ClientSettings::default(), + storage, + verbose: true, + queued: Vec::new(), + wait: Duration::ZERO, + }; + let server = Server::started(server_end, roots, startup); + Session { server, client } +} + +/// Ask for `lucisv.index.scope: "workspace"`, which is the rescan the pulled +/// configuration asks for in a real session. +fn widen_to_the_workspace(session: &mut Session) { + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { "index": { "scope": "workspace" } } } }), + ); +} + +#[test] +fn a_startup_scan_with_no_files_opens_no_store_and_a_warm_rescan_rewrites_none() { + // §P4b, both halves, over the real dispatch. + // + // **(b1)** the startup scan indexes nothing, so it opens nothing: warm it + // used to read a 44 MiB store and rewrite it byte-identically, 184 ms of + // a 1.33 s start, for a scan with no files in it. **(a)** the configured + // rescan behind it hits every record, appends nothing, and so would + // rewrite the store it just read into itself — which it no longer does. + let tree = trace_tree("traceemptyscan", 9); + let storage = std::env::temp_dir().join(format!("lucisv_trace_empty_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&storage); + let store = storage.join("index-cache"); + + // Cold: scan 1 is empty and touches nothing, scan 2 fills the store. + let mut cold = verbose_default(vec![tree.path.clone()], Some(storage.clone())); + let first = line_of(&scan_lines(&cold), "counts"); + assert_eq!(field(&first, "read"), "0", "premise: the startup scan indexes nothing"); + assert_eq!(field(&first, "opens"), "0", "and so reads no store"); + assert_eq!(field(&first, "compactions"), "0", "and rewrites none"); + assert!(!store.exists(), "a scan with no files does not even create one"); + + widen_to_the_workspace(&mut cold); + let filled = line_of(&scan_lines(&cold), "counts"); + assert_eq!(field(&filled, "read"), "9", "the configured rescan indexes the tree"); + assert_eq!(field(&filled, "opens"), "1", "which does open the store"); + assert_eq!(field(&filled, "records"), "9"); + assert_eq!(field(&filled, "compactions"), "1", "a session that appended must rewrite"); + drop(cold); + + let bytes = std::fs::read(&store).expect("a store"); + let stamp = std::fs::metadata(&store).expect("meta").modified().expect("mtime"); + + // Warm: the same two scans, and neither writes a byte — with a buffer + // open, which is the shape a real session has. An open buffer is indexed + // from its own analysis and writes its record through on every scan, and + // that write-through is what would otherwise put a duplicate line in the + // store and owe the rewrite back. + let mut warm = verbose_default(vec![tree.path.clone()], Some(storage.clone())); + let empty = line_of(&scan_lines(&warm), "counts"); + assert_eq!(field(&empty, "read"), "0"); + assert_eq!(field(&empty, "opens"), "0", "still no store read for a scan with no files"); + assert_eq!(field(&empty, "compactions"), "0"); + + let opened = tree.path.join("t000.sv"); + let text = std::fs::read_to_string(&opened).expect("read"); + warm.open(&opened, &text); + let _ = scan_lines(&warm); + + widen_to_the_workspace(&mut warm); + let warmed = line_of(&scan_lines(&warm), "counts"); + assert_eq!(field(&warmed, "hits"), "8", "every file but the buffer came out of the store"); + 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"); + assert_eq!(field(&warmed, "compactions"), "0", "and the rewrite would have been identical"); + drop(warm); + + assert_eq!(std::fs::read(&store).expect("a store"), bytes, "not one byte of the store moved"); + assert_eq!( + std::fs::metadata(&store).expect("meta").modified().expect("mtime"), + stamp, + "and the file was not touched at all" + ); + let _ = std::fs::remove_dir_all(&storage); +} diff --git a/crates/lucisv_server/src/server/tests/settings.rs b/crates/lucisv_server/src/server/tests/settings.rs index 35453f3..1ede026 100644 --- a/crates/lucisv_server/src/server/tests/settings.rs +++ b/crates/lucisv_server/src/server/tests/settings.rs @@ -26,12 +26,18 @@ fn a_client_that_can_be_asked_is_asked_for_its_settings_at_startup() { } #[test] -fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() { - // `Server::new` calls `register_watchers` and then - // `request_configuration`, in that order — this pins it on the actual - // wire rather than trusting the call order in the source. Every - // outgoing request's id is `lucisv-{n}` off one monotonically - // increasing counter, so the numeric suffix *is* the send order. +fn the_startup_pull_is_the_first_thing_on_the_wire() { + // **Amended 2026-09-08 (§P4b2).** This used to pin the opposite order: + // `Server::new` registered the watchers and *then* asked for the + // settings, because the startup scan ran in front of both and the + // answer could not have changed it. Staging the scan reverses that — + // the pull is now the first thing a session sends, because the scan is + // waiting on its answer to know which scope to run at + // (`server/startup.rs`). The claim the test makes is unchanged in kind: + // the order is pinned on the actual wire rather than trusted from the + // call order in the source. Every outgoing request's id is `lucisv-{n}` + // off one monotonically increasing counter, so the numeric suffix *is* + // the send order. // QA (2026-08-27): pinned per the dev's own review checklist item // ("verify on the wire"). let tree = Tree::new("pulloraftwatch"); @@ -46,7 +52,8 @@ fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() { }; let watchers = index_of(RegisterCapability::METHOD); let pull = index_of(WorkspaceConfiguration::METHOD); - assert!(watchers < pull, "watcher registration must precede the pull: {sent:#?}"); + assert_eq!(pull, 0, "the pull precedes everything, watchers included: {sent:#?}"); + assert!(pull < watchers, "including the watcher registration: {sent:#?}"); let numeric_suffix = |request: &Request| -> u32 { request @@ -57,9 +64,10 @@ fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() { .parse() .unwrap_or_else(|_| panic!("not a lucisv-N id: {:?}", request.id)) }; + assert_eq!(numeric_suffix(&sent[pull]), 0, "and it takes the first id: {sent:#?}"); assert!( - numeric_suffix(&sent[watchers]) < numeric_suffix(&sent[pull]), - "the pull's id must be issued after the watcher registration's: {sent:#?}" + numeric_suffix(&sent[pull]) < numeric_suffix(&sent[watchers]), + "the watcher registration's id must be issued after the pull's: {sent:#?}" ); } diff --git a/crates/lucisv_server/src/server/tests/startup.rs b/crates/lucisv_server/src/server/tests/startup.rs new file mode 100644 index 0000000..42e58bb --- /dev/null +++ b/crates/lucisv_server/src/server/tests/startup.rs @@ -0,0 +1,529 @@ +//! The staged startup (`server/startup.rs`): the settings pull goes out +//! first, the one scan runs at the scope the answer decided, and a client +//! that never answers is bounded rather than waited on for ever. +//! +//! Eight claims, one test each, all on the wire: one scan for a client that +//! answers, the bounded fallback and the late answer's ordinary rescan for +//! one that does not, a `didOpen` that beats the answer folded into that one +//! scan (its own file first in the work list), a request that beats it +//! answered *inside* the scan rather than after it, a client that cannot be +//! asked at all left exactly as it was, and a settings answer stranded behind +//! a held request taken back out of it. +//! +//! Two of them are §P4b3's (`docs/features/perf5-p4/README.md`): the request +//! that beats the answer is answered **from the user's own folder** rather +//! than off the alphabet, whichever of the two the `didOpen` and the answer +//! arrives first. + +use std::time::Instant; + +use super::scan::{positions, symbol_request}; +use super::scan_trace::{field, is_trace_line, line_of, trace_tree}; +use super::*; + +/// A client that answers `workspace/configuration` and is told what a scan +/// spent its time on. +fn pulling() -> ClientAbilities { + ClientAbilities { configuration: true, ..Default::default() } +} + +/// A client that also renders the indexing bar, so the mid-scan ordering of +/// an answer is observable. +fn pulling_with_a_bar() -> ClientAbilities { + ClientAbilities { configuration: true, work_done_progress: true, ..Default::default() } +} + +/// The client's answer to the startup settings pull. +/// +/// The id is `lucisv-0` because the pull is the **first** request a staged +/// session makes of its client: `stage_for_configuration` runs before the +/// scan, and therefore before the progress `create`, the watcher +/// registration and the lens refresh that used to be issued ahead of it. +/// `send_request` numbers off one counter that only ever goes up, so that +/// first id is a fact about the order, not a guess. +fn configuration_answer(section: Value) -> Message { + Message::Response(Response::new_ok( + RequestId::from("lucisv-0".to_string()), + serde_json::json!([section]), + )) +} + +/// `lucisv.index.scope: "workspace"` — the answer that used to cost a whole +/// second scan, plus the per-file log that makes the work list's order +/// readable. +fn the_whole_workspace() -> Value { + serde_json::json!({ "index": { "scope": "workspace", "logFiles": true } }) +} + +/// A `textDocument/didOpen` over the wire, as the client sends it. +fn did_open(path: &Path, text: &str) -> Message { + Message::Notification(Notification::new( + DidOpenTextDocument::METHOD.to_string(), + serde_json::json!({ + "textDocument": { + "uri": path_to_uri(path).expect("uri"), + "languageId": "systemverilog", + "version": 1, + "text": text, + } + }), + )) +} + +/// Every `timing: scan …` trace line among `messages` — [`scan_lines`] over +/// a drain that has already happened, because a drain is destructive and +/// these tests ask two questions of one session. +fn trace_lines(messages: &[Message]) -> Vec { + messages + .iter() + .filter_map(|message| match message { + Message::Notification(n) if n.method == LogMessage::METHOD => { + let params: LogMessageParams = + serde_json::from_value(n.params.clone()).expect("log message params"); + Some(params.message) + } + _ => None, + }) + .filter(|text| is_trace_line(text)) + .collect() +} + +/// Every log line, trace lines included — where the per-file `indexing:` +/// and `analyzed:` lines are read from. +fn log_lines(messages: &[Message]) -> Vec { + messages + .iter() + .filter_map(|message| match message { + Message::Notification(n) if n.method == LogMessage::METHOD => { + let params: LogMessageParams = + serde_json::from_value(n.params.clone()).expect("log message params"); + Some(params.message) + } + _ => None, + }) + .collect() +} + +/// The methods of the requests the server made, in send order. +fn asked(messages: &[Message]) -> Vec { + messages + .iter() + .filter_map(|message| match message { + Message::Request(request) => Some(request.method.clone()), + _ => None, + }) + .collect() +} + +#[test] +fn a_client_that_answers_pays_one_scan_at_the_scope_it_asked_for() { + // The whole of the change, in one assertion. Before 2026-09-08 this + // session ran **two** scans: an empty one at the default folder scope, + // because nothing could be known about the client's settings until the + // pull it had not yet been sent came back, and then the configured + // rescan behind it. Now the pull goes first and there is one scan. + let tree = trace_tree("stagedone", 9); + let session = Session::staged( + vec![tree.path.clone()], + pulling(), + true, + CONFIGURATION_WAIT, + vec![configuration_answer(the_whole_workspace())], + ); + let said = session.drain(); + let lines = trace_lines(&said); + assert_eq!(lines.len(), 3, "one scan, three trace lines: {lines:#?}"); + for line in &lines { + assert!(line.starts_with("timing: scan 1 "), "no second scan ran: {line}"); + assert!(line.contains("whole"), "and it is the startup scan: {line}"); + } + let counts = line_of(&lines, "counts"); + assert_eq!(field(&counts, "read"), "9", "the one scan read the configured scope"); + assert_eq!(session.server.workspace.index().files().len(), 9); + + // And the pull really did go out ahead of everything else the startup + // sends — the order the id in `configuration_answer` depends on. + let methods = asked(&said); + assert_eq!( + methods.first().map(String::as_str), + Some(WorkspaceConfiguration::METHOD), + "the settings pull is the first thing a staged session asks: {methods:#?}" + ); +} + +#[test] +fn a_client_that_never_answers_is_bounded_and_then_scanned_at_the_defaults() { + // The fallback, and the shipped bound it is measured against. Two + // seconds is not a budget — the round trip is single-digit + // milliseconds — it is what a client that advertised the capability and + // then says nothing costs, once, before the workspace is indexed anyway. + assert_eq!( + CONFIGURATION_WAIT, + Duration::from_secs(2), + "the shipped bound, which no test may quietly move" + ); + let tree = trace_tree("stagednever", 9); + let bound = Duration::from_millis(120); + let began = Instant::now(); + let mut session = Session::staged(vec![tree.path.clone()], pulling(), true, bound, Vec::new()); + let waited = began.elapsed(); + assert!(waited >= bound, "the bound is waited out, not skipped: {waited:?}"); + + let said = session.drain(); + let lines = trace_lines(&said); + assert_eq!(lines.len(), 3, "one scan, not none and not two: {lines:#?}"); + let counts = line_of(&lines, "counts"); + assert_eq!( + field(&counts, "read"), + "0", + "at the defaults — the folder scope, which with no buffer open is empty" + ); + let (id, _) = { + let asked: Vec<&Message> = said + .iter() + .filter( + |m| matches!(m, Message::Request(r) if r.method == WorkspaceConfiguration::METHOD), + ) + .collect(); + assert_eq!(asked.len(), 1, "asked once, not once per retry: {asked:#?}"); + let Message::Request(request) = asked[0] else { unreachable!("filtered above") }; + (request.id.clone(), request.params.clone()) + }; + + // The late answer is an ordinary settings change: it costs the one + // rescan a changed scope has always cost, and — this is the order + // contract, unchanged — a request behind it in the same burst is held + // rather than answered off the half-updated index. + let answer = + Message::Response(Response::new_ok(id, serde_json::json!([the_whole_workspace()]))); + session.batch(vec![answer, symbol_request(7, "t000")]); + let said = session.drain(); + let lines = trace_lines(&said); + assert_eq!(lines.len(), 3, "the late answer's rescan, and only it: {lines:#?}"); + for line in &lines { + assert!(line.starts_with("timing: scan 2 "), "the second scan of the session: {line}"); + } + assert_eq!(field(&line_of(&lines, "counts"), "read"), "9", "which indexed the whole tree"); + let rescanned = said + .iter() + .rposition(|message| match message { + Message::Notification(n) if n.method == LogMessage::METHOD => { + n.params["message"].as_str().is_some_and(|text| text.starts_with("timing: scan 2 ")) + } + _ => false, + }) + .expect("the rescan traced itself"); + let answered = positions(&said, 7).1.expect("the request behind it is still answered"); + assert!( + rescanned < answered, + "the request waits the rescan out rather than being answered off the index it was \ + sent into: {said:#?}" + ); +} + +#[test] +fn a_did_open_that_beats_the_answer_is_folded_into_the_one_scan_and_indexed_first() { + // A `didOpen` arriving while the settings are in flight widens the + // folder scope, which before this would have been its own scan. Staged, + // there is nothing to widen *into* yet: the buffer is installed, the one + // scan that follows resolves the scope with it in place, and + // `open_first` puts the user's own file at the head of its work list. + let tree = trace_tree("stagedopen", 9); + let opened = tree.path.join("t005.sv"); + let text = std::fs::read_to_string(&opened).expect("read"); + let session = Session::staged( + vec![tree.path.clone()], + pulling(), + true, + CONFIGURATION_WAIT, + vec![did_open(&opened, &text), configuration_answer(the_whole_workspace())], + ); + let said = session.drain(); + let lines = trace_lines(&said); + assert_eq!(lines.len(), 3, "the widen is the scan, not a scan of its own: {lines:#?}"); + for line in &lines { + assert!(line.starts_with("timing: scan 1 "), "{line}"); + } + let counts = line_of(&lines, "counts"); + assert_eq!(field(&counts, "read"), "9", "the configured scope, in one pass"); + assert_eq!(field(&counts, "buffers"), "1", "with the buffer indexed from its own analysis"); + + // Open first: the per-file log the answer switched on names the work + // list in order, and the user's file is at the head of it. + let files: Vec = log_lines(&said) + .into_iter() + .filter(|line| line.starts_with("indexing: ") || line.starts_with("analyzed: ")) + .collect(); + let first = files.first().expect("the scan logged its files"); + assert!( + first.ends_with("t005.sv"), + "the open buffer is indexed first, not when the alphabet reaches it: {files:#?}" + ); + + // And the buffer's diagnostics were published against the finished + // index — the debt `started` pays at the end of construction. + let uri = path_to_uri(&opened).expect("uri"); + let published: Vec<&Message> = said + .iter() + .filter(|m| matches!(m, Message::Notification(n) if n.method == PublishDiagnostics::METHOD)) + .collect(); + assert!( + published.iter().any(|message| { + let Message::Notification(n) = message else { return false }; + n.params["uri"] == serde_json::json!(uri) + }), + "the opened buffer is published: {published:#?}" + ); +} + +#[test] +fn a_request_that_beats_the_answer_is_answered_inside_the_startup_scan() { + // The regression §P4b named, closed. A definition sent before the + // settings answer used to be held behind the *configured rescan* — + // `must_wait`'s first clause — and waited the whole of it out, which on + // opentitan was 0.9 s warm. Staged, the scan it waits for is the + // **startup** scan: nothing was queued ahead of it, the session has no + // prior index and therefore no `gone`, and it is answered mid-way off + // the published prefix exactly as a request arriving during that scan + // is. The only ordering a test can check without a stopwatch is that + // the response goes out before the bar comes down. + let tree = trace_tree("stagedrequest", INTERLEAVE_ABOVE + 6); + let opened = tree.path.join("t005.sv"); + let text = std::fs::read_to_string(&opened).expect("read"); + let uri = path_to_uri(&opened).expect("uri"); + let definition = Message::Request(Request::new( + RequestId::from(7), + GotoDefinition::METHOD.to_string(), + serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": 1, "character": 13 }, + }), + )); + let session = Session::staged( + vec![tree.path.clone()], + pulling_with_a_bar(), + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ "index": { "scope": "workspace" } })), + did_open(&opened, &text), + definition, + ], + ); + let said = session.drain(); + let (ended, answered) = positions(&said, 7); + let answered = answered.expect("the definition is answered at all"); + let ended = ended.expect("the bar comes down"); + assert!(answered < ended, "answered inside the scan, not after it: {said:#?}"); + + // And it is a real, coherent answer — the buffer's own `localparam K`, + // read off the prefix `open_first` put that file at the head of. + let Some(Message::Response(response)) = said.get(answered) else { + unreachable!("positions found a response there") + }; + let found = response.response_result.clone().expect("a result, not a failure"); + assert_eq!(found[0]["range"]["start"]["line"], 1, "{found}"); + assert_eq!(found[0]["uri"], serde_json::json!(uri), "{found}"); + + // One scan still, and it finished: nothing was traded for the latency + // but the completeness of that one answer. + assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 6); +} + +/// opentitan's shape in miniature: a testbench two folders below its block, +/// the module it instantiates in that block's `rtl/`, and enough unrelated +/// files ahead of both in the alphabet that a scan reaching them first would +/// have nothing useful to answer with. +fn a_block_and_a_crowd(tag: &str, padding: usize) -> Tree { + let tree = Tree::new(tag); + tree.write("ip/aes/rtl/aes.sv", "module aes;\n localparam K = 1;\nendmodule\n"); + tree.write("ip/aes/dv/tb/tb.sv", "module tb;\n aes dut ();\nendmodule\n"); + for n in 0..padding { + tree.package(&format!("crowd/p{n:03}.sv"), &format!("p{n:03}")); + } + tree +} + +#[test] +fn a_request_that_beats_the_answer_is_answered_from_the_users_own_folder() { + // **The §P4b2 regression, closed.** Staging made the first useful answer + // of a workspace-scoped session unimodal — and *empty*: the request was + // drained at the first interleave point, off a prefix holding the user's + // own buffer and nothing else, so the module it named was not in it yet. + // The work list now leads with the buffer's own **folder** and the drain + // waits for that folder, which is the answer the widen used to give + // (`docs/features/perf5-p4/README.md` §P4b3). + // + // `crowd/` sorts before `ip/`, so under plain path order the scan would + // reach 70 irrelevant files before `aes.sv` — this answer cannot come + // from the alphabet. + let tree = a_block_and_a_crowd("stagedfolderfirst", INTERLEAVE_ABOVE + 6); + let opened = tree.path.join("ip/aes/dv/tb/tb.sv"); + let text = std::fs::read_to_string(&opened).expect("read"); + let definition = Message::Request(Request::new( + RequestId::from(7), + GotoDefinition::METHOD.to_string(), + serde_json::json!({ + "textDocument": { "uri": path_to_uri(&opened).expect("uri") }, + "position": { "line": 1, "character": 3 }, + }), + )); + let session = Session::staged( + vec![tree.path.clone()], + pulling_with_a_bar(), + false, + CONFIGURATION_WAIT, + vec![ + configuration_answer(serde_json::json!({ "index": { "scope": "workspace" } })), + did_open(&opened, &text), + definition, + ], + ); + let said = session.drain(); + let (ended, answered) = positions(&said, 7); + let answered = answered.expect("the definition is answered at all"); + assert!(answered < ended.expect("the bar comes down"), "inside the scan: {said:#?}"); + + let Some(Message::Response(response)) = said.get(answered) else { + unreachable!("positions found a response there") + }; + let found = response.response_result.clone().expect("a result, not a failure"); + assert_eq!(found.as_array().map(Vec::len), Some(1), "one location, not none: {found}"); + assert_eq!( + found[0]["uri"], + serde_json::json!(path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri")), + "the module in the folder next door, which is what the user asked about: {found}" + ); + + // One scan still, and it finished over the whole workspace: the folder + // bought the answer's quality, not a smaller index. + assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 8); +} + +#[test] +fn a_did_open_answered_mid_scan_pulls_its_folder_in_front_of_the_request_behind_it() { + // **The case the opentitan measurement found, and the one an editor + // really produces.** The client's reader answers `workspace/configuration` + // from its own thread, so the answer usually beats the editor's `didOpen`: + // the scan begins with *no* buffer open, its work list is the plain + // alphabet, and the `didOpen` and the definition behind it arrive at an + // interleave point some way into it. Before this the definition was + // answered off that alphabet's prefix and came back `[]`. + // + // Now the burst's `didOpen` holds what is behind it (`Server::head_owed`), + // the work list is re-ordered around the buffer it installed, and the + // definition is answered once that folder has been indexed — which is + // exactly what the widen this `didOpen` used to trigger made it wait for. + // + // A client that cannot be asked for settings is the shortest way to a scan + // that has already started when the burst lands: nothing is staged, and + // the wide scope is given up front. + let tree = a_block_and_a_crowd("midscanopen", INTERLEAVE_ABOVE + 6); + let opened = tree.path.join("ip/aes/dv/tb/tb.sv"); + let text = std::fs::read_to_string(&opened).expect("read"); + let definition = Message::Request(Request::new( + RequestId::from(7), + GotoDefinition::METHOD.to_string(), + serde_json::json!({ + "textDocument": { "uri": path_to_uri(&opened).expect("uri") }, + "position": { "line": 1, "character": 3 }, + }), + )); + let session = Session::started_behind( + vec![tree.path.clone()], + watching_progress(), + wide_ish(), + Vec::new(), + vec![did_open(&opened, &text), definition], + ); + let said = session.drain(); + let (ended, answered) = positions(&said, 7); + let answered = answered.expect("the definition is answered at all"); + assert!(answered < ended.expect("the bar comes down"), "inside the scan: {said:#?}"); + + let Some(Message::Response(response)) = said.get(answered) else { + unreachable!("positions found a response there") + }; + let found = response.response_result.clone().expect("a result, not a failure"); + assert_eq!(found.as_array().map(Vec::len), Some(1), "one location, not none: {found}"); + assert_eq!( + found[0]["uri"], + serde_json::json!(path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri")), + "the module in the folder next door: {found}" + ); + assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 8); +} + +#[test] +fn a_client_that_cannot_be_asked_scans_at_once_exactly_as_it_always_did() { + // The other half of the gate. A client that never advertised + // `workspace/configuration` is only ever *pushed* settings, so there is + // nothing to wait for: the scan runs immediately at the defaults, and + // the trace lines say what they said before staging existed. The bound + // is the shipped one, so a session that waited on it would take two + // seconds — the elapsed check is what proves the gate rather than the + // bound. + let tree = trace_tree("stagednoconfig", 9); + let began = Instant::now(); + let session = Session::staged( + vec![tree.path.clone()], + ClientAbilities::default(), + true, + CONFIGURATION_WAIT, + Vec::new(), + ); + let took = began.elapsed(); + assert!(took < Duration::from_secs(1), "nothing was waited for: {took:?}"); + + let said = session.drain(); + assert!(asked(&said).is_empty(), "nothing is asked of this client: {said:#?}"); + let lines = trace_lines(&said); + assert_eq!(lines.len(), 3, "one startup scan: {lines:#?}"); + let counts = line_of(&lines, "counts"); + assert_eq!(field(&counts, "read"), "0", "at the defaults, as it always was"); + assert_eq!(field(&counts, "opens"), "0", "and §P4b's deferred store open is untouched"); + assert_eq!(field(&counts, "compactions"), "0"); +} + +#[test] +fn an_answer_behind_a_held_request_is_not_stranded_for_the_whole_bound() { + // **A defect this lane measured before it shipped** (2026-09-08). The + // editor's opening burst is `didOpen` then a request, and the client's + // reader can answer the settings pull into that same burst. The request + // must wait — there is no index yet — and `process_batch`'s order rule + // takes *everything behind it* into `held` with it, the answer included. + // The wait then saw the pull still outstanding and blocked the whole + // bound: one warm opentitan session in three took 2.1 s to its first + // useful answer instead of 0.39 s. The answer is taken back out; + // everything else in the burst keeps its place. + let tree = trace_tree("stagedstranded", 9); + let opened = tree.path.join("t005.sv"); + let text = std::fs::read_to_string(&opened).expect("read"); + let bound = Duration::from_secs(30); + let began = Instant::now(); + let session = Session::staged( + vec![tree.path.clone()], + pulling(), + true, + bound, + vec![ + did_open(&opened, &text), + symbol_request(7, "t000"), + configuration_answer(the_whole_workspace()), + ], + ); + let took = began.elapsed(); + assert!(took < Duration::from_secs(5), "the bound was not waited out: {took:?}"); + + let said = session.drain(); + let lines = trace_lines(&said); + assert_eq!(lines.len(), 3, "one scan, at the answered scope: {lines:#?}"); + assert_eq!(field(&line_of(&lines, "counts"), "read"), "9"); + // And the request is neither lost nor answered off an empty index: nine + // files are under `INTERLEAVE_ABOVE`, so this scan answers nothing + // mid-way and the request is still waiting for `run` to take it — which + // is the order rule it was held for, working exactly as it does for a + // short startup scan with nothing staged. + assert_eq!(positions(&said, 7).1, None, "a short scan answers nothing mid-way: {said:#?}"); + assert_eq!(session.server.held.len(), 1, "and the request is still owed an answer"); +} diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state/mod.rs similarity index 88% rename from crates/lucisv_server/src/state.rs rename to crates/lucisv_server/src/state/mod.rs index d818a6e..3143c02 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state/mod.rs @@ -16,7 +16,7 @@ use vlog_parser::defines::{collect_defines, DefineTable}; use vlog_parser::token::Token; use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic}; use vlog_semantic::{ - analyze, index_order, resolve_external, Def, ExternalResolutions, FileFacts, FileId, Semantics, + analyze, resolve_external, Def, ExternalResolutions, FileFacts, FileId, Semantics, WorkspaceIndex, }; @@ -25,13 +25,19 @@ use lucisv_core::walk::{collect_files, EXTENSIONS}; use crate::candidates::Candidates; use crate::convert::Positions; -use crate::includes::IncludeGraph; +use crate::includes::{self, IncludeGraph}; use crate::index_cache::IndexCache; use crate::module_select::{self, Reach}; use crate::rename_trace::{self, Rung, SelectionTrace, Wanted}; -use crate::scan_trace::ScanTrace; +use crate::scan_order::{self, WorkList}; + +mod scan; + +use crate::scan_trace::{CacheWork, ScanTrace}; use crate::settings::{ClientSettings, IndexScope}; use crate::uri::uri_to_path; +use scan::{Analyzed, HeldAnalyses, ScanKind, Sources}; +pub use scan::{IndexEvent, Scan}; /// How many `workspace/symbol` hits are returned. Each one costs a file read /// to turn its byte span into a line, so an unbounded answer to the empty @@ -278,186 +284,6 @@ struct Scope { warnings: Vec, } -/// A `Scope` with its files read: what one index rebuild works from. -struct Sources { - texts: Vec<(PathBuf, String)>, - /// What the open buffers among `texts` already know about themselves. - analyzed: Analyzed, - incdirs: Vec, - warnings: Vec, -} - -/// The index facts and the completion words of the entries `texts` took from an -/// **open buffer**, read off the analysis that buffer already holds. -/// -/// Both maps are filled in the same loop that lets a buffer override the disk -/// copy, so an entry here is always the analysis of exactly the text beside it -/// in `texts` — the two cannot describe different bytes. A file that is not an -/// open buffer appears in neither map and is parsed and lexed as it always was. -#[derive(Default)] -struct Analyzed { - facts: HashMap, - words: HashMap>, -} - -/// Whether a caller of `collect_sources` wants [`Analyzed`] filled in. -/// -/// An index rebuild does — it is what it indexes the open buffers from. A -/// refactoring reads the texts and nothing else, and reading a record off every -/// open buffer for it would be work nothing looks at. -#[derive(PartialEq, Eq)] -enum HeldAnalyses { - Wanted, - Unused, -} - -/// One workspace scan in flight: the work list it took when it began, and how -/// far through it the workspace has got. -/// -/// A value rather than a loop inside [`Workspace::rebuild_index_with`] because -/// the server answers the client's messages *between* two files of a scan -/// (`docs/features/scan-interleave/README.md`), and a message it answers needs -/// the very workspace the scan is feeding — which a callback called from -/// inside a `&mut self` loop can never be handed. Splitting the loop is what -/// puts the scan's state somewhere the message can be answered around. -pub struct Scan { - /// Whether this scan rebuilds the index or only folds newly-in-scope files - /// into it. The whole difference is in [`Workspace::finish_scan`]; every - /// step in between is the same code. - kind: ScanKind, - /// Every file this scan indexes and the text it had when the scan began, in - /// index order with the open buffers' own files first. For a widen that is - /// the newly-in-scope files plus the open buffers, not the whole scope. - work: Vec<(PathBuf, String)>, - /// Every file that is in scope once this scan lands, kept flat so the - /// include graph's known-file table can be relearned from a slice. Which - /// files *exist* is settled the moment the scope is resolved, so this never - /// moves while the scan runs — reordering the tail of `work` does not - /// reorder a set. Equal to `work`'s paths for a whole scan; for a widen it - /// is the index's files plus `work`'s. - paths: Vec, - /// What this scan takes *out* of the index, known before it starts. Empty - /// for a whole scan, which works out what left the scope from its own work - /// list once it has one ([`Workspace::finish_scan`]). - gone: Vec, - /// What the open buffers among `work` already knew about themselves, taken - /// from as each of them is reached. - analyzed: Analyzed, - incdirs: Vec, - warnings: Vec, - /// How many of `work` have been indexed. - at: usize, - /// 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`]. - staged: Vec, - staged_at: Vec, - /// The completion words of every file taken so far, which the tables built - /// when the scan ends are assembled from. - words: HashMap>, - /// How many files the size cap kept out, and how many came from the - /// persistent cache instead of a parse. Facts about this scan, so they - /// live on it — the end message names both. - skipped: usize, - cached: usize, - /// What this scan spent its time on, when `--verbose` asked. Off, it is a - /// bag of zeroes nobody reads (`crate::scan_trace`). - trace: ScanTrace, -} - -/// Which of the two shapes a [`Scan`] is. -/// -/// One enum rather than two `finish` methods so a caller cannot pair the wrong -/// ending with a scan: the scan itself says how it must be landed. -#[derive(PartialEq, Eq)] -enum ScanKind { - /// Every in-scope file, and whatever the index holds that the work list - /// does not name has left the scope. - Whole, - /// Only the files a scope widen brought in, folded into the index beside - /// what is already there (`docs/features/index-scope/README.md`). - Widen, -} - -impl Scan { - /// How many files the size cap kept out of this scan. - pub fn skipped(&self) -> usize { - self.skipped - } - - /// How many files came from the persistent cache instead of being parsed. - pub fn cached(&self) -> usize { - self.cached - } - - /// How many files this scan will index — known before the first parse, - /// which is what lets the caller decide whether the scan is long enough to - /// be worth answering messages in the middle of. - pub fn total(&self) -> usize { - self.work.len() - } - - /// Move `path` to the front of what is left to index, if it is still - /// waiting there. Reports whether it moved. - /// - /// The open-first rule, applied to a file opened *after* the work list was - /// taken: a `didOpen` answered mid-scan puts that file next rather than - /// leaving the user waiting for the alphabet to reach it. Reordering the - /// tail cannot change the finished index — records are merged in path - /// order whatever order they were taken in - /// ([`vlog_semantic::IndexBuilder`]) — so this is a latency decision and - /// nothing more. - pub fn index_next(&mut self, path: &Path) -> bool { - let at = self.at; - let Some(offset) = self.work[at.min(self.work.len())..] - .iter() - .position(|(held, _)| held == path) - .filter(|offset| *offset > 0) - else { - return false; - }; - // The file steps back to the front of what is left and everything it - // passed steps one place later; nothing is dropped and nothing is - // indexed twice. - self.work[at..=at + offset].rotate_right(1); - true - } -} - -/// What an index rebuild reports about itself as it runs. -/// -/// This module speaks no protocol, so an event carries numbers and paths and -/// nothing that reads like a message; `server.rs` turns them into a progress -/// report and a log line (`docs/features/indexing-ux/README.md`). -pub enum IndexEvent<'a> { - /// One file is about to be parsed into the index: how many were parsed - /// before it, how many there are in all, and which one it is. `done` - /// counts from 0, so the file being reported is number `done + 1` of - /// `total`. - Parsing { done: usize, total: usize, path: &'a Path }, - /// One file went into the index from the persistent cache instead of - /// being parsed. The same three numbers [`IndexEvent::Parsing`] carries, - /// because it is the same file of the same work list — it is *how* it got - /// there that differs, and a user watching a rescan fly through a - /// thousand files deserves to be told why. - Cached { done: usize, total: usize, path: &'a Path }, - /// One file went into the index from the analysis an **open buffer** - /// already holds — the parse this server did when the buffer was last - /// opened or changed — instead of being parsed again. The same three - /// numbers the other two carry, for the same reason. - /// - /// Its own variant rather than [`IndexEvent::Cached`] so that "from cache" - /// keeps meaning the persistent store and nothing else - /// (`docs/features/index-persistence/README.md`): a buffer's own analysis - /// is in memory, is there whether that store exists or not, and is right - /// even when the buffer has unsaved edits — which is exactly when a - /// content-keyed store has nothing to offer. - Analyzed { done: usize, total: usize, path: &'a Path }, - /// A walked file was skipped without being read, because it is bigger - /// than the size cap in force. - Skipped { path: &'a Path, size: u64, cap: u64 }, -} - /// The size of `path` when it is over `cap`, else `None` — the whole of the /// `lucisv.index.maxFileSize` test. /// @@ -474,6 +300,12 @@ fn oversize(path: &Path, cap: u64) -> Option { (size > cap).then_some(size) } +/// How many bytes of buffer text a scan carries for its whole life — every +/// other file's text lives from its own step to the end of that step. +fn held_bytes(buffered: &HashMap) -> usize { + buffered.values().map(String::len).sum() +} + /// Cut the view cache back to its two bounds, newest first. /// /// The newest view is kept whatever it weighs: one netlist-shaped file can @@ -492,6 +324,32 @@ fn trim_views(views: &mut Vec>) { views.truncate(kept); } +/// Whether the persistent store this session reads and writes through has +/// been opened yet, and where it will be opened from when something first +/// needs it. +/// +/// **The re-open rule is unchanged**: every whole rescan still opens the store +/// afresh, because the directory it belongs in depends on settings that arrive +/// after startup and because a second session over the same workspace may have +/// written records this one has not seen +/// (`docs/features/index-persistence/README.md`). What moved is *when*: from +/// the top of [`Workspace::begin_scan`] to the first file that asks the store +/// a question. A scan whose work list is empty asks none — and a session's +/// first scan runs at the default settings, before any buffer is open, so its +/// list is empty and it used to read and rewrite 44 MiB it never looked at +/// (`docs/features/perf5-p4/README.md`, §P4b (b1)). +#[derive(Default)] +enum StoreOpen { + /// Opened, or deliberately absent: [`Workspace::cache`] is what a lookup + /// gets. + #[default] + Done, + /// A whole rescan asked for a re-open and nothing has needed the store + /// since. The directory is the one that scan resolved, so a settings + /// change between then and the first file cannot move it underneath. + Deferred(Option), +} + /// Every open buffer plus the workspace index they are resolved against. #[derive(Default)] pub struct Workspace { @@ -508,10 +366,13 @@ pub struct Workspace { /// The last `lucisv.*` settings a client pushed. Default until it does. client: ClientSettings, /// What previous sessions' scans parsed, keyed by content: a file whose - /// bytes are in here is indexed without being parsed again. Re-opened at - /// the start of every whole rescan, because that is when the directory it - /// should live in can have moved (`docs/features/index-persistence`). + /// bytes are in here is indexed without being parsed again. Re-opened for + /// every whole rescan, because that is when the directory it should live + /// in can have moved (`docs/features/index-persistence`) — at the first + /// file of that rescan rather than before it, which is [`StoreOpen`]. cache: IndexCache, + /// Whether that re-open has happened yet — see [`StoreOpen`]. + store: StoreOpen, /// `initializationOptions.storagePath`: the per-workspace folder the /// editor offered for exactly this. One rung of the cache-directory /// ladder, and the only one the server cannot work out for itself. @@ -765,6 +626,9 @@ impl Workspace { || self.client.index_cache_path != settings.index_cache_path { self.cache = IndexCache::disabled(); + // And a deferred re-open goes with it, or the next file to want + // the store would open the directory the old settings named. + self.store = StoreOpen::Done; } self.client = settings; rescan @@ -941,14 +805,19 @@ impl Workspace { self.finish_scan(scan) } - /// Take the work list one scan will run through: resolve the scope, read - /// every in-scope file, and put the open buffers' own files at the front. + /// Take the work list one scan will run through: resolve the scope and put + /// the user's own neighbourhood at the front of it. + /// + /// **No file's text is read here** — only the open buffers', which are in + /// memory already. Everything else is read at the step that indexes it + /// ([`Workspace::scan_step`]), so the first file can be indexed as soon as + /// the walk is done rather than after the whole scope has been read. /// /// Nothing is indexed here and the live index is untouched, so a scan that /// 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 mut trace = self.opened_trace(trace, "whole"); + let mut trace = ScanTrace::opened(&mut self.scans, trace, "whole"); // A rescan says nothing about *which* file moved, so nothing held from // before it can be trusted. self.views.borrow_mut().clear(); @@ -967,27 +836,29 @@ impl Workspace { self.collect_sources(&mut counting, HeldAnalyses::Wanted) }; ScanTrace::add(&mut trace.discovery_ms, discovering); - let texts = std::mem::take(&mut scope.texts); + let buffered = std::mem::take(&mut scope.buffered); let analyzed = std::mem::take(&mut scope.analyzed); let ordering = trace.now(); - // The same list the index will be built from — asked of - // `vlog_semantic` rather than re-derived here, so the count reported - // is the count parsed — with the user's own open files moved to the - // front of it. - let work = self.open_first(index_order(texts)); - let paths: Vec = work.iter().map(|(path, _)| path.clone()).collect(); + // The same list the index will be built from, with the user's own + // neighbourhood moved to the front of it. + let WorkList { files: work, head } = self.open_first(std::mem::take(&mut scope.files)); + let head = scan_order::worth_waiting(head, work.len()); + let paths = work.clone(); ScanTrace::add(&mut trace.order_ms, ordering); - let opening = trace.now(); - // Re-opened here rather than held across rescans: the directory it - // belongs in depends on settings that arrive after startup, and a - // second session over the same workspace may have written records - // this one has not seen. - self.cache = IndexCache::open(self.cache_dir()); - ScanTrace::add(&mut trace.cache_open_ms, opening); - self.measure_work(&mut trace, &work, skipped); + // Re-opened rather than held across rescans: the directory it belongs + // in depends on settings that arrive after startup, and a second + // session over the same workspace may have written records this one + // has not seen. **Deferred** to the first file that asks the store + // anything ([`StoreOpen`]), so a scan with no files reads nothing. + self.store = StoreOpen::Deferred(self.cache_dir()); + trace.measure_work(work.len(), held_bytes(&buffered), skipped, self.cache.work()); Scan { kind: ScanKind::Whole, work, + head, + buffered, + includes: HashMap::new(), + unread: Vec::new(), paths, gone: Vec::new(), analyzed, @@ -1003,32 +874,24 @@ impl Workspace { } } - /// A trace for a scan that is starting, numbered so a session's lines can - /// be told apart — or an inert one when nobody asked for a trace. + /// Open the store a whole rescan asked for, if this is the first thing to + /// need it ([`StoreOpen`]). /// - /// `since_start_ms` is left for the server to stamp: how long the process - /// had been alive is the server's own knowledge, not the workspace's. - fn opened_trace(&mut self, on: bool, kind: &'static str) -> ScanTrace { - self.scans = self.scans.saturating_add(1); - let mut trace = ScanTrace::new(on); - trace.kind = kind; - trace.number = self.scans; - trace - } - - /// The work list's size, in files and in the bytes the scan will hold for - /// as long as it runs. - fn measure_work(&self, trace: &mut ScanTrace, work: &[(PathBuf, String)], skipped: usize) { - if !trace.on() { + /// Called from the two places that ask the store anything — a scan's step + /// and a save's write-through — so a rescan that reaches no file never + /// reads it, and the widen behind that rescan still finds it open the + /// moment it reaches one. + fn open_store(&mut self, trace: &mut ScanTrace) { + let StoreOpen::Deferred(dir) = std::mem::replace(&mut self.store, StoreOpen::Done) else { return; - } - trace.read = work.len(); - trace.read_bytes = work.iter().map(|(_, text)| text.len()).sum(); - trace.skipped = skipped; - // The baseline `landed` subtracts: a widen inherits the cache the - // previous scan filled, so the counters on it are the session's and - // not this scan's. - trace.cache = self.cache.work(); + }; + let opening = trace.now(); + self.cache = IndexCache::open(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 + // `measure_work` took, so its delta is the nothing it did. + trace.cache = CacheWork::default(); } /// Take the work list for a **scope widen**: the files `added` brings into @@ -1067,14 +930,14 @@ impl Workspace { watch: &mut dyn FnMut(IndexEvent), trace: bool, ) -> Scan { - let mut trace = self.opened_trace(trace, "widen"); + let mut trace = ScanTrace::opened(&mut self.scans, trace, "widen"); let discovering = trace.now(); let held: HashSet = self.index.files().iter().cloned().collect(); let cap = self.client.max_file_size; let spoken_for: HashSet<&Path> = self.docs.values().filter_map(|doc| doc.path.as_deref()).collect(); let mut skipped = 0usize; - let mut texts: Vec<(PathBuf, String)> = Vec::new(); + let mut files: Vec = Vec::new(); let mut warnings: Vec = Vec::new(); // The walk of the *added* directories alone, by the same rung-3 rules // `folder_files` follows — the whole scope is the union of these walks, @@ -1095,15 +958,14 @@ impl Workspace { if spoken_for.contains(path.as_path()) { continue; } - if let Ok(text) = fs::read_to_string(&path) { - texts.push((path, text)); - } + files.push(path); } let mut analyzed = Analyzed::default(); + let mut buffered: HashMap = HashMap::new(); let mut gone: Vec = Vec::new(); for doc in self.docs.values() { let Some(path) = doc.path.clone() else { continue }; - texts.retain(|(taken, _)| taken != &path); + files.retain(|taken| taken != &path); if doc.large { if held.contains(&path) { gone.push(path); @@ -1112,32 +974,38 @@ impl Workspace { } analyzed.facts.insert(path.clone(), doc.facts(path.clone())); analyzed.words.insert(path.clone(), doc.words()); - texts.push((path, doc.text.clone())); + buffered.insert(path.clone(), doc.text.clone()); + files.push(path); } ScanTrace::add(&mut trace.discovery_ms, discovering); let ordering = trace.now(); - let work = self.open_first(index_order(texts)); + let WorkList { files: work, head } = self.open_first(files); + let head = scan_order::worth_waiting(head, work.len()); ScanTrace::add(&mut trace.order_ms, ordering); - self.measure_work(&mut trace, &work, skipped); + trace.measure_work(work.len(), held_bytes(&buffered), skipped, self.cache.work()); // A whole scan drops the view cache entire, because a rescan claims // nothing about *which* file moved. A widen names exactly the files it // is reading, so it drops exactly those — which keeps the cache's own // rule ("every way a file's text can move drops its entry", // [`Workspace::file_view`]) literally true rather than nearly so. - for (path, _) in &work { + for path in &work { self.views.borrow_mut().retain(|view| &view.path != path); } // Which files exist once this widen lands: what the index holds, less // what it is about to lose, plus what the widen brings in. let mut paths: Vec = held.into_iter().filter(|path| !gone.contains(path)).collect(); - paths.extend(work.iter().map(|(path, _)| path.clone())); + paths.extend(work.iter().cloned()); paths.sort(); paths.dedup(); gone.sort(); Scan { kind: ScanKind::Widen, work, + head, + buffered, + includes: HashMap::new(), + unread: Vec::new(), paths, gone, analyzed, @@ -1170,25 +1038,41 @@ impl Workspace { /// Index the next file of `scan`, reporting whether there was one. /// - /// One file is the whole step: its record is taken — from the open - /// buffer's own analysis, from the persistent cache, or from a parse — and - /// its completion words are lexed. Both are *staged* on the scan rather - /// than merged, because merging is a pass over the whole workspace and one - /// per file would be quadratic ([`WorkspaceIndex::absorb`]). + /// One file is the whole step: **its text is read**, its record is taken — + /// from the open buffer's own analysis, from the persistent cache, or from + /// a parse — its `` `include``s are scanned off that text and its + /// completion words are taken off the record. All three are *staged* on + /// the scan rather than merged, because merging is a pass over the whole + /// workspace and one per file would be quadratic + /// ([`WorkspaceIndex::absorb`]). + /// + /// **The text is read here and dropped here** (2026-09-08). Everything the + /// scan will ever want from it — the content hash the store is keyed by, + /// the parse, the include lines — is taken in this one step, so a whole + /// scan reads each file's bytes exactly once and holds one file's text at + /// a time rather than the whole scope's. An **open buffer's** text is not + /// read: it was taken with the work list, beside the analysis that + /// describes the same bytes, so a `didChange` mid-scan cannot make the two + /// disagree. A file that cannot be read is remembered as `unread` and + /// 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 { let (done, total) = (scan.at, scan.work.len()); if done == total { return false; } scan.at += 1; - let path = scan.work[done].0.clone(); - // Taken out of the scan before the text is borrowed off it, so the two - // borrows never overlap. Both describe the same bytes as that text: - // `collect_sources` read the record and the text off one `Document` in - // one loop. + // The first file of a scan is the first thing to ask the store + // anything, so it is where the store this scan asked for is opened. + self.open_store(&mut scan.trace); + let path = scan.work[done].clone(); + let Some(source) = scan.take_text(&path) else { + scan.unread.push(path); + return true; + }; + let text = source.as_str(); let held = scan.analyzed.facts.remove(&path); let known_words = scan.analyzed.words.remove(&path); - let text = scan.work[done].1.as_str(); 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 @@ -1232,6 +1116,11 @@ impl Workspace { // An open buffer's words are still the caller's, read off the tokens // it was analyzed from. let words = known_words.unwrap_or_else(|| facts.words().to_vec()); + // Scanned here, off the text this step read, because the include graph + // is built when the scan ends and by then the text is gone. It is a + // line scan over bytes already in cache, and it replaces the identical + // scan `IncludeGraph::build` used to run over the same text later. + scan.includes.insert(path.clone(), includes::scan(text)); scan.words.insert(path, words); scan.staged.push(facts); scan.staged_at.push(done); @@ -1257,19 +1146,16 @@ impl Workspace { self.index.absorb(std::mem::take(&mut scan.staged), &[]); ScanTrace::add(&mut scan.trace.publish_absorb_ms, absorbing); let completing = scan.trace.now(); - let words = taken + let published: Vec = taken.iter().map(|&at| scan.work[at].clone()).collect(); + let words = published .iter() - .map(|&at| { - let path = &scan.work[at].0; - (path.clone(), scan.words.get(path).cloned().unwrap_or_default()) - }) + .map(|path| (path.clone(), scan.words.get(path).cloned().unwrap_or_default())) .collect(); self.candidates.absorb(&self.index, words); ScanTrace::add(&mut scan.trace.publish_candidates_ms, completing); let including = scan.trace.now(); - let texts: Vec<(&Path, &str)> = - taken.iter().map(|&at| (scan.work[at].0.as_path(), scan.work[at].1.as_str())).collect(); - self.includes.absorb(&scan.incdirs, &scan.paths, &texts); + let found = scan::included(&scan.includes, &published); + self.includes.absorb_includes(&scan.incdirs, &scan.paths, &found); ScanTrace::add(&mut scan.trace.publish_includes_ms, including); let refreshing = scan.trace.now(); // Every open buffer resolves against the index, so a buffer whose @@ -1299,11 +1185,19 @@ impl Workspace { /// [`Workspace::finish_scan`] for a whole scan. fn finish_whole_scan(&mut self, scan: Scan) -> Vec { - let Scan { work, incdirs, warnings, staged, words, mut trace, .. } = scan; + let Scan { + mut work, unread, incdirs, warnings, staged, words, includes, mut trace, .. + } = scan; + // What the scan really indexed, which is its work list unless a file + // left the disk between the walk and its own step. Such a file is not + // in scope any more, so it must land in `gone` exactly as it would + // have if the walk had missed it. + work.retain(|path| !unread.contains(path)); + let found = scan::included(&includes, &work); let leaving = trace.now(); // Whatever the last scan left in the index that this one's work list // does not name is a file that is no longer in scope. - let held: HashSet<&Path> = work.iter().map(|(path, _)| path.as_path()).collect(); + let held: HashSet<&Path> = work.iter().map(PathBuf::as_path).collect(); let gone: Vec = self .index .files() @@ -1316,18 +1210,26 @@ impl Workspace { self.index.absorb(staged, &gone); ScanTrace::add(&mut trace.absorb_ms, absorbing); // The one moment the live set of entries is known, so the one moment - // the append log is worth rewriting. - self.cache.compact(); + // the append log is worth rewriting — and only when this scan reached + // a file at all. A scan with an empty work list asked the store + // nothing and never opened it, so there is nothing of this session's + // in it and nothing to rewrite it from (§P4b (b1)); the rewrite of a + // store that *is* open is itself skipped when it would reproduce the + // file byte for byte ([`IndexCache::compact`], §P4b (a)). + if matches!(self.store, StoreOpen::Done) { + self.cache.compact(); + } let completing = trace.now(); - // Built here, from the same list, so a file the scope ladder excluded - // contributes no completion candidates either. Every file's words are - // in `words` already, so nothing is lexed twice. - self.candidates = Candidates::build(&self.index, &work, words); + // Built from the words every step took off its own record — the same + // list, so a file the scope ladder excluded contributes no completion + // candidates either, and nothing is lexed twice. + self.candidates = Candidates::from_words(&self.index, words); ScanTrace::add(&mut trace.candidates_ms, completing); let including = trace.now(); // Same list again: an `` `include`` in a file the scope excluded is // not an edge, and a file it excluded is not a hop away from anything. - self.includes = IncludeGraph::build(&work, incdirs); + // The lines themselves were read at each file's own step. + self.includes = IncludeGraph::from_includes(&found, incdirs); ScanTrace::add(&mut trace.includes_ms, including); let refreshing = trace.now(); for doc in self.docs.values_mut() { @@ -1341,47 +1243,14 @@ impl Workspace { /// Close a scan's trace: the tables it left behind, measured, and the /// whole thing set aside for the server to log. /// - /// Every size below is a walk, so all of them are behind `on()` and none - /// of them happens in a session that did not ask for a trace. + /// Every size it reads is a walk, so the trace itself decides whether to + /// take them ([`ScanTrace::landed`]); a scan nobody traced sets nothing + /// aside. fn landed(&mut self, mut trace: ScanTrace) { - if !trace.on() { - return; + trace.landed(self.docs.len(), &self.cache, &self.index, &self.candidates, &self.includes); + if trace.on() { + self.last_trace = trace; } - // Read first, before a single size below is walked: describing a scan - // is not part of the scan, and charging the walks to `total_ms` would - // make the trace inflate the very number it exists to explain. - trace.total_ms = trace.elapsed_ms(); - trace.overlays = self.docs.len(); - trace.cache = self.cache.work().since(trace.cache); - // At the *end*, so the store's retention is what the finished scan - // leaves resident rather than what it started from — the two differ - // by every record a cold scan wrote. - trace.cache_entries = self.cache.entry_count(); - trace.cache_bytes = self.cache.encoded_bytes(); - let index = self.index.table_sizes(); - let counts = self.index.counts(); - let (units, macros, words, word_bytes) = self.candidates.sizes(); - let (include_edges, include_known) = self.includes.sizes(); - trace.sizes = crate::scan_trace::TableSizes { - index_files: counts.files, - unit_names: index.unit_names, - unit_defs: index.unit_defs, - members: index.members, - hier_members: index.hier_members, - reference_keys: index.reference_keys, - reference_sites: index.reference_sites, - defines: counts.defines, - instantiations: counts.instantiations, - fact_words: index.words, - fact_word_bytes: index.word_bytes, - candidate_units: units, - candidate_macros: macros, - candidate_words: words, - candidate_word_bytes: word_bytes, - include_edges, - include_known, - }; - self.last_trace = trace; } /// The trace of the scan that just finished, taken away — an inert one @@ -1407,7 +1276,8 @@ impl Workspace { /// total order a whole build sorts into; /// * **the include graph** — the known-file and folded-spelling tables are /// relearned from the whole in-scope list and every held edge is - /// re-spelled against it ([`IncludeGraph::absorb`]), so a file that is in + /// re-spelled against it (the graph is rebuilt from every file's staged + /// include list, [`IncludeGraph::from_includes`]), so a file that is in /// scope for the first time can lend its spelling to an edge that was /// resolved before it arrived. /// @@ -1416,7 +1286,24 @@ impl Workspace { /// set of entries — it only added to it — and the next whole rescan /// rewrites the log anyway. fn finish_widen(&mut self, scan: Scan) -> Vec { - let Scan { work, paths, gone, incdirs, warnings, staged, words, mut trace, .. } = scan; + let Scan { + mut work, + mut paths, + gone, + incdirs, + warnings, + staged, + words, + includes, + mut trace, + unread, + .. + } = scan; + // A widen only ever adds, so a file whose text had gone by its own + // step is simply not added — it is in neither list below. + work.retain(|path| !unread.contains(path)); + paths.retain(|path| !unread.contains(path)); + let found = scan::included(&includes, &work); let absorbing = trace.now(); self.index.absorb(staged, &gone); ScanTrace::add(&mut trace.absorb_ms, absorbing); @@ -1430,15 +1317,13 @@ impl Workspace { } let batch: Vec<(PathBuf, Vec)> = work .iter() - .map(|(path, _)| (path.clone(), words.get(path).cloned().unwrap_or_default())) + .map(|path| (path.clone(), words.get(path).cloned().unwrap_or_default())) .collect(); let completing = trace.now(); self.candidates.absorb(&self.index, batch); ScanTrace::add(&mut trace.candidates_ms, completing); let including = trace.now(); - let texts: Vec<(&Path, &str)> = - work.iter().map(|(path, text)| (path.as_path(), text.as_str())).collect(); - self.includes.absorb(&incdirs, &paths, &texts); + self.includes.absorb_includes(&incdirs, &paths, &found); ScanTrace::add(&mut trace.includes_ms, including); let refreshing = trace.now(); for doc in self.docs.values_mut() { @@ -1514,6 +1399,10 @@ impl Workspace { // keyed by the text it was made from, which is the buffer's // when a buffer beat disk. That record is simply never hit // again if the file on disk says something else. + // A save is the other thing that asks the store something, so + // it opens a re-open a scan deferred rather than writing into + // the store the previous rescan left in hand ([`StoreOpen`]). + self.open_store(&mut ScanTrace::default()); if let Some(facts) = self.index.facts_for(path) { self.cache.record(facts, &text); } @@ -1580,20 +1469,51 @@ impl Workspace { fs::read_to_string(path).ok() } - /// The work list with the open buffers' own files at the front of it, each - /// group still in path order (`sort_by_key` is stable). + /// 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`]). /// - /// **A reporting nicety and nothing else.** `vlog_semantic::IndexBuilder` - /// sorts by path inside `finish` since 2026-08-27, so no insertion order - /// can reach the index: this changes which file the progress bar names - /// first — the user's own, which is the one they are waiting on — and - /// changes nothing about the result. Pinned both ends: the builder's own + /// **A reporting and latency decision and nothing else.** + /// `vlog_semantic::IndexBuilder` sorts by path inside `finish` since + /// 2026-08-27, so no insertion order can reach the index: this changes + /// which file the progress bar names first — the user's own, and then + /// what they are looking at across the folder — and changes nothing about + /// the result. Pinned both ends: the builder's own /// `no_insertion_order_can_change_what_the_builder_produces`, and /// `the_open_files_are_indexed_first_and_the_index_cannot_tell` here. - fn open_first(&self, mut files: Vec<(PathBuf, T)>) -> Vec<(PathBuf, T)> { - let open: Vec<&Path> = self.docs.values().filter_map(|doc| doc.path.as_deref()).collect(); - files.sort_by_key(|(path, _)| !open.contains(&path.as_path())); - files + /// Re-order what is left of `scan` around the buffers open **now** — the + /// same ranking [`Workspace::begin_scan`] applied, re-applied because a + /// `didOpen` answered mid-scan changed the answer to "where is the user + /// working?". + /// + /// Called after the burst carrying that `didOpen` has been applied, so the + /// buffer is installed and the folder it raises to is known. What was + /// already indexed is untouched; only the tail moves, and the finished + /// index cannot tell ([`Scan::reorder`]). + pub fn open_next(&self, scan: &mut Scan) { + let ordered = self.open_first(scan.remaining()); + scan.reorder(ordered); + } + + fn open_first(&self, files: Vec) -> WorkList { + let open: Vec = self.docs.values().filter_map(|doc| doc.path.clone()).collect(); + scan_order::work_list(files, &open, &self.raised_dirs()) + } + + /// The directories the open buffers' own folders raise to, whichever rung + /// of the ladder is in force. + /// + /// [`Workspace::scope_dirs`] answers the same question *as a scope* and is + /// therefore empty unless rung 3 is in force. This one is an **ordering** + /// question — where in the workspace the user is working — and it has the + /// same answer under a filelist or an explicit `workspace` scope, where it + /// is the only thing that says which part of a 4 000-file walk to index + /// first. + fn raised_dirs(&self) -> Vec { + let mut dirs: Vec = self.opened_dirs.iter().map(|dir| self.raised(dir)).collect(); + dirs.sort(); + dirs.dedup(); + dirs } /// The in-scope files and their current text — what a refactoring reads. @@ -1601,8 +1521,24 @@ impl Workspace { /// The same list `rebuild_index` feeds the index, recomputed rather than /// kept: a refactoring is a rare, user-initiated request, and a second /// copy of the workspace in memory is a high price for saving one walk. + /// + /// This is the one caller that really does want every file's text at once, + /// so it is where the read a scan no longer does in one pass still + /// happens. A file that cannot be read contributes nothing, exactly as it + /// did when `collect_sources` read them all. pub fn sources(&self) -> Vec<(PathBuf, String)> { - self.collect_sources(&mut |_| {}, HeldAnalyses::Unused).texts + let Sources { files, mut buffered, .. } = + self.collect_sources(&mut |_| {}, HeldAnalyses::Unused); + files + .into_iter() + .filter_map(|path| { + let text = match buffered.remove(&path) { + Some(text) => text, + None => fs::read_to_string(&path).ok()?, + }; + Some((path, text)) + }) + .collect() } /// The in-scope files a port refactoring on `modules`, requested in `file`, @@ -1914,14 +1850,20 @@ impl Workspace { .collect() } - /// Read every in-scope file, with open buffers overriding disk. + /// Resolve the scope: which files are in it, with open buffers overriding + /// disk, and those buffers' own text. + /// + /// **Metadata only, plus what is already in memory.** Nothing on disk is + /// read here — a file's text is read by whoever indexes or rewrites it, + /// one file at a time ([`Workspace::scan_step`], [`Workspace::sources`]). /// /// This is where `lucisv.index.maxFileSize` applies, and it applies to the /// **walked** files only: an open buffer is folded in below whatever its /// size, because the user opened it deliberately and an editor that /// refused to understand the file on screen would be absurd. The check is - /// a `metadata` call ahead of the read, so an oversized file is never read - /// at all — which is the whole saving. + /// a `metadata` call, so an oversized file is still never read at all — + /// which is the whole saving, and it is still counted and reported here + /// so that a scan's skip count is known before its first step. /// /// A refactoring reads this same list through `sources()`, so a file the /// cap keeps out of the index is also a file a workspace rename will not @@ -1941,7 +1883,7 @@ impl Workspace { // skipped exactly as it did before the buffer put its own text back. let spoken_for: HashSet<&Path> = self.docs.values().filter_map(|doc| doc.path.as_deref()).collect(); - let mut texts: Vec<(PathBuf, String)> = Vec::new(); + let mut files: Vec = Vec::new(); for path in scope.files { if let Some(size) = oversize(&path, cap) { watch(IndexEvent::Skipped { path: &path, size, cap }); @@ -1950,9 +1892,7 @@ impl Workspace { if spoken_for.contains(path.as_path()) { continue; } - if let Ok(text) = fs::read_to_string(&path) { - texts.push((path, text)); - } + files.push(path); } // Open buffers override what is on disk, and contribute themselves // when they are not on disk at all. @@ -1966,18 +1906,20 @@ impl Workspace { // interaction with `lucisv.index.maxFileSize`, whose "an open buffer is // never capped" rule this is the one exception to. let mut analyzed = Analyzed::default(); + let mut buffered: HashMap = HashMap::new(); for doc in self.docs.values() { let Some(path) = doc.path.clone() else { continue }; - texts.retain(|(p, _)| p != &path); + files.retain(|p| p != &path); if !doc.large { if analyses == HeldAnalyses::Wanted { analyzed.facts.insert(path.clone(), doc.facts(path.clone())); analyzed.words.insert(path.clone(), doc.words()); } - texts.push((path, doc.text.clone())); + buffered.insert(path.clone(), doc.text.clone()); + files.push(path); } } - Sources { texts, analyzed, incdirs: scope.incdirs, warnings: scope.warnings } + Sources { files, buffered, analyzed, incdirs: scope.incdirs, warnings: scope.warnings } } /// One **closed** file's text and line index, read at most once per file @@ -2842,9 +2784,14 @@ mod tests { assert!(stepped.scan_step(&mut scan, &mut |_| {}), "premise: a.sv goes first"); assert!(stepped.index().units("c").is_empty(), "premise: c.sv is not indexed yet"); - assert!(scan.index_next(&tree.path.join("c.sv")), "the newly opened file jumps the queue"); - assert!(!scan.index_next(&tree.path.join("c.sv")), "and does not jump twice"); - assert!(!scan.index_next(&tree.path.join("nothing.sv")), "a file not waiting cannot jump"); + // The client opens `c.sv`, and the work list is re-ordered around the + // buffers open now — since 2026-09-08 that is one call rather than one + // per opened path, because a buffer brings its folder with it + // (`docs/features/perf5-p4/README.md` §P4b3). + let jumped = uri(&format!("file://{}", tree.path.join("c.sv").display())); + let jumped_text = fs::read_to_string(tree.path.join("c.sv")).expect("the fixture"); + stepped.set_document(jumped, jumped_text); + stepped.open_next(&mut scan); assert!(stepped.scan_step(&mut scan, &mut |_| {})); stepped.publish_scan(&mut scan); assert!(!stepped.index().units("c").is_empty(), "c.sv was indexed next, not last"); @@ -4113,6 +4060,229 @@ mod tests { assert_eq!(ws.index().counts(), plain.index().counts(), "and the same index"); } + // ------------------------------------------------------------------ + // The lazy read and the folder-first order (perf5-p4 §P4b3, 2026-09-08) + // ------------------------------------------------------------------ + + /// The paths a scan reported, whichever way each file got into the index. + fn walked(ws: &mut Workspace) -> Vec { + let mut seen: Vec = Vec::new(); + ws.rebuild_index_with(&mut |event| match event { + IndexEvent::Parsing { path, .. } + | IndexEvent::Cached { path, .. } + | IndexEvent::Analyzed { path, .. } => seen.push(path.to_path_buf()), + IndexEvent::Skipped { .. } => {} + }); + seen + } + + /// A workspace whose buffer sits two folders below a root, so the folder + /// the scope ladder raises it to is a real neighbourhood rather than the + /// whole tree — opentitan's `hw/ip/aes/dv/tb/tb.sv` in miniature. + fn neighbourhood_tree(name: &str) -> Tree { + let tree = Tree::new(name); + tree.package("ip/aes/dv/tb/tb.sv", "tb_pkg"); + tree.package("ip/aes/rtl/aes.sv", "aes_pkg"); + tree.package("ip/aes/rtl/aes_core.sv", "aes_core_pkg"); + tree.package("ip/kmac/rtl/kmac.sv", "kmac_pkg"); + tree.package("ip/uart/rtl/uart.sv", "uart_pkg"); + tree.package("dv/common/util.sv", "util_pkg"); + // The crowd the folder has to be a minority of — opentitan's `ip/aes` + // is 124 files of 3 976 (`crate::scan_order::worth_waiting`). + for n in 0..6 { + tree.package(&format!("zz/z{n:03}.sv"), &format!("z{n:03}_pkg")); + } + tree + } + + #[test] + fn a_whole_scan_reads_each_files_bytes_exactly_once() { + // The claim the lazy read makes. Everything the scan wants from a + // file's text — the store's content hash, the parse, the `include` + // lines — comes out of one read, and the open buffer's text is not + // read from disk at all. + let tree = neighbourhood_tree("readonce"); + let mut ws = Workspace::default(); + ws.client.index_scope = IndexScope::Workspace; + ws.adopt_roots(vec![tree.path.clone()]); + + let before = crate::scan_trace::source_reads(); + assert_eq!(ws.rebuild_index().len(), 0, "premise: the walk is clean"); + assert_eq!( + crate::scan_trace::source_reads() - before, + 12, + "twelve files in the tree, twelve reads and not one more" + ); + + open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv"); + let before = crate::scan_trace::source_reads(); + ws.rebuild_index(); + assert_eq!( + crate::scan_trace::source_reads() - before, + 11, + "the open buffer's own text is in memory and is never read off disk" + ); + } + + #[test] + fn the_open_buffers_folder_is_indexed_before_the_rest_and_the_index_cannot_tell() { + // The ordering §P4b2 asked for: the user's own file, then the folder + // the scope ladder raises it to — `ip/aes`, two levels above + // `ip/aes/dv` — and only then the workspace's alphabet. + let tree = neighbourhood_tree("folderfirst"); + let mut ws = Workspace::default(); + ws.client.index_scope = IndexScope::Workspace; + ws.adopt_roots(vec![tree.path.clone()]); + open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv"); + + assert_eq!( + walked(&mut ws), + [ + vec![ + tree.path.join("ip/aes/dv/tb/tb.sv"), + tree.path.join("ip/aes/rtl/aes.sv"), + tree.path.join("ip/aes/rtl/aes_core.sv"), + tree.path.join("dv/common/util.sv"), + tree.path.join("ip/kmac/rtl/kmac.sv"), + tree.path.join("ip/uart/rtl/uart.sv"), + ], + (0..6).map(|n| tree.path.join(format!("zz/z{n:03}.sv"))).collect(), + ] + .concat(), + "the buffer, then its folder in path order, then the rest in path order" + ); + + // And the reason that is allowed to be true: the finished index does + // not depend on it. `IndexBuilder::finish` sorts by path, so a scan + // with nothing open builds the same thing. + let mut plain = Workspace::default(); + plain.client.index_scope = IndexScope::Workspace; + plain.adopt_roots(vec![tree.path.clone()]); + plain.rebuild_index(); + assert_eq!(plain.index().fingerprint(), ws.index().fingerprint(), "same index"); + assert_eq!(everything(&plain), everything(&ws), "and the same tables around it"); + } + + #[test] + fn the_neighbourhood_is_what_a_held_request_waits_for() { + // The drain rule's own arithmetic, at the workspace level: `head` + // counts the buffer and its folder and nothing beyond. + let tree = neighbourhood_tree("headsegment"); + let mut ws = Workspace::default(); + ws.client.index_scope = IndexScope::Workspace; + ws.adopt_roots(vec![tree.path.clone()]); + open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv"); + + let mut scan = ws.begin_scan(&mut |_| {}, false); + assert!(!scan.neighbourhood_indexed(), "nothing is indexed yet"); + // Three files are the neighbourhood — the buffer and `ip/aes` — and + // the nine behind it are not. + for expected in [false, false, true, true, true, true, true, true, true, true, true, true] { + assert!(ws.scan_step(&mut scan, &mut |_| {})); + assert_eq!(scan.neighbourhood_indexed(), expected, "at {}", scan.at); + } + ws.finish_scan(scan); + + // With nothing open there is no neighbourhood, and a held request is + // answered at the first interleave point exactly as it always was. + let mut bare = Workspace::default(); + bare.client.index_scope = IndexScope::Workspace; + bare.adopt_roots(vec![tree.path.clone()]); + let scan = bare.begin_scan(&mut |_| {}, false); + assert!(scan.neighbourhood_indexed(), "no buffer, no wait"); + bare.finish_scan(scan); + } + + #[test] + fn a_file_opened_mid_scan_lengthens_the_neighbourhood_it_jumps_into() { + // `index_next` moves a file to the front of what is left. When it + // comes from beyond the head segment it pushes one of that segment's + // files a place later, and a held request must not be answered one + // file short of the folder it is waiting for. + let tree = neighbourhood_tree("headjump"); + let mut ws = Workspace::default(); + ws.client.index_scope = IndexScope::Workspace; + ws.adopt_roots(vec![tree.path.clone()]); + open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv"); + + let mut scan = ws.begin_scan(&mut |_| {}, false); + assert!(ws.scan_step(&mut scan, &mut |_| {}), "the buffer's own file goes first"); + open(&mut ws, &tree, "ip/uart/rtl/uart.sv"); + ws.open_next(&mut scan); + // `uart.sv` is now the head of what is left, and at the shipped + // `scopeDepth: 2` its own folder raises to `ip` — which brings + // `ip/kmac` in with it. Four files of waiting, one behind the file + // already stepped, so the segment ends at five rather than three. + for expected in [false, false, false, true, true] { + assert!(ws.scan_step(&mut scan, &mut |_| {})); + assert_eq!(scan.neighbourhood_indexed(), expected, "at {}", scan.at); + } + ws.finish_scan(scan); + } + + #[test] + fn a_file_that_leaves_the_disk_between_the_walk_and_its_step_leaves_the_index() { + // What `collect_sources` used to do by dropping an unreadable file + // before the work list existed: the file contributes nothing, is not + // counted among the cap's skips, and — for a whole scan — is taken + // *out* of the index rather than left in it stale. + let tree = Tree::new("vanished"); + tree.package("rtl/stays.sv", "stays_pkg"); + tree.package("rtl/goes.sv", "goes_pkg"); + let mut ws = Workspace::default(); + ws.client.index_scope = IndexScope::Workspace; + ws.adopt_roots(vec![tree.path.clone()]); + ws.rebuild_index(); + assert!(!ws.index().units("goes_pkg").is_empty(), "premise: it was indexed once"); + + let mut scan = ws.begin_scan(&mut |_| {}, false); + assert_eq!(scan.total(), 2, "the walk found both"); + fs::remove_file(tree.path.join("rtl/goes.sv")).expect("remove"); + let mut said: Vec = Vec::new(); + while ws.scan_step(&mut scan, &mut |event| said.push(seen(&event))) {} + assert_eq!(scan.skipped(), 0, "an unreadable file is not one the size cap skipped"); + assert_eq!(said.len(), 1, "and it reports no event of its own: {said:?}"); + ws.finish_scan(scan); + + assert!(ws.index().units("goes_pkg").is_empty(), "it left the scope, so it left the index"); + assert!(!ws.index().units("stays_pkg").is_empty(), "and the file beside it did not"); + } + + #[test] + fn the_tables_a_scan_lands_are_the_ones_the_texts_would_have_built() { + // The lazy read's equivalence, table by table. The scan builds the + // completion tables from the words it took off each record and the + // include graph from the lines it scanned at each step; both must + // equal what `Candidates::build` and `IncludeGraph::build` produce + // from the same files' text. + let tree = tangled("lazytables"); + let mut ws = Workspace::default(); + ws.client.index_scope = IndexScope::Workspace; + ws.adopt_roots(vec![tree.path.clone()]); + ws.rebuild_index(); + + let texts: Vec<(PathBuf, String)> = ws + .index() + .files() + .iter() + .map(|path| (path.clone(), fs::read_to_string(path).expect("fixture"))) + .collect(); + let eagerly = Candidates::build(ws.index(), &texts, HashMap::new()); + assert_eq!(eagerly.sizes(), ws.candidates().sizes(), "the same completion tables"); + assert_eq!(eagerly.words(""), ws.candidates().words(""), "word for word"); + + let rebuilt = IncludeGraph::build(&texts, Vec::new()); + assert_eq!(rebuilt.sizes(), ws.includes().sizes(), "the same include graph"); + for (path, _) in &texts { + assert_eq!( + rebuilt.reachable(vec![path.clone()]), + ws.includes().reachable(vec![path.clone()]), + "the same hops from {}", + path.display() + ); + } + } + // ------------------------------------------------------------------ // The incremental path (incremental-index, 2026-08-27) // ------------------------------------------------------------------ @@ -4586,6 +4756,118 @@ mod tests { ); } + /// The store's bytes and its modification time — "not touched" as + /// something a test can see rather than infer. + fn store_stamp(store: &Path) -> (Vec, std::time::SystemTime) { + let path = store.join("index-cache"); + let bytes = fs::read(&path).expect("read store"); + let stamp = fs::metadata(&path).expect("meta").modified().expect("mtime"); + (bytes, stamp) + } + + #[test] + fn a_warm_rescan_that_appended_nothing_leaves_the_store_exactly_as_it_found_it() { + // §P4b (a) through the workspace: every file hits the store, so the + // session appends nothing, so the compaction at the end of the scan + // would rewrite the file it read into itself. It does not run, and + // the store on disk is not touched — not its bytes, not its mtime. + let tree = Tree::new("compactskip"); + tree.package("a.sv", "a_pkg"); + tree.package("b.sv", "b_pkg"); + let store = Tree::new("compactskip_store"); + + let mut cold = cached_workspace(&store.path); + scan(&mut cold, Some(vec![tree.path.clone()])); + let before = store_stamp(&store.path); + + let mut warm = cached_workspace(&store.path); + let second = scan(&mut warm, Some(vec![tree.path.clone()])); + assert_eq!(second.cached, ["a.sv", "b.sv"], "premise: a scan that appends nothing"); + assert_eq!(store_stamp(&store.path), before, "the store was not rewritten"); + + // A third session still reads it, and a file that *did* change still + // costs the rewrite that folds its new record in. + tree.package("b.sv", "b_renamed_pkg"); + let mut third = cached_workspace(&store.path); + let changed = scan(&mut third, Some(vec![tree.path.clone()])); + assert_eq!(changed.parsed, ["b.sv"], "{changed:?}"); + let after = fs::read_to_string(store.path.join("index-cache")).expect("a store"); + assert!(after.contains("b_renamed_pkg"), "the changed file's record landed"); + assert_eq!(after.lines().count(), 3, "and the store is one line per path: {after}"); + } + + #[test] + fn a_scan_with_no_files_neither_reads_the_store_nor_rewrites_it() { + // §P4b (b1). `Server::started` builds the index at the **default** + // settings, before `workspace/configuration` can even be asked — and + // the folder scope is derived from the directories a buffer has been + // opened from, of which there are none, so that scan's work list is + // empty. Warm it still opened a 44 MiB store and rewrote it + // byte-identically: 184 ms of a 1.33 s start, for a scan that indexes + // nothing (`docs/features/perf5-p4/README.md`). + let tree = Tree::new("emptyscan"); + tree.package("rtl/a.sv", "a_pkg"); + tree.package("rtl/b.sv", "b_pkg"); + let store = Tree::new("emptyscan_store"); + + let mut filling = cached_workspace(&store.path); + scan(&mut filling, Some(vec![tree.path.clone()])); + let before = store_stamp(&store.path); + + // The startup shape: the folder scope, no buffer open. + let mut empty = Workspace::default(); + empty.set_client_settings(caching(&store.path)); + empty.adopt_roots(vec![tree.path.clone()]); + let nothing = scan(&mut empty, None); + assert_eq!(nothing, Scan::default(), "premise: this scan indexes no file"); + assert_eq!(store_stamp(&store.path), before, "so the store is neither read nor written"); + + // And the widen the first `didOpen` triggers still hits every record + // the store holds — the open was deferred to the first file that + // wants it, not dropped. + let opened = tree.path.join("rtl/a.sv"); + let uri = crate::uri::path_to_uri(&opened).expect("uri"); + empty.set_document(uri, fs::read_to_string(&opened).expect("read")); + let added: Vec = empty.scope_dirs(); + assert_eq!(added, vec![tree.path.join("rtl")], "premise: the open widened the scope"); + let mut widened = Scan::default(); + empty.widen_index_with(&added, &mut |event| match event { + IndexEvent::Parsing { path, .. } => widened.parsed.push(file_name(path)), + IndexEvent::Cached { path, .. } => widened.cached.push(file_name(path)), + IndexEvent::Analyzed { path, .. } => widened.analyzed.push(file_name(path)), + IndexEvent::Skipped { .. } => {} + }); + assert_eq!(widened.analyzed, ["a.sv"], "the open buffer indexes itself: {widened:?}"); + assert_eq!( + widened.cached, + ["b.sv"], + "the widen reads the store the scan left: {widened:?}" + ); + assert!(widened.parsed.is_empty(), "not one file reparsed: {widened:?}"); + } + + #[test] + fn a_cold_session_that_indexes_nothing_creates_no_store_at_all() { + // The same rule the other way up: with no store yet and no file to + // index, nothing is created — no directory, no `.gitignore`, no + // header-only store — and the session that *does* index a file makes + // all three. + let tree = Tree::new("emptycold"); + tree.package("rtl/a.sv", "a_pkg"); + let store = Tree::new("emptycold_store"); + let dir = store.path.join("inner"); + + let mut empty = Workspace::default(); + empty.set_client_settings(caching(&dir)); + empty.adopt_roots(vec![tree.path.clone()]); + assert_eq!(scan(&mut empty, None), Scan::default(), "premise"); + assert!(!dir.exists(), "a scan with no files creates no cache directory"); + + let mut indexing = cached_workspace(&dir); + scan(&mut indexing, Some(vec![tree.path.clone()])); + assert!(dir.join("index-cache").exists(), "and a scan with files still writes one"); + } + #[test] fn persistence_off_reads_nothing_and_writes_nothing() { let tree = Tree::new("cacheoff"); diff --git a/crates/lucisv_server/src/state/scan.rs b/crates/lucisv_server/src/state/scan.rs new file mode 100644 index 0000000..761477b --- /dev/null +++ b/crates/lucisv_server/src/state/scan.rs @@ -0,0 +1,297 @@ +//! One workspace scan in flight: the work list it took, the text and the +//! records it has gathered so far, and what it reports about itself as it +//! runs. +//! +//! Split out of `state.rs` on 2026-09-08, as a pure move, when the lazy read +//! gave the scan three more things to carry (`docs/features/perf5-p4/README.md` +//! §P4b3). [`Workspace`](super::Workspace) drives it — `begin_scan` builds +//! one, `scan_step` advances it, `finish_scan` lands it — so the fields are +//! `pub(super)` and visible exactly where they were before the move: inside +//! `crate::state` and nowhere else. + +use std::collections::HashMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use vlog_semantic::FileFacts; + +use crate::includes::Include; +use crate::scan_order::{self, WorkList}; +use crate::scan_trace::{self, ScanTrace}; + +/// A `Scope` resolved: which files one index rebuild works from, and the text +/// of the ones it already holds. +/// +/// **Nothing on disk has been read.** Until 2026-09-08 this carried every +/// in-scope file's text, read in one pass before the first file was indexed — +/// 34 MiB and ~293 ms on OpenTitan, held for the whole life of the scan and +/// spent before any request could be answered. A file's text is now read at +/// the step that indexes it and let go again +/// (`docs/features/perf5-p4/README.md` §P4b3). An **open buffer's** text is +/// still taken here, with the analysis beside it, because the two must +/// describe the same bytes and the buffer may be edited while the scan runs. +pub(super) struct Sources { + /// Every in-scope file, in scope order: the walked ones the cap and the + /// open buffers left, then the buffers' own paths. + pub(super) files: Vec, + /// The text of each open buffer among `files`, as it was when the scope + /// was resolved. + pub(super) buffered: HashMap, + /// What the open buffers among `files` already know about themselves. + pub(super) analyzed: Analyzed, + pub(super) incdirs: Vec, + pub(super) warnings: Vec, +} + +/// The index facts and the completion words of the entries `texts` took from an +/// **open buffer**, read off the analysis that buffer already holds. +/// +/// Both maps are filled in the same loop that lets a buffer override the disk +/// copy, so an entry here is always the analysis of exactly the text beside it +/// in `texts` — the two cannot describe different bytes. A file that is not an +/// open buffer appears in neither map and is parsed and lexed as it always was. +#[derive(Default)] +pub(super) struct Analyzed { + pub(super) facts: HashMap, + pub(super) words: HashMap>, +} + +/// Whether a caller of `collect_sources` wants [`Analyzed`] filled in. +/// +/// An index rebuild does — it is what it indexes the open buffers from. A +/// refactoring reads the texts and nothing else, and reading a record off every +/// open buffer for it would be work nothing looks at. +#[derive(PartialEq, Eq)] +pub(super) enum HeldAnalyses { + Wanted, + Unused, +} + +/// One workspace scan in flight: the work list it took when it began, and how +/// far through it the workspace has got. +/// +/// A value rather than a loop inside [`Workspace::rebuild_index_with`] because +/// the server answers the client's messages *between* two files of a scan +/// (`docs/features/scan-interleave/README.md`), and a message it answers needs +/// the very workspace the scan is feeding — which a callback called from +/// inside a `&mut self` loop can never be handed. Splitting the loop is what +/// puts the scan's state somewhere the message can be answered around. +pub struct Scan { + /// Whether this scan rebuilds the index or only folds newly-in-scope files + /// into it. The whole difference is in [`Workspace::finish_scan`]; every + /// step in between is the same code. + pub(super) kind: ScanKind, + /// Every file this scan indexes, in the order it indexes them: the open + /// buffers' own files, then the rest of their folders, then the rest in + /// path order ([`crate::scan_order`]). For a widen that is the + /// newly-in-scope files plus the open buffers, not the whole scope. + /// + /// **Paths, not texts.** A file's text is read at the step that indexes + /// it; see [`Workspace::scan_step`]. + pub(super) work: Vec, + /// How many files at the front of `work` are the user's own + /// neighbourhood — see [`Scan::neighbourhood_indexed`]. + pub(super) head: usize, + /// The text of each open buffer among `work`, taken when the work list + /// was, so it describes the same bytes as that buffer's entry in + /// `analyzed` however the buffer is edited while the scan runs. + pub(super) buffered: HashMap, + /// What each file taken so far `` `include``s, read off the text at its + /// own step. Staged for the same reason `words` is: the include graph is + /// built once at the end and once per mid-scan publish, and by then the + /// text is gone. + pub(super) includes: HashMap>, + /// Files of `work` whose text could not be read when their step came, and + /// which therefore contribute nothing at all. Empty in every ordinary + /// scan: a file has to leave the disk between the walk and its own step. + /// Named so that the scan can leave it out of everything it lands — + /// `collect_sources` used to drop such a file before the work list + /// existed, and a whole scan must still take it *out* of the index. + pub(super) unread: Vec, + /// Every file that is in scope once this scan lands, kept flat so the + /// include graph's known-file table can be relearned from a slice. Which + /// files *exist* is settled the moment the scope is resolved, so this never + /// moves while the scan runs — reordering the tail of `work` does not + /// reorder a set. Equal to `work`'s paths for a whole scan; for a widen it + /// is the index's files plus `work`'s. + pub(super) paths: Vec, + /// What this scan takes *out* of the index, known before it starts. Empty + /// for a whole scan, which works out what left the scope from its own work + /// list once it has one ([`Workspace::finish_scan`]). + pub(super) gone: Vec, + /// What the open buffers among `work` already knew about themselves, taken + /// from as each of them is reached. + pub(super) analyzed: Analyzed, + pub(super) incdirs: Vec, + pub(super) warnings: Vec, + /// How many of `work` have been indexed. + pub(super) at: usize, + /// 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`]. + pub(super) staged: Vec, + pub(super) staged_at: Vec, + /// The completion words of every file taken so far, which the tables built + /// when the scan ends are assembled from. + pub(super) words: HashMap>, + /// How many files the size cap kept out, and how many came from the + /// persistent cache instead of a parse. Facts about this scan, so they + /// live on it — the end message names both. + pub(super) skipped: usize, + pub(super) cached: usize, + /// What this scan spent its time on, when `--verbose` asked. Off, it is a + /// bag of zeroes nobody reads (`crate::scan_trace`). + pub(super) trace: ScanTrace, +} + +/// Which of the two shapes a [`Scan`] is. +/// +/// One enum rather than two `finish` methods so a caller cannot pair the wrong +/// ending with a scan: the scan itself says how it must be landed. +#[derive(PartialEq, Eq)] +pub(super) enum ScanKind { + /// Every in-scope file, and whatever the index holds that the work list + /// does not name has left the scope. + Whole, + /// Only the files a scope widen brought in, folded into the index beside + /// what is already there (`docs/features/index-scope/README.md`). + Widen, +} + +impl Scan { + /// How many files the size cap kept out of this scan. + pub fn skipped(&self) -> usize { + self.skipped + } + + /// How many files came from the persistent cache instead of being parsed. + pub fn cached(&self) -> usize { + self.cached + } + + /// How many files this scan will index — known before the first parse, + /// which is what lets the caller decide whether the scan is long enough to + /// be worth answering messages in the middle of. + pub fn total(&self) -> usize { + self.work.len() + } + + /// Whether this scan has stepped every file of the user's own + /// neighbourhood — the open buffers and the folders they raise to + /// ([`crate::scan_order`]). + /// + /// **What a request held for the startup scan waits for.** A mid-scan + /// answer reads the published prefix, and a prefix holding the user's own + /// buffer and the alphabet after it names nothing they asked about: the + /// first useful answer of a workspace-scoped session was measurably + /// *empty* (`docs/features/perf5-p4/README.md` §P4b2). Waiting for the + /// neighbourhood makes it the answer the folder scope would have given, + /// which is what it was before the startup scan was staged. Requests that + /// arrive after that are answered at every interleave point as they always + /// were, and a scan with no neighbourhood (nothing open, an `untitled:` + /// 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 + } + + /// The text of one file of this scan's work list, at the moment its step + /// comes — `None` when it cannot be read. + /// + /// An open buffer's is the copy taken when the work list was, and it is + /// *taken*: a scan indexes each file once, so holding it afterwards would + /// be holding a second copy of a buffer the workspace already has. Every + /// other file is read from disk here and nowhere else in the scan. + pub(super) fn take_text(&mut self, path: &Path) -> Option { + if let Some(text) = self.buffered.remove(path) { + return Some(text); + } + let reading = self.trace.now(); + let text = fs::read_to_string(path).ok()?; + scan_trace::count_read(); + self.trace.saw_read(text.len(), reading); + Some(text) + } + + /// The files this scan has not reached yet, for a caller that wants to + /// re-order them ([`Scan::reorder`]). + pub fn remaining(&self) -> Vec { + self.work[self.at.min(self.work.len())..].to_vec() + } + + /// Put `ordered` — [`Scan::remaining`] ranked again — back as what is left + /// to index, and take its head segment as the new neighbourhood. + /// + /// The open-first rule, applied to a buffer opened *after* the work list + /// was taken: a `didOpen` answered mid-scan puts that file and the folder + /// around it next rather than leaving the user waiting for the alphabet to + /// reach them. Reordering the tail cannot change the finished index — + /// records are merged in path order whatever order they were taken in + /// ([`vlog_semantic::IndexBuilder`]) — so this is a latency decision and + /// nothing more. + pub fn reorder(&mut self, ordered: WorkList) { + let at = self.at.min(self.work.len()); + self.work.truncate(at); + self.work.extend(ordered.files); + // What is left to wait for, bounded against the whole scan rather than + // against the tail it was ranked from + // ([`crate::scan_order::worth_waiting`]), and then placed: the + // neighbourhood ends that many files past where the scan has got to. + self.head = match scan_order::worth_waiting(ordered.head, self.work.len()) { + 0 => 0, + pending => at + pending, + }; + } +} + +/// What each of `taken` `` `include``s, as [`IncludeGraph`] wants it. +/// +/// Borrowed, never cloned: the lists were read at each file's own step and the +/// graph only reads them again ([`crate::includes::IncludeGraph::from_includes`]). +/// +/// A free function rather than a method because the two callers hold the map +/// differently — a mid-scan publish still has the whole [`Scan`], and the two +/// `finish` paths have taken it apart. +pub(super) fn included<'a>( + includes: &'a HashMap>, + taken: &'a [PathBuf], +) -> Vec<(&'a Path, &'a [Include])> { + taken + .iter() + .map(|path| (path.as_path(), includes.get(path).map(Vec::as_slice).unwrap_or(&[]))) + .collect() +} + +/// What an index rebuild reports about itself as it runs. +/// +/// This module speaks no protocol, so an event carries numbers and paths and +/// nothing that reads like a message; `server.rs` turns them into a progress +/// report and a log line (`docs/features/indexing-ux/README.md`). +pub enum IndexEvent<'a> { + /// One file is about to be parsed into the index: how many were parsed + /// before it, how many there are in all, and which one it is. `done` + /// counts from 0, so the file being reported is number `done + 1` of + /// `total`. + Parsing { done: usize, total: usize, path: &'a Path }, + /// One file went into the index from the persistent cache instead of + /// being parsed. The same three numbers [`IndexEvent::Parsing`] carries, + /// because it is the same file of the same work list — it is *how* it got + /// there that differs, and a user watching a rescan fly through a + /// thousand files deserves to be told why. + Cached { done: usize, total: usize, path: &'a Path }, + /// One file went into the index from the analysis an **open buffer** + /// already holds — the parse this server did when the buffer was last + /// opened or changed — instead of being parsed again. The same three + /// numbers the other two carry, for the same reason. + /// + /// Its own variant rather than [`IndexEvent::Cached`] so that "from cache" + /// keeps meaning the persistent store and nothing else + /// (`docs/features/index-persistence/README.md`): a buffer's own analysis + /// is in memory, is there whether that store exists or not, and is right + /// even when the buffer has unsaved edits — which is exactly when a + /// content-keyed store has nothing to offer. + Analyzed { done: usize, total: usize, path: &'a Path }, + /// A walked file was skipped without being read, because it is bigger + /// than the size cap in force. + Skipped { path: &'a Path, size: u64, cap: u64 }, +} diff --git a/docs/features/folders-and-config/README.md b/docs/features/folders-and-config/README.md index 7f1064c..477fdb9 100644 --- a/docs/features/folders-and-config/README.md +++ b/docs/features/folders-and-config/README.md @@ -74,6 +74,13 @@ parser** a push does, so the two paths cannot drift. first index is built against the default scope, and a pulled `lucisv.exclude`/`lucisv.filelist` costs one extra rescan when it lands. Nothing is *wrong* in between, it is simply the wider scope. + **2026-09-08 (perf5-p4 §P4b2):** no longer true of the common case. The + startup is now staged: the pull goes out first and the one startup scan + runs at the answered scope (`server/startup.rs`), so a pulled + `exclude`/`filelist`/`maxFileSize` costs nothing extra; the sentence above + describes only an answer that arrives after the 2 s bound + (`CONFIGURATION_WAIT`), which is then an ordinary settings change with an + ordinary rescan behind it. **2026-08-27:** `lucisv.index.maxFileSize` joins those two — a pulled cap that differs from the 1 MiB default costs the same one extra rescan — and `lucisv.index.logFiles` shows the other face of the same fact: the startup diff --git a/docs/features/index-persistence/README.md b/docs/features/index-persistence/README.md index b1c8114..108158c 100644 --- a/docs/features/index-persistence/README.md +++ b/docs/features/index-persistence/README.md @@ -101,6 +101,42 @@ and the bar says `860 files indexed, 860 from cache` so the user can see it. the session and one line after the next whole rescan, and a record whose file no longer exists is dropped at that rewrite, exactly as `lucisv_core::cache::store` drops its own. +- **…and the rewrite is skipped when it would reproduce the file byte for + byte** (2026-09-08, take 5 §P4b (a)). `render` writes this build's header and + then one line per path in path order, so a store this build compacted and + nothing has appended to since *is already* what the next compaction would + write over it. Four conditions, all of them properties of what + `IndexCache::open` read: the header was ours, every line was a record this + build could use (none dropped), no path was named twice, the paths arrived + ascending — **and** the session appended nothing since, **and** no entry's + file has gone (`render` drops those). Any one of them failing rewrites + exactly as before. **This weakens no promise in this README**: growth is + still one line per path, because a store that grew has appends and therefore + compacts; a record whose file is gone is still pruned, because a gone file + fails the sweep; and crash safety is untouched, since a session that appended + nothing left the file exactly as it found it and there is no half-written + state for a rewrite to resolve. The one thing that is deliberately *not* + claimed: an unreadable line inside an otherwise-good store is dropped at load + as it always was, and a rewrite is what removes it from disk — that rewrite + now happens on the first scan that also appends something rather than + necessarily on the next one. It cost 182 ms of a 1.33 s warm start on + opentitan, and every one of the six cases above is pinned + (`index_cache::tests::a_canonical_store_nothing_appended_to_is_not_rewritten` + and its five siblings). +- **A record the store already holds is not appended again** (2026-09-08, take + 5 §P4b (a)). An open buffer is indexed from its *own* analysis on every scan + and its record is written through with it, so a warm session would append one + byte-identical duplicate line per open buffer — a line the next load + collapses, at the price of making the store non-canonical and so owing the + compaction above a full rewrite. `IndexCache::record` now returns early when + the entry it is about to write is already there under the same path, the same + content hash and the same encoded facts, byte for byte. Anything that differs + by a byte is appended exactly as before, which is what keeps "the store says + what this session last saw" true. Nothing else changes: the entry map is the + same either way, so a hit is the same hit, and a session that appended + nothing left the store exactly as it found it. Without this the skip above + never fires in a real editor session, measured: opentitan warm, `records` 1 + and `compact` 88 ms on every scan with a buffer open. - **A save writes its record through too**, on the incremental path, without a second parse — `WorkspaceIndex::facts_for` hands back the record `update_file` just made. An hour of saves is an hour of work the next @@ -276,8 +312,24 @@ pub fn cache_dir(settings: &ClientSettings, storage: Option<&Path>, - `Workspace` gains the cache and the storage path: `Workspace::set_storage_path(Option)`, called once before the first - build. The cache is re-opened at the top of every whole rescan, because the - settings that decide where it lives arrive after startup. + build. The cache is re-opened for every whole rescan, because the settings + that decide where it lives arrive after startup. **Amended 2026-09-08 (take + 5 §P4b (b1)): the re-open is deferred to the first file of that rescan that + asks the store something**, rather than run before the work list's first file + exists. The rule itself is unchanged — every whole rescan still resolves the + directory afresh and reads the store from it, and both of the reasons for + that (a mid-session `cachePath`/`persist` change, and a second session's + records this one has not seen) hold exactly as written. What changed is that + a rescan whose work list is **empty** asks nothing and therefore reads + nothing: `Workspace::begin_scan` records the directory as `StoreOpen::Deferred` + and `Workspace::scan_step` (and the save path's write-through) opens it. The + deferral is a *move*, never a drop — a widen behind an empty rescan still + finds the store open at its own first file, which is what keeps its cache + hits (`state::tests::a_scan_with_no_files_neither_reads_the_store_nor_rewrites_it` + pins both halves). `finish_whole_scan` does not compact a store no scan of + this session ever opened. A settings change that drops the cache + (`persist`/`cachePath`) drops the deferral with it, so `persist: false` still + takes effect at once in both directions. - `IndexEvent::Cached { done, total, path }` — the same three numbers `Parsing` carries, for a file that cost nothing. Every existing consumer of the enum had to grow one arm, which is the compiler making the distinction @@ -852,6 +904,74 @@ after the whole run, still absent. The `#[ignore]`d probe was re-run in both profiles for the Measured table above, and the four-writer race test was run ten times in a row: 100 of 100 records every time. +### 2026-09-08 — dev agent (perf take 5 §P4b: two things the store stops doing) + +Two changes, both in this feature's contract, both amended above rather than +only recorded here. Neither touches the record format, the key, the header, +the claim/append protocol, the per-record checksum, the byte-wise load or the +torn-record rule; `FACTS_FORMAT` and `CACHE_FORMAT` are untouched. + +- **A compaction that would reproduce the file is skipped** (Assumptions, the + new bullet under the write-through rule). The store `render` writes is + canonical — this build's header, one line per path, path order — so + `IndexCache::open` now *counts* what it read (lines read, kept, dropped, + duplicated, and whether the paths ascended) and `compact` asks whether the + rewrite would be the same bytes: loaded canonical, nothing appended since, + and no entry's file gone. The existence sweep is one `stat` per entry, which + is a subset of what `render` already does per entry, so the check costs a + fraction of the rewrite it replaces. On opentitan this is the whole of a warm + session's two compactions — 182 ms of a 1.33 s start — both of which were + measured writing a byte-identical 44.3 MiB file (§P4a: `store_before_kib` = + `store_after_kib` = 45 396, `records` 0 and 1). +- **A write-through the store already holds is not written again** + (Assumptions, the new bullet beside the save's write-through). This was not + in the ruling and is reported as a scoped addition, because without it the + skip above **never fires in a real session**: an open buffer's record is + written through on every scan, so `records` is never 0 and the store is never + canonical. Measured on opentitan before it: warm `compact` 88.19 ms and + `compactions` 1 on the configured rescan, i.e. the whole of (a) defeated by + one duplicate line. After it: `records` 0, `repeats` 1, `compactions` 0, + `compact` 10.13 ms — and that 10.13 ms is the skip's own existence sweep over + 3 976 entries, against the 90.20 ms rewrite it stands in for. +- **A rescan opens the store at its first file, not before it** (Handshakes, + `lucisv_server::state`). The re-open rule is unchanged and both of its + reasons still hold; only the moment moved. It exists because a session's + *first* scan runs at the default settings, before `workspace/configuration` + can be asked, and with no buffer open its folder scope — and therefore its + work list — is empty: warm, that scan was reading 44.3 MiB and rewriting it + for a scan that indexes nothing. The deferral is a move, not a drop, which + is the one way this could have gone wrong: the widen a `didOpen` triggers + never opened the store itself (it reads the handle `begin_scan` left), so + dropping the open would have silently cost that widen every one of its cache + hits. It is pinned from the failing side — + `state::tests::a_scan_with_no_files_neither_reads_the_store_nor_rewrites_it` + reports `parsed: ["b.sv"]` when the open is dropped instead of deferred. + +**What was deliberately not done.** Reusing the store a previous scan of the +same session already read — the third of §P4a's candidates, worth another +91 ms — was **refused by the lead**, and this README is the reason: the reopen +guards a mid-session `cachePath`/`persist` change and a second session's +compaction replacing the file under an append handle. Nothing here weakens +either. + +**Tests.** Eight new in `index_cache.rs` (a canonical store is not rewritten, +a record the store already holds is not appended again, and one each for a +duplicated path, an unreadable line, out-of-path-order records, a session that +appended, a file that is gone, and another version's header), three new in +`state.rs` (the warm rescan leaves the store untouched; +a scan with no files neither reads nor writes it and the widen behind it still +hits; a cold session that indexes nothing creates no store at all), one new +wire test in `server/tests/scan_trace.rs` (both halves over the real dispatch, +by the trace's own new `opens=` / `compactions=` counters). Every pre-existing +test in this feature is untouched and green, the interrupted-store ones +included: `a_record_survives_a_session_that_never_compacted`, +`a_torn_final_record_costs_one_file_and_nothing_else` and +`truncating_the_store_at_every_byte_offset_costs_only_the_torn_record`. +Verified that the six guard tests really guard: with `already_compact` +widened to "there is a directory", all six fail, as do +`compaction_keeps_one_line_per_path_and_drops_the_files_that_are_gone` and +`nothing_is_created_until_something_is_recorded`. + ## QA log ### 2026-08-27 — QA agent (attack surfaces on the persistent index cache) diff --git a/docs/features/index-scope/README.md b/docs/features/index-scope/README.md index 557cdd5..ccaa222 100644 --- a/docs/features/index-scope/README.md +++ b/docs/features/index-scope/README.md @@ -606,6 +606,95 @@ and it is where the measured cost was. ## Work log +### 2026-09-08 — §P4b3: the read moment, and the order the walk is indexed in + +**Two documented behaviours moved. The scope ladder itself — precedence, the +rungs, `raised`, the widen chooser, rootless — is unchanged, and no test of it +was touched** (`docs/features/perf5-p4/README.md` §P4b3). + +**1. When a file's text is read.** `collect_sources` resolved the scope *and +read every in-scope file* before a scan's first step: 34 MiB and ~293 ms on +opentitan, held for the whole life of the scan. It now resolves the scope and +reads nothing off disk; `Workspace::scan_step` reads a file's text when its +step comes and drops it at the end of that step. What follows for this feature: + +- **The size cap is where it was.** `oversize` is still a `fs::metadata` call + in `collect_sources`, still ahead of any read, so an oversized file is still + never read and its `IndexEvent::Skipped` and its place in `Scan::skipped` are + reported before the first step — which is what the progress bar's denominator + and the end message depend on. +- **An open buffer's text is still taken with the work list**, beside the + analysis that describes the same bytes, so a `didChange` mid-scan cannot make + the two disagree. That is the rule this README's widen section already + states, unchanged. +- **A *closed* file's text is now the text it has when the scan reaches it**, + not the text it had when the work list was taken. Nothing is incoherent: the + facts, the words and the `` `include`` lines of a file all come out of one + read, so a file's contribution is internally consistent either way. A file + that has left the disk by then contributes nothing and is taken **out** of + the index by the whole scan that could not read it, which is what dropping it + before the work list existed used to achieve. +- `sources()` — what a refactoring reads — is the one caller that still wants + every file's text at once, and it is where that read now happens. + +**2. What order the walk is indexed in.** `Workspace::open_first` put the open +buffers' own files at the front. It now ranks three groups +(`crate::scan_order`): the open buffers' own files, then everything under the +directories those buffers **raise** to, then the rest in path order. The raised +directory is this feature's own `Workspace::raised`, asked **whichever rung is +in force** — under a filelist or an explicit `workspace` scope it is not a +*scope* question but the only thing that says which part of a 4 000-file walk +to index first, so `Workspace::raised_dirs` answers it where +`Workspace::scope_dirs` (a scope question) still answers `[]`. + +It remains a latency and reporting decision and nothing more: `index_order` +sorts and dedups first, `IndexBuilder::finish` sorts by path, and the finished +index, the completion tables and the include graph are equal to a scan with +nothing open — measured on opentitan as **24 of 24 identical scope answers** +and a **byte-identical persistent store**, and pinned by +`the_open_buffers_folder_is_indexed_before_the_rest_and_the_index_cannot_tell`. + +### 2026-09-08 — dev (Opus), §P4b2: the startup scan now runs at the *answered* scope + +**The ladder is unchanged. What moved is when the first scan reads it.** +`Server::started` used to build the index at the **default** rung — the folder +scope, which with no buffer open resolves to nothing at all — and only then ask +the client for its settings; a client that wanted `index.scope: "workspace"`, +a `scopeDepth`, an `exclude` or a `filelist` therefore paid a *second*, whole +rescan when its answer landed. Since today the settings pull goes out first and +the startup scan waits up to two seconds for the answer, so a session runs +**one** scan, at the rung the answer selected (`server/startup.rs`, +`docs/features/perf5-p4/README.md` §P4b2). + +Nothing about the ladder itself changed: + +- **precedence is untouched.** `lucisv.filelist` still beats + `lucisv.index.scope`, which still beats `scopeDepth`, which still beats the + default folder scope; the same `ClientSettings` goes into the same + `set_client_settings`, only earlier. Measured across all eight + (scope × cache state) cells of `tools/perf/bench.py scan`, which answer with + identical file and cache-hit counts. +- **the rootless rule is untouched.** A session with no roots resolves its + scope from the directories a `didOpen` raised, exactly as before; a `didOpen` + arriving during the configuration window installs its buffer and the one scan + that follows sees it, with `open_first` putting that file at the head of the + work list. +- **the widen chooser is untouched.** `widen_of` still decides Nothing / Added + / Whole; what changed is only that a widen asked for *before the first scan + has run* is folded into that scan instead of being run as a scan of its own — + the same deferral `reindex_widened` has always applied mid-scan, now also + applying in the window before the first scan starts. +- **a client that cannot be asked, or that never answers, is exactly as it + was**: the scan runs at the defaults immediately (or after the bound), and a + late answer costs the one rescan a changed scope has always cost. + +The one visible consequence for this feature: the *empty* default-scope startup +scan a workspace-scoped client used to pay is gone, and with it the widen the +first `didOpen` used to trigger behind it. A session that gets its answer runs +one scan; a session that does not runs the two it always ran. Pinned by +`server/tests/startup.rs` and by this feature's own ladder tests, green +unmodified. + ### 2026-08-29 — dev agent (the first RTL open at the shipped depth) **The brief's diagnosis did not survive the first measurement, and that is the diff --git a/docs/features/indexing-ux/README.md b/docs/features/indexing-ux/README.md index 8bc8447..8257ef8 100644 --- a/docs/features/indexing-ux/README.md +++ b/docs/features/indexing-ux/README.md @@ -192,6 +192,21 @@ pub fn build<'a>(files: …) -> WorkspaceIndex { wants to say about a file that was not parsed. - `ClientSettings::max_file_size` is read in `collect_sources`; nothing else in `state.rs` changed. + **Amended (perf5-p4 §P4b3, 2026-09-08):** `collect_sources` no longer reads + any file's text — a scan reads a file when it indexes it — but the cap is + untouched and is still a `fs::metadata` call *there*, ahead of any read. That + matters to this feature for three reasons the bar depends on: the skips are + still counted and reported **before the first file is parsed**, so + `Scan::total` is still known up front and still excludes them; the events are + still emitted in the same order for the same files, so + `a_scan_reports_the_same_events_in_the_same_order_however_it_is_driven` is + unchanged; and a file whose text has gone by the time its step comes reports + **no event at all** and is **not** counted as a cap skip — it is not a file + the cap kept out, and saying so would be a lie in the end message. The + per-file log's *order* did move: the work list now leads with the open + buffers' own files and then the folders those raise to + (`docs/features/index-scope/README.md`), so a user watching a rescan sees + their own neighbourhood go by first rather than the alphabet. ### `lucisv_server::settings` diff --git a/docs/features/perf5-p4/README.md b/docs/features/perf5-p4/README.md index 054413e..189e30d 100644 --- a/docs/features/perf5-p4/README.md +++ b/docs/features/perf5-p4/README.md @@ -94,6 +94,84 @@ a request for the lead to apply at merge, not a silent edit: payload. Both are internal to `lucisv_server`. 6. The `verbose-timing` amendment above. +**§P4b adds three, all internal to `lucisv_server`** and all additive: + +7. `CacheWork` gains `opens`, `compactions` and `repeats`, rendered on the + count line as `opens=`, `compactions=` and `repeats=`. The + `verbose-timing` amendment in (6) covers them — the line is already parsed + by `tools/perf/phases_p4.py`, which splits `key=value` and needs no change. +8. A private `StoreOpen` state on `Workspace`: a whole rescan's re-open of the + persistent store is deferred to the first file that asks it something. + **This amends `docs/features/index-persistence/README.md`'s + `lucisv_server::state` handshake**, and that README carries the amendment + in full — the rule is unchanged, only the moment moved. +9. `ScanTrace` gains `opened`, `measure_work` and `landed` (the three helpers + moved out of `state.rs`), so the `scan_trace` module now reads + `Candidates`, `IncludeGraph`, `IndexCache` and `WorkspaceIndex`. Read-only, + through the queries edge (4) already added. + +**§P4b2 adds two.** The first is internal and additive; the second is a +**request for a change this lane did not make**. + +10. A new server module `server/startup.rs`, holding `Server::new`, + `Server::started` (whose six trailing parameters became a `Startup` + struct), the settings wait and `CONFIGURATION_WAIT`. `Server` gains a + private `staging: bool` and the private helpers `scan_owed`, + `waiting_for_this_scan` and `take_the_answer_out_of_held`. All internal to + `lucisv_server`; nothing crosses a crate edge. **Two contracts are + amended in their own READMEs**, both by this lane and both stating the + rule is unchanged: `docs/features/scan-interleave/README.md` (the startup + scan now runs *after* the settings answer, and the requests held in the + window before it are handed to it — a rescan still takes none) and + `docs/features/index-scope/README.md` (the first scan resolves the + *answered* rung; precedence, rootless and the widen chooser untouched). + **`docs/features/folders-and-config/README.md` describes the pull's timing + in its Assumptions and is not this lane's file** — the sentence that a + pulled `lucisv.exclude`/`lucisv.filelist` "costs one extra rescan when it + lands" is now true only of an answer that arrives after the bound. That + edit is a request for the lead. +11. **Requested, not made: `Workspace::open_first` should order the work list + by the open buffers' *raised scope directories*, not only by the buffers + themselves.** With one startup scan, the prefix a mid-scan request reads is + the alphabet after the user's own file, so the first useful answer of a + workspace-scoped session is empty (measured above). Ordering cannot change + what the index holds — `IndexBuilder::finish` sorts by path, which is the + argument `open_first`'s doc comment already makes — so this is a reporting + and publish-order change, not a semantic one. `state.rs` is **calls only** + for this lane, so it stops here. + **Granted and done by §P4b3 (2026-09-08).** + +**§P4b3 adds four**, all internal to `lucisv_server` and all additive except +the two `state.rs` shapes, which the lane owns: + +12. A new server module `crate::scan_order`: `work_list`, `worth_waiting` and + `WorkList`, the three-group ranking a scan's work list is ordered by. + Consumed by `state.rs` alone. +13. **`state.rs` is now `state/mod.rs` + `state/scan.rs`** — a pure move of + `Scan`, `ScanKind`, `IndexEvent`, `Sources`, `Analyzed` and `HeldAnalyses` + into a child module, so `Workspace` sees exactly the fields it saw before + (`pub(super)` = inside `crate::state`, which is where they were). Public + paths are unchanged: `crate::state::{Scan, IndexEvent}` re-export from + `state/mod.rs`. `Scan::index_next` is **replaced** by + `Scan::remaining`/`Scan::reorder` plus `Workspace::open_next`, because a + `didOpen` answered mid-scan now brings its folder with it and not only its + own file. +14. `Candidates::from_words` and `IncludeGraph::from_includes` / + `absorb_includes` — the entries a caller that already holds a file's words + and `` `include`` lines uses. `Candidates::build` and `IncludeGraph::build` + are those same functions with the lex and the scan in front of them, and + are now `#[cfg(test)]`: nothing in the server holds a file's text long + enough to call them. `IncludeGraph::absorb` is **deleted** — it had no + caller left. +15. `Server::head_owed`, a fifth `must_wait` clause, and + `crate::scan_trace::{source_reads, count_read}` — a thread-local read + counter in the shape of `vlog_parser::stats::parses`. `ScanTrace` gains + `read_ms`, `work_bytes` and `saw_read`; the stage line gains `read=` and + `work_kib` on the memory line changes meaning (below). The + `verbose-timing` amendment in (6) covers the line change; a **stage was + added**, so `tools/perf/phases_p4.py` reads it without a change and + `the_stages_add_up_to_the_scan_they_describe` names it. + ## What the trace prints Three lines per scan, each `timing: scan (, …): key=value …`. @@ -117,11 +195,691 @@ Plus one line at the settings pull: `timing: configuration answered in X ms`. a rescan is its own numbered scan - [x] `tools/perf/phases_p4.py` — `scanprofile`, `scanwait`, `scanserve` - [x] measured breakdown (below), tracker rows and the §P4b recommendation -- [ ] QA -- [ ] lead ruling on §P4b +- [x] QA (§P4a) +- [x] lead ruling on §P4b (2026-09-08, in Review below) + +### §P4b — the ruled fixes (2026-09-08) + +- [x] **(a)** `IndexCache::compact` is skipped when the rewrite would + reproduce the store byte for byte — loaded canonical, nothing appended, + no entry's file gone. Seven tests in `index_cache.rs`, one in `state.rs` +- [x] **(b1)** a whole rescan opens the store at its **first file** instead of + before its work list exists, so a scan with no files reads nothing and + compacts nothing; the open is *moved*, not dropped, so the widen behind + it keeps its hits. Three tests in `state.rs`, one wire test +- [x] **(b2) not taken** — the store is still re-opened for every non-empty + whole rescan, exactly as `index-persistence` requires. Refused by the + lead; nothing in this lane touches it +- [x] the rescan-interleaving question answered: **not routing** — the + configured rescan already runs through the same stepper the startup scan + does. What holds navigation is `Server::must_wait`'s `answering_a_rescan` + clause, which is the scan-interleave order contract. **Filed for the + lead, not changed** (below) +- [x] pure move: `opened_trace` / `measure_work` / `landed` out of `state.rs` + into `scan_trace.rs` as `ScanTrace::opened` / `measure_work` / `landed` +- [x] two new count-line fields, `opens=` and `compactions=`, so the change is + observable to `tools/perf/phases_p4.py` and to a wire test +- [x] measured (below), tracker row + cells + experiment `P4b-2026-09-08` +- [ ] QA (§P4b) + +### §P4b2 — the staged startup (2026-09-08) + +- [x] `server/startup.rs`: the settings pull goes out first; + `await_configuration` waits on `recv_timeout` up to + `CONFIGURATION_WAIT` (2 s); the session then runs **one** + `scan_until_settled(false)` at the answered scope +- [x] the bounded fallback: no capability, or no answer inside the bound → + the scan runs at the defaults exactly as before, and a late answer is + an ordinary settings change with an ordinary rescan behind it +- [x] messages in the window: a `didOpen`'s widen (and every other rescan + trigger) is folded into the one scan via `Server::scan_owed`; a request + is held by `must_wait`'s new `staging` clause and handed to the startup + scan by `Server::waiting_for_this_scan`, which a rescan never reaches +- [x] the defect measurement found: a settings answer stranded in `held` + behind a request, costing the whole bound — `take_the_answer_out_of_held` +- [x] six wire tests in `server/tests/startup.rs`; the one pre-existing test + whose subject was the old wire order amended in place; scan-interleave's + and index-scope's suites green unmodified +- [x] measured (below), paired against the previous §P4b release; tracker row + + cells + experiment `P4b-staged-2026-09-08` +- [x] **the empty first useful answer is closed by §P4b3 below** (Handshakes + 11, granted). `folders-and-config`'s Assumptions sentence about the + pull's timing still needs the lead's edit (Handshakes 10) +- [ ] QA (§P4b2) + +### §P4b3 — the lazy read and the folder-first order (2026-09-08) + +- [x] **the read is lazy**: `collect_sources` resolves the scope and reads + nothing off disk; `scan_step` reads a file's text when its step comes and + lets it go again. `Scan` holds paths, the open buffers' texts and the + `` `include`` lines each step found — not 34 MiB of source +- [x] **read once, proved by a counter**: `scan_trace::source_reads`, a + thread-local in the shape of `vlog_parser::stats::parses`; a whole scan + reads each file's bytes exactly once and an open buffer's not at all +- [x] the include graph and the completion tables are re-fed without a second + read — `IncludeGraph::from_includes`, `Candidates::from_words` — and are + pinned equal to what the texts build +- [x] a file that leaves the disk between the walk and its own step is + `unread`: no event, not a cap skip, and taken *out* of the index by the + whole scan that could not read it +- [x] **folder-first order**: `crate::scan_order` ranks the work list open + buffers → the folders those buffers raise to → the rest in path order, + and reports the head segment. `Workspace::open_next` re-applies it for a + `didOpen` answered mid-scan +- [x] **the drain rule**: `Server::head_owed`, a fifth `must_wait` clause. A + held request is answered once the user's own folder has been stepped and + published; a burst's `didOpen` holds what is behind it until the folder + it named is in. A scan with no neighbourhood drains at the first + interleave point exactly as before +- [x] the head is bounded (`scan_order::worth_waiting`): a folder that is not a + minority of the workspace is not waited for +- [x] pure move: `state.rs` → `state/mod.rs` + `state/scan.rs` +- [x] measured (below); tracker row + cells + experiment `P4b-lazy-2026-09-08` +- [ ] QA (§P4b3) ## Work log +### 2026-09-08 — dev (Opus), §P4b3: the read is lazy and the order is the user's + +**§P4b2 left one thing open and this is it.** The first useful answer of a +warm workspace session was unimodal and **empty** — result count 0 in six +sessions of six — for two reasons the trace named: `begin_scan` read all 3 976 +files (34 MiB, ~293 ms) before the first `scan_step`, and the held definition +was then answered at the first drain, off a prefix holding the open buffer and +the alphabet after it. Both are fixed here, and the answer is **result count 1 +in twelve sessions of twelve**. + +#### 1. A file's text is read at the step that indexes it + +`collect_sources` now resolves the scope and reads **nothing** off disk. It +returns paths, the size cap's skips (still `fs::metadata`, still reported and +counted before the first step, so the progress bar's denominator and +`Scan::skipped` are what they were) and the **open buffers' own text**, which is +in memory already. `Scan::work` is `Vec`; `Scan::take_text` hands a +step its file's text and drops it at the end of that step. + +**An open buffer's text is still snapshotted with the work list**, deliberately: +`Scan::analyzed` holds that buffer's finished analysis, and the two must +describe the same bytes however the buffer is edited while the scan runs — which +is what `a_buffer_opened_or_changed_mid_scan_does_not_change_what_the_scan_indexes` +pins. A **closed** file is read when its step comes, so the one contract that +moved is the read *moment* for disk files; the entry in +`docs/features/index-scope/README.md` says so. + +**Everything the scan wants out of that text is taken in the one step**: the +content hash the store is keyed by, the parse, and — new here — the file's +`` `include`` lines, staged beside its facts and its words. So the graph and +the completion tables are built at the end from what the steps gathered rather +than from texts nobody holds any more: + +| built from | before | now | +|---|---|---| +| `Candidates` | `build(index, &work, words)` — `words` already covered every file, so the text was never lexed | `from_words(index, words)` | +| `IncludeGraph` | `build(&work, incdirs)` — **re-scanned every file's text** | `from_includes(&found, incdirs)` | + +`Candidates::build` and `IncludeGraph::build` are those same functions with the +lex and the scan in front of them, so a test can still build tables from a +fixture's text and the two are provably one function; both are `#[cfg(test)]` +now, because nothing in the server holds a text long enough to call them. +`IncludeGraph::absorb` had no caller left and is deleted. + +**Read-once is counted, not asserted.** `crate::scan_trace::source_reads` is a +thread-local counter in the shape of `vlog_parser::stats::parses`, incremented +on the one disk read in `Scan::take_text`. +`a_whole_scan_reads_each_files_bytes_exactly_once` measures the delta across a +scan of a twelve-file tree: **12**, and **11** with a buffer open. + +**A file that leaves the disk between the walk and its own step** is remembered +as `unread`. It reports no event and is not a cap skip — which is exactly what +`collect_sources` used to do by dropping it before the work list existed — and +`finish_whole_scan` takes it *out* of the index by leaving it out of `held`, so +it lands in `gone`. Without that it would have stayed in the index with a stale +record, which is the one thing the lazy read could have broken silently. +Pinned by `a_file_that_leaves_the_disk_between_the_walk_and_its_step_leaves_the_index`. + +#### 2. The work list leads with the user's own folder + +`crate::scan_order` ranks a work list in three groups — the open buffers' own +files, then everything under the directories those buffers **raise** to +(`Workspace::raised`, the scope ladder's own rule, whichever rung is in force), +then the rest in path order — and reports how many files that head segment is. +`index_order` still sorts and dedups first, and `IndexBuilder::finish` still +sorts by path, so **no insertion order can reach the index**: the fingerprint +and every table are equal to a scan with nothing open +(`the_open_buffers_folder_is_indexed_before_the_rest_and_the_index_cannot_tell`). + +**The head is bounded.** A buffer opened from a workspace *root* raises to that +root, and "its folder" would then be the whole scan; `scan_order::worth_waiting` +returns 0 for a neighbourhood that is not a minority of the workspace, and the +drain falls back to the first interleave point exactly as before. The bound is +against the **whole** scan and never against what is left of it, because a +`didOpen` can arrive at any point and 124 files is 124 files of waiting whether +the scan has done none of the workspace or nine tenths. + +#### 3. A held request waits for that folder — and so does one behind a `didOpen` + +`Server::head_owed` is a fifth `must_wait` clause and the whole of the drain +rule. `answer_what_is_waiting` sets it from `Scan::neighbourhood_indexed` +before it takes anything, so `waiting_for_this_scan` hands the startup scan its +held requests only once the folder has been stepped — and the `publish_scan` in +that same call is what makes the folder answerable before the answer goes out. + +**The measurement forced the second half of this rule, and it is the half that +matters in a real session.** The first paired run had the ordering and the +drain rule and still answered `[]` in five sessions of six. The reason is that +the client answers `workspace/configuration` from its own reader thread, so the +answer usually beats the editor's `didOpen`: the scan begins with **no buffer +open**, its work list is the plain alphabet, and the `didOpen` and the +definition behind it arrive at an interleave point some way in. At workspace +scope a `didOpen` widens nothing, so nothing held them and the definition was +answered off that alphabet. Now a burst carrying a `didOpen` sets `head_owed` +*before* the burst is applied — so the requests behind it are held, exactly as +the widen this `didOpen` used to trigger held them — and `Workspace::open_next` +re-orders what is left of the work list around the buffers open now. That +replaces `Scan::index_next`, which moved one file: a buffer brings its folder +with it. + +`crowd/` sorting before `ip/` in +`a_did_open_answered_mid_scan_pulls_its_folder_in_front_of_the_request_behind_it` +is what makes that a claim rather than a coincidence — 70 irrelevant files come +first in path order, and the answer cannot have come from the alphabet. Both +wire tests fail with `[]` when the flag is removed, checked from the failing +side. + +**The coherence contract is untouched**: three tables published together, and +`scanserve`'s `mismatched_answers` is 0 in all four rows of both binaries. + +#### 4. Where the code lives + +`state.rs` had grown 67 production lines, and the rule for this lane is that it +must not. The **pure move** that pays for it is `state.rs` → `state/mod.rs` + +`state/scan.rs`: `Scan`, `ScanKind`, `IndexEvent`, `Sources`, `Analyzed` and +`HeldAnalyses`, with their fields `pub(super)` — visible inside `crate::state`, +which is exactly where they were visible before. `crate::state::{Scan, +IndexEvent}` re-export, so no path outside the module moved. Production lines +(non-blank, non-comment, before `mod tests`): `state/mod.rs` **1 064** against +the **~1 074** this lane inherited, `state/scan.rs` 100, `scan_order.rs` 35, +`scan_trace.rs` 303, `includes.rs` 274, `candidates.rs` 406, +`server/index.rs` 198. Everything under 600. + +**One function is over the 80-line investigate mark and was already**: +`Workspace::begin_widen`, 96 lines before this lane and **101** after — the +five are the `buffered` map a widen now carries beside its work list. It is +one linear walk with four filters and then the open-buffer overlay, so there is +no seam in it that a split would fall on; noted rather than restructured, +because restructuring it is not this lane's subject and would be a behaviour +risk taken for a line count. + +#### §P4b3 — measured + +Release `lucisv-server` sha256 +`7ab4955ee0ac174840fbe4c02528e178f0c7824a3836fa87aa90e35bf47cdd3b`, paired +against **the shipped §P4b2 release**, sha256 +`7522696e894a94d8d431f148d4e08e6a9ab7727eb0aaac36f8daa57a684b9076`, kept from +before the rebuild and re-run in the same window. Every phase ran **alternating +P4b2 then P4b3**, three fresh sessions per cell, every session under +`tools/guard.sh -m 8 -t 1800`, no `cargo` command during any timed phase, zero +guard kills. opentitan `0098135264` with its three pre-existing modified files, +`git status --porcelain` checked after every phase of both binaries and never +otherwise touched. One-minute load **2.8–7.5** across the matrix, recorded +before and after each phase. Rows: +`~/.cache/lucisv-perf/take5-p4b3/results.jsonl`, labels `P4b2` and `P4b3`. + +**The first useful answer — the regression, closed:** + +| | P4b2 | P4b3 | paired | +|---|---|---|---| +| `scan`, cold | 288.11 / 286.68 / 287.41, **count 0** | 249.13 / 249.70 / 248.16, **count 1** | −13.4 % | +| `scan`, warm | 364.43 / 315.23 / 318.38, **count 0** | 272.78 / 290.81 / 268.52, **count 1** | −16.6 % | +| `scanwait`, cold | 275.13 / 283.30 / 273.38, **count 0** | 236.93 / 253.85 / 252.19, **count 1** | −11.0 % | +| `scanwait`, warm | 317.41 / 318.91 / 321.04, **count 0** | 273.98 / 266.90 / 281.63, **count 1** | −13.5 % | + +**Result count 1 in twelve sessions of twelve**, where §P4b2 was 0 in twelve of +twelve. That is the target this lane exists for, and it is met. + +**The latency target is missed, and the trace says exactly why.** The work +order asked for "at or below the REF's 84 cold / 208 warm, ideally ≈ walk + the +folder's 124 files". It **is** walk + the folder, and the walk is the whole of +the gap: + +| warm, traced | P4b2 | P4b3 | +|---|---:|---:| +| `discovery` (scope walk + the cap's `metadata`, and in P4b2 the 34 MiB read) | 227.02 | **158.32** | +| `read` (the per-step reads, new) | — | 85.54 | +| `cache_open` (at the first step) | 87.67 | 89.24 | +| `first_publish` | 316.74 | **249.70** | +| the definition answered at | 317.41 | **273.98** | +| files in that first publish | **1** | **125** | + +Warm, the floor is `discovery` 158 + `cache_open` 89 = 247 ms before the +folder's 124 files (≈25 ms warm) can be published. The §P0 REF answered in +208 ms because it never walked the workspace at all — it answered off a +**124-file folder scan**, and the workspace walk came later. **The one-scan +design's floor is the walk**, and that is the finding this lane hands the next +one: `discovery` is now 158 ms of pure walk with no read in it, and it is 58 % +of the first useful answer. + +**Stages and memory (`scanwait`, one traced session each):** + +| | P4b2 | P4b3 | change | +|---|---:|---:|---| +| `discovery`, cold / warm | 271.26 / 227.02 | **157.91 / 158.32** | −42 % / −30 % | +| `read`, cold / warm | — | 115.56 / 85.54 | new stage | +| `includes` (the graph built at the end) | 42.11 / 42.12 | **8.55 / 8.60** | **−80 %** | +| `work_kib` — the source text the scan holds for its life | **34 973** | **3 / 0** | **−100 %** | +| `read_kib` | 34 973 | 34 970 / 34 973 | the same bytes, read once | + +`includes` falls by 34 ms because the line scan moved to the step that read the +file — over bytes already in cache — and the graph at the end only resolves +what the steps found. It is the one stage that got cheaper rather than moved. + +**Settled — unchanged, within the window's noise:** + +| cell | P4b2 | P4b3 | paired | +|---|---|---|---| +| workspace, cold (`scan`) | 2 932.23 / 2 720.02 / 2 721.87 (2 791.37) | 2 660.72 / 2 639.93 / 2 637.20 (**2 645.95**) | −5.2 % | +| workspace, warm (`scan`) | 1 019.48 / 1 030.21 / 983.13 (1 010.94) | 968.84 / 967.68 / 1 004.41 (**980.31**) | −3.0 % | +| workspace, cold (`scanprofile`) | 2 602.34 | 2 624.90 | **+0.9 %** | +| workspace, warm (`scanprofile`) | 965.89 | 983.95 | **+1.9 %** | +| default scope, cold / warm | 99.88 / 45.59 | 91.67 / 47.36 | −8 % / +4 % | +| `{"index":{}}`, cold / warm | 102.57 / 48.56 | 104.18 / 47.54 | +2 % / −2 % | +| `scopeDepth 0`, cold / warm | 10.44 / 11.81 | 9.24 / 10.54 | −12 % / −11 % | + +**The two workspace phases disagree in sign, so the honest reading is +"unchanged".** The ledger says why it is close to a wash: `discovery` −69 ms +and `includes` −34 ms against `read` +86 ms — the same 34 MiB read a file at a +time, interleaved with parsing and decoding, costs about 13 ms more than the +same bytes read in one tight loop. Both runs are quoted; neither is dropped. + +**Open buffers (`scanprofile`, warm workspace, settled):** + +| buffers | P4b2 | P4b3 | paired | +|---:|---|---|---| +| 1 | 1 010.91 | 994.74 | −1.6 % | +| 10 | 973.62 | 1 003.75 | +3.1 % | +| 100 | 1 185.95 | 1 181.55 | −0.4 % | + +§P4a's `order` cost — 60.6 ms at 100 buffers, a linear `contains` per file — is +gone with the ranking: `order` is **1.95 ms at 100 buffers**, because the open +set is a `HashSet` now. + +**Memory (`rss`, 3 fresh sessions):** cold idle max **543 024 → 505 200 KiB +(−7.0 %)**, warm idle max **466 256 → 432 736 KiB (−7.2 %)**. Peak equals idle +to the KiB in all twelve sessions of both binaries, as in every round since +§P4a. The mechanism is the one the `work_kib` row measures: the 34 MiB of +source text no longer lives for the scan's life. + +**Requests during a scan (`scanserve`, a definition every 200 ms):** + +| | P4b2 | P4b3 | +|---|---|---| +| cold, answers / slowest | 34 / **427.5 ms** | 36 / **314.8 ms** | +| warm, answers / slowest | 12 / **360.0 ms** | 12 / **313.3 ms** | +| `mismatched_answers` | **0 / 0** | **0 / 0** | + +**`didOpen` (§46's path, 3 fresh sessions):** pinmux_reg_top median 123.52 → +127.72; spi_device 14.37 → 15.05; aes_core 9.80 → 12.05; aes 4.47 → 5.47. Every +row is inside its own spread (P4b2's pinmux tries were 101.87–123.76 in this +same window) and **the path cannot be reached by this change**: `didopen` +settles the scan before it opens the buffer, so `head_owed` is false and the +drain rule is not in play. §46's fix is intact. + +**The scope ladder answers identically.** `scopes`, eight requests × three +scopes × both binaries: **all 24 result counts equal**. + +**The store is byte-identical.** Every warm workspace store written by either +binary is sha256 `e49bc5c176ea…`, 46 486 433 bytes, `store_kib` 45 404 — the +same file §P4b and §P4b2 recorded. **That is the strongest equality proof this +lane has**: the records a lazy scan writes are byte for byte the records an +eager one wrote, over 3 976 real files. + +#### §P4b3 — targets, honestly + +| target | result | +|---|---| +| first useful answer, **result count 1 in 6 of 6** | **met** — 1 in **12 of 12**, across two phases | +| first useful answer ≤ REF's 84 cold / 208 warm | **missed**: 249 cold, 274 warm. It is walk + folder as asked; the walk alone is 158 ms and the REF never walked the workspace. Filed below | +| first useful answer better than §P4b2's | **met**: −13.4 % cold, −16.6 % warm, and useful where §P4b2's was empty | +| `work_kib` → ~0 | **met**: 34 973 → 0–16 KiB | +| each file's bytes read exactly once | **met**, counted | +| peak RSS during the scan not higher | **met**: peak equals idle in all 12 sessions; idle **−7.0 % cold, −7.2 % warm** | +| settled not worse | **met within noise**: −5.2 % / −3.0 % in one phase, +0.9 % / +1.9 % in the other | +| scope cells identical | **met**: 24 of 24 result counts, identical file and cache-hit counts | +| `mismatched_answers` 0 | **met**: 0 of 4 rows, both binaries | +| §46's `didOpen` intact | **met**: every row inside its own spread, and the path is not reachable from this change | +| the store unchanged | **met**: same sha256 and same size from both binaries | + +#### §P4b3 — filed for the next lane + +**The first useful answer is now walk-bound.** `discovery` is 158 ms with no +read in it: the scope walk plus one `fs::metadata` per file for the size cap. +That is 58 % of the 274 ms warm answer and 63 % of the 249 ms cold one, and +nothing in this lane reaches it. Two things worth measuring before anything is +built: whether the walk can hand the cap the size it already stat'd +(`lucisv_core::walk::collect_files` is not this lane's file — a handshake +request, not an edit), and whether the first *folder* of the walk can be +handed to `scan_step` before the walk has finished the workspace. The second +would make the answer ≈ the folder alone, which is the REF's 84 ms. + +**And `cache_open` is still 89 ms at the first step**, which is the refused +(b2) sitting in front of every warm first answer. It is now the second largest +thing between a warm session and its first useful answer. + +### 2026-09-08 — dev (Opus), §P4b2: the startup scan is staged + +**The lead ruled the plan's own sentence, not the fourth state this lane +proposed.** §P4b left one regression open (see "The one regression, named" +above): with the empty startup scan reduced to 0.15 ms, the opening `didOpen` +no longer had its accidental 181 ms head start over the client's +`workspace/configuration` answer, so the warm first useful answer became +bimodal — 117 ms when the `didOpen` won the race, the whole configured rescan +when it did not. The narrow fix this lane had described was a *fourth* +`must_wait` state letting one kind of rescan answer mid-way. The lead took the +work order's own clause instead: + +> *"If the default scan is routinely discarded, stage the initial scan until +> configuration arrives, with a bounded fallback for clients that never answer; +> keep rootless and scope precedence behavior intact."* + +That is a better answer than the fourth state, because it removes the race +rather than arbitrating it: there is no second scan for a request to be queued +behind. + +**What the code does now** (`crates/lucisv_server/src/server/startup.rs`, new): + +1. `Server::started` calls `stage_for_configuration` **before** the scan. For a + client that advertised `workspace/configuration` it sets a new + `Server::staging` flag, sends the pull, and waits. +2. `await_configuration` reads messages until the answer arrives, the bound + runs out, or the client goes away. **The bound is observed on the receive + itself** — `self.queue.recv_timeout(left)` with `left` recomputed from + `CONFIGURATION_WAIT.checked_sub(asked.elapsed())` — so the loop blocks in + the transport, wakes on the next message, and returns at the deadline. No + poll, no busy-wait, no timer the loop has to be woken to read, and no + `unwrap` anywhere in it (`checked_sub` returning `None` *is* the timeout). +3. `staging` and `rescan_wanted` are cleared, and the session runs **one** + `scan_until_settled(false)` — the startup scan proper, at the answered + scope, allowed to answer requests mid-way, with no prior index and + therefore no `gone`. The empty default-scope scan does not happen. + +**The bound is `CONFIGURATION_WAIT = 2 s`, and it is not a budget.** §P4a's +`configuration answered in` line measured 27.3–28.1 ms warm and 82.8–85.2 ms +cold, and both of those numbers were dominated by the empty scan the server ran +*before* reading the answer; with that gone the number is the client's own +reply, single-digit milliseconds. Two seconds is two orders of magnitude of +slack. A client that answers *after* it sees exactly what a client that pushes +a `didChangeConfiguration` sees: `configured` → `apply_settings` → +`set_client_settings` reports the scope moved → `reindex()` → an ordinary +rescan, with `must_wait` holding what is queued behind it. Nothing is stale in +between; it is simply the default scope until the answer lands, which is what +every session was before today. + +**What happens to messages that arrive while waiting.** They go through the +ordinary `process_batch`, so the order contract is the loop's own code, not a +second implementation of it: + +- a **`didOpen`** is applied: the buffer is installed, the folder scope widens, + and `reindex_widened` — seeing `Server::scan_owed()` (now `scanning || + staging`) — records that one more scan is wanted rather than running a widen. + The one scan that follows resolves the scope with the buffer in place and + `open_first` puts its file at the head of the work list, so the widen is + *folded into* the startup scan rather than run beside it. +- a **pushed setting**, a **save**, a **watched-file burst** and a **folder + change** take the same path, for the same reason: whatever they asked for, + the session's first scan reads the whole scope from disk at the final + settings. That is why `rescan_wanted` may be cleared before it runs. +- a **request** is held by a new fourth `must_wait` clause (`staging`) — there + is no index at all to answer it from — and is handed to the startup scan by + `Server::waiting_for_this_scan`, which takes `held` **only** when + `answering_a_rescan` and `rescan_wanted` are both clear. It is then answered + mid-scan off the published prefix, exactly as a request arriving during that + scan always was. A rescan takes nothing from `held`: decision 2 of + `docs/features/scan-interleave/README.md` is unchanged, and the deferred + `gone` set the QA log worried about is empty by construction here, because + this is the session's first scan. +- a **`shutdown`** is held like any other request (the pre-existing rule: a + request sent before a shutdown is still owed an answer) and stops the scan at + its first drain. + +**Two wire-order consequences, both deliberate.** The settings pull is now the +**first** thing a session sends — ahead of the progress `create`, the watcher +registration and the lens refresh. `settings.rs`'s +`the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire` pinned +the opposite and is amended in place (renamed to +`the_startup_pull_is_the_first_thing_on_the_wire`, with the reason in the +test); it is the only pre-existing test in the workspace this round changed. +And a client with a `filelist` in its answer now registers its watchers from +`apply_settings` before `started`'s own `register_watchers` supersedes it — the +same three requests, in a different order. + +**Where the code lives.** `server/mod.rs` was 576 lines with `Server::new` and +`Server::started` in it; both moved to the new `server/startup.rs` (120 +production lines) together with the wait, leaving `mod.rs` at 153 production +lines. `started`'s six trailing parameters became a `Startup` struct — seven +positional arguments were already at clippy's `too_many_arguments` limit, and +the two only a test sets (`queued`, `wait`) read as nothing at a call site. +`index.rs` gained `waiting_for_this_scan` (194 production lines), `mod.rs` +gained `staging` and `scan_owed`, `client.rs`'s `say_held` line gained +`staging=` so the fourth clause is as greppable as the other three. + +**One defect this lane found by measuring, before it shipped.** The first +paired run of the `scan` phase showed one warm session in three taking +**2 125 ms** to its first useful answer — near enough the two-second bound to +be the bound. It was: `process_batch` moves *everything behind* a request that +must wait into `held`, which is what keeps a burst's arrival order intact +across the wait, and the editor's opening burst is `didOpen`, then a +`textDocument/definition`, then — from the client's own reader thread — the +answer to the settings pull. The definition is held; the answer goes into +`held` behind it; the wait sees the pull still outstanding and blocks until the +bound. `Server::take_the_answer_out_of_held` takes **only** a +`Pending::Configuration` answer back out, leaving everything else in `held` in +its place and its order. Reordering just that one message is sound because the +order rule is about the *client's* message stream: the reply to a request the +**server** sent carries no ordering promise against a request the editor +happened to send at the same moment. The preliminary rows that caught it are +kept unquoted at +`~/.cache/lucisv-perf/take5-p4b2/results-preliminary-stranded-answer.jsonl`. + +**Six wire tests**, `crates/lucisv_server/src/server/tests/startup.rs`: + +| test | what it pins | +|---|---| +| `a_client_that_answers_pays_one_scan_at_the_scope_it_asked_for` | exactly **one** scan, `timing: scan 1` only, `read=9` at the answered scope, and the pull first on the wire | +| `a_client_that_never_answers_is_bounded_and_then_scanned_at_the_defaults` | `CONFIGURATION_WAIT` is 2 s; a 120 ms bound is really waited out; one scan at the defaults (`read=0`); the late answer's rescan is `scan 2` and a request behind it is answered **after** it | +| `a_did_open_that_beats_the_answer_is_folded_into_the_one_scan_and_indexed_first` | one scan, `buffers=1`, the buffer's own file is the **first** line of the per-file log, and its diagnostics are published | +| `a_request_that_beats_the_answer_is_answered_inside_the_startup_scan` | a `textDocument/definition` sent before the answer is answered **before the bar comes down**, with a real location, and the index still finishes | +| `a_client_that_cannot_be_asked_scans_at_once_exactly_as_it_always_did` | nothing asked, nothing waited for, `read=0`, `opens=0`, `compactions=0` — §P4b's own path untouched | +| `an_answer_behind_a_held_request_is_not_stranded_for_the_whole_bound` | the defect above: `didOpen` + request + answer in one burst, a 30 s bound, and the session still returns in milliseconds with one scan at the answered scope — the held request neither lost nor answered off an empty index | + +Everything else is the existing suite, green unmodified: `scan.rs`'s +interleave, boundary, held-order, coalescing and shutdown tests; `index.rs`'s +ladder tests; `progress.rs`; `folders.rs`; `watchers.rs`; +`scan_trace.rs`'s §P4b store tests (which use a client without the capability +and therefore exercise the unstaged path). **4 290 tests pass, 0 fail** — the +4 284 the round started with, plus six. + +#### §P4b2 — measured + +Release `lucisv-server` sha256 +`3ff0db0920d1b86bee5237ea7b7827c7383a402ef73ec138c111cf7a867d7ca8` for the +seven-phase matrix, paired against **the previous §P4b release**, sha256 +`623c0ea62df4fe154947725605071fee93e54f02dec3f45e6c566620ed5c0ee3`, kept from +before the rebuild. The **shipped** binary is +`7522696e894a94d8d431f148d4e08e6a9ab7727eb0aaac36f8daa57a684b9076`, which +differs from the measured one by a pure move only — `started`'s `Server { … }` +literal into `Server::empty`, to bring the function under the file-size rule's +80-line investigate mark — and the `scan` phase was **re-run on it**, paired +again, to prove the numbers travel (see "Confirmed on the shipped binary" +below). Every phase ran **alternating P4b then P4b2**. opentitan +`0098135264` with its three pre-existing modified files, `git status +--porcelain` checked after every phase of both binaries and never otherwise +touched. Rows in `~/.cache/lucisv-perf/take5-p4b2/results.jsonl` under labels +`P4b` and `P4b2`. + +**The load is not uniform across this run and the numbers must be read with +it.** `scan` — the headline phase — ran at one-minute load **4.7–5.1**, the +quiet window. Everything after it ran while macOS started an `XProtect` +remediation sweep and `mediaanalysisd`: `scanwait` **20.1–22.9**, +`scanprofile` **23.8–25.9**, `scanserve` **18.0–21.2**, `scopes` 14.7–16.0, +`didopen` 12.8–13.9, `rss` 12.0–12.5. The alternation is what makes those +still comparable — both binaries met the same weather within a phase — but the +absolute values in them are not comparable with §P4b's own window and are not +quoted as if they were. + +**Settled (`scan`, 3 fresh sessions each, the quiet window):** + +| cell | P4b | P4b2 | paired | +|---|---|---|---| +| workspace, cold | 3 125.88 / 2 885.50 / 2 878.26 (mean 2 963.21) | 2 859.99 / 2 869.28 / 2 802.25 (**2 843.84**) | **−4.0 %** | +| workspace, warm | 1 169.60 / 1 159.20 / 1 215.23 (1 181.34) | 1 097.51 / 1 094.56 / 1 101.88 (**1 097.98**) | **−7.1 %** | +| default scope, cold | 100.59 | 95.85 | −4.7 % | +| default scope, warm | 46.22 | 45.10 | −2.4 % | +| `{"index":{}}`, cold | 103.79 | 105.29 | +1.4 % | +| `{"index":{}}`, warm | 41.64 | 44.03 | +5.8 % | +| `scopeDepth 0`, cold | 114.95 | **12.45** | **−89.2 %** | +| `scopeDepth 0`, warm | 51.32 | **14.07** | **−72.6 %** | + +`scopeDepth 0` is the cell the plan predicted in as many words — *"explicit +depth 0 pays for [a 124-file default scan] and then ends with one file"*. It no +longer does: the configured scope is resolved before anything is read, so the +session reads one file and stops. The two default-scope cells move by a few +milliseconds either way, which is the config round trip now serialized ahead of +the scan instead of overlapping an empty one; at 45–105 ms total it is noise a +user cannot feel. + +**Confirmed on the shipped binary** (`scan`, re-run paired at load 8.7–9.1, +storage wiped first): + +| cell | P4b | P4b2 (shipped) | paired | +|---|---|---|---| +| workspace, warm | 1 198.25 / 1 175.12 / 1 198.07 (1 190.48) | 1 040.79 / 1 036.88 / 1 034.28 (**1 037.31**) | **−12.9 %** | +| workspace, cold | 2 938.30 / 2 843.24 / 2 846.96 (2 876.17) | 2 820.57 / 2 795.44 / 2 794.79 (**2 803.60**) | **−2.5 %** | +| `scopeDepth 0`, cold / warm | 108.26 / 52.16 | **10.37 / 12.75** | **−90.4 % / −75.6 %** | +| first useful, cold | 2 881.13 / 2 883.64 / 83.76, count 1 | 304.64 / 301.75 / 304.31, **count 0** | unimodal, empty | +| first useful, warm | 1 203.52 / 1 162.89 / 119.90, count 1 | 348.74 / 350.54 / 352.14, **count 0** | unimodal, empty | + +**Warm settled 1 037.31 ms is inside the ≤ ~1.06 s target**, and the first +run's 1 097.98 was not — the two runs bracket it, at loads 4.7–5.1 and 8.7–9.1 +respectively. Both are quoted; neither is dropped. + +**One scan, not three (`scanprofile`, warm workspace, `--verbose`):** + +| | P4b | P4b2 | +|---|---|---| +| scans traced | 3 (whole 0 files, widen 124, whole 3 976) | **1** (whole 3 976) | +| per-scan total | 0.13 + 119.47 + 1 082.46 = 1 202.06 | **1 093.67** | +| `cache_open` | 0 + 91.38 + 92.32 = **183.70** | **91.91**, once | +| `opens` / `compactions` | 2 / 0 | 1 / 0 | +| settled | 1 233.39 | **1 110.48, −10.0 %** | + +**This is the (b2)-equivalent saving, arriving without store reuse.** §P4b +missed warm < 1 s because the store was opened twice, 181.7 ms, and the lead +had refused reusing it across rescans for two good reasons. Staging removes the +second open by removing the second *scan*: the rule `index-persistence` +requires — every whole rescan resolves the directory afresh and reads the store +— is untouched; there is simply one whole rescan in a session now instead of +two. + +**Open buffers (`scanprofile`, warm workspace, settled):** + +| buffers | P4b | P4b2 | paired | +|---:|---|---|---| +| 1 | 4 scans, 1 555.37 ms | **1 scan, 1 113.56** | **−28.4 %** | +| 10 | 4 scans, 1 555.93 ms | **1 scan, 1 139.27** | **−26.8 %** | +| 100 | 3 scans, 1 721.70 ms | **1 scan, 1 360.10** | **−21.0 %** | + +**Requests during a scan (`scanserve`, a definition every 200 ms, 3 fresh +sessions per cache state):** + +| | P4b | P4b2 | +|---|---|---| +| cold, every answer sorted | 0.22 / 0.23 / 0.28 / 84.88 / 89.22 / **2 621.84 / 2 658.83 / 2 933.71** | 0.20 … 475.41 across **37** answers, nothing above 476 | +| warm, every answer sorted | 0.24 / 0.28 / 0.38 / 121.91 / 124.44 / **933.86 / 942.65 / 1 233.87** | 0.21 … 381.54 across **12** answers, nothing above 382 | +| `mismatched_answers` | 0 / 0 | **0 / 0** | + +**The "queued behind the configured rescan" mode is gone for the startup +case** — that is the whole of what the lead asked for. There is no configured +rescan to be queued behind, so the three-mode distribution §P4a named collapses +to two: mid-scan, and settled. A **genuine** settings-change rescan mid-session +still queues requests exactly as it always did — it is `must_wait`'s first +clause, unchanged, and `startup.rs`'s own wire test drives a late answer and +shows the request behind it answered after the rescan, not during it. + +**`didOpen` (§46's path, `didopen`, 3 fresh sessions, load 12.8–13.9):** +pinmux_reg_top median **118.75 → 110.39**, mean 123.19 → 115.38 (**−6.3 %**); +spi_device 11.05 → 8.40; aes_core 8.16 → 6.33; aes 2.12 → 2.31 (a 2 ms row). +§46's fix is intact. + +**Memory (`rss`, 3 fresh sessions):** cold idle 542 512 → 542 581 KiB +(**+0.0 %**, maximum 542 864 → 545 216, +0.4 %); warm idle 495 291 → +**466 480 KiB (−5.8 %)**, maximum 496 256 → 467 200 (−5.9 %). Peak equals idle +to the KiB in all twelve sessions of both binaries. Warm falls again for the +same reason it fell at §P4b: one fewer whole scan is one fewer set of transient +buffers the allocator holds on to. + +**The store is still left alone.** A cold session then two warm ones, both +binaries: sha256 `e49bc5c176ea…`, 46 486 433 bytes and the **same mtime** after +every one. `store_kib` 45 404 for both. + +**The scope ladder answers identically.** `scopes`, eight requests × three +scopes × both binaries: **all 24 result counts equal** (`workspace/symbol +'aes'` 256 at default and workspace and 0 at `scopeDepth 0`, `references` 11 / +14 / 0, and so on). The per-scan *file* counts moved by design — one scan +instead of three — but what each scope answers did not. + +#### §P4b2 — the regression, named + +**The first useful answer is now unimodal, and it is empty.** + +| | P4b | P4b2 | +|---|---|---| +| cold (`scan`, quiet window) | 2 902.62 / 2 884.55 / **86.97**, result count 1 | 293.04 / 300.26 / 294.82, **result count 0** | +| warm (`scan`, quiet window) | 1 205.18 / 1 204.50 / **125.84**, result count 1 | 396.86 / 404.88 / 411.39, **result count 0** | +| cold (`scanwait`, busy window) | 103.32 / 106.84 / 90.60, count 1 | 357.19 / 316.85 / 309.52, count 0 | +| warm (`scanwait`, busy window) | 1 279.66 / 123.76 / 124.15, count 1 | 389.92 / 400.14 / 386.77, count 0 | + +The bimodality §P4b filed is gone — every session now answers in the same few +hundred milliseconds, and the 1.2 s / 2.9 s mode is unreachable. **But the +answer is `[]` where it used to be a location, and that is a real loss the lead +must rule on.** The mechanism is arithmetic, and the trace says it outright. +Warm, `scanwait`'s traced session: `discovery` **292.74**, `first_publish` +**389.27**, definition answered at **389.92**. + +- `begin_scan` resolves the scope and reads all 3 976 files' text *before* the + first `scan_step`, so the earliest moment any request can be answered is + ≈ 293 ms in. That is the floor of the one-scan design, and it is why 85–120 ms + is not reachable at workspace scope. +- The request is then answered at the **first** drain, off a prefix holding the + open buffer and nothing else — so `aes` is not in it, and the definition is + empty. Coherent (it names nothing rather than something wrong; + `mismatched_answers` is 0), but not useful. +- Under §P4b the same request was answered by the **widen** — a 124-file scan + of the buffer's own neighbourhood which, because `reindex_widened` does not + interleave, ran to *completion* before the request was served. Its 124 ms + answer was complete for that scope. That is what staging traded away: the + fast mode's quality, in exchange for the slow mode's disappearance. + +**Filed, with the fix this lane cannot make.** The narrowest repair is to make +the prefix a mid-scan answer reads be the *user's own neighbourhood* rather +than the alphabet: `Workspace::open_first` puts the open buffers' files first, +and putting the files under those buffers' **raised scope directories** next +would put `aes` in the published prefix within a few tens of milliseconds of the +first file. That is an ordering change only — `IndexBuilder::finish` sorts by +path, so no insertion order can reach the index, which is the argument +`open_first`'s own doc comment already makes — but it is a change to +`Workspace::open_first` in `state.rs`, a file this lane holds **calls only**. +So it is a **handshake request**, not an edit: see Handshakes (11) below. + +**Closed 2026-09-08 by §P4b3** (work log below), and the narrowest repair was +not quite enough on its own: the ordering only helps when the buffer is open +when the scan *begins*, and it usually is not — the client answers the settings +pull from its own reader thread and beats the editor's `didOpen`. The shipped +fix is the ordering **plus** a drain rule: a held request waits for the user's +folder, and a burst's `didOpen` holds what is behind it until the folder it +named is in. Result count 1 in twelve sessions of twelve; the residual is that +the answer is now bounded below by the 158 ms workspace *walk*, filed there. + + ### 2026-09-07 — dev (Opus) Instrumentation written; no behavioural change. Notes on the shape: @@ -145,6 +903,76 @@ Instrumentation written; no behavioural change. Notes on the shape: folded into a neighbouring stage; the tolerance test asserts the stages never *exceed* the scan and account for most of it. +### 2026-09-08 — dev (Opus), §P4b: the ruled fixes + +The lead's ruling, item by item, plus what the measurement then forced. + +- **(a) and (b1) as ruled**, (b2) not taken. The mechanisms are in "§P4b — + what changed" above; the contract amendments are in + `docs/features/index-persistence/README.md` (Assumptions, and the + `lucisv_server::state` handshake), not only here, because the compaction rule + and the re-open rule are that feature's promises. +- **One addition beyond the ruling, and it is reported as one.** (a) alone is + worth **nothing** in a session with a buffer open: the buffer is indexed from + its own analysis on every scan and its record is written through with it, so + `records` is never 0 and the store is never canonical. Measured that way + first, deliberately, and kept as evidence + (`results-compaction-defeated.jsonl`: warm scan 3 `records` 1, + `compactions` 1, `compact` **88.19 ms**). `IndexCache::record` now returns + early when the store already holds that exact record. It is in service of + (a)'s own sentence — "the session appended nothing" — and in a file this lane + owns, but it was not named in the ruling, so: **the lead can back it out by + deleting one `if` and one counter**, at the cost of (a) entirely. +- **The interleaving question is answered and filed, not fixed** — the section + above has the mechanism, the reasons, the number and the narrow fix. It is + the `must_wait` order contract, not routing, and §P4b makes it *more* + reachable: removing the empty scan's 181 ms removed the head start the + `didOpen` used to win the race with. That is the one regression in this lane + and it is named in "The one regression" above rather than buried. +- **What the numbers did to the plan's arithmetic.** §P4a's recommendation + added (a) 182.4 and (b1) 92.5 to get 274.9 ms. The 92.5 is not additive: a + warm session opens the store twice either way, and (b1) *moves* scan 1's open + onto the widen rather than removing it. The honest ledger is + **−180.2 ms of compaction, +10.1 ms of skip check, −0 ms of open** — and the + measured paired settle is −189.2 ms, which is that plus noise. Nobody should + expect the missing 91 ms without (b2). +- **The pure move** took `opened_trace`/`measure_work`/`landed` out of + `state.rs`. `landed` needed `Candidates`, `IncludeGraph`, `IndexCache` and + `WorkspaceIndex` as parameters, so `scan_trace.rs` now imports the four + things it measures; that is the shape of "a diagnostic knows what it is + describing", and it keeps the walks and the `TableSizes` assembly out of the + state module entirely. `state.rs` 1 098 → 1 073 production lines. +- **Gates**: `cargo fmt --all -- --check` clean; guarded + `cargo clippy --all-targets` clean, no new `#[allow]` anywhere in the diff; + guarded `cargo test --workspace` **4 284 passed, 0 failed** against **4 272** + at the lane's start — **+12**, exactly the twelve new tests, nothing lost or + weakened. Zero guard kills; largest resident set seen 591 MiB of the 8 GiB + cap. +- **The corpus** stayed at exactly its three pre-existing modified files after + every phase of both binaries, checked between each. + +**Twelve new tests.** In `index_cache.rs`: a canonical store nothing appended +to is not rewritten (bytes *and* mtime); a record the store already holds is +not appended again, and one byte of difference still is; and one each for a +duplicated path, a line this build cannot read, records out of path order, a +session that recorded a file, an entry whose file is gone, and another +version's header — the six clauses of the skip, one test each. In `state.rs`: a +warm rescan leaves the store exactly as it found it; a scan with no files +neither reads nor writes it **and the widen behind it still hits every +record**; a cold session that indexes nothing creates no store at all. In +`server/tests/scan_trace.rs`: both halves over the real dispatch, with a buffer +open, read off the trace's own new `opens=` / `compactions=` / `repeats=` +counters. + +**The tests were attacked before they were trusted.** Widening +`already_compact` to "there is a directory" fails all six guard tests plus two +pre-existing ones (`compaction_keeps_one_line_per_path_and_drops_the_files_that_are_gone`, +`nothing_is_created_until_something_is_recorded`). Dropping the deferred open +instead of moving it — QA's §P4a warning, exactly — makes +`a_scan_with_no_files_neither_reads_the_store_nor_rewrites_it` report +`parsed: ["b.sv"]` where it expects `cached: ["b.sv"]`. Neither failure mode +can land silently. + ## The measured breakdown Release `08093a3a2b9c0b8796e5f9214ac7bda59e068e49e32a9c2393f29d116fca10bd`, @@ -364,8 +1192,605 @@ attention on its own: **a navigation request that arrives during the configured rescan waits 2.56 s cold / 0.90 s warm**, because the only scan that interleaves is the empty one. +**Corrected by §P4b's own measurement (2026-09-08).** The arithmetic above adds +(a) 182.4 and (b) 92.5 to get 274.9 ms; **the 92.5 is not additive**. A warm +session opens the store twice either way, and taking the open out of the empty +scan 1 only *moves* it onto the widen that follows. The honest ledger is +−180.2 ms of compaction plus 10.1 ms of skip check, and the measured paired +settle is −189.2 ms. The "warm ≈1.05 s" target above is therefore wrong; the +real landing is **1 137.7 ms**, and warm < 1 s needs the refused (b2). Nothing +in this section is edited — it is what the lane recommended on the day, and +what it got wrong is worth more than a silent fix. + +## §P4b — what changed + +Three code changes and one pure move. Nothing touches the record format, the +content key, the store header, the claim/append protocol, the per-record +checksum, the byte-wise load or the torn-record rule; `FACTS_FORMAT` and +`CACHE_FORMAT` are untouched, and `index-persistence`'s own tests are +untouched and green. + +**(a) A compaction that would reproduce the file is skipped.** `render` writes +this build's header and then one line per path in path order, so a store this +build compacted and nothing has appended to since already *is* the file the +next compaction would write. `IndexCache::open` now counts what it read — +lines read, kept, dropped, duplicated, and whether the paths ascended — and +`compact` skips the rewrite when all of: the load was canonical, the session +appended nothing, no entry's file is gone, and there is a directory to write +in. The existence sweep is one `stat` per entry, a subset of what `render` +already does per entry: **10.13 ms measured, against the 90.20 ms rewrite it +stands in for**. + +**(a′) A record the store already holds is not appended again — an addition, +not in the ruling.** Reported as a deviation because the ruling did not name +it, and kept because **without it (a) never fires in a real session**: an open +buffer is indexed from its own analysis on every scan and its record is +written through with it, so `records` is 1 rather than 0 on every scan a buffer +is open for, and the store is never canonical. Measured with (a) alone on +opentitan: warm scan 3 `records` 1, `compactions` 1, `compact` **88.19 ms** — +the whole of (a) defeated by one duplicate line +(`~/.cache/lucisv-perf/take5-p4b/results-compaction-defeated.jsonl`, kept as +evidence and not quoted elsewhere). `IndexCache::record` now returns early when +the entry is already there under the same path, the same content hash and the +same encoded facts, byte for byte; anything differing by a byte is appended +exactly as before. The counter is `repeats=` on the count line. + +**(b1) A whole rescan opens the store at its first file.** `begin_scan` +resolves the directory and records it as `StoreOpen::Deferred`; `scan_step` — +and the save path's write-through — opens it. The **re-open rule is +unchanged**: every whole rescan still resolves the directory afresh and reads +the store, for both of `index-persistence`'s reasons. Only the moment moved, +and a rescan whose work list is empty now asks the store nothing and therefore +reads nothing and compacts nothing. **The open is a move, not a drop** — the +widen a `didOpen` triggers never opened the store itself (it reads the handle +`begin_scan` left), so dropping the open would silently have cost that widen +every cache hit. Pinned from the failing side. + +**(b2) Not taken.** The store is still re-opened for every non-empty whole +rescan. Refused by the lead; nothing in this lane touches it. The consequence +is visible in the stage table below: the warm session still pays `cache_open` +twice, 90.62 + 91.12 = **181.7 ms**, and that is now the largest single thing +the store costs a warm start. + +**The pure move.** `opened_trace`, `measure_work` and `landed` — the three +helpers §P4a left in `state.rs` — are now `ScanTrace::opened`, +`ScanTrace::measure_work` and `ScanTrace::landed`; `state.rs` keeps the calls. +`state.rs` production lines (non-blank, non-comment, before `mod tests`) +**1 098 → 1 073**: the move takes out 45 and §P4b's own code (`StoreOpen`, +`open_store`, the compaction gate, the save-path call) puts back 20. +`scan_trace.rs` 215 → 282, `index_cache.rs` 283 → 338 — both far under 600. + +**Two new count-line fields**, so the change is observable to the harness and +to a wire test rather than only inferable from a stage time: `opens=` (stores +read off disk) and `compactions=` (stores actually rewritten), plus `repeats=` +for (a′). `tools/perf/phases_p4.py` reads them without a change, since it +splits `key=value`. + +## §P4b — measured + +Release `lucisv-server` sha256 +`623c0ea62df4fe154947725605071fee93e54f02dec3f45e6c566620ed5c0ee3`, against a +**control built in the same window from a `git clone --local` at HEAD +`2434729`** (sha256 `5957b0826249a0354b270d2ec865e7cfc702b187bd359049cc5c73b2170354d4`), +every phase run **alternating HEAD then P4b** so the two share the machine's +weather. opentitan `0098135264` with its three pre-existing modified files, +checked after every phase and never otherwise changed. One-minute load +**3.6–6.7** — busier than §P0's REF window (2.9–4.6), which is why the paired +control matters more than the cross-day comparison. Three fresh sessions per +cell, every session under `tools/guard.sh -m 8 -t 1800`, no `cargo` command +during any timed phase, zero guard kills. Rows: +`~/.cache/lucisv-perf/take5-p4b/results.jsonl`, experiment `P4b-2026-09-08`. + +### The startup, stage by stage (warm, `--verbose`, one traced session each) + +| scan | HEAD | P4b | +|---|---:|---:| +| **1, whole, 0 files** | **180.72** — `cache_open` 90.49 + `compact` 90.04 | **0.15** — `opens` 0, `compactions` 0 | +| 2, widen, 124 files | 26.21 — `cache_open` 0.00 (it reads scan 1's handle) | 116.51 — `cache_open` **90.62**, the open scan 1 no longer pays | +| **3, whole, 3 976 files** | 1 087.84 — `cache_open` 90.57, **`compact` 90.20**, `records` 1 | 1 016.23 — `cache_open` 91.12, **`compact` 10.13**, `records` **0**, `repeats` **1**, `compactions` **0** | +| **sum** | **1 294.77** | **1 132.89** (**−12.5 %**) | + +So the 183.5 ms scan 1 no longer spends is really **91 ms saved and 91 ms +moved**: the widen inherits the open scan 1 used to pay for. What is genuinely +removed is the two compactions — 180.2 ms of rewriting a byte-identical file — +minus the 10.1 ms the skip's own existence sweep costs. + +### Settled and first answer (quiet binary, 3 fresh sessions, paired) + +| row | HEAD (same window) | P4b | paired change | +|---|---|---|---| +| Warm workspace settle | 1 325.28 / 1 324.62 / 1 330.64 — mean **1 326.85** | 1 132.60 / 1 143.54 / 1 136.83 — mean **1 137.66** | **−14.3 %**, −189.2 ms | +| Cold workspace settle | 2 857.77 / 2 834.77 / 2 848.29 — mean **2 846.94** | 2 816.59 / 2 813.47 / 2 818.56 — mean **2 816.21** | −1.1 % — unchanged, as predicted (cold is 59 % parse) | +| First useful answer, **cold** | 84.06 / 84.01 / 84.60 | 85.62 / 86.83 / 84.45 | +1.6 % — unchanged | +| First useful answer, **warm** | 208.94 / 206.16 / 208.85 | **116.77** / 1 133.53 / 1 137.51 | **bimodal — see below** | +| `didOpen` pinmux → definition | 107.12 / 128.13 / 118.38 (median 118.38) | 109.68 / 122.74 / 114.53 (median **114.53**) | −3.3 % — §46's fix intact | +| `didOpen` spi_device → definition | 6.32 / 14.67 / 12.40 (median 12.40) | 10.73 / 8.16 / 6.88 (median 8.16) | −34 %, but a sub-15 ms row: not read | +| Idle RSS, **warm** (max of 3) | 563.81 / 569.95 / **569.75** MiB | 482.55 / 481.67 / **482.75** MiB | **−15.3 % on the maximum** | +| Idle RSS, cold (max of 3) | 493.56 / **532.58** / 529.44 MiB | 527.08 / 529.25 / **530.45** MiB | −0.4 % on the maximum | +| Peak RSS across the scan | equal to idle to the KiB, all 6 sessions | equal to idle to the KiB, all 6 sessions | no transient, either binary | +| Store on disk | 45 404 KiB | 45 404 KiB | identical | +| `mismatched_answers` (`scanserve`) | **0** in both cache states | **0** in both cache states | the coherence contract holds | + +**The RSS result is the surprise, and it is the one §P4a said was out of +reach.** Warm idle falls **87 MiB, −15.3 %**, which meets the plan's −15 % +investigation goal — and warm idle is now *below* cold idle. The mechanism is +the one §P4a's memory section named without pricing: a warm HEAD session reads +the 44.3 MiB store into a `Vec` twice **and renders a 44.3 MiB `String` +twice** to write it back; P4b renders none. The encoded-facts retention §P4 +hypothesised (44.20 MiB) is untouched and still resident — this is the +allocator retention of the render buffers beside it. + +**The store really is left alone, byte for byte.** Two warm workspace sessions +over one store, sha256 and mtime after each: + +| | after the cold fill | after warm 1 | after warm 2 | +|---|---|---|---| +| HEAD | `e49bc5c1…` mtime `…960117212853` | `e49bc5c1…` mtime `…982249698088` | `e49bc5c1…` mtime `…985232233976` | +| P4b | `e49bc5c1…` mtime `…960117212853` | **same hash, same mtime** | **same hash, same mtime** | + +Same 46 486 433 bytes throughout — HEAD rewrites them identically twice, P4b +does not open the file for writing at all. (Script: +`~/.cache/lucisv-perf/take5-p4b/storecheck.py`, both binaries, same corpus; the paired run's own log is `run-paired.log` beside it.) + +### The scope ladder is unchanged + +Every cell of the `scan` matrix, both binaries, with the file counts the +sessions reported: + +| scope | HEAD cold / warm | P4b cold / warm | files reported (both) | +|---|---|---|---| +| `default` | 105.98 / 95.11 / 90.95 — 49.84 / 41.04 / 47.45 | 89.99 / 93.19 / 93.15 — 40.05 / 35.71 / 43.24 | `0 files indexed \| 124 files indexed` | +| `{"index":{}}` | 106.94 / 105.44 / 107.99 — 45.03 / 49.12 / 41.11 | 101.00 / 100.06 / 102.41 — 39.79 / 40.51 / 36.74 | `0 \| 124` | +| `scopeDepth 0` | 113.92 / 105.55 / 123.36 — 61.37 / 55.81 / 67.19 | 118.26 / 100.26 / 109.01 — 53.03 / 47.20 / 46.35 | `124 \| 1` | +| `workspace` | above | above | `124 \| 3 976`, 123/3 975 from cache, 3 skipped | + +Identical file counts and identical cache-hit counts in every cell of both +binaries. The rungs answer exactly what they answered. + +### Requests during a scan (`scanserve`, paired) + +| | during scans 1–2 | queued behind the configured rescan | after settle | +|---|---|---|---| +| HEAD cold | 83.55 / 84.79 / 84.80 | 2 520.86 / 2 552.87 / 2 602.80 | 0.27 / 0.36 / 0.37 | +| P4b cold | 84.63 / 85.61 / 85.87 | 2 582.51 / 2 588.46 / 2 600.39 | 0.24 / 0.34 / 0.39 | +| HEAD warm | 206.77 / 208.49 / 209.67 | 891.52 / 893.91 / 895.40 | 0.20 / 0.24 / 0.33 | +| P4b warm | **117.98 / 118.88** | 824.36 / 826.06 / 1 150.43 | 0.27 / 0.30 / 0.37 | + +A warm mid-scan answer falls **207 → 118 ms** for the same reason the first +useful answer does: the empty scan's 181 ms of store I/O is no longer in front +of it. `mismatched_answers` is 0 in all four rows. + +### The one regression, named + +**Warm, the first useful answer is now bimodal: 117–118 ms or the whole +configured rescan (~1 140 ms).** Two of six sessions took the fast mode, four +the slow one. Cold is unaffected (six of six fast, both binaries). + +It is not a new mechanism — it is the interleaving contract filed below, made +*reachable* by §P4b. The startup sequence is: scan 1, then +`request_configuration()`, then the loop. The client answers the configuration +pull from its own reader while its main thread is still sending the `didOpen`, +so the two race. On HEAD, warm scan 1 spent **181 ms** before the pull went +out, which gave the `didOpen` a head start it won in every session ever +measured — §P0's three, §P4a's three, QA's three and this control's six: +**fifteen sessions, fifteen fast**. With scan 1 at 0.15 ms the race is genuine, and when the configuration answer wins, `apply_settings` +starts the configured rescan and `Server::must_wait` holds the definition +behind it — the documented order contract, working as written. + +**Closed 2026-09-08 by §P4b2** (work log below) — and not by the fourth state +this section proposed. The lead took the plan's own sentence instead and staged +the startup scan, which removes the race rather than arbitrating it: there is +no configured rescan for a request to be queued behind. The residual, measured +there, is that the surviving answer is *empty* rather than slow. + +So §P4b did not create the wait; it removed the accidental 181 ms that was +hiding it. The number the user sees is **better in the fast mode (−44 %) and +worse in the slow one**, and which one they get is a race. **The narrow fix is +the fourth state described below, and it is the lead's to rule on.** Nothing in +this lane papers over it: the empty scan's I/O was pure waste either way, and +buying responsiveness back by reinstating it would be indefensible. + +### Targets, honestly + +| target | result | +|---|---| +| warm settled −~270 ms, ≤ ~1.06 s | **missed**: −189 ms, **1 137.7 ms**. The remaining warm settle is discovery 246.1, absorb 208.4, decode 195.1, **`cache_open` 91.1 + 90.6 = 181.7** (the refused (b2)), candidates 105.8, lookup 48.8, includes 44.5 | +| the plan's warm < 1 s | **missed** — it needed all three of §P4a's candidates, and (b2) was refused. Reachable only by not re-opening the store twice | +| first useful answer warm ≈ cold (~85 ms) | **missed as stated**: 117–118 ms in the fast mode (−44 %), the configured rescan in the slow one. The residual is the `must_wait` contract, filed | +| cold unchanged within tolerance | **met**: −1.1 % paired | +| RSS not higher | **beaten**: warm idle **−15.3 %**, cold −0.4 %, peak still equal to idle | +| store bytes identical after a warm session | **met**: same sha256 *and* same mtime over two warm sessions | +| the scope ladder unchanged | **met**: identical file and cache-hit counts in all eight cells | +| `mismatched_answers` 0 | **met**: 0 of 4 rows, both binaries | + +## §P4b — the interleaving question, answered and filed + +The lead's ruling asked why navigation queues behind the configured rescan: +fix it if it is routing, file it if it is not. **It is not routing.** Read +through, the configured rescan takes exactly the same path the startup scan +takes: + +1. `Server::started` runs `scan_until_settled(false)` — scan 1, the empty one + — and only then sends `workspace/configuration`. +2. The client's answer arrives as a `Message::Response` in an ordinary batch: + `process_batch` → `Server::response` → `configured` → `apply_settings` → + `Workspace::set_client_settings` reports that `index.scope` moved → + `Server::reindex()` → `scan_until_settled(**true**)`. +3. That is the *same* `scan_once` the startup scan ran. It steps file by file, + 3 976 is far above `INTERLEAVE_ABOVE` (64), so `answer_what_is_waiting` + runs between every pair of files, drains the queue and calls + `publish_scan` — the three tables really are published mid-rescan, exactly + as they are mid-startup-scan. + +What holds the request is one line further in: `process_batch` sets a +`Message::Request` aside in `held` whenever `Server::must_wait()` is true, and +`must_wait` is `answering_a_rescan || rescan_wanted || !held.is_empty()`. +`scan_until_settled(true)` sets `answering_a_rescan`, so every request that +arrives during the configured rescan waits it out. That is +`docs/features/scan-interleave/README.md`'s order contract, decision 2 of +three, in as many words: *"Only the startup scan answers mid-way. A scan a +message asked for has that message queued ahead of everything else, so nothing +arriving during it may be answered from a half-updated index."* + +**So this is a contract, not a routing bug, and this lane does not change it.** +Two things make relaxing it more than a one-line edit, and both belong to the +lead rather than to §P4b: + +- **The order promise itself.** The configuration response *is* the message + queued ahead: a definition sent after the client answered + `lucisv.index.scope: "workspace"` is, under the one-message-at-a-time model + the loop promises, a definition sent after the workspace scope took effect. + Answering it off the 124-file prefix returns less than the settled index + would — which is precisely the trade the startup scan is allowed to make and + a rescan is not. +- **`gone` is deferred to the very end.** `finish_scan` computes what left the + scope and absorbs it in one call after the last file, and the + scan-interleave QA log names `must_wait` as the reason that is safe: *"every + scan capable of having `gone` files non-empty is a rescan … which `must_wait` + already blocks from answering anything mid-way."* A configured rescan whose + settings **narrow** the scope (an arriving `lucisv.exclude`, a filelist) has + a non-empty `gone`, and a mid-rescan answer could name a file that has + already left. Exempting rescans from `must_wait` would put that hole back. + +**Filed for the lead, with the number.** The cost is unchanged by §P4b and is +re-measured below: a `textDocument/definition` arriving during the configured +rescan is answered in **2 582.5 / 2 588.5 / 2 600.4 ms cold** and **824.4 / +826.1 / 1 150.4 ms warm** (the control, in the same window: 2 520.9 / 2 552.9 / +2 602.8 and 891.5 / 893.9 / 895.4), against **under 0.4 ms** once the scan has +settled and **84.6–85.9 ms cold / 118.0–118.9 ms warm** during scans 1–2. +§P4b made this *more* likely to be what a user meets, not less: it is now also +what the **first** navigation of a warm session gets in four sessions of six — +see "The one regression" above. The narrowest change that +would buy it is a *fourth* state rather than a relaxation: distinguish a rescan +a **client message** asked for from the one the server's **own settings pull** +asked for, and let only the latter answer mid-way — it is the one rescan of a +session with no user message queued ahead of it, and at startup its `gone` set +is empty because the configured scope is a superset of the widen's. That is a +new promise about a documented contract, so it is the lead's to rule on, not +this lane's to take. + + ## QA log +### 2026-09-08 — QA agent, §P4b + §P4b2 + §P4b3 (one pass over the whole uncommitted tree) + +**Verdict: PASS.** All three passes verified together, since they sit on one +uncommitted tree and each later pass amends the one before it. Gates are +clean, the pure move is proven structurally, every safety-net widening was +re-attacked and broke exactly as the dev's own log said it would, three live +process-level attacks (kill -9 mid-scan, a torn last line, two concurrent +sessions) were run against a real `lucisv-server` and none corrupted the +store or crashed the process, and a reduced but real re-measurement on the +opentitan corpus reproduces the headline numbers within tolerance — most +strikingly the exact **1** result-count in every session tried, where the +whole lane exists to fix a **0**. + +**Gates, guarded, main tree.** `cargo fmt --all -- --check`: clean. +`tools/guard.sh -m 8 -t 1800 -- cargo clippy --all-targets --all-features -- +-D warnings`: clean (stricter than the plain gate — deny-warnings, no +suppressions), 0 exit. `grep` over every new/changed file and the diff for +`#[allow`: none added anywhere in this lane. `tools/guard.sh -m 8 -t 1800 -- +cargo test --workspace --release`: **4 305 passed, 0 failed**, matching the +dev's count exactly; guard never fired (exit 0, largest RSS well under the +8 GiB cap). Per-binary against a fresh `git clone --local` at HEAD +`2434729` with no lane diff: **4 272 passed, 0 failed**. Diffing the two +runs' full `test ... ok` line sets (not just the totals): **exactly +one test name lost**, `server::tests::settings::the_startup_pull_is_sent_ +after_the_watcher_registration_on_the_wire`, which is the rename to +`the_startup_pull_is_the_first_thing_on_the_wire` the work log describes — +read side by side, same wire assertions, new name and new comment for the +new order. **One further test kept its name but changed shape**, +`a_file_opened_mid_scan_is_indexed_next_and_the_index_cannot_tell` (read +against the deleted `state.rs` at HEAD): the old body drove `Scan::index_next` +directly and asserted it refuses a second jump and a file not waiting; the +new body drives `Workspace::open_next` (no target-path argument — it just +re-ranks `scan.remaining()` around whichever buffers are open now) and keeps +the same end-to-end premise (the reopened file is indexed next, the finished +index is byte-identical to a one-shot scan). The two dropped assertions do +not have a direct analogue under the new API and I judge that acceptable +rather than a coverage hole: `open_next` takes no path to misuse, so +"jumps twice" and "a file not waiting cannot jump" are failure modes the new +shape cannot express, not failure modes nobody checks — `scan_order.rs`'s own +`a_path_handed_over_twice_is_one_file` and +`an_open_buffer_outside_the_scope_still_lends_its_folder` are the ordering +layer's equivalent guards, and they are new tests, not renamed ones. Nothing +else lost anywhere in the workspace; 34 new test names beyond the rename. + +**Production line counts** (non-blank, non-comment, before `mod tests`, +same method as the dev's): `state/mod.rs` **1 064** (matches exactly), +`state/scan.rs` **99**, `scan_order.rs` **35**, `index_cache.rs` **339**, +`scan_trace.rs` **303**, `server/startup.rs` **150** total lines (no inline +test module — its tests live in `server/tests/startup.rs`), `server/mod.rs` +**158** total (the dev's own count method — bounded by an inline +`#[cfg(test)] mod tests { … }` — doesn't apply here either, since `mod +tests;` is a declaration pointing at the `tests/` directory; whichever way +it's counted it is nowhere near 600), `candidates.rs` **406**, `includes.rs` +**274** — all exact or within a few lines of the dev's figures and all +comfortably under 600. `state/mod.rs` at 1 064 is **not** a new violation: +it inherits `state.rs`'s pre-existing, already-tracked oversize (TODO §55; +CLAUDE.md's own re-measurement table already lists it), and this lane's own +Handshake 13 is explicit that `state.rs` is calls-only apart from the pure +split — every genuinely new file this lane added is under 400 lines. + +**The pure move, proven, not just claimed.** `git diff -M` cannot detect the +rename (the new `state/` directory is untracked, so git has nothing to +diff it against), so I compared structurally instead: `git show +HEAD:crates/lucisv_server/src/state.rs` against the new `state/scan.rs`. +All six named types (`Sources`, `Analyzed`, `HeldAnalyses`, `Scan`, +`ScanKind`, `IndexEvent`) are gone from `state/mod.rs` and present in +`state/scan.rs` with `pub(super)` visibility on every field — exactly +"visible where they were before: inside `crate::state` and nowhere else." +Comparing `Scan`'s field list old vs. new field-by-field: every field from +`state.rs` is still there in the same relative order, and the only +additions (`head`, `buffered` replacing the old `Vec<(PathBuf, String)>`, +`includes`, `unread`) are exactly the §P4b3 lazy-read/ordering fields the +work log describes adding — nothing unaccounted for. `crate::state::{Scan, +IndexEvent}` really is `pub use scan::{IndexEvent, Scan}` in `mod.rs`, so no +external path moved. This is a pure move with a clearly-scoped, tested, +separately-described behavioural delta layered on top — which is what the +lane claims, not silently more. + +**Persistence safety — re-attacked, not just read (invariant-grade, per +CLAUDE.md).** All attacks below ran against a real `lucisv-server` binary, +either as live subprocess attacks (small synthetic fixtures — 60 and 2 000 +tiny modules, under this QA's scratchpad, opentitan never touched for +anything destructive) or as source sabotage-and-reattack inside a +`git clone --local` at HEAD `2434729` with this lane's working-tree diff +applied (confirmed identical `git status --porcelain` to the main tree; all +sabotages reverted and the four touched files diffed byte-identical to their +pre-sabotage copies before moving on). + +- **(a) Kill mid-scan, cold store.** A 2 000-file fixture, SIGKILL'd after + 13 notifications (store at that instant: 10 lines, 9 real records — a + genuine partial write, confirmed by line count far short of 2 000). The + next session did not crash, reported `2000 files indexed, 9 from cache` + (exactly the 9 survivors reused, the rest reparsed), and `workspace/symbol` + resolved files from both ends of the range (`mod0000`, `mod1000`, + `mod1999`) correctly. +- **(b) Truncated last line.** Filled a clean 61-line store (60 records), + then truncated the last 5 bytes off the final line with no trailing + newline. The next session reported `60 files indexed, 59 from cache` + (exactly the one torn record dropped and reparsed, the other 59 kept), + every symbol resolved including the reparsed one, and the store was + re-rendered to a clean 61-line/19 951-byte file afterward — the torn line + was dropped individually and compaction happened (not skipped), because + the load was not canonical. +- **(c), (d), (f) Duplicate path, another version's header, a gone file.** + Not re-run live as separate fixtures (the existing suite already builds + exactly these cases as fixtures); instead re-attacked at the guard level, + which is the stronger form CLAUDE.md asks for: widening `already_compact` + to just `self.dir.is_some()` (dropping the canonical/no-appends/ + nothing-gone conditions) made **10 tests fail**, independently reproduced + in this session — the six named guard tests + (`a_canonical_store_nothing_appended_to_is_not_rewritten`, + `a_record_the_store_already_holds_is_not_appended_again`, and one each for + a duplicated path, an unreadable line, out-of-order records, another + version's header) plus + `compaction_keeps_one_line_per_path_and_drops_the_files_that_are_gone` and + `nothing_is_created_until_something_is_recorded` — matching the dev's own + claimed failure list exactly, re-derived independently rather than taken + on trust. +- **(e) Canonical store no-rewrite / an edited buffer triggers rewrite.** + Live, both halves. A warm session that opens a buffer and saves it with + **unchanged** text: store mtime, size and sha256 identical to the prior + session's. A warm session that edits the buffer and saves the **edited** + text (`textDocument/didSave` with a changed `text` payload, which is the + documented write-through trigger): store mtime, size (19 951 → 20 283 + bytes) and sha256 all changed. Byte-identical stays byte-identical; + anything that differs by a byte is written through and recompacted, as + the Assumptions bullet promises. +- **(g) Two concurrent sessions over the same store.** A cold session and a + warm session started ~50 ms apart against the same `storagePath`, run + concurrently to completion. Neither crashed, both answered correctly + (`workspace/symbol mod1500` resolved in both), the store stayed readable + throughout and ended at exactly 2 001 lines (header + one line per file, + no duplication despite the concurrent writes), and a third, later, + ordinary session read it without incident. +- **(h) The deferred open never drops a hit.** Sabotaged `begin_scan` to set + `self.store = StoreOpen::Done` instead of `StoreOpen::Deferred(dir)` for + an empty whole scan — simulating "dropped" instead of "moved," the exact + regression QA's own §P4a review had warned about and the dev's log says it + guarded against. `state::tests::a_scan_with_no_files_neither_reads_the_ + store_nor_rewrites_it` fails immediately (`read store: NotFound` — the + widen behind the empty scan can no longer find the store the deferral was + supposed to hand it). Reverted; the real code passes the same test. I did + not additionally build the "folder scope, then a `didOpen` into a new + folder" LSP-level scenario live — the unit test above already drives + exactly that scenario (empty default-scope whole scan, then a `didOpen` + triggering a widen that must still hit the store) at the same + granularity the dev's own test does, and I re-attacked its guard directly + rather than re-deriving it through a slower LSP harness. + +None of the six clauses can be widened, dropped, or reordered without a test +failing from the failing side, confirmed by me rather than only asserted by +the dev. + +**Staged startup.** (a) `a_client_that_answers_pays_one_scan_at_the_scope_ +it_asked_for` passed in the full run; independently reproduced live on the +real opentitan corpus below (`scanprofile` shows exactly one `scan 1 +(whole)` line per session, no separate widen/configured-rescan lines, for +the workspace scope). (b) Live-measured the bound with a client that +advertises `workspace/configuration` and never answers it: the first +`$/progress` notification landed at **2.0196 s** after `initialize` — the +2 s `CONFIGURATION_WAIT` bound, not before it and not meaningfully after it. +(c) `an_answer_behind_a_held_request_is_not_stranded_for_the_whole_bound` +passed; **re-attacked** by making `take_the_answer_out_of_held` a no-op — +the test then waits out its full 30 s bound (`30.023924208s` measured, +against the test's own `< 5s` assertion), independently reproducing the +"one warm session in three" defect the dev found by measuring, from the +failing side. (d) and (e) — the no-capability and rootless paths — run +unmodified inside the green full-suite pass; not separately re-attacked +given the volume already covered elsewhere in this pass. (f) The eight +scope-ladder cells are exercised unmodified by the existing `index-scope` +suite (green in the full run) and independently re-measured for the +`scan` phase below with file/hit counts matching the dev's own numbers. + +**Coherence and the drain rule.** `Server::head_owed` — the fifth +`must_wait` clause and the whole of the drain rule — **re-attacked** by +forcing it to `false` unconditionally in `must_wait`. Against +`a_request_that_beats_the_answer_is_answered_from_the_users_own_folder` +(the *staged* burst, config-answer-then-`didOpen`-then-request) the +sabotage made no difference — that request is held by the `staging` clause +before the sabotaged clause is ever consulted, so this test alone would not +have caught the sabotage. Against +`a_did_open_answered_mid_scan_pulls_its_folder_in_front_of_the_request_ +behind_it` (the *unstaged*, scan-already-running case, which is the one the +real opentitan measurement found) the sabotage broke it exactly as +predicted: `assertion left == right failed: one location, not none: []`, +`left: Some(0)`. So `head_owed` is load-bearing specifically for the +mid-scan-`didOpen` path, and the staged-burst test's pass-under-sabotage is +a property of which `must_wait` clause fires first for that message order, +not a hole — worth naming so nobody reads "one test didn't notice" as "the +guard is dead." **Lazy-read + `unread` live-attacked**: on a 2 000-file cold +scan, deleted a not-yet-reached file 6 notifications in; the session +finished cleanly reporting `1999 files indexed` (not 2 000, not an error, +not a crash) and the deleted module never appeared in `workspace/symbol` — +exactly the documented `unread` path, taken out of the index by the whole +scan that could not read it, with no cap-skip event. `mismatched_answers` +is exercised by the green `scan-interleave`/`scan_trace` suites and by my +own `scanserve`-shaped read of the P4b3 evidence (36/12 answers cold/warm, +0 mismatches — see Traceability); I did not additionally construct a +`didClose`-mid-scan or double-`didOpen` burst live, given the breadth +already covered. + +**Re-measurement, on the shipped binary, no rebuild needed.** The main +tree's already-built `target/release/lucisv-server` is sha256 +`7ab4955ee0ac174840fbe4c02528e178f0c7824a3836fa87aa90e35bf47cdd3b` — checked, +matches the dev's quoted hash exactly, confirmed untouched by anything in +this QA pass. (A `git clone --local` at HEAD with the diff applied also +reproduced that exact hash on its first build, before any sabotage; later +rebuilds of that clone, after several edit/revert cycles, landed on a +different-but-source-identical hash — `diff -rq` against the main tree's +`crates/` shows zero differences, so this is this toolchain's release build +not being bit-reproducible across separate invocations, not a functional +difference, and it never touched the untouched main-tree binary used for +every number below.) Reduced scope, disclosed rather than padded: I re-ran +`scan` (all 8 cells, 3 tries), one `scanprofile` pass and one `rss` pass on +real opentitan (`0098135264`, three pre-existing modified files, checked +before/after — unchanged both times) rather than the dev's full ~20-cell +matrix; load average during my run was **3.79–6.07**, busier than the +dev's own quiet windows in places, which explains some of the drift below. + +| cell | dev (P4b3) | this QA | delta | +|---|---:|---:|---:| +| first useful, cold, ms / count | 249.13/249.70/248.16, **1** | 266.29/265.31/268.04, **1** | +7.0% mean | +| first useful, warm, ms / count | 272.78/290.81/268.52, **1** | 287.05/303.26/281.86, **1** | +4.8% mean | +| settled workspace, cold | 2 645.95 | 2 859.09 (3 067.6/2 754.7/2 754.9) | +8.1% | +| settled workspace, warm | 980.31 | 1 002.05 (989.3/1 003.0/1 013.9) | +2.2% | +| `scanprofile` workspace, cold, scan 1 | 2 624.90 | 2 631.41 | +0.25% | +| `scanprofile` workspace, warm, scan 1 | 983.95 | 1 002.36 | +1.9% | +| rss idle, cold max | 505 200 KiB | 504 000 / 499 152 KiB | −0.24% | +| rss idle, warm max | 432 736 KiB | 427 792 / 428 512 KiB | −1.1% | + +**The result-count finding — the one that matters most — reproduces +exactly**: `1` in every session I ran, cold and warm, where the whole lane +exists to fix a `0`. The traced `scanprofile` rows also reproduce the +mechanism, not just the headline: warm `opens=1, compactions=0, repeats=1` +(one open, no rewrite, the open buffer's own duplicate record correctly +skipped), cold `opens=1, compactions=1` (a genuine first fill really does +compact), `work_kib=3` against a clean-fixture size (matching the dev's +"34 973 → 0–16" claim), `store_before_kib=store_after_kib=45396` warm (no +growth), and the memory-table fields — `reference_sites=457666`, +`fact_words=345127`, `cache_encoded_kib=45260`, `unit_names=3067`, +`index_files=3976` — **exact matches** to both the dev's and §P4a QA's own +independently-taken figures, which is strong evidence the index itself is +unperturbed by any of this lane's changes. The one cell outside a strict +±10% band on a sub-stage rather than a headline number is `read` (85.54 dev +vs. 112.78 mine, +32%) in the one traced `scanprofile` session; given every +coarser number above is within tolerance and the qualitative claims +(opens/compactions/repeats, `work_kib`, the memory table) match exactly, I +read this as machine-load noise on a fine-grained timer, not a mechanism +difference — noted rather than smoothed over. + +**Traceability.** Beyond the numbers reproduced live above: cross-checked +`~/.cache/lucisv-perf/take5-p4b3/results.jsonl` directly (113 rows, labels +`P4b2`/`P4b3`, phases `scan`/`scanwait`/`scanprofile`/`scanserve`/`rss`/ +`scopes`/`didopen` — all present as claimed). Exact field-level matches: +first-useful cold/warm ms arrays and `result_count: 1` both scopes; `rss` +cold/warm `rss_kib` arrays (505200/432736 maxima, matching the README's +quoted figures exactly); `scanserve` cold 36 answers / warm 12 answers +(matching "37"/"12"-shaped counts quoted in the README's §P4b2 table to the +one row that differs by version); `didopen` pinmux values. `~/.cache/ +lucisv-perf/take5-p4b/` and `take5-p4b2/` evidence directories both exist +with the files the READMEs cite (`results-compaction-defeated.jsonl`, +`storecheck.py`, `results-preliminary-stranded-answer.jsonl`, etc.). +15+ numbers checked, all traced, none found only in a `-preliminary`-only +file. + +**Opentitan status.** `git -C opentitan status --porcelain` checked before +and after every phase of this QA pass (gates, sabotage/reattack cycles, +live attacks, re-measurement): always exactly `hw/ip/aes/dv/tb/tb.sv`, +`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv` — +never more, never fewer. Every attack that needed a corpus used a synthetic +fixture under this QA's own scratchpad, never opentitan. + +**Guard outcome.** Every `cargo` invocation and every timed phase went +through `tools/guard.sh -m 8 -t 1800` (or a tighter `-t` for a single short +test); zero kills. The one 30 s-bound sabotage test was run with `-t 60` to +give it room to finish rather than being cut off mid-assertion. + +**Fixes made:** none in code — every attack found the lane's own guard +working, not a hole. One stale intra-doc link noted, not fixed (outside +this QA's editable scope): `state/mod.rs`'s doc comment on `finish_widen` +still says `` [`IncludeGraph::absorb`] `` — that method is genuinely deleted +(confirmed: no `fn absorb` left in `includes.rs`, and no live caller +anywhere in `crates/`), so the doc link now points at nothing. It is a +comment, not a behaviour change, and neither `cargo fmt` nor the `-D +warnings` clippy gate catches it, but it is a loose end from the deletion in +Handshake 14 worth the lead's or the next lane's five-minute fix. + +**Handshakes, for the lead.** Nothing here is a silent edit; `docs/topo.md` +confirmed untouched by this lane (`git status --porcelain` on it is empty). +1. `lucisv_core::walk::collect_files` — a request from §P4b3 (not this + lane's file) to hand the size cap the metadata the walk already + collected, filed as the next lane's first thing to measure. +2. `docs/features/folders-and-config/README.md`'s Assumptions sentence — + *"a pulled `lucisv.exclude`/`lucisv.filelist` costs one extra rescan when + it lands"* — is now stale for the common case (§P4b2 answers the pull + before the first scan whenever the client responds inside the 2 s bound; + the sentence is still true only for a late answer). Confirmed by reading + the file: unedited, correctly left for the lead per Handshake 10. +3. New-module topo edges from this pass, all additive per the READMEs: + `server/startup.rs`, `scan_order.rs`, `state/scan.rs`, + `crate::scan_trace::{source_reads, count_read}`; the deleted + `IncludeGraph::absorb`; the amended contracts in `index-persistence` + (compaction skip, deferred open), `index-scope` (read moment, walk + order), `scan-interleave` (the drain rule, `head_owed`), and + `indexing-ux` (skip accounting, per-file log order) — each has its own + dated entry, read and cross-checked against the code in this pass. + +**My own read of the first-answer trade, since the brief asks for it.** +250/275 ms correct in every session I tried (12 of 12, and this QA's own 6 +more agree) against the REF's 84/208 ms that was empty or wrong four +sessions in six under staging alone — I'd take the slower-but-right answer +every time for a `definition` request; an editor user who gets `[]` when +the answer exists has no way to tell that from "there really is no +definition," while a 250 ms wait is invisible against typing latency. The +walk-bound floor this lane files for the next one (`discovery` at 158 ms, +58% of the warm answer) looks like the right next target precisely because +it is now the *only* remaining lever — everything else on the original +§P4a list is spent. + ### 2026-09-08 — QA agent (gates, no-behaviour-change, cost, arithmetic, coherence) **Verdict: PASS.** No behaviour changed, the instrument's own cost is inside @@ -684,3 +2109,42 @@ the TODO.md tick. into `scan_trace.rs` as a pure move. - Deviations accepted: `state.rs`'s growth (to be moved out in P4b); the preliminary run kept unquoted. + +**2026-09-08 (lead, P4b — three passes, one QA).** Accepted. + +- The ruling's two items shipped as ruled — the compaction skip with its + four conditions and the deferred store open as a move, not a drop — and + each surfaced the next thing honestly: (a) was worth nothing until the + write-through learned to skip a byte-identical record; removing the + empty scan's 181 ms turned a race the `didOpen` had always won into one + it lost four times in six. Neither was papered over. +- The second and third passes are the plan's own sentences ("stage the + initial scan until configuration arrives, with a bounded fallback"; + "shorten temporary source lifetimes"): one startup scan at the answered + scope, a 2 s bound observed on the receive itself, the corpus read a + file at a time in its own step, the open buffers' folders at the head + of the work list, and a held opening request answered inside the + startup scan once that head is published. The rescan order contract + (scan-interleave decision 2) is untouched; QA's persistence attacks — + a SIGKILL mid-scan, a truncated line, two concurrent sessions, a + deleted file at step time — all recover as documented. +- Numbers against the P0 reference: warm settle 1.33 → ~1.04–1.10 s + (the plan's < 1 s missed, honestly; the remaining store open is the + refused reuse), cold unchanged, warm idle RSS −15 to −20 %, the store + byte-identical across warm sessions, the 100-buffer ordering 61 → 2 ms, + the "queued behind the configured rescan" mode gone for startup, and + the first useful answer correct in 12 of 12 sessions at ~250 cold / + ~275 warm. **That last number is the trade I accept:** the reference + answered in 84 / 208 ms only when the empty scan happened to win a race, + and otherwise after 1.1–2.5 s; a deterministic 250–275 ms correct answer + is the better contract. The gap to 84 is the workspace walk in front + of the folder, filed for loop 3 with the `walk::collect_files` metadata + request. +- Deviations accepted: the `state/` split (a pure move that also does a + third of TODO §55), `IncludeGraph::absorb` deleted with its last caller, + the two tests amended in place for the APIs they drove. + +Docs applied at merge: the stale `absorb` link in `state/mod.rs`; the +folders-and-config Assumptions sentence; topo (the scan-interleave row +amended, the module ownership entries); the walk-metadata item and the +first-answer gap added to the loop-3 list. diff --git a/docs/features/scan-interleave/README.md b/docs/features/scan-interleave/README.md index 99d141c..00a6570 100644 --- a/docs/features/scan-interleave/README.md +++ b/docs/features/scan-interleave/README.md @@ -99,7 +99,9 @@ impl Scan { pub fn skipped(&self) -> usize; pub fn cached(&self) -> usize; pub fn total(&self) -> usize; - pub fn index_next(&mut self, path: &Path) -> bool; + pub fn neighbourhood_indexed(&self) -> bool; // perf5-p4 §P4b3 + pub fn remaining(&self) -> Vec; // perf5-p4 §P4b3 + pub fn reorder(&mut self, ordered: WorkList); // perf5-p4 §P4b3 } impl Workspace { @@ -299,6 +301,106 @@ attached. ## Work log +### 2026-09-08 — §P4b3: when a held request is drained, and what it reads + +**The order contract is unchanged. The *moment* a held request is drained +moved, and it moved later.** Written here because this README is where "only +the startup scan answers mid-way" lives, and it is now "…once the user's own +folder is in it" (`docs/features/perf5-p4/README.md` §P4b3). + +Three things changed, none of them a promise: + +1. **A held request is answered once the scan has stepped the user's own + neighbourhood** — the open buffers and the directories those buffers raise + to — rather than at the first interleave point. + `Server::waiting_for_this_scan` consults a new `Server::head_owed`, set from + `Scan::neighbourhood_indexed`, and the `publish_scan` that already ran in + the same call is what makes that neighbourhood answerable before the answer + goes out. A scan with **no** neighbourhood (nothing open, an `untitled:` + buffer, or a folder that covers the workspace) reports it with a head of 0 + and drains at the first interleave point exactly as it always did. + *Why:* §P4b2 measured what draining at the first file answers, and it is + `[]` — coherent, and useless. Holding a request **longer** is always safe + under this contract; answering it earlier is what was not. +2. **`head_owed` is a fifth `must_wait` clause**, and it is what a request + behind a `didOpen` in a mid-scan burst now waits on. That reinstates, inside + one scan, exactly what the widen the `didOpen` used to trigger did: the + requests behind it were owed its effect. `Workspace::open_next` then + re-orders what is left of the work list around the buffers open now, + replacing `Scan::index_next` — a `didOpen` brings its folder, not only its + own file. +3. **`Scan::index_next` is gone**, replaced by `Scan::remaining` / + `Scan::reorder` and `Workspace::open_next`. Reordering the tail still cannot + reach the index (`IndexBuilder::finish` sorts by path), which is the + argument the removed method's own doc comment made. + +**The coherence contract is untouched**: an answer mid-scan still sees a +published prefix of all three tables, published together, and `scanserve`'s +`mismatched_answers` is 0 in every row of both binaries. What a scan holds +while it runs did change — a file's text is read at the step that indexes it +and dropped there, so `Scan` carries paths rather than 34 MiB of source — and +`docs/features/index-scope/README.md` carries that amendment. + +### 2026-09-08 — dev (Opus), §P4b2: the startup scan is now staged + +**The order contract is unchanged; what changed is which scan the opening +burst waits for.** Before today a session ran its startup scan at the +**default** settings and only then asked the client for its own +(`workspace/configuration`); a client whose `lucisv.index.scope` differs paid a +second, *configured* scan when the answer landed, and — because that second +scan is one a message asked for — `Server::must_wait`'s `answering_a_rescan` +clause held every request that arrived during it. §P4b measured what that cost +on opentitan: **0.9 s warm, 2.6 s cold**, and named it a contract rather than a +routing bug (`docs/features/perf5-p4/README.md`, "the interleaving question, +answered and filed"). + +The lead's ruling took the plan's own sentence — *"if the default scan is +routinely discarded, stage the initial scan until configuration arrives"* — +rather than the fourth `must_wait` state this lane had proposed. So: + +- `Server::started` now sends the settings pull **first** and waits up to + `CONFIGURATION_WAIT` (2 s) for the answer, then runs **one** + `scan_until_settled(false)` — the startup scan proper — at the scope that + answer decided. The empty default-scope scan no longer happens at all, and + neither does the configured rescan behind it. +- A client that never answers, or answers after the bound, gets the scan at the + defaults exactly as before, and its late answer is an ordinary settings + change with an ordinary rescan behind it — held requests and all. A client + that never advertised `workspace/configuration` is untouched: nothing is + asked, nothing is waited for. + +**Decision 2 of this feature's three is not relaxed.** *"Only the startup scan +answers mid-way. A scan a message asked for has that message queued ahead of +everything else"* still holds, word for word. What the staging adds is that +requests arriving in the **configuration window** — before the startup scan has +begun — are held by a fourth `must_wait` clause (`staging`) and then handed to +that scan by `Server::waiting_for_this_scan`, which takes `held` only when +`answering_a_rescan` and `rescan_wanted` are both clear. The justification is +this feature's own, unchanged: + +- the scan they wait for is the **startup** scan: nothing is queued ahead of + it, because the message that would have been — the client's settings answer — + has already been applied before it starts; +- it is the session's **first** scan, so `finish_scan`'s deferred `gone` set is + empty by construction. The QA log's argument below (*"every scan capable of + having `gone` files non-empty is a rescan … which `must_wait` already + blocks"*) is therefore satisfied, not weakened: a rescan still takes nothing + from `held`. + +**The widen is folded in rather than run.** A `didOpen` arriving in the window +installs its buffer and records that a scan is wanted; the one scan that +follows resolves the scope with that buffer in place and `open_first` puts its +file at the head of the work list. `rescan_wanted` is cleared before that scan +because the scan *is* what every trigger in the window was asking for — it is +the session's first, it resolves the scope afresh and reads every file in it. + +Pinned by `server/tests/startup.rs` (five wire tests: one scan at the answered +scope; the bounded fallback and the late answer's ordinary rescan; a `didOpen` +folded in and indexed first; a definition answered *inside* the startup scan, +before the bar comes down; a client that cannot be asked, unchanged) and by +this feature's own suite, green unmodified — `INTERLEAVE_ABOVE`'s hard +boundary, the held-order tests, the coalescing and shutdown tests included. + ### 2026-08-28 — dev **Measured the merge first, and the number chose the design.** The brief left diff --git a/docs/perf/take5-tracking.md b/docs/perf/take5-tracking.md index 98fb75a..98905dc 100644 --- a/docs/perf/take5-tracking.md +++ b/docs/perf/take5-tracking.md @@ -1,6 +1,6 @@ # Performance implementation tracker — take 5 -**Status: baseline measured; P0 done; P1a–P1c and P2a–P2c implemented, measured and merged; topology handshake 33 closed and P2d measured; P2d's `warnings` dedupe implemented and measured (2026-09-07; the second §P2 lane's QA pending). P2d ships no narrowing — the census below says why — and the ≥×2 rename target is **met at 2.01×** by the dedupe instead. P3 implemented and measured 2026-09-07 (dev; QA pending): the CLI package census shares the interface census's parse and gates on the AST, and **96 % of the `unused-import` all-style increment is gone** (141.7 → 5.0 ms paired against a same-toolchain trunk build; all-style `hw/ip` 0.633 → 0.482 s, −23.9 %), with every stdout byte-identical.** The implementation agent owns the blank candidate columns and experiment entries below. Read [the causes and detailed plan](../performance_take5.md) before selecting work. Baseline provenance and raw rows are in [take5-baseline](take5-baseline/README.md). +**Status (2026-09-08): complete.** Every stage the plan sequenced has run and been measured — P0; P1a, P1b, P1c; P2a, P2b, P2c; handshake 33 and P2d (measured, no narrowing shipped: the proof was negative) with the `warnings` dedupe; P3; P4a and P4b (three passes). P5 stays deferred (no stage's measurement reopened it). Baseline cells are the owner's and untouched; REF cells are the P0 re-take; every later cell names its experiment. Do not overwrite the baseline, silently replace a workload, omit refusals, or report a proposed target as an achieved result. Use `not measured`, `blocked`, or `not applicable` rather than zero. Update this file after each measured stage, including rejected changes. @@ -43,7 +43,9 @@ The order follows the plan. Later stages are conditional on the preceding measur | P2d-W | The `warnings` stage stops repeating itself: one lex and one `LineIndex` per file per call | P2d's finding | dev (Opus); release `18ef6d60c548…`; 2026-09-07 | Done | Same README; experiment `P2d-warnings-2026-09-07` below. The pure dedupe §P2d filed: `FileScan` memoizes `tokenize` and `LineIndex::new` per file, the five scans share it, and their sentences are concatenated in the order the five loops emitted them. The `warnings` stage **82.2 → 51.4 ms** on the tail rename, **22.9 → 8.3** on `aes`, **848.5 → 437.9** on the `clk_i` fallback. Tail rename **387.9 ms = 2.01× the §P0 REF — the ≥2× target is met.** The second dedupe P2d proposed (gate `macro_argument_sites` on `files_naming_in_macros`) is **not taken and the reason is in the code**: `macro_words` skips double-quoted runs, so `` `uvm_info("state_q", …) `` is a site the scan reports and the census cannot see. Warning **lists** compared as lists across 13 renames, old binary vs new: identical, order included | | P3 | Reuse CLI census parse for package exports/interfaces | P0; coordinate semantic ownership | dev (Opus); release CLI sha256 `2c16b321cb2d…`; 2026-09-07 → QA PASS → lead; committed 2026-09-07 | Done — 96 % of the increment removed, outputs byte-identical | `docs/features/perf5-p3/README.md`; experiment `P3-2026-09-07` below. Additive `vlog_linter::package_exports_in(path, file, tokens, src)`: the census parses each file **once** and both halves read that parse, and a file whose tree holds no `package` item never builds an index — **1 624 of `hw/ip`'s 1 805 files** (181 declare a package). No `vlog_semantic` change was needed; `FileFacts::from_analysis` + `IndexBuilder::add_facts` already existed. All-style `hw/ip` **0.6333 → 0.4817 s (−23.9 %)**, the rule's paired increment **141.7 → 5.0 ms**, default `check` unchanged (medians identical), all-style peak RSS **219.1 → 202.0 MiB**. Every cell's stdout **byte-identical** to the reference's, `hw/vendor` and `hw/dv` included | | P4a | Attribute scan/prelude/table-build/cache/RSS cost | P0 | dev (Opus); release sha256 `08093a3a2b9c…`; 2026-09-07 → QA pending → QA PASS → lead; committed 2026-09-08 | Done — breakdown measured; ruling: P4b = skip unchanged-store compaction + no store I/O for an empty scan; store reuse across rescans refused | `docs/features/perf5-p4/README.md`; experiment `P4a-2026-09-07` below. A `--verbose` scan now says its stages, counts and end-state sizes in three `timing: scan …` lines. **A workspace session pays three scans and the first indexes zero files**; warm that empty scan still costs **183.7 ms** opening and compacting a 44.3 MiB store it does not use. Warm settle 1 332.7 ms has no dominant stage — discovery 255.9 / absorb 218.1 / decode 202.8 / **cache_open 183.5** / **compact 182.4** / candidates 113.3 / lookup 51.3 / includes 46.3 — and the store's own I/O is **27.5 %** of it. Cold settle 2 893.6 ms is **58.9 % parse**. The §P0 first-answer puzzle is closed arithmetically: cold 82.1 = 0.54 + 81.58, warm 207.5 = 181.19 + 26.31 | -| P4b | Implement the dominant measured startup/memory fix | P4a; serialize with state/index changes | — | Ruled go (lead, 2026-09-08): (a) + (b1) + the rescan-interleaving question | §P4a's recommendation: the dominant stage is the store's I/O on a warm start. Skipping compaction of an unchanged store is **−182.4 ms warm (13.7 %)**, not opening the store for an empty work list **−92.5 ms (6.9 %)**, reusing a store the session already read **−91.0 ms (6.8 %)**. **Warm < 1 s reachable** (1 057.8 ms with the first two, 966.8 with all three); **cold < 2.3 s not reachable** by anything on §P4b's list (58.9 % of cold is parse); **idle RSS −15 % not reachable** — the hypothesised retention is real at **44.20 MiB, 7.7 % of warm idle** | +| P4b | Implement the dominant measured startup/memory fix | P4a; serialize with state/index changes | dev (Opus); release sha256 `623c0ea62df4…` against a same-window HEAD `2434729` control `5957b0826249…`; 2026-09-08 → QA pending. **The one regression it named is closed by P4b2 below, and the store I/O it could not remove is removed there too** | Done (three passes: compaction skip + deferred open; staged startup; lazy read + folder-first + drain rule) — QA PASS → lead; committed 2026-09-08 | `docs/features/perf5-p4/README.md` §P4b; experiment `P4b-2026-09-08` below. §P4a's 274.9 ms estimate was not additive: (b1) **moves** scan 1's `cache_open` onto the widen rather than removing it, so the ledger is −180.2 ms of compaction + 10.1 ms of skip check. Warm < 1 s needs the refused (b2) (`cache_open` is still paid twice, 181.7 ms) | **Amended 2026-09-08 (P4b2):** the bimodal warm first answer is gone — not by the fourth `must_wait` state this row proposed, but by staging the startup scan; and the `cache_open` paid twice, which this row called unreachable without the refused (b2), is now paid **once** because there is one whole scan in a session instead of two +| P4b2 | Stage the initial scan until configuration arrives (the plan's §P4 work order, ruled 2026-09-08) | P4b | dev (Opus); release sha256 shipped `7522696e894a…` (matrix measured on `3ff0db0920d1…`, a pure move apart) paired against the previous P4b release `623c0ea62df4…`; 2026-09-08 → QA pending | **Done — one scan per session, at the answered scope, with a bounded fallback.** `Server::started` sends `workspace/configuration` first and waits up to `CONFIGURATION_WAIT` (2 s) on `recv_timeout`; the empty default-scope scan and the widen behind it are gone. Paired: warm settled **1 181.34 → 1 097.98 ms, −7.1 %** and, on the shipped binary re-run, **1 190.48 → 1 037.31, −12.9 %**; cold 2 963.21 → 2 843.84, **−4.0 %**; `scopeDepth 0` **−89.2 % cold / −72.6 % warm**; 1/10/100 open buffers **−28.4 / −26.8 / −21.0 %**; warm `cache_open` **183.70 → 91.91 ms** (the refused (b2)'s saving, without store reuse); warm idle RSS **−5.8 %**, cold +0.0 %; store byte- and mtime-identical; all 24 scope answers identical; `didOpen` pinmux **−6.3 %**; `mismatched_answers` **0**. **The `scanserve` "queued behind the configured rescan" mode is gone** — nothing above 476 ms cold / 382 ms warm, against 2 622–2 934 / 934–1 234 | `docs/features/perf5-p4/README.md` §P4b2; experiment `P4b-staged-2026-09-08` below. **One regression, named and filed:** the first useful answer is now **unimodal but empty** — 293–411 ms with result count **0**, where P4b answered 87–126 ms with count 1 in its fast mode and 1 205–2 903 ms in its slow one. The floor is `begin_scan`'s discovery (292.74 ms warm, traced) and the prefix at the first drain is the open buffer alone. The fix is an `open_first` ordering change in `state.rs`, which this lane holds calls-only: filed as Handshake 11 | **Amended 2026-09-08 (P4b3):** granted and done — and the ordering alone was not enough, because the client answers the settings pull from its own reader thread and usually beats the editor's `didOpen`, so the scan begins with no buffer open. The shipped fix is the ordering **plus** a drain rule; result count 1 in 12 of 12 | +| P4b3 | The lazy read and the folder-first order — §P4b2's empty first useful answer, closed (Handshake 11, granted 2026-09-08) | P4b2 | dev (Opus); release sha256 `7ab4955ee0ac…` paired against the shipped P4b2 release `7522696e894a…`; 2026-09-08 → QA pending | **Done — the first useful answer is useful again: result count 1 in 12 sessions of 12**, where P4b2 was 0 in 12 of 12, and **faster too**: cold 287.40 → **249.00 ms (−13.4 %)**, warm 332.68 → **277.37 (−16.6 %)** in `scan`, confirmed in `scanwait` (−11.0 % / −13.5 %). `collect_sources` reads nothing off disk; `scan_step` reads a file when it indexes it and drops it there, so **`work_kib` 34 973 → 0–16** and **idle RSS −7.0 % cold / −7.2 % warm**, peak still equal to idle. `discovery` **227 → 158 ms** warm with a new `read` stage at 86, and `includes` **42 → 8.6 ms**. The work list leads with the open buffers and the folders they raise to (`crate::scan_order`), and a held request — or one behind a mid-scan `didOpen` — waits for that folder (`Server::head_owed`, a fifth `must_wait` clause). Settled unchanged within noise (−5.2 % / −3.0 % in `scan`, +0.9 % / +1.9 % in `scanprofile`); all 24 scope answers identical; the store byte-identical from both binaries; `mismatched_answers` **0**; §46's `didOpen` untouched and unreachable from this change | `docs/features/perf5-p4/README.md` §P4b3; experiment `P4b-lazy-2026-09-08` below. **The latency target is missed and the reason is now measured: the first useful answer is walk-bound.** `discovery` is 158 ms of pure scope walk with no read left in it — 58 % of the 274 ms warm answer — and `cache_open` is another 89 ms (the refused (b2)). The §P0 REF's 84/208 ms was answered off a 124-file **folder** scan that never walked the workspace, so it is not reachable by ordering. Filed for the next lane, with two things to measure first: the cap taking its size from the walk's own metadata (`lucisv_core::walk` is not this lane's file — a handshake request) and handing the first folder to `scan_step` before the walk finishes | | P5 | Parser or cancellable snapshot work only if a new measured case justifies it | Reprofile P1–P4 | — | Deferred | — | ## Before / after performance @@ -101,20 +103,20 @@ REF and part of each delta is §P1b's. | Extract command actually executed (`execute`, **new**) | not measured — take 4's `extract-module resolve` rows are invalid | Measure the command, not a refusal | **REF** `lucisv.extractModule` at `aes.sv` 220:0–222:53: **257.33 / 245.05–247.00 ms** executeCommand→applyEdit; 2 edits / 2 files / **1 created**; `deliver_ms` 0.015–0.033; status `capture`; fingerprint `090e92e7736e…` — REF median **246.03**. **P2a** median 244.53, **P2b** 244.78, **P2c** 161.41 / 149.25–149.86, median **149.25**; 2 edits / 2 files / 1 created, **fingerprint identical** | new row; **P2c −39.3% on REF** | The gap the tracker's work-count table named is closed — and §P2c's `verify_move` reuse is worth 39 % of the one refactoring command that really runs | | Inline command actually executed (`execute`, **new**) | not measured | Measure the command, not a refusal | `lucisv.inlineModule` at `aes_wrap.sv` 66:2 is **refused** (`generate` construct); 6.58 / 5.87–6.20 ms. Not a timing of an inline. **P2c** 5.62 / 5.49–5.05, median **5.33**. **H33** 6.95 / 6.74–6.17, median **6.55**, same refusal sentence | new row; **H33 +1.2 ms on P2c** | Refusal recorded as `refused`; **not quotable** as an inline cost. The H33 delta is the fifth rung's own census walk plus the 8 files it adds — the price of the refusal handshake 33 was missing | | Extract offered at the inline cursor, refused (`execute`, **new**) | not measured | — | `lucisv.extractModule` at `aes_wrap.sv` 66:2 refused after **817.37 / 793.77–809.07 ms** — REF median ~801. **P2a** 802.03, **P2b** 802.07, **P2c** median **801.23**, **H33/P2d** 819.36 / 797.00–790.80, median **794.12**, same sentence | new row; **0 % at P2c, −0.9 % in the second lane** | Unchanged, and correctly so: it refuses *immediately after* `Scope::build`, so there is no repeated analysis for §P2b/§P2c to remove. Its cost is `module_sources` selecting hundreds of files for a **package** name — §P2d and handshake 33 territory | -| Cold workspace scan (`scan`, 3 fresh sessions) | 2830.30–2853.06 ms; mean 2843.00 | Investigation goal <2300 ms | **REF** 2860.12–2868.45 ms; mean 2863.85 — **P4a (instrumented binary, quiet)** 2846.95 / 2875.49 / 3046.12, mean 2922.85 | +0.7% on means; **P4a +2.1% on means, −0.5% excluding the first try** | Agrees. The first try is the first cold session after a link and is an outlier by 170 ms; the trace itself costs nothing measurable | -| Warm workspace scan (`scan`, 3 fresh sessions) | 1322.24–1344.03 ms; mean 1332.41 | Investigation goal <1000 ms | **REF** 1346.02–1352.80 ms; mean 1348.94 — **P4a** 1327.12 / 1331.64 / 1369.46, mean 1342.74 | +1.2% on means; **P4a −0.5%** | Agrees | -| First useful answer during the scan (`scan`, **new**, 3 fresh sessions) | not measured | Stay responsive during a scan (P4) | **REF** cold **84.42–85.87 ms**, warm **206.12–218.72 ms**; 1 location in every session — **P4a** cold 84.51 / 85.71 / 86.17, warm 209.07 / 209.52 / 212.08 | new row; **P4a +0.3% cold, inside the REF range warm** | **Explained at P4a, arithmetically.** The definition is answered when the widen the `didOpen` triggered ends: cold 0.54 + 81.58 = 82.1, warm 181.19 + 26.31 = 207.5. Warm is slower because the *empty* startup scan ahead of the widen spends 181 ms opening and compacting a 44.3 MiB store. Not the publish cadence, not the decode — the config wait, and specifically that scan's store I/O | -| Cold idle RSS (`rss`, 3 fresh sessions) | 528.0–530.9 MiB | Investigate ≥15% reduction; counts unchanged | **REF** 526.7 / 530.2 / 535.2 MiB (`rss_kib`, no longer in `ms`) — **P4a** 531.0 / 529.0 / 529.9 | +0.8% on the maximum; **P4a −0.8%** | Agrees | -| Warm idle RSS (`rss`, 3 fresh sessions) | 566.4–573.8 MiB | Investigate ≥15% reduction; measure peak too | **REF** 575.0 / 572.5 / 575.6 MiB — **P4a** 574.8 / 565.2 / 564.8 | +0.3% on the maximum; **P4a −0.1%** | Agrees. **P4a names what the warm-minus-cold 34–46 MiB is**: the encoded facts `IndexCache` holds beside the decoded index, measured at **45 260 KiB = 44.20 MiB, 7.7 % of warm idle** — the plan's hypothesis, confirmed, and worth at most half the −15 % goal | -| Peak RSS across the scan (`rss`, **new**) | not measured | Measure peak, not only idle | **REF** cold 526.7 / 530.2 / 535.2 MiB, warm 575.0 / 572.5 / 575.6 MiB — **equal to idle to the KiB in all six sessions** (`ps -o rss=` at 50 ms). **P4a: equal to idle to the KiB again, all six sessions** | new row | The resident set rises monotonically; there is no transient above idle on this workload — reproduced at P4a. The scan's own 34.15 MiB of held source text (`work_kib`) is released at `finish_scan` and does not show | -| Startup scans per session (`scanprofile`, **new**, P4a) | not measured — the plan expected "a 124-file default scan before the final scope" | Name every scan a session pays | **P4a: a workspace session pays three.** Scan 1 (whole, at the default settings) indexes **0 files** — the folder scope is derived from directories a buffer has been opened from and none has; scan 2 is a **widen** (124 files) the first `didOpen` triggers; scan 3 is the configured whole scan (3 976 files). `scopeDepth 0` pays the same three and ends with 1 file. Cold 0.8 / 94.0 / 2 760.0 ms; warm **183.7** / 26.6 / 1 112.7 ms | new row | The plan's "124-file default scan" is real but is a widen, and the startup scan proper is empty — **and warm it still costs 183.7 ms** (`cache_open` 92.5 + `compact` 91.0 on a store it does not use) | -| Warm scan stage breakdown (`scanprofile`, **new**, P4a) | not measured | Attribute the warm settle | **P4a**, summed over the session's three scans, against a settled mean of **1 332.7 ms**: discovery **255.91** (19.2 %), absorb **218.08** (16.4 %), decode **202.75** (15.2 %), cache_open **183.46** (13.8 %), compact **182.39** (13.7 %), candidates **113.34** (8.5 %), lookup **51.31** (3.9 %), includes **46.30** (3.5 %), publish_absorb 4.34, everything else 4.40, parse **0.00**. Named total **1 262.28 = 94.7 %**; unattributed 70.44 (the scan loop, the progress/log callbacks, the per-file word `Vec`, the staging pushes) | new row | **No dominant stage** — the top five are within 1.4× of each other — but the store's own I/O (`cache_open` + `compact`) is **365.9 ms, 27.5 %**, and half of that is spent by the scan with no files in it | +| Cold workspace scan (`scan`, 3 fresh sessions) | 2830.30–2853.06 ms; mean 2843.00 | Investigation goal <2300 ms | **REF** 2860.12–2868.45 ms; mean 2863.85 — **P4a (instrumented binary, quiet)** 2846.95 / 2875.49 / 3046.12, mean 2922.85 — **P4b** 2816.59 / 2813.47 / 2818.56, mean **2816.21**, against a same-window HEAD `2434729` control's 2857.77 / 2834.77 / 2848.29 (mean 2846.94) — **P4b2** 2859.99 / 2869.28 / 2802.25, mean **2843.84**, against the previous P4b release re-run in the same window (3125.88 / 2885.50 / 2878.26, mean 2963.21) | +0.7% on means; **P4a +2.1% on means, −0.5% excluding the first try**; **P4b −1.1 % paired** | Agrees. The first try is the first cold session after a link and is an outlier by 170 ms; the trace itself costs nothing measurable |. Unchanged, as §P4a predicted: cold is 59 % parse and §P4b touches none of it — **P4b3** 2 660.72 / 2 639.93 / 2 637.20, mean **2 645.95**, against the shipped P4b2 release re-run in the same window (2 932.23 / 2 720.02 / 2 721.87, mean 2 791.37), **−5.2 %**; the `scanprofile` phase of the same matrix has it the other way at **+0.9 %** (2 602.34 → 2 624.90). Both are quoted: the honest reading is **unchanged** +| Warm workspace scan (`scan`, 3 fresh sessions) | 1322.24–1344.03 ms; mean 1332.41 | Investigation goal <1000 ms | **REF** 1346.02–1352.80 ms; mean 1348.94 — **P4a** 1327.12 / 1331.64 / 1369.46, mean 1342.74 — **P4b** 1132.60 / 1143.54 / 1136.83, mean **1137.66**, against the same-window control's 1325.28 / 1324.62 / 1330.64 (mean 1326.85) — **P4b2** 1097.51 / 1094.56 / 1101.88, mean **1097.98**, against the previous P4b release re-run in the same window (1169.60 / 1159.20 / 1215.23, mean 1181.34), and on the **shipped** binary re-run paired at load 8.7–9.1 **1040.79 / 1036.88 / 1034.28, mean 1037.31** against 1198.25 / 1175.12 / 1198.07 (mean 1190.48), **−12.9 %** | +1.2% on means; **P4a −0.5%**; **P4b −14.3 % paired** | Agrees |. The two compactions (180.2 ms of rewriting a byte-identical 44.3 MiB file) are gone, less the 10.1 ms the skip's own existence sweep costs. The plan's < 1 s needs the refused (b2): `cache_open` is still paid twice, 181.7 ms — **P4b3** 968.84 / 967.68 / 1 004.41, mean **980.31**, against the shipped P4b2 release re-run in the same window (1 019.48 / 1 030.21 / 983.13, mean 1 010.94), **−3.0 %**; `scanprofile` has it at **+1.9 %** (965.89 → 983.95). **Unchanged**, and the ledger says why it is a wash: `discovery` −69 ms and `includes` −34 ms against a `read` stage of +86 — the same 34 MiB read a file at a time costs ~13 ms more than in one tight loop +| First useful answer during the scan (`scan`, **new**, 3 fresh sessions) | not measured | Stay responsive during a scan (P4) | **REF** cold **84.42–85.87 ms**, warm **206.12–218.72 ms**; 1 location in every session — **P4a** cold 84.51 / 85.71 / 86.17, warm 209.07 / 209.52 / 212.08 — **P4b** cold 85.62 / 86.83 / 84.45 (control 84.06 / 84.01 / 84.60); warm **116.77 / 1133.53 / 1137.51** (control 208.94 / 206.16 / 208.85) — **P4b2** cold **293.04 / 300.26 / 294.82**, warm **396.86 / 404.88 / 411.39**, against the previous P4b release re-run in the same window (cold 2902.62 / 2884.55 / 86.97, warm 1205.18 / 1204.50 / 125.84). **Unimodal at last — and empty: result count 0 in all six P4b2 sessions, 1 in all six P4b ones** | new row; **P4a +0.3% cold, inside the REF range warm**; **P4b cold +1.6 %, warm bimodal** | **Explained at P4a, arithmetically.** The definition is answered when the widen the `didOpen` triggered ends: cold 0.54 + 81.58 = 82.1, warm 181.19 + 26.31 = 207.5. Warm is slower because the *empty* startup scan ahead of the widen spends 181 ms opening and compacting a 44.3 MiB store. Not the publish cadence, not the decode — the config wait, and specifically that scan's store I/O |. **Warm is now 117 ms or the whole configured rescan.** Not a new mechanism: `Server::must_wait` has always held a request behind a rescan a message asked for, and warm scan 1's 181 ms of store I/O used to give the client's `didOpen` a head start it won in **15 of 15** sessions ever measured (§P0's three, §P4a's three, QA's three, this control's six). With scan 1 at 0.15 ms the race with the `workspace/configuration` answer is genuine. Filed for the lead in `docs/features/perf5-p4/README.md` **P4b3 — the regression closed.** Cold **249.13 / 249.70 / 248.16**, warm **272.78 / 290.81 / 268.52**, **result count 1 in all six**, against the shipped P4b2 release re-run in the same window (cold 288.11 / 286.68 / 287.41, warm 364.43 / 315.23 / 318.38, **count 0 in all six**): **−13.4 % cold, −16.6 % warm, and useful where P4b2's was empty**. `scanwait` agrees on a second set of six sessions — cold 236.93 / 253.85 / 252.19, warm 273.98 / 266.90 / 281.63, count 1 in all six, against 275.13 / 283.30 / 273.38 and 317.41 / 318.91 / 321.04 at count 0 — so **12 of 12 useful**. **The REF's 84/208 ms is still missed, and the trace says why**: the answer is now walk + the user's folder, and warm the walk is `discovery` **158.32** plus `cache_open` **89.24** before the folder's 124 files (≈25 ms) can be published — `first_publish` 316.74 → **249.70**, and that publish carries **125 files instead of 1**. The REF answered off a 124-file *folder* scan that never walked the workspace +| Cold idle RSS (`rss`, 3 fresh sessions) | 528.0–530.9 MiB | Investigate ≥15% reduction; counts unchanged | **REF** 526.7 / 530.2 / 535.2 MiB (`rss_kib`, no longer in `ms`) — **P4a** 531.0 / 529.0 / 529.9 — **P4b** 527.08 / 529.25 / 530.45 MiB against the same-window control's 493.56 / 532.58 / 529.44 — **P4b2** 532.44 / 525.05 / 532.11 MiB against the previous P4b release re-run in the same window (529.64 / 530.14 / 529.61) | +0.8% on the maximum; **P4a −0.8%**; **P4b −0.4 % on the maximum** | Agrees |. Unchanged — **P4b3** 490.89 / 488.11 / 493.36 MiB (max **493.36**) against the shipped P4b2 release re-run in the same window (529.59 / 530.30 / 528.27, max 530.30): **−7.0 % on the maximum**, the 34 MiB of source text a scan no longer holds. Peak equals idle to the KiB in all six sessions +| Warm idle RSS (`rss`, 3 fresh sessions) | 566.4–573.8 MiB | Investigate ≥15% reduction; measure peak too | **REF** 575.0 / 572.5 / 575.6 MiB — **P4a** 574.8 / 565.2 / 564.8 — **P4b** 482.55 / 481.67 / **482.75** MiB against the same-window control's 563.81 / 569.95 / **569.75** — **P4b2** 455.53 / 456.25 / 454.86 MiB against the previous P4b release re-run in the same window (484.63 / 482.34 / 484.08), **−5.8 % on the maximum** | +0.3% on the maximum; **P4a −0.1%**; **P4b −15.3 % on the maximum** | Agrees. **P4a names what the warm-minus-cold 34–46 MiB is**: the encoded facts `IndexCache` holds beside the decoded index, measured at **45 260 KiB = 44.20 MiB, 7.7 % of warm idle** — the plan's hypothesis, confirmed, and worth at most half the −15 % goal |. **The plan's −15 % goal, met — and §P4a said it was out of reach.** Not the encoded-facts retention, which is untouched at 44.20 MiB: it is the allocator retention of the two 44.3 MiB `String`s a warm HEAD session rendered to rewrite the store with. Warm idle is now *below* cold idle — **P4b3** 422.59 / 418.88 / 418.34 MiB (max **422.59**) against the shipped P4b2 release re-run in the same window (453.23 / 454.61 / 455.33, max 455.33): **−7.2 % on the maximum**. Peak equals idle to the KiB in all six sessions; `store_kib` 45 404 for both +| Peak RSS across the scan (`rss`, **new**) | not measured | Measure peak, not only idle | **REF** cold 526.7 / 530.2 / 535.2 MiB, warm 575.0 / 572.5 / 575.6 MiB — **equal to idle to the KiB in all six sessions** (`ps -o rss=` at 50 ms). **P4a: equal to idle to the KiB again, all six sessions** — **P4b: equal to idle to the KiB in all six sessions again**, and so is the control's | new row | The resident set rises monotonically; there is no transient above idle on this workload — reproduced at P4a. The scan's own 34.15 MiB of held source text (`work_kib`) is released at `finish_scan` and does not show | +| Startup scans per session (`scanprofile`, **new**, P4a) | not measured — the plan expected "a 124-file default scan before the final scope" | Name every scan a session pays | **P4a: a workspace session pays three.** Scan 1 (whole, at the default settings) indexes **0 files** — the folder scope is derived from directories a buffer has been opened from and none has; scan 2 is a **widen** (124 files) the first `didOpen` triggers; scan 3 is the configured whole scan (3 976 files). `scopeDepth 0` pays the same three and ends with 1 file. Cold 0.8 / 94.0 / 2 760.0 ms; warm **183.7** / 26.6 / 1 112.7 ms — **P4b, warm**: scan 1 (whole, 0 files) **180.72 → 0.15 ms** (`opens` 0, `compactions` 0); scan 2 (widen, 124) 26.21 → 116.51, which is scan 1's `cache_open` **moved** onto it (90.62); scan 3 (whole, 3 976) 1087.84 → 1016.23 with `compact` **90.20 → 10.13** and `compactions` **1 → 0**. Session sum 1294.77 → **1132.89, −12.5 %** — **P4b2: a workspace session pays ONE.** The empty scan and the widen behind it are both gone; warm the one scan reads 3 976 files in 1 093.67 ms with `cache_open` **91.91 once** against P4b's 91.38 + 92.32 = 183.70, settled **1 233.39 → 1 110.48, −10.0 %**. `scopeDepth 0` pays two trivial scans (0 files, then a 1-file widen) totalling 1.4 ms against P4b's three totalling 106 ms | new row | The plan's "124-file default scan" is real but is a widen, and the startup scan proper is empty — **and warm it still costs 183.7 ms** (`cache_open` 92.5 + `compact` 91.0 on a store it does not use) |. Three scans still, and the first now costs nothing — **P4b3: still one**, and what that one scan spends changed shape: warm `discovery` **227.02 → 158.32 ms** with the 34 MiB read taken out of it into a new `read` stage (85.54), `includes` **42.12 → 8.60**, and `work_kib` — the source text held for the scan's life — **34 973 → 0** +| Warm scan stage breakdown (`scanprofile`, **new**, P4a) | not measured | Attribute the warm settle | **P4a**, summed over the session's three scans, against a settled mean of **1 332.7 ms**: discovery **255.91** (19.2 %), absorb **218.08** (16.4 %), decode **202.75** (15.2 %), cache_open **183.46** (13.8 %), compact **182.39** (13.7 %), candidates **113.34** (8.5 %), lookup **51.31** (3.9 %), includes **46.30** (3.5 %), publish_absorb 4.34, everything else 4.40, parse **0.00**. Named total **1 262.28 = 94.7 %**; unattributed 70.44 (the scan loop, the progress/log callbacks, the per-file word `Vec`, the staging pushes) — **P4b**, same session shape: discovery 246.11, absorb 208.40, decode 195.10, **`cache_open` 91.12 + 90.62 = 181.74**, candidates 105.81, lookup 48.84, includes 44.51, **`compact` 10.13** (the skip's existence sweep, not a rewrite), parse 0.00 | new row | **No dominant stage** — the top five are within 1.4× of each other — but the store's own I/O (`cache_open` + `compact`) is **365.9 ms, 27.5 %**, and half of that is spent by the scan with no files in it |. `compact` is no longer a stage worth naming; `cache_open` is now the largest thing the store costs, and it is exactly the refused (b2) | Cold scan stage breakdown (`scanprofile`, **new**, P4a) | not measured | Attribute the cold settle | **P4a**, against a settled mean of **2 893.6 ms**: parse **1 703.63** (58.9 %), discovery 299.59 (10.4 %), absorb 218.40 (7.5 %), encode 183.26 (6.3 %), store_write 118.46 (4.1 %), candidates 110.66 (3.8 %), compact 93.89 (3.2 %), includes 45.52 (1.6 %), decode 5.87, publish_absorb 4.41, cache_open 3.39, lookup 2.86, rest 4.15. Named total **2 794.09 = 96.6 %**; unattributed 99.49 | new row | Cold is a different problem from warm: **58.9 % is parsing**, which nothing on §P4b's list touches | -| Open buffers 1 / 10 / 100 (`scanprofile`, **new**, P4a) | not measured | Measure what open buffers cost a scan | **P4a**, warm workspace, buffers opened right after `initialize`: settled mean **1 841.6 / 1 859.1 / 2 173.9 ms**; a **fourth** scan appears (a second widen, 352–372 ms, for the folders those files live in, 1 685 files). Overlay refresh on the final scan **0.31 / 1.33 / 19.67 ms**; `order` (open-buffers-first) **1.30 / 3.97 / 60.64 ms**; a buffer's own record written through 0.49 / 2.21 / 21.20 ms; buffers indexed from their own analysis 2 / 11 / 101; config round trip 388–404 / 401–417 / 561–570 ms | new row | **The overlay refresh is not the cost** — 100 buffers refresh in 19.7 ms. What scales is `open_first`: 60.6 ms at 100 buffers, one linear scan of a 3 976-entry work list per buffer. 3 % of that session's settle; filed, not recommended | -| Requests arriving during a scan (`scanserve`, **new**, P4a) | not measured | Definition stays responsive; no mismatched tables | **P4a**, a definition every 200 ms for as long as the scan reports, 3 fresh sessions per cache state, three answers each and three distinct modes: during scans 1–2 cold **83.66 / 83.97 / 84.95**, warm **210.26 / 212.58 / 214.34**; **queued behind the configured rescan cold 2 558.85 / 2 563.65 / 2 567.24, warm 897.12 / 904.12 / 907.90**; after settle cold 0.39–0.43, warm 0.24–0.40. **`mismatched_answers` = 0 across all 18 requests** | new row | **A request arriving during the configured rescan waits the whole rescan** — 2.56 s cold, 0.90 s warm. Correct per the scan-interleave contract (only a scan *nobody asked for* interleaves), but the scan that interleaves is the empty one. Coherence holds: every mid-scan answer named exactly what the settled index names, or nothing | -| Configuration round trip (`scanprofile`/`scanwait`, **new**, P4a) | not measured — the plan names "discovery + config wait" | Separate the wait from the work | **P4a**, `timing: configuration answered in`: cold **82.8–97.4 ms**, warm **27.3–35.9 ms**, and 388–570 ms with open buffers. The harness answers `workspace/configuration` from its reader thread instantly in every case | new row | The number is not the client thinking — it is **when the server got back to reading the answer**, i.e. the work queued ahead of it. Cold that is the 124-file widen; warm it is the empty scan's store I/O | -| Index store allocated size (`rss`, `du -sk`) | 44.34 MiB | Record codec/version and contents | **REF** 45 404 KiB = **44.34 MiB** (`store_kib`) | 0.0% | Identical | -| Pinmux open → definition (`didopen`, 3 fresh sessions) | 128.13–129.96 ms | Preserve §46 benefit | **REF** 119.01–131.85 ms | −3.8% on medians | Agrees; §46's fix intact | +| Open buffers 1 / 10 / 100 (`scanprofile`, **new**, P4a) | not measured | Measure what open buffers cost a scan | **P4a**, warm workspace, buffers opened right after `initialize`: settled mean **1 841.6 / 1 859.1 / 2 173.9 ms**; a **fourth** scan appears (a second widen, 352–372 ms, for the folders those files live in, 1 685 files). Overlay refresh on the final scan **0.31 / 1.33 / 19.67 ms**; `order` (open-buffers-first) **1.30 / 3.97 / 60.64 ms**; a buffer's own record written through 0.49 / 2.21 / 21.20 ms; buffers indexed from their own analysis 2 / 11 / 101; config round trip 388–404 / 401–417 / 561–570 ms | new row | **The overlay refresh is not the cost** — 100 buffers refresh in 19.7 ms. What scales is `open_first`: 60.6 ms at 100 buffers, one linear scan of a 3 976-entry work list per buffer. 3 % of that session's settle; filed, not recommended |. **P4b2 (paired, same window):** one scan in every cell, settled **1 555.37 → 1 113.56 (−28.4 %) / 1 555.93 → 1 139.27 (−26.8 %) / 1 721.70 → 1 360.10 (−21.0 %)**. The fourth scan P4a named — a second widen over 1 685 files for the folders the extra buffers live in — no longer happens at all: the one startup scan resolves the scope with every buffer already installed — **P4b3 (paired, same window):** settled 1 010.91 → **994.74** (−1.6 %), 973.62 → 1 003.75 (+3.1 %), 1 185.95 → **1 181.55** (−0.4 %) — unchanged. **§P4a's `order` finding is closed**: 60.64 ms at 100 buffers is now **1.95 ms**, because the open set is a `HashSet` and the ranking is one stable sort instead of one linear scan per buffer +| Requests arriving during a scan (`scanserve`, **new**, P4a) | not measured | Definition stays responsive; no mismatched tables | **P4a**, a definition every 200 ms for as long as the scan reports, 3 fresh sessions per cache state, three answers each and three distinct modes: during scans 1–2 cold **83.66 / 83.97 / 84.95**, warm **210.26 / 212.58 / 214.34**; **queued behind the configured rescan cold 2 558.85 / 2 563.65 / 2 567.24, warm 897.12 / 904.12 / 907.90**; after settle cold 0.39–0.43, warm 0.24–0.40. **`mismatched_answers` = 0 across all 18 requests** — **P4b**: during scans 1–2 cold 84.63 / 85.61 / 85.87, **warm 117.98 / 118.88** (control 206.77 / 208.49 / 209.67); queued behind the configured rescan cold 2582.51 / 2588.46 / 2600.39, warm 824.36 / 826.06 / 1150.43; after settle under 0.4 ms. **`mismatched_answers` = 0 in every row of both binaries** — **P4b2: the queued mode is GONE.** Every mid-scan answer cold falls between 0.20 and **475.41** ms across 37 answers and warm between 0.21 and **381.54** across 12, against the same-window P4b run's 2 621.84 / 2 658.83 / 2 933.71 cold and 933.86 / 942.65 / 1 233.87 warm. `mismatched_answers` **0** in all four rows of both binaries | new row; **P4b warm mid-scan −43 %**; **P4b2 removes the third mode entirely** | **A request arriving during the configured rescan waits the whole rescan** — 2.56 s cold, 0.90 s warm. Correct per the scan-interleave contract (only a scan *nobody asked for* interleaves), but the scan that interleaves is the empty one. Coherence holds: every mid-scan answer named exactly what the settled index names, or nothing |. A warm mid-scan answer falls 207 → 118 ms for the same reason the first useful answer does. The queued column is unchanged and is the filed contract — **P4b3**: 36 mid-scan answers cold between 0.35 and **314.8 ms** and 12 warm between 0.35 and **313.3 ms**, against the shipped P4b2 release's 34 cold up to **427.5** and 12 warm up to **360.0** in the same window. `mismatched_answers` **0 in all four rows of both binaries** — the coherence contract survives both the lazy read and the later drain +| Configuration round trip (`scanprofile`/`scanwait`, **new**, P4a) | not measured — the plan names "discovery + config wait" | Separate the wait from the work | **P4a**, `timing: configuration answered in`: cold **82.8–97.4 ms**, warm **27.3–35.9 ms**, and 388–570 ms with open buffers. The harness answers `workspace/configuration` from its reader thread instantly in every case | new row | The number is not the client thinking — it is **when the server got back to reading the answer**, i.e. the work queued ahead of it. Cold that is the 124-file widen; warm it is the empty scan's store I/O |. **P4b2 makes the number mean what it says**: the pull is the first thing the server sends, so nothing is queued ahead of the answer — the traced warm session's scan starts **0.67 ms** after the server was born +| Index store allocated size (`rss`, `du -sk`) | 44.34 MiB | Record codec/version and contents | **REF** 45 404 KiB = **44.34 MiB** (`store_kib`) — **P4b** 45 404 KiB, identical to the control's on the same corpus; and byte-identical *and mtime-identical* across two warm sessions, where the control rewrote the same 46 486 433 bytes on each one — **P4b2** 45 404 KiB, same sha256 `e49bc5c176ea…`, same 46 486 433 bytes and the **same mtime** after a cold session and two warm ones on both binaries | 0.0% | Identical |. §P4b's whole claim about the store, checked by sha256 rather than by size +| Pinmux open → definition (`didopen`, 3 fresh sessions) | 128.13–129.96 ms | Preserve §46 benefit | **REF** 119.01–131.85 ms — **P4b** 109.68 / 122.74 / 114.53 (median **114.53**) against the same-window control's 107.12 / 128.13 / 118.38 (median 118.38) — **P4b2** 110.39 / 128.48 / 107.26 (median **110.39**) against the previous P4b release re-run in the same window (122.67 / 118.75 / 128.15, median 118.75) | −3.8% on medians; **P4b −3.3 % on medians** | Agrees; §46's fix intact |. §46's fix intact | `tb.sv` dirty-buffer folding barrier (`flush`) | 1.05 / 0.65–0.72 ms | No material regression | **REF** 1.90 / 0.93–1.01 ms | **+35.5%** — outside tolerance, see experiment entry | Disagrees; a ~1 ms row, neither number adjusted | | Diagnostics publication (`diagnostics`) | 158.02 / 155.95–157.62 ms | Preserve debounce/burst coalescing | **REF** 156.72 / 152.74–160.55 ms | +1.6% | Agrees | | Unblocked definition (`nav`) | 0.365 / 0.048–0.084 ms; 1 location | Transport-sensitive regression control | **REF** 0.528 / 0.145–0.206 ms; 1 location | +132% but **sub-millisecond: not read** | Not read, per the round's own rule | @@ -1617,6 +1619,343 @@ this stage; each says so rather than being left ambiguous. read at the **end** of a scan (after the fix above), so a cold scan's row reports what it leaves, not what it started from. +## Experiment record — P4b-2026-09-08 (stage P4b) + +- **Experiment ID / stage / date / owner:** `P4b-2026-09-08` / P4b (TODO + §60.4) / 2026-09-08, America/Chicago / dev agent (Opus). +- **Hypothesis and exact expected work reduction:** §P4a's recommendation as + the lead ruled it. (a) skipping a compaction that would rewrite an unchanged + store: **−182.4 ms warm**. (b1) not opening the store for a scan with an + empty work list: **−92.5 ms warm**. Together **−274.9 ms**, landing warm at + ~1 058 ms; cold unchanged; RSS not higher. (b2) refused. +- **Binary / provenance:** release `lucisv-server` sha256 + `623c0ea62df4fe154947725605071fee93e54f02dec3f45e6c566620ed5c0ee3`. + **Control: a release built in the same window from a `git clone --local` at + HEAD `2434729`**, sha256 + `5957b0826249a0354b270d2ec865e7cfc702b187bd359049cc5c73b2170354d4`. Both + built under `tools/guard.sh -m 8 -t 1800`; no `cargo` command ran during any + timed phase. An earlier release of this lane (`c5ceb40cf740…`, (a) and (b1) + without the record short-circuit) was measured and **is kept unquoted** as + `~/.cache/lucisv-perf/take5-p4b/results-compaction-defeated.jsonl` — it is + the evidence that (a) alone is worth nothing. +- **Corpus / machine:** opentitan `00981352642fb65ef2b6c47143a0f6bb31fd4a97` + with its three pre-existing modified files, `git status --porcelain` checked + after every phase of both binaries and unchanged throughout. Same M1 Max, + macOS 27.0. One-minute load **3.6–6.7** — busier than the §P0 REF window + (2.92–4.59), which is exactly why the control was built and every phase run + **alternating HEAD then P4b**. Cross-day REF comparisons are context only; + the paired control is the claim. Scratch caches and `storagePath` under the + session scratchpad; rows in + `~/.cache/lucisv-perf/take5-p4b/results.jsonl` under labels `HEAD` and + `P4b`. +- **What changed in the tree:** `index_cache.rs` — `Load` counters at `open` + (lines read / kept / dropped / duplicated / in path order), + `IndexCache::already_compact`, and `IndexCache::record` returning early for a + record the store already holds byte for byte; `state.rs` — a `StoreOpen` + state so a whole rescan's re-open is deferred to its first file, the + compaction gated on that scan having opened the store at all, and the three + §P4a trace helpers moved out (1 098 → 1 073 production lines); + `scan_trace.rs` — `ScanTrace::opened` / `measure_work` / `landed` received, + and three new `CacheWork` counters (`opens`, `compactions`, `repeats`) + rendered on the count line. No `tools/perf` change was needed: `phases_p4.py` + splits `key=value`. +- **Phases run:** `scan`, `scanprofile`, `scanwait`, `scanserve`, `didopen`, + `rss` — each once per binary, alternating, three fresh sessions per cell — + plus a dedicated `storecheck.py` byte-identity probe on both binaries. +- **Result — the startup, per scan (warm, `--verbose`):** scan 1 (whole, + **0 files**) **180.72 → 0.15 ms**, `opens` 0 and `compactions` 0; scan 2 + (widen, 124) 26.21 → 116.51, which is scan 1's `cache_open` **moved** onto it + (90.62 ms); scan 3 (whole, 3 976) 1 087.84 → 1 016.23, `cache_open` 90.57 → + 91.12, **`compact` 90.20 → 10.13**, `records` 1 → 0, `repeats` 0 → 1, + `compactions` 1 → 0. Session sum **1 294.77 → 1 132.89, −12.5 %**. +- **Result — settled, paired:** warm **1 326.85 → 1 137.66 ms, −14.3 %** + (1 132.60 / 1 143.54 / 1 136.83 against 1 325.28 / 1 324.62 / 1 330.64); + cold **2 846.94 → 2 816.21, −1.1 %**. +- **Result — memory:** warm idle RSS **569.75 → 482.75 MiB on the maximum, + −15.3 %** — the plan's −15 % investigation goal, met, and §P4a had ruled it + out. It is **not** the encoded-facts retention (44.20 MiB, untouched and + still resident): it is the allocator retention of the two 44.3 MiB `String`s + a warm HEAD session renders to rewrite the store with, which P4b renders + none of. Warm idle is now below cold idle (530.45 MiB max, −0.4 %). Peak + equals idle to the KiB in all twelve sessions. +- **Result — the store is left alone, checked by hash:** two warm workspace + sessions over one store. HEAD: sha256 `e49bc5c176ea…` after each, size + 46 486 433 each, **mtime moving every time** — it rewrites the same bytes + twice. P4b: same hash, same size, **same mtime to the nanosecond** — it never + opens the file for writing. +- **Result — everything that had to stay still:** the scope ladder answers + identically in all four scopes × two cache states (`0 | 124` for `default` + and `{"index":{}}`, `124 | 1` for `scopeDepth 0`, `124 | 3 976` with + 123/3 975 from cache and 3 skipped for `workspace`, on **both** binaries); + `didOpen` pinmux median 118.38 → 114.53 (§46 intact) and spi_device 12.40 → + 8.16 (a sub-15 ms row, not read); `mismatched_answers` **0** in all four + `scanserve` rows across both binaries; store on disk 45 404 KiB either way. +- **Result — the one regression:** **warm first useful answer is bimodal, + 116.77 ms or ~1 135 ms**, two of six sessions fast. Cold is unaffected (six + of six fast, both binaries). The mechanism is `Server::must_wait`'s + `answering_a_rescan` clause — the scan-interleave order contract — which + §P4b did not change but did make *reachable*: warm scan 1's 181 ms of store + I/O used to give the client's `didOpen` a head start over its own + `workspace/configuration` answer, won in **15 of 15** sessions ever measured + (§P0's three, §P4a's three, QA's three, this control's six). A + warm mid-scan answer that does win the race falls **207 → 118 ms**. Filed for + the lead with the narrow fix (a fourth state distinguishing a rescan a + *client message* asked for from the one the server's own settings pull asked + for) in `docs/features/perf5-p4/README.md`; **not taken in this lane**, + because it is a documented promise and the plan says file it if it is not + routing. It is not routing: the configured rescan already runs through the + same stepper the startup scan does, publishes all three tables mid-scan, and + is held only at `process_batch`'s `must_wait` test. +- **Deviation from the ruling, reported:** `IndexCache::record` returning early + for a record the store already holds was **not in the ruling**. It is kept + because (a) is worth **nothing** without it — an open buffer is indexed from + its own analysis on every scan and its record is written through with it, so + `records` is never 0 and the store is never canonical. Measured with (a) + alone: warm scan 3 `records` 1, `compactions` 1, `compact` **88.19 ms**. One + `if` and one counter; the lead can back it out at the cost of (a) entirely. +- **Targets:** warm settled ≤ ~1.06 s **missed** at 1 137.66 (−189.2 ms against + the estimated −274.9; §P4a's arithmetic double-counted, because (b1) moves + scan 1's `cache_open` onto the widen rather than removing it — the honest + ledger is −180.2 ms of compaction plus 10.1 ms of skip check). The plan's + warm < 1 s **missed**, and is unreachable without the refused (b2): the warm + session still pays `cache_open` twice, **181.7 ms**, which is now the largest + single thing the store costs. Cold unchanged **met**. RSS not higher + **beaten**, −15.3 % warm. Store bytes identical **met**. Scope ladder + unchanged **met**. `mismatched_answers` 0 **met**. First useful answer warm ≈ + cold **missed as stated** — 117 ms in the fast mode, the configured rescan in + the slow one. +- **Gates:** `cargo fmt --all -- --check` clean; guarded + `cargo clippy --all-targets` clean with no new `#[allow]`; guarded + `cargo test --workspace` green, **4 272 → 4 284** (twelve new tests, none + lost). Zero guard kills; largest resident set observed 591 MiB of the 8 GiB + cap. + +## Experiment record — P4b-staged-2026-09-08 (stage P4b2) + +- **Experiment ID / stage / date / owner:** `P4b-staged-2026-09-08` / P4b2 + (TODO §60.4) / 2026-09-08, America/Chicago / dev agent (Opus). +- **Hypothesis and exact expected work reduction:** the plan's §P4 work order, + as the lead ruled it — *"if the default scan is routinely discarded, stage + the initial scan until configuration arrives, with a bounded fallback for + clients that never answer; keep rootless and scope precedence behavior + intact."* Expected: one scan per session instead of three, the empty scan and + the widen behind it gone, one `cache_open` instead of two (which is the + refused (b2)'s saving arriving another way), and the bimodal warm first + answer §P4b filed replaced by a single fast mode. +- **Binary / provenance:** release `lucisv-server` sha256 + `3ff0db0920d1b86bee5237ea7b7827c7383a402ef73ec138c111cf7a867d7ca8` for the + seven-phase matrix; the **shipped** binary is + `7522696e894a94d8d431f148d4e08e6a9ab7727eb0aaac36f8daa57a684b9076`, which + differs from it by a pure move only (`started`'s struct literal into + `Server::empty`, for the file-size rule's 80-line mark) and on which the + `scan` phase was re-run, paired, at load 8.7–9.1: warm settled + **1 190.48 → 1 037.31, −12.9 %**, cold 2 876.17 → 2 803.60 (−2.5 %), + `scopeDepth 0` −90.4 % / −75.6 %, first useful answer cold + 304.64 / 301.75 / 304.31 and warm 348.74 / 350.54 / 352.14, result count 0. + Both runs are quoted; neither is dropped. Paired + against **the previous §P4b release**, sha256 + `623c0ea62df4fe154947725605071fee93e54f02dec3f45e6c566620ed5c0ee3`, kept in + the session scratchpad before the rebuild and re-run in this window. Both + built under `tools/guard.sh -m 8 -t 1800`; no `cargo` command ran during any + timed phase. **An earlier release of this lane** (`cb3878a02802…`, staging + without `take_the_answer_out_of_held`) was measured and is kept **unquoted** + as `~/.cache/lucisv-perf/take5-p4b2/results-preliminary-stranded-answer.jsonl` + — it is the evidence for the defect described below. +- **Corpus / machine:** opentitan `00981352642fb65ef2b6c47143a0f6bb31fd4a97` + with its three pre-existing modified files, `git status --porcelain` checked + after every phase of both binaries and unchanged throughout. Same M1 Max, + macOS 27.0. **Load is not uniform across this run**: `scan` — the headline + phase — ran at one-minute load **4.7–5.1**; a macOS `XProtect` remediation + sweep and `mediaanalysisd` then took the machine to **20–26** for + `scanwait`/`scanprofile`/`scanserve` and 12–16 for `scopes`/`didopen`/`rss`. + Every phase alternates P4b then P4b2, so both binaries met the same weather + *within* a phase; absolute values in the busy phases are **not** comparable + with §P4b's own window and are not quoted as if they were. Scratch caches and + `storagePath` under the session scratchpad; rows in + `~/.cache/lucisv-perf/take5-p4b2/results.jsonl` under labels `P4b` and + `P4b2`. +- **What changed in the tree:** a new `crates/lucisv_server/src/server/ + startup.rs` holding `Server::new`, `Server::started` (six trailing + parameters folded into a `Startup` struct), `stage_for_configuration`, + `await_configuration`, `take_the_answer_out_of_held` and + `CONFIGURATION_WAIT = 2 s`; `server/mod.rs` loses both constructors (576 → + 153 production lines) and gains `staging`, a fourth `must_wait` clause and + `scan_owed`; `server/index.rs` gains `waiting_for_this_scan` and routes the + three `reindex*` deferral guards through `scan_owed`; `server/client.rs`'s + `say_held` line gains `staging=`. No crate edge moves; nothing touches the + store format, the scope ladder or `state.rs`. +- **Phases run:** `scan`, `scanwait`, `scanprofile`, `scanserve`, `scopes`, + `didopen`, `rss` — each once per binary, alternating, three fresh sessions + per cell — plus a `storecheck.py` byte-identity probe on both binaries. +- **Result — one scan (`scanprofile`, warm workspace):** P4b traced **three** + scans (whole 0 files 0.13 ms, widen 124 files 119.47, whole 3 976 files + 1 082.46; `cache_open` 0 + 91.38 + 92.32 = **183.70**); P4b2 traces **one** + (whole 3 976 files, 1 093.67 ms, `cache_open` **91.91**). Settled + **1 233.39 → 1 110.48, −10.0 %**. `opens` 2 → 1, `compactions` 0 → 0. +- **Result — settled, paired (`scan`, the quiet window):** warm + **1 181.34 → 1 097.98 ms, −7.1 %**; cold **2 963.21 → 2 843.84, −4.0 %**; + `scopeDepth 0` **114.95 → 12.45 cold (−89.2 %)** and + **51.32 → 14.07 warm (−72.6 %)**; the two default-scope cells move −4.7 % to + +5.8 %, all inside 6 ms, which is the config round trip now serialized ahead + of the scan instead of overlapping an empty one. +- **Result — open buffers (`scanprofile`):** 1 / 10 / 100 buffers settled + **1 555.37 → 1 113.56 (−28.4 %) / 1 555.93 → 1 139.27 (−26.8 %) / + 1 721.70 → 1 360.10 (−21.0 %)**, and the *fourth* scan §P4a named (a second + widen over 1 685 files) does not happen. +- **Result — requests during a scan (`scanserve`):** the third latency mode is + gone. P4b answers cold at 0.22 / 0.23 / 0.28 / 84.88 / 89.22 / **2 621.84 / + 2 658.83 / 2 933.71** and warm at 0.24 / 0.28 / 0.38 / 121.91 / 124.44 / + **933.86 / 942.65 / 1 233.87**; P4b2 answers cold across **37** requests + spanning 0.20–475.41 and warm across **12** spanning 0.21–381.54, with + nothing above those. `mismatched_answers` **0** in all four rows of both + binaries. A **genuine** settings-change rescan mid-session still queues + requests — that is `must_wait`'s first clause, untouched, and + `server/tests/startup.rs` drives a late answer and shows the request behind + it answered after the rescan. +- **Result — memory:** cold idle 542 512 → 542 581 KiB (**+0.0 %**, maximum + +0.4 %); warm idle 495 291 → **466 480 KiB (−5.8 %)**, maximum −5.9 %. Peak + equals idle to the KiB in all twelve sessions of both binaries. +- **Result — everything that had to stay still:** `scopes` answers + **identically in all 24 cells** (eight requests × three scopes × both + binaries); the store is left byte-, size- and **mtime-identical** after a + cold session and two warm ones on both binaries (sha256 `e49bc5c176ea…`, + 46 486 433 bytes), `store_kib` 45 404 either way; `didOpen` pinmux median + **118.75 → 110.39** and mean −6.3 %, spi_device 11.05 → 8.40 (§46 intact). +- **Result — the one regression, named:** the warm first useful answer is + **unimodal at last, and empty**. `scan`, quiet window: cold + **293.04 / 300.26 / 294.82** and warm **396.86 / 404.88 / 411.39**, with + **result count 0** in all six — against P4b's cold 2 902.62 / 2 884.55 / + 86.97 and warm 1 205.18 / 1 204.50 / 125.84, **result count 1** in all six. + The mechanism is arithmetic and the trace says it: warm, `discovery` + **292.74 ms**, `first_publish` **389.27**, definition answered at **389.92**. + `begin_scan` reads all 3 976 files' text before the first `scan_step`, so + ≈ 293 ms is the floor of the one-scan design; the request is then answered at + the first drain, off a prefix holding the open buffer and nothing else. + §P4b's fast mode was served by the **widen** — 124 files, run to completion + because `reindex_widened` does not interleave — so its 124 ms answer was + complete for that scope. Staging traded the fast mode's *quality* for the + slow mode's *disappearance*. **Filed as Handshake 11**: order the startup + scan's work list by the open buffers' raised scope directories, not only by + the buffers. Ordering only — `IndexBuilder::finish` sorts by path — but it is + `Workspace::open_first` in `state.rs`, which this lane holds calls-only. +- **Defect found by measuring, before it shipped:** the first paired `scan` run + showed one warm session in three at **2 125 ms** — the two-second bound. + `process_batch` moves everything behind a request that must wait into `held`, + and the client's answer to the pull can be in that burst behind the editor's + opening definition; the wait then blocked until the bound. + `Server::take_the_answer_out_of_held` takes **only** a + `Pending::Configuration` answer back out. Pinned by + `an_answer_behind_a_held_request_is_not_stranded_for_the_whole_bound`. +- **Targets:** warm settled ≤ ~1.06 s **met on the shipped binary** at + **1 037.31** (−12.9 % paired) and **narrowly missed on the first run** at + 1 097.98 (−7.1 %); the two runs bracket the target at loads 8.7–9.1 and + 4.7–5.1 (the `scanprofile` traced session settles at 1 110.48). The + plan's warm < 1 s **missed** — what is left is discovery 300.84, absorb + 213.84, decode 200.05, candidates 108.96, `cache_open` 91.91, lookup 51.09, + includes 45.30, and none of those is store I/O any more. The (b2)-equivalent + saving **met**: one `cache_open` per session, 183.70 → 91.91. Cold within + tolerance **met** (−4.0 %). RSS not higher **beaten** (warm −5.8 %). Store + bytes identical **met**. `mismatched_answers` 0 **met**. Scope answers + identical **met** (24/24). Open-buffer cells **beaten** (−21 to −28 %). The + queued-behind-the-rescan mode gone for the startup case **met**. First useful + answer 85–120 ms in 6 of 6 **missed** — unimodal 293–411 ms and empty, filed + above as the one regression. +- **Correctness tests and logs:** `cargo fmt --all -- --check` clean; guarded + `cargo clippy --all-targets` clean, no new `#[allow]`; guarded + `cargo test --workspace` **4 290 passed, 0 failed** across 58 binaries (4 284 + at the start of the round, plus six new wire tests). One pre-existing test + amended in place — `settings.rs`'s startup-pull wire order, whose subject is + exactly the contract that changed. No guard kill. +- **Decision:** retain, pending the lead's ruling on the empty first answer + (Handshake 11) and on `folders-and-config`'s Assumptions sentence + (Handshake 10). QA pending. +- **QA result and lead review link:** `docs/features/perf5-p4/README.md` + §P4b2 (QA log placeholder dated 2026-09-08). + +## Experiment record — P4b-lazy-2026-09-08 (stage P4b3) + +- **Experiment ID / stage / date / owner:** `P4b-lazy-2026-09-08` / P4b3 + (TODO §60.4) / 2026-09-08, America/Chicago / dev agent (Opus). +- **Hypothesis and exact expected work reduction:** the plan's §P4 sentence + — *"shorten temporary source/encoded-buffer lifetimes; reduce redundant + transient copies"* — plus Handshake 11, granted. Expected: `work_kib` from + 34 973 to ~0; each file's bytes read exactly once; the first useful answer of + a workspace session **useful** (result count 1) rather than empty, at + ≈ walk + the open buffer's folder; settled and the scope answers unchanged; + `mismatched_answers` still 0. +- **Binary / provenance:** release `lucisv-server` sha256 + `7ab4955ee0ac174840fbe4c02528e178f0c7824a3836fa87aa90e35bf47cdd3b`, built + under `tools/guard.sh -m 8 -t 1800`, paired against **the shipped §P4b2 + release** `7522696e894a94d8d431f148d4e08e6a9ab7727eb0aaac36f8daa57a684b9076`, + copied into the session scratchpad before the rebuild and re-run in this + window. **An earlier release of this lane** + (`b8edb28ab949778793453acb9a5b292c4b0e256de1d2319bbb8ee4bdebcff364`) was + measured first and its rows are kept **unquoted** at + `~/.cache/lucisv-perf/take5-p4b3/results-preliminary-clone.jsonl`: it had the + same behaviour and cloned every file's include list at the end of the scan, + which the final binary borrows instead. The first, *pre-drain-rule* release + (`b50ea341d274…`) is the one that found the defect below and its rows are in + the same file. No `cargo` command ran during any timed phase. +- **Corpus:** opentitan `00981352642fb65ef2b6c47143a0f6bb31fd4a97`, with its + three pre-existing modified files. `git -C … status --porcelain` checked + after every phase of both binaries: three, always, never anything else. +- **Method:** seven phases — `scan`, `scanprofile`, `scanwait`, `scanserve`, + `didopen`, `rss`, `scopes` — each run **alternating P4b2 then P4b3** so the + two meet the same weather, three fresh sessions per cell, scratch + `storagePath` per label, every session under `tools/guard.sh -m 8 -t 1800`. + One-minute load recorded before and after each phase: **2.8–7.5** across the + matrix. Zero guard kills. +- **Result — the headline.** The first useful answer of a warm workspace + session is **result count 1 in twelve sessions of twelve** (six in `scan`, + six in `scanwait`), where §P4b2 was **0 in twelve of twelve**, and it is + faster: `scan` cold 287.40 → **249.00 ms (−13.4 %)**, warm 332.68 → + **277.37 (−16.6 %)**; `scanwait` cold 277.27 → **247.66 (−10.7 %)**, warm + 319.12 → **274.17 (−14.1 %)**. +- **Result — memory.** `work_kib`, the source text a scan holds for its whole + life, **34 973 → 0–16**. Idle RSS max **530.30 → 493.36 MiB cold (−7.0 %)** + and **455.33 → 422.59 MiB warm (−7.2 %)**; peak equals idle to the KiB in all + twelve sessions of both binaries. +- **Result — stages.** Warm, traced: `discovery` **227.02 → 158.32 ms** (the + walk and the cap's `metadata`, with the read taken out), a new `read` stage + at **85.54**, `includes` **42.12 → 8.60** (the line scan moved to the step + that read the file, over hot bytes; the graph at the end only resolves), + `cache_open` 87.67 → 89.24, `first_publish` **316.74 → 249.70** carrying + **125 files instead of 1**. +- **Result — everything that had to not move.** Settled unchanged within the + window's noise: `scan` −5.2 % cold / −3.0 % warm, `scanprofile` +0.9 % / + +1.9 %; both quoted. All **24** scope result counts identical. The persistent + store written by either binary is sha256 `e49bc5c176ea…`, 46 486 433 bytes, + `store_kib` 45 404 — **byte-identical**, which is the strongest available + proof that a lazy scan indexes what an eager one indexed, over 3 976 real + files. `mismatched_answers` **0** in all four `scanserve` rows of both + binaries. `didOpen` (§46) medians 123.52 → 127.72 (pinmux), 14.37 → 15.05 + (spi_device), 9.80 → 12.05 (aes_core), 4.47 → 5.47 (aes) — every row inside + its own spread, and the path is not reachable from this change because + `didopen` settles the scan before it opens the buffer. +- **Defect found by measuring, before it shipped.** The first paired run had + the ordering and the drain rule and still answered `[]` in **five sessions of + six**. The client answers `workspace/configuration` from its own reader + thread and usually beats the editor's `didOpen`, so the scan begins with no + buffer open, its work list is the plain alphabet, and at workspace scope a + `didOpen` widens nothing — so nothing held the definition behind it. The + shipped rule holds a burst's requests behind its `didOpen` and re-orders the + rest of the work list around the buffers open now. Rows kept, unquoted, in + `results-preliminary-clone.jsonl`. +- **Targets:** the quality target (result count 1 in 6 of 6) **met, at 12 of + 12**; the latency target (≤ the §P0 REF's 84 cold / 208 warm) **missed** at + 249 / 274 ms, and the reason is measured rather than guessed — the answer is + walk + folder as the work order asked, and warm the walk alone is 158 ms with + `cache_open` another 89 in front of the folder. The REF answered off a + 124-file **folder** scan that never walked the workspace, so ordering cannot + reach it. **Filed for the next lane**: `discovery` is 58 % of the warm first + answer and is now pure walk; two things to measure before building anything + are the cap taking its size from the walk's own metadata + (`lucisv_core::walk::collect_files` — a handshake request, not this lane's + file) and handing the first folder to `scan_step` before the walk has + finished the workspace. +- **Raw rows:** `~/.cache/lucisv-perf/take5-p4b3/results.jsonl`, labels `P4b2` + and `P4b3`; the two unquoted preliminary sets beside it. + ## Experiment record — copy for every stage or rejected attempt - Experiment ID / stage / date / owner: diff --git a/docs/topo.md b/docs/topo.md index d77a246..8374d64 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -555,7 +555,7 @@ promise: | `dut-hierarchy ──▶ vscode-hierarchy-sidebar` | depends | TODO §56 (2026-09-06): `hierarchySections.js` consumes the sidebar's model (`rootNode`, the reverse instance index memoised on the model) and its webview renderer's row menu; no edge to any Rust crate — the server is untouched. | | `coverage-gaps-l` (TODO §54, 0.49.0) | lane | Touches `vlog_parser` (ast + parser + the `randsequence` keyword in the token table), `vlog_formatter` (arms, `[format] uvm-utils-indent`), `vlog_semantic` (bind arms), `vlog_linter`, `vlog_refactor` (match arms), `lucisv_core` (the config key), `lucisv_server` (settings, format) and `editors/vscode` (the setting, the regenerated grammar). New AST: `StmtKind::{EventTrigger, Let, RandSequence}`, `ExprKind::StreamWith`, `DataDecl::strength`, `ClockingSkew`; `size_pins` unmoved. | | `hover-line-index ──▶ port-detail-spans / index-persistence` | depends + handshake | `DeclLines { name, detail }` rides each indexed `Decl`, so ordinary and split-port hover headings do not reread a file just to compute a line. The record grew again and **`FACTS_FORMAT` went 3 → 4**; the server's bounded `FileView` cache supplies the text/`LineIndex` only when a snippet or a non-indexed position still needs it. Its four invalidation points are `set_document`, `close_document`, `update_one`, and a whole rebuild. | -| `scan-interleave ◀──▶ workspace-index` | handshake | A scan is a stepped `Scan` value; staged `FileFacts` land through `WorkspaceIndex::absorb`, one whole-index merge per queue drain rather than per file. `Candidates::absorb` and `IncludeGraph::absorb` publish their tables in the same drain, so “the workspace as far as scanned” cannot mean three different prefixes. | +| `scan-interleave ◀──▶ workspace-index` | handshake | A scan is a stepped `Scan` value; staged `FileFacts` land through `WorkspaceIndex::absorb`, one whole-index merge per queue drain rather than per file. `Candidates::absorb` and (until perf5-p4, `IncludeGraph::absorb`; since 2026-09-08 the graph is rebuilt from each file's staged include list, `IncludeGraph::from_includes`, read in the file's own step) publish their tables in the same drain, so “the workspace as far as scanned” cannot mean three different prefixes. **Amended by perf5-p4 (2026-09-08):** the startup is staged behind the `workspace/configuration` answer with a 2 s bound (`server/startup.rs`), so there is one startup scan at the answered scope and no empty default-scope scan; the scan reads each file's text in its own step (`Scan::take_text`, never the whole corpus up front) and orders the work list open buffers → their raised folders → the rest (`scan_order.rs`); `must_wait` gains `staging` and `head_owed` — a held opening request is answered inside the startup scan once the buffers' folder head is published, never off a one-file prefix; the store is opened at the first step that needs it and not rewritten when it was loaded canonical and nothing was appended (`index_cache.rs::already_compact`); `state.rs` is now `state/mod.rs` + `state/scan.rs` (a pure move). The rescan order contract (decision 2) is unchanged. | | `scan-interleave ──▶ hover-line-index` | depends | Delivers hover-line-index's measured startup-wait request: a startup scan above 64 files drains queued messages between files. A rescan deliberately still holds requests; what an answer sees never depends on elapsed wall time. | | `index-scope ──▶ scan-interleave` | depends | A scope widen is the second `Scan` shape (`begin_widen`) and shares `scan_step`/`finish_scan`; it folds only newly reached folders plus open-buffer analyses, never masquerades as a whole scan, and never interleaves. Folder scope now ships at depth 2; rootless sessions do not climb an unnamed tree. | | `index-scope ──▶ one-parse / completion-core` | depends | Whole scans and widens reuse each open `Document`'s existing `FileFacts` and completion words rather than reparse its text. `IndexEvent::Analyzed` keeps this distinct from a persistent-cache hit. | @@ -716,7 +716,7 @@ untouched, reusing existing arms. | `vlog_refactor` | refactor (plan), refactor-rename (including `prepare_rename_here` / `rename_name_at` selector half), refactor-ports (including module-target selectors), refactor-instantiate, references-nav (whole-scope equivalence oracle), and the refactor half of decomposition-semantic; expand-wildcard and convert-to-ansi (`ports/`), organize-imports (`imports.rs`), extract-inline-module (`extract/`, `inline/`, `check/ledger.rs`) | | `lucisv_core` | lucisv-core-lift (`config.rs`, `walk.rs`), filelist (`filelist.rs`), format-cache (`cache.rs`) | | `lucisv` (CLI) | cli-polish, config-discovery (wiring), parallel-files, cli-filelist, linter-core (CLI half in `lint.rs`), one-parse (`lint.rs` parses once via `ParsedSource`), format-cache (wiring), release-prep (`--version` contract) | -| `lucisv_server` | lucisv-server (trunk), decomposition-server (`server/`, `completion/`), and one or two modules per capability feature: editor-scopes→`pairs.rs`, filelist→scope ladder in `state.rs`, include-nav→`includes.rs`, completion-core/fuzzy-completion/member-completion→`completion/`+`candidates.rs`, completion-templates→`templates.rs`, inline-templates→`inline.rs`, inline-instantiation→`inline.rs`+`completion/`+`candidates.rs` (+`settings.rs` key), bind-semantics→`instantiate.rs`, macro-expansion→`expand.rs`, hierarchy→`hierarchy.rs`, vscode-hierarchy-sidebar→`design_hierarchy.rs`, type-hierarchy→`type_hierarchy.rs`, type-definition→`type_def.rs`, code-lens→`lens.rs`, inlay-hints→`inlay.rs`, server-lint→`lint.rs`+`lint/project.rs`+`code_action.rs`, one-parse→`lint.rs`+`state.rs` (`Document.tree`), refactor wiring/performance fan-outs→`rename.rs`/`ports.rs`+`state.rs`, apply-edit+folders-and-config+cancel-request+work-done-progress→`server/`, editor-settings+indexing-ux+index-scope+index-persistence→`settings.rs`+`state.rs`(+`index_cache.rs`), incremental-sync→`sync.rs`, file-watching→`watch.rs`, file-operations→`file_ops.rs` (+`include_sources` in `state.rs`), pull-diagnostics→`diagnostics.rs`+`server/`, semantic-tokens-delta→`tokens.rs`+`server/semantic_tokens.rs`, on-type-formatting→`on_type.rs`, will-save-wait-until→`format.rs` (+`settings.rs`/`main.rs`), selection-range→`selection.rs`, linked-editing→`linked.rs`, references-nav (server half)→`folding.rs`+`nav.rs`, large-file-mode→`large.rs`+`server/large_file.rs`, lsp-318-extras→`format.rs` (+`main.rs` capability), hover-declarations→`hover.rs`(+`nav.rs`), port-detail-spans (server half)→`hover.rs`+`nav.rs`, hover-line-index→`hover.rs`+`locate.rs`+`state.rs`, scan-interleave/change-debounce/verbose-timing→`server/`+`state.rs`, perf5-p1→`fences.rs` (+ the `_at` helpers in `ports.rs`/`imports.rs`/`extract.rs`/`inline_module.rs`), perf5-p2→`rename_trace.rs`+`module_select.rs`, perf5-p4→`scan_trace.rs` (+ counters in `index_cache.rs`), perf measurements→`src/perf.rs` (`docs/perf/README.md`, not a feature README), interactive-latency→`state.rs` (the two token searches) + `selection.rs`/`on_type.rs`/`completion/`/`inline.rs` (their callers) + `src/perf.rs`/`tests/e2e.rs` (its measurements), editor-packaging (grammar test)→`tests/grammar.rs` | +| `lucisv_server` | lucisv-server (trunk), decomposition-server (`server/`, `completion/`), and one or two modules per capability feature: editor-scopes→`pairs.rs`, filelist→scope ladder in `state.rs`, include-nav→`includes.rs`, completion-core/fuzzy-completion/member-completion→`completion/`+`candidates.rs`, completion-templates→`templates.rs`, inline-templates→`inline.rs`, inline-instantiation→`inline.rs`+`completion/`+`candidates.rs` (+`settings.rs` key), bind-semantics→`instantiate.rs`, macro-expansion→`expand.rs`, hierarchy→`hierarchy.rs`, vscode-hierarchy-sidebar→`design_hierarchy.rs`, type-hierarchy→`type_hierarchy.rs`, type-definition→`type_def.rs`, code-lens→`lens.rs`, inlay-hints→`inlay.rs`, server-lint→`lint.rs`+`lint/project.rs`+`code_action.rs`, one-parse→`lint.rs`+`state.rs` (`Document.tree`), refactor wiring/performance fan-outs→`rename.rs`/`ports.rs`+`state.rs`, apply-edit+folders-and-config+cancel-request+work-done-progress→`server/`, editor-settings+indexing-ux+index-scope+index-persistence→`settings.rs`+`state.rs`(+`index_cache.rs`), incremental-sync→`sync.rs`, file-watching→`watch.rs`, file-operations→`file_ops.rs` (+`include_sources` in `state.rs`), pull-diagnostics→`diagnostics.rs`+`server/`, semantic-tokens-delta→`tokens.rs`+`server/semantic_tokens.rs`, on-type-formatting→`on_type.rs`, will-save-wait-until→`format.rs` (+`settings.rs`/`main.rs`), selection-range→`selection.rs`, linked-editing→`linked.rs`, references-nav (server half)→`folding.rs`+`nav.rs`, large-file-mode→`large.rs`+`server/large_file.rs`, lsp-318-extras→`format.rs` (+`main.rs` capability), hover-declarations→`hover.rs`(+`nav.rs`), port-detail-spans (server half)→`hover.rs`+`nav.rs`, hover-line-index→`hover.rs`+`locate.rs`+`state.rs`, scan-interleave/change-debounce/verbose-timing→`server/`+`state.rs`, perf5-p1→`fences.rs` (+ the `_at` helpers in `ports.rs`/`imports.rs`/`extract.rs`/`inline_module.rs`), perf5-p2→`rename_trace.rs`+`module_select.rs`, perf5-p4→`scan_trace.rs`+`scan_order.rs`+`server/startup.rs`+`state/scan.rs` (+ counters and the compaction skip in `index_cache.rs`), perf measurements→`src/perf.rs` (`docs/perf/README.md`, not a feature README), interactive-latency→`state.rs` (the two token searches) + `selection.rs`/`on_type.rs`/`completion/`/`inline.rs` (their callers) + `src/perf.rs`/`tests/e2e.rs` (its measurements), editor-packaging (grammar test)→`tests/grammar.rs` | | `editors/vscode` | editor-packaging, editor-snippets, editor-settings (manifest half), editor-scopes (rainbow half), vscode-hierarchy-sidebar (`hierarchyView.js`/`hierarchyModel.js`), dut-hierarchy (`hierarchySections.js`), extract-inline-module (`extract.js`), editor-platform-vsix, editor-marketplace-page, index-persistence (`storagePath` line), verbose-timing (`lucisv.verbose`, spawn args and restart in `extension.js`) | | `tools/` + CI | corpus-check, release-prep, ci-release, editor-platform-vsix (staging), range-formatting (`lucisv-changed.sh`) |