Perf take 5 P4b (§60.4): the startup staged behind the configuration answer (one scan at the answered scope, 2 s bound), the store not rewritten when unchanged and opened at the first step that needs it, the corpus read a file at a time in its own step, open buffers' folders at the head of the work list and a held opening request answered once that head is published; warm start 1.33 → ~1.05 s, warm idle RSS −15 to −20 %, store byte-identical across sessions, first useful answer correct in every session; state.rs split into state/ (pure move)

This commit is contained in:
lucio committed 2026-09-08 04:36:11 -05:00
1 parent 243472901d
commit 32204eba71
26 files changed
+5158 -571

No files matched your search

+127 -2
View File
@@ -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
+32 -6
View File
@@ -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<PathBuf, Vec<String>>,
) -> 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<PathBuf, Vec<String>>) -> 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();
+48 -10
View File
@@ -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<PathBuf>) -> IncludeGraph {
let scanned: Vec<(PathBuf, Vec<Include>)> =
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<PathBuf>) -> 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<PathBuf> = sources.iter().map(|(path, _)| path.clone()).collect();
let paths: Vec<PathBuf> = 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<PathBuf> =
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),
+352 -8
View File
@@ -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<PathBuf>) -> 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<PathBuf> = 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<u8>, 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<String> {
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<String> = 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,
+1
View File
@@ -41,6 +41,7 @@ mod perf;
mod ports;
mod rename;
mod rename_trace;
mod scan_order;
mod scan_trace;
mod selection;
mod server;
+193
View File
@@ -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<PathBuf>,
/// 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<PathBuf>, 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<PathBuf> {
names.iter().map(PathBuf::from).collect()
}
fn names(list: &WorkList) -> Vec<String> {
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);
}
}
+169 -7
View File
@@ -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<u64> = 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<Instant>) {
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<Instant> {
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),
)
}
}
+4 -3
View File
@@ -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
));
}
}
+73 -12
View File
@@ -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<std::path::PathBuf>) {
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<lsp_server::Message> {
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);
+51 -136
View File
@@ -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<std::path::PathBuf>,
abilities: ClientAbilities,
storage: Option<std::path::PathBuf>,
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<std::path::PathBuf>,
abilities: ClientAbilities,
client: ClientSettings,
storage: Option<std::path::PathBuf>,
verbose: bool,
queued: Vec<Message>,
) -> 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
+310
View File
@@ -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<std::path::PathBuf>,
/// `--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<Message>,
/// 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<std::path::PathBuf>,
abilities: ClientAbilities,
storage: Option<std::path::PathBuf>,
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<Message>,
) -> 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<std::path::PathBuf>,
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);
}
}
}
+69 -12
View File
@@ -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<PathBuf>,
abilities: ClientAbilities,
verbose: bool,
wait: Duration,
queued: Vec<Message>,
) -> 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 }
}
@@ -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<usize>, Option<usize>) {
pub(super) fn positions(messages: &[Message], id: i32) -> (Option<usize>, Option<usize>) {
let ended = messages.iter().position(|message| {
matches!(message, Message::Notification(n) if n.method == Progress::METHOD
&& n.params["value"]["kind"] == "end")
@@ -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<String> {
pub(super) fn scan_lines(session: &Session) -> Vec<String> {
session
.logged()
.into_iter()
@@ -28,13 +28,13 @@ fn scan_lines(session: &Session) -> Vec<String> {
/// Whether a log line is one of a scan's three trace lines — `timing: scan
/// <number> …` — 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::<u32>().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<PathBuf>, storage: Option<PathBuf>) -> 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);
}
@@ -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:#?}"
);
}
@@ -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<String> {
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<String> {
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<String> {
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<String> = 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");
}
File diff suppressed because it is too large. Load diff
+297
View File
@@ -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<PathBuf>,
/// The text of each open buffer among `files`, as it was when the scope
/// was resolved.
pub(super) buffered: HashMap<PathBuf, String>,
/// What the open buffers among `files` already know about themselves.
pub(super) analyzed: Analyzed,
pub(super) incdirs: Vec<PathBuf>,
pub(super) warnings: Vec<String>,
}
/// 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<PathBuf, FileFacts>,
pub(super) words: HashMap<PathBuf, Vec<String>>,
}
/// 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<PathBuf>,
/// 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<PathBuf, String>,
/// 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<PathBuf, Vec<Include>>,
/// 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<PathBuf>,
/// 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<PathBuf>,
/// 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<PathBuf>,
/// 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<PathBuf>,
pub(super) warnings: Vec<String>,
/// 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<FileFacts>,
pub(super) staged_at: Vec<usize>,
/// The completion words of every file taken so far, which the tables built
/// when the scan ends are assembled from.
pub(super) words: HashMap<PathBuf, Vec<String>>,
/// 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<String> {
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<PathBuf> {
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<PathBuf, Vec<Include>>,
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 },
}
@@ -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
+122 -2
View File
@@ -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<PathBuf>)`, 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)
+89
View File
@@ -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
+15
View File
@@ -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`
File diff suppressed because it is too large. Load diff
+103 -1
View File
@@ -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<PathBuf>; // 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
+354 -15
View File
@@ -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 <n> …` 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:
+2 -2
View File
@@ -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`) |