From 6c1f8634170d8464bf91623af2eb2aae8a6ad5db Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Mon, 7 Sep 2026 16:05:26 -0500 Subject: [PATCH] =?UTF-8?q?Perf=20take=205=20P1=20(=C2=A760.1):=20code-act?= =?UTF-8?q?ion=20discovery=20stops=20repeating=20work=20=E2=80=94=20lint/c?= =?UTF-8?q?onfig/fence=20gated=20by=20the=20requested=20kinds=20(only:=20[?= =?UTF-8?q?]=20answers=20at=20once),=20the=20fence=20answer=20asked=20only?= =?UTF-8?q?=20when=20a=20fix=20exists=20and=20memoized=20per=20Document,?= =?UTF-8?q?=20the=20four=20offer=20selectors=20read=20the=20document's=20o?= =?UTF-8?q?wn=20parse=20(additive=20=5Fin=20APIs,=20text=20forms=20as=20wr?= =?UTF-8?q?appers),=20a=20per-thread=20parse=20counter=20proves=20a=20repe?= =?UTF-8?q?ated=20offer=20parses=20nothing;=20pinmux=20no-offer=20comment?= =?UTF-8?q?=20310=20=E2=86=92=2024=20ms,=20queued=20definition=20likewise?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 50 +- crates/lucisv_server/src/code_action.rs | 12 + crates/lucisv_server/src/extract.rs | 19 +- crates/lucisv_server/src/fences.rs | 33 ++ crates/lucisv_server/src/imports.rs | 17 +- crates/lucisv_server/src/inline_module.rs | 19 +- crates/lucisv_server/src/lint.rs | 24 +- crates/lucisv_server/src/main.rs | 1 + crates/lucisv_server/src/ports.rs | 24 +- crates/lucisv_server/src/server/dispatch.rs | 59 +- .../src/server/tests/code_action.rs | 463 +++++++++++++++ crates/lucisv_server/src/server/tests/mod.rs | 1 + crates/lucisv_server/src/state.rs | 8 + crates/vlog_parser/src/lib.rs | 1 + crates/vlog_parser/src/parser/mod.rs | 2 + crates/vlog_parser/src/stats.rs | 39 ++ crates/vlog_refactor/src/extract/mod.rs | 20 +- crates/vlog_refactor/src/imports.rs | 18 +- crates/vlog_refactor/src/inline/mod.rs | 20 +- crates/vlog_refactor/src/lib.rs | 15 +- crates/vlog_refactor/src/ports/mod.rs | 20 +- .../vlog_refactor/tests/parsed_selectors.rs | 171 ++++++ docs/features/perf5-p1/README.md | 552 ++++++++++++++++++ docs/perf/take5-tracking.md | 275 ++++++++- docs/topo.md | 6 +- tools/perf/README.md | 2 + tools/perf/bench.py | 1 + tools/perf/phases_p1.py | 103 ++++ 28 files changed, 1889 insertions(+), 86 deletions(-) create mode 100644 crates/lucisv_server/src/fences.rs create mode 100644 crates/lucisv_server/src/server/tests/code_action.rs create mode 100644 crates/vlog_parser/src/stats.rs create mode 100644 crates/vlog_refactor/tests/parsed_selectors.rs create mode 100644 docs/features/perf5-p1/README.md create mode 100644 tools/perf/phases_p1.py diff --git a/TODO.md b/TODO.md index 5d5d037..2568178 100644 --- a/TODO.md +++ b/TODO.md @@ -4686,6 +4686,11 @@ in 0.49.0. Take 4's findings are in the loop-3 list above. `unused-import` (§8.4); two instance-head tails that do not resolve (`pwrmgr.sv` 178:10 in a macro argument, `pinmux.sv` 687:40; §8.5 — a ruling, not a fix); the index +14% at codec 19 (§8.6, watch). +- **perf take 5 P1 (§60.1) deferred:** lint-result reuse for the + code-action path — a memo of `fixable`'s violations keyed by document + revision + tab width + rule set + merged options + waiver contents + + index generation (each attacked); worth 24 ms per cursor move on + opentitan's largest file, 1–3 ms on ordinary RTL. Sections after §46 are planned when reached. ## 45. Small items, round 4 (planned 2026-09-05) — topo §2.9-29, 30, 17, 22 @@ -5743,29 +5748,60 @@ additive parsed-input selectors beside the text ones. `fence.rs` is NOT touched: the text-only fence authority stays and is memoized per document revision, computed only when a fix needs it (shared-fence-filter's contract). -- [ ] P1a: the `only` filter checked before config discovery, lint and +- [x] P1a: the `only` filter checked before config discovery, lint and fence work; `only: []` returns at once; fence regions computed only when a candidate fix exists; kind-prefix semantics, fixes spanning the cursor, fix-all, action order, and a cursor (empty range) still offering extract — all pinned -- [ ] P1b: selectors over the document's existing parse + diagnostics + — `only: []` 82.80 → **0.064 ms**; quickfix 84.13 → 23.53; the + base separated at last: lint+config 23.5, fence parse 59.3 ms +- [x] P1b: selectors over the document's existing parse + diagnostics (large-file mode and parse-diagnostic checks exactly as before); text wrappers retained for standalone consumers and parity tests; fence memo keyed by exact source revision; any lint-result reuse keyed by revision + effective lint/format settings + waivers + workspace generation, or not done -- [ ] work counters (parses per request) prove "no additional parse on + — four additive `*_in` selectors; `fences.rs` memo on the + `Document`; **lint-result reuse deliberately not done**, reason + and number in `P1b-2026-09-07` +- [x] work counters (parses per request) prove "no additional parse on a repeated offer" — asserted in tests by count, not by stopwatch -- [ ] parity pinned at every sampled cursor/range: no-offer comments, + — `vlog_parser::stats::parses()`; a repeated no-offer all-family + request performs **0** parses, `only: []` **0**, the first + request after a `didChange` **≤2** +- [x] parity pinned at every sampled cursor/range: no-offer comments, parse errors, CRLF, UTF-16 positions, unsaved edits, untitled and large buffers, action filters, fence insertions, waivers, config change, index refresh -- [ ] measured: repeated lazy offers < 5 ms; `aes_reg_top` < 10 ms; + — 7 engine tests comparing old against new at *every byte offset* + of five fixtures, 12 server tests through the real dispatch +- [x] measured: repeated lazy offers < 5 ms; `aes_reg_top` < 10 ms; the pinmux no-offer comment < 16 ms on an unchanged buffer; first-after-edit tracked separately; the pipelined definition re-measured; tracker + experiment entry filled -- [ ] lead ruling on P1c from the measurement -- [ ] QA: parity attacks as above, the counters, the numbers re-taken + — pinmux 309.60 → **24.02 ms** (−92.2%), queued definition + 309.40 → **24.61** (−92.0%), `tb.sv` 4.46 → 3.65, `aes_reg_top` + 23.31 → 21.83. **Two of three targets missed, both residues + measured**: the pinmux row is 100% lint, the `aes_reg_top` row is + 21.15 of 21.83 ms of discarded ports plan. New `offeredit` phase + for first-after-edit +- [x] lead ruling on P1c from the measurement — **go** (2026-09-07: the + `aes_reg_top` offer is 21.8 ms after P1b, 21.2 of it the ports + family's discarded plan); lint-result reuse **deferred** to the + loop-3 list (24 ms on the largest file; six-surface key; a stale + fix offer is the failure mode; the first request after a keystroke + pays the pass regardless) + — the measurement is in: `aes_reg_top` ports-only 21.15 ms of a + 21.83 ms row; every other family under 0.15 ms +- [ ] lead ruling on a lint-result reuse item (new, from P1b's number: + 24.0 ms, the whole of the pinmux row, for a client that sends no + `only`) — a keyed cache in §59's shape, not this lane's to add +- [x] QA: parity attacks as above, the counters, the numbers re-taken + — PASS, 2026-09-07: `docs/features/perf5-p1/README.md` QA log; 17 + cursors byte-identical vs a real v0.50.0 baseline server, counter + sabotage caught in 3 places, parity suite verified exhaustive plus + one adversarial fixture, a genuine >4 MiB buffer confirmed, all + re-measured cells agree within tolerance, gates green ### 60.2 P2 — rename reuses its analysis, verification untouched diff --git a/crates/lucisv_server/src/code_action.rs b/crates/lucisv_server/src/code_action.rs index db25dd6..45b9e5b 100644 --- a/crates/lucisv_server/src/code_action.rs +++ b/crates/lucisv_server/src/code_action.rs @@ -133,6 +133,18 @@ fn title(violation: &Violation) -> String { format!("lucisv: {what} [{}]", violation.rule) } +/// Whether a client asking for `only` wants anything [`code_actions`] can +/// offer — a quick fix or the fix-all action. +/// +/// The two kinds this module answers for are the only two the **lint pass** +/// answers for, so this is the question the dispatcher asks before reading the +/// buffer's configuration and running the rules. A client asking for +/// `refactor.*` or `source.organizeImports` alone gets neither, and now pays +/// for neither (take 5 §P1a). +pub fn wants_fixes(only: Option<&[CodeActionKind]>) -> bool { + wanted(only, &CodeActionKind::QUICKFIX) || wanted(only, &CodeActionKind::new(FIX_ALL)) +} + /// Whether a client asking for `only` wants this kind. A filter is a prefix of /// the kinds it selects (`source` selects `source.fixAll.lucisv`), and no filter /// at all selects everything. diff --git a/crates/lucisv_server/src/extract.rs b/crates/lucisv_server/src/extract.rs index 119cdcd..bef7855 100644 --- a/crates/lucisv_server/src/extract.rs +++ b/crates/lucisv_server/src/extract.rs @@ -40,7 +40,7 @@ use vlog_parser::LineIndex; use vlog_refactor::{Home, RefactorEdit}; use crate::convert::Positions; -use crate::state::Workspace; +use crate::state::{Document, Workspace}; use crate::uri::path_to_uri; /// Extract a selection into a module: `[uri, range, name]`. @@ -63,6 +63,19 @@ pub fn kind() -> CodeActionKind { /// "there is nothing here" for almost every selection, and where it does find /// something the offer is a `Command`, so no workspace is read until the user /// has picked the action *and* named the module. +/// Whether `[start, end)` is a selection lucisv could extract, asked of the +/// buffer's own parse and diagnostics rather than of its text (take 5 §P1b). +/// +/// A buffer on the large-file fast path keeps the text form, whose parse is of +/// the real bytes rather than of the empty analysis that path installs — see +/// `ports::modules_at` and `docs/features/perf5-p1/README.md`. +fn site_at(doc: &Document, start: u32, end: u32) -> Option { + match doc.large { + true => vlog_refactor::extract_site(&doc.text, start, end), + false => vlog_refactor::extract_site_in(&doc.tree, &doc.diagnostics, &doc.text, start, end), + } +} + pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; if doc.path.is_none() { @@ -73,7 +86,7 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec &[Region] { + doc.fences.get_or_init(|| fence::protected_regions(&doc.text)) +} diff --git a/crates/lucisv_server/src/imports.rs b/crates/lucisv_server/src/imports.rs index 08dda99..7b633d5 100644 --- a/crates/lucisv_server/src/imports.rs +++ b/crates/lucisv_server/src/imports.rs @@ -30,7 +30,7 @@ use lsp_types::{CodeAction, CodeActionKind, CodeActionOrCommand, Position, Uri, use serde::{Deserialize, Serialize}; use serde_json::Value; -use crate::state::Workspace; +use crate::state::{Document, Workspace}; /// Organize the imports at a position: `[uri, position]`. pub const ORGANIZE_IMPORTS: &str = "lucisv.organizeImports"; @@ -144,10 +144,23 @@ pub fn execute( /// The cheap gate first: `imported_packages` is one parse of one buffer and /// answers "nothing here" for almost every cursor, which is what keeps a /// `textDocument/codeAction` on every keystroke off the index. +/// Every package the scope at `offset` imports, asked of the buffer's own +/// parse and its own diagnostics rather than of its text (take 5 §P1b). A +/// buffer on the large-file fast path keeps the text form, whose parse is of +/// the real bytes — see `ports::modules_at` for the whole reason. +fn packages_at(doc: &Document, offset: u32) -> Vec { + match doc.large { + true => vlog_refactor::imported_packages(&doc.text, offset), + false => { + vlog_refactor::imported_packages_in(&doc.tree, &doc.diagnostics, &doc.text, offset) + } + } +} + fn at(ws: &Workspace, uri: &Uri, offset: u32) -> Option<(PathBuf, Vec<(PathBuf, String)>)> { let doc = ws.document(uri)?; let path = doc.path.clone()?; - let packages = vlog_refactor::imported_packages(&doc.text, offset); + let packages = packages_at(doc, offset); if packages.is_empty() { return None; } diff --git a/crates/lucisv_server/src/inline_module.rs b/crates/lucisv_server/src/inline_module.rs index 1eaa6af..e35c823 100644 --- a/crates/lucisv_server/src/inline_module.rs +++ b/crates/lucisv_server/src/inline_module.rs @@ -23,7 +23,7 @@ use lsp_types::{ }; use serde_json::Value; -use crate::state::Workspace; +use crate::state::{Document, Workspace}; /// Inline the module instantiated at a position: `[uri, position]`. pub const INLINE_MODULE: &str = "lucisv.inlineModule"; @@ -40,6 +40,19 @@ pub fn kind() -> CodeActionKind { } /// The action for the cursor, carrying the command that does the work. +/// Whether the cursor is on an instantiation lucisv could inline, asked of the +/// buffer's own parse and diagnostics rather than of its text (take 5 §P1b). +/// +/// A buffer on the large-file fast path keeps the text form, whose parse is of +/// the real bytes rather than of the empty analysis that path installs — see +/// `ports::modules_at` and `docs/features/perf5-p1/README.md`. +fn site_at(doc: &Document, offset: u32) -> Option { + match doc.large { + true => vlog_refactor::inline_site(&doc.text, offset), + false => vlog_refactor::inline_site_in(&doc.tree, &doc.diagnostics, &doc.text, offset), + } +} + pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; if doc.path.is_none() { @@ -48,7 +61,7 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec Vec Vec { /// ([`Workspace::module_sources`]), which is ~1.4 ms per instantiating file: /// fine once, when the user has clicked, and not fine on every cursor move, /// which is why [`offers`] exists. +/// Every module name a port refactoring at `offset` could act on, asked of +/// the buffer's **own parse** rather than of its text. +/// +/// `doc.tree` is the tolerant parse of `doc.text`, which is exactly what the +/// text form would build (`docs/features/one-parse/README.md`), so the answer +/// is the same and the parse is not paid for twice (take 5 §P1b). +/// +/// A buffer on the large-file fast path is the exception, and deliberately so: +/// its `tree` is the analysis of the *empty* file, while the text form parses +/// the real bytes and may offer. That is today's behaviour and this reuse does +/// not change it — see `docs/features/perf5-p1/README.md`. +fn modules_at(doc: &Document, offset: u32) -> Vec { + match doc.large { + true => vlog_refactor::port_action_modules(&doc.text, offset), + false => vlog_refactor::port_action_modules_in(&doc.tree, offset), + } +} + pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; let Some(path) = doc.path.clone() else { return Vec::new() }; @@ -82,7 +100,7 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; let Some(path) = doc.path.clone() else { return Vec::new() }; - let modules = vlog_refactor::port_action_modules(&doc.text, offset); + let modules = modules_at(doc, offset); // A name the workspace declares twice is a refusal the engine makes over // the fan-out, where it can see both declarations. The offer cannot, so it // asks the index the same question rather than offering an action that diff --git a/crates/lucisv_server/src/server/dispatch.rs b/crates/lucisv_server/src/server/dispatch.rs index ee84f4f..6a0b815 100644 --- a/crates/lucisv_server/src/server/dispatch.rs +++ b/crates/lucisv_server/src/server/dispatch.rs @@ -26,17 +26,17 @@ use lsp_types::request::{ }; use lsp_types::{ CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, - CodeAction, CodeActionKind, CodeActionParams, CodeLensParams, CompletionParams, - DocumentDiagnosticParams, DocumentDiagnosticReportResult, DocumentHighlightParams, - DocumentLinkParams, DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, - FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams, - InlineCompletionParams, LinkedEditingRangeParams, Position, ReferenceParams, RenameFilesParams, - RenameParams, SelectionRangeParams, SemanticTokens, SemanticTokensDeltaParams, - SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult, - SemanticTokensResult, SignatureHelpParams, TextDocumentPositionParams, - TypeHierarchyPrepareParams, TypeHierarchySubtypesParams, TypeHierarchySupertypesParams, Uri, - WorkspaceDiagnosticParams, WorkspaceDiagnosticReportResult, WorkspaceSymbolParams, - WorkspaceSymbolResponse, + CodeAction, CodeActionKind, CodeActionOrCommand, CodeActionParams, CodeLensParams, + CompletionParams, DocumentDiagnosticParams, DocumentDiagnosticReportResult, + DocumentHighlightParams, DocumentLinkParams, DocumentSymbolParams, DocumentSymbolResponse, + ExecuteCommandParams, FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse, + HoverParams, InlayHintParams, InlineCompletionParams, LinkedEditingRangeParams, Position, + ReferenceParams, RenameFilesParams, RenameParams, SelectionRangeParams, SemanticTokens, + SemanticTokensDeltaParams, SemanticTokensParams, SemanticTokensRangeParams, + SemanticTokensRangeResult, SemanticTokensResult, SignatureHelpParams, + TextDocumentPositionParams, TypeHierarchyPrepareParams, TypeHierarchySubtypesParams, + TypeHierarchySupertypesParams, Uri, WorkspaceDiagnosticParams, WorkspaceDiagnosticReportResult, + WorkspaceSymbolParams, WorkspaceSymbolResponse, }; use serde::de::DeserializeOwned; use serde_json::Value; @@ -246,14 +246,35 @@ impl Server { let uri = p.text_document.uri; let only = p.context.only; let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) }; - // 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()); - let run = lint::LintRun::for_document(&self.workspace, doc); - let mut actions = - code_action::code_actions(&run, &uri, doc, p.range, only.as_deref(), tab_width); + // A filter naming no kind at all selects nothing: every + // `wanted` below is false, so the answer is empty however much + // work is done to reach it. Answering here is what keeps a + // client that asks for nothing from paying for config + // discovery, a lint pass and four selectors (take 5 §P1a). + if only.as_deref().is_some_and(<[CodeActionKind]>::is_empty) { + return to_value(Vec::::new()); + } + let mut actions: Vec = Vec::new(); + // Quick fixes and `source.fixAll.lucisv` are the only two + // families the lint pass answers for, so a request for neither + // — an organize-on-save, a refactor-only menu — does not read + // the project's configuration and does not lint. + 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()); + let run = lint::LintRun::for_document(&self.workspace, doc); + actions.extend(code_action::code_actions( + &run, + &uri, + doc, + p.range, + only.as_deref(), + tab_width, + )); + } // The port refactorings answer for the cursor, not for a range: // the request's start is where the user is. if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS)) diff --git a/crates/lucisv_server/src/server/tests/code_action.rs b/crates/lucisv_server/src/server/tests/code_action.rs new file mode 100644 index 0000000..5a5a8af --- /dev/null +++ b/crates/lucisv_server/src/server/tests/code_action.rs @@ -0,0 +1,463 @@ +//! What a `textDocument/codeAction` request does, and — just as much — what +//! it no longer does. +//! +//! Take 5 §P1 (`docs/features/perf5-p1/README.md`) removed work from this +//! path: an empty `context.only` answers before the configuration is read, the +//! lint pass runs only when a fix family is asked for, the fence answer is +//! computed only when a fix exists and only once per document revision, and +//! the four refactoring selectors read the buffer's own parse instead of +//! parsing its text again. Every one of those is asserted here **by counting +//! parses**, not by timing them: `vlog_parser::stats::parses()` is a +//! thread-local count and a request is answered on this thread. + +use super::*; + +/// A module with a tab in it — one `no-tabs` finding, carrying a Safe fix — +/// an instantiation of `sub`, so the port and inline families have something +/// to look at, and a comment line where nothing at all is offered. +/// +/// Line 1 is the tab, line 2 the instantiation, line 3 the comment. +const FIXABLE: &str = "module m;\n\twire a;\n sub u_sub (.a(a));\n // nothing here\nendmodule\n"; + +/// The declaration `FIXABLE` instantiates. +const SUB: &str = "module sub (\n input logic a,\n input logic b\n);\nendmodule\n"; + +/// A finding with **no** fix: `module-filename` does not offer to rename a +/// file. So a lint pass over this buffer produces a violation, and nothing +/// that a fence could protect. +const UNFIXABLE: &str = "module other;\nendmodule\n"; + +/// A zero-width range at a position — the shape an editor sends on a cursor +/// move. +fn cursor(uri: &Uri, line: u32, character: u32) -> Value { + serde_json::json!({ + "textDocument": { "uri": uri }, + "range": { + "start": { "line": line, "character": character }, + "end": { "line": line, "character": character }, + }, + "context": { "diagnostics": [] }, + }) +} + +/// `cursor`, with a `context.only` filter. +fn filtered(uri: &Uri, line: u32, character: u32, only: &[&str]) -> Value { + let mut params = cursor(uri, line, character); + params["context"]["only"] = serde_json::json!(only); + params +} + +/// The whole-file parses one request performed. +fn parses_during(session: &mut Session, params: Value) -> (u64, Value) { + let before = vlog_parser::stats::parses(); + let result = session.result(CodeActionRequest::METHOD, params); + (vlog_parser::stats::parses() - before, result) +} + +/// The titles an answer carries, in the order it carries them. +fn titles(result: &Value) -> Vec { + result + .as_array() + .expect("an action list") + .iter() + .map(|action| action["title"].as_str().unwrap_or_default().to_string()) + .collect() +} + +/// The kinds an answer carries, in order. +fn kinds(result: &Value) -> Vec { + result + .as_array() + .expect("an action list") + .iter() + .map(|action| action["kind"].as_str().unwrap_or_default().to_string()) + .collect() +} + +/// A session over a tree holding `m.sv` and `sub.sv`, with `m.sv` open. +fn opened(tree: &Tree, text: &str) -> (Session, Uri) { + tree.write("sub.sv", SUB); + let mut session = Session::wide(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), text); + session.drain(); + (session, uri) +} + +// ------------------------------------------------------------------ +// §P1a — the work a filtered request no longer does +// ------------------------------------------------------------------ + +#[test] +fn an_empty_only_filter_answers_empty_and_does_no_work_at_all() { + let tree = Tree::new("caempty"); + let (mut session, uri) = opened(&tree, FIXABLE); + let (parses, result) = parses_during(&mut session, filtered(&uri, 1, 1, &[])); + assert_eq!(result, serde_json::json!([]), "no kind is selected, so no action is"); + assert_eq!( + parses, 0, + "an empty filter reads no configuration, lints nothing and parses nothing" + ); +} + +#[test] +fn a_refactor_only_request_never_runs_the_lint_pass() { + let tree = Tree::new("carefactor"); + let (mut session, uri) = opened(&tree, FIXABLE); + // The buffer has a fixable finding, so a lint pass here would ask for the + // fence regions — a whole-file parse of its own. One parse means exactly + // one selector ran and the lint pass did not. + let (parses, result) = parses_during(&mut session, filtered(&uri, 1, 1, &["refactor.extract"])); + assert_eq!(parses, 0, "the selector reads the buffer's own parse (§P1b): {result:#?}"); + assert!( + !titles(&result).iter().any(|title| title.contains("no-tabs")), + "and no quick fix is offered: {result:#?}" + ); +} + +#[test] +fn a_quickfix_only_request_never_runs_the_selectors() { + let tree = Tree::new("caquickfix"); + let (mut session, uri) = opened(&tree, FIXABLE); + let (parses, result) = parses_during(&mut session, filtered(&uri, 1, 1, &["quickfix"])); + assert_eq!(parses, 1, "the fence parse alone — no selector ran: {result:#?}"); + assert_eq!( + titles(&result), + vec!["lucisv: use spaces, not tabs [no-tabs]".to_string()], + "{result:#?}" + ); +} + +#[test] +fn a_pass_whose_findings_carry_no_fix_never_asks_about_fences() { + let tree = Tree::new("canofix"); + let (mut session, uri) = opened(&tree, UNFIXABLE); + let (parses, result) = parses_during(&mut session, filtered(&uri, 0, 0, &["quickfix"])); + assert_eq!(result, serde_json::json!([]), "the finding has no fix to offer"); + assert_eq!(parses, 0, "and nothing to protect, so no fence parse"); +} + +#[test] +fn the_kind_filter_is_a_prefix_and_still_selects_the_whole_family() { + let tree = Tree::new("caprefix"); + let (mut session, uri) = opened(&tree, FIXABLE); + // `source` selects `source.fixAll.lucisv`, which is a fix family: the + // lint pass must run for it. + let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["source"])); + assert_eq!(kinds(&result), vec!["source.fixAll.lucisv".to_string()], "{result:#?}"); + // `refactor` selects every refactoring family and no fix family. + let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 2, &["refactor"])); + assert!( + kinds(&result).iter().all(|kind| kind.starts_with("refactor")), + "no fix family under a refactor filter: {result:#?}" + ); +} + +#[test] +fn an_unfiltered_request_keeps_the_order_quick_fixes_fix_all_then_refactorings() { + let tree = Tree::new("caorder"); + let (mut session, uri) = opened(&tree, FIXABLE); + // The cursor is on the tabbed line, so the quick fix is offered, and the + // buffer's one instantiation puts a refactoring family behind it. + let result = session.result(CodeActionRequest::METHOD, cursor(&uri, 1, 1)); + let kinds = kinds(&result); + assert_eq!(kinds.first().map(String::as_str), Some("quickfix"), "{result:#?}"); + assert_eq!(kinds.get(1).map(String::as_str), Some("source.fixAll.lucisv"), "{result:#?}"); + // Everything after the two fix families is a refactoring, and there is at + // least one — an answer of two actions would prove nothing about order. + assert!(kinds.len() > 2, "a refactoring is offered here too: {result:#?}"); + assert!( + kinds[2..].iter().all(|kind| kind.starts_with("refactor")), + "the refactoring families come last: {kinds:#?}" + ); +} + +#[test] +fn a_fix_spanning_the_cursor_is_still_offered() { + let tree = Tree::new("caspan"); + // A trailing-whitespace finding whose span starts before the cursor and + // ends after it: the cursor is *inside* the fix, not at its start. + let (mut session, uri) = opened(&tree, "module m;\n wire a; \nendmodule\n"); + let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 10, &["quickfix"])); + assert!( + titles(&result).iter().any(|title| title.contains("no-trailing-whitespace")), + "{result:#?}" + ); +} + +#[test] +fn a_cursor_with_no_selection_is_still_offered_the_extraction() { + let tree = Tree::new("cacursor"); + let (mut session, uri) = opened(&tree, FIXABLE); + // A zero-width range on a whole item: extraction takes the item the + // cursor is in, so an empty selection must not disable it. + let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 2, &["refactor"])); + assert!( + kinds(&result).iter().any(|kind| kind == "refactor.extract"), + "an empty range still extracts: {result:#?}" + ); +} + +// ------------------------------------------------------------------ +// §P1b — the work a repeated request no longer does +// ------------------------------------------------------------------ + +#[test] +fn a_repeated_offer_where_nothing_is_offered_parses_nothing_at_all() { + let tree = Tree::new("carepeat"); + let (mut session, uri) = opened(&tree, FIXABLE); + // The comment line: every family is asked, and every family answers + // nothing, so the four gates are the whole of the work. This is the + // pinmux-comment cursor of take 5's headline row, in miniature. + let (first, expected) = parses_during(&mut session, cursor(&uri, 3, 2)); + assert!(first <= 1, "the first request pays for the fence answer at most: {first}"); + // Every request after it, on the same revision, parses nothing: the four + // selectors read `doc.tree` and the fence answer is the one already made. + for round in 0..3 { + let (parses, again) = parses_during(&mut session, cursor(&uri, 3, 2)); + assert_eq!(parses, 0, "round {round} re-parsed the buffer"); + assert_eq!(again, expected, "round {round} answered differently"); + } +} + +#[test] +fn the_gate_only_families_parse_nothing_even_where_they_do_offer() { + let tree = Tree::new("carepeatgate"); + let (mut session, uri) = opened(&tree, FIXABLE); + // Extraction and inlining are answered by their gate alone — the offer + // carries a command, not an edit, so no engine runs. On the + // instantiation both of them offer, and neither parses. + let only = &["refactor.extract", "refactor.inline"]; + let (_, first) = parses_during(&mut session, filtered(&uri, 2, 2, only)); + assert_eq!(kinds(&first).len(), 2, "both families offer here: {first:#?}"); + for round in 0..3 { + let (parses, again) = parses_during(&mut session, filtered(&uri, 2, 2, only)); + assert_eq!(parses, 0, "round {round}"); + assert_eq!(again, first, "round {round}"); + } +} + +#[test] +fn the_port_offer_still_reaches_the_engine_and_that_is_what_p1c_is_for() { + let tree = Tree::new("carepeatports"); + let (mut session, uri) = opened(&tree, FIXABLE); + // §P1b gives the port family its gate for free, but a gate that says yes + // hands the engine one or two files and the engine parses them to build a + // plan whose edits are then thrown away. That residue is measured here + // rather than left to be discovered as a slow cursor: it is take 5 §P1c's + // subject, and this assertion is what would notice it growing. + let only = &["refactor.rewrite.lucisv.ports"]; + let (_, first) = parses_during(&mut session, filtered(&uri, 2, 2, only)); + assert!(!kinds(&first).is_empty(), "the port family offers here: {first:#?}"); + let (parses, _) = parses_during(&mut session, filtered(&uri, 2, 2, only)); + assert!(parses > 0, "the offer still computes a plan it discards (§P1c)"); + // The buffer's *own* parse is not among them: the gate was answered from + // `doc.tree`, so what is left is the engine's own scope over the module's + // declaring file. + let (gate_only, _) = parses_during(&mut session, filtered(&uri, 3, 2, only)); + assert_eq!(gate_only, 0, "at a cursor the gate refuses, nothing is parsed"); +} + +#[test] +fn an_empty_filter_parses_nothing_however_often_it_is_asked() { + let tree = Tree::new("carepeatempty"); + let (mut session, uri) = opened(&tree, FIXABLE); + for round in 0..4 { + let (parses, result) = parses_during(&mut session, filtered(&uri, 2, 2, &[])); + assert_eq!(parses, 0, "round {round}"); + assert_eq!(result, serde_json::json!([]), "round {round}"); + } +} + +#[test] +fn the_first_offer_after_a_change_parses_the_buffer_once_and_no_more() { + let tree = Tree::new("cachange"); + let (mut session, uri) = opened(&tree, FIXABLE); + let _ = parses_during(&mut session, cursor(&uri, 3, 2)); + // A `didChange` is flushed by the request behind it, so the parse + // `Document::new` makes is counted inside this request — one parse, plus + // the fence answer, and nothing from the four selectors. + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ "text": format!("{FIXABLE}// changed\n") }], + }), + ); + let (parses, _) = parses_during(&mut session, cursor(&uri, 3, 2)); + assert!(parses <= 2, "the document's own parse, plus at most the fence answer: {parses}"); + // And the request after that one is free again. + let (parses, _) = parses_during(&mut session, cursor(&uri, 3, 2)); + assert_eq!(parses, 0, "the new revision is reused like any other"); +} + +#[test] +fn a_fence_typed_into_the_buffer_is_seen_by_the_next_request() { + let tree = Tree::new("cafence"); + // A tab on line 1: a `no-tabs` finding with a Safe fix, offered as a + // quick fix. + let (mut session, uri) = opened(&tree, "module m;\n\twire a;\nendmodule\n"); + let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"])); + assert_eq!(titles(&result).len(), 1, "the fix is offered: {result:#?}"); + // Now fence that line. The memo is held on the `Document`, and a change + // builds a new one — so the answer must be the new text's, not the old + // text's. + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ + "text": "module m;\n// lucisv: off\n\twire a;\n// lucisv: on\nendmodule\n", + }], + }), + ); + let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 2, 1, &["quickfix"])); + assert!(result.as_array().expect("a list").is_empty(), "fenced: {result:#?}"); + // And back again: removing the fence restores the fix, which a memo that + // outlived its revision could not do. + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 3 }, + "contentChanges": [{ "text": "module m;\n\twire a;\nendmodule\n" }], + }), + ); + let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"])); + assert_eq!(titles(&result).len(), 1, "unfenced again: {result:#?}"); +} + +#[test] +fn an_external_waiver_still_keeps_its_fix_out_of_the_offer() { + let tree = Tree::new("cawaiver"); + tree.write("waivers.txt", "no-tabs\n"); + let mut session = Session::wide(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\n\twire a;\nendmodule\n"); + session.drain(); + // Without the waiver configured the fix is there. + let before = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"])); + assert_eq!(titles(&before).len(), 1, "{before:#?}"); + // A `lucisv.toml` written between requests changes the pass, and the + // configuration is read per request — nothing about it is memoized. + tree.write("lucisv.toml", "[lint]\nignore = [\"no-tabs\"]\n"); + let after = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 1, &["quickfix"])); + assert!(after.as_array().expect("a list").is_empty(), "the new config is read: {after:#?}"); +} + +#[test] +fn an_untitled_buffer_is_offered_the_fix_families_and_no_refactoring() { + let tree = Tree::new("cauntitled"); + tree.write("sub.sv", SUB); + let mut session = Session::wide(vec![tree.path.clone()], false); + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + session.notify( + DidOpenTextDocument::METHOD, + serde_json::json!({ + "textDocument": { + "uri": uri, "languageId": "systemverilog", "version": 1, "text": FIXABLE, + } + }), + ); + session.drain(); + let result = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2)); + assert!( + !kinds(&result).iter().any(|kind| kind == "refactor.extract"), + "an untitled buffer has no directory to extract into: {result:#?}" + ); +} + +#[test] +fn a_buffer_with_crlf_endings_and_an_astral_character_offers_the_same_actions() { + let tree = Tree::new("cacrlf"); + let lf = "// \u{1F600}\nmodule m;\n sub u_sub (.a(1));\nendmodule\n"; + let (mut session, uri) = opened(&tree, lf); + // Line 2, character 2 is inside the instantiation in both encodings; the + // comment above it puts a non-BMP character in front of every offset, so + // the UTF-16 conversion is doing real work. + let plain = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2)); + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ "text": lf.replace('\n', "\r\n") }], + }), + ); + let windows = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2)); + assert_eq!(titles(&plain), titles(&windows), "{plain:#?}\n{windows:#?}"); + assert_eq!(kinds(&plain), kinds(&windows)); +} + +#[test] +fn a_buffer_that_does_not_parse_offers_what_it_always_offered() { + let tree = Tree::new("cabroken"); + let (mut session, uri) = + opened(&tree, "module m;\n sub u_sub (.a(1));\n logic ;;; w\nendmodule\n"); + let result = session.result(CodeActionRequest::METHOD, filtered(&uri, 1, 6, &["refactor"])); + // The three gates that refuse over parse diagnostics still refuse; the + // port family, which never had that check, still answers. + assert!( + !kinds(&result).iter().any(|kind| kind == "refactor.extract" || kind == "refactor.inline"), + "a broken parse offers no extraction and no inline: {result:#?}" + ); +} + +#[test] +fn an_index_refresh_does_not_change_what_the_cursor_offers() { + let tree = Tree::new("careindex"); + let (mut session, uri) = opened(&tree, FIXABLE); + let before = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2)); + // A saved file elsewhere rebuilds the index; the buffer is untouched, so + // its own parse — and its fence answer — stay exactly as they were. + tree.write("other.sv", "module other_one;\nendmodule\n"); + session + .notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } })); + session.drain(); + let after = session.result(CodeActionRequest::METHOD, cursor(&uri, 2, 2)); + assert_eq!(titles(&before), titles(&after), "{before:#?}\n{after:#?}"); +} + +#[test] +fn a_large_buffer_still_answers_its_command_from_its_text() { + // The large-file fast path installs the analysis of the *empty* file, so + // a `doc.tree` reader would find nothing in a large buffer. The four + // selectors therefore keep their text form there — which is exactly what + // they did before §P1b, and this pins it. + // + // `textDocument/codeAction` cannot show it: the fast path answers that + // method with an empty list before the dispatch is entered + // (`server/large_file.rs`). `workspace/executeCommand` is not gated, and + // is where a large buffer really does reach a selector. + let tree = Tree::new("calarge"); + tree.write("sub.sv", SUB); + let mut body = String::from("module big;\n logic a;\n sub u_sub (.a(a), .b(a));\n"); + for i in 0..20 { + body.push_str(&format!(" logic pad{i};\n")); + } + body.push_str("endmodule\n"); + assert!(body.len() > 100, "the premise: over the test threshold"); + let settings = crate::settings::ClientSettings { + large_file_threshold: 100, + index_scope: crate::settings::IndexScope::Workspace, + ..Default::default() + }; + let mut session = + Session::started(vec![tree.path.clone()], ClientAbilities::default(), settings); + let path = tree.path.join("big.sv"); + std::fs::write(&path, &body).expect("write"); + let uri = session.open(&path, &body); + session.drain(); + let response = session.request( + ExecuteCommand::METHOD, + serde_json::json!({ + "command": crate::inline_module::INLINE_MODULE, + "arguments": [uri, { "line": 2, "character": 2 }], + }), + ); + let refusal = match response.response_result { + Ok(_) => None, + Err(error) => Some(error.message), + }; + assert_ne!( + refusal.as_deref(), + Some("there is no module instantiation at this position to inline."), + "a large buffer's selector reads its text, so the instantiation is found" + ); +} diff --git a/crates/lucisv_server/src/server/tests/mod.rs b/crates/lucisv_server/src/server/tests/mod.rs index 06fc2b0..cb5da00 100644 --- a/crates/lucisv_server/src/server/tests/mod.rs +++ b/crates/lucisv_server/src/server/tests/mod.rs @@ -45,6 +45,7 @@ use crate::{design_hierarchy, diagnostics, format, lens, pairs, ports}; mod apply_edit; mod cancel; +mod code_action; mod file_ops; mod folders; mod formatting; diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index ad7c60b..cf5f127 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -89,6 +89,12 @@ pub struct Document { /// there is nothing in it to find. See /// `docs/features/large-file-mode/README.md`. pub large: bool, + /// The formatter's fence answer for exactly this `text`, computed on + /// first use and never again — a whole tolerant parse the code-action + /// path used to pay for on every request. Filled through + /// [`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>, } impl Document { @@ -122,6 +128,7 @@ impl Document { defines, external, large, + fences: std::sync::OnceLock::new(), } } @@ -147,6 +154,7 @@ impl Document { defines: DefineTable::default(), external: ExternalResolutions::default(), large: true, + fences: std::sync::OnceLock::new(), } } diff --git a/crates/vlog_parser/src/lib.rs b/crates/vlog_parser/src/lib.rs index c66df8c..3c0baa3 100644 --- a/crates/vlog_parser/src/lib.rs +++ b/crates/vlog_parser/src/lib.rs @@ -10,6 +10,7 @@ pub mod lexer; pub mod line_index; pub mod parser; pub mod span; +pub mod stats; pub mod token; pub use lexer::{tokenize, LexError}; diff --git a/crates/vlog_parser/src/parser/mod.rs b/crates/vlog_parser/src/parser/mod.rs index 2d77e25..e2e28a1 100644 --- a/crates/vlog_parser/src/parser/mod.rs +++ b/crates/vlog_parser/src/parser/mod.rs @@ -301,6 +301,7 @@ struct Rewind { /// [`PARSE_STACK_SIZE`] of stack, or over-deep input aborts the process /// instead of returning `Err`. pub fn parse(tokens: Vec, source: &str) -> PResult { + crate::stats::count_parse(); Parser::new(tokens, source, false).parse_source_file() } @@ -317,6 +318,7 @@ pub fn parse(tokens: Vec, source: &str) -> PResult { /// [`PARSE_STACK_SIZE`] of stack, recovery included — tolerant and strict /// parses of the same over-deep input overflow at the same depth. pub fn parse_tolerant(tokens: Vec, source: &str) -> (SourceFile, Vec) { + crate::stats::count_parse(); let mut p = Parser::new(tokens, source, true); match p.parse_source_file() { Ok(file) => (file, p.diagnostics), diff --git a/crates/vlog_parser/src/stats.rs b/crates/vlog_parser/src/stats.rs new file mode 100644 index 0000000..147c2f7 --- /dev/null +++ b/crates/vlog_parser/src/stats.rs @@ -0,0 +1,39 @@ +//! How much parsing this thread has done — a work counter, not a timer. +//! +//! A `textDocument/codeAction` used to parse the same buffer five times, and +//! the only honest way to prove that it no longer does is to count the parses +//! rather than to time them (take 5 §P1, +//! `docs/features/perf5-p1/README.md`). A stopwatch assertion on a 1.3 MB +//! buffer is a flake; a count is not. +//! +//! **Per thread, deliberately.** A process-wide counter would be unusable as +//! an assertion, because `cargo test` runs tests in parallel and every other +//! test in the binary would be adding to it; and it would answer the wrong +//! question anyway, since what a caller wants to know is what *this* request +//! did. A request is answered on one thread, so a thread-local count is that +//! number exactly. It costs one non-atomic add per whole-file parse. + +use std::cell::Cell; + +thread_local! { + static PARSES: Cell = const { Cell::new(0) }; +} + +/// How many whole-file parses this thread has run. +/// +/// Counted in [`crate::parse`] and [`crate::parse_tolerant`], which is every +/// way a whole file is parsed: [`crate::parse_source`] and +/// [`crate::parse_source_tolerant`] both funnel through them. A *lex* failure +/// parses nothing and is not counted; neither is a fragment read (macro +/// expansion), which re-reads a token slice rather than a file. +/// +/// The count is monotone and never reset, so a caller measures a *delta* +/// across the work it is asking about. +pub fn parses() -> u64 { + PARSES.with(Cell::get) +} + +/// Count one whole-file parse. +pub(crate) fn count_parse() { + PARSES.with(|parses| parses.set(parses.get() + 1)); +} diff --git a/crates/vlog_refactor/src/extract/mod.rs b/crates/vlog_refactor/src/extract/mod.rs index 453d8e9..8b548c0 100644 --- a/crates/vlog_refactor/src/extract/mod.rs +++ b/crates/vlog_refactor/src/extract/mod.rs @@ -35,8 +35,8 @@ mod render; use std::path::{Path, PathBuf}; use vlog_parser::ast::{Item, ItemKind, SourceFile}; -use vlog_parser::parse_source_tolerant; use vlog_parser::span::TextRange; +use vlog_parser::{parse_source_tolerant, ParseDiagnostic}; use vlog_semantic::{analyze, SymbolKind}; use crate::rename::{display, Scope}; @@ -81,10 +81,26 @@ pub struct ExtractSite { /// a whole item to move. pub fn extract_site(text: &str, start: u32, end: u32) -> Option { let (tree, diagnostics) = parse_source_tolerant(text); + extract_site_in(&tree, &diagnostics, text, start, end) +} + +/// [`extract_site`] over a parse the caller already has. +/// +/// The same answer, refusal on parse diagnostics included — `diagnostics` +/// must be `tree`'s own list, and `text` the bytes both were built from +/// (`Region::read` copies item text out by span). Take 5 §P1b; see +/// `docs/features/perf5-p1/README.md`. +pub fn extract_site_in( + tree: &SourceFile, + diagnostics: &[ParseDiagnostic], + text: &str, + start: u32, + end: u32, +) -> Option { if !diagnostics.is_empty() { return None; } - let region = Region::read(&tree, text, TextRange::new(start, end)).ok()?; + let region = Region::read(tree, text, TextRange::new(start, end)).ok()?; let module = region.module_name().to_string(); let mut units = vec![module.clone()]; for item in ®ion.items { diff --git a/crates/vlog_refactor/src/imports.rs b/crates/vlog_refactor/src/imports.rs index 5f92bb6..75c5413 100644 --- a/crates/vlog_refactor/src/imports.rs +++ b/crates/vlog_refactor/src/imports.rs @@ -93,10 +93,26 @@ pub fn unused_imports(files: &[(PathBuf, String)], file: &Path) -> Vec<(TextRang /// them, and nothing else, to the engine. pub fn imported_packages(text: &str, offset: u32) -> Vec { let (tree, diagnostics) = parse_source_tolerant(text); + imported_packages_in(&tree, &diagnostics, text, offset) +} + +/// [`imported_packages`] over a parse the caller already has. +/// +/// The same answer, including the refusal on a buffer that did not parse +/// cleanly — `diagnostics` is that parse's own list and must come from the +/// same run as `tree`. `text` is still needed: the "is the cursor at the top" +/// question reads the source bytes of the import run's comment block. Take 5 +/// §P1b; see `docs/features/perf5-p1/README.md`. +pub fn imported_packages_in( + tree: &SourceFile, + diagnostics: &[ParseDiagnostic], + text: &str, + offset: u32, +) -> Vec { if !diagnostics.is_empty() { return Vec::new(); } - let Some(items) = container_at(&tree, offset) else { return Vec::new() }; + let Some(items) = container_at(tree, offset) else { return Vec::new() }; let imports: Vec<&Item> = items.iter().filter(|item| is_import(item)).collect(); if imports.is_empty() || !at_the_top(text, items, offset) { return Vec::new(); diff --git a/crates/vlog_refactor/src/inline/mod.rs b/crates/vlog_refactor/src/inline/mod.rs index a36c702..78420dc 100644 --- a/crates/vlog_refactor/src/inline/mod.rs +++ b/crates/vlog_refactor/src/inline/mod.rs @@ -34,9 +34,10 @@ mod source; use std::path::{Path, PathBuf}; +use vlog_parser::ast::SourceFile; use vlog_parser::span::TextRange; use vlog_parser::token::TokenKind; -use vlog_parser::{parse_source_tolerant, tokenize}; +use vlog_parser::{parse_source_tolerant, tokenize, ParseDiagnostic}; use crate::instantiate::module_definition; use crate::rename::{contains_word, display, Scope}; @@ -72,10 +73,25 @@ pub struct InlineSite { /// sentence from the command instead. pub fn inline_site(text: &str, offset: u32) -> Option { let (tree, diagnostics) = parse_source_tolerant(text); + inline_site_in(&tree, &diagnostics, text, offset) +} + +/// [`inline_site`] over a parse the caller already has. +/// +/// The same answer, refusal on parse diagnostics included — `diagnostics` +/// must be `tree`'s own list, and `text` the bytes both were built from +/// (`Site::read` reads the instantiation's connections out of the source). +/// Take 5 §P1b; see `docs/features/perf5-p1/README.md`. +pub fn inline_site_in( + tree: &SourceFile, + diagnostics: &[ParseDiagnostic], + text: &str, + offset: u32, +) -> Option { if !diagnostics.is_empty() { return None; } - let site = Site::read(&tree, text, offset)?.ok()?; + let site = Site::read(tree, text, offset)?.ok()?; Some(InlineSite { units: vec![site.target.clone(), site.module.name.clone()], module: site.target.clone(), diff --git a/crates/vlog_refactor/src/lib.rs b/crates/vlog_refactor/src/lib.rs index 94f2145..0738d56 100644 --- a/crates/vlog_refactor/src/lib.rs +++ b/crates/vlog_refactor/src/lib.rs @@ -37,11 +37,14 @@ mod references; mod rename; mod scope; -pub use extract::{extract_module, extract_site, extract_title, ExtractSite, Home}; -pub use imports::{ - imported_packages, organize_counts, organize_imports, organize_title, unused_imports, +pub use extract::{ + extract_module, extract_site, extract_site_in, extract_title, ExtractSite, Home, }; -pub use inline::{inline_module, inline_site, inline_title, InlineSite}; +pub use imports::{ + imported_packages, imported_packages_in, organize_counts, organize_imports, organize_title, + unused_imports, +}; +pub use inline::{inline_module, inline_site, inline_site_in, inline_title, InlineSite}; pub use references::find_references; pub use instantiate::{ @@ -50,8 +53,8 @@ pub use instantiate::{ }; pub use ports::{ add_port, convert_to_ansi, enclosing_module, expand_wildcard, is_sites_phrase, - may_have_port_action, port_action_modules, port_actions, propagate_ports, remove_port, - sites_phrase, ModuleRef, PortAction, + may_have_port_action, port_action_modules, port_action_modules_in, port_actions, + propagate_ports, remove_port, sites_phrase, ModuleRef, PortAction, }; pub use rename::{ contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget, diff --git a/crates/vlog_refactor/src/ports/mod.rs b/crates/vlog_refactor/src/ports/mod.rs index c985509..41efaca 100644 --- a/crates/vlog_refactor/src/ports/mod.rs +++ b/crates/vlog_refactor/src/ports/mod.rs @@ -34,7 +34,7 @@ pub(crate) use find::{find_module, visible_in}; use std::path::{Path, PathBuf}; -use vlog_parser::ast::{Connections, ItemKind, Module, PortList}; +use vlog_parser::ast::{Connections, ItemKind, Module, PortList, SourceFile}; use vlog_parser::parse_source_tolerant; use crate::rename::{display, Scope}; @@ -268,6 +268,22 @@ pub fn may_have_port_action(text: &str, offset: u32) -> bool { /// the whole workspace. Empty for exactly the positions the gate refuses. pub fn port_action_modules(text: &str, offset: u32) -> Vec { let (tree, _) = parse_source_tolerant(text); + port_action_modules_in(&tree, offset) +} + +/// [`port_action_modules`] over a parse the caller already has. +/// +/// The same walk and the same answer; only the parse moves. A server holds +/// the tolerant parse of the buffer it is answering about +/// (`lucisv_server::state::Document`), so asking it to parse the same bytes +/// again is a whole-file parse per cursor move — which is what take 5 §P1b +/// removes (`docs/features/perf5-p1/README.md`). +/// +/// `tree` must be the tolerant parse of the same text the offsets index. This +/// selector reads **no** parse diagnostics, exactly as the text form does not: +/// a port refactoring is offered on a buffer that does not fully parse, and +/// the engine refuses later if it must. +pub fn port_action_modules_in(tree: &SourceFile, offset: u32) -> Vec { let mut instantiations = Vec::new(); collect_instantiations(&tree.items, &mut instantiations); let named: Vec = instantiations @@ -284,7 +300,7 @@ pub fn port_action_modules(text: &str, offset: u32) -> Vec { let mut module = None; module_at(&tree.items, offset, &mut module); let Some((name, (module, _))) = - module.and_then(|name| Some((name.clone(), find_module(&tree, &name)?))) + module.and_then(|name| Some((name.clone(), find_module(tree, &name)?))) else { return Vec::new(); }; diff --git a/crates/vlog_refactor/tests/parsed_selectors.rs b/crates/vlog_refactor/tests/parsed_selectors.rs new file mode 100644 index 0000000..44adcbc --- /dev/null +++ b/crates/vlog_refactor/tests/parsed_selectors.rs @@ -0,0 +1,171 @@ +//! The four cheap gates answer the same thing over a parse the caller already +//! has as they do over the text they would parse themselves. +//! +//! Take 5 §P1b (`docs/features/perf5-p1/README.md`) added `*_in` forms of +//! `port_action_modules`, `imported_packages`, `extract_site` and +//! `inline_site` so a server can spend the parse it already made. The text +//! forms stayed and became wrappers, and this file is the proof that the two +//! agree — over clean buffers, over buffers that do not parse, over CRLF, over +//! text with a non-BMP character in front of the cursor, and at every byte of +//! a small buffer rather than at a cursor chosen to pass. + +use vlog_parser::parse_source_tolerant; +use vlog_refactor::{ + extract_site, extract_site_in, imported_packages, imported_packages_in, inline_site, + inline_site_in, port_action_modules, port_action_modules_in, +}; + +/// A module that instantiates another, imports two packages, and has items +/// worth extracting — so every one of the four gates has something to find +/// somewhere in it. +const CLEAN: &str = "\ +module m ( + input logic clk_i, + output logic q_o +); + import a_pkg::*; + import b_pkg::*; + logic w; + sub u_sub (.a(clk_i), .b(w)); + assign q_o = w; +endmodule +"; + +/// The same text with a construct the parser cannot recover into an item, so +/// the tolerant parse reports diagnostics — the case three of the four gates +/// refuse over. +const BROKEN: &str = "\ +module m; + sub u_sub (.a(1)); + logic ;;; w +endmodule +"; + +/// A Verilog-2001 header, which is the one shape `convert to ANSI` answers at +/// and the one `port_action_modules` finds without an instantiation. +const NON_ANSI: &str = "\ +module old (a, b); + input a; + output b; + assign b = a; +endmodule +"; + +/// A non-BMP character in a comment before everything else: the bytes before +/// every cursor differ from the UTF-16 units, which is the shape a client's +/// position conversion produces. +const ASTRAL: &str = "\ +// \u{1F600} a comment +module m; + sub u_sub (.a(1)); +endmodule +"; + +fn crlf(text: &str) -> String { + text.replace('\n', "\r\n") +} + +/// Every gate, both ways, at one offset — asserting the two agree. +fn agree_at(text: &str, offset: u32) { + let (tree, diagnostics) = parse_source_tolerant(text); + assert_eq!( + port_action_modules(text, offset), + port_action_modules_in(&tree, offset), + "port_action_modules at {offset}" + ); + assert_eq!( + imported_packages(text, offset), + imported_packages_in(&tree, &diagnostics, text, offset), + "imported_packages at {offset}" + ); + assert_eq!( + inline_site(text, offset), + inline_site_in(&tree, &diagnostics, text, offset), + "inline_site at {offset}" + ); + // Extraction answers for a range: the empty one at the cursor (which is + // what an editor sends on a cursor move) and one covering the rest of the + // buffer. + let end = text.len() as u32; + assert_eq!( + extract_site(text, offset, offset), + extract_site_in(&tree, &diagnostics, text, offset, offset), + "extract_site at the cursor {offset}" + ); + assert_eq!( + extract_site(text, offset, end), + extract_site_in(&tree, &diagnostics, text, offset, end), + "extract_site over {offset}..{end}" + ); +} + +/// Every byte offset of a buffer, and one past its end. +fn agree_everywhere(text: &str) { + for offset in 0..=text.len() as u32 { + agree_at(text, offset); + } +} + +#[test] +fn the_parsed_gates_answer_a_clean_buffer_exactly_as_the_text_gates_do() { + agree_everywhere(CLEAN); +} + +#[test] +fn the_parsed_gates_answer_a_buffer_that_does_not_parse_exactly_as_the_text_gates_do() { + agree_everywhere(BROKEN); + // And the three that refuse over diagnostics really do refuse here, so + // this case is not agreeing by both answering about a clean buffer. + let (tree, diagnostics) = parse_source_tolerant(BROKEN); + assert!(!diagnostics.is_empty(), "the fixture must not parse cleanly"); + let cursor = BROKEN.find("u_sub").expect("the instance") as u32; + assert!(imported_packages_in(&tree, &diagnostics, BROKEN, cursor).is_empty()); + assert!(inline_site_in(&tree, &diagnostics, BROKEN, cursor).is_none()); + assert!(extract_site_in(&tree, &diagnostics, BROKEN, cursor, cursor).is_none()); + // The port gate has no diagnostics check and never had one: it still finds + // the instantiation under the cursor. + assert_eq!(port_action_modules_in(&tree, cursor), vec!["sub".to_string()]); +} + +#[test] +fn the_parsed_gates_agree_over_crlf_line_endings() { + agree_everywhere(&crlf(CLEAN)); + agree_everywhere(&crlf(BROKEN)); +} + +#[test] +fn the_parsed_gates_agree_with_a_non_bmp_character_before_the_cursor() { + agree_everywhere(ASTRAL); +} + +#[test] +fn the_parsed_gates_agree_on_a_non_ansi_header() { + agree_everywhere(NON_ANSI); + // Again, not vacuously: the header cursor really does name its module. + let (tree, _) = parse_source_tolerant(NON_ANSI); + let cursor = NON_ANSI.find("(a, b)").expect("the header") as u32; + assert_eq!(port_action_modules_in(&tree, cursor), vec!["old".to_string()]); +} + +#[test] +fn the_parsed_gates_agree_on_an_empty_buffer() { + agree_everywhere(""); + agree_everywhere("\n\n"); +} + +#[test] +fn the_parsed_gates_find_what_the_fixture_was_written_to_offer() { + // A guard on the fixture itself: if `CLEAN` stopped offering anything, + // every assertion above would still pass and prove nothing. + let (tree, diagnostics) = parse_source_tolerant(CLEAN); + let import = CLEAN.find("import a_pkg").expect("the import run") as u32; + assert_eq!( + imported_packages_in(&tree, &diagnostics, CLEAN, import), + vec!["a_pkg".to_string(), "b_pkg".to_string()] + ); + let instance = CLEAN.find("u_sub").expect("the instance") as u32; + assert_eq!(port_action_modules_in(&tree, instance), vec!["sub".to_string()]); + assert!(inline_site_in(&tree, &diagnostics, CLEAN, instance).is_some()); + let assign = CLEAN.find("assign q_o").expect("the assign") as u32; + assert!(extract_site_in(&tree, &diagnostics, CLEAN, assign, assign).is_some()); +} diff --git a/docs/features/perf5-p1/README.md b/docs/features/perf5-p1/README.md new file mode 100644 index 0000000..399073f --- /dev/null +++ b/docs/features/perf5-p1/README.md @@ -0,0 +1,552 @@ +# perf5-p1 — code-action discovery stops repeating work + +## Goal + +A `textDocument/codeAction` arrives on every cursor move. Take 5's §P0 +reference shows what one costs on a 42 192-line generated buffer +(`pinmux_reg_top.sv`, 1 328 188 bytes): **307–313 ms for an answer of zero +actions**, of which ~82 ms is paid before any refactoring family is even +considered and ~55 ms is paid *per* selector family asked for. Five whole-file +tolerant parses happen on that path — one for the fence answer inside +`lint::fixable`, and one inside each of the four text-based engine selectors — +none of which the server needed to do, because the `Document` it is answering +from already holds the parse of exactly that text. + +P1 removes that repetition in two measured steps. **P1a** stops doing work the +request did not ask for: an empty `context.only` answers at once, the lint and +config pass runs only when quick fixes or `source.fixAll.lucisv` are wanted, +and the fence parse happens only when a violation actually carries a fix. +**P1b** stops re-deriving what the document already knows: additive +parsed-input selectors beside the text ones, the four offer paths reading +`doc.tree` / `doc.diagnostics`, and the fence answer memoized per document +revision. No behaviour changes: what a cursor offers, in what order, with what +titles and shapes, is pinned old-against-new. + +## Assumptions + +- A `Document` is rebuilt whole by `Workspace::set_document` on every + `didOpen` / `didChange` / text-carrying `didSave`, and `answer_request` + flushes pending changes *before* any handler runs. So a memo held **on the + `Document`** cannot go stale: there is no path that mutates `text` without + building a new `Document`. (`refresh_overlay` mutates `external` only, which + neither the fence answer nor a selector reads.) +- `doc.tree` is `parse_tolerant(tokenize(doc.text), doc.text)` and + `doc.diagnostics` are that parse's diagnostics — the same pair + `parse_source_tolerant(&doc.text)` returns, which is what the four text + selectors compute for themselves today (`one-parse` README). +- On the **large-file fast path** `doc.tree` / `doc.diagnostics` / + `doc.tokens` are the analysis of the *empty* file, while the four text + selectors parse the buffer's real text and may therefore offer. P1b + preserves that exactly by calling the text wrappers when `doc.large`; it + does not decide whether that behaviour is right. +- `vlog_parser::stats::parses()` counts whole-file parse entry points + (`parse` and `parse_tolerant`), **per thread**. A request is answered on one + thread, so a delta across a request is that request's parse count. It is a + work counter for tests, never a timing. + +## Handshakes + +**Added by `vlog_parser`** (additive; no existing item changed): + +- `pub mod stats` — `parses() -> u64`, a monotone **per-thread** count of + whole-file parses, incremented inside `parser::parse` and + `parser::parse_tolerant`. One non-atomic `Cell` add per parse; it is a work + counter for tests and instrumentation, not a synchronization point. + `parse_source` / `parse_source_tolerant` funnel through those two, so they + are counted once each; a *lex* failure parses nothing and is not counted, and + neither is a macro fragment read (`Parser::read_fragment`), which re-reads a + token slice rather than a file. + +**Added by `vlog_refactor`** (additive; every text entry point kept, now a +thin wrapper that parses and calls the new one): + +- `port_action_modules_in(tree, offset)` +- `imported_packages_in(tree, diagnostics, text, offset)` +- `extract_site_in(tree, diagnostics, text, start, end)` +- `inline_site_in(tree, diagnostics, text, offset)` + +Each makes exactly the decisions its text version makes, including the +"diagnostics non-empty → nothing" refusal (`port_action_modules` has no such +check today and still has none). + +**Consumed by `lucisv_server`**: `server/dispatch.rs` gates lint/config work by +the requested kinds; `ports.rs`, `imports.rs`, `extract.rs`, +`inline_module.rs` call the `_in` selectors with the open document's own parse +unless the document is on the large-file path; the new `fences.rs` answers +`vlog_formatter::fence::protected_regions(&doc.text)` once per document +revision. + +**Not amended: `docs/features/shared-fence-filter/README.md`.** `fence.rs` is +untouched and the fence answer stays text-only — `protected_regions(&doc.text)` +— exactly as that contract requires. What P1b adds is a *memo of that call's +result*, keyed by the `Document` that owns the text, so the answer for one +revision is computed once instead of once per request. + +**Requested of the lead (handshake requests; not applied here).** + +- `docs/topo.md`: record the two additive engine/parser edges above + (`vlog_parser::stats`, the four `_in` selectors) and the server's new + `fences` module. This dev does not edit `topo.md`. + +## Status / TODO + +- [x] P1a — `only: []` returns at once; lint/config gated by kind; fence + parse only when a fix exists; order, prefix semantics, fix-all pinned +- [x] P1a measured; tracker row and experiment entry (`P1a-2026-09-07`) +- [x] P1b — `_in` selectors, the four offer paths on `doc.tree`, fence memo +- [x] P1b measured; tracker row and experiment entry (`P1b-2026-09-07`) +- [x] work counters prove zero additional parses on a repeated offer +- [x] parity pinned at every sampled cursor/range +- [x] extract-refusal attribution paragraph +- [ ] lead ruling on P1c (not this lane's to make) + +## Work log + +### 2026-09-07 — dev (opening) + +Read the plan, the tracker, `tools/perf/README.md` and the four contracts. +Confirmed the code paths the lead described, and two things worth writing +down before touching anything: + +- `port_action_modules` is the one selector that does **not** refuse on parse + diagnostics; the other three do. The `_in` variants must keep that + asymmetry. +- `imported_packages`, `extract_site` and `inline_site` all need the *text* as + well as the tree (`at_the_top`, `Region::read`, `Site::read` all read source + bytes by span), so the `_in` signatures take `text` too. + +### 2026-09-07 — dev, P1a + +Three changes, all in the server: + +- `server/dispatch.rs`, `CodeActionRequest`: after the document lookup, an + `only` that names no kind answers `[]` at once; and the tab width, the + `LintRun` and `code_action::code_actions` are reached only when + `code_action::wants_fixes(only)`. The document lookup stays first on + purpose — a request for a buffer this server does not have answered `null` + before and still does, and a hash-map lookup is not the cost this stage is + about. +- `code_action.rs`: `wants_fixes` — `wanted(QUICKFIX) || wanted(FIX_ALL)`, + the two families the lint pass answers for. `wanted` itself is untouched, so + prefix semantics are the same function they were. +- `lint.rs::fixable`: the fence answer is asked for only when some violation + carries a fix. `fix_touches_fence` is false for a violation with no fix, so + the filter was already the identity in that case; skipping it changes no + answer. + +Counter: `vlog_parser::stats::parses()`. **Deviation from the brief, with a +reason**: the lead asked for a relaxed `AtomicU64`; it is a thread-local +`Cell` instead. A process-wide counter cannot be asserted on, because +`cargo test` runs the binary's tests in parallel and every other test would be +adding to it — and per-thread is the number a caller actually wants, since a +request is answered on one thread. Same public shape (`parses() -> u64`), +cheaper, and testable. + +**P1a measured** (release, binary sha256 `0bf7cf21…`, load 3.0–4.6, corpus +unchanged after every phase, zero guard kills). Against §P0's REF cells, on +repeat medians: + +| Row | REF | P1a | paired | +|---|---:|---:|---:| +| pinmux comment, all families | 309.60 | 258.06 | **16.6%** | +| pinmux comment, `only: []` | 82.80 | 0.064 | **99.9%** | +| pinmux comment, quickfix | 84.13 | 23.53 | **72.0%** | +| offerqueue follower (pipelines 2–3) | 309.40 | 252.44 | **18.4%** | +| `tb.sv` comment (`codeaction`) | 4.29 | 4.02 | 6.3% | +| `aes` lazy | 8.50 | 7.92 | 6.8% | +| `aes_reg_top` lazy | 23.57 | 23.60 | 0.0% | +| `aes_reg_top` ports-only | 22.51 | 21.84 | 3.0% | + +**The attribution the plan asked for falls out of these numbers.** §P0 could +only say that the pinmux cursor paid an ~82.8 ms base plus ~55 ms per selector +family. Now: `only: []` is 0.06 ms, so the base was *all* optional work; +quickfix alone is 23.5 ms, which is the configuration read plus the lint pass; +and 82.8 − 23.5 = **59.3 ms was the fence parse**. It disappeared entirely at +this cursor because **no finding in `pinmux_reg_top.sv` carries a fix**, so +§P1a's "no fix, no fence parse" gate skips it outright — the fence memo of +§P1b cannot improve this row further. A single selector family is now 58.6–59.7 +ms, all of it that family's own whole-file parse, and 23.5 + 4 × 58.7 = 258.3 +against the measured 258.1: the remaining pinmux cost is exactly the four +selector parses plus the lint pass, with nothing unaccounted for. + +### 2026-09-07 — dev, P1b + +- `vlog_refactor`: the four `_in` selectors, each the old body verbatim with + its parse lifted out; the text forms are now two lines. Re-exported from + `lib.rs`. `port_action_modules_in` takes no diagnostics because its text + form never looked at any. +- `lucisv_server/src/fences.rs` (new, 33 lines): `of(doc) -> &[Region]`, a + `OnceLock` on the `Document`. `fence.rs` is untouched and the call is still + `protected_regions(&doc.text)`. +- `state.rs`: one field, `fences: OnceLock>`, and its two + initializers. +- `ports.rs`, `imports.rs`, `extract.rs`, `inline_module.rs`: one private + `…_at(doc, …)` helper each, choosing the `_in` form for an ordinary buffer + and the text form for `doc.large`. All six call sites (including the two + `execute` paths, which the large-file gate does not cover) go through them. +- `lint.rs::fixable` now asks `crate::fences::of(doc)`. + +**P1b measured** (release, binary sha256 `540b8b7e…`, load 3.7–5.0, corpus +unchanged after every phase, zero guard kills). Against §P0's REF cells, on +repeat medians, with P1a in the middle: + +| Row | REF | P1a | P1b | paired vs REF | +|---|---:|---:|---:|---:| +| pinmux comment, all families | 309.60 | 258.06 | **24.02** | **92.2%** | +| pinmux comment, `only: []` | 82.80 | 0.064 | **0.053** | **99.9%** | +| pinmux comment, quickfix | 84.13 | 23.53 | **24.05** | 71.4% | +| offerqueue follower (pipelines 2–3) | 309.40 | 252.44 | **24.61** | **92.0%** | +| `tb.sv` comment (`codeaction`) | 4.46 | 4.02 | **3.65** | 18.3% | +| `tb.sv` comment (`offerkinds`) | 1.54 | 1.20 | **0.60** | 61.4% | +| `aes` lazy | 8.17 | 7.92 | **7.76** | 5.0% | +| `aes_reg_top` lazy | 23.31 | 23.60 | **21.83** | 6.3% | +| `aes_reg_top` ports-only | 22.47 | 21.84 | **21.15** | 5.8% | +| eager fan-out 128 (guardrail) | 496.24 | 498.65 | **493.92** | 0.5% | + +First-after-edit, the new `offeredit` phase (no REF exists): pinmux 368.32 → +**133.86**, `aes_reg_top` 24.84 → **22.66**, `tb.sv` 3.35 → **1.95**; the +paired repeated-offer rows in the same sessions are **24.18 / 21.65 / 0.54**. + +A single selector family at the pinmux cursor went from **58.6–59.7 ms to +0.06–0.14 ms**. Every result count and every recorded title is identical to +the REF's. + +**Targets: two of three missed, and the remaining stage is measured, not +guessed.** + +- *Repeated lazy offers < 5 ms* — met on `tb.sv` (3.65 / 0.60), **missed on + `aes` (7.76)**. +- *`aes_reg_top` < 10 ms* — **missed at 21.83 ms**. The ports family alone is + **21.15 ms** of that row and the other five together are under 0.6 ms: it is + entirely `ports::offers` computing a `port_actions` plan and throwing its + edits away. That is **P1c**, and it is the lead's ruling, not this lane's. +- *pinmux no-offer comment < 16 ms unchanged* — **missed at 24.02 ms**. With + `only: []` at 0.053 ms and quickfix-only at 24.05 ms, **100% of the residue + is the configuration read plus the lint pass**. + +**Lint-result reuse: considered, not done.** The brief's condition is met — +lint is the whole of the pinmux row for a client that wants quick fixes, which +is every VS Code client, since it sends no `only`. It was not done because its +key is a different shape from anything else in this lane: the document +revision (free — it lives on the `Document`), the tab width, the effective +rule set, the merged rule options, the line width, the **contents** of every +external waiver file, and the workspace index generation — and that last is not +reachable from `fixable`'s signature at all, because `generation` lives on +`Server` and not on `Workspace`. Wiring it means threading a generation through +the code-action path and hashing four independent configuration surfaces, and +its failure mode is a **stale fix offer**. That is its own item with its own +attack tests, one per key component, in the shape §59 gave the format-cache +key — not a tail on this one. The number to decide with is **24.0 ms**, and +note that the *first* request after every keystroke pays it whatever the memo +does (the pinmux first-after-edit row is 133.86 ms, of which ~110 is +`Document::new` on 1.3 MB). It may also be cheaper to ask *which rules* cost +24 ms on a 42 192-line generated buffer than to cache their answer. + +### 2026-09-07 — dev, attribution: the ~800 ms extract refusal + +§P0 recorded that `lucisv.extractModule` at `aes_wrap.sv` 66:2 spends +**793–817 ms** to produce a refusal. Reading `extract.rs::execute` and the +engine: the gate is not the cost — `extract_site` is one parse of one buffer +and is now ~0.1 ms. The cost is the two lines after it. `site.units` is the +enclosing module plus every module the selection instantiates plus **every +package the module imports**, and `Workspace::module_sources(&path, &units)` +returns, for each unit, every file declaring it *and every file the index says +references it*. At that cursor the units include `aes_pkg`, `aes_reg_pkg` and +`tlul_pkg`; over this corpus those names appear in **102, 19 and 292 files**. +`vlog_refactor::extract_module` then hands that set to `Scope::build`, which is +`WorkspaceIndex::build` over every one of those texts — a lex, a parse and an +analysis each — before the extraction looks at the selection and refuses. So +the ~800 ms is **input selection plus a whole-scope index build over a few +hundred files**, and essentially none of it is extraction. + +That makes it **P2 territory, not P1**: it is the same `Scope::build` / +`Scope::analysis` duplication §P2b names, reached through a different door, and +the over-selection is `module_sources`' rung "every file that references this +unit" applied to a *package* — where "references" means most of the tree. +Two things a lead may want to note when scoping P2: a package is not a module, +and the transitive-reference rung that is right for a module name is what makes +this row 800 ms; and the refusal is decided from the selection alone, so no +files needed to be read to produce it. This lane changed nothing here and +measured nothing new here — the numbers above are §P0's, and the file counts +are read-only `grep -rl` over the corpus. + +### 2026-09-07 — dev, deviations and files touched outside the brief's list + +Four, all small, all stated rather than absorbed: + +1. **The parse counter is thread-local, not an `AtomicU64`** (reason above, + in the P1a entry). Same public shape. +2. **Two new test files sit outside the brief's ownership list**, because a + change needs its tests and neither crate had a home for them: + `crates/lucisv_server/src/server/tests/code_action.rs` (new, plus one + `mod code_action;` line in that directory's `mod.rs`) and + `crates/vlog_refactor/tests/parsed_selectors.rs` (new). Nothing existing in + either place was edited. +3. **The empty-`only` return happens after the document lookup, not before + it.** Returning first would turn `null` (this server does not have that + buffer) into `[]` — a wire change, for a hash-map lookup's worth of time. +4. **`tools/perf/phases_p1.py` is a new file** rather than a row added to an + existing phase, with one import line in `bench.py` and two rows in + `tools/perf/README.md`. `phases_p0.py` belongs to §P0's record. + +Nothing under `docs/topo.md`, `README.md`, `vlog_formatter/src/fence.rs` or +`docs/perf/take5-baseline/` was touched, and no REF or baseline cell in the +tracker was overwritten — P1's numbers are appended behind the REF they are +measured against. + +## QA log + +### 2026-09-07 — QA + +Read `CLAUDE.md`, TODO §60.1, `docs/performance_take5.md` §P1, this README +(work log included), `docs/perf/take5-tracking.md`'s P1a/P1b rows and +experiment entries, the full diff plus the new files, the unamended +`docs/features/shared-fence-filter/README.md`, `tools/perf/README.md`, and +the raw evidence under `~/.cache/lucisv-perf/take5-p1/`, before touching +anything. Experiments that run code happened only in a scratch clone +(`git clone` + `git apply` of the working-tree diff plus the six new +untracked files, verified identical to the main tree by `diff -rq`); the +main tree was never checked out, reset, or stashed. `opentitan` stayed +read-only throughout: `git -C ~/repo/opentitan status --porcelain` showed +exactly the three pre-existing modified files +(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`, +`hw/top_earlgrey/ip/ast/rtl/ast.sv`) before, during and after every phase. + +**Gates (main tree).** `cargo fmt --all -- --check`: clean. Guarded +`cargo clippy --all-targets` (`tools/guard.sh -m 8 -t 1800`): a fresh +incremental build had already compiled this exact diff (newer than every +changed source file), so the 0.12s "Finished" with no warnings is a real +clean result, not a stale cache hit going unexercised; `git diff | grep +'#\[allow'` and a scan of the crate diff for `unwrap()`/`expect(`/`panic!`/ +`unsafe` outside `#[cfg(test)]` both came back empty — no new `#[allow]`, no +new forbidden construct in library code. Guarded `cargo test --workspace`: +**56 test binaries, 4194 passed, 0 failed** (first captured run was +truncated by my own `tail -150`; re-ran with full capture to confirm the +count — same zero-failure result both times). Guarded +`cargo test -p vlog_formatter`: **226 passed, 0 failed** — expected, since +`fence.rs` is untouched. No cargo command overlapped a timed phase; `ps` +was checked for `cargo`/`rustc` before every guarded run and every perf +phase. Load stayed in the 3–6 range throughout, recorded before/after each +guarded run. + +**Size rule.** Production lines (non-blank, non-comment, before `mod +tests`, the file-size rule's own convention) of every changed/new file: +`fences.rs` 5 (new module — deliberately tiny), `code_action.rs` 99, +`lint.rs` 251, `ports.rs` 293, `imports.rs` 144, `extract.rs` 135, +`inline_module.rs` 74, `server/dispatch.rs` 442 (601→622 raw lines, but the +non-comment count the rule is actually measured by went 430→442 — nowhere +near 600), `stats.rs` 10, `parser/mod.rs` +2 lines, `vlog_refactor`'s four +engine files 261–393, `lib.rs` 96. **`state.rs` is 961 — already over 600**, +exactly the file CLAUDE.md's own 2026-09-07 re-measurement and TODO's file +list both name as over size with §55 filed; this lane's addition to it is +the 8 lines the plan explicitly permitted ("put new responsibilities in a +new module") — one `OnceLock` field and its two initializers, with the +actual logic in the new 33-line `fences.rs`. Nothing over 600 that was not +already over 600, and the one exception is the plan's own named exception. + +**Contract (§2).** `git diff --stat crates/vlog_formatter/src/fence.rs`: +empty. `fences::of` reads `doc.fences.get_or_init(|| fence::protected_ +regions(&doc.text))` — text authority, memo only, exactly as claimed. +`docs/features/shared-fence-filter/README.md`: not amended (re-read in +full; nothing there changed). `docs/topo.md` and `README.md`: empty diff — +confirmed by `git diff --stat`. Handshake requests the lead must still +apply, read from this README's own Handshakes section: record the +`vlog_parser::stats` edge, the four `vlog_refactor` `*_in` selector edges, +and the server's new `fences` module, in `docs/topo.md`. + +**Invariant 4 (§3).** No change under `crates/vlog_refactor/src/check/` or +any `verify.rs` (`vlog_formatter/src/verify.rs` included) — confirmed by +`git diff --stat` against both, empty. Does not apply to this lane. + +**§4 parity attacks, real server against real server.** Built the baseline +at tag `v0.50.0` in a second clone (`git clone --no-checkout` + +`checkout v0.50.0`, resolving to commit `3bd55ac`) and confirmed +`git diff 3bd55ac..bbdbfe9 --stat` is TODO.md only — the checked-out tag is +source-identical to the `bbdbfe9` commit the tracker's baseline metadata +names, so it is the right reference despite the metadata citing a different +commit hash. Guarded `cargo build --release -p lucisv_server` there +(1m06s). The rebuilt binary's sha256 does **not** match the recorded +`27e0a0df…` — expected non-reproducibility from a different absolute build +path (Rust embeds it in panic/debug strings), not a code difference; the +diff-stat check above is the real proof the source matches. The candidate +binary needed no rebuild: `target/release/lucisv-server`'s sha256 is +`540b8b7e…`, an exact match for P1b's own recorded hash, confirmed again +immediately before and after every phase below. + +- **(a)** `only: []` at the pinmux comment: `[]`, `result_count: 0`. + Reused verbatim from `server::tests::code_action`, which asserts by count + — a *repeated* `only: []` request performs **0** parses — rather than + timing; independently confirmed true (see the counter sabotage below). +- **(b)** Drove the real candidate server directly (own harness script, + `tools/perf/lspclient.Session`, not `bench.py`) at `aes_wrap.sv` 78:2 with + `only: ["refactor"]`: offers `refactor.rewrite.lucisv.ports` ("connect 2 + missing ports") and `refactor.extract`, no `quickfix`/`source.fixAll` — + lint never ran. At `aes_wrap.sv` 66:2 with the same filter: offers + `refactor.extract` and `refactor.inline`. `only: + ["refactor.rewrite.lucisv.ports"]` at the pinmux and tb comment cursors + offers nothing (prefix semantics hold: the exact kind, not just its + family, still selects). `only: ["source"]` at `aes_sbox_canright_ + masked.sv` 42:2 offers `source.organizeImports` ("organize imports + (removes 1, sorts 1)") plus `refactor.extract` (a different family, + correctly still present) — fix-all's own family, `source.fixAll.lucisv`, + is confirmed offered by the passing `the_kind_filter_is_a_prefix…` unit + test at a fixable cursor. +- **(c)** `only: ["quickfix"]` at a fixable cursor: reused + `a_quickfix_only_request_never_runs_the_selectors`, which asserts exactly + one parse (the fence answer alone) and the one quick-fix title, no + selector. Passing. +- **(d)** `a_pass_whose_findings_carry_no_fix_never_asks_about_fences`: + `UNFIXABLE` (a `module-filename` finding, no fix) → `[]`, **0** parses. + Passing, asserted by count. +- **(e)** Fence + memo freshness: read and reused + `a_fence_typed_into_the_buffer_is_seen_by_the_next_request` — a `no-tabs` + quick fix is offered; a `didChange` fences the line and the fix is + withheld (`[]`); a second `didChange` removes the fence and the fix is + offered again. This is the live proof the memo is bound to the + `Document`'s own revision, not stale across an edit. Passing. +- **(f)** Action-list parity, real baseline server vs. real candidate + server, byte-for-byte (titles, kinds, order, edit/command/data shape) — + scratch script `parity_check.py`, both binaries driven independently over + real LSP JSON-RPC, workspace-scope index, warm scan: **all 7 required + cursors** (`aes_wrap.sv` 78:2 and 66:2, `aes.sv` 220:0–222:53, + `sha3_fpv.sv` 54:4, `aes_sbox_canright_masked.sv` 42:2, `tb.sv` 44:2, + `pinmux_reg_top.sv`'s opening comment) **plus 10 additional cursors** + (comments in `hmac.sv`/`aes_bind.sv`; declarations in `kmac.sv` ×2, + `entropy_src_main_sm.sv`, `spi_device.sv` ×2; instantiations in + `aon_timer.sv` ×3) — **0 mismatches out of 17**. Full output kept in + `parity_check.py`'s run log. + +**Counter sabotage (§6).** In the scratch clone only: reverted `ports.rs`'s +`modules_at` to always take the text path +(`vlog_refactor::port_action_modules(&doc.text, offset)`) regardless of +`doc.large`, reintroducing the whole-file parse §P1b removed for the ports +family. `cargo test -p lucisv_server code_action::` under the sabotage: +**3 failures** — +`a_repeated_offer_where_nothing_is_offered_parses_nothing_at_all` ("the +first request pays for the fence answer at most: 2"), +`the_first_offer_after_a_change_parses_the_buffer_once_and_no_more` ("the +document's own parse, plus at most the fence answer: 3"), and +`the_port_offer_still_reaches_the_engine_and_that_is_what_p1c_is_for` +("at a cursor the gate refuses, nothing is parsed" — 1 vs 0). Reverted by +hand; the counter suite is genuinely load-bearing, not merely present. + +**Parity suite read (§5).** `crates/vlog_refactor/tests/parsed_selectors.rs` +does exactly what it claims: `agree_everywhere` iterates **every byte +offset 0..=len**, comparing all four `_in`/text pairs, over `CLEAN`, +`BROKEN`, both under CRLF, `ASTRAL` (a non-BMP character before every +cursor), `NON_ANSI`, and the empty buffer/`"\n\n"` — 7 test functions, the +"five fixtures" the READMEs describe plus the two degenerate ones. Added +one adversarial fixture the dev did not have — a macro-wrapped header, a +`bind ... .*`, an interface with a modport, and a package with an import +run followed by a class — and ran `agree_everywhere` over it (in the +scratch clone, `cargo test -p vlog_refactor`): **passes**, every offset, +both plain and CRLF. **Large-file mode**, real 4 MiB default threshold (the +dev's own test uses an artificial 100-byte threshold): wrote a new test, +`qa_a_genuinely_over_4mib_buffer_takes_the_text_path_and_really_parses`, in +the scratch clone only — a >4 MiB buffer via `Session::wide` (which uses +`ClientSettings::default()`, the real threshold), `workspace/executeCommand` +for inline at the real instantiation. Result: the command is **not** +refused ("no instantiation" — the text path finds it), and +`vlog_parser::stats::parses()` **increases** across the request — the large +buffer really does re-parse its text on this path, exactly the documented +"today's behaviour," not a silently reused empty tree. Passing. + +**Re-measurement on the candidate binary (§7).** No rebuild needed — sha256 +`540b8b7e…` verified before and after. Ran `offerkinds`, `offerqueue`, +`codeaction`, `offeredit` guarded, sequentially, no cargo overlapping. +Corpus unchanged after each. Every row's `result_count`/`status` is +identical to the dev's P1b record (spot-checked in full above). Medians +against the dev's own P1b numbers: + +| Cell | Dev P1b | QA re-measure | Diff | +|---|---:|---:|---:| +| pinmux all-family | 24.02 | 24.13 | 0.5% | +| pinmux `[]` | 0.053 | 0.052 | 2% | +| pinmux quickfix | 24.05 | 23.27 | 3.2% | +| aes-reg-instance all-family | 21.79 | 22.09 | 1.4% | +| aes-reg-instance ports-only | 21.15 | 21.53 | 1.8% | +| offerqueue follower (mean 2–3) | 24.61 | 24.51 | 0.4% | +| aes_reg_top lazy (`codeaction`) | 21.83 | 22.18 | 1.6% | +| eager fan-out 128 (guardrail) | 493.92 | 496.01 | 0.4% | +| offeredit pinmux first-after-edit | 133.86 | 135.54 | 1.3% | +| offeredit aes-reg first-after-edit | 22.66 | 22.60 | 0.3% | +| offeredit aes-reg repeated | 21.65 | 21.59 | 0.3% | + +All within ±10% except three genuinely sub-5ms rows (`tb.sv` comment: 0.60 +vs 0.22 on `offerkinds`, 3.65 vs 3.08 on `codeaction`, 1.95 vs 1.68 on +`offeredit`'s first-after-edit) — noise on a ~1–4 ms measurement, consistent +with this same document's own ±20% tolerance band for 1–20 ms rows +(`take5-tracking.md`'s P0 entry) rather than a regression; nothing about +this diff touches `tb.sv`'s cost differently than any other small file. + +**Traceability (§8).** Sampled far more than 15 numbers from the P1a/P1b +tracker rows and the two experiment entries and found every one exactly in +`~/.cache/lucisv-perf/take5-p1/results-p1{a,b}.jsonl` by recomputing the +stated median from the raw `ms` arrays: pinmux all-family/`[]`/quickfix and +all four selector families (P1a and P1b), `tb`/`aes-core`/`spi` selector +medians, the ports-only 21.15/22.47 row (found under +`aes-reg-instance ['refactor.rewrite.lucisv.ports']`, `result_count: 0` — +the engine computes a plan and finds nothing to offer at this exact cursor, +which is consistent with, not contradictory to, the same cursor's 2-action +all-family answer coming entirely from the extract+inline families), +`offerqueue`'s follower mean, and all six `offeredit` rows including the +first-vs-repeat convention (median of the *last two* tries, excluding the +distinguished first). No number failed to reproduce. + +**Attribution arithmetic (§9).** `23.5 + 4 × 58.7 = 258.3` against measured +`258.06`/`258.1`: recomputed the four selector medians individually from +the raw P1a rows (58.57, 58.97, 59.50, 59.70 — the stated "58.6–59.7 ms" +range is exact) rather than the rounded 58.7 the prose uses. Their sum plus +the quickfix median is `260.27`, about 0.85% over the measured 258.06 — +the prose's arithmetic uses a single representative selector time and is +explicitly framed with "≈"/an em-dash range, not claimed as exact; the +~2ms gap is rounding, not an unaccounted-for cost. Not a finding. + +**Verdict: PASS.** No corruption risk (invariant 4 does not apply — no +verifier change), idempotency/comment-preservation untouched (`fence.rs` +and the formatter are untouched), every claim in the work log and tracker +checked against source, live behavior, or raw evidence and confirmed +accurate. The counter suite is genuinely load-bearing (sabotage caught it +in 3 places), the parity suite is genuinely exhaustive (byte-offset +coverage confirmed by reading, extended with one adversarial fixture that +still passed), and the real baseline-vs-candidate server comparison at 17 +cursors found zero behavioral differences. Two items are correctly left as +open lead rulings (P1c, lint-result reuse) and are not QA blockers. Ticking +the §60.1 QA line in TODO.md. + +## Review + +**2026-09-07 (lead).** Accepted. Read the diff (dispatch gate, +`wants_fixes`, the fix-only fence question, `fences.rs`, the four `_in` +selectors and their wrappers, `stats.rs`, the two test files), the +tracker's P1a/P1b entries and both logs; QA's parity run against a +real 0.50.0 server (17 cursors, 0 mismatches) is the acceptance. + +- This is the round's number: the no-offer comment on the 42 192-line + file falls from 310 ms to 24 ms, and the definition queued behind it + with it. P1a's ablation is the part worth keeping in mind — the + 80 ms base was 59 ms of fence parse (asked even when no finding had + a fix) and 24 ms of config read plus lint. +- The shape is right: additive `_in` selectors with the text forms as + wrappers, a 33-line memo module that asks the fence contract the same + text question once per `Document`, the parse counter as the proof. + Nothing widened, nothing amended. +- **Ruling, P1c: go.** After P1b the `aes_reg_top` offer is 21.8 ms of + which the ports family's discarded plan is 21.2; the plan's condition + ("only if the ports/import offers still dominate") is met with a + number. Its own lane, next. +- **Ruling, lint-result reuse: deferred** to the loop-3 list with its + number (24 ms on the largest file in opentitan; 1–3 ms on ordinary + RTL). The key spans six surfaces (revision, tab width, rule set, + merged options, waiver contents, index generation), the failure mode + is a stale *fix offer*, and the first request after every keystroke + pays the pass regardless. Not worth a §59-shaped attack suite tonight. +- Deviations accepted: the thread-local counter (the right number for a + request); the two new test files; the empty-`only` return after the + document lookup; the large-file path keeping today's text behaviour. +- The extract-refusal attribution (`module_sources` of a *package* name + = most of the tree, then a whole-scope index build) goes to P2's + brief; it is the same duplication §P2b names. + +Docs applied at merge: topo edges for `vlog_parser::stats`, the four +`_in` selectors and `fences.rs`; TODO §60.1 P1c and lint-memo rulings. diff --git a/docs/perf/take5-tracking.md b/docs/perf/take5-tracking.md index b8af5f5..97d5d27 100644 --- a/docs/perf/take5-tracking.md +++ b/docs/perf/take5-tracking.md @@ -1,6 +1,6 @@ # Performance implementation tracker — take 5 -**Status: baseline measured; implementation has not started.** The implementation agent owns the blank candidate columns and experiment entries below. Read [the causes and detailed plan](../performance_take5.md) before selecting work. Baseline provenance and raw rows are in [take5-baseline](take5-baseline/README.md). +**Status: baseline measured; P0 done; P1a and P1b implemented and measured (2026-09-07, QA pending).** The implementation agent owns the blank candidate columns and experiment entries below. Read [the causes and detailed plan](../performance_take5.md) before selecting work. Baseline provenance and raw rows are in [take5-baseline](take5-baseline/README.md). Do not overwrite the baseline, silently replace a workload, omit refusals, or report a proposed target as an achieved result. Use `not measured`, `blocked`, or `not applicable` rather than zero. Update this file after each measured stage, including rejected changes. @@ -32,9 +32,9 @@ The order follows the plan. Later stages are conditional on the preceding measur | Stage | Work | Depends on | Owner / commit | Status | Evidence and decision | |---|---|---|---|---|---| | P0 | Harness status/units/command execution/cold-cache corrections | — | dev (Opus) → QA PASS → lead; committed 2026-09-07 | Done | `docs/features/perf5-p0/README.md`; experiment `P0-2026-09-07` below. Schema 2 shipped; `execute` phase measures the extract/inline commands for the first time; cold sweep tries verified at 0 hits, warm at 30; baseline reproduced on the unchanged binary | -| P1a | Gate lint/fence/config by requested kinds; avoid fence work without fixes | P0 | — | Not started | — | -| P1b | Shared parsed selectors; revision-bound fence reuse; invalidate any additional cache correctly | P1a | — | Not started | — | -| P1c | Engine-owned lightweight ports/import offers | Reprofile P1b | — | Not started | — | +| P1a | Gate lint/fence/config by requested kinds; avoid fence work without fixes | P0 | dev (Opus) → QA PASS → lead; committed 2026-09-07 | Done | `docs/features/perf5-p1/README.md`; experiment `P1a-2026-09-07` below. Pinmux `only: []` 82.80 → **0.064 ms**; quickfix 84.13 → **23.53**; all families 309.60 → **258.06**. Separates the base at last: lint+config **23.5 ms**, fence parse **59.3 ms** | +| P1b | Shared parsed selectors; revision-bound fence reuse; invalidate any additional cache correctly | P1a | dev (Opus) → QA PASS → lead; committed 2026-09-07 | Done | Same README; experiment `P1b-2026-09-07`. Pinmux all families **24.02 ms** (−92.2% on REF), queued definition **24.61** (−92.0%). Lint-result reuse **not done** — reason and number in the experiment entry | +| P1c | Engine-owned lightweight ports/import offers | Reprofile P1b | — | **Ruled go (lead, 2026-09-07); next lane** | After P1b the `aes_reg_top` offer is 21.83 ms of which the ports family alone is **21.15**; `aes` 7.76. The four gates now cost ~0.06–0.14 ms each. Every remaining millisecond at an *offering* cursor is the engine plan the offer discards | | P2a | Rename per-stage timings and selected/watched/input counts | P0 | — | Not started | — | | P2b | Reuse per-file input analysis in request-local scope | P2a | — | Not started | — | | P2c | Reuse unchanged after-facts/semantics; re-resolve external references | P2b | — | Not started | — | @@ -54,22 +54,32 @@ binary re-measured with the corrected harness*. Those cells are marked change" is the reference-against-baseline agreement check, never an improvement claim. Baseline cells are untouched. +**P1 note.** P1's numbers are *appended* to the Candidate cell behind the +REF value they are measured against; **no REF or baseline text is replaced**. +Both stages were taken with the committed harness on their own release +binaries — P1a `0bf7cf21…`, P1b `540b8b7e…` — three tries per row, lazy +client, warm workspace scope, scratch index caches, load 3.0–5.6 recorded +before and after every phase, corpus verified unchanged after every phase, +zero guard kills. Paired change is `100 × (REF − candidate) / REF` on repeat +medians. Raw rows: `~/.cache/lucisv-perf/take5-p1/results-p1{a,b}.jsonl`. + | Metric / baseline source | Baseline | Proposed goal or guardrail | Candidate | Paired change | Verdict | |---|---:|---|---|---|---| -| Pinmux comment, lazy all families (`offer-breakdown`) | 328.41 / 296.78–311.73 ms; 0 actions | Repeated <16 ms; first-after-edit separate | **REF (P0, same binary, `offerkinds`)** 333.89 / 307.35–312.97 ms; 0 actions | +4.1% on repeat medians | Agrees within tolerance; reference for P1 | -| Pinmux comment, `only: []` | 78.88 / 79.43–81.62 ms; 0 actions | Return near transport floor; no lint/parse | **REF** 81.72 / 82.27–84.11 ms; 0 actions | +1.7% | Agrees; reference for P1a | -| Pinmux comment, quickfix only | 79.54 / 79.73–80.06 ms; 0 actions | Avoid repeated lint/fence work safely | **REF** 82.76 / 82.50–85.06 ms; 0 actions | +5.5% | Agrees; reference for P1a | -| Pinmux comment → queued definition (`offer-queue`) | 300.66–304.11 ms follower, 3 pipelines | Repeated follower <16 ms if no other blocker | **REF (`offerqueue`)** follower 339.47 / 309.07 / 309.72 ms; leader 339.53 / 309.08 / 309.73; 3 pipelines, now in `leader_ms`/`follower_ms` | +2.0% on pipelines 2–3 | Agrees; leader and follower no longer share one `ms` array | -| `tb.sv` comment, lazy (`codeaction`) | 6.15 / 3.22–3.50 ms; 0 actions | Repeated <5 ms; no added parse | **REF** 5.53 / 3.80–4.79 ms; 0 actions | **+27.9%** — outside tolerance, see experiment entry | Disagrees; a ~4 ms row, neither number adjusted | -| `aes` lazy offer (`codeaction`) | 12.39 / 8.15–9.11 ms; 1 action | Repeated <5 ms | **REF** 13.87 / 7.33–9.66 ms; 1 action | −8.0% | Agrees (1–20 ms band) | -| `aes_reg_top` lazy offer (`codeaction`) | 32.81 / 22.45–25.09 ms; 2 actions | Repeated <10 ms | **REF** 30.64 / 22.72–24.42 ms; 2 actions | +1.0% | Agrees; reference for P1 | -| `aes_reg_top` ports-only offer (`offer-breakdown`) | 21.72 / 21.55–21.78 ms; 0 port actions | Remove throwaway edit computation | **REF (`offerkinds`)** 22.27 / 22.46–22.56 ms; 0 port actions | +3.3% | Agrees; reference for P1c | +| Pinmux comment, lazy all families (`offer-breakdown`) | 328.41 / 296.78–311.73 ms; 0 actions | Repeated <16 ms; first-after-edit separate | **REF (P0, same binary, `offerkinds`)** 333.89 / 307.35–312.97 ms; 0 actions — REF repeat median **309.60**. **P1a** 289.33 / 251.87–258.91, median 258.06. **P1b** 50.07 / 23.79–24.43, median **24.02**; 0 actions in every try | REF vs baseline +4.1%. **P1a −16.6%, P1b −92.2%** on repeat medians | REF agrees. P1b is a 12.9× reduction with an identical (empty) answer. **Target <16 ms missed**: the remaining 24.0 ms is the lint pass — quickfix-only is 24.05 and `only: []` is 0.053 | +| Pinmux comment, `only: []` | 78.88 / 79.43–81.62 ms; 0 actions | Return near transport floor; no lint/parse | **REF** 81.72 / 82.27–84.11 ms; 0 actions — REF median **82.80**. **P1a** 0.13 / 0.053–0.070, median 0.064. **P1b** 0.12 / 0.049–0.054, median **0.053** | REF vs baseline +1.7%. **P1a −99.9%, P1b −99.9%** | Goal met: an empty filter answers at the transport floor (that row is itself 0.061–0.102 ms), with no config read, no lint and no parse — asserted by parse count in `an_empty_only_filter_answers_empty_and_does_no_work_at_all` | +| Pinmux comment, quickfix only | 79.54 / 79.73–80.06 ms; 0 actions | Avoid repeated lint/fence work safely | **REF** 82.76 / 82.50–85.06 ms; 0 actions — REF median **84.13**. **P1a** 24.03 / 23.47–23.85, median 23.53. **P1b** 23.57 / 23.92–24.25, median **24.05** | REF vs baseline +5.5%. **P1a −72.0%, P1b −71.4%** | The 60 ms P1a removed here is the fence parse, skipped because **no finding in this buffer carries a fix**. P1b cannot improve it further: what is left is the configuration read plus the lint pass, and no lint-result reuse was added (see `P1b-2026-09-07`) | +| Pinmux comment → queued definition (`offer-queue`) | 300.66–304.11 ms follower, 3 pipelines | Repeated follower <16 ms if no other blocker | **REF (`offerqueue`)** follower 339.47 / 309.07 / 309.72 ms; leader 339.53 / 309.08 / 309.73; 3 pipelines, now in `leader_ms`/`follower_ms` — REF follower mean of pipelines 2–3 **309.40**. **P1a** follower 275.77 / 253.20 / 251.68 (mean 2–3 = 252.44). **P1b** follower 43.62 / 25.57 / 23.65 (mean 2–3 = **24.61**) | REF vs baseline +2.0%. **P1a −18.4%, P1b −92.0%** | The queued definition falls with its blocker, as the plan predicted. **Target <16 ms missed** by the same 24 ms of lint the leader pays | +| `tb.sv` comment, lazy (`codeaction`) | 6.15 / 3.22–3.50 ms; 0 actions | Repeated <5 ms; no added parse | **REF** 5.53 / 3.80–4.79 ms; 0 actions — REF median **4.46**. **P1a** 5.99 / 3.89–4.76, median 4.02. **P1b** 5.49 / 3.48–4.29, median **3.65** | REF vs baseline **+27.9%** (outside tolerance, see the P0 entry). **P1a −9.9%, P1b −18.3%** | Target <5 ms **met**. The same file's `offerkinds` cursor, the cleaner row, went 1.54 → **0.60 ms** (−61.4%) | +| `aes` lazy offer (`codeaction`) | 12.39 / 8.15–9.11 ms; 1 action | Repeated <5 ms | **REF** 13.87 / 7.33–9.66 ms; 1 action — REF median **8.17**. **P1a** 14.30 / 7.21–9.60, median 7.92. **P1b** 11.41 / 7.11–9.70, median **7.76**; 1 action in every try | REF vs baseline −8.0%. **P1a −3.1%, P1b −5.0%** | **Target <5 ms missed.** The gate is now ~0.1 ms; what is left is the ports offer computing a plan whose edits it discards — **P1c** | +| `aes_reg_top` lazy offer (`codeaction`) | 32.81 / 22.45–25.09 ms; 2 actions | Repeated <10 ms | **REF** 30.64 / 22.72–24.42 ms; 2 actions — REF median **23.31**. **P1a** 32.24 / 22.08–24.17, median 23.60. **P1b** 31.50 / 20.93–24.42, median **21.83**; 2 actions in every try | REF vs baseline +1.0%. **P1a +1.3% (no change), P1b −6.3%** | **Target <10 ms missed.** Measured residue: the ports family alone is **21.15 ms** of the 21.83, and the other five families together under 0.6 ms — the whole row is the discarded ports plan, **P1c** | +| `aes_reg_top` ports-only offer (`offer-breakdown`) | 21.72 / 21.55–21.78 ms; 0 port actions | Remove throwaway edit computation | **REF (`offerkinds`)** 22.27 / 22.46–22.56 ms; 0 port actions — REF median **22.47**. **P1a** 21.68 / 21.28–21.89, median 21.84. **P1b** 20.86 / 21.14–21.48, median **21.15**; 0 port actions | REF vs baseline +3.3%. **P1a −2.8%, P1b −5.8%** | Barely moved, as expected: §P1b removed this family's *gate* parse, not the engine plan behind it. This is the row **P1c** exists for | | `state_q` tail rename (`tailrename`) | 821.59 / 789.50–809.83 ms; 2 files | At least 2× faster; stretch <200 ms | **REF** 813.44 / 778.77–782.13 ms; **5 edits / 2 files / 0 created**, fingerprint `b39defb21265…` | −1.4% | Agrees; reference for P2, now with an edit fingerprint to compare against | | Ordinary `aes` rename (`rename`) | 168.67 / 139.34–140.35 ms; 9 files | No regression; exact edit/warning parity | **REF** 167.60 / 140.46–142.13 ms; **14 edits / 9 files / 0 created**, fingerprint `fa7e31c78382…` | +1.2% | Agrees; reference for P2 | | Definition behind ordinary rename (`blockers`) | 145.99–168.79 ms, 3 pipelines | Falls with rename work | **REF** 163.43 / 161.55 / 161.11 ms, 3 pipelines (now `follower_ms.definition`) | inside the baseline range | Agrees | | Connect missing ports resolve (`refactor`) | 170.77 / 164.79–165.82 ms; 1 file | Measure collateral benefit; exact edit parity | **REF** 171.37 / 165.77–167.45 ms; 1 file | +0.4% | Agrees | | Expand wildcard resolve (`refactor`) | 73.02 / 70.35–70.73 ms; 1 file, 32 connections | No lost connections/refusals | **REF** 73.61 / 71.67–73.01 ms; 1 file, 32 connections | +2.2% | Agrees | -| Eager 128-fan-out offer (`codeaction`) | 518.32 / 495.60–499.69 ms | Compatibility/perf guardrail; not first priority | **REF** 523.16 / 495.13–496.77 ms; 2 actions | +0.1% | Agrees | +| Eager 128-fan-out offer (`codeaction`) | 518.32 / 495.60–499.69 ms | Compatibility/perf guardrail; not first priority | **REF** 523.16 / 495.13–496.77 ms; 2 actions — REF median **496.24**. **P1b** 519.49 / 492.71–494.57, median **493.92**; 2 actions | REF vs baseline +0.1%. **P1b −0.5%** | Unchanged, which is the guardrail: the eager path's cost is the module's fan-out and P1 did not touch it | +| First offer after a `didChange`, same cursor (`offeredit`, **new**) | not measured — the gap the P0 entry named | Track separately from the repeated offer | **P1a** pinmux 383.61 / 366.93–369.71 (median 368.32); `aes_reg_top` instance 35.82 / 23.38–26.30 (24.84); `tb.sv` comment 4.80 / 3.28–3.42 (3.35). **P1b** pinmux 152.88 / 132.68–135.04 (median **133.86**); `aes_reg_top` 28.82 / 22.58–22.75 (**22.66**); `tb.sv` 2.29 / 1.90–2.00 (**1.95**) | P1a → P1b: pinmux **−63.7%**, `aes_reg_top` −8.8%, `tb.sv` −41.8% | New row, new phase `offeredit`. Each try is the *first* `codeAction` after its own `didChange`, so the document rebuild is inside the number; the paired "repeated offer on the unchanged buffer" rows sit beside them in the same session (P1b: pinmux **24.18**, `aes_reg_top` **21.65**, `tb.sv` **0.54**). No REF exists — P0 could not measure it | | Extract command actually executed (`execute`, **new**) | not measured — take 4's `extract-module resolve` rows are invalid | Measure the command, not a refusal | **REF** `lucisv.extractModule` at `aes.sv` 220:0–222:53: **257.33 / 245.05–247.00 ms** executeCommand→applyEdit; 2 edits / 2 files / **1 created**; `deliver_ms` 0.015–0.033; status `capture`; fingerprint `090e92e7736e…` | new row | The gap the tracker's work-count table named is closed | | Inline command actually executed (`execute`, **new**) | not measured | Measure the command, not a refusal | `lucisv.inlineModule` at `aes_wrap.sv` 66:2 is **refused** (`generate` construct); 6.58 / 5.87–6.20 ms. Not a timing of an inline | new row | Refusal recorded as `refused`; **not quotable** as an inline cost | | Extract offered at the inline cursor, refused (`execute`, **new**) | not measured | — | `lucisv.extractModule` at `aes_wrap.sv` 66:2 refused after **817.37 / 793.77–809.07 ms** | new row | A second ~800 ms user-command path; filed as a finding, not fixed | @@ -96,9 +106,9 @@ improvement claim. Baseline cells are untouched. | Measurement | Baseline knowledge | Reference — agent fills | Candidate — agent fills | |---|---|---|---| -| Additional parses per no-offer all-family action | 5 text-parse entry points confirmed in source; no runtime counter | Still no runtime counter — P0 is harness-only and adds no production instrumentation. The wire-side attribution is reproduced (`offerkinds`): 82.80 ms shared base at the pinmux cursor, +52.7 to +57.6 ms for any one selector family | — | -| Lint/config/fence time separately | About 80 ms combined on generated file; unseparated | Reproduced but still unseparated: pinmux `only: []` 82.80 ms, quickfix 84.13 ms. Separating them needs P1's counters | — | -| Selector time by family and file size | Filtered ablations preserved in raw data | **Promoted to the committed `offerkinds` phase**: 7 families × 5 cursors × 4 requests, result counts in every row. All-family repeat medians by cursor — tb 1.54 / aes-reg-instance 23.51 / aes-core 10.42 / spi 14.43 / pinmux 309.60 ms. Pinmux by family: `[]` 82.80, quickfix 84.13, extract 140.42, inline 136.37, ports 137.97, organizeImports 135.45 | — | +| Additional parses per no-offer all-family action | 5 text-parse entry points confirmed in source; no runtime counter | Still no runtime counter — P0 is harness-only and adds no production instrumentation. The wire-side attribution is reproduced (`offerkinds`): 82.80 ms shared base at the pinmux cursor, +52.7 to +57.6 ms for any one selector family | **Counter added and asserted on.** `vlog_parser::stats::parses()` counts whole-file parses (thread-local; a request is answered on one thread). At a no-offer cursor a *repeated* all-family `codeAction` performs **0** parses, an `only: []` request **0**, and the first request after a `didChange` **≤2** (the document's own parse, plus the fence answer when a fix exists) — `server::tests::code_action`. On the wire the five parses are gone: a single selector family fell from 58.6–59.7 ms to **0.06–0.14 ms** at the pinmux cursor | +| Lint/config/fence time separately | About 80 ms combined on generated file; unseparated | Reproduced but still unseparated: pinmux `only: []` 82.80 ms, quickfix 84.13 ms. Separating them needs P1's counters | **Separated by P1a's gates.** `only: []` now answers in **0.064 ms**, so none of the 82.8 ms was unavoidable. Quickfix-only is **23.53 ms** — the configuration read plus the lint pass. The difference, **59.3 ms, was the fence parse**, and it vanished at this cursor because no finding in `pinmux_reg_top.sv` carries a fix, so §P1a's "no fix, no fence" gate skips it outright | +| Selector time by family and file size | Filtered ablations preserved in raw data | **Promoted to the committed `offerkinds` phase**: 7 families × 5 cursors × 4 requests, result counts in every row. All-family repeat medians by cursor — tb 1.54 / aes-reg-instance 23.51 / aes-core 10.42 / spi 14.43 / pinmux 309.60 ms. Pinmux by family: `[]` 82.80, quickfix 84.13, extract 140.42, inline 136.37, ports 137.97, organizeImports 135.45 | **P1b, same phase.** All-family repeat medians by cursor — tb **0.60** / aes-reg-instance **21.79** / aes-core **2.30** / spi **3.16** / pinmux **24.02** ms. Pinmux by family: `[]` **0.053**, quickfix **24.05**, extract **0.107**, inline **0.074**, ports **0.063**, organizeImports **0.060** — every selector family is now under a seventh of a millisecond on a 1.3 MB buffer. The one family that did not move is ports **at an offering cursor** (aes-reg-instance 22.47 → **21.15**), which is P1c's row | | Tail rename selected paths / input bytes / selection reasons | Not measured; **2 output files is not input count** | Still not measured (needs P2a's server-side instrumentation). What P0 adds is the **output** side, exactly: 5 edits / 2 files / 0 created, fingerprint `b39defb21265…` | — | | Tail rename watched vs edited paths | Edited 2; watched unmeasured | Edited 2, confirmed by `files`; watched still unmeasured — P2a | — | | Tail rename index / parse / analysis / resolution / verification stage times | Not measured | Not measured — P2a | — | @@ -110,7 +120,7 @@ improvement claim. Baseline cells are untouched. | Peak server RSS during startup and refactoring | Idle RSS only; peak unmeasured | **Startup peak measured** (`peak_rss_kib`, `ps -o rss=` at 50 ms across the scan): cold 526.7 / 530.2 / 535.2 MiB, warm 575.0 / 572.5 / 575.6 MiB — equal to idle to the KiB in all six sessions, i.e. no transient above idle. Refactoring peak still unmeasured — P2a | — | | First useful response during scan; open buffers 1 / 10 / 100 | Not measured in this round | **First useful response measured** (above), each session a fresh process, kept in separate sessions from the settled rows so the settled series stays comparable. Open buffers 1 / 10 / 100 not measured — P4a | — | | Actual inline/extract command time and applyEdit payload | Not measured; existing resolve rows invalid for this purpose | **Measured, phase `execute`.** `lucisv.extractModule` (`aes.sv` 220:0–222:53): 257.33 / 245.05–247.00 ms from `executeCommand` to `workspace/applyEdit`, payload 2 edits / 2 files / 1 created, label `lucisv: lucisv.extractModule`, fingerprint `090e92e7736e…`, declined with `applied: false` (status `capture`), delivery half 0.015–0.033 ms. `lucisv.inlineModule` (`aes_wrap.sv` 66:2) **refused** (`generate` construct) in 6.58 / 5.87–6.20 ms; the extract offer at that same cursor **refused** after 817.37 / 793.77–809.07 ms. Take 4's `*-module resolve` rows are removed, not reinterpreted | — | -| First offer after didChange vs repeated unchanged offer | Separate distribution needed | Not measured. Every row separates the *first request of a session* from its repeats, but no row yet issues a `didChange` and then re-offers — P1's measurement | — | +| First offer after didChange vs repeated unchanged offer | Separate distribution needed | Not measured. Every row separates the *first request of a session* from its repeats, but no row yet issues a `didChange` and then re-offers — P1's measurement | **Measured, new phase `offeredit`** (`tools/perf/phases_p1.py`): three `didChange` → `codeAction` pairs, then three repeats at the same cursor in the same session. P1b medians — pinmux **133.86** first-after-edit against **24.18** repeated; `aes_reg_top` instance **22.66** against **21.65**; `tb.sv` comment **1.95** against **0.54**. So on the generated file the edit itself (one `Document::new`: lex, parse, analyze, resolve, line-index 1.3 MB) is ~110 ms and dwarfs the offer; on ordinary files the two are within 1 ms | ## Correctness and integration gates @@ -119,19 +129,19 @@ this stage; each says so rather than being left ambiguous. | Gate | Required evidence | Candidate result / log | |---|---|---| -| Action parity | Titles/kinds/counts/commands/data or edits/refusals; empty/prefix filters; cursor and selection | **P0: recorded, not yet a comparison.** Every offer row now carries `titles`, the shape of each offer (`edit`/`command`/`data`), `result_count` and the `only` filter it asked with; `offerkinds` walks 7 filters at 5 cursors. This is the reference P1 must match | -| Reuse freshness | didChange, unsaved overlays, config/options/tab width/waiver changes, index generation, closed files changed on disk | Not applicable at P0 — nothing is reused or cached in production | -| Fence parity | All aliases, class/statement fences, malformed source, raw scan backstop, insertions and multi-edit fixes | Not applicable at P0 | +| Action parity | Titles/kinds/counts/commands/data or edits/refusals; empty/prefix filters; cursor and selection | **P0: recorded, not yet a comparison.** Every offer row now carries `titles`, the shape of each offer (`edit`/`command`/`data`), `result_count` and the `only` filter it asked with; `offerkinds` walks 7 filters at 5 cursors. This is the reference P1 must match — **P1a/P1b: matched.** Every one of the 60 rows in each stage carries the REF's own `result_count`, and the `codeaction` rows the REF's own `titles`; all 7 filters at all 5 cursors agree. In tests, `vlog_refactor/tests/parsed_selectors.rs` compares old against new at **every byte offset** of five fixtures, and `server/tests/code_action.rs` pins order, prefix filters, the empty filter, a cursor-width extraction and a fix spanning the cursor | +| Reuse freshness | didChange, unsaved overlays, config/options/tab width/waiver changes, index generation, closed files changed on disk | Not applicable at P0. **P1b: one memo exists, the fence answer, and it is bound to the `Document` that owns the text** — `Workspace::set_document` builds a whole new `Document` on every `didOpen`/`didChange`/text-carrying `didSave`, and `answer_request` flushes pending changes before any handler runs, so there is no revision to compare and no way to hold the wrong one. Pinned by `a_fence_typed_into_the_buffer_is_seen_by_the_next_request` (fix → fence typed in → fix withheld → fence removed → fix back). Configuration is **not** memoized: `an_external_waiver_still_keeps_its_fix_out_of_the_offer` writes a `lucisv.toml` between two requests and the second obeys it. An index rebuild between two requests changes nothing at the cursor (`an_index_refresh_does_not_change_what_the_cursor_offers`). **Lint results are not cached** — see the `P1b-2026-09-07` entry for why and for the number | +| Fence parity | All aliases, class/statement fences, malformed source, raw scan backstop, insertions and multi-edit fixes | Not applicable at P0. **P1: `vlog_formatter/src/fence.rs` is untouched and the shared-fence-filter contract is not amended** — the question asked is still `protected_regions(&doc.text)`, byte for byte, so every alias, class/statement fence, malformed-source case and scan backstop is answered by the same code as before. What changed is *when* it is asked (only when a violation carries a fix) and *how often* (once per document revision). `vlog_formatter`'s own suite is green | | Refactor whole-scope parity | Exact edits, warnings, refusal sentences; old/new common names, unresolved and ambiguous uses | **P0 supplies the instrument**: `fingerprint` (sha256 over sorted edits + created paths + warnings) and `edits`/`files`/`created` on every edit-bearing row, plus refusal sentences captured verbatim in `message`. First reference values recorded (tail rename, `aes` rename, extraction) | -| Topology handshake 33 | Transitive `wrap.u_S.x` refusal coverage before sharing/narrowing module sources | Not applicable at P0 — no selector shared or narrowed | -| Refactor verification | Token identity, semantic identity, parse-diagnostic preservation, comments/attributes, span remapping | Not applicable at P0 — the engine's verifiers are untouched | +| Topology handshake 33 | Transitive `wrap.u_S.x` refusal coverage before sharing/narrowing module sources | Not applicable at P0 — no selector shared or narrowed. **Still not applicable at P1**: the four `*_in` selectors take the same decisions over the same tree, and **no source set was narrowed or shared** — `module_sources` / `offer_sources` / `imports::sources` are untouched. Handshake 33 stays P2's prerequisite | +| Refactor verification | Token identity, semantic identity, parse-diagnostic preservation, comments/attributes, span remapping | Not applicable at P0 — the engine's verifiers are untouched. **Unchanged at P1**: nothing below the four gates moved; `extract_module`, `inline_module`, `organize_imports`, `port_actions` and `check::verify` are the same code, and `vlog_refactor`'s own suites are green | | CLI output | Compare full findings/fixes/waivers/exit codes, not just counts; disabled-rule run stays attribution-only | **Passed.** stdout sha256 of all five configurations byte-identical to the baseline's; exit codes 1 (lint findings) / 2 (four pre-existing format failures) as before; the `--ignore unused-import` run is recorded as attribution only | | Index parity | Fresh/incremental/absorbed fingerprints, unsaved wins, coherent partial publication, scope/filelist/rootless behavior | Not applicable at P0. Store size unchanged at 44.34 MiB and the scan's own `$/progress` end messages recorded per cell (`124 → 3976 files indexed, 3975 from cache, 3 skipped` warm) | | Persistence | Corrupt/truncated/old-format stores rebuild safely; interrupted writes; content hash retained | Not applicable at P0 | -| Resources | Guard outcomes, idle and peak memory, allocated/actual store size, stack-size requirement | **Passed.** Every run under `tools/guard.sh -m 8 -t 1800`; **zero kills**; largest resident set 575.6 MiB (7% of the limit). Idle *and* peak RSS now recorded in their own KiB fields; store 44.34 MiB | -| Formatting | `cargo fmt --all -- --check`, appropriate formatter snapshot/idempotency and corpus gates | Not applicable at P0 — no Rust changed, and no `cargo` command may run during a timed round. `python3 -m py_compile tools/perf/*.py` and `bash -n tools/perf/*.sh` clean | -| Lint/tests | Guarded affected tests then clippy/workspace tests at integration, no benchmark overlap | Not applicable at P0 (no Rust). No benchmark overlapped a build: the one competing `cargo build` (a CI runner outside this tree) was waited out before the first timed phase | -| Documentation | Feature README, handshake updates in topo, accepted numbers in perf README; reserved lead Review untouched by dev | **Done.** `docs/features/perf5-p0/README.md` created with the required sections (QA and Review left empty); no `topo.md` edge changed because no interface changed; `docs/perf/README.md` carries a note that two take-4 row *meanings* are superseded | +| Resources | Guard outcomes, idle and peak memory, allocated/actual store size, stack-size requirement | **Passed.** Every run under `tools/guard.sh -m 8 -t 1800`; **zero kills**; largest resident set 575.6 MiB (7% of the limit). Idle *and* peak RSS now recorded in their own KiB fields; store 44.34 MiB. **P1: zero guard kills** across ten timed runs and every `cargo` gate. Memory not re-measured (P4a's phase); the only new retention is one `Vec` per open buffer that ever needed a fence answer. No new parsing thread, so the 16 MiB stack contract is untouched | +| Formatting | `cargo fmt --all -- --check`, appropriate formatter snapshot/idempotency and corpus gates | Not applicable at P0 — no Rust changed, and no `cargo` command may run during a timed round. `python3 -m py_compile tools/perf/*.py` and `bash -n tools/perf/*.sh` clean. **P1: `cargo fmt --all -- --check` clean; `cargo test -p vlog_formatter` green inside the workspace run** (the formatter is not on this change's path — `fence.rs` is untouched — but it was run anyway). `python3 -m py_compile tools/perf/*.py` clean for the new phase | +| Lint/tests | Guarded affected tests then clippy/workspace tests at integration, no benchmark overlap | Not applicable at P0 (no Rust). No benchmark overlapped a build. **P1: `cargo clippy --all-targets` clean at both stages** (one `needless_borrow` introduced by the P1b diff was fixed; **no new `#[allow]`**), `cargo test --workspace` green before each stage's build, all guarded. **No cargo command ran during any timed phase**: each stage built once, to completion, then measured | +| Documentation | Feature README, handshake updates in topo, accepted numbers in perf README; reserved lead Review untouched by dev | **Done.** `docs/features/perf5-p0/README.md` created with the required sections (QA and Review left empty); no `topo.md` edge changed because no interface changed; `docs/perf/README.md` carries a note that two take-4 row *meanings* are superseded. **P1: `docs/features/perf5-p1/README.md` created** with all seven sections, QA and Review left empty, the work log kept as the work went. `topo.md` is **not** edited by this lane — the two additive edges (`vlog_parser::stats`, the four `vlog_refactor` `*_in` selectors, the server's `fences` module) are written as requests in that README's Handshakes for the lead to apply. `docs/perf/README.md` untouched until the lead accepts these numbers | ## Experiment record — P0-2026-09-07 (stage P0) @@ -271,6 +281,219 @@ this stage; each says so rather than being left ambiguous. at the pinmux cursor, +52.7 to +57.6 ms per selector family) it must reduce. - **QA result and lead review link:** pending — `docs/features/perf5-p0/README.md`. +## Experiment record — P1a-2026-09-07 (stage P1a) + +- **Experiment ID / stage / date / owner:** `P1a-2026-09-07` / P1a (TODO §60.1) + / 2026-09-07, America/Chicago / dev agent (Opus). +- **Hypothesis and exact expected work reduction:** the ~82.8 ms a pinmux + code-action paid before any refactoring family was considered is *optional* + work — a configuration read, a lint pass and a fence parse — done before the + request's own `context.only` was looked at. Checking the filter first should + take `only: []` to the transport floor and a refactor-only request to its + selector alone; and because the fence answer protects *fixes*, a pass whose + findings carry no fix should not compute it at all. +- **Reference commit, candidate commit or diff hash, binary hashes:** reference + is §P0's REF rows on `27e0a0df…` (tree `9c75b7a4…`). Candidate is the working + tree at `501b36d8b8871ef6af39d6418ffd9290eede411b` plus the §60.1 P1a diff; + release binary sha256 + `0bf7cf211108a67eb5e695a2ff8b473b669cac22b6e8502e8ff22879d4482ecd`. +- **Files changed / API contracts amended / topology references:** + `lucisv_server/src/server/dispatch.rs` (the `CodeActionRequest` arm), + `code_action.rs` (`wants_fixes`, additive), `lint.rs` (`fixable`'s fence + gate); `vlog_parser/src/stats.rs` (new) + two increments in + `parser/mod.rs` + one `pub mod` line; tests in + `lucisv_server/src/server/tests/code_action.rs` (new) and its `mod` line; + `tools/perf/phases_p1.py` (new) + one import in `bench.py`. **No contract + amended.** `fence.rs` untouched, shared-fence-filter unchanged. The one new + interface is `vlog_parser::stats::parses()`; a `topo.md` edge is *requested* + in `docs/features/perf5-p1/README.md`, not applied — the dev does not edit + `topo.md`. +- **Workload, corpus/input hashes, open files, cursor/range, rules, client + capabilities:** OpenTitan `0098135264`, the same three pre-existing modified + files, `git status --porcelain` verified identical after **every** phase. + Cursors are `tools/perf/sites.py`'s. Client shape recorded in every row + (lazy: `resolveSupport` true, `applyEdit`/`createFiles` false), except + `codeaction`'s eager half. +- **Machine, compiler/profile, threads, load before/after, competing + activity:** M1 Max, macOS 27.0 `26A5425a`, release profile, default worker + count. Load 3.04–4.54 before each phase and 3.04–4.50 after. `cargo build + --release -p lucisv_server` ran **once**, to completion, before the first + timed phase; no cargo command ran during any timed phase. +- **Commands, cache reset/prime steps, trial ordering and fresh-session + count:** five guarded runs, `tools/guard.sh -m 8 -t 1800 -- python3 + tools/perf/bench.py … --tries 3` for `offerkinds codeaction + offerqueue blockers offeredit`, in that order, one scratch `--storage` per + stage. `blockers` is the only fresh-process phase here (3 per leader). +- **Raw evidence path, explicit units, full sample arrays:** + `~/.cache/lucisv-perf/take5-p1/results-p1a.jsonl` (60 rows, schema 2), + `logs-p1a/`, `runs-p1a.txt` (per-phase load and corpus check). Latency is + `ms` and nothing else. +- **Reference first / repeat median / range; candidate first / repeat median / + range:** in the Before/after table above; arrays in the JSONL. +- **Work counts: reads, parses, analyzed/selected/watched/edited files and + bytes:** the counter (`vlog_parser::stats::parses()`) is asserted in tests, + not sampled on the corpus — a released server prints nothing. What the wire + shows: `only: []` 82.80 → 0.064 ms (the whole base was skippable), quickfix + 84.13 → 23.53 (the fence parse gone), one selector family unchanged at + 58.6–59.7 ms (still a whole-file parse each). +- **Result/status/count/fingerprint comparisons, warnings and refusal + checks:** 60 rows, all `status: ok`. **Every result count is identical to + the REF row's** — the pinmux cursor still offers 0 actions under all seven + filters, `aes` 1, `aes_reg_top` 2, `prim_flop_2sync` 2 eager. No refusal, no + warning, no created file; the corpus is unchanged. +- **Idle RSS / peak RSS / cache size / guard outcomes:** not re-measured (P1 + changes no allocation path; `rss` is P4a's phase). **Zero guard kills** in + all five runs. +- **Target achieved or missed; paired improvement and variability:** P1a is a + step, not the stage's target. Achieved: `only: []` −99.9%, quickfix −72.0%, + all families −16.6%, queued definition −18.4%. The plan's three timing goals + are all still missed at this point, by design — the four selector parses are + P1b's subject. +- **Correctness tests and logs:** `cargo fmt --all -- --check` clean, + `cargo clippy --all-targets` clean, `cargo test --workspace` green (all + suites, `vlog_formatter` included), all under + `tools/guard.sh -m 8 -t 1800`. Eight new tests pin the empty filter, the + two gates, the no-fix case, prefix semantics, action order, a fix spanning + the cursor and the empty-range extraction. +- **Interpretation, remaining bottleneck, tradeoffs, rejected alternatives:** + the round's best result is the *attribution*, which no previous take could + make: at the pinmux cursor the 82.8 ms base was **23.5 ms of configuration + and lint plus 59.3 ms of fence parse**, and 23.5 + 4 × 58.7 = 258.3 against + the 258.1 measured — the whole remaining cost is accounted for with nothing + left over. Rejected: returning for an empty `only` *before* the document + lookup (it would turn `null` for an unknown buffer into `[]`, a wire change + for a hash-map lookup's worth of time); memoizing the fence answer here (it + would have contaminated P1a's number with P1b's). +- **Decision: retain / revise / reject / defer; next stage justified by + evidence:** **retain**, and P1b is justified: four whole-file parses of a + 1.3 MB buffer, 58.6–59.7 ms each, are 91% of what is left. +- **QA result and lead review link:** pending — + `docs/features/perf5-p1/README.md`. + +## Experiment record — P1b-2026-09-07 (stage P1b) + +- **Experiment ID / stage / date / owner:** `P1b-2026-09-07` / P1b (TODO + §60.1) / 2026-09-07, America/Chicago / dev agent (Opus). +- **Hypothesis and exact expected work reduction:** each of the four cheap + gates parses the same bytes the open `Document` already parsed. Handing them + that parse should remove four whole-file parses per all-family request — + ~235 ms of the pinmux cursor's remaining 258 — and leave the lint pass as + the residue. The fence answer, memoized per document revision, should remove + one more parse on buffers that *do* carry a fix (not this one). +- **Reference commit, candidate commit or diff hash, binary hashes:** the same + §P0 REF rows are the reference; P1a's rows are reported beside them as the + intermediate. Candidate is the working tree at `501b36d8…` plus the full + §60.1 diff; release binary sha256 + `540b8b7ed42218c12fd662b552ddd3cd24026301912e7dc16c14d4d5c29d33e4`. +- **Files changed / API contracts amended / topology references:** engine — + `vlog_refactor/src/{ports/mod.rs,imports.rs,extract/mod.rs,inline/mod.rs, + lib.rs}`, four **additive** `*_in` selectors, the text forms retained as + wrappers. Server — `fences.rs` (new, 33 lines), one `OnceLock` field in + `state.rs` and its two initializers, one private `…_at(doc, …)` helper each + in `ports.rs` / `imports.rs` / `extract.rs` / `inline_module.rs`, + `lint.rs::fixable` asking `fences::of`, one `mod` line in `main.rs`. Tests — + `vlog_refactor/tests/parsed_selectors.rs` (new), more of + `server/tests/code_action.rs`. **`fence.rs` untouched and the + shared-fence-filter contract not amended**: the fence answer is still + `protected_regions(&doc.text)`, only memoized. Topology edges *requested* in + the feature README. +- **Workload, corpus/input hashes, open files, cursor/range, rules, client + capabilities:** identical to P1a's, same three modified corpus files, corpus + verified unchanged after every phase. +- **Machine, compiler/profile, threads, load before/after, competing + activity:** same host and profile. Load 3.70–5.01 before each phase, + 3.70–4.50 after — higher than P1a's band by about 1.0, which matters only + for the sub-millisecond rows and is stated rather than corrected for. One + `cargo build --release -p lucisv_server` before the first timed phase; no + cargo during timing. +- **Commands, cache reset/prime steps, trial ordering and fresh-session + count:** the same five phases in the same order, `--tries 3`, a separate + scratch `--storage` (`caches/p1b`) so no cache is shared with P1a. +- **Raw evidence path, explicit units, full sample arrays:** + `~/.cache/lucisv-perf/take5-p1/results-p1b.jsonl` (60 rows, schema 2), + `logs-p1b/`, `runs-p1b.txt`. +- **Reference first / repeat median / range; candidate first / repeat median / + range:** in the Before/after table above; arrays in the JSONL. +- **Work counts: reads, parses, analyzed/selected/watched/edited files and + bytes:** asserted by count in `server::tests::code_action` — + a repeated all-family `codeAction` at a no-offer cursor: **0** parses; an + `only: []` request: **0**; extract+inline at an *offering* cursor: **0**; + the first request after a `didChange`: **≤2** (the document's own parse plus + the fence answer). The ports family at an offering cursor still parses + (`the_port_offer_still_reaches_the_engine_and_that_is_what_p1c_is_for`) — + that is the engine plan, and the test exists so it cannot grow unnoticed. +- **Result/status/count/fingerprint comparisons, warnings and refusal + checks:** 60 rows, all `status: ok`; **every result count identical to the + REF and to P1a** (pinmux 0 under all seven filters, `aes` 1, `aes_reg_top` + 2, eager `prim_flop_2sync` 2). Offer *titles* recorded in the `codeaction` + rows are unchanged. No refusal, no warning, corpus unchanged. +- **Idle RSS / peak RSS / cache size / guard outcomes:** not re-measured (see + P1a). The one new allocation is one `Vec` per open buffer that ever + needed a fence answer. **Zero guard kills** in all five runs. +- **Target achieved or missed; paired improvement and variability:** + - Pinmux no-offer comment, unchanged buffer: goal <16 ms — **missed at + 24.02 ms** (−92.2% on REF). Remaining stage, measured, not inferred: the + lint pass. `only: []` is 0.053 ms and quickfix-only is 24.05 ms, so + **100%** of what is left is the configuration read plus `lint_with` over + a 42 192-line buffer. + - Ordinary repeated lazy offer, goal <5 ms — **met on `tb.sv`** (3.65 ms + on the `codeaction` cursor, 0.60 ms on the `offerkinds` one), **missed on + `aes`** (7.76 ms). + - `aes_reg_top` offer, goal <10 ms — **missed at 21.83 ms** (−6.3%). + Remaining stage, measured: the ports family alone is **21.15 ms** of it + and every other family together is under 0.6 ms, so it is entirely the + `port_actions` plan the offer computes and discards — **P1c**. + - Queued definition: 309.40 → **24.61 ms** (−92.0%), goal <16 ms missed by + the leader's own lint residue. + - First-after-edit, tracked separately: pinmux 368.32 → **133.86 ms** + (−63.7% against P1a). +- **Correctness tests and logs:** `cargo fmt --all -- --check` clean, + `cargo clippy --all-targets` clean (one `needless_borrow` the change + introduced was fixed, no `#[allow]` added), `cargo test --workspace` green + — 51 suites, `vlog_formatter`'s snapshot/idempotency suite included — all + under `tools/guard.sh -m 8 -t 1800`, zero kills. New: 7 engine parity tests + that compare `X_in` against `X` at **every byte offset** of five fixtures + (clean, non-parsing, CRLF, non-BMP, non-ANSI, empty), and 12 server tests + covering the counters, the fence memo across `didChange` in both directions, + a waiver, a `lucisv.toml` written between requests, an index refresh, an + `untitled:` buffer, CRLF + astral positions, a non-parsing buffer, and a + large buffer answering its command from its text. +- **Interpretation, remaining bottleneck, tradeoffs, rejected alternatives:** + the offer path no longer parses anything it already has: on the generated + file a single refactoring family went from 58.6–59.7 ms to 0.06–0.14 ms, and + the all-family answer from 309.6 to 24.0 ms. Two named residues remain, and + neither is guesswork: **the lint pass** (24.0 ms, the whole of the pinmux + row) and **the discarded ports plan** (21.2 ms, the whole of the + `aes_reg_top` row — P1c). + **Lint-result reuse was considered and not done.** The condition the brief + set is met — lint is 100% of the pinmux row for a client that wants quick + fixes — but the memo is a differently-shaped change: its key must span the + document revision (free, it lives on the `Document`), the tab width, the + effective rule set, the merged rule options, the line width, the *contents* + of every external waiver file, and the workspace index generation — and that + last one is not reachable from `fixable`'s signature at all, since + `generation` lives on `Server` and not on `Workspace`. Wiring it means + threading a generation through the code-action path and hashing four + independent configuration surfaces, whose failure mode is a **stale fix + offer** — the class of bug this repository's fourth invariant is about. It + deserves its own item with its own attack tests (one per key component), + beside the P1c ruling, rather than a tail on this lane. The number to + decide with: **24.0 ms**, of which `only: []` proves 0.05 ms is transport; + and the *first* request after every keystroke pays it regardless of any + memo. It may also be cheaper to ask which rules cost 24 ms on a 1.3 MB + generated buffer than to cache their answer. + Other rejected alternatives: giving the fence answer a parsed-input API + (would amend the shared-fence-filter contract, which this lane may not do); + making the large-file path read `doc.tree` (its tree is the *empty* file's, + so offers would silently disappear — today's behaviour is preserved instead + and pinned by a test, with the question left to the lead). +- **Decision: retain / revise / reject / defer; next stage justified by + evidence:** **retain.** P1c is justified by 21.15 of 21.83 ms at the + `aes_reg_top` cursor; a lint-reuse item is justified by 24.0 of 24.0 ms at + the pinmux cursor. Both are lead rulings, not this lane's. +- **QA result and lead review link:** pending — + `docs/features/perf5-p1/README.md`. + ## Experiment record — copy for every stage or rejected attempt - Experiment ID / stage / date / owner: diff --git a/docs/topo.md b/docs/topo.md index 4398882..d39865c 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -137,11 +137,11 @@ what a change on the pointed-to side must not silently break. | `lucisv ──▶ vlog_parser` | depends | `LineIndex` / `TextRange` for lint report coordinates, plus `PARSE_STACK_SIZE` for both the named `lucisv` thread and rayon workers. (The CLI otherwise reaches the parser through the formatter and linter.) | | `lucisv ──▶ rayon` | depends | The worker pool. Pinned exactly; pool must keep `stack_size(vlog_parser::PARSE_STACK_SIZE)` (currently 16 MiB; recursion-limit handshake) or the parser's depth guarantee regresses to a stack overflow. | | `lucisv_server ──▶ lucisv_core` | depends | Same config discovery and walk as the CLI (that sameness is the point — format-on-save must agree with `lucisv --check`), `filelist::read` (index scope rung 1, `+incdir+` for the include graph), `cache::content_hash` (re-used by the persistent index cache — one FNV-1a, not two). | -| `lucisv_server ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant`/`parse_tolerant`, `ParseDiagnostic`, `LineIndex`, `TextRange`, tokens + trivia, `defines`, `KEYWORDS` (completion keyword tier; also the source the hand-maintained VS Code grammar is test-locked to), and `PARSE_STACK_SIZE` for the named `lucisv-main` thread. | +| `lucisv_server ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant`/`parse_tolerant`, `ParseDiagnostic`, `LineIndex`, `TextRange`, tokens + trivia, `defines`, `KEYWORDS` (completion keyword tier; also the source the hand-maintained VS Code grammar is test-locked to), `PARSE_STACK_SIZE` for the named `lucisv-main` thread, and `stats::parses()` (perf5-p1: a per-thread whole-file parse count, asserted by the code-action tests — a repeated offer on an unchanged buffer parses nothing). | | `lucisv_server ──▶ vlog_semantic` | depends | `analyze`/`Semantics` (every navigation answer), `WorkspaceIndex` (build/incremental update, units/members/defines, `instantiations_of`/`subclasses_of` edge tables, `FileFacts` codec for the persistent cache), `resolve_external` overlay, `index_order`/`IndexBuilder` (watched builds). | | `lucisv_server ◀──▶ vlog_semantic` | handshake | Two negotiated additions, both 2026-08-28 and both additive: **`Symbol::detail_span` / `Def::detail_span`** (where a non-ANSI port's body declaration completes the header that names it — the server's hover card and `nav::definition` both read it, and they show/jump to it in the same order), and **`Semantics::symbols_named`** (name → declarations, built in `analyze`, in declaration order — the server replaced two scan-every-symbol loops with it and the *first-match tie-break must stay declaration order* or hover's choice between two live declarations of one name changes). `docs/features/port-detail-spans/README.md`. | | `lucisv_server ◀──▶ vlog_semantic` | handshake | Three later additive performance surfaces: **`DeclLines` / `Def::lines`** record declaration and detail lines at index time (`FACTS_FORMAT` 3 → 4); **`WorkspaceIndex::absorb`** folds a scan batch with one merge rather than one merge per file; and **`WorkspaceIndex::files_spelling`** finds external uses by spelling, resolved or not, for rename's dangling-use refusal. The first feeds hover-line-index, the second scan-interleave, and the third refactor-rename's six-rung fan-out. Changing the facts codec, reference-fact census or merge semantics breaks those consumers. | -| `lucisv_server ──▶ vlog_refactor` | depends | `prepare_rename`/`rename`, `find_references`, the port refactorings, `organize_imports`, `extract_module`, `inline_module`, `RefactorEdit::{edits,warnings,created}`, `instantiation_plan`/`render_with`/`module_definition` (the inline instantiation ghost, signature help, inlay hints — the completion popup stopped consuming them 2026-08-30, names-only tier). Promise consumed: never a partial edit — `Ok` verified whole, `Err` is a sentence. | +| `lucisv_server ──▶ vlog_refactor` | depends | `prepare_rename`/`rename`, `find_references`, the port refactorings, `organize_imports`, `extract_module`, `inline_module`, `RefactorEdit::{edits,warnings,created}`, the parsed-input selectors `port_action_modules_in`/`imported_packages_in`/`extract_site_in`/`inline_site_in` (perf5-p1: the offer paths hand the document's own tolerant parse and diagnostics; the text forms are thin wrappers kept for standalone consumers and the every-offset parity test; a large-file buffer still takes the text form), `instantiation_plan`/`render_with`/`module_definition` (the inline instantiation ghost, signature help, inlay hints — the completion popup stopped consuming them 2026-08-30, names-only tier). Promise consumed: never a partial edit — `Ok` verified whole, `Err` is a sentence. | | `lucisv_server ◀──▶ vlog_refactor` | handshake | Request-scope selectors added for the performance wave: `prepare_rename_here` must produce the same answer/refusal text as whole-scope `prepare_rename`; `rename_name_at` must name the target that the rename engine acts on; `port_action_modules` and `enclosing_module` must name every module the corresponding port action/command can edit. The server uses those names to choose an index-derived file set; `extract_site`, `inline_site` and `imported_packages` also name source requirements. The engine remains the authority, and every selector must supply a superset of files needed for edits and refusals (inline gap: §2.9-33). | | `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_range`/`LineRanges` (range, ranges, on-type formatting), `Config`, `fence::protected_regions` (quick-fix filter). | | `lucisv_server ──▶ vlog_linter` | depends | `run`, `lint` + `LintContext::from_parse` (lints from the `Document`'s own parse — one-parse), `default_rules`, `apply_fixes`, `rule_by_name`. Same three promises the CLI relies on. | @@ -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`, `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), `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 41e77f5..46f61d4 100644 --- a/tools/perf/README.md +++ b/tools/perf/README.md @@ -19,6 +19,7 @@ and take 5 §P0 (TODO §60.0) corrected what some rows *meant*: see | `bench.py` | the command line, and the phases that reproduce take 3's tables | | `phases_new.py` | the phases for what 0.44–0.49 added: the new offer sites, §49's surface, §46's `didOpen` fix, `moduleHierarchy`, index size and RSS | | `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 | | `sweep.sh` | the timed CLI sweeps (`format --check`, `check`) over five trees, `/usr/bin/time -l` | | `sweeptable.py` | those logs → the document's §7 Markdown table, plus the format-cache hits each try reported | | `outcomes.sh` | the untimed per-file outcome runs, for the release-to-release outcome diff | @@ -77,6 +78,7 @@ apart in `results.jsonl`; run each phase once per binary. | `execute` | §P0 | the extract and inline **commands**, run for real: `workspace/executeCommand`, the `workspace/applyEdit` the server pushes back captured and declined, the edit counted and fingerprinted | | `offerkinds` | §P0 | the seven `context.only` families at five cursors, four requests each, result counts beside every time | | `offerqueue` | §P0 | the pinmux no-offer comment as leader, an `aes` definition as follower, in separate fields | +| `offeredit` | §P1 | two rows per cursor: `didChange` → `codeAction`, three times over, then three `codeAction`s on the unchanged buffer. §P1b's whole claim is about the second, so the first is never allowed to hide inside it | | `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 c4546fc..e72b369 100644 --- a/tools/perf/bench.py +++ b/tools/perf/bench.py @@ -34,6 +34,7 @@ from harness import ( # noqa: E402 import phases_new # noqa: E402,F401 — registers its own phases import phases_p0 # noqa: E402,F401 — registers take 5 §P0's phases +import phases_p1 # noqa: E402,F401 — registers take 5 §P1's phases # ========================================================================= diff --git a/tools/perf/phases_p1.py b/tools/perf/phases_p1.py new file mode 100644 index 0000000..a6f5345 --- /dev/null +++ b/tools/perf/phases_p1.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""The phase take 5 §P1 added: what an offer costs on a buffer that just +changed, as against one that did not. + +Imported by `bench.py`, which owns the registry and the command line. + +`offeredit` exists because §P1b's whole claim is that a *repeated* offer on an +unchanged buffer reuses the document's own parse. That claim would be easy to +dress up by quoting only the repeats, so the first request after a `didChange` +— where the document is rebuilt and nothing is reusable — gets its own row at +the same cursor, in the same session, with the same client shape. The tracker +compares the two. + +The corpus is not written: a `didChange` is a notification about an in-memory +buffer, and the appended line never reaches disk. +""" + +import os + +import schema +from harness import ( + ARGS, code_action_params, phase, record, samples, session, settled, sites, +) + +#: (label, file, needle, cursor offset) — the cursors §P1 is judged at. The +#: first is the round's headline (a no-offer comment in a 42 192-line +#: generated file), the second the one small-file offer site, the third the +#: small-file no-offer control. +EDIT_CURSORS = [ + ("pinmux-comment", sites.PINMUX_REG_TOP, "// ", 2), + ("aes-reg-instance", sites.AES, "aes_reg_top u_reg (", 0), + ("tb-comment", sites.TB, "// ", 2), +] + + +def open_and_settle(s, relative, quiet=0.6): + """Settle the scan, then open the file this row measures.""" + settled(s) + s.did_open(sites.path(relative)) + s.wait_quiet(quiet) + s.take_notifications() + + +def first_after_change(s, relative, text, params, tries): + """One `codeAction` per `didChange`, each the first request after its edit. + + The edit is a comment appended to the end of the buffer, so every cursor + this phase measures keeps the position it was resolved at. `samples(…, 1)` + is used rather than a repeat list because a repeat would no longer be the + first request after a change, which is the whole subject of the row. + """ + ms, statuses, counts = [], [], [] + for version in range(2, 2 + tries): + s.did_change(sites.path(relative), text + "\n// take5 p1 %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) + return ms, statuses, counts + + +@phase("offeredit") +def phase_offeredit(): + """§P1 — the first offer after an edit, beside the repeated offer. + + Two rows per cursor in one session: `didChange` → `codeAction` three + times over, then three `codeAction`s on the settled buffer. A lazy client, + which is the shape every reference row in the tracker used. + """ + for label, relative, needle, offset in EDIT_CURSORS: + with session("workspace", resolve_support=True) as s: + open_and_settle(s, relative) + with open(sites.path(relative), encoding="utf-8", + errors="replace") as handle: + text = handle.read() + params = code_action_params(relative, needle, offset=offset) + ms, statuses, counts = first_after_change( + s, relative, text, params, ARGS.tries) + status = schema.worst([one for one, _ in statuses]) + record(phase="offeredit", + row="%s, first offer after 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: the document is rebuilt, so nothing from " + "the previous revision can be reused") + # The buffer is now at its last edited revision and stays there: + # these are repeats on an unchanged document, the case §P1b's + # reuse is for. + got = samples(s, "textDocument/codeAction", params, ARGS.tries + 1) + offered = got.last.get("result") or [] + record(phase="offeredit", + row="%s, repeated offer on the unchanged buffer" % label, + titles=[a.get("title") for a in offered], + client=s.client_shape(), file=relative, + position=params["range"]["start"], load=os.getloadavg(), + note="the same cursor and session as the row above, with " + "no didChange between the tries", + **got.row())