Perf take 5 P4a (§60.4): startup and memory instrumented on the --verbose channel (scan_trace, cache counters, table sizes; scanprofile/scanserve phases) — a session runs an empty scan before configuration that still opens and rewrites the 45 MB store (184 ms of a 1.33 s warm start), warm has no dominant stage and 27 % is store I/O, cold is 59 % parse; P4b ruled
ci / checks (push) Successful in 1m7s
ci / corpus (push) Successful in 35s

This commit is contained in:
lucio committed 2026-09-08 00:05:43 -05:00
1 parent 8e65da1ba8
commit 4621214a51
21 files changed
+2095 -47

No files matched your search

+28 -3
View File
@@ -6004,14 +6004,39 @@ first useful answer; 1/10/100 open buffers; requests during a scan)
then §P4b (the dominant measured stage only). Files: `server/index.rs`,
`state.rs`, `index_cache.rs`, `candidates.rs`, `includes.rs` and the
semantic build/facts owners. Serialized after 60.1–60.3.
- [ ] P4a instrumentation and the measured breakdown in the tracker
- [ ] lead ruling: which stage, or none
- [x] P4a instrumentation and the measured breakdown in the tracker
(2026-09-07; `docs/features/perf5-p4/README.md`, experiment
`P4a-2026-09-07`). Three `timing: scan <n> …` lines per scan on
the `--verbose` channel; `tools/perf/phases_p4.py` reads them.
**A workspace session pays three scans and the first indexes
zero files** — warm it still costs 183.7 ms opening and
compacting a 44.3 MiB store it never uses, which is also the
whole of §P0's cold-84 / warm-209 first-answer puzzle. Warm
settle 1 332.7 ms has no dominant stage but 27.5 % of it is the
store's own I/O; cold settle 2 893.6 ms is 58.9 % parse. The
encoded-facts retention §P4 hypothesised is real: 44.20 MiB,
7.7 % of warm idle RSS. Requests queued behind the configured
rescan wait 2.56 s cold / 0.90 s warm, with zero mismatched
tables in 18 mid-scan answers
- [x] lead ruling: which stage, or none — **2026-09-08: go** on (a) skip
`compact` when the store is unchanged and was loaded canonical,
(b1) no store open/compact for an empty work list (open deferred to
the first file); **refused** (b2) store reuse across rescans (the
reopen guards a mid-session cache-path change and a second session's
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
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
- [ ] QA
- [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)
### 60.5 Closing
+11
View File
@@ -293,6 +293,17 @@ impl Candidates {
self.remask_words();
}
/// How many entries each completion table holds, and what the word table
/// weighs — the startup memory question, asked of the one table that
/// grows with the corpus rather than with its declarations.
///
/// A walk, so it is asked once at the end of a traced scan and never on a
/// request path (`docs/features/perf5-p4/README.md`).
pub fn sizes(&self) -> (usize, usize, usize, usize) {
let word_bytes: usize = self.words.iter().map(String::len).sum();
(self.units.len(), self.macros.len(), self.words.len(), word_bytes)
}
/// Index names starting with `prefix`, case-insensitively.
pub fn units(&self, prefix: &str) -> &[Candidate] {
matching(&self.units, prefix, |c| &c.name)
+6
View File
@@ -230,6 +230,12 @@ impl IncludeGraph {
}
}
/// How many resolved edges the graph holds and how many files it knows —
/// the two numbers that say what a rebuilt graph weighs.
pub fn sizes(&self) -> (usize, usize) {
(self.edges.values().map(Vec::len).sum(), self.known.len())
}
/// The `+incdir+` directories an include is looked for in, in filelist
/// order — the search rungs past the including file's own directory.
pub fn incdirs(&self) -> &[PathBuf] {
+81 -4
View File
@@ -24,14 +24,17 @@
//! `docs/features/index-persistence/README.md` and is the same one
//! `lucisv_core::cache` accepts.
use std::cell::Cell;
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Instant;
use lucisv_core::cache::content_hash;
use vlog_semantic::{record_path, FileFacts, FACTS_FORMAT};
use crate::scan_trace::CacheWork;
use crate::settings::ClientSettings;
/// The store inside the cache directory.
@@ -75,6 +78,15 @@ 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 this cache's own work has cost since it was opened, for the
/// startup breakdown (`docs/features/perf5-p4/README.md`).
///
/// A `Cell` because [`IndexCache::facts_for`] is a `&self` read and the
/// hash/decode split is exactly the number §P4a needed. Counted whether
/// anything is going to read it or not: four clock reads per file are
/// noise beside the decode they bracket, and a flag threaded down here to
/// save them would cost more code than time.
work: Cell<CacheWork>,
}
impl IndexCache {
@@ -113,7 +125,24 @@ impl IndexCache {
}
}
}
IndexCache { dir: Some(dir), entries, log: None, header_ok }
IndexCache { dir: Some(dir), entries, log: None, header_ok, work: Cell::default() }
}
/// What this cache has spent and moved since it was opened.
pub fn work(&self) -> CacheWork {
self.work.get()
}
/// How many records this cache is holding.
pub fn entry_count(&self) -> usize {
self.entries.len()
}
/// The encoded bytes those records weigh — the retention §P4's memory
/// hypothesis is about, since every one of them sits beside a decoded
/// copy in the workspace index.
pub fn encoded_bytes(&self) -> usize {
self.entries.values().map(|entry| entry.facts.len()).sum()
}
/// Where this cache writes. Test-only: production opens a cache from a
@@ -133,11 +162,28 @@ impl IndexCache {
/// they were written with, which [`IndexCache::open`] drops before it ever
/// gets here.
pub fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
let entry = self.entries.get(path)?;
if entry.content != content_hash(text.as_bytes()) {
let looking = Instant::now();
let found =
self.entries.get(path).filter(|entry| entry.content == content_hash(text.as_bytes()));
let mut work = self.work.get();
work.lookup_ns += elapsed_ns(looking);
let Some(entry) = found else {
work.misses += 1;
self.work.set(work);
return None;
};
let decoding = Instant::now();
let facts = FileFacts::decode(&entry.facts);
work.decode_ns += elapsed_ns(decoding);
work.decoded_bytes += entry.facts.len();
// A record that no longer decodes costs a parse, so it is a miss —
// the counters say what the scan actually did, not what it looked up.
match facts.is_some() {
true => work.hits += 1,
false => work.misses += 1,
}
FileFacts::decode(&entry.facts)
self.work.set(work);
facts
}
/// Record what parsing `text` found, and write it through immediately.
@@ -153,9 +199,17 @@ impl IndexCache {
if self.dir.is_none() {
return;
}
let encoding = Instant::now();
let Some(encoded) = facts.encode() else { return };
let content = content_hash(text.as_bytes());
let mut work = self.work.get();
work.encode_ns += elapsed_ns(encoding);
let writing = Instant::now();
self.append(&line(content, &encoded));
work.write_ns += elapsed_ns(writing);
work.records += 1;
work.written_bytes += encoded.len();
self.work.set(work);
self.entries.insert(facts.path().to_path_buf(), Entry { content, facts: encoded });
}
@@ -172,6 +226,24 @@ impl IndexCache {
/// failure anywhere leaves the previous store standing. A cache that could
/// fail a rescan would be worse than no cache.
pub fn compact(&mut self) {
let before = self.store_bytes();
let compacting = Instant::now();
self.compact_now();
let mut work = self.work.get();
work.compact_ns += elapsed_ns(compacting);
work.store_before = before;
work.store_after = self.store_bytes();
self.work.set(work);
}
/// 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 };
std::fs::metadata(dir.join(FILE)).map(|meta| meta.len()).unwrap_or_default()
}
/// [`IndexCache::compact`] without the accounting around it.
fn compact_now(&mut self) {
let Some(dir) = self.dir.clone() else { return };
// The append handle must go before the rename, or a later append would
// write into the file the rename replaced.
@@ -342,6 +414,11 @@ fn line(content: u64, facts: &str) -> String {
/// `None` for anything that is not a whole record whose facts still match
/// their checksum, which includes the torn last line of a store whose writer
/// was killed.
/// Nanoseconds since `from`, saturated into the counters' `u64`.
fn elapsed_ns(from: Instant) -> u64 {
from.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64
}
fn parse_entry(line: &str) -> Option<(PathBuf, Entry)> {
let (hash, rest) = line.split_once('\t')?;
// Exactly as wide as `line` writes it: a hash that reads as a number but
+1
View File
@@ -41,6 +41,7 @@ mod perf;
mod ports;
mod rename;
mod rename_trace;
mod scan_trace;
mod selection;
mod server;
mod settings;
+3 -3
View File
@@ -401,7 +401,7 @@ fn what_a_scan_does_before_its_first_file() {
});
workspace.adopt_roots(vec![dir.clone()]);
let started = Instant::now();
let mut scan = workspace.begin_scan(&mut |_| {});
let mut scan = workspace.begin_scan(&mut |_| {}, false);
let head = started.elapsed();
let started = Instant::now();
workspace.scan_step(&mut scan, &mut |_| {});
@@ -556,7 +556,7 @@ fn what_a_jump_into_a_new_folder_costs_before_and_after() {
let added: Vec<PathBuf> =
incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect();
let started = Instant::now();
let mut scan = incremental.begin_widen(&added, &mut |_| {});
let mut scan = incremental.begin_widen(&added, &mut |_| {}, false);
while incremental.scan_step(&mut scan, &mut |_| {}) {}
black_box(incremental.finish_scan(scan));
let widen = started.elapsed();
@@ -646,7 +646,7 @@ fn what_a_widen_that_subsumes_the_old_scope_costs() {
incremental.scope_dirs().into_iter().filter(|d| !before.contains(d)).collect();
let mut read = 0usize;
let started = Instant::now();
let mut scan = incremental.begin_widen(&added, &mut |_| {});
let mut scan = incremental.begin_widen(&added, &mut |_| {}, false);
while incremental.scan_step(&mut scan, &mut |_| read += 1) {}
// Split out because it is where the 2026-08-29 round's fix landed: folding
// a widen's words into the completion table used to move the table's tail
+381
View File
@@ -0,0 +1,381 @@
//! What one workspace scan spent its time on, and what the tables it left
//! behind weigh — the startup breakdown take 5 §P4a exists to measure.
//!
//! A [`ScanTrace`] rides on the [`crate::state::Scan`] it describes. It is a
//! bag of sums and counters and nothing else: no per-file allocation, no
//! per-file string, no `Vec` that grows with the work list, so a traced scan
//! costs a handful of clock reads per file and two `format!`s at the end. It
//! is off unless `--verbose` asked for it ([`ScanTrace::new`]), and off means
//! [`ScanTrace::now`] hands back `None` and every `add` below is a branch.
//!
//! The three lines it renders go out on the `timing:` channel
//! (`docs/features/verbose-timing/README.md`) when the scan ends. They are
//! `key=value` after a human prefix because both readers matter: a person
//! grepping an output channel, and `tools/perf/phases_p4.py`, which turns
//! them into schema-2 rows.
use std::time::Instant;
/// What the persistent store's own work cost, counted inside
/// [`crate::index_cache::IndexCache`] because that is where it happens.
///
/// Always counted, trace or no trace: the four clock reads a file costs here
/// are noise beside the read and the decode they bracket, and a flag threaded
/// through the cache to save them would be more code than it saves time.
#[derive(Clone, Copy, Default)]
pub struct CacheWork {
/// Hashing the text and finding the entry — what every lookup pays,
/// whether it hits or misses.
pub lookup_ns: u64,
/// Decoding the record of a lookup that hit.
pub decode_ns: u64,
/// Encoding a record on the way out.
pub encode_ns: u64,
/// Appending an encoded record to the log.
pub write_ns: u64,
/// Rewriting the whole store at the end of a whole scan.
pub compact_ns: u64,
/// Lookups that found a record for exactly these bytes.
pub hits: usize,
/// Lookups that did not, and so cost a parse.
pub misses: usize,
/// Records written through.
pub records: usize,
/// Encoded bytes handed to `FileFacts::decode`.
pub decoded_bytes: usize,
/// Encoded bytes appended to the log.
pub written_bytes: usize,
/// The store file's size before and after a compaction, in bytes.
pub store_before: u64,
pub store_after: u64,
}
impl CacheWork {
/// This session's counters minus the ones a scan started with, so a scan
/// reports its own work rather than the process's.
pub fn since(self, before: CacheWork) -> CacheWork {
CacheWork {
lookup_ns: self.lookup_ns.saturating_sub(before.lookup_ns),
decode_ns: self.decode_ns.saturating_sub(before.decode_ns),
encode_ns: self.encode_ns.saturating_sub(before.encode_ns),
write_ns: self.write_ns.saturating_sub(before.write_ns),
compact_ns: self.compact_ns.saturating_sub(before.compact_ns),
hits: self.hits.saturating_sub(before.hits),
misses: self.misses.saturating_sub(before.misses),
records: self.records.saturating_sub(before.records),
decoded_bytes: self.decoded_bytes.saturating_sub(before.decoded_bytes),
written_bytes: self.written_bytes.saturating_sub(before.written_bytes),
store_before: self.store_before,
store_after: self.store_after,
}
}
}
/// How big the tables a finished scan leaves behind are — the memory half of
/// §P4a, in counts and bytes rather than in a resident-set reading.
#[derive(Clone, Copy, Default)]
pub struct TableSizes {
pub index_files: usize,
pub unit_names: usize,
pub unit_defs: usize,
pub members: usize,
pub hier_members: usize,
pub reference_keys: usize,
pub reference_sites: usize,
pub defines: usize,
pub instantiations: usize,
pub fact_words: usize,
pub fact_word_bytes: usize,
pub candidate_units: usize,
pub candidate_macros: usize,
pub candidate_words: usize,
pub candidate_word_bytes: usize,
pub include_edges: usize,
pub include_known: usize,
}
/// One scan's stage times, counts and end-state sizes.
///
/// Every `*_ms` is a sum over however many times that stage ran: `parse_ms`
/// is every parse of the scan added up, `absorb_ms` is the one final absorb,
/// `publish_absorb_ms` is the mid-scan ones.
#[derive(Default)]
pub struct ScanTrace {
on: bool,
/// When the scan began — the first thing [`crate::state::Workspace::begin_scan`] does.
started: Option<Instant>,
/// How long the server had been alive when this scan began.
pub since_start_ms: f64,
/// Whether this scan rebuilds the whole index or folds a widen in.
pub kind: &'static str,
/// Which scan of the session this is, counting from 1.
pub number: u32,
// -- discovery ------------------------------------------------------
/// Resolving the scope, walking it and reading every file's text.
pub discovery_ms: f64,
/// Sorting into index order and moving the open buffers to the front.
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.
pub read: usize,
pub read_bytes: usize,
/// Files the size cap kept out.
pub skipped: usize,
/// Entries the store held when it was opened, and their encoded bytes.
pub cache_entries: usize,
pub cache_bytes: usize,
// -- per file -------------------------------------------------------
/// Parsing a file the store could not answer for, and its bytes.
pub parse_ms: f64,
pub parse_bytes: usize,
/// Files indexed from an open buffer's own finished analysis. Untimed:
/// there is nothing to time — the facts are already in hand, and what
/// that file then costs is the record the store writes through, which is
/// counted with every other record below.
pub buffers: usize,
/// The store's own work over this scan.
pub cache: CacheWork,
// -- mid-scan publishes ---------------------------------------------
pub publishes: usize,
pub published: usize,
pub publish_absorb_ms: f64,
pub publish_candidates_ms: f64,
pub publish_includes_ms: f64,
pub publish_overlay_ms: f64,
/// When the first publish landed, measured from the start of the scan —
/// the earliest moment a request answered mid-scan can see any of it.
pub first_publish_ms: f64,
// -- the end --------------------------------------------------------
/// Working out which files left the scope.
pub gone_ms: f64,
pub absorb_ms: f64,
pub candidates_ms: f64,
pub includes_ms: f64,
/// Re-resolving every open buffer against the finished index.
pub overlay_ms: f64,
pub overlays: usize,
/// The whole scan, `begin_scan` to the end of `finish_scan`.
pub total_ms: f64,
pub sizes: TableSizes,
}
impl ScanTrace {
/// A trace that records, or one that does nothing at all.
pub fn new(on: bool) -> ScanTrace {
ScanTrace { on, started: on.then(Instant::now), ..ScanTrace::default() }
}
/// Whether anything below will be recorded.
pub fn on(&self) -> bool {
self.on
}
/// The clock a stage is timed from — `None`, and so free, when off.
pub fn now(&self) -> Option<Instant> {
self.on.then(Instant::now)
}
/// Add the time since `from` to `slot`. Nothing at all when off, because
/// `now` handed out no clock to be since.
pub fn add(slot: &mut f64, from: Option<Instant>) {
if let Some(from) = from {
*slot += millis(from);
}
}
/// How long this scan has been running, or 0 when it is not being traced.
pub fn elapsed_ms(&self) -> f64 {
self.started.map(millis).unwrap_or_default()
}
/// Stamp the first publish, if this is the first one.
pub fn saw_publish(&mut self, files: usize) {
self.publishes += 1;
self.published += files;
if self.publishes == 1 {
self.first_publish_ms = self.elapsed_ms();
}
}
/// The stage line: every `*_ms` this scan collected, in the order the
/// scan spends them.
pub fn stage_line(&self) -> String {
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} \
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",
self.number,
self.kind,
self.read,
self.discovery_ms,
self.order_ms,
self.cache_open_ms,
nanos(c.lookup_ns),
nanos(c.decode_ns),
self.parse_ms,
nanos(c.encode_ns),
nanos(c.write_ns),
self.publish_absorb_ms,
self.publish_candidates_ms,
self.publish_includes_ms,
self.publish_overlay_ms,
self.gone_ms,
self.absorb_ms,
nanos(c.compact_ns),
self.candidates_ms,
self.includes_ms,
self.overlay_ms,
self.total_ms,
self.since_start_ms,
)
}
/// The count line: how much work of each kind there was to spend that
/// time on.
pub fn count_line(&self) -> String {
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={}",
self.number,
self.kind,
self.read,
kib(self.read_bytes),
self.skipped,
c.hits,
c.misses,
self.buffers,
c.records,
kib(c.decoded_bytes),
kib(c.written_bytes),
self.publishes,
self.published,
self.first_publish_ms,
self.overlays,
)
}
/// The memory line: what the scan left resident, table by table.
pub fn memory_line(&self) -> String {
let s = &self.sizes;
format!(
"scan {} memory ({}): store_before_kib={} store_after_kib={} cache_entries={} \
cache_encoded_kib={} index_files={} unit_names={} unit_defs={} members={} \
hier_members={} reference_keys={} reference_sites={} defines={} instantiations={} \
fact_words={} fact_word_kib={} candidate_units={} candidate_macros={} \
candidate_words={} candidate_word_kib={} include_edges={} include_known={} \
work_kib={}",
self.number,
self.kind,
kib(self.cache.store_before as usize),
kib(self.cache.store_after as usize),
self.cache_entries,
kib(self.cache_bytes),
s.index_files,
s.unit_names,
s.unit_defs,
s.members,
s.hier_members,
s.reference_keys,
s.reference_sites,
s.defines,
s.instantiations,
s.fact_words,
kib(s.fact_word_bytes),
s.candidate_units,
s.candidate_macros,
s.candidate_words,
kib(s.candidate_word_bytes),
s.include_edges,
s.include_known,
kib(self.read_bytes),
)
}
}
/// Milliseconds since `from`.
fn millis(from: Instant) -> f64 {
from.elapsed().as_secs_f64() * 1_000.0
}
/// Nanoseconds as milliseconds, the unit every line is written in.
fn nanos(ns: u64) -> f64 {
ns as f64 / 1_000_000.0
}
/// Bytes as whole KiB, rounded down — the unit every size field carries.
fn kib(bytes: usize) -> usize {
bytes / 1024
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_trace_that_is_off_hands_out_no_clock_and_stays_zero() {
let trace = ScanTrace::new(false);
assert!(!trace.on());
assert!(trace.now().is_none());
assert_eq!(trace.elapsed_ms(), 0.0);
let mut slot = 0.0;
ScanTrace::add(&mut slot, trace.now());
assert_eq!(slot, 0.0, "an off trace cannot accumulate");
}
#[test]
fn a_trace_that_is_on_accumulates_into_the_slot_it_is_given() {
let trace = ScanTrace::new(true);
let started = trace.now();
assert!(started.is_some());
let mut slot = 0.0;
ScanTrace::add(&mut slot, started);
ScanTrace::add(&mut slot, started);
assert!(slot >= 0.0, "two adds are two summands, never a replacement");
}
#[test]
fn the_first_publish_is_the_one_that_is_stamped() {
let mut trace = ScanTrace::new(true);
trace.saw_publish(10);
let first = trace.first_publish_ms;
trace.saw_publish(5);
assert_eq!(trace.publishes, 2);
assert_eq!(trace.published, 15);
assert_eq!(trace.first_publish_ms, first, "a later publish never moves the stamp");
}
#[test]
fn cache_work_reports_a_scans_own_share_and_never_goes_negative() {
let before = CacheWork { hits: 10, lookup_ns: 500, ..CacheWork::default() };
let after = CacheWork { hits: 25, lookup_ns: 900, ..CacheWork::default() };
let mine = after.since(before);
assert_eq!(mine.hits, 15);
assert_eq!(mine.lookup_ns, 400);
// A counter that somehow went backwards saturates rather than wrapping
// into a nonsense number the tracker would then quote.
assert_eq!(before.since(after).hits, 0);
}
#[test]
fn every_line_names_its_scan_and_is_one_line() {
let mut trace = ScanTrace::new(true);
trace.kind = "whole";
trace.number = 2;
trace.read = 124;
for line in [trace.stage_line(), trace.count_line(), trace.memory_line()] {
assert!(line.starts_with("scan 2 "), "{line}");
assert!(!line.contains('\n'), "a timing line is one line: {line}");
assert!(line.contains("(whole, 124 files)") || line.contains("(whole)"), "{line}");
}
}
}
+10 -3
View File
@@ -61,7 +61,7 @@ impl Server {
}],
};
let id = self.send_request(WorkspaceConfiguration::METHOD, params);
self.pending.insert(id, Pending::Configuration);
self.pending.insert(id, Pending::Configuration(std::time::Instant::now()));
}
/// Ask the client to watch the source files and the filelist for us,
@@ -174,7 +174,7 @@ impl Server {
pub(super) fn response(&mut self, response: Response) {
match self.pending.remove(&response.id) {
Some(Pending::ApplyEdit(command)) => self.applied(command, response),
Some(Pending::Configuration) => self.configured(response),
Some(Pending::Configuration(asked)) => self.configured(asked, response),
None => {}
}
}
@@ -211,7 +211,8 @@ impl Server {
/// string) means the same thing: the client has no settings for us, which
/// is the defaults. Nothing here is worth a popup — the user did not ask
/// for this request and cannot act on its failure.
fn configured(&mut self, response: Response) {
fn configured(&mut self, asked: std::time::Instant, response: Response) {
self.timed(self.timer().map(|_| asked), |took| format!("configuration answered in {took}"));
let answered = response.response_result.unwrap_or(Value::Null);
let section = answered.get(0).cloned().unwrap_or(Value::Null);
self.apply_settings(settings::from_section(&section));
@@ -271,6 +272,12 @@ impl Server {
self.verbose.then(std::time::Instant::now)
}
/// How long this server has been alive, in milliseconds — the clock every
/// startup number is read against.
pub(super) fn since_start(&self) -> f64 {
self.born.elapsed().as_secs_f64() * 1_000.0
}
/// One timing line for work that was being timed — and nothing at all,
/// closure included, for work that was not.
pub(super) fn timed(
+25 -2
View File
@@ -127,6 +127,7 @@ impl Server {
return;
}
let started = self.timer();
let since_start = self.since_start();
if started.is_some() {
// The folders by name: which folder a jump widened into is the one
// thing the file log below it does not say in one line.
@@ -138,9 +139,10 @@ impl Server {
paths.join(", ")
));
}
let verbose = started.is_some();
let bar = self.begin_indexing();
let mut scan =
self.watching(bar.as_ref(), |workspace, watch| workspace.begin_widen(&added, watch));
self.watching(bar.as_ref(), |ws, watch| ws.begin_widen(&added, watch, verbose));
let total = scan.total();
// No drain between the files: a widen is a rescan a message asked for,
// and `must_wait` would hold every request queued behind it anyway. It
@@ -163,6 +165,7 @@ impl Server {
plural(total)
)
});
self.say_scan_trace(since_start);
self.refresh_code_lenses();
self.hierarchy_index_changed();
self.generation += 1;
@@ -224,8 +227,10 @@ impl Server {
// scope and walking it is part of what a scan costs, and a number that
// left it out would be the wrong answer to "why was that slow?".
let started = self.timer();
let since_start = self.since_start();
let verbose = started.is_some();
let bar = self.begin_indexing();
let mut scan = self.watching(bar.as_ref(), |workspace, watch| workspace.begin_scan(watch));
let mut scan = self.watching(bar.as_ref(), |ws, watch| ws.begin_scan(watch, verbose));
let interleave = scan.total() > INTERLEAVE_ABOVE;
let total = scan.total();
if started.is_some() {
@@ -252,9 +257,27 @@ impl Server {
plural(total)
)
});
self.say_scan_trace(since_start);
warnings
}
/// The three `timing: scan …` lines the startup breakdown is read from —
/// stages, counts and the sizes the scan left resident.
///
/// Silent without `--verbose`, because a scan that was not traced left a
/// trace of zeroes and three lines of them would be a lie
/// (`docs/features/perf5-p4/README.md` holds the field list).
fn say_scan_trace(&mut self, since_start: f64) {
let mut trace = self.workspace.take_scan_trace();
if !trace.on() {
return;
}
trace.since_start_ms = since_start;
self.timing(trace.stage_line());
self.timing(trace.count_line());
self.timing(trace.memory_line());
}
/// Do one piece of a scan with the progress bar and the per-file log
/// watching it.
///
+9 -2
View File
@@ -214,6 +214,11 @@ pub struct Server {
/// costs is the branch that reads this field — see
/// [`Server::timer`] and `docs/features/verbose-timing/README.md`.
verbose: bool,
/// When this server was built — the moment after `initialize`/`initialized`
/// that `main` hands control over. Every startup number is measured from
/// here, so a scan's line can say how much of the wait came before it
/// (`docs/features/perf5-p4/README.md`).
born: std::time::Instant,
}
/// How long a burst of `didChange` notifications may sit unanalyzed once the
@@ -252,8 +257,9 @@ enum Pending {
/// A `workspace/applyEdit`, remembering the command that asked for it so
/// a refusal can be named to the user.
ApplyEdit(String),
/// A `workspace/configuration` asking for the `lucisv` section.
Configuration,
/// A `workspace/configuration` asking for the `lucisv` section, and when
/// it was asked — the config round trip is part of what a startup costs.
Configuration(std::time::Instant),
}
/// One semantic-token answer, kept so the next delta request can be answered
@@ -340,6 +346,7 @@ impl Server {
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
@@ -56,6 +56,7 @@ mod progress;
mod pull_diagnostics;
mod requests;
mod scan;
mod scan_trace;
mod settings;
mod sync;
mod tokens;
@@ -191,6 +192,27 @@ impl Session {
Session { server, 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`).
fn verbose_wide(roots: Vec<PathBuf>, storage: Option<PathBuf>) -> Session {
let wide = ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
};
let (server_end, client) = Connection::memory();
let server = Server::started(
server_end,
roots,
ClientAbilities::default(),
wide,
storage,
true,
Vec::new(),
);
Session { server, client }
}
fn notify(&mut self, method: &str, params: impl serde::Serialize) {
self.server.notification(Notification::new(method.to_string(), params));
}
@@ -0,0 +1,186 @@
//! What a scan says it spent its time on (`docs/features/perf5-p4/README.md`).
//!
//! Three claims, one test each: the lines exist only under `--verbose`, the
//! counts on them are the work the scan actually did, and the stages add up
//! to the scan they describe.
use super::*;
/// A tree of `files` one-package files.
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}"));
}
tree
}
/// Every `timing: scan …` line the server has said since the last drain.
fn scan_lines(session: &Session) -> Vec<String> {
session
.logged()
.into_iter()
.filter(|(typ, text)| *typ == MessageType::LOG && is_trace_line(text))
.map(|(_, text)| text)
.collect()
}
/// 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 {
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 {
lines
.iter()
.find(|line| line.contains(&format!(" {kind} (")))
.unwrap_or_else(|| panic!("no {kind} line among {lines:#?}"))
.clone()
}
/// The value of `key=` on a `key=value` line, as text.
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("")
}
/// The value of `key=` as a number.
fn number(line: &str, key: &str) -> f64 {
let text = field(line, key);
text.parse().unwrap_or_else(|_| panic!("{key}={text} is not a number on {line}"))
}
#[test]
fn without_the_flag_a_scan_says_nothing_about_its_stages() {
// The shipped state. `Session::wide` is every other test in this module,
// and none of them may start seeing three extra log lines per scan.
let tree = trace_tree("tracequiet", 12);
let session = Session::wide(vec![tree.path.clone()], false);
assert!(scan_lines(&session).is_empty(), "verbose is off: {:#?}", session.logged());
}
#[test]
fn the_flag_makes_a_scan_say_what_it_spent_and_what_it_left() {
let tree = trace_tree("traceverbose", 12);
let session = Session::verbose_wide(vec![tree.path.clone()], None);
let lines = scan_lines(&session);
// Three lines, and they name the same scan.
let stages = line_of(&lines, "stages");
let counts = line_of(&lines, "counts");
let memory = line_of(&lines, "memory");
for line in [&stages, &counts, &memory] {
assert!(line.starts_with("timing: scan 1 "), "{line}");
assert!(line.contains("whole"), "the startup scan is a whole scan: {line}");
}
// The counts are this fixture's, exactly: twelve files walked and read,
// none skipped, none open, and no store to hit.
assert_eq!(field(&counts, "read"), "12");
assert_eq!(field(&counts, "skipped"), "0");
assert_eq!(field(&counts, "hits"), "0");
assert_eq!(field(&counts, "misses"), "12");
assert_eq!(field(&counts, "buffers"), "0");
// Twelve files is under `INTERLEAVE_ABOVE`, so the scan is one shot and
// nothing is published mid-way.
assert_eq!(field(&counts, "publishes"), "0");
assert_eq!(field(&stages, "since_start"), field(&stages, "since_start"));
// And the index it left is those twelve packages.
assert_eq!(field(&memory, "index_files"), "12");
assert_eq!(field(&memory, "cache_entries"), "0", "no storage path, so no store");
}
#[test]
fn a_warm_second_session_reports_every_file_as_a_hit() {
// The one claim the whole warm-scan column rests on: `hits` counts
// records served for exactly these bytes, and `misses` counts the parses.
let tree = trace_tree("tracewarm", 9);
let storage = std::env::temp_dir().join(format!("lucisv_trace_store_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&storage);
let cold = Session::verbose_wide(vec![tree.path.clone()], Some(storage.clone()));
let cold_lines = scan_lines(&cold);
let cold_counts = line_of(&cold_lines, "counts");
assert_eq!(field(&cold_counts, "hits"), "0");
assert_eq!(field(&cold_counts, "misses"), "9");
assert_eq!(field(&cold_counts, "records"), "9", "a cold scan writes every record through");
drop(cold);
let warm = Session::verbose_wide(vec![tree.path.clone()], Some(storage.clone()));
let warm_lines = scan_lines(&warm);
let warm_counts = line_of(&warm_lines, "counts");
assert_eq!(field(&warm_counts, "hits"), "9", "the same bytes, so every lookup hits");
assert_eq!(field(&warm_counts, "misses"), "0");
assert_eq!(field(&warm_counts, "records"), "0", "a hit writes nothing back");
let warm_memory = line_of(&warm_lines, "memory");
assert_eq!(field(&warm_memory, "cache_entries"), "9");
assert!(number(&warm_counts, "decoded_kib") >= 0.0);
drop(warm);
let _ = std::fs::remove_dir_all(&storage);
}
#[test]
fn the_stages_add_up_to_the_scan_they_describe() {
// The tolerance claim: what the trace attributes must be most of the scan
// and can never be more than all of it. The slack is the loop itself —
// the progress callbacks, the per-file word `Vec`, the staging pushes —
// which is deliberately unattributed rather than silently folded into a
// neighbouring stage.
let tree = trace_tree("tracesums", 40);
let session = Session::verbose_wide(vec![tree.path.clone()], None);
let stages = line_of(&scan_lines(&session), "stages");
let total = number(&stages, "total");
let named = [
"discovery",
"order",
"cache_open",
"lookup",
"decode",
"parse",
"encode",
"store_write",
"publish_absorb",
"publish_candidates",
"publish_includes",
"publish_overlay",
"gone",
"absorb",
"compact",
"candidates",
"includes",
"overlay",
];
let sum: f64 = named.iter().map(|key| number(&stages, key)).sum();
assert!(total > 0.0, "a scan of 40 files takes measurable time: {stages}");
assert!(sum <= total * 1.02, "the stages cannot exceed the scan: {sum} of {total}");
assert!(sum >= total * 0.5, "the stages must account for most of it: {sum} of {total}");
}
#[test]
fn a_rescan_is_a_second_scan_with_its_own_three_lines() {
// A session pays for more than one scan — the startup scan runs at the
// default settings and whatever the client then says can ask for another
// (`docs/features/perf5-p4/README.md`, the two-scan startup). Each gets
// its own numbered triple so no reader adds two scans together.
let tree = trace_tree("tracerescan", 8);
let mut session = Session::verbose_wide(vec![tree.path.clone()], None);
let first = scan_lines(&session);
assert_eq!(first.len(), 3, "one scan, three lines: {first:#?}");
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": {
"index": { "scope": "workspace" },
"exclude": ["**/t000.sv"],
} } }),
);
let second = scan_lines(&session);
assert_eq!(second.len(), 3, "the rescan says the same three things: {second:#?}");
for line in &second {
assert!(line.starts_with("timing: scan 2 "), "{line}");
}
let counts = line_of(&second, "counts");
assert_eq!(field(&counts, "read"), "7", "the exclusion is one file fewer");
}
+156 -10
View File
@@ -29,6 +29,7 @@ use crate::includes::IncludeGraph;
use crate::index_cache::IndexCache;
use crate::module_select::{self, Reach};
use crate::rename_trace::{self, Rung, SelectionTrace, Wanted};
use crate::scan_trace::ScanTrace;
use crate::settings::{ClientSettings, IndexScope};
use crate::uri::uri_to_path;
@@ -359,6 +360,9 @@ pub struct Scan {
/// live on it — the end message names both.
skipped: usize,
cached: usize,
/// What this scan spent its time on, when `--verbose` asked. Off, it is a
/// bag of zeroes nobody reads (`crate::scan_trace`).
trace: ScanTrace,
}
/// Which of the two shapes a [`Scan`] is.
@@ -522,6 +526,14 @@ pub struct Workspace {
/// without changing an answer, and every way a file's text can move drops
/// its entry (see [`Workspace::file_view`]).
views: RefCell<Vec<Rc<FileView>>>,
/// The trace of the scan that finished most recently, waiting for the
/// server to read it out and log it. Held here rather than returned from
/// [`Workspace::finish_scan`] so that no caller's signature moves for a
/// diagnostic; empty and zeroed unless `--verbose` asked for one.
last_trace: ScanTrace,
/// How many scans this workspace has run, so a session's lines can be
/// told apart — a `workspace` scope pays two (`docs/features/perf5-p4`).
scans: u32,
}
impl Workspace {
@@ -904,7 +916,7 @@ impl Workspace {
/// is what every test that just wants an index calls instead.
#[cfg(test)]
pub fn rebuild_index_with(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Vec<String> {
let mut scan = self.begin_scan(watch);
let mut scan = self.begin_scan(watch, false);
while self.scan_step(&mut scan, watch) {}
self.finish_scan(scan)
}
@@ -924,7 +936,7 @@ impl Workspace {
added: &[PathBuf],
watch: &mut dyn FnMut(IndexEvent),
) -> Vec<String> {
let mut scan = self.begin_widen(added, watch);
let mut scan = self.begin_widen(added, watch, false);
while self.scan_step(&mut scan, watch) {}
self.finish_scan(scan)
}
@@ -935,10 +947,12 @@ impl Workspace {
/// Nothing is indexed here and the live index is untouched, so a scan that
/// is never stepped changes nothing but the view cache and the open cache
/// handle.
pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Scan {
pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent), trace: bool) -> Scan {
let mut trace = self.opened_trace(trace, "whole");
// A rescan says nothing about *which* file moved, so nothing held from
// before it can be trusted.
self.views.borrow_mut().clear();
let discovering = trace.now();
let mut skipped = 0usize;
let mut scope = {
// The cap's skips are reported by `collect_sources` and counted
@@ -952,19 +966,25 @@ impl Workspace {
};
self.collect_sources(&mut counting, HeldAnalyses::Wanted)
};
ScanTrace::add(&mut trace.discovery_ms, discovering);
let texts = std::mem::take(&mut scope.texts);
let analyzed = std::mem::take(&mut scope.analyzed);
let ordering = trace.now();
// The same list the index will be built from — asked of
// `vlog_semantic` rather than re-derived here, so the count reported
// is the count parsed — with the user's own open files moved to the
// front of it.
let work = self.open_first(index_order(texts));
let paths: Vec<PathBuf> = work.iter().map(|(path, _)| path.clone()).collect();
ScanTrace::add(&mut trace.order_ms, ordering);
let opening = trace.now();
// Re-opened here rather than held across rescans: the directory it
// belongs in depends on settings that arrive after startup, and a
// second session over the same workspace may have written records
// this one has not seen.
self.cache = IndexCache::open(self.cache_dir());
ScanTrace::add(&mut trace.cache_open_ms, opening);
self.measure_work(&mut trace, &work, skipped);
Scan {
kind: ScanKind::Whole,
work,
@@ -979,9 +999,38 @@ impl Workspace {
words: HashMap::new(),
skipped,
cached: 0,
trace,
}
}
/// 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.
///
/// `since_start_ms` is left for the server to stamp: how long the process
/// had been alive is the server's own knowledge, not the workspace's.
fn opened_trace(&mut self, on: bool, kind: &'static str) -> ScanTrace {
self.scans = self.scans.saturating_add(1);
let mut trace = ScanTrace::new(on);
trace.kind = kind;
trace.number = self.scans;
trace
}
/// The work list's size, in files and in the bytes the scan will hold for
/// as long as it runs.
fn measure_work(&self, trace: &mut ScanTrace, work: &[(PathBuf, String)], skipped: usize) {
if !trace.on() {
return;
}
trace.read = work.len();
trace.read_bytes = work.iter().map(|(_, text)| text.len()).sum();
trace.skipped = skipped;
// The baseline `landed` subtracts: a widen inherits the cache the
// previous scan filled, so the counters on it are the session's and
// not this scan's.
trace.cache = self.cache.work();
}
/// Take the work list for a **scope widen**: the files `added` brings into
/// scope that the index does not already hold, plus every open buffer's own
/// analysis.
@@ -1012,7 +1061,14 @@ impl Workspace {
/// `added` is the directories that entered [`Workspace::scope_dirs`]; the
/// caller decides that they really are an addition and nothing else
/// (`server.rs`'s `widen_of`).
pub fn begin_widen(&mut self, added: &[PathBuf], watch: &mut dyn FnMut(IndexEvent)) -> Scan {
pub fn begin_widen(
&mut self,
added: &[PathBuf],
watch: &mut dyn FnMut(IndexEvent),
trace: bool,
) -> Scan {
let mut trace = self.opened_trace(trace, "widen");
let discovering = trace.now();
let held: HashSet<PathBuf> = self.index.files().iter().cloned().collect();
let cap = self.client.max_file_size;
let spoken_for: HashSet<&Path> =
@@ -1058,7 +1114,11 @@ impl Workspace {
analyzed.words.insert(path.clone(), doc.words());
texts.push((path, doc.text.clone()));
}
ScanTrace::add(&mut trace.discovery_ms, discovering);
let ordering = trace.now();
let work = self.open_first(index_order(texts));
ScanTrace::add(&mut trace.order_ms, ordering);
self.measure_work(&mut trace, &work, skipped);
// A whole scan drops the view cache entire, because a rescan claims
// nothing about *which* file moved. A widen names exactly the files it
// is reading, so it drops exactly those — which keeps the cache's own
@@ -1094,6 +1154,7 @@ impl Workspace {
words: HashMap::new(),
skipped,
cached: 0,
trace,
}
}
@@ -1136,6 +1197,7 @@ impl Workspace {
// the next session starts from it.
Some(facts) => {
watch(IndexEvent::Analyzed { done, total, path: &path });
scan.trace.buffers += 1;
self.cache.record(&facts, text);
facts
}
@@ -1152,7 +1214,10 @@ impl Workspace {
}
None => {
watch(IndexEvent::Parsing { done, total, path: &path });
let parsing = scan.trace.now();
let facts = FileFacts::of(path.clone(), text);
ScanTrace::add(&mut scan.trace.parse_ms, parsing);
scan.trace.parse_bytes += text.len();
self.cache.record(&facts, text);
facts
}
@@ -1188,7 +1253,10 @@ impl Workspace {
return;
}
let taken = std::mem::take(&mut scan.staged_at);
let absorbing = scan.trace.now();
self.index.absorb(std::mem::take(&mut scan.staged), &[]);
ScanTrace::add(&mut scan.trace.publish_absorb_ms, absorbing);
let completing = scan.trace.now();
let words = taken
.iter()
.map(|&at| {
@@ -1197,14 +1265,20 @@ impl Workspace {
})
.collect();
self.candidates.absorb(&self.index, words);
ScanTrace::add(&mut scan.trace.publish_candidates_ms, completing);
let including = scan.trace.now();
let texts: Vec<(&Path, &str)> =
taken.iter().map(|&at| (scan.work[at].0.as_path(), scan.work[at].1.as_str())).collect();
self.includes.absorb(&scan.incdirs, &scan.paths, &texts);
ScanTrace::add(&mut scan.trace.publish_includes_ms, including);
let refreshing = scan.trace.now();
// Every open buffer resolves against the index, so a buffer whose
// cross-file names the scan has just reached must be able to see them.
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
ScanTrace::add(&mut scan.trace.publish_overlay_ms, refreshing);
scan.trace.saw_publish(taken.len());
}
/// Finish `scan`: the index, the completion tables, the include graph and
@@ -1225,7 +1299,8 @@ impl Workspace {
/// [`Workspace::finish_scan`] for a whole scan.
fn finish_whole_scan(&mut self, scan: Scan) -> Vec<String> {
let Scan { work, incdirs, warnings, staged, words, .. } = scan;
let Scan { work, incdirs, warnings, staged, words, mut trace, .. } = scan;
let leaving = trace.now();
// Whatever the last scan left in the index that this one's work list
// does not name is a file that is no longer in scope.
let held: HashSet<&Path> = work.iter().map(|(path, _)| path.as_path()).collect();
@@ -1236,23 +1311,85 @@ impl Workspace {
.filter(|path| !held.contains(path.as_path()))
.cloned()
.collect();
ScanTrace::add(&mut trace.gone_ms, leaving);
let absorbing = trace.now();
self.index.absorb(staged, &gone);
ScanTrace::add(&mut trace.absorb_ms, absorbing);
// The one moment the live set of entries is known, so the one moment
// the append log is worth rewriting.
self.cache.compact();
let completing = trace.now();
// Built here, from the same list, so a file the scope ladder excluded
// contributes no completion candidates either. Every file's words are
// in `words` already, so nothing is lexed twice.
self.candidates = Candidates::build(&self.index, &work, words);
ScanTrace::add(&mut trace.candidates_ms, completing);
let including = trace.now();
// Same list again: an `` `include`` in a file the scope excluded is
// not an edge, and a file it excluded is not a hop away from anything.
self.includes = IncludeGraph::build(&work, incdirs);
ScanTrace::add(&mut trace.includes_ms, including);
let refreshing = trace.now();
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
ScanTrace::add(&mut trace.overlay_ms, refreshing);
self.landed(trace);
warnings
}
/// Close a scan's trace: the tables it left behind, measured, and the
/// whole thing set aside for the server to log.
///
/// Every size below is a walk, so all of them are behind `on()` and none
/// of them happens in a session that did not ask for a trace.
fn landed(&mut self, mut trace: ScanTrace) {
if !trace.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.
trace.total_ms = trace.elapsed_ms();
trace.overlays = self.docs.len();
trace.cache = self.cache.work().since(trace.cache);
// At the *end*, so the store's retention is what the finished scan
// leaves resident rather than what it started from — the two differ
// by every record a cold scan wrote.
trace.cache_entries = self.cache.entry_count();
trace.cache_bytes = self.cache.encoded_bytes();
let index = self.index.table_sizes();
let counts = self.index.counts();
let (units, macros, words, word_bytes) = self.candidates.sizes();
let (include_edges, include_known) = self.includes.sizes();
trace.sizes = crate::scan_trace::TableSizes {
index_files: counts.files,
unit_names: index.unit_names,
unit_defs: index.unit_defs,
members: index.members,
hier_members: index.hier_members,
reference_keys: index.reference_keys,
reference_sites: index.reference_sites,
defines: counts.defines,
instantiations: counts.instantiations,
fact_words: index.words,
fact_word_bytes: index.word_bytes,
candidate_units: units,
candidate_macros: macros,
candidate_words: words,
candidate_word_bytes: word_bytes,
include_edges,
include_known,
};
self.last_trace = trace;
}
/// The trace of the scan that just finished, taken away — an inert one
/// when the scan was not being traced.
pub fn take_scan_trace(&mut self) -> ScanTrace {
std::mem::take(&mut self.last_trace)
}
/// [`Workspace::finish_scan`] for a widen: the same three tables, folded
/// into rather than replaced.
///
@@ -1279,8 +1416,10 @@ impl Workspace {
/// set of entries — it only added to it — and the next whole rescan
/// rewrites the log anyway.
fn finish_widen(&mut self, scan: Scan) -> Vec<String> {
let Scan { work, paths, gone, incdirs, warnings, staged, words, .. } = scan;
let Scan { work, paths, gone, incdirs, warnings, staged, words, mut trace, .. } = scan;
let absorbing = trace.now();
self.index.absorb(staged, &gone);
ScanTrace::add(&mut trace.absorb_ms, absorbing);
// Before the additions, so the two never disagree about a path that is
// in both lists — which cannot happen today (a large buffer is in
// neither `work` nor `paths`) and would be a silent wrong answer if it
@@ -1293,13 +1432,20 @@ impl Workspace {
.iter()
.map(|(path, _)| (path.clone(), words.get(path).cloned().unwrap_or_default()))
.collect();
let completing = trace.now();
self.candidates.absorb(&self.index, batch);
ScanTrace::add(&mut trace.candidates_ms, completing);
let including = trace.now();
let texts: Vec<(&Path, &str)> =
work.iter().map(|(path, text)| (path.as_path(), text.as_str())).collect();
self.includes.absorb(&incdirs, &paths, &texts);
ScanTrace::add(&mut trace.includes_ms, including);
let refreshing = trace.now();
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
ScanTrace::add(&mut trace.overlay_ms, refreshing);
self.landed(trace);
warnings
}
@@ -2578,7 +2724,7 @@ mod tests {
/// the worst case the interleaved path can produce, and the one a
/// one-shot scan has to agree with.
fn scan_publishing_every_file(ws: &mut Workspace) -> Vec<String> {
let mut scan = ws.begin_scan(&mut |_| {});
let mut scan = ws.begin_scan(&mut |_| {}, false);
while ws.scan_step(&mut scan, &mut |_| {}) {
ws.publish_scan(&mut scan);
}
@@ -2659,7 +2805,7 @@ mod tests {
let mut stepped = Workspace::default();
stepped.client.index_scope = IndexScope::Workspace;
stepped.adopt_roots(vec![tree.path.clone()]);
let mut scan = stepped.begin_scan(&mut |_| {});
let mut scan = stepped.begin_scan(&mut |_| {}, false);
assert!(stepped.scan_step(&mut scan, &mut |_| {}), "premise: there is a first file");
stepped.publish_scan(&mut scan);
// The client opens `b.sv` and types in it, mid-scan.
@@ -2692,7 +2838,7 @@ mod tests {
let mut stepped = Workspace::default();
stepped.client.index_scope = IndexScope::Workspace;
stepped.adopt_roots(vec![tree.path.clone()]);
let mut scan = stepped.begin_scan(&mut |_| {});
let mut scan = stepped.begin_scan(&mut |_| {}, false);
assert!(stepped.scan_step(&mut scan, &mut |_| {}), "premise: a.sv goes first");
assert!(stepped.index().units("c").is_empty(), "premise: c.sv is not indexed yet");
@@ -2724,7 +2870,7 @@ mod tests {
stepped.client.index_scope = IndexScope::Workspace;
stepped.adopt_roots(vec![tree.path.clone()]);
let mut also = Vec::new();
let mut scan = stepped.begin_scan(&mut |event| also.push(seen(&event)));
let mut scan = stepped.begin_scan(&mut |event| also.push(seen(&event)), false);
while stepped.scan_step(&mut scan, &mut |event| also.push(seen(&event))) {
stepped.publish_scan(&mut scan);
}
+2 -2
View File
@@ -38,8 +38,8 @@ pub use model::{
pub use workspace::{
index_order, resolve_external, DeclLines, DeclPositions, DeclSite, Def, Definition,
DefinitionKey, ExternalResolutions, ExternalTarget, FileFacts, FileId, IndexBuilder,
IndexCounts, InheritanceEdge, InstanceOccurrence, InstantiationEdge, ReferenceSite, Utf16Pos,
Utf16Range, WorkspaceIndex, WorkspaceSymbol,
IndexCounts, IndexTableSizes, InheritanceEdge, InstanceOccurrence, InstantiationEdge,
ReferenceSite, Utf16Pos, Utf16Range, WorkspaceIndex, WorkspaceSymbol,
};
use std::collections::HashMap;
+22 -2
View File
@@ -17,8 +17,8 @@ use super::external::{fold_path, last_segment, member_chain, own_members};
use super::hierarchy;
use super::record::{FileFacts, ReferenceFact};
use super::{
reexport, Def, DefinitionKey, FileId, IndexCounts, InheritanceEdge, InstantiationEdge,
Reexport, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
reexport, Def, DefinitionKey, FileId, IndexCounts, IndexTableSizes, InheritanceEdge,
InstantiationEdge, Reexport, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
};
impl WorkspaceIndex {
@@ -516,6 +516,26 @@ impl WorkspaceIndex {
}
}
/// How many entries each table holds — [`IndexCounts`] asked by table
/// rather than by declaration kind.
pub fn table_sizes(&self) -> IndexTableSizes {
IndexTableSizes {
unit_names: self.units.len(),
unit_defs: self.units.values().map(Vec::len).sum(),
members: self.members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
hier_members: self.hier_members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
reference_keys: self.reference_sites.len(),
reference_sites: self.reference_sites.values().map(Vec::len).sum(),
words: self.facts.iter().map(|facts| facts.words().len()).sum(),
word_bytes: self
.facts
.iter()
.flat_map(|facts| facts.words())
.map(|word| word.len())
.sum(),
}
}
fn units_of_kind(&self, kind: SymbolKind) -> usize {
self.units.values().flatten().filter(|d| d.kind == kind).count()
}
+27
View File
@@ -365,3 +365,30 @@ pub struct IndexCounts {
/// `extends` edges recorded, one per class that names a base.
pub inheritances: usize,
}
/// How many entries each of a built index's tables holds — the memory
/// question, asked in counts rather than in bytes.
///
/// Additive to [`IndexCounts`] rather than folded into it: those are the
/// headline numbers a user is told after a scan ("1 544 modules"), these are
/// the per-table sizes a performance round reads once at the end of a traced
/// scan. Cheap by construction — map lengths and one sum per table, no walk
/// into a `Def` and no allocation — but it is still a walk over the tables, so
/// it belongs at the end of a scan and not on a request path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct IndexTableSizes {
/// File-scope names, and the declarations under them once duplicates are
/// counted separately.
pub unit_names: usize,
pub unit_defs: usize,
/// Connection-surface member declarations, and the hierarchical-only ones.
pub members: usize,
pub hier_members: usize,
/// Declarations that have at least one recorded use, and the uses.
pub reference_keys: usize,
pub reference_sites: usize,
/// The identifier census every file carries since `FACTS_FORMAT` 13, and
/// what those strings weigh.
pub words: usize,
pub word_bytes: usize,
}
+686
View File
@@ -0,0 +1,686 @@
# perf5-p4 — the startup and memory breakdown (take 5 §P4a)
## Goal
Take 5 §P4 asks whether startup work and resident memory are worth
optimizing, and its own text says the individual shares are unmeasured:
"a warm index still reads source text to hash it, decodes encoded facts,
rebuilds/merges query tables, constructs completion/include tables and
refreshes open-buffer overlays […] their individual time/memory shares are
unmeasured." §P4a is the measurement that ends that sentence. It adds a
startup trace on the `--verbose` channel and a harness that reads it, so the
lead can rule on §P4b — which stage, or none — against numbers rather than
against the plan's hypotheses. **No optimization is in this lane.** Nothing
here changes what a scan does; it changes only what a scan is willing to say
about itself, and only when the flag is on.
## Assumptions
- **`--verbose` is the right channel.** The trace is three
`window/logMessage` lines per scan under the existing `timing:` prefix
(`docs/features/verbose-timing/README.md`), so a user who turns the flag on
gets them and a shipped server never does. The verbose-timing README's
"nobody parses these lines" assumption is amended by this feature: the
harness parses them, which is why they are `key=value` and why their shape
is pinned by tests.
- **A clock read per file is free enough to leave always on inside the
store.** `IndexCache`'s counters are not behind the flag: `facts_for` is a
`&self` read and threading a flag into it would cost more code than the
four `Instant::now()`s a file pays there. The settled-time tolerance check
below is what makes that claim measured rather than asserted.
- **Everything that is a walk is behind the flag.** The table sizes
(`WorkspaceIndex::table_sizes`, `Candidates::sizes`, `IncludeGraph::sizes`,
`IndexCache::encoded_bytes`) are each a pass over a table, so they run once
at the end of a scan and only when a trace asked for them.
- **A session pays for more than one scan.** The startup scan runs at the
**default** settings — `Server::started` builds the index before
`workspace/configuration` can be asked, let alone answered — so a client
that configures a wider scope pays a default scan and then a configured
rescan. The trace numbers its scans for exactly this reason, and no row in
this feature ever adds two scans together.
- **RSS is the harness's to measure.** The trace reports table *sizes*, not a
resident set: `ps -o rss=` at 50 ms is the existing `rss` phase's job and
stays there. What the trace adds is the sizes that explain the reading.
## Handshakes
### `vlog_semantic` — a new additive query
```rust
/// How many entries each table holds — `IndexCounts` asked by table rather
/// than by declaration kind.
pub fn table_sizes(&self) -> IndexTableSizes;
```
Additive: no existing query moved, no codec changed, `FACTS_FORMAT` untouched.
`IndexTableSizes` is exported beside `IndexCounts`. It is a walk over the
tables (map lengths plus one sum per table), so it belongs at the end of a
scan and never on a request path — that restriction is in its doc comment.
### `lucisv_server` internals
- `Workspace::begin_scan` and `Workspace::begin_widen` take a `trace: bool`.
Every existing caller passes `false`; only `Server::scan_once` and
`Server::reindex_widened` pass the flag through.
- `Workspace::take_scan_trace()` hands the finished trace to the server. The
trace is parked on the workspace rather than returned from `finish_scan` so
that no caller's signature moved for a diagnostic.
- `Candidates::sizes()` and `IncludeGraph::sizes()` are new read-only queries.
- `Pending::Configuration` carries the `Instant` it was asked at, so the
config round trip is a number rather than a guess.
- `Server` gains `born: Instant`: how long the process had been alive when a
scan started is the server's knowledge, not the workspace's.
**Amends `docs/features/verbose-timing/README.md`'s line table** with three
lines. That README's own "Nobody parses these lines" assumption no longer
holds for these three; the amendment is recorded here and in the work log.
### Requests for the lead (`docs/topo.md` is not edited by this lane)
Every edge below is **additive** — nothing existing changed shape — and each is
a request for the lead to apply at merge, not a silent edit:
1. `lucisv_server ──▶ vlog_semantic`: `WorkspaceIndex::table_sizes() ->
IndexTableSizes`, a new read-only query beside `counts()`. No codec change,
`FACTS_FORMAT` untouched, no existing query moved.
2. A new server module `scan_trace`, consumed by `state.rs`, `index_cache.rs`
and `server/index.rs`.
3. `Workspace::begin_scan` and `Workspace::begin_widen` take a `trace: bool`;
`Workspace::take_scan_trace()` is new. Every pre-existing caller passes
`false` and reads nothing.
4. `Candidates::sizes()`, `IncludeGraph::sizes()`, `IndexCache::work()`,
`IndexCache::entry_count()`, `IndexCache::encoded_bytes()` — all read-only.
5. `Server` gains `born: Instant`; `Pending::Configuration` gains an `Instant`
payload. Both are internal to `lucisv_server`.
6. The `verbose-timing` amendment above.
## What the trace prints
Three lines per scan, each `timing: scan <n> <kind> (<shape>, …): key=value …`.
| line | carries |
|---|---|
| `stages` | `discovery order cache_open lookup decode parse encode store_write publish_absorb publish_candidates publish_includes publish_overlay gone absorb compact candidates includes overlay total since_start`, all in ms |
| `counts` | `read read_kib skipped hits misses buffers records decoded_kib written_kib publishes published first_publish overlays` |
| `memory` | `store_before_kib store_after_kib cache_entries cache_encoded_kib index_files unit_names unit_defs members hier_members reference_keys reference_sites defines instantiations fact_words fact_word_kib candidate_units candidate_macros candidate_words candidate_word_kib include_edges include_known work_kib` |
Plus one line at the settings pull: `timing: configuration answered in X ms`.
## Status / TODO
- [x] `crates/lucisv_server/src/scan_trace.rs` — the trace type and its lines
- [x] `state.rs` call sites (calls only), `index_cache.rs` counters,
`candidates.rs` / `includes.rs` size queries,
`vlog_semantic::WorkspaceIndex::table_sizes`
- [x] `server/index.rs` emits the lines; `server/client.rs` times the config pull
- [x] tests: flag-gated, exact counts, warm-hit counts, stage-sum tolerance,
a rescan is its own numbered scan
- [x] `tools/perf/phases_p4.py` — `scanprofile`, `scanwait`, `scanserve`
- [x] measured breakdown (below), tracker rows and the §P4b recommendation
- [ ] QA
- [ ] lead ruling on §P4b
## Work log
### 2026-09-07 — dev (Opus)
Instrumentation written; no behavioural change. Notes on the shape:
- **The trace lives on the `Scan`.** A `ScanTrace` is a bag of `f64` sums and
`usize` counters with an `on` flag; `now()` hands out `Option<Instant>` and
`add(slot, from)` is a branch, so a scan that is not traced reads no clock
and allocates nothing. Nothing per file is allocated even when it is on.
- **The cache's own split needed counters inside the cache.** `facts_for` is
the one place that can separate "hash the text and find the entry" from
"decode the record", which is exactly §P4's hypothesis, so `IndexCache`
holds a `Cell<CacheWork>` and `compact` records the store's size before and
after. A `Cell` because `facts_for` takes `&self`.
- **`buffers` is counted and not timed.** Taking an open buffer's own
finished analysis costs nothing to *take*; what that file then costs is the
record written through, which is in `encode`/`store_write` like every other
file's. Timing the arm as well would have double-counted it.
- **The stages are disjoint, and they do not have to add to `total`.** The
slack is the scan loop itself — the progress/log callbacks, the per-file
word `Vec`, the staging pushes. Left unattributed on purpose rather than
folded into a neighbouring stage; the tolerance test asserts the stages
never *exceed* the scan and account for most of it.
## The measured breakdown
Release `08093a3a2b9c0b8796e5f9214ac7bda59e068e49e32a9c2393f29d116fca10bd`,
opentitan `0098135264`, three fresh sessions per cell, every run under
`tools/guard.sh -m 8 -t 1800`, one-minute load 4.1–5.0 during the timed
phases. Raw rows: `~/.cache/lucisv-perf/take5-p4/results.jsonl`, experiment
`P4a-2026-09-07` in `docs/perf/take5-tracking.md`.
### A workspace session pays three scans, and the first one indexes nothing
The single most useful thing the trace says is structural, and it was not in
anybody's model of the startup:
| scan | when | what it indexes | cold | warm |
|---|---|---|---:|---:|
| 1, whole | `Server::started`, at the **default** settings, before any buffer is open | **0 files** — the folder scope is derived from directories a buffer has been opened from, and none has | **0.8 ms** | **183.7 ms** |
| 2, widen | the `didOpen` of the first buffer widens the scope to its folder | 124 files | 94.0 ms | 26.6 ms |
| 3, whole | the pulled `lucisv.index.scope: "workspace"` arrives and asks for a rescan | 3 976 files | 2 760.0 ms | 1 112.7 ms |
The 124-file "default scan" the plan expected is really a **widen**, and the
startup scan proper is empty. Warm, that empty scan still costs **183.7 ms**:
it opens the 44.3 MiB store (`cache_open` 92.5 ms) and then **compacts it**
(`compact` 91.0 ms) — rewriting 45 396 KiB to produce a byte-identical file,
because `finish_whole_scan` compacts unconditionally and the work list being
empty is not consulted. Cold the same scan costs 0.8 ms, because there is no
store yet.
### Ranked stages — cold, settled mean 2 893.6 ms (2 866.7 / 2 936.3 / 2 877.7)
Summed over all three scans of the session.
| stage | ms | % of settled |
|---|---:|---:|
| parse | 1 703.63 | 58.9 % |
| discovery (scope walk + read 34.2 MiB of text) | 299.59 | 10.4 % |
| absorb (the final merge) | 218.40 | 7.5 % |
| encode (records out) | 183.26 | 6.3 % |
| store_write (append log) | 118.46 | 4.1 % |
| `Candidates::build` | 110.66 | 3.8 % |
| compact | 93.89 | 3.2 % |
| `IncludeGraph::build` | 45.52 | 1.6 % |
| decode | 5.87 | 0.2 % |
| publish_absorb (one mid-scan publish) | 4.41 | 0.2 % |
| cache_open | 3.39 | 0.1 % |
| lookup (content hash) | 2.86 | 0.1 % |
| order, gone, overlay, publish_candidates/includes/overlay | 4.15 | 0.1 % |
| **named total** | **2 794.09** | **96.6 %** |
| unattributed (the scan loop, the progress/log callbacks, the per-file word `Vec`, the staging pushes, and the `didOpen`/publish work between scans) | 99.49 | 3.4 % |
### Ranked stages — warm, settled mean 1 332.7 ms (1 332.6 / 1 330.0 / 1 335.5)
| stage | ms | % of settled |
|---|---:|---:|
| discovery (scope walk + read 34.2 MiB of text) | 255.91 | 19.2 % |
| absorb (the final merge) | 218.08 | 16.4 % |
| decode (44.2 MiB of records) | 202.75 | 15.2 % |
| **cache_open** (the store read **twice**, 44.3 MiB each) | **183.46** | **13.8 %** |
| **compact** (the store rewritten **twice**, unchanged both times) | **182.39** | **13.7 %** |
| `Candidates::build` | 113.34 | 8.5 % |
| lookup (content hash of 34.2 MiB) | 51.31 | 3.9 % |
| `IncludeGraph::build` | 46.30 | 3.5 % |
| publish_absorb | 4.34 | 0.3 % |
| everything else (order, gone, overlay, encode, store_write, publish_*) | 4.40 | 0.3 % |
| **named total** | **1 262.28** | **94.7 %** |
| unattributed | 70.44 | 5.3 % |
| parse | **0.00** | **0.0 %** |
**Warm has no dominant stage.** The five largest are within a factor of 1.4 of
each other, and two of them — 365.9 ms, **27.5 % of the whole warm settle** —
are the persistent store reading and rewriting itself.
### Memory
| what | measured | note |
|---|---:|---|
| Idle RSS, cold, 3 sessions | 531.0 / 529.0 / 529.9 MiB | REF 526.7 / 530.2 / 535.2 — agrees |
| Idle RSS, warm, 3 sessions | 574.8 / 565.2 / 564.8 MiB | REF 575.0 / 572.5 / 575.6 — agrees (−0.1 % on the maximum) |
| Peak RSS across the scan | equal to idle to the KiB, all six sessions | `ps -o rss=` at 50 ms; still no transient above idle |
| Store on disk | 45 396 KiB = 44.33 MiB | `du -sk` 44.34 MiB |
| **Encoded facts held in `IndexCache` beside the decoded index** | **45 260 KiB = 44.20 MiB** | 7.7 % of warm idle RSS. The plan's hypothesis, measured |
| Source text held by the scan for its whole life (`work`) | 34 973 KiB = 34.15 MiB | released at `finish_scan`; not in idle RSS |
| Index: files / unit names / unit declarations | 3 976 / 3 067 / 4 013 | |
| Index: connection members / hierarchical members | 91 894 / 56 913 | |
| Index: reference keys / reference sites | 59 529 / **457 666** | the largest single table by entry count |
| Index: `` `define``s / instantiation edges | 1 358 / 13 894 | |
| Index: identifier census (`FileFacts::words`) | 345 127 words, 4 754 KiB = 4.64 MiB | |
| Completion tables: units / macros / words | 50 726 / 658 / 105 042 words, 1 888 KiB | |
| Include graph: resolved edges / known files | 1 984 / 3 976 | |
The **warm-minus-cold idle difference is 34–46 MiB**, and the store path is the
only thing that differs between the two sessions: both end holding the same
index and the same 44.20 MiB of encoded entries, but the warm session
additionally reads a 44.3 MiB file into one `Vec<u8>` twice and renders a
44.3 MiB `String` twice. That is consistent with the encoded retention plus
allocator retention of those buffers; it is **not** an allocation profile and
is not quoted as one.
### The first useful answer, explained
§P0 measured cold **84.4–85.9 ms** and warm **206.1–218.7 ms** and could not
say why warm was 2.5× slower. The trace answers it arithmetically.
| | scan 1 | scan 2 (widen) | sum | measured first answer |
|---|---:|---:|---:|---:|
| cold | 0.54 | 81.58 | **82.1** | **83.4 / 85.7 / 84.9** |
| warm | 181.19 | 26.31 | **207.5** | **208.7 / 208.9 / 209.2** |
The definition arrives with the `didOpen` and is answered as soon as the widen
that `didOpen` triggered has finished. Cold, the wait is that widen's 123
parses. Warm, the widen is 3× cheaper (26 ms, every file a cache hit) but the
**empty startup scan ahead of it has spent 181 ms opening and compacting the
store**. So it is neither the publish cadence nor the decode: **it is the
config wait — the empty scan the server runs before configuration can arrive —
and specifically that scan's store I/O.** The `configuration answered in` line
agrees: 82.8–85.2 ms cold, 27.3–28.1 ms warm — the client answers instantly in
both, and what the number measures is when the server got back to reading it.
### Open buffers: 1 / 10 / 100
Warm workspace scope, the first N files of `hw/ip/*/rtl` opened right after
`initialize`, all before the scan settles.
| | 1 buffer | 10 buffers | 100 buffers |
|---|---:|---:|---:|
| settled mean | 1 841.6 ms | 1 859.1 ms | **2 173.9 ms** |
| scans traced | 4 | 4 | 4 |
| final whole scan | 1 268.2 ms | 1 230.9 ms | 1 348.5 ms |
| overlay refresh, final scan (`overlay` + `publish_overlay`) | 0.31 ms | 1.33 ms | **19.67 ms** |
| `order` (open-buffers-first) | 1.30 ms | 3.97 ms | **60.64 ms** |
| `encode` + `store_write` (a buffer's own record written through) | 0.49 ms | 2.21 ms | **21.20 ms** |
| buffers indexed from their own analysis | 2 | 11 | 101 |
| config round trip | 388–404 ms | 401–417 ms | 561–570 ms |
Opening buffers adds a **fourth** scan — a second widen (352–372 ms) for the
folders those files live in, which brings 1 685 files into scope before the
configured scope arrives. **The overlay refresh is not the cost**: 100 open
buffers refresh in 19.7 ms. The cost that actually scales is `order` — 60.6 ms
at 100 buffers, which is `open_first` moving each buffer's path to the front of
a 3 976-entry work list, one linear scan per buffer. It is 3 % of that
session's settle, so it is measured and filed, not a recommendation.
### Requests arriving during a scan
A `textDocument/definition` every 200 ms for as long as the scan is still
reporting, three fresh sessions per cache state. Each session gets three
answers, and the distribution has three distinct modes rather than a spread:
| | during scans 1–2 | **queued behind the configured rescan** | after settle |
|---|---:|---:|---:|
| cold | 83.66 / 83.97 / 84.95 ms | **2 558.85 / 2 563.65 / 2 567.24 ms** | 0.39 / 0.43 / 0.43 ms |
| warm | 210.26 / 212.58 / 214.34 ms | **897.12 / 904.12 / 907.90 ms** | 0.24 / 0.26 / 0.40 ms |
The middle column is the finding: **a request that arrives during the
configured rescan waits the whole rescan** — 2.56 s cold, 0.90 s warm. That is
the scan-interleave contract behaving exactly as written (only a scan *nobody
asked for* answers mid-way, and the scan nobody asked for is the empty one), so
it is not a bug; but it means the interleaving that §46's round bought is
currently spent on a scan with no files in it, and the scan that really takes
seconds blocks navigation outright.
**Table coherence: 0 mismatched answers in 18 requests across all six
sessions.** Every mid-scan answer either named exactly what the settled index
names or was empty; none named anywhere else. That is the observable form of
`docs/features/index-scope/README.md`'s coherent-prefix contract, and the
`scanserve` row fails loudly (`status: error`) if it is ever violated.
### The instrumented binary against the REF
The trace must not slow the scan it measures. Measured with the **quiet**
binary (no `--verbose`), same `scan` phase as §P0:
| row | §P0 REF | instrumented, quiet | delta |
|---|---|---|---|
| Cold workspace scan | 2 860.12–2 868.45 (mean 2 863.85) | 2 846.95 / 2 875.49 / 3 046.12 (mean 2 922.85) | +2.1 % on means; **−0.5 % excluding the first try**, which is the first cold session after a link and is an outlier by 170 ms |
| Warm workspace scan | 1 346.02–1 352.80 (mean 1 348.94) | 1 327.12 / 1 331.64 / 1 369.46 (mean 1 342.74) | **−0.5 %** |
| First useful answer, cold | 84.42–85.87 | 84.51 / 85.71 / 86.17 | +0.3 % |
| First useful answer, warm | 206.12–218.72 | 209.07 / 209.52 / 212.08 | within the REF range |
| Idle RSS, warm (max) | 575.6 MiB | 574.8 MiB | −0.1 % |
| Idle RSS, cold (max) | 535.2 MiB | 531.0 MiB | −0.8 % |
**The always-on `IndexCache` counters cost nothing measurable**: four clock
reads per file over 3 976 files is under a millisecond of a 1.3–2.9 second
scan, and every row above is inside tolerance.
## Recommendation for the lead's §P4b ruling
**The dominant measured stage is the persistent store's own I/O on a warm
start — `cache_open` + `compact`, 365.9 ms, 27.5 % of the warm settle — and
183.7 ms of that is spent by a scan that indexes zero files.** Cold is a
different problem entirely: 58.9 % of it is `parse`, and nothing on §P4b's list
touches parsing. Taking the plan's three suggestions in numbers:
**(a) avoid compaction on an unchanged store** is worth **182.4 ms warm
(13.7 %)** and ~0 cold — both warm compactions rewrite a byte-identical file
(`store_before_kib` = `store_after_kib` = 45 396, `records` 0 and 1);
**(b) shorten temporary buffer lifetimes / reduce redundant transient copies**
is worth **92.5 ms (6.9 %)** for not opening the store at all when the work
list is empty, plus **91.0 ms (6.8 %)** more if a scan may reuse the store the
previous scan of the same session already read — the second half changes
`index-persistence`'s "re-opened at the start of every whole rescan" rule and
is a contract question, not a free win; **(c) reduce repeated full merges**
is worth **nothing measurable** — there is exactly one mid-scan publish
(`publish_absorb` 4.3 ms) and one final `absorb` (218 ms), so the merge is
already done once. Against the plan's investigation goals: **warm < 1 s is
reachable but only with all of (a) and both halves of (b)** — 1 332.7 − 274.9 =
1 057.8 ms with the safe two, 966.8 ms with the third; **cold < 2.3 s is not
reachable** by anything on §P4b's list, since it would need 35 % of the parse
stage and the plan rules out parser worker parallelism without a separate
measured case; **idle RSS −15 % is not reachable** — the one retention §P4
hypothesised is real and measured at **44.20 MiB, 7.7 % of warm idle**, so
dropping it after a scan buys at most half the goal, and the rest sits in the
decoded index (457 666 reference sites, 345 127 words) where only a
representation change reaches it. If the lead rules §P4b in, the honest scope
is **"the store stops working for a scan that has no files", targeting warm
≈1.05 s and warm first-useful-answer ≈27 ms (from 209)**, with the RSS goal
restated as −8 % or dropped. One thing outside §P4's list is worth the lead's
attention on its own: **a navigation request that arrives during the configured
rescan waits 2.56 s cold / 0.90 s warm**, because the only scan that
interleaves is the empty one.
## QA log
### 2026-09-08 — QA agent (gates, no-behaviour-change, cost, arithmetic, coherence)
**Verdict: PASS.** No behaviour changed, the instrument's own cost is inside
tolerance, every headline number in this README's tables reproduces from the
dev's own `results.jsonl` (and independently, in fresh sessions run for this
QA pass), and the harness's coherence check is real. One code-organization
observation and one safety note on the §P4b recommendation are filed below;
neither is a defect in this lane, which implements no optimization.
**Gates, guarded, main tree.** `cargo fmt --all -- --check`: clean.
`cargo clippy --all-targets`: clean, `grep -rn '#\[allow' <diff>` empty — no
new `#[allow]`. `tools/guard.sh -m 8 -t 1800 -- cargo test --workspace`:
**4 272 passed, 0 failed**, matching the dev's count exactly. Compared
per-binary against a fresh clone at HEAD `8e65da1` (the commit immediately
before this lane's uncommitted diff — confirmed HEAD really is that commit):
baseline **4 262 passed**. Normalizing both logs' `Running …` / `test
result:` lines and diffing them line-for-line: the **only** difference in the
whole workspace is `lucisv_server`'s unittest binary, **1 564 → 1 574
(+10)**, exactly the ten new tests in `scan_trace.rs`
(`a_trace_that_is_off_…`, `…is_on_…`, `the_first_publish_is_…`,
`cache_work_reports_…`, `every_line_names_its_scan_…`, five in
`server/tests/scan_trace.rs`). Zero tests lost or weakened anywhere else.
Zero guard kills.
**Production line counts.** `scan_trace.rs`: 215 lines before `#[cfg(test)]
mod tests` (non-blank, non-comment) — matches the dev's figure exactly.
`index_cache.rs`: 283 lines before its `mod tests` (the `#[cfg(test)] pub fn
dir` helper at line 150 is a single test-only accessor inside the production
section, not the test module, and is excluded correctly by both the dev's
count and mine) — matches exactly. `state.rs` **grew from 988 to 1 099
non-blank/non-comment production lines (before `mod tests`), +111** —
measured against the same HEAD-8e65da1 clone with the same method. That is
more than "calls only" reads as: three new private methods appear
(`opened_trace`, `measure_work`, `landed`, roughly 60 of the 111 lines)
alongside the `trace.now()`/`ScanTrace::add(...)` call pairs threaded through
`begin_scan`/`begin_widen`/`finish_whole_scan`/`finish_widen`. `state.rs` was
already one of the files over the CLAUDE.md guidance ceiling and carries a
filed decomposition (TODO §55); this lane continues to grow it. **Not a
defect** — the three new methods are pure measurement (walks/sums/`Instant`
math), not business logic, and moving them out would need `Scan`'s and
`Workspace`'s internals exposed more widely than a single-purpose trace
module should be — but it is exactly the kind of growth the file-size rule
asks an agent to flag rather than wave through, so it is filed here for the
lead's decomposition planning rather than treated as a QA blocker.
**No behaviour change — hunks read.** Every non-trace line touched in
`state.rs`, `server/index.rs`, `server/mod.rs`, `server/client.rs`,
`candidates.rs`, `includes.rs`, `index_cache.rs`, `vlog_semantic`'s
`workspace/index.rs`/`workspace/mod.rs`/`lib.rs` is either (a) a call-site
signature growing a `trace: bool` parameter with every existing caller
passing `false` (four call sites in `state.rs`'s own tests, three in
`perf.rs`, confirmed by `git diff`), (b) an `Instant`/counter read wrapped
around an unchanged decision (`facts_for`'s hit/miss test, `record`'s
encode-then-append, `compact`'s unconditional call and its dir-then-rename
sequence are byte-for-byte the pre-existing logic), or (c) a new read-only
query (`table_sizes`, `Candidates::sizes`, `IncludeGraph::sizes`,
`IndexCache::work`/`entry_count`/`encoded_bytes`) that no existing call site
invokes. No `if trace.on()` branch anywhere skips or alters a decision that
used to run unconditionally — it only skips *measuring* it. Confirmed by
running the code, not only reading it (below).
**No behaviour change — running it.** Built the pre-lane baseline from a
clean `git clone --local` at HEAD `8e65da1ba82` (`cargo build --release
--locked -p lucisv_server -p lucisv`, guarded) and compared it against the
tree's own release binary, sha256 `08093a3a2b9c…` — the exact binary the
dev's README quotes, confirming this QA measured the same artifact.
- `scan` phase (quiet), all six (scope × cache) cells, both binaries: **every
`$/progress end` file count is identical** — 124/1/3 976 files by scope,
123/3 975 "from cache" by warmth, 3 skipped, for both binaries, every cell.
- `scopes` phase (definition/typeDefinition/hover/references/
documentHighlight/signatureHelp/inlayHint/`workspace/symbol` at the `aes`
instantiation, three scopes): **24/24 `result_count` fields identical**
between the two binaries, 0 mismatches.
- `didopen` phase (the four files the 2026-09-05 table used, including the
pinmux row) and `nav` (18 per-cursor requests): **20/20 `result_count`
fields identical**, 0 mismatches; `didOpen pinmux_reg_top.sv -> definition`
116.0 ms baseline vs 118.4 ms instrumented (single try each, §46's fix
intact, well inside session-to-session noise).
- `git -C opentitan status --porcelain` after every one of the above: always
exactly the three pre-existing modified files.
No exposed `lucisv/index` status method or wire-level fingerprint exists in
this codebase (grepped `crates/lucisv_server/src` and `crates/vlog_semantic`
for `fingerprint`/`lucisv/index`); `WorkspaceIndex::fingerprint()` is a
Rust-internal test-only tool used inside `vlog_semantic`'s own suite, not
reachable from an external LSP client. The 44/44 identical `result_count`s
above plus the file-count identity across every scope/cache cell is the
external-observer equivalent of the fingerprint check the brief asked for,
and it is a stronger check than a single hash would be — it is 44 independent
observations across three request families, and it caught nothing.
**The instrument's cost.** `scan` phase (quiet), 3 fresh sessions,
independently re-run (own `results.jsonl` under this QA's scratchpad):
cold **2 836.34 / 2 821.32 / 2 826.97 ms** (mean 2 828.2; REF mean 2 863.85,
**−1.2 %**; dev's own quiet re-take mean 2 922.85, **+2.1 %** on means but
this session's load average was lower, 4.6–7.2 vs the dev's 4.1–5.0 and the
REF's 2.9–4.6 — direction, not magnitude, is what matters here and it stayed
negative); warm **1 315.59 / 1 364.76 / 1 313.34 ms** (mean 1 331.2; REF
1 348.94, **−1.3 %**). First useful answer cold **85.46 / 87.15 / 86.87 ms**
(REF 84.42–85.87, +1–2 %); warm **208.84 / 209.82 / 210.65 ms** (inside REF
206.12–218.72). Then the **with-`--verbose` cost**, same binary, same
machine window (`scanprofile`'s per-session `settled_ms`): cold summed-scan
settle mean **2 811.2 ms** (−0.6 % vs the quiet re-take, i.e. verbose was
*not* measurably slower); warm **1 335.6 ms** (+0.3 % vs quiet). **`--verbose`
costs nothing measurable beyond noise — well under the 2 % the brief flags
as worth a finding.**
**Arithmetic, recomputed from the dev's own `results.jsonl`** (not
re-derived from prose): summing every named stage over a session's three
scans gives cold **2 794.09 ms / 96.56 %** of the 2 893.58 ms settled mean,
warm **1 262.28 ms / 94.71 %** of 1 332.72 ms — both match the README's 96.6 %
/ 94.7 % to rounding. **The empty first scan, confirmed from the raw rows**:
`workspace, warm cache, scan 1 (whole)` carries `read=0`,
`store_before_kib=store_after_kib=45396` and `cache_open=92.5`,
`compact=91.02` ms — a full open-and-rewrite of an unchanged 44.3 MiB file for
a scan that touches nothing. **Charged twice, confirmed**: scan 1 pays
`cache_open`/`compact` 92.5/91.0 ms, scan 2 (widen) pays 0.0/0.0 (it reuses
`self.cache` scan 1 left open — matches the `begin_widen` diff, which never
calls `IndexCache::open`), scan 3 (the configured whole rescan) pays a
*second* 90.96/91.37 ms and its own compaction shrinks the store back from
45410 to 45396 KiB. Sum 365.85 ≈ the README's 365.9 ms / 27.5 %.
**The empty scan is genuinely unconditional, read from source.**
`Server::started` (`server/mod.rs:373`) calls `server.scan_until_settled(false)`
*before* `server.request_configuration()` is ever sent (`server/mod.rs:399`
region) — the first whole scan cannot be gated on configuration because
configuration has not been asked for yet. `finish_whole_scan`
(`state.rs`) calls `self.cache.compact()` with no check on
`work.is_empty()` anywhere in the path. Both claims hold exactly as stated;
this is not an artifact of the test fixtures.
**First useful answer, reproduced independently** (`scanwait`, 3 fresh
sessions, own run): cold scan totals 0.57 + 85.63 = 86.2 ms against a
measured mean of 84.6 ms; warm 183.4 + 26.31 = 209.7 ms against a measured
mean of 210.5 ms — the same arithmetic the dev's README describes, holding on
an independent set of sessions with its own machine noise.
**Coherence, re-run** (`scanserve`, 3 fresh sessions per cache state):
during-scan latencies cold 82.6/84.3/85.0 ms, warm 207.9/209.1/211.3 ms;
**queued behind the configured rescan cold 2 546.7/2 562.7/2 594.6 ms, warm
888.5/892.8/931.3 ms**; after settle both states under 0.3 ms.
**`mismatched_answers = 0` across all 18 requests**, reproducing the dev's
exact finding. Read the check itself
(`tools/perf/phases_p4.py:265-268`): it takes one *settled* definition answer
after the scan goes quiet and compares every mid-scan answer's `result`
payload against it with `answer != settled_answer` — a real per-request
content comparison against the finished index's own answer, not a constant
and not a hash of an unrelated table. It is a narrower check than a full
index fingerprint (it only ever asks one cursor), but it is what an external
client can actually observe, which is what `index-scope`'s coherent-prefix
contract is about; 18 samples across 6 sessions and both cache states caught
nothing.
**Open buffers, the 100 cell** (2+ sessions, from the `scanprofile` re-run
above): settled mean 2 164.4 ms (dev 2 173.9 ms, agrees); final whole scan
(scan 4) `order` **59.2 ms** (dev 60.64 ms), `overlay + publish_overlay`
**18.34 ms** (dev's combined 19.67 ms), `overlays: 101` /
`counts.buffers: 101` confirming all 100 opened buffers plus the TB landed
via their own held analysis before the scan settled, matching the README's
"the 100 didOpens really preceded the settle" claim.
**Memory, re-taken** (`rss`, 3 fresh sessions, quiet binary): idle RSS cold
542 224/544 064/543 584 KiB = 529.5/531.3/530.8 MiB; warm 591 216/580 528/
577 888 KiB = 577.4/566.9/564.3 MiB — both agree with the dev's cold
531.0/529.0/529.9 and warm 574.8/565.2/564.8 to within session noise. **Peak
equals idle to the KiB in all six sessions again** (the 50 ms `ps -o rss=`
sampler never saw a transient above the settled reading). Store on disk
45 404 KiB (dev: 45 396 — 8 KiB of drift from repeated compactions across
sessions, immaterial). Table sizes re-read from an independent session's own
trace (`scanprofile`, scan 3 memory line): `reference_sites=457666`,
`fact_words=345127`, `cache_encoded_kib=45260`, `index_files=3976`,
`unit_names=3067` — every one identical to the dev's figures.
**The two instrument defects, verified fixed by diffing the preliminary and
final evidence files** (not just reading the work-log prose). Preliminary's
`workspace, cold cache, scan 3 (whole)` reports `cache_entries: 124` (what
the store held *before* the scan started — leftover from scan 2's widen);
the final file's same row reports `cache_entries: 3976` (what the finished
scan actually left resident, after all 3 976 records were written) — exactly
the "read at the start, not the end" bug the work log describes, now fixed.
`total_ms` differs by 1.5 ms between the two files on the same warm scan-1
row (185.26 vs 183.72), consistent with the size-walk-inflating-`total_ms`
bug being excluded after the fix. Confirmed the preliminary file's phase set
(`scanprofile`, `scan` only) **cannot** be the source of the `scanwait`/
`scanserve`/`rss` numbers quoted in this README — those phases are entirely
absent from `results-preliminary.jsonl`.
**Traceability — 15+ headline numbers checked against `results.jsonl`, all
matched, none traced to `results-preliminary.jsonl`-only fields**: scan 1
`read=0`; scan 1 warm `cache_open=92.5`/`compact=91.02`; scan 2/3 `read=124`/
`3976` (cold and warm); `cache_encoded_kib=45260`; `reference_sites=457666`;
`fact_words=345127`; the 100-buffer final scan's `order=60.64`/
`overlays=101`; `scanwait` cold `ms` array; `scanserve` cold
`mismatched_answers=0`; `rss` cold/warm `rss_kib` arrays — each an exact
field-level match, cross-checked in the section above.
**The `scan_chatter` quiet-detection fix, read** (`phases_p4.py:218-226`):
the busy test counts only `$/progress` and `textDocument/publishDiagnostics`
notifications, explicitly excluding `window/logMessage` — under `--verbose`
the server logs one such line per request, so counting it would make the
poll listen to its own noise and never terminate, which the work log and the
tracker's "Refusals / gaps" entry both describe as the first draft's actual
failure mode. Confirmed by inspection; the fixed loop terminated cleanly in
every `scanserve` session run for this QA pass.
**Handshake requests — six listed, all additive, `topo.md` untouched**
(`git diff`/`git status` on `docs/topo.md`: no changes from this lane, as
claimed): (1) `WorkspaceIndex::table_sizes() -> IndexTableSizes`; (2) the new
`scan_trace` module; (3) `trace: bool` on `begin_scan`/`begin_widen` plus
`take_scan_trace()`; (4) `Candidates::sizes`/`IncludeGraph::sizes`/
`IndexCache::work`/`entry_count`/`encoded_bytes`; (5) `Server::born` and
`Pending::Configuration`'s `Instant` payload; (6) the `verbose-timing`
amendment. `docs/features/verbose-timing/README.md` itself is untouched
(correctly left for the lead to reconcile at merge). **The "nobody parses
these lines" assumption is genuinely amended, not just asserted**: five tests
in `crates/lucisv_server/src/server/tests/scan_trace.rs` parse the emitted
lines with the same `key=value` splitting `tools/perf/phases_p4.py` uses
(`field`/`number` helpers), and `scan_trace.rs`'s own
`every_line_names_its_scan_and_is_one_line` pins the `scan N kind (…)` prefix
and the one-line-no-newline shape. The line contract is pinned by tests, not
only by convention.
**§P4b recommendation — my own safety read, beyond what the dev's hedge
already says.** `index-persistence`'s README gives **two** independent
reasons for reopening the cache at the top of every whole rescan (both also
in the `state.rs` comment the diff leaves untouched): (i) the cache
directory depends on settings (`index.cachePath`, `index.persist`) that
arrive by `workspace/configuration`, after the default-settings scan; (ii)
**a second session over the same workspace may have written records this one
has not seen** — cross-session freshness.
- **(a) skip compaction of an unchanged store** does not touch the reopen
decision at all — it only skips a rewrite when `store_before ==
store_after`/no records were written. Safe against both reasons; it never
changes *where* or *whether* the store opens, only whether an unchanged
file gets rewritten. I see no way this interacts with corrupt-store
recovery either, since `compact_now`'s temp-file-then-rename sequence is
unaffected — skipping it just means the append log stays unvacuumed a
little longer.
- **(b), first half (no store open for an empty work list), is not quite as
free as it reads.** Today only `begin_scan` (whole) calls `IndexCache::open`;
`begin_widen` never does — it relies on `begin_scan` having already opened
`self.cache` into the field a widen then reads through. If scan 1's open is
skipped outright because its work list is empty, and nothing else opens the
store before scan 2's widen runs, **the widen would silently lose every
cache hit** (all 124 files reparsed instead of served from the store) —
not a corruption, but a real regression against exactly the warm-start cost
this whole round is trying to cut, and a subtler one than "skip an
unconditional open" suggests. The 92.5 ms this half claims to save is real
only if the open is *deferred* to the first scan that actually needs the
store (i.e., moved, not dropped) — worth spelling out explicitly if the
lead rules this in.
- **(b), second half (reuse the store the session already read), is not safe
as a blanket rule against either of `index-persistence`'s two reasons.**
Against reason (i): if the pulled configuration changes `cachePath` or
flips `index.persist` between scan 1 and scan 3, reusing scan 1's
already-open cache would read/write the *wrong* directory (or keep writing
after the user asked for persistence off) for the rest of the session —
a behaviour regression against the persistence feature's own contract, not
merely a missed optimization. Against reason (ii): reusing the in-memory
store means a concurrent second session's writes between scan 1 and scan 3
are invisible to this one — but that direction is safe-but-suboptimal
(a missed cache hit still reparses correctly), never a wrong answer. My
read: **this half needs an explicit re-validation step (reuse only if the
resolved `cachePath`/`persist` are unchanged from what scan 1 opened,
reopen otherwise) before it can be called safe**, which is exactly what the
dev's own "contract question, not a free win" hedge is pointing at — I'm
narrowing which of the two documented reasons each half of (b) would
actually violate, not overturning the recommendation.
- (c) is correctly assessed as nothing to remove (one mid-scan publish, one
final absorb — verified from the same `results.jsonl` rows).
**Guard outcome.** Zero kills across every phase run for this QA pass
(gates, two release builds, and roughly a dozen guarded timed phases).
Largest resident set observed 591 MiB (7 % of the 8 GiB limit).
**Opentitan status.** `git -C opentitan status --porcelain` checked after
every phase in this QA pass (gates excluded, since no phase touches the
corpus during them): always exactly `hw/ip/aes/dv/tb/tb.sv`,
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv` —
never more, never fewer.
**Fixes made:** none needed. No code or doc changes beyond this QA log and
the TODO.md tick.
## Review
**2026-09-08 (lead, P4a).** Accepted, and the P4b ruling follows.
- The instrument is the plan's §P4a as written: disjoint stages, counters
not allocations, nothing changed in what a scan does (QA: 44/44 result
counts identical against the pre-lane binary; the stage sums re-derived).
- The structural finding is the one worth the whole stage: a workspace
session runs an empty scan at default settings before configuration
arrives, and that empty scan still opens the 45 MB store and rewrites it
byte-identically — 184 ms of a 1.33 s warm start — and the configured
scan's `compact` rewrites an unchanged store once more. That is also the
whole of the first-useful-answer gap between cold (82 ms) and warm
(208 ms).
- Warm has no dominant stage; the store's I/O is 27 % of it. Cold is 59 %
parse, which P4b may not touch; idle RSS retention is 7.7 %, so the
plan's −15 % is not on the table. The plan's goals are read honestly:
warm < 1 s reachable, the other two not.
- **Ruling, P4b — go, on exactly two of the recommendation's three:**
(a) `compact` is skipped when the session appended nothing, nothing is
gone and the loaded store was already canonical (one line per path, no
dropped lines), since the rewrite would be byte-identical; (b1) a scan
with an empty work list opens no store and compacts nothing (the open
is deferred to the first file that needs it, so the widen's hits are
untouched — QA's point). **(b2), reusing the store across rescans, is
refused:** the reopen exists for a mid-session cache-path change and for
a second session's compaction replacing the file under an append handle;
−91 ms does not buy that. Also in P4b: the configured rescan queues
navigation for 2.5 s cold / 0.9 s warm because only the empty scan
interleaves — find why, fix it if it is routing, file it if it is not;
and move the three trace helpers that landed in `state.rs` (+111 lines)
into `scan_trace.rs` as a pure move.
- Deviations accepted: `state.rs`'s growth (to be moved out in P4b); the
preliminary run kept unquoted.
+152 -16
View File
@@ -42,8 +42,8 @@ The order follows the plan. Later stages are conditional on the preceding measur
| P2d | Exact-name postings; source-set narrowing only with whole-scope proof | Reprofile P2c; topology 33 for shared module selector | dev (Opus); same release; committed 2026-09-07 → QA PASS → lead; committed 2026-09-07 | Done — no narrowing (proof negative); handshake 33 closed; warnings dedupe; tail rename 2.01× | Same README; experiment `P2d-2026-09-07` below. The census says **133 of the tail rename's 238 selected files (56 %, 58 % of the bytes, ~130 ms) write neither name down** — all of them on the container rungs. They are not droppable: they are what `fold_path` hops through for a multi-level hierarchical tail and what `base_chain` climbs, so dropping them turns a resolved tail `StillUnresolved` (a **missed edit**, §49's own feature) and, where a reference has two paths, lets it fall through onto the target (an **extra edit**). Exact-name postings not implemented: selection is **13.6 ms of 420 (3.2 %)**, below the plan's own materiality gate. The target-scoped selector — fan out from the one declaration the cursor resolves to — is filed with its full shape list as a lane of its own |
| 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 | — | Not started | — |
| P4b | Implement the dominant measured startup/memory fix | P4a; serialize with state/index changes | — | Not started | — |
| 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** |
| P5 | Parser or cancellable snapshot work only if a new measured case justifies it | Reprofile P1–P4 | — | Deferred | — |
## Before / after performance
@@ -101,12 +101,18 @@ 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 | +0.7% on means | Agrees |
| 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 | +1.2% on means | 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 | new row | Warm is 2.5× *slower* than cold to first answer — carried to P4a |
| 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`) | +0.8% on the maximum | 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 | +0.3% on the maximum | Agrees |
| 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) | new row | The resident set rises monotonically; there is no transient above idle on this workload |
| 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 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 |
| `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 |
@@ -135,9 +141,9 @@ REF and part of each delta is §P1b's.
| Ambiguous-use all-sources fallback frequency | Not measured | Not measured — P2a | **Measured, §P2a.** Of the eight renames the `renametrace` phase walks, **four** take the whole scope: a common port name (`clk_i`, whose declarations carry ambiguous references), a duplicate module name (`rstmgr_por`, declared in four files), a new name a great many external uses spell, and a cursor on no symbol at all (which `rename.rs` answers with `ws.sources()` outright, without consulting the ladder). Each costs a **3 976-file / 35.8 MB** `Scope::build`, ~1 840 ms, before anything else happens |
| Per-file parses for CLI census and lint | Multiple paths confirmed; runtime counts unmeasured | Not measured — P3 | **Counted by construction, §P3.** Before: an all-style run over `hw/ip` did 1 805 `ParsedSource::parse` (the interface census) + 1 805 `WorkspaceIndex::build` (each a lex + parse + analyse + record) + 1 805 lint parses = **5 415 whole-file parses**. After: 1 805 census parses + **181** analyses (no parse — the record is read off the census's own tree, and only for the files whose AST holds a `package` item) + 1 805 lint parses = **3 610 parses + 181 analyses**. The third parse, the lint pass's own, is untouched and is the remaining duplicate |
| CLI package-census vs unused-import body time | Combined 123 ms wall increment; stages unseparated | Increment reproduced on the same binary at **137 ms, 23.3% of all-style** (means 0.587 vs 0.450 s, three trials, alternating order, stdout hashes identical to baseline). Stages still unseparated — P3 | **Separated, §P3.** The increment is **141.7 ms** on a same-toolchain trunk build and **5.0 ms** on the candidate: the census's per-file index build was **136.7 ms of it, 96%**, and the rule body plus the surviving 181-file census is the remaining **5.0 ms (1.0% of all-style)**. Measured as the paired difference `all-style − (all-style with --ignore unused-import)` on each binary, six alternating trials |
| Startup discovery / hash / decode / merge / candidates / includes / compact | Only combined scan time measured | Still only combined — P4a. P0 adds the scan's *other* half: first useful answer, cold **84.42–85.87 ms** vs warm **206.12–218.72 ms**, and the settle of those same perturbed sessions (cold 2855–2877, warm 1340–1358 ms) | — |
| Peak server RSS during startup and refactoring | Idle RSS only; peak unmeasured | **Startup peak measured** (`peak_rss_kib`, `ps -o rss=` at 50 ms across the scan): 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, i.e. no transient above idle. Refactoring peak still unmeasured — P2a | **Measured, §P2a, and re-measured at §P2b/§P2c** (MiB, `ps -o rss=` at 50 ms across each rename): tail 590 → 610 → 593; `aes` 582 → 577 → 585; unique internal 570 → 579 → 579; **`clk_i` fallback 1 864 → 1 840 → 1 830**; conflict 647 → 639 → 641; `cipher_alert → clk_i` **1 809 → 1 695 → 1 590**; `rstmgr_por` fallback 922 → 901 → 927; no-symbol 914 → 905 → 918. **No row's peak rose by more than 20 MiB and the two heaviest fell** — retention is bounded to the files the request was going to analyse anyway |
| First useful response during scan; open buffers 1 / 10 / 100 | Not measured in this round | **First useful response measured** (above), each session a fresh process, kept in separate sessions from the settled rows so the settled series stays comparable. Open buffers 1 / 10 / 100 not measured — P4a | — |
| Startup discovery / hash / decode / merge / candidates / includes / compact | Only combined scan time measured | Still only combined — P4a. P0 adds the scan's *other* half: first useful answer, cold **84.42–85.87 ms** vs warm **206.12–218.72 ms**, and the settle of those same perturbed sessions (cold 2855–2877, warm 1340–1358 ms) | **Separated, §P4a**, by the server's own trace (three `timing: scan <n> …` lines under `--verbose`; `docs/features/perf5-p4/README.md` holds the field list). Every stage the gate names, in ms, summed over a session's scans — **warm** (settle 1 332.7): discovery 255.91, hash/`lookup` 51.31, decode 202.75, merge/`absorb` 218.08 + 4.34 mid-scan, candidates 113.34, includes 46.30, `cache_open` 183.46, `compact` 182.39, parse 0.00, overlay 0.15 + 0.05; **cold** (settle 2 893.6): parse 1 703.63, discovery 299.59, absorb 218.40 + 4.41, encode 183.26, store_write 118.46, candidates 110.66, compact 93.89, includes 45.52, decode 5.87, cache_open 3.39, lookup 2.86. The trace accounts for **94.7 % warm / 96.6 % cold** of the settle; the remainder is the scan loop and the per-file callbacks, left unattributed rather than folded into a neighbour. Counts on every row: read / read_kib / skipped / hits / misses / buffers / records / decoded_kib / written_kib / publishes / published / first_publish / overlays |
| Peak server RSS during startup and refactoring | Idle RSS only; peak unmeasured | **Startup peak measured** (`peak_rss_kib`, `ps -o rss=` at 50 ms across the scan): 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, i.e. no transient above idle. Refactoring peak still unmeasured — P2a. **P4a re-measures startup**: cold 531.0 / 529.0 / 529.9 MiB, warm 574.8 / 565.2 / 564.8, peak equal to idle to the KiB in all six sessions again, and the scan's 34.15 MiB of held source text is released before idle | **Measured, §P2a, and re-measured at §P2b/§P2c** (MiB, `ps -o rss=` at 50 ms across each rename): tail 590 → 610 → 593; `aes` 582 → 577 → 585; unique internal 570 → 579 → 579; **`clk_i` fallback 1 864 → 1 840 → 1 830**; conflict 647 → 639 → 641; `cipher_alert → clk_i` **1 809 → 1 695 → 1 590**; `rstmgr_por` fallback 922 → 901 → 927; no-symbol 914 → 905 → 918. **No row's peak rose by more than 20 MiB and the two heaviest fell** — retention is bounded to the files the request was going to analyse anyway |
| First useful response during scan; open buffers 1 / 10 / 100 | Not measured in this round | **First useful response measured** (above), each session a fresh process, kept in separate sessions from the settled rows so the settled series stays comparable. Open buffers 1 / 10 / 100 not measured — P4a | **Both measured, §P4a.** The first useful response is now *explained* rather than only measured (the row above). Open buffers 1 / 10 / 100, warm workspace: settle **1 841.6 / 1 859.1 / 2 173.9 ms**, a fourth scan (a 1 685-file widen, 352–372 ms), overlay refresh **0.31 / 1.33 / 19.67 ms**, `order` **1.30 / 3.97 / 60.64 ms**. Also new: requests arriving *during* a scan (`scanserve`), three modes and 0 mismatched answers |
| Actual inline/extract command time and applyEdit payload | Not measured; existing resolve rows invalid for this purpose | **Measured, phase `execute`.** `lucisv.extractModule` (`aes.sv` 220:0–222:53): 257.33 / 245.05–247.00 ms from `executeCommand` to `workspace/applyEdit`, payload 2 edits / 2 files / 1 created, label `lucisv: lucisv.extractModule`, fingerprint `090e92e7736e…`, declined with `applied: false` (status `capture`), delivery half 0.015–0.033 ms. `lucisv.inlineModule` (`aes_wrap.sv` 66:2) **refused** (`generate` construct) in 6.58 / 5.87–6.20 ms; the extract offer at that same cursor **refused** after 817.37 / 793.77–809.07 ms. Take 4's `*-module resolve` rows are removed, not reinterpreted | — |
| First offer after didChange vs repeated unchanged offer | Separate distribution needed | Not measured. Every row separates the *first request of a session* from its repeats, but no row yet issues a `didChange` and then re-offers — P1's measurement | **Measured, new phase `offeredit`** (`tools/perf/phases_p1.py`): three `didChange` → `codeAction` pairs, then three repeats at the same cursor in the same session. P1b medians — pinmux **133.86** first-after-edit against **24.18** repeated; `aes_reg_top` instance **22.66** against **21.65**; `tb.sv` comment **1.95** against **0.54**. So on the generated file the edit itself (one `Document::new`: lex, parse, analyze, resolve, line-index 1.3 MB) is ~110 ms and dwarfs the offer; on ordinary files the two are within 1 ms |
@@ -156,11 +162,11 @@ this stage; each says so rather than being left ambiguous.
| Refactor verification | Token identity, semantic identity, parse-diagnostic preservation, comments/attributes, span remapping | **P2: the checks are untouched; their inputs changed.** `Print`, `print`, `Shifts`, `Excluded`, `watched_files`, `tokens_match`, `first_difference`, the `ledger` and the parse-diagnostic comparison are the same code and the same comparisons; what moved is where a `Semantics` and an after-index come from (`check/after.rs`, new). Every existing attack still refuses — `check::tests`' eight `tokens_match` pairs, `check/ledger.rs`'s, `removing_an_import_a_reference_needs_is_rejected`, the `rename/tests.rs` refusals — and **three new attack pairs aimed at the reuse** were added and pass: a stale retained analysis (`a_rename_whose_edit_rebinds_a_name_in_the_edited_file_is_refused`), an after-index that forgot an unedited file (`a_rename_that_would_make_a_third_files_use_ambiguous_is_refused`), and shifted file ids (`a_print_names_paths_so_shifted_file_ids_cannot_change_it`). Not applicable at P0 — the engine's verifiers are untouched. **Unchanged at P1**: nothing below the four gates moved; `extract_module`, `inline_module`, `organize_imports`, `port_actions` and `check::verify` are the same code, and `vlog_refactor`'s own suites are green. **P1c: still unchanged where it matters.** `check::verify_splice`, `check::verify` and `ports::confirm` are untouched, and every resolve/execute path still runs them — the three resolve rows measured above carry fingerprints byte-identical to the REF's. The *offer* predicates deliberately do not run them; that is the only widening, it is confined to a menu, it was already the lazy offer's stated contract, and the every-offset parity suites find **zero** cursors on their fixtures where it changes the answer |
| CLI output | Compare full findings/fixes/waivers/exit codes, not just counts; disabled-rule run stays attribution-only | **Passed.** stdout sha256 of all five configurations byte-identical to the baseline's; exit codes 1 (lint findings) / 2 (four pre-existing format failures) as before; the `--ignore unused-import` run is recorded as attribution only. **P3: passed again, this time against a changed binary** — the candidate's stdout is byte-identical to the reference's on all five cells (`hw/ip` default 445, all-style 7 751 including 17 `unused-import`, minus rule 7 734; `hw/vendor` 1 666; `hw/dv` 1 158), `diff`ed as files. Exit codes unchanged. The `--ignore unused-import` run stays the attribution control and is never quoted as the optimization |
| Index parity | Fresh/incremental/absorbed fingerprints, unsaved wins, coherent partial publication, scope/filelist/rootless behavior | **P2c pins the absorbed-against-fresh equality where the verifier now stands on it**: `an_absorbed_after_index_is_the_index_a_rebuild_would_give` compares fingerprint, file list **and** a query-level print (`units`, `references_to`, `instantiations_of`, `hierarchical_declarations`, `workspace_symbols`) on nine cases including a file gaining and losing a declaration, an edit that changes what another file resolves to, a re-export chain, an edited package and a file that stops lexing; `absorbing_an_edited_file_keeps_every_file_id` pins id stability; `an_index_from_analyzed_facts_is_the_index_a_build_gives` pins the §P2b assembly. Not applicable at P0. Store size unchanged at 44.34 MiB and the scan's own `$/progress` end messages recorded per cell (`124 → 3976 files indexed, 3975 from cache, 3 skipped` warm) |
| Persistence | Corrupt/truncated/old-format stores rebuild safely; interrupted writes; content hash retained | Not applicable at P0 |
| Resources | Guard outcomes, idle and peak memory, allocated/actual store size, stack-size requirement | **P2: zero guard kills** across nineteen timed phases and every `cargo` gate; largest resident set **1 864 MiB** (23 % of the 8 GiB limit), on the §P2a all-sources fallback — and §P2b/§P2c *lowered* it. Peak RSS re-measured per rename at all three stages (the row above); no row rose by more than 20 MiB. The one new retention is a request-local `HashMap<usize, Semantics>` bounded to the files whose text spells one of the two names, which are the files the request analyses anyway. No new parsing thread, so the 16 MiB stack contract is untouched. **Passed.** Every run under `tools/guard.sh -m 8 -t 1800`; **zero kills**; largest resident set 575.6 MiB (7% of the limit). Idle *and* peak RSS now recorded in their own KiB fields; store 44.34 MiB. **P1: zero guard kills** across ten timed runs and every `cargo` gate. Memory not re-measured (P4a's phase); the only new retention is one `Vec<Region>` per open buffer that ever needed a fence answer. No new parsing thread, so the 16 MiB stack contract is untouched |
| Formatting | `cargo fmt --all -- --check`, appropriate formatter snapshot/idempotency and corpus gates | **P2: `cargo fmt --all -- --check` clean** at every stage; the formatter is not on this change's path (`vlog_formatter` is untouched) and its suite ran green inside each workspace run. `python3 -m py_compile tools/perf/*.py` clean for the new `phases_p2.py`. Not applicable at P0 — no Rust changed, and no `cargo` command may run during a timed round. `python3 -m py_compile tools/perf/*.py` and `bash -n tools/perf/*.sh` clean. **P1: `cargo fmt --all -- --check` clean; `cargo test -p vlog_formatter` green inside the workspace run** (the formatter is not on this change's path — `fence.rs` is untouched — but it was run anyway). `python3 -m py_compile tools/perf/*.py` clean for the new phase |
| Lint/tests | Guarded affected tests then clippy/workspace tests at integration, no benchmark overlap | **P2: guarded `cargo test --workspace` green before every release build — 4 215 (before the lane) → 4 225 (§P2b) → 4 231 (§P2c), 0 failed, no test removed or weakened**; guarded `cargo clippy --all-targets` clean at each stage with **no new `#[allow]`**; `cargo fmt --all -- --check` clean. **No `cargo` command ran during any timed phase**: each stage built once, to completion, then measured. Not applicable at P0 (no Rust). No benchmark overlapped a build. **P1: `cargo clippy --all-targets` clean at both stages** (one `needless_borrow` introduced by the P1b diff was fixed; **no new `#[allow]`**), `cargo test --workspace` green before each stage's build, all guarded. **No cargo command ran during any timed phase**: each stage built once, to completion, then measured. **Second lane (H33/P2d): guarded `cargo test --workspace` 4 231 → **4 248 passed / 0 failed** (+17, none removed or weakened); guarded `cargo clippy --all-targets` clean with **no new `#[allow]`**; `cargo fmt --all -- --check` clean; one release build, then eight timed phases with no `cargo` running; zero guard kills; corpus unchanged after every phase.** **P1c: `cargo fmt --all -- --check` clean, guarded `cargo clippy --all-targets` clean, guarded `cargo test --workspace` **4215 passed / 0 failed** (4194 at P1b, +21), then one guarded release build, then four timed phases with no cargo running; zero guard kills; corpus unchanged after every phase. One new `#[allow(clippy::too_many_arguments)]`, on `imports::planned`, with the reason on the line |
| Documentation | Feature README, handshake updates in topo, accepted numbers in perf README; reserved lead Review untouched by dev | **P2: `docs/features/perf5-p2/README.md` created** with all seven sections, QA and Review left empty, the work log kept as the work went. **`topo.md` is not edited by this lane** — four additive edges (`FileFacts::analyzed`; `vlog_refactor::rename_traced` and its trace values; the server's `rename_trace` module; `rename::rename_traced` / `Workspace::rename_sources_traced` replacing their untraced forms at the one production call site) are written as requests in that README's Handshakes for the lead to apply. `docs/perf/README.md` untouched until the lead accepts these numbers. **Done.** `docs/features/perf5-p0/README.md` created with the required sections (QA and Review left empty); no `topo.md` edge changed because no interface changed; `docs/perf/README.md` carries a note that two take-4 row *meanings* are superseded. **P1: `docs/features/perf5-p1/README.md` created** with all seven sections, QA and Review left empty, the work log kept as the work went. `topo.md` is **not** edited by this lane — the two additive edges (`vlog_parser::stats`, the four `vlog_refactor` `*_in` selectors, the server's `fences` module) are written as requests in that README's Handshakes for the lead to apply. `docs/perf/README.md` untouched until the lead accepts these numbers. **P1c: the same README gains a P1c section in Goal, Handshakes, Status and Work log**, a dated empty QA heading, and two further handshake requests for the lead — the `port_offers` / `organize_offer` topo edges, and a `vlog_semantic` request to expose a `FileFacts` built from an existing analysis (worth ~0.8 ms of the organize-imports offer). Review still untouched by the dev |
| Persistence | Corrupt/truncated/old-format stores rebuild safely; interrupted writes; content hash retained | Not applicable at P0. **P4a: the store's behaviour is unchanged and its counters are new.** `open`, `facts_for`, `record` and `compact` take the same decisions over the same bytes — the content hash is still the whole key, a record that no longer decodes is still a miss, `compact` still writes to a temp file and renames — and what was added is timing/byte counters and a rename of the body to `compact_now` behind a measuring wrapper. `index_cache.rs`'s own suite (including the truncate-at-every-offset attack) is green |
| Resources | Guard outcomes, idle and peak memory, allocated/actual store size, stack-size requirement | **P2: zero guard kills** across nineteen timed phases and every `cargo` gate; largest resident set **1 864 MiB** (23 % of the 8 GiB limit), on the §P2a all-sources fallback — and §P2b/§P2c *lowered* it. Peak RSS re-measured per rename at all three stages (the row above); no row rose by more than 20 MiB. The one new retention is a request-local `HashMap<usize, Semantics>` bounded to the files whose text spells one of the two names, which are the files the request analyses anyway. No new parsing thread, so the 16 MiB stack contract is untouched. **Passed.** Every run under `tools/guard.sh -m 8 -t 1800`; **zero kills**; largest resident set 575.6 MiB (7% of the limit). Idle *and* peak RSS now recorded in their own KiB fields; store 44.34 MiB. **P1: zero guard kills** across ten timed runs and every `cargo` gate. Memory not re-measured (P4a's phase); the only new retention is one `Vec<Region>` per open buffer that ever needed a fence answer. No new parsing thread, so the 16 MiB stack contract is untouched. **P4a: zero guard kills** across five timed phases, the workspace test run, clippy and two release builds; largest resident set **574.8 MiB (7 % of the limit)**. Idle *and* peak RSS re-measured (cold 531.0/529.0/529.9, warm 574.8/565.2/564.8 MiB; peak equal to idle to the KiB), store 44.34 MiB, and the retentions that explain them are now numbers rather than hypotheses (encoded facts **44.20 MiB**, scan-held source text **34.15 MiB**). The only new retention is one `ScanTrace` per scan — a fixed-size bag of counters — and a `Cell<CacheWork>` on the cache. No new parsing thread |
| Formatting | `cargo fmt --all -- --check`, appropriate formatter snapshot/idempotency and corpus gates | **P2: `cargo fmt --all -- --check` clean** at every stage; the formatter is not on this change's path (`vlog_formatter` is untouched) and its suite ran green inside each workspace run. `python3 -m py_compile tools/perf/*.py` clean for the new `phases_p2.py`. Not applicable at P0 — no Rust changed, and no `cargo` command may run during a timed round. `python3 -m py_compile tools/perf/*.py` and `bash -n tools/perf/*.sh` clean. **P1: `cargo fmt --all -- --check` clean; `cargo test -p vlog_formatter` green inside the workspace run** (the formatter is not on this change's path — `fence.rs` is untouched — but it was run anyway). `python3 -m py_compile tools/perf/*.py` clean for the new phase. **P4a: `cargo fmt --all` clean; `python3 -m py_compile tools/perf/phases_p4.py` clean.** The formatter is not on this change's path and its suite ran green inside the workspace run |
| Lint/tests | Guarded affected tests then clippy/workspace tests at integration, no benchmark overlap | **P2: guarded `cargo test --workspace` green before every release build — 4 215 (before the lane) → 4 225 (§P2b) → 4 231 (§P2c), 0 failed, no test removed or weakened**; guarded `cargo clippy --all-targets` clean at each stage with **no new `#[allow]`**; `cargo fmt --all -- --check` clean. **No `cargo` command ran during any timed phase**: each stage built once, to completion, then measured. Not applicable at P0 (no Rust). No benchmark overlapped a build. **P1: `cargo clippy --all-targets` clean at both stages** (one `needless_borrow` introduced by the P1b diff was fixed; **no new `#[allow]`**), `cargo test --workspace` green before each stage's build, all guarded. **No cargo command ran during any timed phase**: each stage built once, to completion, then measured. **Second lane (H33/P2d): guarded `cargo test --workspace` 4 231 → **4 248 passed / 0 failed** (+17, none removed or weakened); guarded `cargo clippy --all-targets` clean with **no new `#[allow]`**; `cargo fmt --all -- --check` clean; one release build, then eight timed phases with no `cargo` running; zero guard kills; corpus unchanged after every phase.** **P1c: `cargo fmt --all -- --check` clean, guarded `cargo clippy --all-targets` clean, guarded `cargo test --workspace` **4215 passed / 0 failed** (4194 at P1b, +21), then one guarded release build, then four timed phases with no cargo running; zero guard kills; corpus unchanged after every phase. One new `#[allow(clippy::too_many_arguments)]`, on `imports::planned`, with the reason on the line. **P4a: guarded `cargo test --workspace` **4 272 passed / 0 failed** (4 262 before the lane, +10 new, none removed or weakened); guarded `cargo clippy --all-targets` clean with **no new `#[allow]`**; `cargo fmt --all` clean; then one release build, then five timed phases with no `cargo` running; zero guard kills; corpus unchanged after every phase** |
| Documentation | Feature README, handshake updates in topo, accepted numbers in perf README; reserved lead Review untouched by dev | **P2: `docs/features/perf5-p2/README.md` created** with all seven sections, QA and Review left empty, the work log kept as the work went. **`topo.md` is not edited by this lane** — four additive edges (`FileFacts::analyzed`; `vlog_refactor::rename_traced` and its trace values; the server's `rename_trace` module; `rename::rename_traced` / `Workspace::rename_sources_traced` replacing their untraced forms at the one production call site) are written as requests in that README's Handshakes for the lead to apply. `docs/perf/README.md` untouched until the lead accepts these numbers. **Done.** `docs/features/perf5-p0/README.md` created with the required sections (QA and Review left empty); no `topo.md` edge changed because no interface changed; `docs/perf/README.md` carries a note that two take-4 row *meanings* are superseded. **P1: `docs/features/perf5-p1/README.md` created** with all seven sections, QA and Review left empty, the work log kept as the work went. `topo.md` is **not** edited by this lane — the two additive edges (`vlog_parser::stats`, the four `vlog_refactor` `*_in` selectors, the server's `fences` module) are written as requests in that README's Handshakes for the lead to apply. `docs/perf/README.md` untouched until the lead accepts these numbers. **P1c: the same README gains a P1c section in Goal, Handshakes, Status and Work log**, a dated empty QA heading, and two further handshake requests for the lead — the `port_offers` / `organize_offer` topo edges, and a `vlog_semantic` request to expose a `FileFacts` built from an existing analysis (worth ~0.8 ms of the organize-imports offer). Review still untouched by the dev. **P4a: `docs/features/perf5-p4/README.md` created** with all seven sections, QA and Review left empty, the work log kept as the work went. `topo.md` is **not** edited by this lane — the additive edges (`vlog_semantic::WorkspaceIndex::table_sizes` / `IndexTableSizes`; the server's `scan_trace` module; the `trace: bool` on `begin_scan`/`begin_widen` and `Workspace::take_scan_trace`; `Candidates::sizes` / `IncludeGraph::sizes`; `IndexCache::work`/`entry_count`/`encoded_bytes`) are written as requests in that README's Handshakes for the lead to apply, together with the amendment to `verbose-timing`'s "nobody parses these lines" assumption. `docs/perf/README.md` untouched until the lead accepts these numbers |
## Experiment record — P0-2026-09-07 (stage P0)
@@ -1481,6 +1487,136 @@ this stage; each says so rather than being left ambiguous.
re-use of a parse the census already paid for.
- **QA result and lead review link:** QA pending.
## Experiment record — P4a-2026-09-07 (stage P4a)
- **Experiment ID / stage / date / owner:** `P4a-2026-09-07` / P4a (TODO
§60.4) / 2026-09-07, America/Chicago / dev agent (Opus).
- **Hypothesis and exact expected work reduction:** none — **this is a
measurement lane and it implements no optimization**. The hypothesis under
test is the plan's own §P4 sentence, that a warm start's cost is spread
across reading text to hash it, decoding records, merging tables, building
the completion/include tables and refreshing overlays, "their individual
time/memory shares unmeasured", plus its memory hypothesis that `IndexCache`
retains encoded facts beside the decoded index. The expected *output* is a
per-stage attribution accounting for most of the settle, and a number for
that retention.
- **Binary / provenance:** release `lucisv-server` sha256
`08093a3a2b9c0b8796e5f9214ac7bda59e068e49e32a9c2393f29d116fca10bd`, built
once under `tools/guard.sh -m 8 -t 1800` before any timing; no `cargo`
command ran during a timed phase. An earlier release of the same lane
(`ca5910bf1434…`) was measured, two instrument defects were found in its
output — `total_ms` included the size-measuring walks, and the cache
retention was read at the *start* of a scan rather than the end — both fixed
and everything re-measured on `08093a3a…`. The earlier run is kept as
`~/.cache/lucisv-perf/take5-p4/results-preliminary.jsonl` and **is not
quoted**.
- **Corpus / machine:** opentitan `00981352642fb65ef2b6c47143a0f6bb31fd4a97`
with its three pre-existing modified files, verified `git status
--porcelain` after every phase and unchanged throughout. Same M1 Max,
macOS 27.0. One-minute load **4.1–5.0** during the timed phases (the §P0 REF
was taken at 2.92–4.59, so this round is slightly busier — recorded, not
adjusted for). Scratch caches and `storagePath` under the session scratchpad;
results in `~/.cache/lucisv-perf/take5-p4/results.jsonl`.
- **What changed in the tree:** new `crates/lucisv_server/src/scan_trace.rs`
(the trace type and its three lines); calls only in `state.rs`; counters in
`index_cache.rs` (`Cell<CacheWork>`, always on: the hash/decode split needs a
`&self` site); `Candidates::sizes` and `IncludeGraph::sizes`; an additive
`WorkspaceIndex::table_sizes` in `vlog_semantic` (no codec change,
`FACTS_FORMAT` untouched); the emit sites in `server/index.rs` and the config
round-trip line in `server/client.rs`; `Server::born` and a payload on
`Pending::Configuration` in `server/mod.rs`; a new phase file
`tools/perf/phases_p4.py`. **No behaviour changed.** Off is the shipped
state: without `--verbose` no line is sent, no clock is read in `state.rs`,
and no size is walked.
- **Phases run:** `scan` (the tolerance check, on the *quiet* binary),
`scanprofile`, `scanwait`, `scanserve`, `rss`. Three fresh sessions per cell.
- **Result — the structural finding:** **a workspace session pays three
scans**, and the first indexes **zero files**. `Server::started` builds the
index at the default settings before `initialized` can bring any; the folder
scope is derived from directories a buffer has been opened from, and none
has. The 124-file "default scan" the plan expected is the **widen** the first
`didOpen` triggers. Warm, the empty scan 1 still costs **183.7 ms** — it
opens the 44.3 MiB store (`cache_open` 92.5 ms) and then compacts it
(`compact` 91.0 ms), rewriting 45 396 KiB into a byte-identical file, because
`finish_whole_scan` compacts unconditionally.
- **Result — warm, settled mean 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 %**. **No dominant stage** — the top five are within 1.4×
— but `cache_open` + `compact` is **365.9 ms, 27.5 % of the warm settle**.
- **Result — cold, settled mean 2 893.6 ms:** parse **1 703.63** (58.9 %),
discovery 299.59, absorb 218.40, encode 183.26, store_write 118.46,
candidates 110.66, compact 93.89, includes 45.52, decode 5.87, cache_open
3.39, lookup 2.86. Named total 2 794.09 = **96.6 %**. Cold and warm are
different problems.
- **Result — the §P0 first-answer puzzle, closed:** cold 0.54 + 81.58 =
**82.1** against a measured 83.4 / 85.7 / 84.9; warm 181.19 + 26.31 =
**207.5** against 208.7 / 208.9 / 209.2. The definition is answered when the
widen the `didOpen` triggered ends. Cold that wait is the widen's 123 parses;
warm the widen is 3× cheaper but the **empty startup scan ahead of it has
spent 181 ms on store I/O**. So it is the config wait — specifically that
scan's store I/O — and neither the publish cadence nor the decode.
- **Result — memory:** idle RSS cold 531.0 / 529.0 / 529.9 MiB, warm 574.8 /
565.2 / 564.8; peak equal to idle to the KiB in all six sessions again. The
plan's retention hypothesis is **confirmed and quantified**: `IndexCache`
holds **45 260 KiB = 44.20 MiB** of encoded facts beside the decoded index,
**7.7 % of warm idle RSS**. The scan additionally holds **34 973 KiB =
34.15 MiB** of source text for its whole life, released at `finish_scan` and
therefore absent from idle. Index sizes: 3 976 files, 3 067 unit names /
4 013 declarations, 91 894 connection members, 56 913 hierarchical members,
59 529 reference keys / **457 666 reference sites**, 1 358 defines, 13 894
instantiation edges, 345 127 census words (4.64 MiB); completion tables
50 726 units / 658 macros / 105 042 words (1.84 MiB); include graph 1 984
edges over 3 976 known files.
- **Result — open buffers 1 / 10 / 100:** settle 1 841.6 / 1 859.1 /
**2 173.9 ms**; a **fourth** scan appears (a second widen, 352–372 ms, 1 685
files). Overlay refresh **0.31 / 1.33 / 19.67 ms** — *not* the cost. What
scales is `order` (`open_first`), **1.30 / 3.97 / 60.64 ms**, one linear scan
of a 3 976-entry work list per buffer.
- **Result — requests during a scan:** three distinct modes, not a spread.
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. **Table coherence: `mismatched_answers` = 0 across all 18
requests** — every mid-scan answer named exactly what the settled index names
or was empty. The row's status turns `error` if that is ever violated.
- **Tolerance of the instrumented binary (quiet, no `--verbose`):** warm scan
**−0.5 %** on means against the §P0 REF, cold **+2.1 %** on means and
**−0.5 %** excluding a first-try outlier 170 ms above its own siblings;
first useful answer cold +0.3 %, warm inside the REF range; idle RSS −0.8 %
cold, −0.1 % warm. The always-on `IndexCache` counters (four clock reads per
file over 3 976 files) cost under a millisecond of a 1.3–2.9 s scan.
**Within tolerance; no re-work needed.**
- **Recommendation for §P4b (the lead rules, not this lane):** the dominant
measured stage is the store's own I/O on a warm start. (a) **Avoid
compaction on an unchanged store: −182.4 ms warm, 13.7 %**, ~0 cold — both
warm compactions rewrite a byte-identical file. (b) **Do not open the store
for a scan with an empty work list: −92.5 ms, 6.9 %**; reusing a store the
session already read is another **−91.0 ms, 6.8 %**, but that amends
`index-persistence`'s "re-opened at the start of every whole rescan" rule and
is a contract question. (c) **Reduce repeated full merges: nothing to
remove** — one mid-scan publish (4.3 ms) and one final absorb (218 ms).
Against the plan's goals: **warm < 1 s reachable** (1 057.8 ms with (a) and
the safe half of (b); 966.8 ms with all three); **cold < 2.3 s not
reachable** by anything on §P4b's list — it needs 35 % of a parse stage the
plan rules out touching; **idle RSS −15 % not reachable** — the retention is
real but is 7.7 %, and the rest is in the decoded index where only a
representation change reaches it. Outside §P4's list and worth the lead's
attention: **navigation queued behind the configured rescan waits 2.56 s cold
/ 0.90 s warm**, because the only scan that interleaves is the empty one.
- **Guard outcome:** zero kills across five timed phases, the workspace test
run, clippy and two release builds. Largest resident set observed 574.8 MiB
(7 % of the 8 GiB limit).
- **Refusals / gaps:** `scanserve`'s first draft never terminated — under
`--verbose` the server logs a line per request, so a "has the server gone
quiet" test that counted every notification was listening to itself. Fixed
to count `$/progress` and `publishDiagnostics` only, and the phase re-run;
the abandoned run produced no rows. `cache_entries` / `cache_encoded_kib` are
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 — copy for every stage or rejected attempt
- Experiment ID / stage / date / owner:
+6
View File
@@ -21,6 +21,7 @@ and take 5 §P0 (TODO §60.0) corrected what some rows *meant*: see
| `phases_p0.py` | take 5 §P0's phases: `execute` (what an extract/inline command really costs), `offerkinds` (the `context.only` families), `offerqueue` (leader/follower), and `scan`'s first-useful-answer half |
| `phases_p1.py` | take 5 §P1's phase: `offeredit` — the first offer after a `didChange` beside the repeated offer on the unchanged buffer, at the same cursor in the same session |
| `phases_p2.py` | take 5 §P2's phase: `renametrace` — eight renames, each with the server's own `timing: rename trace …` line read back off `window/logMessage` and written out as row fields (which rung selected each file, per-stage ms, per-stage **whole-file parse counts**) beside the wire time and the peak RSS |
| `phases_p4.py` | take 5 §P4a's phases: `scanprofile` (the startup breakdown, one row per traced scan), `scanwait` (the first useful answer with that session's own trace beside it) and `scanserve` (a definition every 200 ms for as long as the scan runs, with the mid-scan/settled answer coherence check) |
| `sweep.sh` | the timed CLI sweeps (`format --check`, `check`) over five trees, `/usr/bin/time -l` |
| `sweeptable.py` | those logs → the document's §7 Markdown table, plus the format-cache hits each try reported |
| `outcomes.sh` | the untimed per-file outcome runs, for the release-to-release outcome diff |
@@ -81,6 +82,9 @@ apart in `results.jsonl`; run each phase once per binary.
| `offerqueue` | §P0 | the pinmux no-offer comment as leader, an `aes` definition as follower, in separate fields |
| `offeredit` | §P1 | two rows per cursor: `didChange` → `codeAction`, three times over, then three `codeAction`s on the unchanged buffer. §P1b's whole claim is about the second, so the first is never allowed to hide inside it |
| `renametrace` | §P2 | eight renames — the tail, `aes`, a unique internal name, a common port name, a conflicting new name, a new name many external uses spell, a duplicate module name and a cursor on no symbol — each in its own `--verbose` session, with the engine's stage trace parsed out of the log into `trace_*` row fields and peak RSS sampled across the request. **A rename's input is not its output**: the row says how many files went in, how many bytes, which rung asked for each, and how many whole-file parses the request ran |
| `scanprofile` | §P4a | the startup breakdown, from the server's own `timing: scan <n> stages/counts/memory` lines: workspace cold and warm, the default scope, `scopeDepth 0`, and 1 / 10 / 100 open buffers. **One row per traced scan** — a session at a configured scope pays two (the startup scan runs at the default settings and the pulled scope asks for another), and adding them together would be wrong |
| `scanwait` | §P4a | §P0's first-useful-answer rows, re-run under `--verbose`, so the trace of the very session that answered sits in the row: when the first publish landed, how many publishes there were, how long the config round trip took |
| `scanserve` | §P4a | a `textDocument/definition` every 200 ms for as long as the scan is still saying anything: the mid-scan latency distribution, and `mismatched_answers` — non-empty answers that named somewhere the settled index does not, which must be 0 (the coherence contract of `docs/features/index-scope/README.md`) |
| `probe` | — | ad-hoc: `--probe FILE:LINE:CHAR` (0-based) prints what a cursor offers. This is how `sites.REFACTOR_SITES` was found |
## The CLI sweeps
@@ -147,6 +151,8 @@ file; `schema.py` is the vocabulary for new rows.
| `fingerprint` | sha256 over the sorted `(uri, start, end, newText)` edits, the sorted created paths and the sorted warnings — two runs' refactorings compared without copying corpus text out |
| `rss_kib` / `peak_rss_kib` / `store_kib` | idle resident set, the maximum of a 50 ms `ps -o rss=` poll across the scan, and `du -sk` of the index store |
| `leader_ms` / `follower_ms` | a pipelined pair, each in its own field |
| `stages` / `counts` / `memory` | §P4a's three trace lines, parsed into dicts: per-stage ms, per-stage work counts, and the sizes the finished scan left resident. `ms` on such a row is the scan's own `total`, and `settled_ms` is every try's wall clock |
| `config_wait_ms` / `mismatched_answers` | how long `workspace/configuration` took to come back, and how many mid-scan answers disagreed with the settled index |
| `settled_ms` / `first_answer_ms` | when the scan went quiet, and when the first useful answer arrived — separate numbers, and `scan` measures them in separate sessions so the settled series stays comparable with take 4's |
**The status vocabulary.**
+1
View File
@@ -36,6 +36,7 @@ import phases_new # noqa: E402,F401 — registers its own phases
import phases_p0 # noqa: E402,F401 — registers take 5 §P0's phases
import phases_p1 # noqa: E402,F401 — registers take 5 §P1's phases
import phases_p2 # noqa: E402,F401 — registers take 5 §P2's phases
import phases_p4 # noqa: E402,F401 — registers take 5 §P4's phases
# =========================================================================
+280
View File
@@ -0,0 +1,280 @@
#!/usr/bin/env python3
"""Take 5 §P4a: where a startup goes, read off the server's own trace.
Imported by `bench.py`, which owns the registry and the command line.
The server built for §P4a says, at the end of every scan and only under
`--verbose`, three `timing: scan <n> …` lines — stages in ms, counts, and the
sizes the scan left resident (`docs/features/perf5-p4/README.md`). This module
runs the scans the plan named, parses those lines, and writes one schema-2 row
per (cell, scan). Nothing here changes the server; it reads what the server
says about itself.
- `scanprofile` — the workspace scope cold and warm, the default scope, depth
0, and 1 / 10 / 100 open buffers. Every cell is `--tries` fresh processes.
A session at a non-default scope pays **two** scans: the startup scan runs
at the default settings, and the configured scope arrives afterwards and
asks for another. They are separate rows because they are separate scans.
- `scanwait` — the first useful answer during a scan, cold and warm, with the
trace of the very session that answered it beside the latency. This is the
§P0 finding (cold 84 ms, warm 206 ms) with the breakdown that explains it.
- `scanserve` — a definition every 200 ms for as long as the scan runs: the
latency distribution of requests that arrive mid-scan, and whether any of
them saw a table the settled index disagrees with.
"""
import os
import re
import time
import schema
from harness import (
ARGS, at, phase, record, session, sites,
)
#: One trace line: `timing: scan <n> <kind> (<shape>, …): a=1 b=2 …`.
TRACE_LINE = re.compile(r"^timing: scan (\d+) (stages|counts|memory) \(([a-z]+)[,)]")
#: `timing: scan finished: N file(s) (S skipped, C from cache) in X ms`.
FINISHED = re.compile(r"^timing: scan finished: (\d+) files? \((\d+) skipped, (\d+) from cache\)")
#: How long to let a scan run before giving up on it going quiet.
QUIET = 1.5
def fields(line):
"""Every `key=value` on a trace line, values as numbers where they are."""
out = {}
for token in line.split(":", 2)[-1].split():
if "=" not in token:
continue
key, value = token.split("=", 1)
try:
out[key] = float(value) if "." in value else int(value)
except ValueError:
out[key] = value
return out
def traces(s):
"""The scans a session traced, in order, as dicts keyed by scan number.
Each entry is `{"n", "kind", "stages", "counts", "memory"}`. A scan whose
three lines did not all arrive is still reported, with the halves it has —
a missing half is a finding, not something to hide.
"""
s.drain()
found = {}
for text in s.log_messages:
seen = TRACE_LINE.match(text)
if not seen:
continue
number, kind, shape = int(seen.group(1)), seen.group(2), seen.group(3)
entry = found.setdefault(number, {"n": number, "kind": shape})
entry[kind] = fields(text)
return [found[n] for n in sorted(found)]
def config_wait_ms(s):
"""How long the client took to answer `workspace/configuration`."""
for text in s.log_messages:
if text.startswith("timing: configuration answered in "):
return float(text.rsplit(" ", 2)[-2])
return None
def stage_row(phase_name, row, cell, scans, settled, extra=None):
"""One row per traced scan, plus the settled wall time of the session."""
for scan in scans:
stages = scan.get("stages") or {}
counts = scan.get("counts") or {}
memory = scan.get("memory") or {}
missing = [k for k in ("stages", "counts", "memory") if not scan.get(k)]
record(
phase=phase_name,
row="%s, scan %d (%s)" % (row, scan["n"], scan["kind"]),
ms=[stages.get("total", 0.0)],
settled_ms=settled,
stages=stages, counts=counts, memory=memory,
fresh_process=True,
result_count=counts.get("read", 0),
status="ok" if not missing else "error",
message=None if not missing else "no %s line" % "/".join(missing),
note=cell + ("" if not extra else " | " + extra),
)
def settle(s, open_files=(), first=sites.TB):
"""Open `first` (and any extra buffers), then wait for the scan to end.
Returns the milliseconds from the `didOpen` to the last notification, with
the quiet window taken back off — the same barrier `bench.py::phase_scan`
uses, so the numbers are comparable with the settled series.
"""
started = time.perf_counter()
s.did_open(sites.path(first))
for relative in open_files:
s.did_open(relative if os.path.isabs(relative) else sites.path(relative))
s.wait_quiet(QUIET)
return (time.perf_counter() - started) * 1000.0 - QUIET * 1000.0
def rtl_files(count):
"""`count` opentitan RTL files, in a stable order, for the buffer cells."""
found = []
for folder in ("hw/ip/aes/rtl", "hw/ip/kmac/rtl", "hw/ip/spi_device/rtl",
"hw/ip/entropy_src/rtl", "hw/ip/otbn/rtl", "hw/ip/hmac/rtl",
"hw/ip/flash_ctrl/rtl", "hw/ip/keymgr/rtl", "hw/ip/rv_dm/rtl",
"hw/ip/usbdev/rtl", "hw/ip/i2c/rtl", "hw/ip/spi_host/rtl"):
directory = sites.path(folder)
if not os.path.isdir(directory):
continue
for name in sorted(os.listdir(directory)):
if name.endswith(".sv") and len(found) < count:
found.append(os.path.join(directory, name))
return found
@phase("scanprofile")
def phase_scanprofile():
"""The startup breakdown, one cell per (scope, cache state, buffers)."""
cells = [
("workspace, cold cache", "workspace", True, 0),
("workspace, warm cache", "workspace", False, 0),
("default scope, cold cache", "default", True, 0),
("default scope, warm cache", "default", False, 0),
("depth0, cold cache", "depth0", True, 0),
("depth0, warm cache", "depth0", False, 0),
("workspace warm, 1 open buffer", "workspace", False, 1),
("workspace warm, 10 open buffers", "workspace", False, 10),
("workspace warm, 100 open buffers", "workspace", False, 100),
]
for label, scope, cold, buffers in cells:
settled, per_try, waits = [], [], []
opened = rtl_files(buffers)
for _ in range(ARGS.tries):
with session(scope, cold=cold, verbose=True,
storage_name="p4-" + scope) as s:
s.initialize()
settled.append(settle(s, opened))
per_try.append(traces(s))
waits.append(config_wait_ms(s))
# The scans line up across tries (the same scope resolves the same
# way), so a scan's row carries the first try's fields and every try's
# settled time. A try that traced a different number of scans is a
# finding, and the note says so.
shapes = {len(t) for t in per_try}
extra = "config wait %s ms | %d open buffer(s)" % (
"/".join("%.2f" % w if w is not None else "-" for w in waits), buffers)
if len(shapes) != 1:
extra += " | tries traced %s scans" % sorted(shapes)
stage_row("scanprofile", label, label, per_try[0], settled, extra)
@phase("scanwait")
def phase_scanwait():
"""The first useful answer during a scan, with that session's own trace.
§P0 measured the latency and could not explain it: cold 84 ms, warm 206.
Here the definition goes out exactly as it did there, and the trace of the
very session that answered it is in the row beside it.
"""
for cache in ("cold", "warm"):
first, settled, found, statuses, per_try, waits = [], [], [], [], [], []
for _ in range(ARGS.tries):
with session("workspace", cold=(cache == "cold"), verbose=True,
storage_name="p4-wait") as s:
s.initialize()
started = time.perf_counter()
s.did_open(sites.path(sites.TB))
answer_ms, message = s.await_id(
s.send("textDocument/definition", at(sites.TB, " aes #(", 1, 2)))
first.append(answer_ms)
statuses.append(schema.status_of(message)[0])
found.append(schema.result_count(message))
s.wait_quiet(QUIET)
settled.append((time.perf_counter() - started) * 1000.0 - QUIET * 1000.0)
per_try.append(traces(s))
waits.append(config_wait_ms(s))
shape = s.client_shape()
status = schema.worst(statuses)
record(phase="scanwait", row="workspace, %s cache, first useful answer" % cache,
ms=first, first_answer_ms=first, settled_ms=settled,
fresh_process=True, status=status, client=shape,
message=None if status == "ok" else "a definition did not answer ok",
result_count=found[-1], result_counts=found,
config_wait_ms=[w for w in waits if w is not None],
scans=[{"n": t["n"], "kind": t["kind"],
"first_publish": (t.get("counts") or {}).get("first_publish"),
"publishes": (t.get("counts") or {}).get("publishes"),
"total": (t.get("stages") or {}).get("total")}
for t in per_try[0]],
note="ms is the definition sent during the scan; `scans` is the "
"first try's trace, so the answer can be placed inside it")
stage_row("scanwait", "workspace, %s cache, answering" % cache,
"the session that answered the first request", per_try[0], settled)
def scan_chatter(s):
"""How many notifications a *scan* has sent — the busy signal.
`window/logMessage` is excluded: a `--verbose` server logs one per
request, so a loop that counted it would be listening to itself.
"""
s.drain()
return sum(1 for n in s.notifications
if n["method"] in ("$/progress", "textDocument/publishDiagnostics"))
@phase("scanserve")
def phase_scanserve():
"""A definition every 200 ms for as long as the scan runs.
Two questions: what those requests cost while the index is being built,
and whether any of them saw a table the finished index disagrees with. The
coherence check is what a client can actually observe — a mid-scan answer
may be *empty* (the file it would name has not been reached), but it may
never name somewhere else than the settled index does.
"""
for cache in ("cold", "warm"):
during, results, mismatched, settled = [], [], 0, []
for _ in range(ARGS.tries):
with session("workspace", cold=(cache == "cold"), verbose=True,
storage_name="p4-serve") as s:
s.initialize()
started = time.perf_counter()
s.did_open(sites.path(sites.TB))
params = at(sites.TB, " aes #(", 1, 2)
seen = []
# As long as the *scan* is still saying things, keep asking.
# The busy test counts `$/progress` and `publishDiagnostics`
# only: under `--verbose` the server logs a line per request,
# so counting every notification would count this loop's own
# noise and never stop.
while True:
before = scan_chatter(s)
elapsed, message = s.request("textDocument/definition", params)
during.append(elapsed)
seen.append(message.get("result"))
time.sleep(0.2)
if scan_chatter(s) == before and (
time.perf_counter() - started) > 1.0:
break
s.wait_quiet(QUIET)
settled.append((time.perf_counter() - started) * 1000.0 - QUIET * 1000.0)
settled_answer = s.request("textDocument/definition", params)[1].get("result")
results.append(len(seen))
mismatched += sum(1 for answer in seen
if answer and answer != settled_answer)
during.sort()
record(phase="scanserve", row="definition every 200 ms during a %s scan" % cache,
ms=during, fresh_process=True, result_count=len(during),
requests_per_session=results, mismatched_answers=mismatched,
settled_ms=settled,
status="ok" if mismatched == 0 else "error",
message=None if mismatched == 0 else
"%d mid-scan answers disagreed with the settled index" % mismatched,
note="ms is every mid-scan definition, sorted, across all tries; "
"`mismatched_answers` counts non-empty answers that named "
"somewhere the settled index does not — the coherence "
"contract of docs/features/index-scope/README.md")