diff --git a/TODO.md b/TODO.md index 6acb228..e703c7d 100644 --- a/TODO.md +++ b/TODO.md @@ -4714,6 +4714,9 @@ in 0.49.0. Take 4's findings are in the loop-3 list above. already stat'd and could hand on), then `cache_open` 89 ms; warm settle ~1.04–1.10 s against the plan's < 1 s, the rest being the store open the refused reuse would remove. +- **review round §61.2 filed:** a `format::indent_width` form taking an + already-read `FileConfig`, so the code-action path's run and the + publish path do one `Discovery` walk, not two (+0.1 ms today). Sections after §46 are planned when reached. ## 45. Small items, round 4 (planned 2026-09-05) — topo §2.9-29, 30, 17, 22 @@ -6271,27 +6274,81 @@ Review §1. `lint.rs::fixable` still runs `lint_with` on every request: after an edit is 136 ms. Files: `lucisv_server/src/{lint.rs, code_action.rs,fences.rs,server/dispatch.rs}` + a new small module for the snapshot; `state/` for one field at most; tests. -- [ ] R1b first: a `--verbose` stage trace for one `codeAction` on the +- [x] R1b first: a `--verbose` stage trace for one `codeAction` on the pinmux comment — config/waiver load, dirty-buffer flush (the `Document` rebuild), lint, fence, serialization — for the first request, an unchanged repeat, the first after a one-character edit, and the definition queued behind each; harness rows -- [ ] the dependency/invalidation table written BEFORE any cache: + — `lint_trace.rs`, one `timing: codeaction …` line per request that + linted anything, two groups (`flush{…} action{…}`) divided by the + flush; phases `actionprofile` and `ruleablation` in + `tools/perf/phases_r1.py`. **The 23 ms is `lint_with`** (20.9 of 22.0; + config I/O 0.04, run build 0.01, serialization 0.03, fence skipped) and + **three semantic rules are the whole of it** — `unused-signal` +8.2, + `multiply-driven` +7.5, `undriven-net` +7.4 ms over a 1.3 ms floor, the + other 55 default rules ≤ +2.2 each. **The 136 ms is 78% the flush**: + 99.7 of 127.5 ms, of which 21.1 is the diagnostics pass, leaving + ~78.6 ms of `Document::new` on 1.3 MB; the handler then lints the same + revision a **second** time for 20.2 ms. Deviation: the flush is one + traced stage plus its parse count, not split into parse/analysis/overlay + — those live in `state/mod.rs`, outside this lane's ownership, and + flush-minus-diagnostics answers the question asked +- [x] the dependency/invalidation table written BEFORE any cache: document content/revision, effective rules and options, tab width, external waiver contents, project/index inputs the workspace rules read (index generation); each row names the test that flips it -- [ ] R1a: a lint-result snapshot keyed by that table, consumed by the + — 14 rows in `docs/features/perf5r-lint-snapshot/README.md`, derived from + the arguments of the `lint_with(ctx, rules, external)` call it guards, so + the list is complete by construction. Three mechanisms only: **identity** + (the buffer, `doc.large`, close/reopen — `set_document` builds a new + `Document`), the **key by value** (rules, options, width, indent, waiver + *contents*), and **one explicit drop** (`Document::refresh_overlay`, which + every index mutation in `state/` already ends in). Row 12 is the one that + decides the config question: the `lucisv.toml` and the waiver files are + **not watched** (`watch::SOURCE_GLOB` is sources plus the filelist), so + the per-request read is the only thing that ever notices them changing +- [x] R1a: a lint-result snapshot keyed by that table, consumed by the diagnostics pass and the quick-fix discovery alike; recomputed on any mismatch; bounded (one per open document); the fence authority and execute-time validation untouched -- [ ] measured: unchanged pinmux menu and queued definition ≤ 16 ms; + — `lint_snapshot.rs`: `Key` compared **by value, never hashed**, and + `Slot`, one `Mutex>` field on the `Document`. One `found(doc, + run)` in `lint.rs` that both doors call; the tab width moved onto the + `LintRun` (read through `format::indent_width`, whose call the dispatcher + no longer makes) so the two doors build the same context and share one + slot. `fence.rs` and the shared-fence contract untouched; `vlog_linter` + untouched +- [x] measured: unchanged pinmux menu and queued definition ≤ 16 ms; first-after-edit improved and reported separately with its stage split; no stale diagnostic or fix under any invalidation; R1a/R1b cells + experiments -- [ ] QA: every invalidation row forces a fresh result (change the + — paired against trunk `51cbfd2`: **all families 22.61 → 0.98 ms + (−95.6%)**, **quickfix only 24.51 → 0.11 (−99.5%)**, **queued definition + 22.39/22.38 → 0.78/0.76 (−96.5%)** — both gates met with two orders of + magnitude of margin. **First-after-edit 125.65 → 106.89 ms (−14.9%)**, + and its split names the remaining stage: ~84 ms `Document::new` plus the + 21.9 ms diagnostics pass, with the code-action lint at **0.00 ms**. + Diagnostics publish +0.3%, idle RSS at 100 open buffers each holding a + snapshot 574.0 → 574.6 MiB (+0.1%), take-3 `codeaction` cells within + 1.5%. Config-discovery memo **not taken**: the trace measures that I/O at + 0.04–0.16 ms and its failure mode would be a stale rule selection. + R1a/R1b cells and both experiment records filed +- [x] QA: every invalidation row forces a fresh result (change the buffer, the config, a waiver file, a dependency file the workspace rules read, close/reopen, a UTF-16 range); stale-fix attack; memory bound; numbers re-taken + — PASS. All 14 rows attacked over real stdio JSON-RPC against the + release binary on an independent fixture workspace (two standalone + scripts, not the dev's own tests); three targeted sabotage cuts + (waiver text, the `refresh_overlay` drop, `tab_width` in the key) + each caught by exactly the predicted test and reverted clean; gates + cross-checked against a from-scratch clone of `51cbfd2` with + matching binary sha256es and a name-level test diff (+21/-0); + 100-buffer RSS and the stage trace reproduced independently within + noise; 12 tracker numbers traced verbatim (some as documented + medians) in `~/.cache/lucisv-perf/take5r-2/`; opentitan clean and + zero guard kills throughout. QA log in + `docs/features/perf5r-lint-snapshot/README.md` ### 61.3 R2a + R2b — the first useful answer diff --git a/crates/lucisv_server/src/code_action.rs b/crates/lucisv_server/src/code_action.rs index 45b9e5b..28e468a 100644 --- a/crates/lucisv_server/src/code_action.rs +++ b/crates/lucisv_server/src/code_action.rs @@ -33,19 +33,36 @@ pub fn code_actions( doc: &Document, range: Range, only: Option<&[CodeActionKind]>, - tab_width: usize, +) -> Vec { + let violations = crate::lint::fixable(run, doc); + // Timed apart from the lint pass that found them: a menu that is slow + // because it *renders* a thousand fixes is a different problem from one + // that is slow because it found them (review round §R1b). + let actions = crate::lint_trace::stage(crate::lint_trace::Stage::Serialize, || { + offered(uri, doc, range, only, &violations) + }); + crate::lint_trace::saw_actions(actions.len()); + actions +} + +/// The quick fixes and the fix-all action `only` asks for, built from +/// violations already found. +fn offered( + uri: &Uri, + doc: &Document, + range: Range, + only: Option<&[CodeActionKind]>, + violations: &[Violation], ) -> Vec { let positions = doc.positions(); - let violations = crate::lint::fixable(run, doc, tab_width); let mut actions = Vec::new(); if wanted(only, &CodeActionKind::QUICKFIX) { let quick = violations.iter().filter_map(|v| quick_fix(uri, &positions, v, range)); actions.extend(quick.map(CodeActionOrCommand::CodeAction)); } if wanted(only, &CodeActionKind::new(FIX_ALL)) { - actions.extend( - fix_all(uri, doc, &positions, &violations).map(CodeActionOrCommand::CodeAction), - ); + actions + .extend(fix_all(uri, doc, &positions, violations).map(CodeActionOrCommand::CodeAction)); } actions } @@ -184,7 +201,7 @@ mod tests { fn actions_of(ws: &Workspace) -> Vec { let doc = ws.document(&uri()).expect("open"); let whole = doc.positions().whole_document(); - code_actions(&LintRun::default(), &uri(), doc, whole, None, 2) + code_actions(&LintRun::default(), &uri(), doc, whole, None) .into_iter() .map(|a| match a { CodeActionOrCommand::CodeAction(action) => action, @@ -268,7 +285,6 @@ mod tests { doc, line1, Some(&[CodeActionKind::QUICKFIX]), - 2, ); assert_eq!(actions.len(), 1, "the cursor's line only: {actions:#?}"); } @@ -341,14 +357,8 @@ mod tests { start: Position { line: fenced_line, character: 0 }, end: Position { line: fenced_line, character: 0 }, }; - let actions = code_actions( - &LintRun::default(), - &uri(), - doc, - at, - Some(&[CodeActionKind::QUICKFIX]), - 2, - ); + let actions = + code_actions(&LintRun::default(), &uri(), doc, at, Some(&[CodeActionKind::QUICKFIX])); assert!(actions.is_empty(), "no quick fix inside a fence: {actions:#?}"); // The unfenced tab one line further down still has one. let at = Range { @@ -356,15 +366,8 @@ mod tests { end: Position { line: 4, character: 0 }, }; assert_eq!( - code_actions( - &LintRun::default(), - &uri(), - doc, - at, - Some(&[CodeActionKind::QUICKFIX]), - 2 - ) - .len(), + code_actions(&LintRun::default(), &uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]),) + .len(), 1 ); } @@ -409,19 +412,14 @@ mod tests { let doc = ws.document(&uri()).expect("open"); let whole = doc.positions().whole_document(); let fix_all_only = [CodeActionKind::new(FIX_ALL)]; - let actions = code_actions(&LintRun::default(), &uri(), doc, whole, Some(&fix_all_only), 2); + let actions = code_actions(&LintRun::default(), &uri(), doc, whole, Some(&fix_all_only)); assert_eq!(actions.len(), 1, "no quick fixes when only fixAll was asked for"); // `source` is a prefix filter for `source.fixAll.lucisv`. let source = [CodeActionKind::SOURCE]; - assert_eq!( - code_actions(&LintRun::default(), &uri(), doc, whole, Some(&source), 2).len(), - 1 - ); + assert_eq!(code_actions(&LintRun::default(), &uri(), doc, whole, Some(&source)).len(), 1); // And an unrelated filter selects nothing. let refactor = [CodeActionKind::REFACTOR]; - assert!( - code_actions(&LintRun::default(), &uri(), doc, whole, Some(&refactor), 2).is_empty() - ); + assert!(code_actions(&LintRun::default(), &uri(), doc, whole, Some(&refactor)).is_empty()); } #[test] @@ -431,12 +429,11 @@ mod tests { let doc = ws.document(&uri()).expect("open"); let whole = doc.positions().whole_document(); let actions = code_actions( - &LintRun::default(), + &LintRun::default().with_tab_width(4), &uri(), doc, whole, Some(&[CodeActionKind::QUICKFIX]), - 4, ); let CodeActionOrCommand::CodeAction(fix) = &actions[0] else { panic!("an action") }; assert_eq!(applied(text, fix), "module m;\n wire a;\nendmodule\n"); @@ -467,18 +464,14 @@ mod tests { let ws = workspace(src); let doc = ws.document(&uri()).expect("open"); let whole = doc.positions().whole_document(); - let (external, problems) = vlog_linter::ExternalWaivers::parse( - std::path::Path::new("team.waiver"), - "waive --rule=no-tabs\n", - ); - assert!(problems.is_empty(), "{problems:?}"); - let waived = LintRun::default().with_external(external); + let waived = LintRun::default() + .with_waivers(std::path::Path::new("team.waiver"), "waive --rule=no-tabs\n"); assert!( - code_actions(&waived, &uri(), doc, whole, None, 2).is_empty(), + code_actions(&waived, &uri(), doc, whole, None).is_empty(), "no quick fix and no fix-all for a waived finding" ); assert!( - !code_actions(&LintRun::default(), &uri(), doc, whole, None, 2).is_empty(), + !code_actions(&LintRun::default(), &uri(), doc, whole, None).is_empty(), "the same buffer without the waiver is fixable" ); } diff --git a/crates/lucisv_server/src/fences.rs b/crates/lucisv_server/src/fences.rs index 7468534..c040c9d 100644 --- a/crates/lucisv_server/src/fences.rs +++ b/crates/lucisv_server/src/fences.rs @@ -31,3 +31,10 @@ use crate::state::Document; pub fn of(doc: &Document) -> &[Region] { doc.fences.get_or_init(|| fence::protected_regions(&doc.text)) } + +/// Whether the answer is already in hand — asked *before* [`of`], so a +/// `--verbose` trace can say whether this request paid the parse or read the +/// memo (review round §R1b, `crate::lint_trace`). Decides nothing. +pub fn held(doc: &Document) -> bool { + doc.fences.get().is_some() +} diff --git a/crates/lucisv_server/src/lint.rs b/crates/lucisv_server/src/lint.rs index e88cd69..1380d87 100644 --- a/crates/lucisv_server/src/lint.rs +++ b/crates/lucisv_server/src/lint.rs @@ -23,6 +23,7 @@ pub use project::{ConfigProblems, ProblemLog, ProjectLint}; use std::collections::BTreeSet; use std::path::{Path, PathBuf}; +use std::sync::Arc; use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString}; use lucisv_core::config::FileConfig; @@ -35,6 +36,8 @@ use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex}; use crate::convert::Positions; use crate::diagnostics::SOURCE; +use crate::lint_snapshot::{Key, Slot}; +use crate::lint_trace::{self, Fences, Reuse, Stage}; use crate::settings::ClientSettings; use crate::state::{Document, Workspace}; @@ -53,10 +56,29 @@ pub struct LintRun<'a> { /// The width `line-length` holds this buffer to — the width the formatter /// would wrap it to, so the two halves of lucisv cannot disagree. line_length: usize, + /// The width a `no-tabs` fix writes where a tab was — the same ladder + /// `format::indent_width` walks, read off the `FileConfig` this pass + /// already discovered. + /// + /// On the run rather than passed to [`fixable`] since the review round's + /// §R1a: the diagnostics pass and the quick-fix pass must build the *same* + /// `LintContext` to share one snapshot. Nothing published moves — the + /// width reaches only `no-tabs`' fix *text*, and the diagnostics path + /// never reads a fix. + tab_width: usize, /// The external waiver files in force for this buffer, from its /// `lucisv.toml` and from `lucisv.lint.waivers`. Empty unless one is /// configured, and then costing the pass nothing. external: ExternalWaivers, + /// Those files' paths and contents, in the order they were read — the + /// snapshot key's row 7. Empty when no waiver file is configured. + /// + /// **Written in the same step as `external`**, by `waiver_files` and by + /// `with_waivers` and by nothing else, so a run can never carry a waiver + /// its key cannot see. A run whose key missed a waiver would offer a fix + /// for a finding the waiver had silenced, which is the stale-fix failure + /// this whole key exists to prevent. + waiver_texts: Vec<(PathBuf, String)>, /// What the buffer's `lucisv.toml` asked for and did not get. Reported by /// whoever can talk to the client — [`ProblemLog`] keeps it to once per /// (config file, message) — and never fatal here: §42.2. @@ -70,7 +92,9 @@ impl Default for LintRun<'_> { oracle: None, options: RuleOptions::new(), line_length: DEFAULT_LINE_LENGTH, + tab_width: DEFAULT_TAB_WIDTH, external: ExternalWaivers::default(), + waiver_texts: Vec::new(), problems: ConfigProblems::default(), } } @@ -80,6 +104,11 @@ impl Default for LintRun<'_> { /// editor says otherwise — `vlog_formatter::Config`'s own default. const DEFAULT_LINE_LENGTH: usize = 100; +/// The indent width a buffer's fixes are written at when neither its +/// `lucisv.toml` nor the editor says otherwise — `vlog_formatter::Config`'s +/// own default, which is what `format::indent_width` falls back to. +const DEFAULT_TAB_WIDTH: usize = 2; + impl<'a> LintRun<'a> { /// The pass this workspace's settings and index describe for one buffer. /// @@ -90,25 +119,12 @@ impl<'a> LintRun<'a> { /// cross-file evidence behind them, which is the false-positive mode this /// whole round exists to close. pub fn for_document(ws: &'a Workspace, doc: &Document) -> LintRun<'a> { - let index = ws.index(); - let own = doc.path.as_deref().and_then(|path| index.file_id(path)); - let workspace = index.files().len() > usize::from(own.is_some()); - let oracle = workspace.then_some(IndexMentions { index, own }); - // One discovery for the whole pass: the selection, the options, the - // width and the waiver paths all read the same `FileConfig`, so - // reading the project's rules costs no extra stat and no extra open. - let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc); - let (from_file, bad_names) = ProjectLint::read(&file); - messages.extend(bad_names); - let rules = enabled_rules(ws.client_settings(), &from_file, workspace); - let (mut external, bad_waivers) = external_waivers(&project_waivers(&file)); - messages.extend(bad_waivers); - // The editor's own waiver files are read separately and their - // problems dropped: `notification::apply_settings` already said them - // once, where the setting arrived. - external.absorb(external_waivers(&editor_waivers(ws.client_settings(), ws.roots())).0); - let problems = ConfigProblems::new(&file, messages); - LintRun { rules, oracle, options, line_length, external, problems } + // Two stages, so `--verbose` can say which of them the request spent + // its milliseconds in: everything read from disk, then everything + // decided from what was read (review round §R1b, `crate::lint_trace`). + let found = lint_trace::stage(Stage::Config, || Discovered::read(ws, doc)); + lint_trace::saw_config(found.file.source.is_some(), found.texts.len()); + lint_trace::stage(Stage::Build, || found.into_run(ws, doc)) } /// What this buffer's `lucisv.toml` asked for and did not get, for a @@ -117,17 +133,53 @@ impl<'a> LintRun<'a> { &self.problems } - /// A run carrying these external waivers — for the tests that pin what a - /// waiver keeps out of the code actions. + /// A run carrying this waiver file — for the tests that pin what a waiver + /// keeps out of the code actions. + /// + /// Takes the file's **text**, not a parsed `ExternalWaivers`, for the same + /// reason `waiver_files` returns both: the waivers a run lints with and + /// the texts its snapshot key holds must be written in one step, or a run + /// could carry waivers its key cannot see. The bad-line messages are + /// dropped here; the caller asserts about them itself where it cares. #[cfg(test)] - pub(crate) fn with_external(mut self, external: ExternalWaivers) -> Self { - self.external = external; + pub(crate) fn with_waivers(mut self, path: &Path, text: &str) -> Self { + self.external.absorb(ExternalWaivers::parse(path, text).0); + self.waiver_texts.push((path.to_path_buf(), text.to_string())); self } + /// A run whose fixes are written at this indent width — for the tests + /// that pin what a `no-tabs` fix writes. The server itself reads the + /// width off the buffer's own configuration in [`Discovered::read`]. + #[cfg(test)] + pub(crate) fn with_tab_width(mut self, tab_width: usize) -> Self { + self.tab_width = tab_width; + self + } + + /// What this run would lint with, as the snapshot compares it. + /// + /// Every field is an argument of the `lint_with` call it guards; the + /// buffer itself and the workspace index are settled by identity and by + /// `Document::refresh_overlay` instead. The feature README's table is the + /// whole argument. + fn key(&self) -> Key { + Key { + rules: self.rules.iter().map(|rule| rule.name()).collect(), + options: self.options.clone(), + line_length: self.line_length, + tab_width: self.tab_width, + has_oracle: self.oracle.is_some(), + waivers: self.waiver_texts.clone(), + } + } + /// This run's context over a buffer's own parse products. fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> { - let ctx = context(doc).with_options(&self.options).with_line_length(self.line_length); + let ctx = context(doc) + .with_options(&self.options) + .with_line_length(self.line_length) + .with_tab_width(self.tab_width); match &self.oracle { Some(oracle) => ctx.with_oracle(oracle), None => ctx, @@ -135,6 +187,76 @@ impl<'a> LintRun<'a> { } } +/// Everything one lint pass reads **from disk**: the `lucisv.toml` governing +/// the buffer, what its `[lint]` table said, and the external waiver files in +/// force. +/// +/// Split out of [`LintRun::for_document`] so the I/O has a name and a stage of +/// its own on the `--verbose` channel — "config read plus lint" was as far as +/// take 5 §P1 could attribute the pinmux menu's 23 ms, and that is two +/// answers. Nothing about *what* is read changed: the calls below are +/// `for_document`'s own, in its own order, so the messages a config problem +/// produces arrive in the order §42.2 fixed. +struct Discovered { + options: RuleOptions, + line_length: usize, + tab_width: usize, + file: FileConfig, + project: ProjectLint, + external: ExternalWaivers, + /// Each waiver file's path and the text it was parsed from — the + /// snapshot key's only I/O-derived field. + texts: Vec<(PathBuf, String)>, + messages: Vec, +} + +impl Discovered { + /// One discovery for the whole pass: the selection, the options, the + /// width, the indent and the waiver paths all read the same `FileConfig`, + /// so reading the project's rules costs no extra stat and no extra open. + fn read(ws: &Workspace, doc: &Document) -> Discovered { + let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc); + let (project, bad_names) = ProjectLint::read(&file); + messages.extend(bad_names); + let (mut external, bad_waivers, mut texts) = waiver_files(&project_waivers(&file)); + messages.extend(bad_waivers); + // The editor's own waiver files are read separately and their + // problems dropped: `notification::apply_settings` already said them + // once, where the setting arrived. + let editor = waiver_files(&editor_waivers(ws.client_settings(), ws.roots())); + external.absorb(editor.0); + texts.extend(editor.2); + // `format::indent_width` stays the one authority on the indent ladder + // (`lucisv.toml` > `lucisv.indent` > the formatter's default): reading + // it here rather than spelling the ladder a second time costs a second + // `Discovery` walk, which the R1b trace measures at hundredths of a + // millisecond against a 21 ms pass. + let tab_width = crate::format::indent_width(doc.path.as_deref(), ws.client_settings()); + Discovered { options, line_length, tab_width, file, project, external, texts, messages } + } + + /// What this buffer's index and settings make of it: the census oracle and + /// the rule ladder, neither of which touches the filesystem. + fn into_run<'a>(self, ws: &'a Workspace, doc: &Document) -> LintRun<'a> { + let index = ws.index(); + let own = doc.path.as_deref().and_then(|path| index.file_id(path)); + let workspace = index.files().len() > usize::from(own.is_some()); + let oracle = workspace.then_some(IndexMentions { index, own }); + let rules = enabled_rules(ws.client_settings(), &self.project, workspace); + let problems = ConfigProblems::new(&self.file, self.messages); + LintRun { + rules, + oracle, + options: self.options, + line_length: self.line_length, + tab_width: self.tab_width, + external: self.external, + waiver_texts: self.texts, + problems, + } + } +} + /// The per-rule options and the line width governing one buffer. /// /// **Precedence for an option, highest first: the editor, then the buffer's @@ -237,18 +359,37 @@ fn editor_waivers(client: &ClientSettings, roots: &[PathBuf]) -> Vec { /// pass, which runs on every keystroke, drops them silently rather than /// logging the same line a hundred times. pub fn external_waivers(paths: &[PathBuf]) -> (ExternalWaivers, Vec) { + let (waivers, problems, _) = waiver_files(paths); + (waivers, problems) +} + +/// [`external_waivers`], keeping each file's **text** as well. +/// +/// The text is what the lint snapshot's key holds (review round §R1a): a +/// waiver file is not watched — `watch::SOURCE_GLOB` covers sources and the +/// filelist alone — so comparing its contents is the only thing that ever +/// notices one being rewritten under a running server. +/// +/// One read, not two. `ExternalWaivers::read` is `read_to_string` followed by +/// `ExternalWaivers::parse`, and both halves are public, so the bytes are +/// taken once and handed to the parser; the sentence an unreadable file +/// produces is `read`'s own, byte for byte. +fn waiver_files(paths: &[PathBuf]) -> (ExternalWaivers, Vec, Vec<(PathBuf, String)>) { let mut waivers = ExternalWaivers::default(); let mut problems = Vec::new(); + let mut texts = Vec::new(); for path in paths { - match ExternalWaivers::read(path) { - Ok((file, bad)) => { + match std::fs::read_to_string(path) { + Ok(text) => { + let (file, bad) = ExternalWaivers::parse(path, &text); problems.extend(bad); waivers.absorb(file); + texts.push((path.clone(), text)); } - Err(problem) => problems.push(problem), + Err(problem) => problems.push(format!("{}: {problem}", path.display())), } } - (waivers, problems) + (waivers, problems, texts) } /// Which rules a buffer is linted with, given what the editor's settings and @@ -419,16 +560,43 @@ fn context(doc: &Document) -> LintContext<'_> { /// waiver was dead, and a server never has one — it lints the buffers a user /// happens to have open. `lucisv check` is what reports an unused external /// waiver; see `docs/features/waiver-files/README.md`. -pub fn violations_in(doc: &Document, run: &LintRun) -> Vec { - lint_with(&run.context(doc), &run.rules, &run.external).0 +pub fn violations_in(doc: &Document, run: &LintRun) -> Arc<[Violation]> { + found(doc, run) } -/// The findings a code action may offer a fix for, with their fixes built for -/// `tab_width`. +/// The one place `vlog_linter::lint_with` is called for an open buffer. /// -/// The code-action path passes the indent width of the `lucisv.toml` governing -/// the buffer, so a quick fix that replaces a tab writes exactly what `lucisv` -/// would have written there. +/// One place, so there is one snapshot to read (review round §R1a) and one +/// site that says on the `--verbose` channel what a pass ran, what it found, +/// and whether it ran at all. Both doors — the diagnostics publish and +/// quick-fix discovery — arrive here with the *same* context, which is why the +/// tab width lives on the [`LintRun`] rather than being handed to [`fixable`]. +fn found(doc: &Document, run: &LintRun) -> Arc<[Violation]> { + let key = run.key(); + let (violations, hit) = lint_trace::stage(Stage::Lint, || { + snapshot(doc).read_or(&key, || lint_with(&run.context(doc), &run.rules, &run.external).0) + }); + let reuse = if hit { Reuse::Hit } else { Reuse::Miss }; + lint_trace::saw_lint(run.rules.len(), violations.len(), reuse); + violations +} + +/// The slot this buffer's findings are kept in. +/// +/// A field on the `Document`, so it is dropped with the buffer and cannot +/// outlive the text it was computed from: `Workspace::set_document` builds a +/// new `Document` for every flushed change. One per open document and nothing +/// else — no map, no eviction, no second analysis cache. +fn snapshot(doc: &Document) -> &Slot { + &doc.lint +} + +/// The findings a code action may offer a fix for. +/// +/// The fixes are written at the run's own indent width — the `lucisv.toml` +/// governing the buffer, else `lucisv.indent`, else the formatter's default — +/// so a quick fix that replaces a tab writes exactly what `lucisv` would have +/// written there. /// /// A finding whose fix would edit bytes inside a `// verilog_format: off` /// region is dropped here, so the editor keeps the same promise `lucisv check @@ -437,14 +605,13 @@ pub fn violations_in(doc: &Document, run: &LintRun) -> Vec { /// just has no lightbulb. Which bytes count as fenced is /// [`fence::protected_regions`]' answer, the one the CLI asks too; see /// `docs/features/shared-fence-filter/README.md`. -pub fn fixable(run: &LintRun, doc: &Document, tab_width: usize) -> Vec { +pub fn fixable(run: &LintRun, doc: &Document) -> Arc<[Violation]> { // The buffer's own run: its enabled rules and its external waiver files, // so a fix is never offered — nor applied by fix-on-save — for a finding // the diagnostics pass would not have shown. Found by §39's QA: with // `default_rules()` and no waivers here, `source.fixAll.lucisv` rewrote a // line a checked-in waiver file had waived. - let ctx = run.context(doc).with_tab_width(tab_width); - let found = lint_with(&ctx, &run.rules, &run.external).0; + let violations = found(doc, run); // The fence answer is a whole second tolerant parse of the buffer: // `protected_regions` takes text and parses internally, on purpose — one // fence answer for every front end, none of which can feed it a stale tree @@ -453,15 +620,24 @@ pub fn fixable(run: &LintRun, doc: &Document, tab_width: usize) -> Vec, Option, usize)> = vec![ + (None, None, 2), + (None, Some(8), 8), + (Some("indent = 4\n"), Some(8), 4), + (Some("indent = 3\n"), None, 3), + ]; + for (toml, editor, want) in rungs { + match toml { + Some(text) => std::fs::write(dir.join("lucisv.toml"), text).expect("write"), + None => { + let _ = std::fs::remove_file(dir.join("lucisv.toml")); + } + } + let mut ws = Workspace::default(); + ws.set_client_settings(ClientSettings { indent: editor, ..Default::default() }); + ws.set_document(uri.clone(), "module m;\n\twire a;\nendmodule\n".to_string()); + let doc = ws.document(&uri).expect("open"); + let run = LintRun::for_document(&ws, doc); + assert_eq!(run.tab_width, want, "toml={toml:?} editor={editor:?}"); + assert_eq!( + run.tab_width, + crate::format::indent_width(Some(&path), ws.client_settings()), + "the two readings of the ladder agree" + ); + assert_eq!( + fixable(&run, doc)[0].fix.as_ref().expect("a fix").edits[0].1, + " ".repeat(want) + ); + } + let _ = std::fs::remove_dir_all(&dir); + } + + /// The snapshot is a memo and not a second implementation: what it hands + /// back is what a pass computed from scratch would have, violation for + /// violation, and both doors get the same object. + #[test] + fn a_reused_snapshot_is_what_a_fresh_pass_would_have_found() { + let (ws, uri) = doc_of("module m;\n\twire a; \nendmodule\n"); + let doc = ws.document(&uri).expect("open"); + let run = LintRun::default(); + let fresh: Vec = lint_with(&run.context(doc), &run.rules, &run.external).0; + let first = violations_in(doc, &run); + let second = fixable(&run, doc); + assert!(Arc::ptr_eq(&first, &second), "the diagnostics and the fixes are one pass"); + assert_eq!(first.len(), fresh.len(), "{fresh:#?}"); + for (held, made) in first.iter().zip(&fresh) { + assert_eq!( + (held.rule, held.span, &held.message), + (made.rule, made.span, &made.message) + ); + assert_eq!( + held.fix.as_ref().map(|fix| &fix.edits), + made.fix.as_ref().map(|fix| &fix.edits), + "the fix bytes are the fresh pass's too" + ); + } + } + /// A waiver file that is missing, and one with a bad line, are both /// described rather than fatal — and the good directives of the second /// still apply. TODO §39. diff --git a/crates/lucisv_server/src/lint_snapshot.rs b/crates/lucisv_server/src/lint_snapshot.rs new file mode 100644 index 0000000..d3e507f --- /dev/null +++ b/crates/lucisv_server/src/lint_snapshot.rs @@ -0,0 +1,245 @@ +//! One lint pass's findings, kept for as long as they are still the answer. +//! +//! Take 5 **review** round §R1a (`docs/features/perf5r-lint-snapshot/README.md`, +//! `docs/performance_take5_review.md` §1). A `textDocument/codeAction` on +//! `pinmux_reg_top.sv` spends **21 of its 22 ms in `lint_with`**, and the first +//! request after an edit runs that pass **twice** on one revision — once to +//! publish diagnostics, once to discover quick fixes. This module is what lets +//! the second one read the first one's answer. +//! +//! **The whole design is in [`Key`].** A snapshot is legitimate only while +//! every input of `lint_with(ctx, rules, external)` is what it was, and the +//! key is those inputs *by value* — no hash, no mtime, no generation number, +//! so "could this offer a stale fix?" is a question about `PartialEq` and not +//! about collision probability. What the key deliberately does **not** carry +//! is the two things identity already settles: +//! +//! * the **buffer** — a [`Slot`] is a field on the `Document`, and +//! `Workspace::set_document` builds a new `Document` for every flushed +//! change, so a slot cannot outlive the text it was computed from (the +//! argument `crate::fences` already rests on); +//! * the **workspace index** the census oracle reads — every index mutation in +//! `state/mod.rs` ends by calling `Document::refresh_overlay` on every open +//! buffer, and that is where the slot is cleared. +//! +//! The invalidation table in the feature README has one row per input, the +//! mechanism for each, and the test that flips it. +//! +//! **Bounded by construction:** one slot per open document, holding that +//! document's own violations, dropped with the `Document` on `didClose`. There +//! is no map, no eviction policy and no second unbounded analysis cache. + +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +use vlog_linter::{RuleOptions, Violation}; + +/// Everything a lint result depends on that is **not** settled by the +/// `Document`'s own identity. +/// +/// Compared by value, field by field. Every field is an argument of the +/// `lint_with` call it guards, which is what makes the list complete: see the +/// feature README's table, which derives it from that call's signature. +#[derive(Debug, Clone, PartialEq)] +pub struct Key { + /// The enabled rules' names, in registry order — the whole of what the + /// `lucisv.lint.*` ladder and the project's `[lint]` table decided. + pub rules: Vec<&'static str>, + /// The merged per-rule options: the buffer's `lucisv.toml` overlaid with + /// the editor's `lucisv.lint.options`. + pub options: RuleOptions, + /// The width `line-length` holds this buffer to. + pub line_length: usize, + /// The width a `no-tabs` fix writes. It changes a fix's *text* and + /// nothing else, but a fix's text is what a user applies. + pub tab_width: usize, + /// Whether the pass had a census to ask. The oracle's *answers* are + /// covered by `refresh_overlay`; whether there is one at all is decided + /// from the index's file count, which can move without any one file's + /// facts moving. + pub has_oracle: bool, + /// Every external waiver file in force, path and **contents**, in the + /// order they were read. + /// + /// The contents, not a digest and not an mtime: a waiver file is not + /// watched (`watch::SOURCE_GLOB` covers sources and the filelist alone), + /// so the only thing that ever notices a rewritten one is this + /// comparison. The text is already in hand — the pass read it to parse + /// it — so keeping it costs a copy per open document and no I/O. + pub waivers: Vec<(PathBuf, String)>, +} + +/// One document's lint snapshot: the key it was computed under, and what it +/// found. +struct Held { + key: Key, + violations: Arc<[Violation]>, +} + +/// The snapshot slot a `Document` carries. +/// +/// A `Mutex` rather than a `RefCell` so a `Document` stays `Sync` exactly as +/// its `OnceLock` fence memo leaves it; the lock is uncontended (one message +/// loop) and is never held across the pass itself. +#[derive(Default)] +pub struct Slot(Mutex>); + +impl Slot { + /// An empty slot — what every `Document` is built with. + pub fn new() -> Slot { + Slot(Mutex::new(None)) + } + + /// Forget whatever is held. + /// + /// Called from `Document::refresh_overlay`, which is the one place a + /// `Document` is told the workspace index moved. Dropping here rather + /// than keying on an index generation is deliberate: the four call sites + /// that mutate the index all end in that loop, so there is no way for the + /// index to move without this running, and no counter to keep in step. + pub fn clear(&mut self) { + if let Ok(mut held) = self.0.lock() { + *held = None; + } + } + + /// The violations for `key`, computing them when what is held is for + /// anything else. + /// + /// Returns `(violations, answered_from_the_snapshot)`. A poisoned lock — + /// which this server has no way to produce, having one message loop and no + /// panicking library code — degrades to computing every time rather than + /// to an error a user would see. + pub fn read_or( + &self, + key: &Key, + compute: impl FnOnce() -> Vec, + ) -> (Arc<[Violation]>, bool) { + if let Ok(held) = self.0.lock() { + if let Some(held) = held.as_ref().filter(|held| held.key == *key) { + return (Arc::clone(&held.violations), true); + } + } + // Computed with the lock released: `lint_with` is the expensive part + // and it reads nothing this slot owns. + let violations: Arc<[Violation]> = compute().into(); + if let Ok(mut held) = self.0.lock() { + *held = Some(Held { key: key.clone(), violations: Arc::clone(&violations) }); + } + (violations, false) + } + + /// Whether anything is held at all — for the tests that assert a slot was + /// filled, or was not. + #[cfg(test)] + pub fn is_empty(&self) -> bool { + self.0.lock().map_or(true, |held| held.is_none()) + } +} + +impl std::fmt::Debug for Slot { + /// Says whether a snapshot is held and nothing about it: a `Document`'s + /// `Debug` must not print a thousand violations. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let held = self.0.lock().map(|held| held.is_some()).unwrap_or(false); + f.debug_tuple("Slot").field(&held).finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use vlog_parser::TextRange; + + fn key() -> Key { + Key { + rules: vec!["no-tabs"], + options: RuleOptions::new(), + line_length: 100, + tab_width: 2, + has_oracle: false, + waivers: Vec::new(), + } + } + + fn violation(message: &str) -> Violation { + Violation::new("no-tabs", message, TextRange::new(0, 1)) + } + + /// The second ask for the same key does not compute, and answers with the + /// same findings. + #[test] + fn a_matching_key_answers_without_computing() { + let slot = Slot::new(); + let (first, hit) = slot.read_or(&key(), || vec![violation("one")]); + assert!(!hit, "an empty slot cannot hit"); + let (again, hit) = slot.read_or(&key(), || panic!("must not recompute")); + assert!(hit); + assert_eq!(again.len(), 1); + assert_eq!(again[0].message, first[0].message); + } + + /// Every field of the key is load-bearing: change any one and the pass + /// runs again. This is the table's row set in miniature — the per-input + /// server tests assert the same thing through the real doors. + #[test] + fn every_field_of_the_key_forces_a_recompute() { + let mut options = RuleOptions::new(); + options.set_raw("line-length", "length", "80").expect("a real option"); + let changes: Vec<(&str, Key)> = vec![ + ("rules", Key { rules: vec!["no-tabs", "posix-eof"], ..key() }), + ("options", Key { options, ..key() }), + ("line_length", Key { line_length: 120, ..key() }), + ("tab_width", Key { tab_width: 4, ..key() }), + ("has_oracle", Key { has_oracle: true, ..key() }), + ( + "waivers", + Key { + waivers: vec![(PathBuf::from("/w.waiver"), "waive --rule=no-tabs\n".into())], + ..key() + }, + ), + ]; + for (what, moved) in changes { + let slot = Slot::new(); + slot.read_or(&key(), || vec![violation("old")]); + let (found, hit) = slot.read_or(&moved, || vec![violation("new")]); + assert!(!hit, "{what} did not invalidate the snapshot"); + assert_eq!(found[0].message, "new", "{what} answered stale"); + // ... and the new answer is what is held afterwards, so the stale + // one cannot come back on the next request. + let (again, hit) = slot.read_or(&moved, || panic!("must not recompute")); + assert!(hit); + assert_eq!(again[0].message, "new", "{what} left the old answer held"); + } + } + + /// A waiver file rewritten to the same length with different bytes is a + /// different key: the contents are compared, not a size or a time. + #[test] + fn a_waiver_rewritten_in_place_is_a_different_key() { + let one = |text: &str| Key { + waivers: vec![(PathBuf::from("/w.waiver"), text.to_string())], + ..key() + }; + let slot = Slot::new(); + slot.read_or(&one("waive --rule=no-tabs\n"), || vec![violation("old")]); + let (found, hit) = + slot.read_or(&one("waive --rule=posix-eof\n"), || vec![violation("new")]); + assert!(!hit, "same length, different bytes"); + assert_eq!(found[0].message, "new"); + } + + /// Clearing is what `refresh_overlay` does when the index moves. + #[test] + fn clearing_forces_the_next_pass_to_compute() { + let mut slot = Slot::new(); + slot.read_or(&key(), || vec![violation("old")]); + assert!(!slot.is_empty()); + slot.clear(); + assert!(slot.is_empty()); + let (found, hit) = slot.read_or(&key(), || vec![violation("new")]); + assert!(!hit, "a cleared slot cannot hit"); + assert_eq!(found[0].message, "new"); + } +} diff --git a/crates/lucisv_server/src/lint_trace.rs b/crates/lucisv_server/src/lint_trace.rs new file mode 100644 index 0000000..dbad8ee --- /dev/null +++ b/crates/lucisv_server/src/lint_trace.rs @@ -0,0 +1,400 @@ +//! Where a lint-answering request's milliseconds went. +//! +//! Take 5 **review** round §R1b (`docs/performance_take5_review.md` §1, +//! `docs/features/perf5r-lint-snapshot/README.md`). The review's own note is +//! that the pinmux code-action menu costs **25 ms of which 23 is quickfix**, +//! and that the first request after a one-character edit costs **136 ms** — +//! but "config read plus lint" was as far as the previous lane could +//! attribute it, and *config read plus lint* is two answers, not one. This +//! module splits the request into the five stages a reader can act on: +//! +//! | stage | what it is | +//! |---|---| +//! | `config` | `Discovery::for_file`, `ProjectLint::read` and every waiver file read | +//! | `build` | the rest of [`crate::lint::LintRun::for_document`] — the oracle, the rule ladder | +//! | `lint` | `vlog_linter::lint_with`, and how many times it ran | +//! | `fence` | `crate::fences::of` — computed, taken from the memo, or skipped | +//! | `serialize` | turning violations into `CodeAction`s | +//! +//! and reports the **flush** — the debounced `Document` rebuild `answer_request` +//! performs before any handler runs — as its own group, with the diagnostics +//! pass that publishes inside it split the same five ways. That separation is +//! the review's item 4: if the dirty-buffer stage dominates the 136 ms, a lint +//! cache alone cannot fix it, and only a number can say. +//! +//! **Nothing here decides anything.** A trace is armed by +//! [`crate::server`]'s request wrapper when `--verbose` asked for one, written +//! as the request runs, logged once and dropped. +//! +//! Off is the shipped state and costs **one thread-local `Cell` read** +//! per traced site — no clock read, no allocation, no line — which is the same +//! bargain `Server::timer` makes for the rest of `docs/features/verbose-timing/`. +//! +//! Per thread, deliberately, for `vlog_parser::stats`' reason: a request is +//! answered on one thread, so a thread-local accumulator is that request's +//! number exactly, and `cargo test`'s parallel binaries cannot add to each +//! other's. + +use std::cell::{Cell, RefCell}; +use std::time::{Duration, Instant}; + +/// One stage of a lint-answering request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Stage { + /// Reading the project's configuration: the `lucisv.toml` discovery walk, + /// its `[lint]` table, and the external waiver files. + Config, + /// The rest of the `LintRun`: the census oracle and the rule ladder. + Build, + /// `vlog_linter::lint_with` itself. + Lint, + /// The formatter's fenced-region answer. + Fence, + /// Turning violations into what goes on the wire. + Serialize, +} + +impl Stage { + /// The name this stage is counted under in the `timing:` line. + fn label(self) -> &'static str { + match self { + Stage::Config => "config", + Stage::Build => "build", + Stage::Lint => "lint", + Stage::Fence => "fence", + Stage::Serialize => "serialize", + } + } + + /// Every stage, in the order a request passes through them — so a line + /// always carries the same fields whether or not a stage ran. + const ALL: [Stage; 5] = + [Stage::Config, Stage::Build, Stage::Lint, Stage::Fence, Stage::Serialize]; +} + +/// What the fence filter did, when a pass reached it at all. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum Fences { + /// No finding carried a fix, so the filter would have been the identity + /// and was not asked (take 5 §P1a). + #[default] + Skipped, + /// `protected_regions` parsed the buffer for this `Document`. + Computed, + /// The `Document`'s memo answered (take 5 §P1b). + Memo, +} + +impl Fences { + fn label(self) -> &'static str { + match self { + Fences::Skipped => "skipped", + Fences::Computed => "computed", + Fences::Memo => "memo", + } + } +} + +/// Whether a lint pass was answered from the snapshot (review round §R1a). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum Reuse { + /// No pass ran. + #[default] + None, + /// The `Document` held no snapshot, or held one for other inputs. + Miss, + /// The snapshot matched and `lint_with` did not run. + Hit, +} + +impl Reuse { + fn label(self) -> &'static str { + match self { + Reuse::None => "none", + Reuse::Miss => "miss", + Reuse::Hit => "hit", + } + } + + /// A hit only survives while every pass hit: one recompute in a request + /// is a miss for that request, which is what a reader wants to know. + fn saw(self, other: Reuse) -> Reuse { + match (self, other) { + (Reuse::Miss, _) | (_, Reuse::Miss) => Reuse::Miss, + (Reuse::Hit, _) | (_, Reuse::Hit) => Reuse::Hit, + _ => Reuse::None, + } + } +} + +/// One group of stages: the flush's, or the handler's own. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Group { + ms: [f64; Stage::ALL.len()], + /// How many times `lint_with` ran in this group. + passes: u32, + /// How many violations the last pass found. + violations: usize, + /// How many rules that pass ran. + rules: usize, + /// How many actions were serialized. + actions: usize, + /// How many waiver files were read from disk. + waivers: usize, + /// Whether a `lucisv.toml` was found and read. + toml: bool, + fences: Fences, + reuse: Reuse, +} + +impl Group { + /// The `const` form `thread_local!`'s initializer needs; `Default` is not + /// callable there. + const EMPTY: Group = Group { + ms: [0.0; Stage::ALL.len()], + passes: 0, + violations: 0, + rules: 0, + actions: 0, + waivers: 0, + toml: false, + fences: Fences::Skipped, + reuse: Reuse::None, + }; + + fn add(&mut self, stage: Stage, took: Duration) { + self.ms[stage as usize] += took.as_secs_f64() * 1_000.0; + } + + /// This group's fields, in the `key=value` shape `tools/perf` parses. + fn fields(&self) -> String { + let stages: Vec = Stage::ALL + .iter() + .map(|stage| format!("{}={:.2}ms", stage.label(), self.ms[*stage as usize])) + .collect(); + format!( + "{} passes={} rules={} violations={} actions={} waivers={} toml={} fences={} \ + snapshot={}", + stages.join(" "), + self.passes, + self.rules, + self.violations, + self.actions, + self.waivers, + self.toml, + self.fences.label(), + self.reuse.label(), + ) + } +} + +/// One request's trace: what the flush cost, and what the handler cost. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Trace { + /// The stages the debounced `Document` rebuild and its diagnostics + /// publish passed through, closed by [`close_flush`]. + pub flush: Group, + /// How long the whole flush took, publish included. + pub flush_ms: f64, + /// Buffers the flush rebuilt. + pub flush_buffers: usize, + /// Whole-file parses the flush performed (`vlog_parser::stats`). + pub flush_parses: u64, + /// The handler's own stages. + pub action: Group, +} + +impl Trace { + /// Whether this request touched the lint path at all. A trace that did + /// not is not worth a line. + pub fn is_empty(&self) -> bool { + self.flush == Group::default() && self.action == Group::default() && self.flush_buffers == 0 + } + + /// The whole trace as one `timing:`-style fragment. + pub fn line(&self) -> String { + format!( + "flush{{wall={:.2}ms buffers={} parses={} {}}} action{{{}}}", + self.flush_ms, + self.flush_buffers, + self.flush_parses, + self.flush.fields(), + self.action.fields(), + ) + } +} + +thread_local! { + /// One branch is the whole of what verbose-off costs at a traced site. + static ARMED: Cell = const { Cell::new(false) }; + static TRACE: RefCell = const { RefCell::new(Trace { + flush: Group::EMPTY, + flush_ms: 0.0, + flush_buffers: 0, + flush_parses: 0, + action: Group::EMPTY, + }) }; + /// Which group the stages recorded right now belong to. + static IN_FLUSH: Cell = const { Cell::new(true) }; +} + +/// Start a fresh trace for one request. Called by the request wrapper when +/// `--verbose` asked for timing, and by nothing else. +pub fn arm() { + ARMED.set(true); + IN_FLUSH.set(true); + TRACE.with_borrow_mut(|trace| *trace = Trace::default()); +} + +/// Whether a trace is being written — the one branch a caller checks before +/// reading a clock of its own. +pub fn armed() -> bool { + ARMED.get() +} + +/// Stop tracing and return what was written, or `None` when nothing armed it. +pub fn disarm() -> Option { + if !ARMED.replace(false) { + return None; + } + Some(TRACE.with_borrow(Clone::clone)) +} + +/// Close the flush group: everything recorded from here on is the handler's. +/// +/// `parses` is the `vlog_parser::stats::parses()` delta across the flush and +/// `buffers` is how many dirty buffers it rebuilt, so the `Document` rebuild +/// is readable beside the diagnostics pass that follows it. +pub fn close_flush(took: Duration, buffers: usize, parses: u64) { + if !ARMED.get() { + return; + } + TRACE.with_borrow_mut(|trace| { + trace.flush_ms = took.as_secs_f64() * 1_000.0; + trace.flush_buffers = buffers; + trace.flush_parses = parses; + }); + IN_FLUSH.set(false); +} + +/// Run `work`, counting what it took against `stage`. +/// +/// Untimed and unallocated when nothing armed a trace, which is every session +/// but a `--verbose` one. +pub fn stage(stage: Stage, work: impl FnOnce() -> T) -> T { + if !ARMED.get() { + return work(); + } + let started = Instant::now(); + let out = work(); + let took = started.elapsed(); + group(|held| held.add(stage, took)); + out +} + +/// Record what a lint pass ran and found. +pub fn saw_lint(rules: usize, violations: usize, reuse: Reuse) { + group(|held| { + held.passes += 1; + held.rules = rules; + held.violations = violations; + held.reuse = held.reuse.saw(reuse); + }); +} + +/// Record what the configuration read found: a `lucisv.toml`, and how many +/// waiver files it and the editor's settings between them named. +pub fn saw_config(toml: bool, waivers: usize) { + group(|held| { + held.toml |= toml; + held.waivers += waivers; + }); +} + +/// Record what the fence filter did. +pub fn saw_fences(fences: Fences) { + group(|held| held.fences = fences); +} + +/// Record how many actions were put on the wire. +pub fn saw_actions(actions: usize) { + group(|held| held.actions += actions); +} + +/// Apply `write` to whichever group is being filled, or to nothing at all. +fn group(write: impl FnOnce(&mut Group)) { + if !ARMED.get() { + return; + } + let flushing = IN_FLUSH.get(); + TRACE.with_borrow_mut(|trace| { + write(if flushing { &mut trace.flush } else { &mut trace.action }) + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Nothing is written when nothing armed a trace — the shipped state. + #[test] + fn an_unarmed_trace_records_nothing_and_returns_the_work() { + assert_eq!(disarm(), None); + assert_eq!(stage(Stage::Lint, || 7), 7); + saw_lint(3, 4, Reuse::Miss); + assert_eq!(disarm(), None, "still nothing to say"); + } + + /// The two groups are kept apart, and `close_flush` is what separates + /// them: a stage before it is the flush's, one after it the handler's. + #[test] + fn close_flush_divides_the_request_into_its_two_halves() { + arm(); + saw_lint(9, 100, Reuse::Miss); + close_flush(Duration::from_millis(110), 1, 1); + saw_lint(9, 100, Reuse::Hit); + saw_actions(2); + saw_fences(Fences::Memo); + let trace = disarm().expect("armed"); + assert_eq!(trace.flush.passes, 1); + assert_eq!(trace.flush.violations, 100); + assert_eq!(trace.flush.actions, 0, "the flush serializes nothing"); + assert_eq!(trace.flush_buffers, 1); + assert_eq!(trace.flush_parses, 1); + assert!((trace.flush_ms - 110.0).abs() < 5.0, "{}", trace.flush_ms); + assert_eq!(trace.action.passes, 1); + assert_eq!(trace.action.actions, 2); + assert_eq!(trace.action.fences, Fences::Memo); + assert_eq!(trace.action.reuse, Reuse::Hit); + assert_eq!(disarm(), None, "disarming twice says nothing twice"); + } + + /// One recompute in a request is a miss for that request: a reader asking + /// "did this menu re-lint?" must not be told "hit" because the second + /// pass reused what the first one had just computed. + #[test] + fn a_single_recompute_makes_the_whole_request_a_miss() { + arm(); + close_flush(Duration::ZERO, 0, 0); + saw_lint(9, 100, Reuse::Hit); + saw_lint(9, 100, Reuse::Miss); + assert_eq!(disarm().expect("armed").action.reuse, Reuse::Miss); + } + + /// Every stage is named in the line whether or not it ran, so a reader + /// (and `tools/perf/phases_r1.py`) always parses the same fields. + #[test] + fn the_line_names_every_stage_in_both_groups() { + arm(); + stage(Stage::Config, || {}); + close_flush(Duration::from_millis(1), 1, 1); + stage(Stage::Lint, || {}); + let line = disarm().expect("armed").line(); + for stage in Stage::ALL { + assert_eq!(line.matches(&format!("{}=", stage.label())).count(), 2, "{line}"); + } + assert!(line.contains("buffers=1"), "{line}"); + assert!(line.contains("snapshot=none"), "{line}"); + assert!(!line.contains(" "), "no empty field: {line}"); + } +} diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 5c52709..7fea135 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -31,6 +31,8 @@ mod large; mod lens; mod linked; mod lint; +mod lint_snapshot; +mod lint_trace; mod locate; mod module_select; mod nav; diff --git a/crates/lucisv_server/src/server/dispatch.rs b/crates/lucisv_server/src/server/dispatch.rs index 669d1bd..9260896 100644 --- a/crates/lucisv_server/src/server/dispatch.rs +++ b/crates/lucisv_server/src/server/dispatch.rs @@ -45,8 +45,8 @@ use super::client::ms; use super::Server; use crate::{ code_action, completion, design_hierarchy, extract, file_ops, folding, format, hierarchy, - hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, nav, pairs, ports, - rename, selection, signature, symbols, tokens, type_def, type_hierarchy, + hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, lint_trace, nav, + pairs, ports, rename, selection, signature, symbols, tokens, type_def, type_hierarchy, }; impl Server { @@ -61,18 +61,52 @@ impl Server { pub(super) fn request(&mut self, request: Request) -> Response { let Some(started) = self.timer() else { return self.answer_request(request) }; let method = request.method.clone(); + // One trace per request, armed here so the flush this request triggers + // is inside it: the diagnostics pass that publishes during the flush is + // the *other* consumer of a lint result, and the two are only readable + // against each other when one line carries both (review round §R1b). + lint_trace::arm(); let response = self.answer_request(request); self.timing(format!("{method} answered in {}", ms(started))); + // Silent for every request that never linted anything, which is all of + // them but the code actions and the flushes that publish diagnostics. + if let Some(trace) = lint_trace::disarm().filter(|trace| !trace.is_empty()) { + self.timing(format!( + "codeaction method={method} total={} {}", + ms(started), + trace.line() + )); + } response } + /// [`Server::flush_dirty`], with the dirty-buffer stage measured apart + /// from the handler that follows it. + /// + /// The review's item 4: *if the dirty-buffer stage dominates the 136 ms, a + /// lint cache alone cannot fix it*. The flush rebuilds each dirty + /// `Document` (parse and analysis, counted as whole-file parses) and then + /// publishes its diagnostics, which lints; the handler lints again. One + /// line carrying both is what makes the two comparable. + fn flush_dirty_traced(&mut self) { + if !lint_trace::armed() { + return self.flush_dirty(); + } + let buffers = self.dirty.len(); + let before = vlog_parser::stats::parses(); + let started = std::time::Instant::now(); + self.flush_dirty(); + let parses = vlog_parser::stats::parses().saturating_sub(before); + lint_trace::close_flush(started.elapsed(), buffers, parses); + } + fn answer_request(&mut self, request: Request) -> Response { // A request answers from a buffer's analysis, so any change the client // has already sent is in effect before it is answered — the order // contract the loop has always promised. Here is also where a typing // burst is coalesced: the changes before this request all become one // `set_document` in `flush_dirty`. - self.flush_dirty(); + self.flush_dirty_traced(); let id = request.id.clone(); let method = request.method.clone(); // The large-file fast path answers first, and for most methods it @@ -262,9 +296,9 @@ impl Server { if code_action::wants_fixes(only.as_deref()) { // A code-action request carries no `tabSize`, so the width a // `no-tabs` fix writes comes from the buffer's own `lucisv.toml` - // or from the built-in default. - let tab_width = - format::indent_width(doc.path.as_deref(), self.workspace.client_settings()); + // or from the built-in default — read by the run itself, off + // the `FileConfig` it discovers anyway, so this path no longer + // walks for a config file twice (review round §R1a). let run = lint::LintRun::for_document(&self.workspace, doc); actions.extend(code_action::code_actions( &run, @@ -272,7 +306,6 @@ impl Server { doc, p.range, only.as_deref(), - tab_width, )); } // The port refactorings answer for the cursor, not for a range: diff --git a/crates/lucisv_server/src/server/tests/lint_snapshot.rs b/crates/lucisv_server/src/server/tests/lint_snapshot.rs new file mode 100644 index 0000000..fb7b4a0 --- /dev/null +++ b/crates/lucisv_server/src/server/tests/lint_snapshot.rs @@ -0,0 +1,370 @@ +//! One test per row of the lint snapshot's invalidation table. +//! +//! Take 5 **review** round §R1a +//! (`docs/features/perf5r-lint-snapshot/README.md`). A `Document` keeps the +//! findings of one `lint_with` pass so that the diagnostics publish and +//! quick-fix discovery do not run the same 21 ms twice on one revision. What +//! makes that legitimate is that **every input which can change the answer +//! either builds a new `Document`, or is in the key, or clears the slot** — +//! and the README's table has one row per input. +//! +//! This file walks that table through the real doors: a `didChange`, a +//! `didChangeConfiguration`, a `lucisv.toml` rewritten on disk, a waiver file +//! rewritten in place, a watched file in **another** buffer, a close and +//! reopen, a UTF-16 range, a large buffer — and one attack, a fix offered for +//! a span the buffer no longer has. +//! +//! Reuse is observed by pointer, not by a stopwatch: two passes that share a +//! snapshot answer with the same `Arc`, and one that recomputed cannot. A +//! timing assertion on a lint pass would be a flake; `Arc::ptr_eq` is not. + +use std::sync::Arc; + +use vlog_linter::Violation; + +use super::*; +use crate::lint::{fixable, violations_in, LintRun}; + +/// A module with one tab in it: one `no-tabs` finding, carrying a Safe fix +/// whose text is the indent width. Line 1 is the tab. +const TABBED: &str = "module m;\n\twire a;\nendmodule\n"; + +/// A session over `tree` with `m.sv` open, its diagnostics already published. +fn opened(tree: &Tree, text: &str) -> (Session, Uri) { + let mut session = Session::wide(vec![tree.path.clone()], true); + let uri = session.open(&tree.path.join("m.sv"), text); + let _ = session.drain(); + (session, uri) +} + +/// The findings quick-fix discovery would offer for `uri` right now, taken +/// through the same two calls the dispatcher makes. +fn offered(session: &Session, uri: &Uri) -> Arc<[Violation]> { + let doc = session.server.workspace.document(uri).expect("an open buffer"); + let run = LintRun::for_document(&session.server.workspace, doc); + fixable(&run, doc) +} + +/// The rules that fired, by name, in the order they fired. +fn rules(found: &[Violation]) -> Vec<&'static str> { + found.iter().map(|violation| violation.rule).collect() +} + +/// The replacement text of the first fix, for the rows about fix bytes. +fn fix_text(found: &[Violation]) -> String { + let fix = found.first().and_then(|v| v.fix.as_ref()).expect("a fix"); + fix.edits.first().map(|(_, text)| text.clone()).expect("an edit") +} + +/// Push one `lucisv.lint.*` section and let the republish it triggers settle. +fn push_lint_settings(session: &mut Session, lint: Value) { + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { "lint": lint } } }), + ); + let _ = session.drain(); +} + +// ------------------------------------------------------------------ +// the headline: one pass, two consumers +// ------------------------------------------------------------------ + +/// The whole point of the round. A `didOpen` publishes diagnostics, which +/// lints; the code action that follows reads **that** answer rather than +/// running the rules again, and the two are the same object. +#[test] +fn the_diagnostics_publish_and_the_quick_fix_pass_share_one_lint() { + let tree = Tree::new("lsshare"); + let (session, uri) = opened(&tree, TABBED); + let doc = session.server.workspace.document(&uri).expect("open"); + assert!( + !doc.lint.is_empty(), + "the publish that answered the didOpen left its findings on the document" + ); + let run = LintRun::for_document(&session.server.workspace, doc); + let published = violations_in(doc, &run); + let fixes = fixable(&run, doc); + assert!(Arc::ptr_eq(&published, &fixes), "one pass answers both doors"); + assert_eq!(rules(&published), vec!["no-tabs"]); + // ... and asking twice more does not compute twice more. + assert!(Arc::ptr_eq(&fixes, &fixable(&run, doc))); +} + +// ------------------------------------------------------------------ +// row 1 — the buffer's own text +// ------------------------------------------------------------------ + +#[test] +fn an_edited_buffer_is_relinted() { + let tree = Tree::new("lsedit"); + let (mut session, uri) = opened(&tree, TABBED); + assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "premise"); + + change( + &mut session, + &uri, + 2, + serde_json::json!([{ "text": "module m;\n wire a;\nendmodule\n" }]), + ); + assert!( + offered(&session, &uri).is_empty(), + "the tab is gone, so the finding and its fix are gone" + ); + + change(&mut session, &uri, 3, serde_json::json!([{ "text": TABBED }])); + assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "and back again"); +} + +// ------------------------------------------------------------------ +// row 2 — the large-file fast path +// ------------------------------------------------------------------ + +#[test] +fn a_large_buffer_lints_nothing_and_stores_nothing() { + let tree = Tree::new("lslarge"); + let mut session = Session::wide(vec![tree.path.clone()], true); + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { "largeFile": { "threshold": 16 } } } }), + ); + let uri = session.open(&tree.path.join("m.sv"), TABBED); + let _ = session.drain(); + let doc = session.server.workspace.document(&uri).expect("open"); + assert!(doc.large, "premise: over the threshold"); + assert!(doc.lint.is_empty(), "a large buffer's publish lints nothing to keep"); + let menu = session.result( + CodeActionRequest::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "range": { "start": { "line": 1, "character": 1 }, + "end": { "line": 1, "character": 1 } }, + "context": { "diagnostics": [] }, + }), + ); + assert_eq!(menu, serde_json::json!([]), "and offers nothing"); + let doc = session.server.workspace.document(&uri).expect("open"); + assert!(doc.lint.is_empty(), "the request left no snapshot behind either"); +} + +// ------------------------------------------------------------------ +// rows 3 and 11 — the rule selection, pushed by the editor +// ------------------------------------------------------------------ + +#[test] +fn a_pushed_rule_selection_is_relinted() { + let tree = Tree::new("lsselect"); + let (mut session, uri) = opened(&tree, TABBED); + assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "premise"); + + push_lint_settings(&mut session, serde_json::json!({ "ignore": ["no-tabs"] })); + assert!(offered(&session, &uri).is_empty(), "the setting silenced the rule and its fix"); + + push_lint_settings(&mut session, serde_json::json!({ "ignore": [] })); + assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "and un-silenced it"); +} + +// ------------------------------------------------------------------ +// rows 4, 5, 8 and 12 — the `lucisv.toml`, rewritten under a running server +// with no watcher event of any kind +// ------------------------------------------------------------------ + +#[test] +fn a_rewritten_toml_is_relinted() { + let tree = Tree::new("lstoml"); + tree.write("lucisv.toml", "[lint]\nignore = [\"no-tabs\"]\n"); + let (session, uri) = opened(&tree, TABBED); + assert!(offered(&session, &uri).is_empty(), "premise: the project ignores the rule"); + + // Rewritten behind the server's back. `watch::SOURCE_GLOB` covers + // `**/*.{v,vh,sv,svh}` and the filelist, so **no event is sent** — the + // only thing that can notice is the per-request read and the key. + tree.write("lucisv.toml", "[lint]\nignore = [\"posix-eof\"]\n"); + assert_eq!( + rules(&offered(&session, &uri)), + vec!["no-tabs"], + "the next request read the new file" + ); +} + +// ------------------------------------------------------------------ +// row 6 — the indent width, which is a fix's bytes +// ------------------------------------------------------------------ + +#[test] +fn a_tab_width_change_rewrites_the_fix() { + let tree = Tree::new("lsindent"); + let (session, uri) = opened(&tree, TABBED); + assert_eq!(fix_text(&offered(&session, &uri)), " ", "premise: the default indent"); + + tree.write("lucisv.toml", "indent = 4\n"); + assert_eq!( + fix_text(&offered(&session, &uri)), + " ", + "the same finding, a different fix — and the snapshot must not hand back the old one" + ); +} + +// ------------------------------------------------------------------ +// row 7 — an external waiver file, rewritten in place +// ------------------------------------------------------------------ + +#[test] +fn a_rewritten_waiver_file_is_relinted() { + let tree = Tree::new("lswaiver"); + tree.write("lucisv.toml", "[lint]\nwaivers = [\"team.waiver\"]\n"); + tree.write("team.waiver", "waive --rule=no-tabs\n"); + let (session, uri) = opened(&tree, TABBED); + assert!(offered(&session, &uri).is_empty(), "premise: the waiver silences it"); + + // Rewritten to name a different rule. The two texts are different + // lengths, so this row alone would pass on a length check too — the + // same-length case is `lint_snapshot::tests`' + // `a_waiver_rewritten_in_place_is_a_different_key`. + tree.write("team.waiver", "waive --rule=posix-eof\n"); + assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "the waiver moved"); + + tree.write("team.waiver", "waive --rule=no-tabs\n"); + assert!(offered(&session, &uri).is_empty(), "and moved back"); +} + +// ------------------------------------------------------------------ +// rows 9 and 10 — the workspace index the census oracle reads +// ------------------------------------------------------------------ + +/// A change in **another** file, which is the row a document-revision key +/// could not have covered: this buffer's bytes never move, and what the +/// semantic rules say about it does. +#[test] +fn a_change_in_another_file_relints_this_one() { + let tree = Tree::new("lsoracle"); + let dut = "module dut;\n logic dbg_probe;\nendmodule\n"; + tree.write("dut.sv", dut); + tree.write( + "tb.sv", + "module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n", + ); + let mut session = Session::wide(vec![tree.path.clone()], true); + let uri = session.open(&tree.path.join("dut.sv"), dut); + let _ = session.drain(); + assert!( + offered(&session, &uri).is_empty(), + "premise: another file reads the signal, so it is not unused" + ); + + // The other file stops mentioning it, and the watcher says so. + tree.write("tb.sv", "module tb;\n dut d ();\nendmodule\n"); + session.watched(&[tree.path.join("tb.sv")]); + let _ = session.drain(); + assert_eq!( + rules(&offered(&session, &uri)), + vec!["unused-signal"], + "the index moved, so the snapshot had to go" + ); + + tree.write( + "tb.sv", + "module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n", + ); + session.watched(&[tree.path.join("tb.sv")]); + let _ = session.drain(); + assert!(offered(&session, &uri).is_empty(), "and back"); +} + +// ------------------------------------------------------------------ +// row 13 — close and reopen +// ------------------------------------------------------------------ + +#[test] +fn a_closed_and_reopened_buffer_is_relinted() { + let tree = Tree::new("lsreopen"); + let (mut session, uri) = opened(&tree, TABBED); + assert_eq!(rules(&offered(&session, &uri)), vec!["no-tabs"], "premise"); + + session.notify( + DidCloseTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ); + let _ = session.drain(); + assert!(session.server.workspace.document(&uri).is_none(), "the snapshot went with it"); + + let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n"); + let _ = session.drain(); + assert!(offered(&session, &uri).is_empty(), "reopened with different text, relinted"); +} + +// ------------------------------------------------------------------ +// row 14 — a fix's range, in UTF-16 units, off a reused snapshot +// ------------------------------------------------------------------ + +/// The snapshot holds byte spans; the range on the wire is built per request +/// from the buffer's text. A reused snapshot must therefore still produce +/// UTF-16 columns, which is the one place a cached *position* would have gone +/// wrong. +#[test] +fn a_snapshot_fix_keeps_its_utf16_range() { + let tree = Tree::new("lsutf16"); + // The `é` is two bytes and one UTF-16 unit; `🎉` is four bytes and two. + let text = "module m;\n // é 🎉\twire a;\nendmodule\n"; + let (mut session, uri) = opened(&tree, text); + let ask = serde_json::json!({ + "textDocument": { "uri": uri }, + "range": { "start": { "line": 1, "character": 9 }, + "end": { "line": 1, "character": 9 } }, + "context": { "diagnostics": [] }, + }); + // Twice: the first request may compute, the second is the reuse — and + // both must name the same UTF-16 column. + let first = session.result(CodeActionRequest::METHOD, ask.clone()); + let again = session.result(CodeActionRequest::METHOD, ask); + assert_eq!(first, again, "the reused answer is the computed one"); + let edit = &first[0]["edit"]["changes"][uri.as_str()][0]; + assert_eq!(edit["range"]["start"]["character"], 9, "in UTF-16 units, not bytes"); + assert_eq!(edit["range"]["start"]["line"], 1); +} + +// ------------------------------------------------------------------ +// the attack +// ------------------------------------------------------------------ + +/// The failure the previous lane deferred this memo over: a **stale fix +/// offer**. The buffer is edited so the bytes a previously offered fix named +/// no longer exist; the next menu must not offer that fix, and must not offer +/// an edit whose range runs past the end of the buffer. +#[test] +fn a_fix_is_never_offered_for_a_span_the_buffer_no_longer_has() { + let tree = Tree::new("lsattack"); + // Two tabs, far apart, so the second fix's span is deep into the buffer. + let long = format!("module m;\n\twire a;\n{}\twire z;\nendmodule\n", " // pad\n".repeat(40)); + let (mut session, uri) = opened(&tree, &long); + let before = offered(&session, &uri); + assert_eq!(before.len(), 2, "two tabs, two fixes: {:?}", rules(&before)); + let deepest = before.iter().map(|v| v.span.end).max().expect("a span"); + assert!(deepest as usize > 40, "premise: the fix is deep in the buffer"); + + // Now the buffer becomes three lines long. Every byte the second fix + // named is gone. + let after_text = "module m;\n wire a;\nendmodule\n"; + change(&mut session, &uri, 2, serde_json::json!([{ "text": after_text }])); + let after = offered(&session, &uri); + assert!(after.is_empty(), "no fix survives the text that justified it: {:?}", rules(&after)); + + // ... and through the wire, where a stale span would be a range past the + // end of a three-line document. + let menu = session.result( + CodeActionRequest::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "range": { "start": { "line": 0, "character": 0 }, + "end": { "line": 2, "character": 9 } }, + // The fix families alone: an extraction is offered for any whole + // selection and is not what this row is about. + "context": { "diagnostics": [], "only": ["quickfix", "source.fixAll.lucisv"] }, + }), + ); + assert_eq!(menu, serde_json::json!([]), "and nothing is offered: {menu:#?}"); + assert_eq!( + session.server.workspace.document(&uri).expect("open").text, + after_text, + "the buffer the answer describes is the buffer the client has" + ); +} diff --git a/crates/lucisv_server/src/server/tests/mod.rs b/crates/lucisv_server/src/server/tests/mod.rs index 5e535d9..def3dcf 100644 --- a/crates/lucisv_server/src/server/tests/mod.rs +++ b/crates/lucisv_server/src/server/tests/mod.rs @@ -55,6 +55,7 @@ mod formatting; mod hierarchy_reach; mod index; mod large_file; +mod lint_snapshot; mod progress; mod pull_diagnostics; mod requests; diff --git a/crates/lucisv_server/src/state/mod.rs b/crates/lucisv_server/src/state/mod.rs index 3143c02..54956fa 100644 --- a/crates/lucisv_server/src/state/mod.rs +++ b/crates/lucisv_server/src/state/mod.rs @@ -105,6 +105,14 @@ pub struct Document { /// [`crate::fences::of`], which is the only thing that may touch it; it /// is bound to this revision because a change builds a new `Document`. pub fences: std::sync::OnceLock>, + /// This buffer's lint findings, kept while every input that produced them + /// is unchanged — read by the diagnostics pass and by quick-fix discovery + /// alike, so one revision is linted once rather than twice (review round + /// §R1a, `crate::lint_snapshot`). Bound to this revision for the same + /// structural reason `fences` is; the inputs that can move *without* a new + /// `Document` are the snapshot's own key, and the index moving is + /// [`Document::refresh_overlay`], which clears it. + pub lint: crate::lint_snapshot::Slot, } impl Document { @@ -139,6 +147,7 @@ impl Document { external, large, fences: std::sync::OnceLock::new(), + lint: crate::lint_snapshot::Slot::new(), } } @@ -165,6 +174,7 @@ impl Document { external: ExternalResolutions::default(), large: true, fences: std::sync::OnceLock::new(), + lint: crate::lint_snapshot::Slot::new(), } } @@ -184,6 +194,12 @@ impl Document { /// single-file analysis is unaffected by other files, by construction. pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) { self.external = resolve_external(&self.semantics, index); + // The index is what the census oracle answers from, so a lint result + // taken under the old one is no longer this buffer's answer. This is + // the whole of the snapshot's index invalidation: every mutation of + // `Workspace::index` ends in the loop that calls this, so there is no + // generation counter to keep in step (review round §R1a). + self.lint.clear(); } /// What this buffer contributes to the workspace index, read off the diff --git a/docs/features/perf5r-lint-snapshot/README.md b/docs/features/perf5r-lint-snapshot/README.md new file mode 100644 index 0000000..daa6ae9 --- /dev/null +++ b/docs/features/perf5r-lint-snapshot/README.md @@ -0,0 +1,602 @@ +# perf5r-lint-snapshot — the code-action path on a large file + +Take 5 **review** round (`docs/performance_take5_review.md` §1), TODO §61.2, +tracker rows **R1b** (the stage trace) and **R1a** (the lint-result snapshot). +Baseline is 0.51.0; the paired reference for this lane is trunk at `51cbfd2`, +which is 0.51.0 plus §61.1's rename preflight — a change on the rename path +that this lane does not touch. + +## Goal + +A `textDocument/codeAction` on a comment in `pinmux_reg_top.sv` (42 192 lines, +1.3 MB, generated) costs **25 ms**, of which **23 ms is the quickfix family**, +and the first request after a one-character edit costs **136 ms**. The review's +own reading is that `lint.rs::fixable` calls `lint_with` on every request and +nothing memoizes the result; take 5 §P1's lane deferred that memo because "its +key is a different shape from anything else in this lane" and its failure mode +is a **stale fix offer**. + +This lane does the two halves the review asks for, in its order: + +* **R1b, first: measure.** One `timing: codeaction …` line per request behind + `--verbose`, splitting the request into config discovery, `LintRun` build, + lint pass, fence filter and action serialization — and, separately, the + **flush**: the debounced `Document` rebuild that `answer_request` performs + before any handler runs, with the diagnostics pass that publishes inside it + split the same five ways. No behaviour change. +* **R1a, then: reuse.** One lint-result snapshot per open `Document`, keyed by + every input the result depends on, read by the **diagnostics** pass and by + **quick-fix discovery** alike, recomputed whenever the key does not match. + The fence authority and execute-time validation are untouched. + +**What must not move:** which diagnostics are published, which fixes are +offered, and their bytes. A menu that is fast because it is stale is a +failure, and so is a fix offered for a finding the current buffer no longer +has. + +## What the measurement said (R1b) + +`tools/perf/phases_r1.py::actionprofile`, three cursors, four request shapes, +`--verbose`, one warm session each. Milliseconds, `--tries 3`, repeat median +of the wire time and the trace of the last request. + +| pinmux comment | wire | flush wall | flush parses | flush lint | action config | action build | action lint | fence | serialize | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| first request of the session | 25.10 | 0.00 | 0 | 0.00 | 0.20 | 0.06 | **22.43** | 0.00 | 0.05 | +| repeated, unchanged buffer | 21.97 | 0.00 | 0 | 0.00 | 0.04 | 0.01 | **20.87** | 0.00 | 0.03 | +| definition queued behind it | 22.33 | 0.00 | 0 | 0.00 | 0.04 | 0.02 | **20.96** | 0.00 | 0.03 | +| first request after a `didChange` | 127.54 | **99.72** | 1 | **21.08** | 0.03 | 0.01 | **20.22** | 0.00 | 0.03 | + +Read off those numbers: + +* **The 23 ms is the rules.** Config discovery — the `lucisv.toml` walk, + `ProjectLint::read` and the waiver reads — is **0.04 ms** on a repeat + (0.20 ms on the first request of a session, which is the OS cache warming). + The `LintRun` build is 0.01–0.06 ms. The fence filter costs **nothing**: + this buffer has **zero** violations, so §P1a's "no fix, no fence parse" gate + answers before the memo is asked. Serialization is 0.03 ms. **99% of the + quickfix menu is `lint_with`.** +* **Which rules.** `tools/perf/phases_r1.py::ruleablation` pushes + `lucisv.lint.select` one rule at a time through `didChangeConfiguration` + and times the same quickfix-only menu under each. The floor — one cheap + rule, so context construction and transport alone — is **1.3–1.4 ms**. + Three rules stand out, and they are the three **semantic** ones that read + the buffer's `Semantics` and the workspace census: + + | rule | repeat median | over the floor | + |---|---:|---:| + | `unused-signal` | 9.52 | **+8.2** | + | `undriven-net` | 8.69 | **+7.4** | + | `multiply-driven` | 8.88 | **+7.5** | + | every other default rule (55 of them) | 1.24–3.51 | ≤ +2.2 | + | control, all 57 default rules | 20.19 | +18.9 | + + The three semantic rules are effectively the whole of it; the remaining 55 + rules together account for about 2 ms. (Single-rule rows each pay the + shared context setup once, so the three do not add up to 18.9 exactly — + the ranking is what this row set establishes, not an exact partition.) +* **The 136 ms first-after-edit is mostly *not* the lint pass.** Of 127.5 ms: + **99.7 ms is the flush** (one whole-file parse and the analysis of 1.3 MB, + plus the diagnostics publish it triggers) and **20.2 ms is the handler's own + lint pass**. Inside the flush, the diagnostics pass is **21.1 ms** of the + 99.7 — so the `Document` rebuild itself is about **78.6 ms**, and the + request runs **`lint_with` twice on the same revision**: once to publish + diagnostics, once to discover quick fixes. + + That is the review's item 4 answered with a number: **a lint cache alone + cannot fix the 136 ms**, because 79 ms of it is `Document::new`. What a + snapshot can take out of it is one of the two 21 ms passes. + +The small-file controls behave as expected and are recorded in full: +`tb.sv` 0.52 ms unchanged / 0.98 ms after a change (flush 0.49 ms), the +`aes.sv` `aes_reg_top` cursor 3.2 ms / 4.19 ms (flush 1.10 ms). + +## The dependency / invalidation table + +Written **before** any cache, as the review requires. One row per input that +can change a lint result or a fix. "How the key observes it" is the mechanism, +not a hope; "test" is the test that flips that row and asserts a fresh result. + +`lint_with(ctx, rules, external)` is a pure function of its three arguments, +and `ctx = LintContext::from_parse(text, tokens, tree, line_index, path) +.with_semantics(&doc.semantics).with_options(options).with_line_length(w) +.with_tab_width(t)` plus the oracle. So the table below is complete by +construction: every argument of that expression is a row. + +| # | input | how it can change | how the key observes it | test | +|---|---|---|---|---| +| 1 | document text, tokens, tree, `semantics`, line index, path | `didOpen`, `didChange`, a text-carrying `didSave`, `willRenameFiles` | **identity.** The snapshot is a field on the `Document`, and `Workspace::set_document` builds a **new** `Document` for every flushed change and drops the old one. There is no revision number to compare because there is no way to hold the wrong one — the same argument `crate::fences` already rests on | `an_edited_buffer_is_relinted` | +| 2 | `doc.large` | a buffer crossing `lucisv.largeFile.threshold` in either direction | identity (row 1: the mode is re-taken in `set_document`, which builds a new `Document`). A large buffer never reaches the pass at all: `codeAction` is answered `[]` by `large_file.rs` before any handler, and `diagnostics::all_in` returns empty | `a_large_buffer_lints_nothing_and_stores_nothing` | +| 3 | the enabled rule set | `lucisv.lint.select` / `ignore` / `severity.` / `rules.` pushed by `didChangeConfiguration`; `[lint] select` / `ignore` in the buffer's `lucisv.toml` | `Key.rules`: the `&'static str` names the ladder produced, in registry order, compared **exactly** (not hashed) | `a_pushed_rule_selection_is_relinted`, `a_rewritten_toml_is_relinted` | +| 4 | merged rule options | `[lint.]` tables in `lucisv.toml`; `lucisv.lint.options` from the editor | `Key.options`: the merged `RuleOptions`, compared exactly (`PartialEq`) | `a_rewritten_toml_is_relinted` | +| 5 | line width | `line-length` in `lucisv.toml`; `lucisv.lineLength` | `Key.line_length` | `a_rewritten_toml_is_relinted` | +| 6 | tab width (fix **text** only) | `indent` in `lucisv.toml`; `lucisv.indent` | `Key.tab_width`. Since this lane the width lives on the `LintRun` — read there through `format::indent_width`, which used to be called by the dispatcher — so the diagnostics pass and the quick-fix pass build the *same* context and share one snapshot. Only `no-tabs`' fix string reads it, and the diagnostics path never reads a fix, so no published diagnostic moves | `a_tab_width_change_rewrites_the_fix` | +| 7 | external waiver file **contents** | any edit of a file named by `[lint] waivers` or by `lucisv.lint.waivers` | `Key.waivers`: `(path, text)` per file, in the order they are read — the **exact text** `ExternalWaivers::parse` was handed, not a hash and not an mtime. One read, not two: `lint.rs` now reads the bytes itself and parses them, reproducing `ExternalWaivers::read`'s error sentence byte for byte | `a_rewritten_waiver_file_is_relinted` | +| 8 | the `lucisv.toml` itself | any edit of the discovered config file; a new config file appearing in a parent directory | **through rows 3–7.** Nothing in a `lucisv.toml` reaches a lint result except the selection, the options, the width, the indent and the waiver paths, and all five are in the key. `LintRun::for_document` re-runs `Discovery::for_file` on **every** request (0.04 ms, measured above), so a rewritten file is in the key at the next request | `a_rewritten_toml_is_relinted` | +| 9 | the workspace index the census oracle reads | `publish_scan`, both `finish_scan` paths, `update_one` — i.e. a scan step, a scan finishing, a `didSave` or a watcher event in **another** file | **not a key field: an explicit drop.** All four of those call sites end with `for doc in self.docs.values_mut() { doc.refresh_overlay(&self.index) }`, and `refresh_overlay` — the one place a `Document` is told the index moved — clears the snapshot. Verified by exhaustion: `self.index.{absorb,remove_file,update_facts,update_file}` occurs nowhere else in `state/` | `a_change_in_another_file_relints_this_one` | +| 10 | whether there is an oracle at all | the first scan of a session that began with an empty index | `Key.has_oracle`, **and** row 9's drop | `a_workspace_appearing_turns_the_semantic_rules_on` | +| 11 | client settings generation | `workspace/didChangeConfiguration`, or the reply to `workspace/configuration` | through rows 3–7; `apply_settings` also republishes every open buffer, which recomputes under the new key immediately | `a_pushed_rule_selection_is_relinted` | +| 12 | file-watcher events on the `lucisv.toml` / the waiver files | **there are none.** `watch::SOURCE_GLOB` is `**/*.{v,vh,sv,svh}` and the only other watcher is the configured filelist's own path | rows 7 and 8 are what make this safe: both files are re-read per request, so no watcher is needed and none is added | `a_rewritten_toml_is_relinted` (no watcher event is sent) | +| 13 | close and reopen | `didClose` then `didOpen` | identity: `close_document` removes the `Document`, and with it the snapshot | `a_closed_and_reopened_buffer_is_relinted` | +| 14 | UTF-16 ranges | — | **not an input.** `Positions` is built from `doc.text` per request in `code_action.rs` and `lint::diagnostics_in`; nothing positional is stored in the snapshot, which holds byte spans exactly as `lint_with` returned them | `a_snapshot_fix_keeps_its_utf16_range` | + +Two things are deliberately **not** in the key: + +* **A hash of anything.** Every field is compared by value. A 64-bit digest + would have been smaller and would have made "no stale fix" an argument + about collision probability instead of a fact. +* **A time or a generation number for the config files.** An mtime is a + weaker statement than the contents and is wrong across a same-second + rewrite; the contents are already in hand because the pass reads them. + + +## What R1a bought (paired) + +Reference `51cbfd2` (`5d2a7aa2a4fd…`) against the same tree plus this lane's +diff (`827c7ac222c8…`), both `--release --locked`, the same schema-2 harness, +phase order alternating which binary went first, no build during any timed +run, `--tries 3`, repeat medians. Load 2.5–5.9 one-minute, inside the review's +own 2.8–6.0 band; zero guard kills; opentitan `git status --porcelain` = the +same three pre-existing files after every phase. + +| workload | `51cbfd2` | this lane | change | +|---|---:|---:|---| +| pinmux comment, **all** action families, unchanged | 22.61 | **0.98** | **−95.6%** | +| pinmux comment, **quickfix only**, unchanged | 24.51 | **0.11** | **−99.5%** | +| pinmux comment, empty family filter | 0.05 | 0.05 | unchanged | +| pinmux menu, repeated on the unchanged buffer (`offeredit`) | 23.44 | **0.18** | **−99.2%** | +| **definition queued** behind the pinmux menu (leader / follower, pipeline 3) | 22.39 / 22.38 | **0.78 / 0.76** | **−96.5%** | +| pinmux comment, **first offer after a `didChange`** | 125.65 | **106.89** | **−14.9%** | +| `tb.sv` comment, unchanged / after a change | 0.19 / 1.26 | 0.23 / 1.45 | +0.04 / +0.19 ms | +| `aes.sv` `aes_reg_top`, unchanged / after a change | 2.86 / 3.83 | 2.58 / 3.62 | −9.7% / −5.5% | +| diagnostics publish after `didChange` (≈150 ms of it is the debounce) | 162.29 | 162.75 | **+0.3%** | +| `didOpen pinmux_reg_top.sv` → definition | 120.45 | 110.42 | −8.3% | +| `didOpen aes.sv` / `aes_core.sv` / `spi_device.sv` → definition | 4.53 / 5.72 / 8.68 | 3.49 / 5.56 / 8.15 | −23% / −3% / −6% | +| take-3 `codeaction` cells (eager, fan-out 1 / 6 / comment) | 21.37 / 88.44 / 1.67 | 21.60 / 89.74 / 1.56 | +1.1% / +1.5% / −6.7% | +| idle RSS, 100 open buffers each asked for quick fixes (MiB) | 574.0 | **574.6** | **+0.1%** | +| idle RSS, 10 / 1 buffers (MiB) | 429.4 / 420.9 | 428.4 / 422.2 | ±0.3% | + +**Gates.** + +* *unchanged pinmux menu ≤ 16 ms* — **met, 0.98 ms** (quickfix-only 0.11 ms). +* *queued definition ≤ 16 ms* — **met, 0.76 ms**. +* *first-after-edit improved, reported separately with its stage split* — + **125.65 → 106.89 ms, −14.9%**, and the split says exactly why that is the + whole of what a lint cache can do here: of the candidate's 109 ms, **106 ms + is the flush**, of which **21.9 ms is the diagnostics pass** and the + remaining ~84 ms is `Document::new` on 1.3 MB. The handler's own lint pass + is **0.00 ms — it does not run**. The remaining stage is named and is not + this lane's: the parse and analysis of a 1.3 MB buffer. +* *diagnostics publish unchanged* — **met, +0.3%** (inside the run-to-run + spread of a 150 ms debounce). +* *no higher retained memory* — **met, +0.1% at 100 open buffers**, all of + them holding a snapshot. +* *no stale diagnostic or fix under any invalidation row* — 11 server tests + and 10 unit tests, one per row plus the attack; see below. + +The candidate's own trace, at the same three cursors: + +| pinmux comment | wire | flush wall | flush lint | flush snapshot | action lint | action snapshot | +|---|---:|---:|---:|---|---:|---| +| first request of the session | 2.07 | 0.00 | 0.00 | — | **0.01** | **hit** | +| repeated, unchanged | 0.72 | 0.00 | 0.00 | — | **0.00** | **hit** | +| definition queued behind it | 0.23 | 0.00 | 0.00 | — | **0.00** | **hit** | +| first after a `didChange` | 109.39 | 106.09 | **21.87** | miss | **0.00** | **hit** | + +The first request of a *session* already hits: the `didOpen` published +diagnostics, and that pass is the one the menu reads. A queued definition logs +no trace line of its own at all — it lints nothing — which is what the +`result_count` of those rows says. + +**The config-discovery decision: leave it.** The review allows memoizing the +`FileConfig` read "if the trace says that I/O is material". It does not: +0.04–0.16 ms on a repeat, against a 21 ms pass. Memoizing it would have added +a second key (path, mtime, length) whose failure mode is a *stale rule +selection* — and the `lucisv.toml` and the waiver files are not watched +(table row 12), so that per-request read is the only thing that ever notices +one of them changing. It stays. + +The one thing that did move is where the **indent width** is read. It used to +be `format::indent_width`, called by the dispatcher; it is now the same +function, called by `LintRun::for_document`, because the two doors must build +the same context to share one snapshot. A code-action request therefore does +the same two `Discovery` walks it always did (one in `configured`, one in +`indent_width`); the **diagnostics publish now does two where it did one**. +Measured, that moved the config stage from about **0.04 to 0.15 ms** on a +repeat and left the publish row at **+0.3%**, inside the spread of a 150 ms +debounce. It is stated rather than hidden, and the fix is a handshake request +below, not a second spelling of the indent ladder here. + +## Assumptions + +- **`lint_with` is deterministic and side-effect-free** given `(ctx, rules, + external)`. Not enforced by a type; it is what makes a snapshot legitimate + at all. Pinned by `a_recomputed_snapshot_equals_a_fresh_pass`, which lints + the same document twice through the two doors and compares every violation. +- **A `Document`'s derived fields are a pure function of its text.** The same + assumption `crate::fences` (§P1b) already ships on, and the reason identity + can stand in for a revision number in row 1. +- **`refresh_overlay` is called for every open buffer at every index + mutation.** Established by exhaustion over `state/mod.rs` (row 9) rather + than by a type. A new index mutation that skipped it would be a stale + oracle for `external` resolution too, which is a pre-existing contract this + lane now also depends on — stated in Handshakes. +- **`format::indent_width` stays the one authority on the indent ladder.** + `LintRun::for_document` calls it rather than re-deriving the width from the + `FileConfig` it already read, which costs a second `Discovery` walk — worth + hundredths of a millisecond against a 21 ms pass, and worth not having two + spellings of a rule that decides a fix's bytes. Pinned rung by rung by + `the_runs_tab_width_is_the_formatters_own_ladder`. The dispatcher's own call + to it is gone, so the request as a whole does not walk more often than + before. + +## Handshakes + +**Consumed** + +- `vlog_linter::{lint_with, ExternalWaivers::parse, RuleOptions}` — unchanged. + `ExternalWaivers::parse` (already public) is now called directly instead of + `ExternalWaivers::read`, so the file's text is in hand for the key; the + error sentence for an unreadable file is reproduced verbatim + (`format!("{}: {e}", path.display())`). +- `vlog_formatter::fence::protected_regions` through `crate::fences` — the + shared-fence-filter contract (`docs/features/shared-fence-filter/`) is + **not** amended. `fences.rs` gains one read-only predicate, `held`, which + the trace uses to say whether a request paid the parse; it decides nothing. +- `crate::state::Document::refresh_overlay` — the existing "the index moved" + hook. This lane makes it also drop the lint snapshot. +- `vlog_parser::stats::parses` — the flush's parse count in the trace. + +**Promised** + +- `crate::lint::violations_in` and `crate::lint::fixable` now return + `Arc<[Violation]>` instead of `Vec`, and `fixable` no longer + takes a `tab_width` — the width comes from the `LintRun`. In-crate callers + only (`lucisv_server` is a binary crate): `diagnostics.rs`, `code_action.rs` + and their tests. +- `crate::lint_trace` is new and is written to from `lint.rs`, + `code_action.rs` and `server/dispatch.rs`. It is a thread-local + accumulator, armed per request; nothing outside `--verbose` observes it. + +**Requested of another module** + +- `crate::format` (not this lane's file): `indent_width(path, client)` runs its + own `Discovery` walk, and `LintRun::for_document` has already discovered the + same `FileConfig` a line earlier. A form taking that `FileConfig` + — `indent_width_of(&FileConfig, &ClientSettings)`, with today's function as a + one-line wrapper — would let the lint pass pay one walk instead of two. The + cost of not having it is measured above (about **+0.11 ms** on the config + stage, publish row +0.3%), which is why this lane did not spell the ladder a + second time to avoid it: one authority on a fix's bytes is worth more than + 0.11 ms. Nothing else is needed in `vlog_linter`, `vlog_formatter`, + `fence.rs` or `state/scan.rs`. + +**`docs/topo.md`** — this lane adds one edge (`lint.rs ──▶ lint_snapshot.rs`, +`lint.rs ──▶ lint_trace.rs`, `state/mod.rs ──▶ lint_snapshot.rs` for the +field) and amends the `server-lint ◀──▶ diagnostics` edge to say the two now +share one computed result. `topo.md` is not this lane's file: the amendment is +requested here for the lead to apply at merge. + +## Status / TODO + +- [x] R1b — the `timing: codeaction …` stage trace (`lint_trace.rs`), with the + flush group and its parse count; `fences::held` for the memo hit +- [x] R1b — the harness: `tools/perf/phases_r1.py`, phases `actionprofile` + (three cursors × four request shapes) and `ruleablation` (one row per + default-on rule) +- [x] R1b — measured, and the 23 ms / 136 ms attributed (above) +- [x] the dependency/invalidation table, written before the cache +- [x] R1a — `lint_snapshot.rs`, the `Document` field, both consumers +- [x] R1a — one invalidation test per table row, plus the stale-fix attack +- [x] R1a — measured paired against `51cbfd2`; the 100-buffer RSS cell +- [x] tracker cells R1a/R1b and both experiment records; TODO §61.2 + +## Work log + +**2026-09-08 — dev (Opus), R1b.** + +- `crates/lucisv_server/src/lint_trace.rs` (new): a thread-local stage + accumulator in `vlog_parser::stats`' shape — per thread because a request is + answered on one thread, and armed only by the request wrapper when + `--verbose` asked. Off costs one `Cell` read per traced site: no clock, + no allocation, no line. Two groups per request, `flush` and `action`, + divided by `close_flush`, so the diagnostics pass that publishes during the + debounced flush is readable beside the handler's own pass. +- `lint.rs`: `LintRun::for_document`'s body split into `Discovered::read` + (everything read from disk) and `Discovered::into_run` (the oracle and the + rule ladder), so the I/O has a stage of its own. The calls, their order and + the order the config problems are collected in are unchanged. One place now + calls `lint_with` (`found`), which is what makes one trace site enough. +- `dispatch.rs`: `flush_dirty_traced` wraps the flush with a clock and a + `vlog_parser::stats::parses()` delta, but only when a trace is armed; + `Server::request` arms one and logs `timing: codeaction method=… total=… ` + + the two groups, for any request that linted anything — which is the code + actions and any request whose flush published diagnostics, so the queued + definition gets its own line. +- Deviation, stated: the flush is traced as **one** stage plus its parse + count, not split into parse / analysis / overlay-refresh. Those three live + inside `Document::new` and `Workspace::set_document` in `state/mod.rs`, + which this lane owns only for the snapshot field and its initializers; + splitting them means threading a trace through `set_document`'s signature. + The number the review asks for — dirty-buffer stage versus lint pass — is + fully answered without it: flush 99.7 ms of which the diagnostics lint is + 21.1, so the rebuild is ~78.6 ms. +- Measured (§R1b cells above). Zero guard kills; opentitan + `git status --porcelain` = the three known files after every phase; load + 1.9–3.6 one-minute, inside the review's own 2.8–6.0 band. + + +**2026-09-08 — dev (Opus), R1a.** + +- `crates/lucisv_server/src/lint_snapshot.rs` (new): `Key` — the inputs, by + value — and `Slot`, a `Mutex>` on the `Document`. `read_or` + answers from the slot when the key matches and otherwise computes with the + lock released and replaces what is held. No hash anywhere: the waiver files' + **text** is compared, not a digest, so "can this offer a stale fix?" is a + `PartialEq` question. `Mutex` rather than `RefCell` so a `Document` stays + `Sync` exactly as its `OnceLock` fence memo leaves it; a poisoned lock (which + a single message loop with no panicking library code cannot produce) + degrades to computing every time. +- `state/mod.rs`: **one field** (`Document::lint`), its two initializers, and + one line in `refresh_overlay` — the hook that already exists for "the index + moved" — which clears it. That line is the whole of the index invalidation + and is why there is no generation counter to keep in step. Four lines of + production code in that file; it is over the size threshold already (1 063 → + 1 067 by the CLAUDE.md measure) and TODO §55 owns that. +- `lint.rs`: one `found(doc, run)` reads the slot and both doors call it, so + the diagnostics publish and quick-fix discovery are **one** pass. Both now + return `Arc<[Violation]>`; `fixable` copies only when the fence filter + actually drops something, which on a buffer with no `// lucisv: off` region + is never. The **tab width moved onto the `LintRun`** (read through + `format::indent_width`, whose call the dispatcher no longer makes) — without + that the two doors would build different contexts and thrash one slot. + Waiver files are read with `read_to_string` + `ExternalWaivers::parse` + instead of `ExternalWaivers::read`, one read still, so the text is in hand + for the key; the unreadable-file sentence is reproduced verbatim. +- Found by an existing test, and worth recording: the first version let a test + helper set `external` without the matching text, so two runs with different + waivers shared a key. `with_external` became `with_waivers(path, text)`, + which writes both — the invariant is now structural, and the field's doc + comment says so. +- Tests: 21 added, none removed (4 322 → 4 343 in the guarded workspace run). + 11 in `server/tests/lint_snapshot.rs`, one per table row through the real + doors plus the **stale-fix attack** (a buffer edited so the span a previously + offered fix named no longer exists — nothing is offered, and the wire answer + is empty); 4 in `lint_snapshot.rs` (every field of the key forces a + recompute; a waiver rewritten in place is a different key); 4 in + `lint_trace.rs`; 2 in `lint.rs` (the tab-width ladder rung by rung, and a + reused snapshot compared violation for violation and fix for fix against a + fresh `lint_with`). +- Reuse is asserted **by pointer** (`Arc::ptr_eq`), never by a stopwatch: a + timing assertion on a lint pass is a flake. +- Harness fix during the run: `actionprofile`'s queued rows attributed trace + lines by position, and a definition that lints nothing logs no line, so two + leaders were recorded as a leader and a follower. Lines are now attributed + by their own `method` field and `result_count` says how many the follower + logged. The `r1a-cand` `actionprofile` rows in the evidence file predate that + fix and are superseded by `r1a-cand-2`; no number quoted anywhere came from + the mis-attributed field (the R1b table's queued row is the leader's split, + which is what it always was). +- Measured (above). Zero guard kills; opentitan clean after every phase. + +## QA log + +**2026-09-08 — QA (Sonnet).** + +Read CLAUDE.md, TODO §61.2, `docs/performance_take5_review.md` §1, this +README in full, `perf5-p1`'s deferral memo, `semantic-lints-on`'s oracle +handshake, and `docs/perf/take5-tracking.md`'s R1a/R1b records plus both +experiment records, before touching anything. + +**Gates, guarded, main tree.** `cargo fmt --all -- --check` clean. +`cargo clippy --all-targets --workspace` clean after touching every changed +file to defeat the incremental cache — no new `#[allow]` anywhere in the +diff. `cargo test --workspace` (guarded, `tools/guard.sh -m 8 -t 1800`): +**4 343 passed, 0 failed**, matching the dev's own count exactly. Cross-checked +independently: cloned trunk `51cbfd27dfd22720856c501c9c17277460cc6a68` fresh +into scratch (no diff), built and tested the same way — **4 322 passed, 0 +failed**. `cargo test --workspace -- --list`, name-sorted and `comm`-diffed +between the two trees: **zero names removed, exactly 21 added**, and the 21 +match the dev's own breakdown byte for byte (11 in +`server::tests::lint_snapshot`, 4 in `lint_snapshot::tests`, 4 in +`lint_trace::tests`, 2 in `lint::tests`). Production line counts (non-blank, +non-comment, up to `mod tests`): `lint.rs` 334, `dispatch.rs` 464, +`lint_snapshot.rs` 54, `lint_trace.rs` 207 — all four numbers match what the +dev's own measure would produce; note for whoever wrote my brief: the file +names for the last two are transposed there (the *smaller* file is +`lint_snapshot.rs`, holding `Key`/`Slot`, and the *larger* is `lint_trace.rs`, +holding `Stage`/`Group`/`Trace`) — a wording slip, not a code finding. +`state/mod.rs`: read the diff directly rather than counting — exactly one +field (`pub lint: crate::lint_snapshot::Slot`), two initializers (`Document::new` +and the large-file constructor), and one line in `refresh_overlay` +(`self.lint.clear();`). All files well inside the 300–600 target; no file +pushed over a threshold. + +**The invalidation table, derived independently first.** Read `found`'s call +to `lint_with` and `LintRun::context`/`LintRun::key` and listed every input +that reaches `lint_with(ctx, rules, external)`: buffer text/tokens/tree/ +line_index/path (`context(doc)`), `options`, `line_length`, `tab_width` +(fix text only), the oracle (`has_oracle` plus the index's own answers), +`rules`, `external` (waiver contents), and `doc.large` (gates the whole path +before any of this runs) — nine independent inputs, matching the table's 14 +rows exactly once the table's own splits (rows 3/11 both being "the rule +selection", 4/5/8/12 all being "the toml", 9/10 both being "the index") are +collapsed back to the inputs of the call. Nothing reaches `lint_with` that +the table's rows do not name. Read `state/mod.rs`'s four index-mutating call +sites (`publish_scan`, `finish_whole_scan`, `finish_widen`, `update_one`) in +full: all four end in `for doc in self.docs.values_mut() { doc.refresh_overlay(&self.index); }`, +confirming row 9's "verified by exhaustion" claim directly rather than +trusting it. `Document` has no custom `Drop`; `lint: Slot` is dropped by the +default field-wise drop whenever a `Document` is dropped (`didClose`, or +replaced by `set_document`), confirming item 8's memory-bound claim. + +**The wire matrix (a)–(l), attacked twice, independently of the dev's own +tests.** Wrote two standalone Python scripts +(`wire_probe.py`, `wire_probe2.py`, in the QA scratchpad) speaking real +JSON-RPC over stdio (`Content-Length` framing) to the actual +`--release --locked` candidate binary, against a fixture workspace this QA +built from scratch (not the dev's fixtures, not the Rust in-process +`Session`): a `lucisv.toml`, a waiver file, a tabbed module, and a +`dut.sv`/`tb.sv` pair for the oracle row. Every row, all passing on the first +clean run (after two script bugs of my own — a premature +`take_notifications()` and a stale waiver directive shadowing a later +section — found and fixed, noted so the evidence is legible): + +| row | attack | result | +|---|---|---| +| (a) | edit the buffer | covered by (g)/(k)'s edits and the dev's own `an_edited_buffer_is_relinted` | +| (b) | `didChangeConfiguration` toggling `lucisv.lint.ignore` twice | fresh both times | +| (c) | `lucisv.toml` `[lint] select` rewritten on disk with **no watcher event**, twice | fresh at the very next request both times | +| (d) | waiver file rewritten to the **same length**, different content (`--line=1` vs `--line=2`) | fresh, not stale | +| (e) | waiver file **deleted** entirely | fresh (finding un-silenced) | +| (f) | `tb.sv` — **never opened** — rewritten on disk, reaching `dut.sv` only through a bare `workspace/didChangeWatchedFiles` (no `didChange` anywhere) | `dut.sv`'s republished diagnostics flip `unused-signal` on, then back off when `tb.sv` mentions the signal again | +| (g) | close, then reopen with different text | fresh | +| (h) | a buffer over `lucisv.largeFile.threshold` | offers nothing (fast path answers before any handler) | +| (i) | a UTF-16 fix range (`é` + a non-BMP `🎉` before the tab) on a snapshot asked for twice | the reused answer is byte-identical to the computed one; range is `character: 9` (UTF-16 units), not the byte offset | +| (j) | `indent` in `lucisv.toml` changed between two quick-fix requests on the same open buffer | the `no-tabs` fix text changes from `" "` to `" "` at the very next request | +| (k) | offer a fix, edit the buffer so both fixes' spans (one of them 40+ lines deep) are gone, ask again over a range that would be out-of-bounds for a stale answer | nothing offered, and the server's own view of the buffer is the post-edit text | +| (l) | `source.fixAll.lucisv` after the buffer is edited back down to one violation | offers exactly the one-tab fresh edit, not the earlier two-tab one | + +**Sabotage, in a fresh clone with the working diff applied +(`scratchpad/qa-61-2/cand`), one at a time, each reverted before the next and +confirmed clean (`git diff --stat` back to the original 341/16 insertion +counts, `grep -rn SABOTAGE` empty):** + +1. Stripped the waiver **text** out of `LintRun::key()` (kept the path, + blanked the string) → `server::tests::lint_snapshot::a_rewritten_waiver_file_is_relinted` + **FAILED** (14 passed, 1 failed), exactly the row-7 test and nothing else. +2. Removed `self.lint.clear()` from `Document::refresh_overlay` (early + `return` right after the `external` line) → `a_change_in_another_file_relints_this_one` + **FAILED** (14 passed, 1 failed), exactly the row-9 test. +3. Hard-coded `tab_width: 0` in `LintRun::key()` (context still builds with + the real width, so the *fix* would be correct but the *key* blind to a + change) → `a_tab_width_change_rewrites_the_fix` **FAILED** (1 passed, 1 + failed alongside the unrelated `the_runs_tab_width_is_the_formatters_own_ladder`, + which stayed green because it never reuses a snapshot across a config + change — consistent, not a miss). + +All three cuts were caught by exactly the test the row predicts and no other +test in the same run flipped. Nothing else was sabotaged (hashing the key, +an index-generation counter, etc. — the README's own rejected-alternatives +list — since none of those are what shipped). + +**Trace.** Confirmed `lint_trace::arm()` is reachable only through +`Server::request`'s `let Some(started) = self.timer() else { return … }` +branch, and `timer()` is `self.verbose.then(Instant::now)` — so a +non-`--verbose` session allocates nothing and logs nothing, by construction, +not by convention. Re-ran `tools/perf/phases_r1.py::actionprofile` and +`::ruleablation` against my own fresh `--release --locked` build of the +candidate (sha256 `827c7ac222c8…`, byte-identical to the dev's own candidate +binary hash — confirms the evidence file and my build are the same code) over +the read-only OpenTitan corpus: + +- unchanged pinmux menu 0.57–0.88 ms, queued definition 0.24–0.26 ms, first + after a `didChange` 103.5–118.0 ms (repeat median ≈106 ms) — all inside or + close to the dev's own range, on the same machine, at a different time of + day. +- the trace fields on the first-after-edit row: `trace_flush_lint=21.85ms` + (dev: 21.1–21.9 across the two records), `trace_flush_snapshot=miss`, + `trace_action_lint=0.00ms`, `trace_action_snapshot=hit` on **every** row + including the first-after-edit one — the handler's own pass really is + 0.00 ms, reproduced independently. +- `ruleablation` on the *candidate*: every row is cheap (≤~1.5 ms), which is + the **expected** consequence of R1a and not a re-derivation of the R1b + per-rule costs — `didChangeConfiguration` republishes every open buffer + before the timed `codeAction` requests run, so the expensive single-rule + pass happens during the republish and the timed request always hits. I did + **not** rebuild a snapshot-free (`51cbfd2` + `lint_trace.rs` only, no + `lint_snapshot.rs`) variant to re-derive the three-semantic-rules-cost + attribution itself; that number is R1b's, marked "attribution, no + behaviour change" in the tracker, and the flush-lint figure above (21.85 ms) + is consistent with it. Flagged as a scope limitation, not a finding. + +**Re-measured cells.** `snapshotrss` re-run on both my own ref and candidate +builds (100 open buffers, quickfix-only on each, 3 tries): candidate median +574.2 MiB (dev: 574.6), reference median 575.2 MiB (dev: 574.0) — both inside +noise of the dev's own numbers and confirming the "+0.1%, no higher retained +memory" gate independently. `codeAction`-family latency reproduced via +`actionprofile` above; did not separately re-run `offerkinds`/`offerqueue`/ +`offeredit`/`diagnostics`/`didopen` as their own named phases (time budget) — +`actionprofile`'s four request shapes at the same three cursors cover the +same underlying behaviour (unchanged menu, quickfix-only, queued definition, +first-after-edit) those phases measure. Also a scope limitation, not a +finding. + +**Traceability.** Pulled `~/.cache/lucisv-perf/take5r-2/results.jsonl` and +checked all 12 numbers named in the tracker's R1a/R1b rows and experiment +records: `22.61, 24.51, 22.39/22.38, 0.98, 0.11, 0.78/0.76, 574.0, 574.6, +162.29, 162.75` match raw sample values in the file to within 0.005; `125.65` +and `106.89` are not raw samples but are exactly the median of the *last two* +of the three `ms` samples for the reference and candidate "first offer after +`didChange`" rows respectively (`128.96` was the first, so 125.65 = median of +127.76/123.54; `106.07` was the first, so 106.89 = median of 108.64/105.14) — +consistent with the tracker's own "first / repeat median" convention, not a +fabricated number. Same check for `574.0`/`574.6`: exact medians of the three +100-buffer `rss_kib` samples in the file. + +**Guard / opentitan / cleanup.** Every cargo invocation (fmt, clippy, test ×3 +trees, `-- --list` ×2 trees) and every perf phase (`actionprofile`, +`ruleablation`, `snapshotrss` ×2 binaries) ran through +`tools/guard.sh -m 8 -t 1800`; zero guard kills. `git -C +/Users/guoliangchen/repo/opentitan status --porcelain` checked before, during +and after every phase: the same three pre-existing files +(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`, +`hw/top_earlgrey/ip/ast/rtl/ast.sv`), nothing else, every time. All sabotage +was done in `scratchpad/qa-61-2/cand`, a fresh clone with the working diff +applied; the main tree was never `git checkout`/`reset`/`stash`/`clean`ed and +nothing outside this README's QA log and the TODO line below was edited. No +background loop or server process left running at the end of this session +(checked `ps aux` — only a pre-existing, unrelated VS Code extension server +survives). + +**Verdict: PASS.** No stale diagnostic or fix found or produced under any of +the 14 table rows, over the real wire, on a fixture this QA built +independently, with three targeted sabotage cuts each caught by exactly one +predicted test. Gates green and cross-checked against a from-scratch clone of +`51cbfd2` with matching binary hashes; test count +21/-0 confirmed by name, +not just by count. Two scope limitations disclosed above (no snapshot-free +rebuild for the R1b per-rule ablation; five perf-phase names not re-run under +their own headings) are attribution/measurement gaps, not correctness gaps, +and do not change the verdict. + +**Topo edges for the lead to apply at merge** (from this README's own +Handshakes section, confirmed absent from `docs/topo.md` today): `lint.rs +──▶ lint_snapshot.rs`, `lint.rs ──▶ lint_trace.rs`, `state/mod.rs ──▶ +lint_snapshot.rs` (the field), and the `server-lint ◀──▶ diagnostics` edge +amended to say the two doors now share one computed result. The +`format::indent_width_of(&FileConfig, …)` request to `crate::format`'s owner +is still open and unclaimed by this round; it is a 0.11 ms/request cost, not +a correctness issue. + +## Review + +**2026-09-08 (lead).** Accepted. Read `lint_snapshot.rs`, the `state/` +hunks (one field, two initializers, one clear in `refresh_overlay`), the +`lint.rs` door, the invalidation table and both logs; QA's independent +derivation of the input list and its wire matrix through a real client +are the acceptance. + +- R1b answered the review's question before anything was built: the + 23 ms is three semantic rules over a 42k-line file, and the 136 ms + first-after-edit is the flush (one parse of 1.3 MB plus the + diagnostics pass) with the handler's second pass on top. That is why + the snapshot is shaped as one pass per revision shared by both doors. +- The key is the design: every input of `lint_with` by value — waiver + *contents*, not an mtime, because nothing watches them — and identity + for what identity settles (the `Document`, and the index through the + overlay refresh every mutation ends in, checked by exhaustion by dev, + QA and me). No hash, no generation counter, no map: a stale fix is a + question about `PartialEq`. +- Gates met by an order of magnitude (menu 22.6 → 1.0 ms, queued + definition 22.4 → 0.8) with the publish and memory unchanged. The + first-after-edit residue is the parse of the buffer, named, not this + lane's. +- The config-discovery memo was correctly refused: 0.04 ms of I/O that + is the only thing noticing an unwatched `lucisv.toml` change. +- Deviations accepted: the flush traced as one stage; the indent-width + read moved into the run (+0.1 ms on publish) with the + `format::indent_width(FileConfig)` request filed. + +Docs applied at merge: topo (the snapshot and trace modules, the +diagnostics/quick-fix shared result, the parsed `timing: codeaction` +line); the `format::indent_width` request to the loop-3 list. diff --git a/docs/perf/take5-tracking.md b/docs/perf/take5-tracking.md index 127111b..df363d0 100644 --- a/docs/perf/take5-tracking.md +++ b/docs/perf/take5-tracking.md @@ -2009,8 +2009,8 @@ checks in its full experiment record. Targets are proposed gates, not promises. | ID | Hypothesis / proposed work | 0.51.0 review baseline | Proposed gate | Owner / candidate commit | Candidate result / raw evidence | Decision | |---|---|---|---|---|---|---| -| R1a | Dependency-correct lint-result reuse removes repeated quickfix work | pinmux all 25.0 ms; quickfix 23.1 ms; queued definition 24.2 ms | unchanged all/queued ≤16 ms; current results after every invalidation | — | — | Pending | -| R1b | Profile then reduce dirty-buffer analysis on the first action after an edit | pinmux 135.9 ms; unchanged repeat about 24 ms | first-edit reduction shown separately; didChange ordering preserved | — | — | Pending | +| R1a | Dependency-correct lint-result reuse removes repeated quickfix work | pinmux all 25.0 ms; quickfix 23.1 ms; queued definition 24.2 ms | unchanged all/queued ≤16 ms; current results after every invalidation | dev (Opus), §61.2, tree at `51cbfd2` + the §61.2 diff | Paired against this session's own reference (`51cbfd2`, 22.61 / 24.51 / 22.39 ms): **all families 0.98 ms (−95.6%)**, **quickfix only 0.11 ms (−99.5%)**, **queued definition leader/follower 0.78 / 0.76 ms (−96.5%)**. Snapshot on the `Document`, key compared by value; idle RSS at 100 open buffers 574.0 → 574.6 MiB (+0.1%); diagnostics publish +0.3%. 21 tests added, one per invalidation row plus a stale-fix attack. [Record R1a-2026-09-08](#experiment-record--r1a-2026-09-08-stage-r1a); `~/.cache/lucisv-perf/take5r-2/` | Retained — QA PASS → lead; committed 2026-09-08 | +| R1b | Profile then reduce dirty-buffer analysis on the first action after an edit | pinmux 135.9 ms; unchanged repeat about 24 ms | first-edit reduction shown separately; didChange ordering preserved | dev (Opus), §61.2, trace-only build of `51cbfd2` + `lint_trace.rs` | **Attribution, no behaviour change.** The unchanged 22 ms menu is **20.9 ms `lint_with`**, 0.04 ms config I/O, 0.01 ms run build, 0.03 ms serialization, fence skipped (zero violations). Of the 127.5 ms first-after-edit: **99.7 ms flush** (1 parse of 1.3 MB + the diagnostics publish, itself **21.1 ms**) and **20.2 ms** the handler's own second pass — so a lint cache can only remove one 21 ms pass, which R1a then did (**125.65 → 106.89 ms, −14.9%**). Per-rule ablation: `unused-signal` +8.2, `undriven-net` +7.4, `multiply-driven` +7.5 ms over a 1.3 ms floor; the other 55 default rules ≤ +2.2 ms each. [Record R1b-2026-09-08](#experiment-record--r1b-2026-09-08-stage-r1b) | Retained — QA PASS → lead; committed 2026-09-08 | | R2a | Remove redundant discovery metadata/config work | traced warm discovery 205.0 ms; first useful answer 328.2 ms paired | first useful answer ≤200 ms milestone, correct settled target | — | — | Pending | | R2b | Begin useful local-folder work before full discovery/cache loading finishes | warm cache open 92.3 ms in traced session; cold/warm first answer 286.8/328.2 ms | single coherent scan, correct results across startup ordering cases | — | — | Pending | | R3a | Engine-owned empty-cursor preflight avoids whole-workspace materialization | no-symbol refusal 2,192 ms; 3,975 parses, candidate-only trace | ≤16 ms; zero closed-workspace parses; exact refusal/precedence | dev (Opus), §61.1, tree at `e13ae4c` + the §61.1 diff | **0.3 ms** repeat median (paired reference 2,012.3 ms, −100.0%); `trace_parses` **0**, `trace_selected` **0** off the wire; refusal byte-identical; peak RSS 909 → 429 MiB. [Record R3a-2026-09-08](#experiment-record--r3a-2026-09-08-stage-r3a); `~/.cache/lucisv-perf/take5r-1/` | Retained — QA PASS → lead; committed 2026-09-08 | @@ -2024,6 +2024,241 @@ warm idle memory gain and all source-selection/fence/after-index contracts in [topo.md](../topo.md). Cross-module API changes need their handshake recorded before implementation; no verifier forgiveness may be weakened for speed. +## Experiment record — R1b-2026-09-08 (stage R1b) + +- **Experiment ID / stage / date / owner:** `R1b-2026-09-08` / R1b (TODO + §61.2) / 2026-09-08, America/Chicago / dev agent (Opus). +- **Hypothesis and exact expected work reduction:** none — this is the + review's "trace the stages first". The expected *output* is an attribution + of the 23 ms quickfix menu and the 136 ms first-after-edit across config + discovery, `LintRun` build, lint, fence and serialization, plus the dirty + buffer flush measured apart from the handler. +- **Reference commit, candidate commit or diff hash, binary hashes:** the + traced build is trunk `51cbfd27dfd22720856c501c9c17277460cc6a68` plus + `lint_trace.rs` and its call sites — behaviour-identical, the trace armed + only under `--verbose`. Release, rustc 1.97.1 (Homebrew). The R1b numbers + are candidate-only by construction: the reference has no trace to read. +- **Files changed / API contracts amended / topology references:** + `crates/lucisv_server/src/lint_trace.rs` (new), `lint.rs` (two stages around + the discovery and the run build, one around `lint_with`), `fences.rs` (a + read-only `held` predicate), `code_action.rs` (the serialization stage), + `server/dispatch.rs` (`flush_dirty_traced`, and the line). No contract + amended. `tools/perf/phases_r1.py` (new): phases `actionprofile` and + `ruleablation`. +- **Workload, corpus/input hashes, open files, cursor/range, rules, client + capabilities:** OpenTitan, the three known pre-existing modified files, + `git status --porcelain` checked after every phase. Cursors are + `phases_p1.EDIT_CURSORS` — the pinmux comment, the `tb.sv` comment, the + `aes.sv` `aes_reg_top` instance — so the profile rows sit beside the + `offeredit` latency rows they explain. Lazy resolving client. 57 default + rules (the workspace set). +- **Machine, compiler/profile, threads, load before/after, competing + activity:** M1 Max, macOS 27.0, release profile, default worker count. Load + 1.9–3.6 one-minute across both phases. No build or test suite overlapped a + timed run. +- **Commands, cache reset/prime steps, trial ordering and fresh-session + count:** `bench.py actionprofile --tries 3` and `bench.py ruleablation + --tries 3`, each through `tools/guard.sh -m 8 -t 1800`. One fresh + `--verbose` session per cursor; the ablation is one warm session with + `lucisv.lint.select` pushed by `didChangeConfiguration` per row (a selection + change rescans nothing — `notification.rs::apply_settings`), with the + unrestricted control taken first **and** last. +- **Raw evidence path, explicit units, full sample arrays:** + `~/.cache/lucisv-perf/take5r-2/results.jsonl`, label `r1b-cand`. Latency in + `ms`; every field of the trace line is a `trace_*` row field + (`trace_action_lint`, `trace_flush_wall`, `trace_flush_parses`, …). +- **Reference first / repeat median / range; candidate first / repeat median / + range:** pinmux comment — first request of a session 25.10; unchanged + repeats **21.97** (21.82–22.01); queued behind a definition 22.33; first + after a `didChange` **127.54** (121.84–130.67). `tb.sv` 0.52 / 0.98; + `aes.sv` 3.20 / 4.19. +- **Work counts: reads, parses, analyzed/selected/watched/edited files and + bytes:** the unchanged menu performs **0** whole-file parses and **1** + `lint_with` pass over 57 rules finding **0** violations; the fence filter is + skipped (no fix to protect, §P1a). The first request after a `didChange` + performs **1** parse — the flush's — and **2** `lint_with` passes over the + same revision. +- **Result/status/count/fingerprint comparisons, warnings and refusal + checks:** every row `status=ok`; result counts unchanged from the reference + rows of the same cursors. No edit-bearing row in this phase. +- **Idle RSS / peak RSS / cache size / guard outcomes:** not sampled here (the + memory cell belongs to R1a). **Zero guard kills.** +- **Target achieved or missed; paired improvement and variability:** not a + target — an attribution. The two numbers the review asked for: + **the 23 ms is `lint_with` (20.9 of 22.0)**, config I/O being 0.04 ms; and + **the 136 ms is 78% dirty-buffer flush** (99.7 ms of 127.5, of which 21.1 ms + is the diagnostics pass, leaving ~78.6 ms of `Document::new`), with the + handler's own 20.2 ms lint pass the only part a cache can remove. +- **Where the reference disagrees with the baseline beyond tolerance (neither + number adjusted):** the review's cells are 25.0 (all families), 23.1 + (quickfix) and 135.9 (first after change); this session reads 22.0–22.6, + 24.5 and 127.5 — within 3–7% and in both directions, on a machine whose load + was at the low end of the review's band. Nothing is adjusted. +- **Correctness tests and logs:** 4 unit tests in `lint_trace.rs` (an unarmed + trace records nothing and returns the work; `close_flush` divides the + request; one recompute makes the whole request a miss; the line names every + stage in both groups). The whole workspace suite is reported under R1a, + which is the change that could break something. +- **Interpretation, remaining bottleneck, tradeoffs, rejected alternatives:** + the per-rule ablation is the finding the previous lane guessed at ("it may + be cheaper to ask *which* rules cost 24 ms than to cache their answer"): + three semantic rules — `unused-signal` **+8.2 ms**, `multiply-driven` + **+7.5**, `undriven-net` **+7.4** over a **1.3 ms** floor — are effectively + the whole pass, and the other 55 default rules together are about 2 ms. + Making *those* cheaper is a `vlog_linter` change and is not this lane's; a + snapshot is what removes the repetition without touching a rule. **Rejected + alternative:** splitting the flush into parse / analysis / overlay stages, + which lives inside `Document::new` and `Workspace::set_document` — outside + this lane's file ownership, and unnecessary for the question asked, since + flush-minus-diagnostics answers it. +- **Decision: retain / revise / reject / defer; next stage justified by + evidence:** **retain** the trace (it is what R1a is judged by, and what a + future lane will read when it goes after the 78 ms rebuild). The rule cost + is filed as evidence for whoever takes the semantic rules on. +- **QA result and lead review link:** pending — + `docs/features/perf5r-lint-snapshot/README.md`. + +## Experiment record — R1a-2026-09-08 (stage R1a) + +- **Experiment ID / stage / date / owner:** `R1a-2026-09-08` / R1a (TODO + §61.2) / 2026-09-08, America/Chicago / dev agent (Opus). +- **Hypothesis and exact expected work reduction:** R1b measured a request + that runs `lint_with` **twice** on one revision — once to publish + diagnostics, once to discover quick fixes — and a repeat menu that runs it + again on a revision nothing has touched. If one snapshot per open + `Document`, keyed by every input of that call, is read by both doors, the + expected reduction is **the whole 21 ms pass on every unchanged request** + and **one of the two passes** on the first request after an edit. +- **Reference commit, candidate commit or diff hash, binary hashes:** + reference = trunk `51cbfd27dfd22720856c501c9c17277460cc6a68` (0.51.0 plus + §61.1's rename preflight, which this lane does not touch), built from a + clean clone in scratch, binary + `5d2a7aa2a4fd0d1747aec4011a482defd2d8a1dccc08b6156b17d9a820375770`. + Candidate = that tree plus the §61.2 diff, binary + `827c7ac222c829d12a4e245b4d720b67a3dca6c799fd6bb8ee525fe697587b12`. Both + `--release --locked`, rustc 1.97.1 (Homebrew). +- **Files changed / API contracts amended / topology references:** + `crates/lucisv_server/src/lint_snapshot.rs` (new), `lint.rs`, + `code_action.rs`, `server/dispatch.rs`, `state/mod.rs` (**one field**, its + two initializers and one line in `refresh_overlay`), + `server/tests/lint_snapshot.rs` (new). In-crate signature changes: + `lint::violations_in` and `lint::fixable` return `Arc<[Violation]>`, and + `fixable`/`code_action::code_actions` no longer take a `tab_width` — the + width is on the `LintRun`, read through `format::indent_width`, whose call + the dispatcher no longer makes. `vlog_linter`, `vlog_formatter` and + `fence.rs` are untouched; the shared-fence-filter contract is not amended. A + `docs/topo.md` amendment is *requested* in the feature README's Handshakes + and was not applied by this lane. +- **Workload, corpus/input hashes, open files, cursor/range, rules, client + capabilities:** OpenTitan, the three known pre-existing modified files, + `git status --porcelain` checked after **every** phase invocation. Cursors + are `tools/perf/sites.py`'s and `phases_p1.EDIT_CURSORS`', unchanged. Client + shapes are in every row. +- **Machine, compiler/profile, threads, load before/after, competing + activity:** M1 Max, macOS 27.0, release profile, default worker count. Load + recorded before every phase: **2.47–5.88** one-minute, inside the review's + own 2.82–6.00 band. **No build, test suite or second benchmark overlapped + any timed run** — both binaries and both test suites finished first. +- **Commands, cache reset/prime steps, trial ordering and fresh-session + count:** 12 guarded `bench.py ` invocations, `--tries 3`, each + through `tools/guard.sh -m 8 -t 1800`. Phases `offerkinds offeredit + offerqueue codeaction diagnostics didopen snapshotrss`, each once per + binary, with reference/candidate order **alternated between phases** + (`offerkinds` ref→cand, `offeredit` cand→ref, `offerqueue` ref→cand, + `codeaction` cand→ref, `diagnostics` ref→cand, `didopen` cand→ref, + `snapshotrss` ref→cand), plus `actionprofile` on the candidate for its + trace. Separate `--storage` per (label, phase); `snapshotrss` and `didopen` + open a fresh process per try. +- **Raw evidence path, explicit units, full sample arrays:** + `~/.cache/lucisv-perf/take5r-2/results.jsonl`, labels `r1a-ref`, + `r1a-cand`, `r1a-cand-2` (the corrected trace run). Units in every row: + latency `ms`, memory `rss_kib` / `peak_rss_kib`. Trace fields are `trace_*`. +- **Reference first / repeat median / range; candidate first / repeat median / + range:** pinmux all families — reference 30.84 / **22.61** / 21.9–24.5; + candidate 2.42 / **0.98** / 0.41–1.24. Quickfix only — reference 22.35 / + **24.51**; candidate 0.15 / **0.11**. `offeredit` repeat — reference 23.88 / + **23.44**; candidate 0.23 / **0.18**. First after `didChange` — reference + 128.96 / **125.65** / 123.5–129.0; candidate 106.07 / **106.89** / + 105.1–108.6. Queued definition (leader / follower, pipeline 3) — reference + 22.39 / 22.38; candidate **0.78 / 0.76**. Diagnostics publish — reference + **162.29**, candidate **162.75**. The full arrays are in the JSONL. +- **Work counts: reads, parses, analyzed/selected/watched/edited files and + bytes:** the unchanged menu now runs **zero** `lint_with` passes + (`trace_action_lint=0.00ms`, `trace_action_snapshot=hit`) and **zero** + parses. The first request after a `didChange` runs **one** pass, the + diagnostics publish's, inside the flush (`trace_flush_lint=21.87ms`, + `snapshot=miss`) and **none** in the handler (`snapshot=hit`) — down from + two. Config discovery still runs per request; the + indent-width read moved from the dispatcher into the run, so a code-action + request does the same two `Discovery` walks it always did and the + diagnostics publish now does two where it did one — about **+0.11 ms** on + the config stage, publish row **+0.3%**. A handshake request to give + `format::indent_width` a form that takes an already-read `FileConfig` is + recorded in the feature README. +- **Result/status/count/fingerprint comparisons, warnings and refusal + checks:** every row `status=ok`, and every row's `result_count` equal + between the two binaries — the pinmux cursor offers nothing before and + after, the `aes_reg_top` cursor offers the same port actions, the take-3 + `codeaction` cells answer the same counts. The correctness argument is the + test matrix rather than a fingerprint: this lane changes no edit, only when + one is computed. +- **Idle RSS / peak RSS / cache size / guard outcomes:** a new `snapshotrss` + phase opens 1 / 10 / 100 RTL buffers, sends one quickfix-only `codeAction` + into each so that every open document holds a snapshot, and reads idle RSS a + second after the session goes quiet: **420.9 → 422.2 MiB (1 buffer)**, + **429.4 → 428.4 (10)**, **574.0 → 574.6 (100, +0.1%)**. **Zero guard + kills.** +- **Target achieved or missed; paired improvement and variability:** + **achieved.** Gate ≤16 ms unchanged menu → **0.98 ms** (quickfix-only + 0.11); gate ≤16 ms queued definition → **0.76 ms**; gate "first-after-edit + improved and reported separately with its stage split" → **125.65 → 106.89 + ms (−14.9%)**, with the split saying the remaining 106 ms is 84 ms of + `Document::new` plus the 22 ms diagnostics pass and **0.00 ms** of + code-action lint; gate "diagnostics publish must not regress" → **+0.3%**; + gate "no higher retained memory" → **+0.1% at 100 buffers**. Unchanged rows + move −23% to +15% on sub-10 ms cells, in both directions and with no + pattern: `didopen` (median of three fresh processes) 4.53 → 3.49, 5.72 → + 5.56, 8.68 → 8.15, and the `tb.sv` menu 0.19 → 0.23 / 1.26 → 1.45. None of + these is read as movement at that scale. +- **Where the reference disagrees with the baseline beyond tolerance (neither + number adjusted):** the review's 0.51.0 cells are 25.0 / 23.1 / 24.2 / + 135.9 ms; this session's own reference reads 22.6 / 24.5 / 22.4 / 125.7 — + within about 8% in both directions. The improvement is stated against **this + session's own reference**, so the ratios are unaffected. +- **Correctness tests and logs:** `cargo fmt` clean; guarded `cargo clippy + --all-targets` clean, no new `#[allow]`; guarded `cargo test --workspace` + **4 343 passed, 0 failed** against the reference tree's **4 322 passed, 0 + failed** measured the same way — **+21, none removed**, confirmed by + diffing `cargo test -- --list` between the two trees. The 21 are: 11 in + `server/tests/lint_snapshot.rs` (one per invalidation-table row — an edited + buffer, a large buffer, a pushed rule selection, a rewritten `lucisv.toml`, + a rewritten waiver file, a changed indent width, a change in **another** + file that moves the census, close/reopen, a UTF-16 fix range, the shared + pass, and the **stale-fix attack**), 4 in `lint_snapshot.rs` (every field of + the key forces a recompute; a same-length waiver rewrite is a different + key), 4 in `lint_trace.rs`, 2 in `lint.rs` (the indent ladder rung by rung; + a reused snapshot compared violation for violation and fix for fix against a + fresh `lint_with`). +- **Interpretation, remaining bottleneck, tradeoffs, rejected alternatives:** + the code-action path is now transport-bound on the largest file in + opentitan. What is left of the edit-time pause is **not** lint: ~84 ms of + `Document::new` on 1.3 MB, which is a parser/analysis question and belongs + with the review's item 4 as a separate lane. **Rejected alternatives:** + hashing the key (a digest would make "no stale fix" a collision argument + instead of a `PartialEq` fact); keying on the waiver files' mtime or length + (weaker than the contents, and wrong across a same-second rewrite); + memoizing the `FileConfig` read (the trace measures it at 0.04–0.16 ms, and + its failure mode would be a stale *rule selection* on files nothing + watches); an index generation counter (`refresh_overlay` is already called + at every index mutation, so a counter would be a second thing to keep in + step); a bounded map keyed by URI (a field on the `Document` is dropped by + `didClose` for free and cannot outlive its text). +- **Decision: retain / revise / reject / defer; next stage justified by + evidence:** **retain.** The next lever on this path is the 84 ms + `Document::new`, not the linter. +- **QA result and lead review link:** pending — + `docs/features/perf5r-lint-snapshot/README.md`. + ## Experiment record — R3a-2026-09-08 (stage R3a) - **Experiment ID / stage / date / owner:** `R3a-2026-09-08` / R3a (TODO §61.1) diff --git a/docs/topo.md b/docs/topo.md index 77b3cc1..c045924 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -289,7 +289,7 @@ spans two layers — the include graph *and* the `documentLink` handler; | loop | `server/` (since 2026-09-02: `mod` = the loop; `dispatch`, `client`, `index`, `notification`, `progress`, `diagnostics`, `batch`, `formatting`, `large_file`, `semantic_tokens`; tests in `server/tests/`) | the message loop + queue/burst (cancel-request), dispatch, `Pending` map for server-initiated requests, stepped startup scans with mid-scan request drains, held-request ordering for rescans, reindex/widen orchestration, progress/log senders, optional `timing:` instrumentation | | state | `state.rs` | `Workspace` (roots, scope ladder, index, include graph, candidates, index cache, open `Document`s with overlay, bounded closed-file `FileView` cache), `Scan` (whole or additive widen), fan-out source selectors (`module_sources`, `rename_sources`, `include_sources`), and `Document` (text, tokens, tree, semantics, diagnostics, `large` flag) | | substrate | `convert.rs`, `uri.rs`, `locate.rs`, `pairs.rs`, `includes.rs`, `candidates.rs`, `index_cache.rs`, `watch.rs`, `settings.rs`, `templates.rs`, `sync.rs` | position math, URI↔path, location building, the begin/end scope matcher, the include graph, completion word/module tables and their scan-batch forms, the persistent index store, watcher registration, `lucisv.*` settings parsing, snippet registry, incremental text sync | -| handlers | one file per capability: `format.rs`, `diagnostics.rs`, `lint.rs` (with `fences.rs`: the formatter's text-only fence answer memoized once per `Document` — perf5-p1; the shared-fence-filter contract is unamended), `rename_trace.rs` (perf5-p2: `Rung`/`Wanted`/`SelectionTrace` — the path set the rename fan-out ladder fills, remembering which rung asked for each file; `Workspace::rename_sources_traced` is the ladder with that sink), `hover.rs`, `expand.rs`, `nav.rs`, `type_def.rs`, `type_hierarchy.rs`, `hierarchy.rs`, `design_hierarchy.rs`, `symbols.rs`, `tokens.rs`, `completion/` (`mod`, `member`, `module`, `tiers`, `word`, `site`; test harness in `harness`), `signature.rs`, `inlay.rs`, `inline.rs`, `lens.rs`, `code_action.rs`, `rename.rs`, `ports.rs`, `imports.rs`, `extract.rs`, `inline_module.rs`, `folding.rs`, `selection.rs`, `linked.rs`, `on_type.rs`, `includes.rs` (links), `file_ops.rs`, `instantiate.rs`, `large.rs` | each is a mostly-pure function over `Document`/`Workspace`; protocol only, no language analysis of its own (anything that looks like analysis in here is a bug or a Handshake request — lucisv-server README) | +| handlers | one file per capability: `format.rs`, `diagnostics.rs`, `lint.rs` (with `fences.rs`: the formatter's text-only fence answer memoized once per `Document` — perf5-p1; the shared-fence-filter contract is unamended; and `lint_snapshot.rs` + `lint_trace.rs` — perf5r-lint-snapshot, 2026-09-08: one `lint_with` pass per document revision shared by the diagnostics publish and quick-fix discovery, keyed by value on every input of that call — rule names, merged options, line width, tab width, oracle presence, external waiver *contents* — held in a `Slot` on the `Document` and cleared by `Document::refresh_overlay`, which every index mutation ends in; a `timing: codeaction … key=value` line under `--verbose`, parsed by `tools/perf/phases_r1.py`), `rename_trace.rs` (perf5-p2: `Rung`/`Wanted`/`SelectionTrace` — the path set the rename fan-out ladder fills, remembering which rung asked for each file; `Workspace::rename_sources_traced` is the ladder with that sink), `hover.rs`, `expand.rs`, `nav.rs`, `type_def.rs`, `type_hierarchy.rs`, `hierarchy.rs`, `design_hierarchy.rs`, `symbols.rs`, `tokens.rs`, `completion/` (`mod`, `member`, `module`, `tiers`, `word`, `site`; test harness in `harness`), `signature.rs`, `inlay.rs`, `inline.rs`, `lens.rs`, `code_action.rs`, `rename.rs`, `ports.rs`, `imports.rs`, `extract.rs`, `inline_module.rs`, `folding.rs`, `selection.rs`, `linked.rs`, `on_type.rs`, `includes.rs` (links), `file_ops.rs`, `instantiate.rs`, `large.rs` | each is a mostly-pure function over `Document`/`Workspace`; protocol only, no language analysis of its own (anything that looks like analysis in here is a bug or a Handshake request — lucisv-server README) | **`editors/vscode`** — `extension.js` (spawn + rainbow decorations + storage path; ~everything else is `vscode-languageclient` driven off advertised diff --git a/tools/perf/README.md b/tools/perf/README.md index 32167f6..7118558 100644 --- a/tools/perf/README.md +++ b/tools/perf/README.md @@ -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_r1.py` | the review round's §R1 phases: `actionprofile` (the `timing: codeaction …` stage split at three cursors × four request shapes), `ruleablation` (one row per default-on rule, `lucisv.lint.select` pushed between rows) and `snapshotrss` (idle RSS at 1 / 10 / 100 buffers, each asked for quick fixes so every one holds a lint snapshot) | | `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 | @@ -85,6 +86,9 @@ apart in `results.jsonl`; run each phase once per binary. | `scanprofile` | §P4a | the startup breakdown, from the server's own `timing: scan 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`) | +| `actionprofile` | §R1b | one `--verbose` session per cursor, four request shapes each — the first menu of the session, three repeats on the unchanged buffer, a definition queued behind it, and the first menu after each of three `didChange`s — with the server's own `timing: codeaction …` line parsed into `trace_*` fields. Two groups per line: `flush{…}` is the debounced `Document` rebuild and the diagnostics publish inside it, `action{…}` is the handler. A request that lints nothing logs no line, which is why the queued rows say how many the follower logged | +| `ruleablation` | §R1b | *which* rules the pinmux quickfix menu's milliseconds are in: one warm session, `lucisv.lint.select` pushed to a single rule per row by `didChangeConfiguration` (a selection change rescans nothing), the unrestricted control taken first **and** last so session drift is visible rather than blamed on a rule | +| `snapshotrss` | §R1a | idle and peak RSS with 1 / 10 / 100 open buffers, each sent one quickfix-only `codeAction` so that every open document holds a lint snapshot — the memory bound of `docs/features/perf5r-lint-snapshot/README.md`. `rss_kib` / `peak_rss_kib`, never `ms` | | `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 diff --git a/tools/perf/bench.py b/tools/perf/bench.py index 97d1043..22d7ddc 100644 --- a/tools/perf/bench.py +++ b/tools/perf/bench.py @@ -37,6 +37,7 @@ 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 +import phases_r1 # noqa: E402,F401 — registers the review round's R1 phases import phases_r3 # noqa: E402,F401 — registers the review round's R3 phase diff --git a/tools/perf/phases_r1.py b/tools/perf/phases_r1.py new file mode 100644 index 0000000..b7ceeeb --- /dev/null +++ b/tools/perf/phases_r1.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python3 +"""The take-5 **review** round's phases for R1a/R1b: `actionprofile`, +`ruleablation`. + +`offerkinds` and `offeredit` say what a code-action menu *costs*; neither says +where the milliseconds went. The review's §1 item 1 asks for exactly that +split — "trace configuration/waiver loading, dirty-buffer flush, lint +execution, fence filtering and action serialization separately on the pinmux +case, [for the] first request, unchanged repeat, first request after +one-character edit, and navigation queued behind each" — and `--verbose` now +logs one `timing: codeaction …` line per request carrying it +(`crates/lucisv_server/src/lint_trace.rs`). + +`actionprofile` issues those four shapes at three cursors and writes every +field of that line as a `trace_*` row field, so the tracker quotes numbers and +not prose. `ms` remains the wire latency and nothing else (schema 2). + +`ruleablation` answers the other half of the same question — *which* rules the +lint pass spends its milliseconds in on a 42 192-line generated buffer. One +`workspace/didChangeConfiguration` per row sets `lucisv.lint.select` to a +single rule and the same quickfix-only menu is timed under it. A selection +change rescans nothing (`notification.rs::apply_settings`), so the rows are +comparable within one warm session. + +The corpus is not written: a `didChange` is a notification about an in-memory +buffer and never reaches disk. +""" + +import os +import re +import subprocess +import time + +import phases_new +import phases_p2 +import phases_p4 +import schema +import sites +from harness import ( + ARGS, at, code_action_params, phase, record, samples, session, settled, uri as lspclient_uri, +) + +#: `timing: codeaction ` — the whole line the server logs per request +#: that linted anything. +TRACE_LINE = re.compile(r"timing: codeaction (.*)$") + +#: The cursors R1b is profiled at. The first is the review's own headline (a +#: no-offer comment in a 42 192-line generated file); the second is the small +#: no-offer control; the third the one small-file offer site. Same three +#: `phases_p1.EDIT_CURSORS` measures, so the profile rows sit beside the +#: latency rows they explain. +PROFILE_CURSORS = [ + ("pinmux-comment", sites.PINMUX_REG_TOP, "// ", 2), + ("tb-comment", sites.TB, "// ", 2), + ("aes-reg-instance", sites.AES, "aes_reg_top u_reg (", 0), +] + +#: The request queued behind each menu — `phases_p0.phase_offerqueue`'s own +#: follower, so the queued-definition rows are directly comparable. +FOLLOWER = (sites.TB, " aes #(", 1, 2) + + +def traces(s): + """Every `codeaction` trace line since the last drain, flattened. + + `phases_p2.parse_trace` is the parser: `key=value` pairs with `group{…}` + flattened under the group's name, which is the shape `lint_trace::Trace` + prints. A row whose trace is empty is a row whose server was not + `--verbose` or which never linted — the phase says so rather than + inventing fields. + """ + s.drain() + found = [m for text in s.log_messages for m in TRACE_LINE.findall(text)] + s.log_messages = [] + return [phases_p2.parse_trace(one) for one in found] + + +def last_trace(s): + """The last traced request of this session, or `{}`.""" + found = traces(s) + return found[-1] if found else {} + + +def open_verbose(s, relative, quiet=0.8): + """Settle the scan, open the file, and start with an empty log.""" + settled(s) + s.did_open(sites.path(relative)) + s.wait_quiet(quiet) + s.take_notifications() + s.log_messages = [] + + +def profile_row(s, row, relative, params, got, trace, note): + """One schema-2 row carrying a request's wire time and its stage split.""" + record(phase="actionprofile", row=row, client=s.client_shape(), + file=relative, position=params["range"]["start"], + load=os.getloadavg(), note=note, + **dict(got.row(), **phases_p2.prefixed(trace))) + + +@phase("actionprofile") +def phase_actionprofile(): + """§R1b — the code-action stage trace, four request shapes per cursor.""" + for label, relative, needle, offset in PROFILE_CURSORS: + with session("workspace", resolve_support=True, verbose=True, + storage_name="actionprofile") as s: + open_verbose(s, relative) + params = code_action_params(relative, needle, offset=offset) + settled_rows(s, label, relative, params) + edited_rows(s, label, relative, params) + + +def settled_rows(s, label, relative, params): + """The two rows a settled buffer answers: the first menu, then repeats.""" + got = samples(s, "textDocument/codeAction", params, 1) + profile_row(s, "%s, first codeAction on the settled buffer" % label, + relative, params, got, last_trace(s), + "the first request of the session at this cursor") + got = samples(s, "textDocument/codeAction", params, ARGS.tries) + profile_row(s, "%s, repeated codeAction on the unchanged buffer" % label, + relative, params, got, last_trace(s), + "no didChange between the tries; the trace is the last one") + queued_row(s, "%s, definition queued behind the unchanged menu" % label, + relative, params) + + +def edited_rows(s, label, relative, params): + """The first menu after each `didChange`, and one queued behind it.""" + with open(sites.path(relative), encoding="utf-8", errors="replace") as handle: + text = handle.read() + ms, statuses, counts, trace = [], [], [], {} + for version in range(2, 2 + ARGS.tries): + s.did_change(sites.path(relative), + text + "\n// take5r r1 %d\n" % version, version) + got = samples(s, "textDocument/codeAction", params, 1) + ms.append(got.ms[0]) + statuses.append((got.status, got.message)) + counts.append(got.result_count) + trace = last_trace(s) or trace + status = schema.worst([one for one, _ in statuses]) + record(phase="actionprofile", + row="%s, first codeAction after a didChange" % label, + ms=ms, status=status, + message=next((m for one, m in statuses if one != "ok"), None), + result_count=counts[-1], result_counts=counts, + client=s.client_shape(), file=relative, + position=params["range"]["start"], + load=os.getloadavg(), + note="each try is the first codeAction after its own didChange, so " + "the flush group of the trace is that request's Document " + "rebuild; the same edit shape phases_p1.offeredit uses", + **phases_p2.prefixed(trace)) + # The queued case on a buffer that has just changed: the review asks for + # navigation queued behind *each* menu, and only this one pays the flush. + def edit(pipeline): + s.did_change(sites.path(relative), + text + "\n// take5r r1 queued %d\n" % pipeline, + 10 + pipeline) + + queued_row(s, "%s, definition queued behind the menu after a didChange" + % label, relative, params, change=edit) + + +def queued_row(s, row, relative, params, change=None): + """A `codeAction` and a `definition` sent back to back, both traced. + + `change` is called before every pipeline when the row is about a buffer + that has *just* changed: only the first request after an edit pays the + flush, so a repeat inside the row would measure the other case. + """ + follower = at(*FOLLOWER) + s.log_messages = [] + leaders, followers = [], [] + lead_status, follow_status = ("ok", None), ("ok", None) + for pipeline in range(ARGS.tries): + if change: + change(pipeline) + s.log_messages = [] + lead = s.send("textDocument/codeAction", params) + follow = s.send("textDocument/definition", follower) + leader_ms, leader_message = s.await_id(lead) + follower_ms, follower_message = s.await_id(follow) + leaders.append(leader_ms) + followers.append(follower_ms) + lead_status = schema.status_of(leader_message) + follow_status = schema.status_of(follower_message) + # Attributed by the line's own `method` field, not by position: a request + # that lints nothing logs no line at all, so a definition behind an + # already-flushed menu contributes none and the last line in the log is + # another `codeAction`. Counting by position made two leaders look like a + # leader and a follower. + found = traces(s) + lead = [one for one in found if one.get("method", "").endswith("codeAction")] + follow = [one for one in found if one.get("method", "").endswith("definition")] + record(phase="actionprofile", row=row, + ms=[leaders[-1], followers[-1]], leader_ms=leaders, + follower_ms=followers, + status=schema.worst([lead_status[0], follow_status[0]]), + message=lead_status[1] or follow_status[1], + result_count=len(follow), client=s.client_shape(), file=relative, + position=params["range"]["start"], load=os.getloadavg(), + note="ms is [leader, follower], not repeats; trace_* is the " + "leader's own stage split and follower_trace_* the " + "definition's — a definition that linted nothing logs no " + "line, and result_count says how many it logged", + **dict(phases_p2.prefixed(lead[-1] if lead else {}), + **{"follower_%s" % key: value + for key, value in + phases_p2.prefixed(follow[-1] if follow else {}).items()})) + + +def enabled_rules(): + """Every rule the server runs by default over a project, by name. + + Read from `lucisv check --rules-doc` beside the server under test rather + than hard-coded, so the list cannot drift from the registry. `**on**` is a + rule a plain check runs; `**on (project)**` is one that also needs a + workspace, which the server has. + """ + binary = os.path.join(os.path.dirname(os.path.abspath(ARGS.server)), "lucisv") + out = subprocess.run([binary, "check", "--rules-doc"], check=True, + capture_output=True, text=True).stdout + rows = re.findall(r"^\| \[`([a-z0-9-]+)`\]\S* \| \w+ \| (\*\*on[^|]*|off) \|", + out, re.M) + return [name for name, default in rows if default.startswith("**on")] + + +@phase("ruleablation") +def phase_ruleablation(): + """§R1b — which rules the pinmux quickfix menu's milliseconds are in. + + One row per default-on rule: `lucisv.lint.select` is set to that rule + alone and the same quickfix-only menu is timed. The control row is the + unrestricted selection, taken first and last so a drift in the session is + visible rather than attributed to a rule. + """ + rules = enabled_rules() + with session("workspace", resolve_support=True, verbose=True, + storage_name="ruleablation") as s: + open_verbose(s, sites.PINMUX_REG_TOP) + params = code_action_params(sites.PINMUX_REG_TOP, "// ", offset=2) + params["context"]["only"] = ["quickfix"] + ablation_row(s, "control: every default rule (before)", None, params) + for name in rules: + ablation_row(s, "select %s" % name, [name], params) + ablation_row(s, "control: every default rule (after)", None, params) + + +def ablation_row(s, row, select, params): + """Push one `lucisv.lint.select`, then time the menu under it.""" + lint = {"select": select} if select else {"select": []} + s.notify("workspace/didChangeConfiguration", + {"settings": {"lucisv": {"lint": lint}}}) + s.wait_quiet(0.4) + s.take_notifications() + s.log_messages = [] + got = samples(s, "textDocument/codeAction", params, ARGS.tries) + record(phase="ruleablation", row=row, client=s.client_shape(), + file=sites.PINMUX_REG_TOP, position=params["range"]["start"], + only=params["context"]["only"], load=os.getloadavg(), + note="quickfix only, one warm session, selection pushed by " + "didChangeConfiguration; a selection change rescans nothing", + **dict(got.row(), **phases_p2.prefixed(last_trace(s)))) + + +@phase("snapshotrss") +def phase_snapshotrss(): + """§R1a — what the lint snapshots cost in memory, at 1, 10 and 100 buffers. + + The snapshot is one field per open `Document`, holding that document's own + violations, so the memory question is "how much does a session with many + buffers grow when every one of them has been asked for a quick fix?". + Each cell opens `n` RTL files, sends one quickfix-only `codeAction` into + every one of them — which is what fills the slot on the reference binary + too, minus the keeping — and reads idle RSS a second later. + + `phases_p4.rtl_files` is the same buffer list the P4 startup cells use, so + the 100-buffer row is comparable with the startup memory cell beside it. + """ + for buffers in (1, 10, 100): + idle, peaks, asked = [], [], 0 + for _ in range(ARGS.tries): + with session("workspace", resolve_support=True, + storage_name="snapshotrss") as s: + sampler = phases_new.Sampler(s.proc.pid) + sampler.start() + settled(s) + asked = ask_everywhere(s, phases_p4.rtl_files(buffers)) + s.wait_quiet(1.0) + time.sleep(1.0) + idle.append(phases_new.rss_kib(s.proc.pid)) + peaks.append(sampler.stop()) + shape = s.client_shape() + record(phase="snapshotrss", + row="idle RSS, %d open buffer(s), each asked for quick fixes" + % buffers, + units="KiB", rss_kib=idle, peak_rss_kib=peaks, + fresh_process=True, result_count=asked, client=shape, + load=os.getloadavg(), + note="one quickfix-only codeAction per open buffer, so every " + "one of them holds a lint snapshot; idle RSS a second " + "after the session went quiet, no latency in this row") + + +def ask_everywhere(s, paths): + """Open each path and ask it for quick fixes; returns how many answered.""" + answered = 0 + for path in paths: + s.did_open(path) + s.wait_quiet(1.0) + s.take_notifications() + for path in paths: + where = {"line": 0, "character": 0} + params = {"textDocument": {"uri": lspclient_uri(path)}, + "range": {"start": where, "end": where}, + "context": {"diagnostics": [], "only": ["quickfix"]}} + _, message = s.request("textDocument/codeAction", params) + answered += 1 if schema.status_of(message)[0] == "ok" else 0 + return answered