Review round §61.5 (R3b/R3c): the rename's scope stage split (the parser is two thirds of it, a third spent on files never analysed) and facts reuse under a content-hash tie — a closed file's record is reused only when the handed bytes hash to what the store entry was written for, record and hash from one place, never the workspace index; tail rename 380 → 314 ms (−21 % against the review's baseline), the duplicate-module refusal 2.05 s → 0.7 s, 36 rows and 1 750 warning sentences byte-identical, check/ untouched

This commit is contained in:
lucio committed 2026-09-09 00:41:34 -05:00
1 parent 07ef771a35
commit 5e02142a8f
17 files changed
+1882 -63

No files matched your search

+71 -6
View File
@@ -4724,6 +4724,15 @@ in 0.49.0. Take 4's findings are in the loop-3 list above.
needs the 89 ms; and a walk that can skip an already-walked subtree so
the two-phase discovery stops walking the open folder twice (+2.5–5 %
on the 1/10-buffer settle).
- **review round §61.5 filed (QA, pre-existing):** a `bind` file's own
occurrence of a renamed name (`aes_bind.sv` for a bound name or a
two-level hierarchical tail) is neither edited nor warned about,
identically before and after the reuse — the whole-scope engine's
answer, so a missing warning at least (QA task `task_834abda3`); the
scope reuse's collateral for the other refactorings (`_with` doors for
extract/inline/imports/ports/references — the resolves and the extract
edit are the candidates, the 805 ms refusal is after the build); the
31 ms store decode the one-place tie costs.
Sections after §46 are planned when reached.
## 45. Small items, round 4 (planned 2026-09-05) — topo §2.9-29, 30, 17, 22
@@ -6522,13 +6531,69 @@ to the selected source bytes, unsaved-buffer precedence kept, cross-file
resolution rebuilt for the candidate workspace, a memory budget stated;
the 51 ms warning pass profiled and tightened without changing a
sentence; the selection set stays the correctness reference (P2d).
- [ ] lead ruling from 61.1's split: go / defer
- [ ] if go: the reuse, ≥ 20 % wire-time on the large rename at bounded
- [x] lead ruling from 61.1's split: go / defer — **go — 34.3 %.** The
tail rename's 242.4 ms scope stage is `lead` 0.4 + `kept` 133.5 +
**`other` 83.1** + `merge` 23.4, where `other` is the 103 container
files analysed for their index record and never read again; 83.1 /
242.4 = 34.3 %, against a 30 % condition. Agreed by every other
multi-file row (25.0 / 33.0 / 35.8 / 36.0 %, and **87.8 %** on the
duplicate-module refusal); 0 % on the two rows where every selected
file spells the name, which is the case the reuse is not for. The
split is now shipped in the engine's trace (`IndexTrace`,
`WarnTrace`), and a trace-only build put the inside of one analysis
at **lex 34 %, parse 32 %, analyse 20 %, read-off 13 %** — the
review's "parser versus index" question answered as *parser*. The
49.7 ms warning pass is **84 % the macro-argument scan**, which is
one per-file lex already shared by all five scans (§P2d): no
duplicated work left in it, and retaining tokens instead is refused
on the `clk_i` row's 1.9 GiB peak
- [x] if go: the reuse, ≥ 20 % wire-time on the large rename at bounded
peak RSS, ordinary / common-port / collision / macro-bind /
hierarchical-tail / fallback cases compared, verifier untouched
- [ ] QA
hierarchical-tail / fallback cases compared, verifier untouched —
**shipped as an engine door (`vlog_refactor::KnownFacts`) with one
server implementation: a caller may hand back the index record it
holds for exactly the bytes it is handing over, and the engine skips
that file's parse. The tie is `IndexCache`'s own store entry —
record and FNV-1a written by one read and compared in one function —
never the workspace index's record, which carries no hash. No
persistent decoded-analysis cache; nothing retained past the
request; unsaved-buffer precedence falls out of the content key.
Paired against `07ef771` with the order alternated per phase: tail
**380.2 → 314.0 ms (−17.4 %)**, parses **240 → 137** = `(K − 103) +
E`; fallback `clk_i` −17.4 %, conflict −18.8 %, new-name-many-uses
−18.5 %, duplicate-module refusal **2 053 → 695 ms (−66.1 %, 3 975
→ 14 parses)**; `aes` −0.5 %, extract refusal −0.7 %, resolves
within ±1.4 %; peak RSS lower or level everywhere. Parity: 36 rows
equal on fingerprint/message/status/counts/titles and **1 750
warning sentences compared line by line** by a new `renamewarn`
phase — identical. `check/` no diff. **The ≥ 20 % gate is missed at
−17.4 %** against the paired reference (−21.2 % against the review's
own 398.3 baseline; the absolute ≤ 318 ms form met at 314.0), and
the remaining stage is named: the reuse's own **31.1 ms of store
decode**, the price of the one-place tie. Collateral for the other
refactorings **not taken** — measured nil, and reaching them needs a
`_with` entry point in five files this lane does not own. Feature
README `docs/features/perf5r-scope-reuse/`; 4 366 → 4 374 tests**
- [x] QA — **PASS** (2026-09-09). The tie verified as one comparison
(`entry_for`) fed by one store entry, never the workspace index;
stale-disk, unsaved-buffer, misfiled-record and identical-content
cross-path attacks all forgiven correctly; two sabotage variants
(hash check removed; workspace-index record substituted) both caught
by existing tests. Index equality re-checked at the query level
(`defines`, `member`, `references_to`, `members_of_chain`,
`hierarchical_declarations`) over a macro-table + re-export fixture.
`check/` no diff; `(K-reused)+E` formula sabotage-verified. 36-row and
1 750-sentence parity, and the 34.3 % go arithmetic, re-derived from
raw evidence, not just read. Three QA-chosen renames (wildcard
import, bind-visible name, two-level hierarchical tail) run directly
against the real opentitan tree: byte-identical outcomes across
no-reuse/full-reuse/half-reuse. One out-of-scope observation flagged
separately (a bind-file's own occurrence going unedited/unwarned,
reproducible at HEAD, unrelated to the reuse door). Full log:
`docs/features/perf5r-scope-reuse/README.md`'s QA log.
### 61.6 Closing
- [ ] `docs/perf/README.md` entry; topo for every contract amended; the
review's status line; release 0.52.0 with assets verified
- [x] `docs/perf/README.md` entry; topo for every contract amended; the
review's status line; release 0.52.0 with assets verified — entry,
topo and status lines done 2026-09-09; release below
+59 -2
View File
@@ -215,6 +215,28 @@ impl IndexCache {
self.dir.as_deref()
}
/// The entry that asserts *exactly these bytes*, if there is one.
///
/// The one place the record and the key it is filed under are read
/// together: an entry holds the FNV-1a of the bytes its facts were read
/// off, and this is the only comparison anything in the server makes
/// against it. Both readers below go through here, so "the store answers
/// for this text" means one thing in a scan and in a refactoring alike.
fn entry_for(&self, path: &Path, text: &str) -> Option<&Entry> {
self.entries.get(path).filter(|entry| entry.content == content_hash(text.as_bytes()))
}
/// [`IndexCache::facts_for`] asked by something that is **not** a scan.
///
/// The same question, the same entry, the same answer — but the work is
/// not counted into [`IndexCache::work`], because that counter is what a
/// scan's own trace subtracts to say what *it* did. A refactoring reading
/// records between two scans would otherwise show up as decodes the next
/// scan never made (review round §R3b, `crate::state::Workspace::known_facts`).
pub fn facts_now(&self, path: &Path, text: &str) -> Option<FileFacts> {
FileFacts::decode(&self.entry_for(path, text)?.facts)
}
/// The facts a previous session read off this exact text, if it did.
///
/// The hash is of the text the server is about to index — an open buffer's
@@ -226,8 +248,7 @@ impl IndexCache {
/// gets here.
pub fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
let looking = Instant::now();
let found =
self.entries.get(path).filter(|entry| entry.content == content_hash(text.as_bytes()));
let found = self.entry_for(path, text);
let mut work = self.work.get();
work.lookup_ns += elapsed_ns(looking);
let Some(entry) = found else {
@@ -713,6 +734,42 @@ mod tests {
assert!(reopened.facts_for(Path::new("/nowhere.sv"), M).is_none());
}
/// **The R3b tie, both ways.** `facts_now` is the same content key
/// `facts_for` is — a record answers for the bytes it was read off and for
/// no others — and it leaves the scan's own work counters alone.
///
/// The stale case is the one that matters: a record written from one text
/// must never be handed to a refactoring reading a different text, because
/// the refactoring would index it as that file's facts and edit against an
/// index describing bytes nobody has.
#[test]
fn a_request_local_read_answers_for_these_bytes_and_counts_as_no_scan_work() {
let dir = TempDir::new("factsnow");
let file = dir.file("m.sv", M);
let mut cache = IndexCache::open(Some(dir.path.clone()));
cache.record(&facts(&file, M), M);
cache.compact();
let reopened = IndexCache::open(Some(dir.path.clone()));
let before = reopened.work();
assert_eq!(reopened.facts_now(&file, M), Some(facts(&file, M)), "these bytes");
// Every way the bytes can differ, and the wrong path too.
const EDITED: &str = "module m;\n sub u ();\n wire added;\nendmodule\n";
assert!(reopened.facts_now(&file, EDITED).is_none(), "a stale record must not be served");
assert!(reopened.facts_now(&file, "").is_none(), "nor an empty buffer's");
assert!(reopened.facts_now(&file, &M[..M.len() - 1]).is_none(), "nor one byte short");
assert!(reopened.facts_now(Path::new("/nowhere.sv"), M).is_none(), "nor another path's");
let after = reopened.work();
assert_eq!(
(after.hits, after.misses, after.decode_ns, after.lookup_ns),
(before.hits, before.misses, before.decode_ns, before.lookup_ns),
"a refactoring's reads are not a scan's work"
);
// The counted reader, asked the same questions, answers the same way.
assert_eq!(reopened.facts_for(&file, M), reopened.facts_now(&file, M));
assert_eq!(reopened.facts_for(&file, EDITED), reopened.facts_now(&file, EDITED));
}
#[test]
fn a_record_survives_a_session_that_never_compacted() {
// The crash case: records are written through as they are made, so a
+133 -1
View File
@@ -17,6 +17,7 @@ use std::path::PathBuf;
use lsp_types::{PrepareRenameResponse, TextEdit, Uri, WorkspaceEdit};
use vlog_parser::LineIndex;
use vlog_semantic::FileFacts;
use crate::convert::Positions;
use crate::locate::display_name;
@@ -100,7 +101,9 @@ pub fn rename_traced(
}
};
let mut engine = vlog_refactor::RenameTrace::default();
let outcome = vlog_refactor::rename_traced(&sources, &path, offset, new_name, &mut engine);
let known = Known(ws);
let outcome =
vlog_refactor::rename_traced_with(&sources, &path, offset, new_name, &known, &mut engine);
*trace = Some(format!("{} {}", selection.line(), engine.line()));
let refactoring = outcome?;
@@ -136,6 +139,23 @@ pub fn rename_traced(
Ok((WorkspaceEdit::new(changes), warnings))
}
/// The workspace answering the engine's `KnownFacts` question, and nothing
/// else: one call, to the one query that ties a record to the bytes it was
/// read off ([`Workspace::known_facts`]).
///
/// A newtype rather than an `impl` on `Workspace` so that the promise this
/// makes to `vlog_refactor` is written where a reader of the rename can see
/// it, and so that no other handler can acquire it by accident — the facts a
/// refactoring may reuse are the facts of the very texts it was handed, which
/// is a property of *this* call site.
struct Known<'a>(&'a Workspace);
impl vlog_refactor::KnownFacts for Known<'_> {
fn facts_for(&self, path: &std::path::Path, text: &str) -> Option<FileFacts> {
self.0.known_facts(path, text)
}
}
/// One sentence per file that writes the old name inside a macro invocation,
/// a directive line or an attribute and was **not** among the files the engine
/// was handed.
@@ -233,6 +253,118 @@ mod tests {
(ws, uri)
}
/// A third file that spells nothing this rename is about, kept open so
/// the open-buffer rung selects it: the "container" class in miniature —
/// a file the engine must index and never analyses.
const BYSTANDER: &str = "module bystander;\n logic unrelated;\nendmodule\n";
/// `sub.sv`, `top.sv` and `quiet.sv`, with the last two open and a
/// persistent index store behind the workspace — so a rename is handed
/// records keyed on the very bytes it reads.
fn three_with_store(tree: &Tree, store: Option<&Tree>) -> (Workspace, Uri) {
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let quiet = tree.write("bystander.sv", BYSTANDER);
let mut ws = Workspace::default();
ws.set_client_settings(crate::settings::ClientSettings {
index_cache_path: store.map(|s| s.path.to_string_lossy().into_owned()),
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
});
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
ws.set_document(path_to_uri(&quiet).expect("uri"), BYSTANDER.to_string());
(ws, uri)
}
/// Every edit and every warning one rename produced, with the workspace's
/// own scratch path taken out — the fingerprint the parity proof compares.
fn print(result: &(WorkspaceEdit, Vec<String>), root: &Path) -> String {
let (edit, warnings) = result;
let mut lines: Vec<String> = Vec::new();
for (uri, edits) in edit.changes.iter().flatten() {
for one in edits {
lines.push(format!(
"{} {:?}..{:?} -> {}",
uri.as_str(),
one.range.start,
one.range.end,
one.new_text
));
}
}
lines.sort();
lines.extend(warnings.iter().map(|w| format!("warn {w}")));
lines.join("\n").replace(root.to_str().expect("utf-8"), "")
}
/// **§R3b's server-side proof.** The same rename over the same files, once
/// with a warm index store behind it — where the engine is handed every
/// file's record and stops parsing the ones nothing analyses — and once
/// with no store at all, where it parses them all: byte-identical edits,
/// byte-identical warnings.
///
/// The reuse is asserted to have happened *and* to have removed a parse,
/// so a store that silently stopped answering would fail this rather than
/// pass it for the wrong reason.
#[test]
fn a_rename_over_a_warm_store_says_exactly_what_one_with_no_store_says() {
let tree = Tree::new("reuse_store");
let store = Tree::new("reuse_store_cache");
let (warm, uri) = three_with_store(&tree, Some(&store));
let mut line = None;
let with_store = rename_traced(&warm, &uri, at(TOP, "clk"), "clk_x", &mut line)
.expect("the rename succeeds");
let trace = line.expect("a trace is always written");
assert!(trace.contains("selected=3"), "all three files are selected: {trace}");
assert!(trace.contains("reused_files=3"), "and every record came from the store: {trace}");
assert!(trace.contains("other_files=1"), "bystander.sv is the unread one: {trace}");
assert!(trace.contains("parses{index=2"), "so only the two analysed files: {trace}");
let bare = Tree::new("reuse_none");
let (plain, plain_uri) = three_with_store(&bare, None);
let mut plain_line = None;
let no_store = rename_traced(&plain, &plain_uri, at(TOP, "clk"), "clk_x", &mut plain_line)
.expect("the rename succeeds");
let plain_trace = plain_line.expect("a trace is always written");
assert!(plain_trace.contains("reused_files=0"), "premise: no store, no reuse");
assert!(plain_trace.contains("parses{index=3"), "premise: all three parsed");
assert_eq!(
print(&with_store, &tree.path),
print(&no_store, &bare.path),
"the reuse changed an edit or a warning"
);
}
/// **Unsaved-buffer precedence, for free.** A buffer whose text disagrees
/// with the file on disk is not the bytes any record was written from, so
/// the store answers nothing for it and it is parsed — and the rename acts
/// on the buffer's text, which is the precedence it always had.
///
/// Nothing in the reuse arranges this: the key is the content, so unsaved
/// text misses the same way changed text does.
#[test]
fn an_unsaved_buffer_is_parsed_and_renamed_from_its_own_text() {
let tree = Tree::new("reuse_unsaved");
let store = Tree::new("reuse_unsaved_cache");
let (mut ws, uri) = three_with_store(&tree, Some(&store));
// A signal that exists only in the buffer. Its record cannot be in a
// store keyed on what is on disk.
let edited = "module top;\n logic only_here;\n sub u_sub (.clk(only_here));\nendmodule\n";
ws.set_document(uri.clone(), edited.to_string());
let mut line = None;
let (edit, _) = rename_traced(&ws, &uri, at(edited, "only_here"), "renamed", &mut line)
.expect("the buffer's own declaration renames");
let trace = line.expect("a trace is always written");
assert!(trace.contains("reused_files=1"), "only the untouched buffer's record: {trace}");
assert!(trace.contains("lead=0.0ms") || trace.contains("parses{index=1"), "{trace}");
let edits = edit.changes.as_ref().expect("changes").values().flatten().count();
assert_eq!(edits, 2, "the declaration and its one use, both in the buffer");
}
#[test]
fn prepare_offers_the_identifier_and_its_placeholder() {
let tree = Tree::new("prepare");
+16
View File
@@ -474,6 +474,22 @@ impl Workspace {
&self.index
}
/// The index record this workspace already holds for **exactly these
/// bytes**, or nothing.
///
/// What `vlog_refactor::KnownFacts` asks a refactoring's caller. Exactly
/// one thing in this server can promise it: the persistent index cache
/// files each record under the FNV-1a of the bytes it was read off, so
/// record and key are one store entry written by one read
/// ([`crate::index_cache::IndexCache::facts_now`]). Not a modified time,
/// not a size, and **not the workspace index's own record**, which carries
/// no hash of the text it came from. An unsaved buffer misses for the same
/// reason a changed file does, so precedence needs no rule here
/// (`docs/features/perf5r-scope-reuse/README.md`).
pub fn known_facts(&self, path: &Path, text: &str) -> Option<FileFacts> {
self.cache.facts_now(path, text)
}
/// The project-wide completion tables, as of the last index rebuild.
pub fn candidates(&self) -> &Candidates {
&self.candidates
+2 -2
View File
@@ -60,9 +60,9 @@ pub use ports::{
};
pub use rename::{
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, rename_preflight,
rename_traced, RenameTarget,
rename_traced, rename_traced_with, KnownFacts, RenameTarget,
};
pub use trace::{RenameTrace, Stage, VerifyTrace};
pub use trace::{IndexTrace, RenameTrace, Stage, VerifyTrace, WarnTrace};
use std::path::PathBuf;
+41 -8
View File
@@ -20,7 +20,9 @@ mod warnings;
pub use preflight::rename_preflight;
// The rename was the first refactoring, so most of the crate still spells the
// workspace `crate::rename::Scope`. It lives at `crate::scope` now (§29.1).
// workspace `crate::rename::Scope`. It lives at `crate::scope` now (§29.1),
// and so does the door a caller hands its own index records through.
pub use crate::scope::KnownFacts;
pub(crate) use crate::scope::{display, Scope};
pub use warnings::contains_word;
@@ -180,7 +182,29 @@ pub fn rename_traced(
trace: &mut RenameTrace,
) -> Result<RefactorEdit, String> {
let started = vlog_parser::stats::parses();
let out = renaming(files, file, offset, new_name, trace);
let out = renaming(files, file, offset, new_name, None, trace);
trace.parses = vlog_parser::stats::parses() - started;
out
}
/// [`rename_traced`], letting the caller answer for the index records of the
/// files it is handing over — see [`KnownFacts`].
///
/// The same rename over the same files, deciding everything the same way: a
/// record the caller answers with is one this call would otherwise have
/// produced by parsing that file, so the only difference is that it did not
/// parse it (review round §R3b). A caller that answers `None` to everything
/// gets [`rename_traced`] exactly.
pub fn rename_traced_with(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
new_name: &str,
known: &dyn KnownFacts,
trace: &mut RenameTrace,
) -> Result<RefactorEdit, String> {
let started = vlog_parser::stats::parses();
let out = renaming(files, file, offset, new_name, Some(known), trace);
trace.parses = vlog_parser::stats::parses() - started;
out
}
@@ -192,6 +216,7 @@ fn renaming(
file: &Path,
offset: u32,
new_name: &str,
known: Option<&dyn KnownFacts>,
trace: &mut RenameTrace,
) -> Result<RefactorEdit, String> {
check_new_name(new_name)?;
@@ -202,11 +227,18 @@ fn renaming(
// name under the cursor — which the request file's own analysis, the first
// one the build makes, is what says. A wrong guess costs a re-parse and
// can change nothing: retention is a cache.
let mut scope = trace.index.measure(|| {
Scope::build_keeping(files, file, |here| {
let cursor = here.and_then(|semantics| rename_name_at(semantics, offset));
cursor.into_iter().chain(Some(new_name.to_string())).collect()
})
let RenameTrace { index, indexing, .. } = &mut *trace;
let mut scope = index.measure(|| {
Scope::build_keeping(
files,
file,
|here| {
let cursor = here.and_then(|semantics| rename_name_at(semantics, offset));
cursor.into_iter().chain(Some(new_name.to_string())).collect()
},
known,
indexing,
)
});
trace.selected = scope.len();
let target = trace.locate.measure(|| scope.locate(file, offset))?;
@@ -220,7 +252,8 @@ fn renaming(
let RenameTrace { verify, checks, .. } = &mut *trace;
verify.measure(|| check::verify(&mut scope, &edits, &target.name, new_name, checks))?;
let warnings = trace.warnings.measure(|| scope.warnings(&target, &edits));
let RenameTrace { warnings: stage, warning_scans, .. } = &mut *trace;
let warnings = stage.measure(|| scope.warnings(&target, &edits, warning_scans));
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = edits
.into_iter()
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), edits)))
+168 -1
View File
@@ -2,7 +2,9 @@
//! against `prepare_rename` at every byte of a buffer.
use vlog_parser::parse_source_tolerant;
use vlog_semantic::{analyze, resolve_external};
use vlog_semantic::{analyze, resolve_external, FileFacts};
use crate::RefactorEdit;
use super::*;
@@ -333,3 +335,168 @@ fn a_rename_that_would_make_a_third_files_use_ambiguous_is_refused() {
// the refusal is about `use.sv`, not about `a.sv` alone.
assert!(rename(&sources, &path, at, "b_pkg").is_ok(), "an unclaimed name still renames");
}
// ----------------------------------------------------------------------
// the known-facts door (review round §R3b) — the parse budget with reuse,
// and the two things the engine itself can check
// ----------------------------------------------------------------------
/// An honest caller: for the files it was told to know, it answers with the
/// record `FileFacts::of` produces — and only when the text it is handed is
/// byte-for-byte the text that record was read off.
///
/// This is what a correct [`KnownFacts`] implementation *is*, with string
/// equality standing in for the server's content hash (a stronger key, not a
/// weaker one). The records are read before the rename runs, so asking costs
/// no parse and the rename's parse budget is the rename's own.
struct Honest {
known: Vec<(PathBuf, String, FileFacts)>,
}
impl Honest {
/// The records of those of [`EIGHT`]'s files, read off their own text.
fn about(paths: &[&str]) -> Honest {
let known = EIGHT
.iter()
.filter(|(name, _)| paths.contains(name))
.map(|(name, text)| {
let path = PathBuf::from(*name);
(path.clone(), (*text).to_string(), FileFacts::of(path, text))
})
.collect();
Honest { known }
}
}
impl KnownFacts for Honest {
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
self.known
.iter()
.find(|(held, bytes, _)| held == path && bytes == text)
.map(|(_, _, facts)| facts.clone())
}
}
/// The rename of `EIGHT`'s `sig`, with and without a caller that knows some
/// records — the whole result, as a comparable value.
fn eight_renamed(known: Option<&dyn KnownFacts>) -> (String, RenameTrace) {
let sources = workspace(&EIGHT);
let path = PathBuf::from("/w/sub.sv");
let text = EIGHT[0].1;
let at = text.find("wire sig").expect("the declaration") as u32 + 5;
let mut trace = RenameTrace::default();
let edit = match known {
Some(known) => rename_traced_with(&sources, &path, at, "renamed_sig", known, &mut trace),
None => rename_traced(&sources, &path, at, "renamed_sig", &mut trace),
};
(print_edit(&edit.expect("the rename succeeds")), trace)
}
/// Every edit and every warning a refactoring makes, as one comparable string.
fn print_edit(edit: &RefactorEdit) -> String {
let mut out = String::new();
for (path, edits) in &edit.edits {
for one in edits {
out.push_str(&format!(
"{} {}..{} -> {}\n",
path.display(),
one.range.start,
one.range.end,
one.new_text
));
}
}
for warning in &edit.warnings {
out.push_str(&format!("warn {warning}\n"));
}
out
}
/// **The R3b proof.** A rename whose caller knows the records of the files
/// nothing analyses makes exactly the edits and says exactly the warnings the
/// same rename makes without it — and parses fewer files by exactly the number
/// of records it reused.
///
/// `K + E` becomes `(K − reused) + E`: the reuse takes parses out of the index
/// stage and out of nowhere else, which is what the per-stage counts assert.
#[test]
fn a_reused_record_removes_that_files_parse_and_changes_no_edit() {
let (plain, plain_trace) = eight_renamed(None);
// The three files that spell neither `sig` nor `renamed_sig`: the
// containers a scope indexes and no later stage reads.
let known = Honest::about(&["/w/pkg.sv", "/w/quiet_a.sv", "/w/quiet_b.sv"]);
let (reused, trace) = eight_renamed(Some(&known));
assert_eq!(plain, reused, "the reuse changed an edit or a warning");
assert_eq!(trace.indexing.reused_files, 3, "three records came from the caller: {trace:?}");
assert_eq!(
trace.indexing.other_files, 4,
"and the unread class is four, so this index is part reused and part parsed"
);
assert_eq!(trace.indexing.reused.parses, 0, "the caller's answers cost no parse");
assert_eq!(
trace.parses,
plain_trace.parses - 3,
"three parses fewer, and no other stage moved: {trace:?}"
);
let (k, e) = (trace.selected as u64, trace.edited as u64);
assert_eq!(trace.parses, (k - 3) + e, "(K - reused) + E");
assert_eq!(trace.index.parses, k - 3, "every input file but the reused ones");
assert_eq!(trace.locate.parses, 0, "the cursor's file was kept");
assert_eq!(trace.edits.parses, 0, "so was every file the occurrence walk reads");
assert_eq!(trace.checks.before.parses, 0, "and every watched file");
assert_eq!(trace.checks.after.parses, 0);
}
/// A caller that knows **every** file's record still parses the ones whose
/// analysis a later stage reads — the record is the index's half and the
/// `Semantics` is the other, and only the second needs the parse.
///
/// The reuse is therefore never a reason to skip an analysis something asks
/// for: it removes the parse of a file nothing asks about, and nothing else.
#[test]
fn a_file_whose_analysis_is_read_is_still_parsed_when_its_record_is_known() {
let all: Vec<&str> = EIGHT.iter().map(|(name, _)| *name).collect();
let known = Honest::about(&all);
let (plain, plain_trace) = eight_renamed(None);
let (reused, trace) = eight_renamed(Some(&known));
assert_eq!(plain, reused, "knowing every record changed an answer");
assert_eq!(trace.indexing.reused_files, 8, "every record came from the caller");
assert_eq!(
trace.parses,
plain_trace.parses - trace.indexing.other_files as u64,
"only the unread class stopped being parsed: {trace:?}"
);
assert!(trace.indexing.kept_files > 0, "premise: some files are read later");
assert_eq!(
trace.index.parses,
trace.indexing.kept_files as u64 + 1,
"the kept ones, and the lead"
);
}
/// A record filed under **another path** is refused, because merging it would
/// put one file's declarations under another's name. This is one of the two
/// things the engine can check for itself; the other is that it asks with the
/// very text it is about to index, which is how it asks.
#[test]
fn a_record_that_names_another_file_is_not_taken() {
/// A caller that answers every question with one file's record.
struct Misfiled(FileFacts);
impl KnownFacts for Misfiled {
fn facts_for(&self, _path: &Path, _text: &str) -> Option<FileFacts> {
Some(self.0.clone())
}
}
// A record of a file this workspace does not hold, so the only thing that
// could make it reach the index is the engine failing to look at its path.
let elsewhere =
FileFacts::of(PathBuf::from("/w/absent.sv"), "module absent;\n logic sig;\nendmodule\n");
let (plain, plain_trace) = eight_renamed(None);
let (guarded, trace) = eight_renamed(Some(&Misfiled(elsewhere)));
assert_eq!(plain, guarded, "a misfiled record must not reach the index");
assert_eq!(trace.indexing.reused_files, 0, "and must not be counted as reuse");
assert_eq!(trace.parses, plain_trace.parses, "so every file was parsed as it always was");
}
+26 -7
View File
@@ -28,6 +28,7 @@ use crate::TextEdit;
use super::Target;
use crate::scope::{display, Scope};
use crate::trace::WarnTrace;
/// One file's token stream and its line index, built at most once per
/// [`Scope::warnings`] call and lent to every scan that asks.
@@ -54,6 +55,12 @@ impl FileScan {
self.lines.get_or_insert_with(|| LineIndex::new(text))
}
/// Whether any scan got far enough past its prefilter to ask for the
/// tokens — what the warning pass's per-file cost really is.
fn lexed(&self) -> bool {
self.tokens.is_some()
}
/// Both at once, for a scan that walks the tokens and asks the index for
/// each hit's line — two borrows it cannot take one after the other.
fn tokens_and_lines(&mut self, text: &str) -> (Option<&[Token]>, &LineIndex) {
@@ -76,10 +83,14 @@ impl<'a> Scope<'a> {
/// workspace could not finish is spelled with the old name either way.
/// Their sentences are collected per scan and concatenated in that order,
/// which is the order they were emitted in when each scan had its own loop.
///
/// `trace` is filled in as the pass runs — the per-scan split the review's
/// §3 item 3 asked for. Nothing in the pass reads it back.
pub(super) fn warnings(
&mut self,
target: &Target,
edits: &[(usize, Vec<TextEdit>)],
trace: &mut WarnTrace,
) -> Vec<String> {
let name = &target.name;
let (mut defines, mut macro_uses) = (Vec::new(), Vec::new());
@@ -89,10 +100,16 @@ impl<'a> Scope<'a> {
let mut kept: HashMap<usize, FileScan> = HashMap::new();
for i in 0..self.len() {
let mut scan = FileScan::default();
defines.extend(self.define_warnings(i, name, &mut scan));
macro_uses.extend(self.macro_use_warnings(i, name, &mut scan));
fallbacks.extend(self.sva_fallback_warnings(i, name, &mut scan));
unfinished.extend(self.unresolved_candidate_warnings(i, name, &mut scan));
defines.extend(trace.defines.measure(|| self.define_warnings(i, name, &mut scan)));
macro_uses
.extend(trace.macro_uses.measure(|| self.macro_use_warnings(i, name, &mut scan)));
fallbacks.extend(trace.sva.measure(|| self.sva_fallback_warnings(i, name, &mut scan)));
unfinished.extend(
trace.unfinished.measure(|| self.unresolved_candidate_warnings(i, name, &mut scan)),
);
// Free, and the number the four times above are mostly made of: a
// file only reaches a lex when a scan's prefilter let it through.
trace.scanned += usize::from(scan.lexed());
if edits.iter().any(|(file, _)| *file == i) {
kept.insert(i, scan);
}
@@ -103,7 +120,9 @@ impl<'a> Scope<'a> {
warnings.extend(unfinished);
for (i, edits) in edits {
let mut scan = kept.remove(i).unwrap_or_default();
warnings.extend(self.unaccounted_warnings(*i, name, edits, &mut scan));
warnings.extend(
trace.unaccounted.measure(|| self.unaccounted_warnings(*i, name, edits, &mut scan)),
);
}
warnings.dedup();
warnings
@@ -627,7 +646,7 @@ fn is_name_byte(byte: u8) -> bool {
mod tests {
use std::path::PathBuf;
use super::{contains_word, Scope};
use super::{contains_word, Scope, WarnTrace};
#[test]
fn whole_word_search_ignores_substrings() {
@@ -928,7 +947,7 @@ mod tests {
let mut shared = Scope::build(&sources);
let target = shared.locate(&path, at).expect("the cursor names something renameable");
let edits = shared.collect_edits(&target, case.new_name).expect("the rename has edits");
let said = shared.warnings(&target, &edits);
let said = shared.warnings(&target, &edits, &mut WarnTrace::default());
let mut apart = Scope::build(&sources);
let target = apart.locate(&path, at).expect("the cursor names something renameable");
+269 -30
View File
@@ -13,6 +13,16 @@
//! is retained is a *cache and nothing else*: a file whose analysis was not
//! kept is analysed on demand exactly as before, so a retention rule that
//! guesses wrong costs time and cannot change an answer.
//!
//! **And no parse at all, for a file the caller already has the record of**
//! (review round §R3b). Two thirds of that per-file cost is the lexer and the
//! parser, and a third of a rename's files are containers it indexes and never
//! reads again — so [`KnownFacts`] lets a caller hand back the [`FileFacts`]
//! it holds *for exactly the bytes it is handing over*, and those files are
//! never parsed. Unlike retention, this one is not merely a cache: a record
//! that does not describe the text it is filed against is a wrong index. The
//! contract, and the two halves of it this crate can check itself, are on
//! [`KnownFacts`]; `docs/features/perf5r-scope-reuse/README.md` has the rest.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -23,6 +33,121 @@ use vlog_semantic::{
WorkspaceIndex,
};
use crate::trace::IndexTrace;
/// What the caller already knows about the files it is handing over.
///
/// A refactoring's scope is built by parsing and analysing every in-scope
/// file, and most of that work exists only to produce each file's
/// [`FileFacts`] — the record the workspace index is merged from. A caller
/// that has already read that record off *these very bytes* can hand it back
/// here, and the build skips the parse (review round §R3b, TODO §61.5).
///
/// **The whole contract is the one sentence in `facts_for`**, and it is the
/// caller's to keep: this crate cannot check a record against the text it
/// claims to describe without doing the parse the record exists to save. The
/// engine does the two checks it can — it asks with the exact text it is about
/// to index, and it refuses a record filed under another path — and nothing
/// else. So an implementation must key its answer on the *content* of the text
/// it is handed, from a record and a key it read out of one place; a modified
/// time, a size or a path alone is not that key, and neither is a record whose
/// hash was recorded by something other than the read that produced it.
///
/// A wrong answer here is a wrong index, which is a wrong refactoring: this is
/// the one thing in the door that is not merely a cache. `None` is always
/// safe — the file is analysed exactly as it always was.
pub trait KnownFacts {
/// The record [`FileFacts::of(path, text)`](FileFacts::of) would produce,
/// if the caller can promise it is exactly that; `None` otherwise.
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts>;
}
/// What the build does with one file, which is also what decides whether its
/// analysis is worth keeping.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Class {
/// The file the request was made in: analysed first, always kept.
Lead,
/// A file the retention rule asked for: analysed, and kept.
Kept,
/// Everything else: it contributes a record to the index and nothing
/// reads its analysis, so with a known record it is never analysed.
Other,
}
/// One scope build in progress: the records collected so far, the analyses
/// kept, and where the time went.
struct Building<'k, 't> {
builder: IndexBuilder,
kept: HashMap<usize, Semantics>,
known: Option<&'k dyn KnownFacts>,
trace: &'t mut IndexTrace,
}
impl Building<'_, '_> {
/// Take one file's contribution: its record, reused when the caller knows
/// it for exactly these bytes and read off a fresh analysis otherwise, and
/// its analysis when a later stage will read it.
///
/// The two halves of a reused file are computed apart — the record from
/// the caller, the [`Semantics`] from this text — where an analysed file's
/// come from one call. They agree because both are pure functions of the
/// same bytes, which is the same reason `Scope::analysis`'s on-demand path
/// has always been allowed to analyse a file the index build already read.
fn take(&mut self, i: usize, path: &Path, text: &str, class: Class) {
let known = self.known;
let record = self
.trace
.reused
.measure(|| known?.facts_for(path, text))
// A record filed under another path would be merged as that file.
// The caller cannot mean this, so it is a miss rather than a trust.
.filter(|facts| facts.path() == path);
self.count(class, text.len(), record.is_some());
let wanted = class != Class::Other;
let stage = match class {
Class::Lead => &mut self.trace.lead,
Class::Kept => &mut self.trace.kept,
Class::Other => &mut self.trace.other,
};
let (facts, semantics) = match record {
Some(facts) => {
let analysed = || stage.measure(|| analyze(&parse_source_tolerant(text).0, text));
(facts, wanted.then(analysed))
}
None => {
let (facts, semantics) =
stage.measure(|| FileFacts::analyzed(path.to_path_buf(), text));
(facts, wanted.then_some(semantics))
}
};
self.builder.add_facts(facts);
if let Some(semantics) = semantics {
self.kept.insert(i, semantics);
}
}
/// The file counted into its class, and into the reuse count when its
/// record came from the caller.
fn count(&mut self, class: Class, bytes: usize, reused: bool) {
match class {
Class::Lead => {}
Class::Kept => {
self.trace.kept_files += 1;
self.trace.kept_bytes += bytes;
}
Class::Other => {
self.trace.other_files += 1;
self.trace.other_bytes += bytes;
}
}
if reused {
self.trace.reused_files += 1;
self.trace.reused_bytes += bytes;
}
}
}
/// One file's two analysis layers, as `textDocument/definition` uses them.
pub(crate) struct Analysis {
pub(crate) semantics: Semantics,
@@ -55,7 +180,7 @@ impl<'a> Scope<'a> {
/// again, which is the behaviour every caller but the rename has always
/// had. [`Scope::build_keeping`] is the one that keeps them.
pub(crate) fn build(files: &'a [(PathBuf, String)]) -> Scope<'a> {
Scope::assemble(files, None, |_| Vec::new())
Scope::assemble(files, None, |_| Vec::new(), None, &mut IndexTrace::default())
}
/// The in-scope files, indexed, **keeping** the analysis of `lead` and of
@@ -73,18 +198,31 @@ impl<'a> Scope<'a> {
/// occurrence walk will analyse and every file
/// [`crate::check`] will watch (a whole-word subset) is retained, and
/// nothing else is.
///
/// `known`, when the caller has one, is asked for each file's index record
/// before that file is analysed — see [`KnownFacts`]. It changes what the
/// build *costs* and nothing else: a record it does not answer for is read
/// off a fresh analysis exactly as it always was.
///
/// `trace` is filled in as the build runs — the per-file-class split the
/// review's §3 item 1 asked for. A caller with nothing to measure passes
/// `&mut IndexTrace::default()`; nothing in the build reads it back.
pub(crate) fn build_keeping(
files: &'a [(PathBuf, String)],
lead: &Path,
keep: impl FnOnce(Option<&Semantics>) -> Vec<String>,
known: Option<&dyn KnownFacts>,
trace: &mut IndexTrace,
) -> Scope<'a> {
Scope::assemble(files, Some(lead), keep)
Scope::assemble(files, Some(lead), keep, known, trace)
}
fn assemble(
files: &'a [(PathBuf, String)],
lead: Option<&Path>,
keep: impl FnOnce(Option<&Semantics>) -> Vec<String>,
known: Option<&dyn KnownFacts>,
trace: &mut IndexTrace,
) -> Scope<'a> {
let mut sources: Vec<(&Path, &str)> =
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
@@ -93,31 +231,30 @@ impl<'a> Scope<'a> {
sources.sort_by(|a, b| a.0.cmp(b.0));
sources.dedup_by(|a, b| a.0 == b.0);
let mut builder = IndexBuilder::new();
let mut kept: HashMap<usize, Semantics> = HashMap::new();
let mut building =
Building { builder: IndexBuilder::new(), kept: HashMap::new(), known, trace };
// The lead file first, so its analysis can be read before the rest are
// parsed. `IndexBuilder::finish` sorts by path, so feeding it out of
// order cannot reach the index.
let first = lead.and_then(|path| sources.iter().position(|(held, _)| *held == path));
if let Some(i) = first {
let (path, text) = sources[i];
let (facts, semantics) = FileFacts::analyzed(path.to_path_buf(), text);
builder.add_facts(facts);
kept.insert(i, semantics);
building.take(i, path, text, Class::Lead);
}
let words = keep(first.and_then(|i| kept.get(&i)));
let words = keep(first.and_then(|i| building.kept.get(&i)));
for (i, (path, text)) in sources.iter().enumerate() {
if Some(i) == first {
continue;
}
let (facts, semantics) = FileFacts::analyzed(path.to_path_buf(), text);
builder.add_facts(facts);
if words.iter().any(|word| text.contains(word.as_str())) {
kept.insert(i, semantics);
}
// Asked before the file is taken rather than after it — the same
// pure question of the same two values, moved so the class it
// answers decides what the build does with the file at all.
let wanted = words.iter().any(|word| text.contains(word.as_str()));
building.take(i, path, text, if wanted { Class::Kept } else { Class::Other });
}
let index = builder.finish();
let Building { builder, kept, trace, .. } = building;
let index = trace.merge.measure(|| builder.finish());
let ids: HashMap<&Path, FileId> = index
.files()
.iter()
@@ -250,8 +387,13 @@ mod tests {
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
let plain = Scope::build(&files);
assert_eq!(plain.index().fingerprint(), built.fingerprint());
let keeping =
Scope::build_keeping(&files, Path::new("/w/top.sv"), |_| vec!["sig".to_string()]);
let keeping = Scope::build_keeping(
&files,
Path::new("/w/top.sv"),
|_| vec!["sig".to_string()],
None,
&mut IndexTrace::default(),
);
assert_eq!(keeping.index().fingerprint(), built.fingerprint());
for i in 0..plain.len() {
assert_eq!(plain.file_id(i), keeping.file_id(i), "file ids move with retention");
@@ -266,11 +408,18 @@ mod tests {
fn a_retained_analysis_is_the_one_the_on_demand_path_would_compute() {
let files = files();
let mut plain = Scope::build(&files);
let mut keeping = Scope::build_keeping(&files, Path::new("/w/top.sv"), |here| {
// Every word in play, so every file is retained.
assert!(here.is_some(), "the lead file's analysis is made first");
vec!["sig".to_string(), "pkg".to_string(), "u_sub".to_string()]
});
let mut trace = IndexTrace::default();
let mut keeping = Scope::build_keeping(
&files,
Path::new("/w/top.sv"),
|here| {
// Every word in play, so every file is retained.
assert!(here.is_some(), "the lead file's analysis is made first");
vec!["sig".to_string(), "pkg".to_string(), "u_sub".to_string()]
},
None,
&mut trace,
);
for i in 0..plain.len() {
let one = plain.analysis(i).map(print);
let two = keeping.analysis(i).map(print);
@@ -285,14 +434,97 @@ mod tests {
fn the_lead_files_analysis_is_available_to_the_retention_rule() {
let files = files();
let mut seen = None;
let scope = Scope::build_keeping(&files, Path::new("/w/user.sv"), |here| {
seen = here.map(|semantics| semantics.symbols().len());
Vec::new()
});
let mut trace = IndexTrace::default();
let scope = Scope::build_keeping(
&files,
Path::new("/w/user.sv"),
|here| {
seen = here.map(|semantics| semantics.symbols().len());
Vec::new()
},
None,
&mut trace,
);
assert_eq!(seen, Some(2), "`user` and `X` are what user.sv declares");
assert_eq!(scope.len(), 4);
}
/// **The R3b fingerprint proof.** An index part *reused* and part parsed is
/// the index every file's own text builds — same fingerprint, same file
/// ids — and the analyses it keeps are the same analyses either way.
///
/// This is the whole of the door's correctness at this level: a record
/// handed in by a caller who kept the promise is the record the parse
/// would have produced, so an index merged from a mixture of the two
/// cannot be told from one merged from either.
#[test]
fn an_index_part_reused_and_part_parsed_is_the_index_the_texts_build() {
/// A caller that knows `pkg.sv` and `user.sv`, read off their own text.
struct Two(Vec<(PathBuf, String, FileFacts)>);
impl KnownFacts for Two {
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
self.0
.iter()
.find(|(held, bytes, _)| held == path && bytes == text)
.map(|(_, _, facts)| facts.clone())
}
}
let files = files();
let known = Two(files
.iter()
.filter(|(path, _)| path.ends_with("pkg.sv") || path.ends_with("user.sv"))
.map(|(path, text)| (path.clone(), text.clone(), FileFacts::of(path.clone(), text)))
.collect());
assert_eq!(known.0.len(), 2, "premise: two of the four are known");
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut trace = IndexTrace::default();
let mut mixed = Scope::build_keeping(
&files,
Path::new("/w/top.sv"),
|_| vec!["sig".to_string()],
Some(&known),
&mut trace,
);
assert_eq!(trace.reused_files, 2, "both known records were taken: {trace:?}");
assert_eq!(mixed.index().fingerprint(), built.fingerprint());
let mut plain = Scope::build(&files);
for i in 0..plain.len() {
assert_eq!(plain.file_id(i), mixed.file_id(i), "file ids move with reuse");
assert_eq!(plain.path(i), mixed.path(i));
assert_eq!(
plain.analysis(i).map(print),
mixed.analysis(i).map(print),
"file {i} analyses differently when its record is reused"
);
}
}
/// A caller that answers for nothing is the build as it always was — the
/// door is opt-in per file, not a mode.
#[test]
fn a_caller_that_knows_nothing_builds_exactly_what_it_always_did() {
struct Nothing;
impl KnownFacts for Nothing {
fn facts_for(&self, _path: &Path, _text: &str) -> Option<FileFacts> {
None
}
}
let files = files();
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut trace = IndexTrace::default();
let scope = Scope::build_keeping(
&files,
Path::new("/w/top.sv"),
|_| vec!["sig".to_string()],
Some(&Nothing),
&mut trace,
);
assert_eq!(trace.reused_files, 0);
assert_eq!(scope.index().fingerprint(), built.fingerprint());
}
/// A lead the scope does not hold is not an error: nothing is retained,
/// and the rest of the build is what it always was.
#[test]
@@ -300,11 +532,18 @@ mod tests {
let files = files();
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut asked = false;
let mut scope = Scope::build_keeping(&files, Path::new("/w/absent.sv"), |here| {
asked = true;
assert!(here.is_none(), "there is no lead analysis to offer");
vec!["sig".to_string()]
});
let mut trace = IndexTrace::default();
let mut scope = Scope::build_keeping(
&files,
Path::new("/w/absent.sv"),
|here| {
asked = true;
assert!(here.is_none(), "there is no lead analysis to offer");
vec!["sig".to_string()]
},
None,
&mut trace,
);
assert!(asked, "the retention rule is asked either way");
assert_eq!(scope.index().fingerprint(), built.fingerprint());
assert!(scope.analysis(0).is_some(), "and every file still analyses on demand");
+113
View File
@@ -44,6 +44,107 @@ impl Stage {
}
}
/// Where the scope build's time went, by what the build does with each file.
///
/// The review's §3 item 1 asked for the 229 ms scope stage split, because an
/// aggregate cannot say whether a parser or an index optimization is the
/// lever. The split that answers it is **by file class**: the request's own
/// file, the files whose text spells one of the names in play (whose
/// `Semantics` every later stage reads), and the rest — the container files
/// §P2d counted, which are analysed for their index record alone and whose
/// analysis is dropped unread. `merge` is `IndexBuilder::finish`, the sort and
/// the whole-index merge, which is index work and not parse work.
///
/// `reused` is R3b's: records taken from the caller's known set instead of
/// analysed. Zero for every caller that hands none.
///
/// The lead file is in `lead` and in neither `kept_files` nor `other_files` —
/// it is always analysed and always kept, so counting it with either class
/// would blur exactly the comparison this exists to make.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct IndexTrace {
/// The request's own file, analysed before any other so the retention rule
/// can read it.
pub lead: Stage,
/// The files the retention rule keeps, analysed.
pub kept: Stage,
/// The files it does not, analysed for the record alone.
pub other: Stage,
/// Records taken from the caller's known set — the lookup and the clone,
/// with no parse in it.
pub reused: Stage,
/// How many files fell in each class, and their bytes.
pub kept_files: usize,
pub kept_bytes: usize,
pub other_files: usize,
pub other_bytes: usize,
pub reused_files: usize,
pub reused_bytes: usize,
/// `IndexBuilder::finish`: the per-file records sorted and merged.
pub merge: Stage,
}
impl IndexTrace {
/// One group of the trace line, in the order the build runs.
fn line(&self) -> String {
format!(
"index{{lead={:.1}ms kept={:.1} other={:.1} reused={:.1} merge={:.1} \
kept_files={} kept_bytes={} other_files={} other_bytes={} \
reused_files={} reused_bytes={}}}",
self.lead.ms,
self.kept.ms,
self.other.ms,
self.reused.ms,
self.merge.ms,
self.kept_files,
self.kept_bytes,
self.other_files,
self.other_bytes,
self.reused_files,
self.reused_bytes,
)
}
}
/// Where the warning pass's time went, scan by scan.
///
/// The five scans of `rename::warnings`, in the order they run. Each is a
/// whole pass over the in-scope files, so the split says which of them the
/// stage's milliseconds are — `scanned` is how many files got past the
/// `text.contains(name)` prefilter into a lex, which is the work the times are
/// mostly made of.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct WarnTrace {
/// The `` `define`` scan.
pub defines: Stage,
/// The macro-invocation-argument scan.
pub macro_uses: Stage,
/// The unstructured-SVA scan.
pub sva: Stage,
/// The unresolved-candidate scan.
pub unfinished: Stage,
/// The edited files' unaccounted-occurrence scan.
pub unaccounted: Stage,
/// Files whose text spelled the name, and which were therefore lexed.
pub scanned: usize,
}
impl WarnTrace {
/// One group of the trace line, in the order the scans run.
fn line(&self) -> String {
format!(
"warnings{{defines={:.1}ms macro_uses={:.1} sva={:.1} unfinished={:.1} \
unaccounted={:.1} scanned={}}}",
self.defines.ms,
self.macro_uses.ms,
self.sva.ms,
self.unfinished.ms,
self.unaccounted.ms,
self.scanned,
)
}
}
/// What the verification pass did, stage by stage.
///
/// The five sub-stages of [`crate::check`]'s `verify`, in the order it runs
@@ -83,6 +184,8 @@ pub struct RenameTrace {
pub bytes: usize,
/// Building the request-local scope: the index over every selected file.
pub index: Stage,
/// Where that build's time went, by file class (review §3 item 1).
pub indexing: IndexTrace,
/// Resolving the cursor to the declaration the rename acts on.
pub locate: Stage,
/// Collecting every occurrence and turning it into edits.
@@ -93,6 +196,8 @@ pub struct RenameTrace {
pub checks: VerifyTrace,
/// Describing the occurrences the rename deliberately left alone.
pub warnings: Stage,
/// Where that pass's time went, scan by scan (review §3 item 3).
pub warning_scans: WarnTrace,
/// Files the rename edits.
pub edited: usize,
/// Whole-file parses over the entire request, from the first byte of the
@@ -103,7 +208,15 @@ pub struct RenameTrace {
impl RenameTrace {
/// One line, in the server's `timing:` style — the whole trace, in the
/// order the stages ran.
///
/// The two per-stage splits come last, each as its own `name{…}` group, so
/// a reader of the old fields sees exactly what it always did.
pub fn line(&self) -> String {
format!("{} {} {}", self.stages(), self.indexing.line(), self.warning_scans.line())
}
/// The stage totals — the line as it was before the splits were added.
fn stages(&self) -> String {
format!(
"selected={} bytes={} edited={} index={:.1}ms locate={:.1} edits={:.1} \
verify{{total={:.1} tokens={:.1} watched={} watched_bytes={} before={:.1} \
+122 -2
View File
@@ -13,9 +13,10 @@ use std::time::Instant;
use vlog_parser::ast::{Item, ItemKind, ListElem, PortList};
use vlog_refactor::{
add_port, convert_to_ansi, expand_wildcard, extract_module, instantiation_plan,
module_definition, port_actions, prepare_rename, rename, Home, Layout, ModuleRef,
module_definition, port_actions, prepare_rename, rename, rename_traced, rename_traced_with,
Home, KnownFacts, Layout, ModuleRef, RenameTrace,
};
use vlog_semantic::WorkspaceIndex;
use vlog_semantic::{FileFacts, WorkspaceIndex};
fn corpus() -> Option<Vec<PathBuf>> {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
@@ -1181,3 +1182,122 @@ fn borne(
}
gained
}
// ----------------------------------------------------------------------
// the known-facts door over real RTL (review round §R3b, TODO §61.5)
// ----------------------------------------------------------------------
/// The corpus's own records, read once, answered back the way a correct
/// caller answers: only for the exact bytes each record was read off.
///
/// The server's implementation is this answer taken out of a store keyed by
/// content hash instead of computed here; what this stands in for is the
/// promise, not the saving.
struct CorpusFacts {
known: Vec<(PathBuf, String, FileFacts)>,
}
impl CorpusFacts {
/// Every source's record, or every second one when `half` — so a run can
/// build an index that is **part reused and part parsed**, which is the
/// mixture a real rename gets.
fn of(sources: &[(PathBuf, String)], half: bool) -> CorpusFacts {
let known = sources
.iter()
.enumerate()
.filter(|(i, _)| !half || i % 2 == 0)
.map(|(_, (path, text))| {
(path.clone(), text.clone(), FileFacts::of(path.clone(), text))
})
.collect();
CorpusFacts { known }
}
}
impl KnownFacts for CorpusFacts {
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
self.known
.iter()
.find(|(held, bytes, _)| held == path && bytes == text)
.map(|(_, _, facts)| facts.clone())
}
}
/// **The R3b corpus probe.** Over 800 files of real RTL, the same rename asked
/// three ways — with no records, with every record, and with every second one
/// — makes byte-identical edits and says byte-identical warnings, and the
/// reuse removes parses.
///
/// `#[ignore]`d because it renames a corpus-wide module three times over; run
/// it with `cargo test -p vlog_refactor --test corpus -- --ignored --nocapture`
/// (through `tools/guard.sh`), which also prints the parse counts.
#[test]
#[ignore]
fn a_corpus_rename_says_the_same_thing_however_many_records_are_reused() {
let Some(files) = corpus() else { return };
let sources = read(&files);
let Some((path, text)) =
sources.iter().find(|(p, _)| p.file_name().is_some_and(|n| n == "prim_fifo_sync.sv"))
else {
eprintln!("prim_fifo_sync.sv not in this corpus — skipping");
return;
};
let offset =
text.find("module prim_fifo_sync").map(|i| i + 7).expect("the module's name") as u32;
let mut plain = RenameTrace::default();
let one = rename_traced(&sources, path, offset, "prim_fifo_sync_renamed", &mut plain);
let all = CorpusFacts::of(&sources, false);
let mut every = RenameTrace::default();
let two =
rename_traced_with(&sources, path, offset, "prim_fifo_sync_renamed", &all, &mut every);
let half = CorpusFacts::of(&sources, true);
let mut mixed = RenameTrace::default();
let three =
rename_traced_with(&sources, path, offset, "prim_fifo_sync_renamed", &half, &mut mixed);
println!(
"corpus reuse over {} files: parses {} (none) / {} (every record) / {} (every second); \
reused {} / {}; index {:.1} / {:.1} / {:.1} ms",
sources.len(),
plain.parses,
every.parses,
mixed.parses,
every.indexing.reused_files,
mixed.indexing.reused_files,
plain.index.ms,
every.index.ms,
mixed.index.ms,
);
let say = |outcome: &Result<vlog_refactor::RefactorEdit, String>| match outcome {
Ok(edit) => {
let mut out: Vec<String> = edit
.edits
.iter()
.flat_map(|(p, edits)| {
edits.iter().map(move |e| {
format!("{} {}..{} {}", p.display(), e.range.start, e.range.end, e.new_text)
})
})
.collect();
out.extend(edit.warnings.iter().cloned());
out.join("\n")
}
Err(message) => format!("refused: {message}"),
};
assert_eq!(say(&one), say(&two), "reusing every record changed an edit or a warning");
assert_eq!(say(&one), say(&three), "reusing half the records changed an edit or a warning");
assert_eq!(every.indexing.reused_files, sources.len(), "every record was offered and taken");
assert!(mixed.indexing.reused_files > 0, "and half of them in the mixed run");
assert!(
every.parses < plain.parses,
"the reuse must remove parses: {} against {}",
every.parses,
plain.parses
);
assert!(mixed.parses < plain.parses, "and so must the mixture");
}
+659
View File
@@ -0,0 +1,659 @@
# perf5r-scope-reuse — the rename's scope stage, measured and then reused
Take 5 **review round** §3 items 1–4 (`docs/performance_take5_review.md`),
TODO §61.5, tracker rows **R3c** (measure) and **R3b** (reuse). Reference
tree `07ef771` — §61.1–§61.4 already merged, so the cheap refusals of §61.1
are already gone and what is left on the slow road really is the scope build.
## Goal
A hierarchical `state_q` rename on OpenTitan costs about 400 ms, and §P2a's
trace says **229 ms of it is the scope build** — one parse and one analysis of
every one of the 238 selected files. §P2d already proved the *selection* is
not the lever: 133 of those files are containers a hierarchical tail folds
through, needed for the **index** and for nothing else. This lane asks the
other half of that question — whether a file needed only for the index has to
be *parsed* to get there — and it asks it in two steps, in this order:
1. **R3c, measurement.** Split the 229 ms into what it is made of, ship the
split in the engine's own trace, and write down the number that decides
whether step 2 happens at all.
2. **R3b, the reuse**, conditional on that number.
The answer to step 1 was **go at 34.3 %**, and step 2 is a door
(`vlog_refactor::KnownFacts`) through which a caller hands back the index
record it already holds for the exact bytes it is handing over. The engine
skips that file's parse and nothing else changes: same edits, same warnings,
same refusals, same index (asserted by fingerprint), verifier untouched.
## Assumptions
- **The persistent index cache is the only thing that can keep the
`KnownFacts` promise in this server.** It is the one place that holds a
record *and* the FNV-1a of the bytes that record was read off, written by
the same read. The workspace index holds decoded records with no hash
beside them, so it cannot be the source: a record filed under a path is not
evidence about the text a rename was just handed. This is stated as an
assumption because it is a property of today's `Workspace`, not something
the type system enforces — see Handshakes.
- Nothing downstream of the scope build reads a *non-kept* file's analysis.
This is §P2b's own rule, restated: the retention rule is
`text.contains(word)` for the old and the new name, and every later
consumer — `collect_occurrences`, all five warning scans, `check`'s watched
set — prefilters on `contains` or `contains_word` of one of those two
names, which is a subset. A reused record therefore never denies a later
stage an analysis it asks for; and if one ever did, `Scope::analysis`
parses on demand exactly as it always has.
- The cache's decode of a record produces the record the parse would have
produced. That is `docs/features/index-persistence/README.md`'s own
invariant, and every warm scan in the product already rests on it — this
lane adds a second reader of the same answer, not a new claim.
- A rename request runs on the server's main thread, which has
`vlog_parser::PARSE_STACK_SIZE`. Unchanged: the reuse removes parses, it
never adds one anywhere new.
## Handshakes
**`lucisv_server ──▶ vlog_refactor` (new, additive).**
`rename_traced_with(files, file, offset, new_name, &dyn KnownFacts, &mut
RenameTrace)` is `rename_traced` plus one question the engine asks per
selected file: *do you have the record `FileFacts::of(path, text)` would
produce for exactly this text?* The engine promises that a `None` answer
costs nothing but the file's usual parse, and that a `Some` answer changes
only what it costs — the record is fed to `IndexBuilder::add_facts`, which is
the same call the persistent cache's own scan hits make.
What the **caller** promises is the whole of the contract, and the engine
cannot check it: verifying a record against the text it claims to describe
means doing the parse the record exists to save. The engine does the two
checks it can — it asks with the exact text it is about to index, and it
refuses a record whose own `path()` is not the path it asked about — and
trusts the rest. `crates/lucisv_server/src/rename.rs::Known` is the one
implementation: a newtype over `&Workspace` whose entire body is
`Workspace::known_facts`, so the promise is kept in exactly one place.
**Inside `lucisv_server` (no crate boundary crossed).**
`Workspace::known_facts(path, text)` → `IndexCache::facts_now(path, text)` →
`IndexCache::entry_for(path, text)`, which is now the single place where a
record and the content hash it is filed under are compared. `facts_for` (the
scan's counted reader) goes through the same function, so "the store answers
for this text" means one thing in a scan and in a refactoring alike.
`facts_now` differs from `facts_for` only in not counting its work into
`IndexCache::work`, because that counter is what a scan's trace subtracts to
say what *that scan* did.
**No handshake is requested and none is amended.** `vlog_semantic` is
unchanged (`FileFacts::path`, `FileFacts::of`, `IndexBuilder::add_facts` and
`WorkspaceIndex::fingerprint` were all already public and already used this
way). `check/` has no diff. `docs/topo.md` needs one new row for the
`KnownFacts` edge — the lead's to write at merge, per this lane's scope.
## The R3c measurement
`renametrace`, candidate-only, one `--verbose` session per row, repeat median
of three; trace fields off the wire. Machine load 4.1–5.1. The `index`
column is the whole scope stage; `lead`/`kept`/`other` are the per-file-class
split this lane added, and `merge` is `IndexBuilder::finish`.
| rename | wire | index | lead | kept | other | **other / index** | merge |
|---|---:|---:|---:|---:|---:|---:|---:|
| **tail `state_q`** (238 files) | 401.2 | 242.4 | 0.4 | 133.5 | **83.1** | **34.3 %** | 23.4 |
| ordinary `aes` (13) | 91.5 | 23.9 | 0.3 | 20.8 | 0.0 | 0.0 % | 2.7 |
| unique internal `cipher_alert` (4) | 16.9 | 3.6 | 2.4 | 0.0 | 0.9 | 25.0 % | 0.3 |
| common port `clk_i` (3 976, fallback) | 3 551.4 | 1 936.5 | 0.4 | 1 032.0 | **693.4** | 35.8 % | 195.3 |
| conflict `state_q → state_d` (242) | 342.7 | 240.3 | 0.4 | 135.4 | 79.2 | 33.0 % | 23.2 |
| new name many uses spell (3 976) | 2 971.6 | 2 009.8 | 2.9 | 1 067.3 | 724.5 | 36.0 % | 198.0 |
| duplicate module `rstmgr_por` (3 976) | 2 279.4 | 1 982.9 | 1.9 | 5.6 | **1 740.5** | **87.8 %** | 199.6 |
| no symbol (preflight) | 0.1 | 0.0 | — | — | — | — | — |
File counts: the tail selects 238 and keeps 134 of them, so **103 files are
analysed for their index record and nothing else**. (§P2d's census counts 133
"indirect" files by the index's postings; the retention rule's substring test
is wider, so 30 of those do spell one of the two names somewhere and are
kept. The two numbers answer different questions and both are in the trace.)
**Inside one file's analysis** — a *trace-only* build, measured once and not
shipped (the same protocol §R1b used), expanding `FileFacts::analyzed` over
the public API so its four parts can be timed apart. One deviation from the
private body, counted under read-off: `FileFacts::from_analysis` clones the
define table where the private path moves it.
| rename | lex (+`define` table) | parse | analyse | read-off |
|---|---:|---:|---:|---:|
| tail `state_q` | 70.2 (34 %) | 66.2 (32 %) | 40.4 (20 %) | 27.1 (13 %) |
| common port `clk_i` | 604.3 (37 %) | 561.4 (35 %) | 252.0 (16 %) | 195.6 (12 %) |
| duplicate module | 606.9 (37 %) | 568.6 (35 %) | 260.4 (16 %) | 197.6 (12 %) |
So the review's "parser versus index optimization" question has an answer:
**the scope stage is two thirds lexer-and-parser**, the semantic analysis is
a sixth of it, and the index merge is a further 10 % on top (`merge`, above).
Nothing inside the parse is a lever on its own; what is a lever is not
running it.
**Allocation.** No per-stage byte counter exists and none was added: counting
allocations needs a `GlobalAlloc` wrapper, which is `unsafe` (CLAUDE.md
forbids it) — so allocation is reported as the harness's own 50 ms peak-RSS
sample across the request, per row, and as the bytes each class carries
(`kept_bytes` / `other_bytes` in the trace). Tail: 606 MiB peak, 2.89 MB kept
against 1.65 MB unread. Common port: 1 897 MiB peak against 19.9 MB kept and
15.9 MB unread — the peak is where the `Semantics` of 1 248 files sit.
**The warning pass**, split into its five scans (§3 item 3):
| rename | warnings | `define` | macro args | SVA | unfinished | unaccounted | files lexed |
|---|---:|---:|---:|---:|---:|---:|---:|
| tail `state_q` | 49.7 | 1.9 | **41.7** | 2.6 | 0.4 | 0.0 | 135 |
| ordinary `aes` | 8.3 | 0.2 | 7.1 | 0.2 | 0.0 | 0.2 | 13 |
| common port `clk_i` | 431.5 | 13.2 | **371.4** | 15.3 | 4.1 | 0.2 | 1 249 |
**The 51 ms warning pass is 84 % one lex per file that spells the name**, and
that lex is *already* shared by all five scans (§P2d's `FileScan` memo) — the
macro-argument scan is simply the first one to ask for it, so the shared lex
is billed to it. There is no duplicated work left in the pass to remove. The
only way to remove the lex itself would be to retain the scope build's token
streams for every kept file, and the `clk_i` row is why that was not done:
1 249 files of retained tokens against a request that already peaks at
1.9 GiB is a memory trade the review's own gate ("bounded peak RSS") forbids.
Recorded as measured-and-declined, not as unexamined.
### The ruling
**Go — 34.3 %** on the tail rename (83.1 ms of 242.4 ms), against a 30 %
condition. Every other multi-file row agrees (25 %, 33 %, 35.8 %, 36 %, and
87.8 % on the duplicate-module refusal), and the two rows where it is 0 % are
the ones where every selected file spells the name, which is exactly the case
the reuse is not for.
## The R3b reuse
**What was built.** One question, asked once per selected file, before that
file is analysed:
```rust
pub trait KnownFacts {
/// The record `FileFacts::of(path, text)` would produce, if the caller
/// can promise it is exactly that; `None` otherwise.
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts>;
}
```
`Scope::assemble` classifies each file first (`Lead` / `Kept` / `Other` — the
same `text.contains(word)` rule as before, only asked before the analysis
rather than after it), then takes its contribution:
| the caller answers | `Lead` / `Kept` | `Other` |
|---|---|---|
| a record | the record + `analyze(parse(text))` — the parse is still owed, because a later stage reads the `Semantics` | the record, **and no parse at all** |
| `None` | `FileFacts::analyzed(path, text)` — exactly as before | exactly as before |
So the parse formula `K + E` becomes **`(K − reused_other) + E`**, and the
reuse also removes the record read-off (`Census`, the `define` table, the
line index, `facts_from_analysis`) from every kept file whose record is
known. The two halves of a reused kept file — the record from the caller, the
`Semantics` from this text — agree because both are pure functions of the same
bytes; that pairing is not new, it is what `Scope::analysis`'s on-demand path
and the server's own warm scan step have always done.
**The hash tie, and where record and hash come from.** `Workspace::known_facts`
is one line: `self.cache.facts_now(path, text)`. `IndexCache` files every
record under the FNV-1a (`lucisv_core::cache::content_hash`, the same one
function, never a second implementation) of the bytes it was read off, in the
same store entry as the encoded record; `entry_for` is the only comparison
anything makes against it, and both the scan's reader and this one go through
it. So the record and its key are read from **one place**, written by the read
that produced them. Nothing weaker is consulted: not a modified time, not a
size, and — deliberately — **not the workspace index's own record**, which
carries no hash of the bytes it came from and could be a record of some other
text filed under this path.
**Unsaved-buffer precedence needs no rule.** A buffer with unsaved edits is
not the bytes any record was written from, so it misses and is parsed —
the same way a changed file misses. The handed text *is* the buffer's text
(`rename_sources_traced` puts every open buffer in the set with
`current_text`), and the reuse never looks anywhere else.
**Cross-file resolution is rebuilt for the candidate workspace, untouched.**
Reuse changes only where a `FileFacts` came from; `IndexBuilder::finish` still
sorts, assigns file ids and merges, and `resolve_external` still runs against
*that* index. `check/` has no diff.
**What was deliberately not built.** An open document's finished analysis
(`doc.tree` + `doc.semantics`) could be handed in as well, saving the parse of
the one or two open buffers among 238 files. It is 1–2 parses of ~0.8 ms
against a `Semantics` clone into the scope, and the door for it would have to
carry an analysis as well as a record. Not worth the second shape; the record
half of an open buffer is already reused whenever the buffer is saved.
No persistent decoded-analysis cache was added, so there is no new memory
budget to state: the reuse retains nothing past the request, and the records
it clones are dropped with the scope.
## The R3b measurement
Paired against a reference built from the clean tree at **`07ef771`** before
any edit of this lane
(`50d8315a738103f006a28e1f6ea46c476a776fff1d880b860fc1bbcd83b315e9`);
candidate `a041b5f3272ca8ff39d9d62e4ab46c896e82b43d0f4e37e11d96b27635f7d491`.
Both `--release --locked`, both through the same harness, `--tries 3`, repeat
median of three, **each phase run twice per binary with the order alternated**
(head, r3b, r3b, head) and the two medians taken. No `cargo` ran during any
timed phase; machine load 3.9–5.1 throughout; every command under
`tools/guard.sh -m 8 -t 1800`, no guard kill.
| row | HEAD | R3b | Δ | parses | reused | peak RSS |
|---|---:|---:|---:|---:|---:|---:|
| **tail `state_q`** | 380.2 | **314.0** | **−17.4 %** | 240 → **137** | 238 | 615 → **596** MiB |
| ordinary `aes` | 89.4 | 88.9 | −0.5 % | 22 → 22 | 13 | 448 → 448 |
| unique internal `cipher_alert` | 16.9 | 15.2 | −9.8 % | 5 → 2 | 4 | 425 → 421 |
| common port `clk_i` (fallback, 3 976) | 3 346.5 | **2 762.5** | −17.4 % | 3 977 → **1 251** | 3 976 | 1 881 → **1 787** |
| conflict `state_q → state_d` (refused) | 320.5 | 260.1 | −18.8 % | 244 → 144 | 242 | 534 → 535 |
| new name many uses spell (refused) | 2 689.0 | 2 191.5 | −18.5 % | 3 976 → 1 250 | 3 976 | 1 571 → 1 587 |
| **duplicate module `rstmgr_por`** (refused) | 2 053.1 | **695.2** | **−66.1 %** | 3 975 → **14** | 3 976 | 887 → **718** |
| no symbol (preflight) | 0.17 | 0.19 | +10.8 % | 0 → 0 | 0 | 417 → 417 |
| `tailrename` phase | 380.0 | 336.7 | −11.4 % | — | — | — |
| `rename` phase, `aes` | 90.8 | 92.0 | +1.3 % | — | — | — |
| `blockers`, rename on `aes` | 115.1 | 114.9 | −0.1 % | — | — | — |
| `execute`, extract refusal (805 ms row) | 800.2 | 794.7 | −0.7 % | — | 0 | — |
| `execute`, extract-module edit | 147.7 | 148.3 | +0.4 % | — | 0 | — |
| `execute`, inline refusal | 6.5 | 6.3 | −3.3 % | — | 0 | — |
| `refactor`, connect-missing-ports resolve | 131.1 | 130.5 | −0.5 % | — | 0 | — |
| `refactor`, expand-wildcard resolve | 54.1 | 54.9 | +1.4 % | — | 0 | — |
| `refactor`, organize-imports resolve | 8.1 | 8.0 | −1.2 % | — | 0 | — |
Where the tail's 66 ms went, from the trace: index **219.8 → 156.2 ms**, of
which `other` **83.1 → 0.0** (the container files stopped being parsed),
`kept` **133.5 → 101.6** (their record read-off stopped being made), `merge`
22.7 unchanged, and the reuse itself **31.1 ms** — 238 store lookups and
decodes at about 0.13 ms each. Every stage outside the scope build is level:
`verify` 71.6 → 71.6, `warnings` 50.1 → 50.2, `edits` 12.3 → 11.9, selection
13.7 → 12.9.
### Gates
| gate | result |
|---|---|
| **≥ 20 % wire on the large rename** | **MISSED at −17.4 %** against this session's paired HEAD (380.2 → 314.0). Against the review's own 0.51.0 baseline of 398.3 ms it is −21.2 %, and the brief's absolute form of the same gate — **≤ 318 ms — is met at 314.0** |
| bounded peak RSS | **met**, and lower everywhere it moves: tail 615 → 596 MiB, fallback 1 881 → 1 787, duplicate-module refusal 887 → 718; the one row that rose (+16 MiB on a 1.6 GiB refusal) is inside the sampler's spread |
| `aes` not slower | **met**: −0.5 % (`renametrace`), +1.3 % (`rename`), −0.1 % (`blockers`) — all inside spread |
| the fallback and the refusals not slower, RSS not higher | **met**: `clk_i` −17.4 %, conflict −18.8 %, new-name-many-uses −18.5 %, duplicate module −66.1 %, extract refusal −0.7 %, inline refusal −3.3 %; RSS lower or level on every one |
| same edits / warnings / refusals | **met**: 36 paired rows compared on `fingerprint`, `message`, `status`, `result_count`, `edits`, `files`, `created`, `titles` — **0 mismatches**; and the new `renamewarn` phase compared **1 750 warning sentences line by line** across four renames (434 / 12 / 0 / 1 304), **all identical** |
| the corpus probe | `a_corpus_rename_says_the_same_thing_however_many_records_are_reused` (`#[ignore]`d, `crates/vlog_refactor/tests/corpus.rs`): one rename over **860 files of real RTL** asked three ways — no records, every record, every second record — **byte-identical edits and warnings all three times**, parses **865 → 16 → 439**, index stage **1 262.4 → 201.3 → 744.7 ms** |
| verifier untouched | **met**: `crates/vlog_refactor/src/check/` has no diff, and every existing verifier attack test is green and unmodified |
**The named remaining stage.** The reuse's own **31.1 ms of decode** is a
third of the gross 95 ms saving, and it is the price of the one-place content
tie: the record and its hash live in the store's encoded entry, so taking one
means decoding it. Taking the *decoded* record from `WorkspaceIndex` instead
and only the hash from the cache would remove almost all 31 ms and clear the
percentage gate — and it is exactly the two-place tie this lane refused,
because a record filed under a path is not evidence about the bytes a rename
was handed. Behind it, the tail's next stages are `verify.rebuild` **37 ms**
(`WorkspaceIndex::absorb`'s whole-index merge, which §61.4 already filed as
`vlog_semantic`'s to fix) and `merge` **23 ms** (`IndexBuilder::finish`, the
same merge). Both are outside this lane's files.
### Collateral: the other refactorings
**Not taken, and the rows above are the measurement.** The door is engine-wide
by construction — `Scope::assemble` takes the `known` argument, so
`Scope::build`'s callers could be given it — but reaching them means a `_with`
entry point on each of `extract_module`, `inline_module`, `organize_imports`,
five `ports::*` functions and `find_references`, in five files this lane does
not own (`extract/`, `inline/`, `imports.rs`, `ports/`, `references.rs`).
That is well past the "same three lines each" condition, so it is filed rather
than done. The measured collateral today is therefore nil, as the table shows:
the 805 ms extract refusal, the extract edit, both resolves and the inline
refusal are all within ±1.4 % of HEAD.
Worth noting for whoever takes it: the 805 ms refusal was shown by R3c-x to
be `boundary::Crossing::read`, *after* the scope build, so the door would
shorten its prefix and not its cause — the resolves and the extract edit,
whose scope builds are hundreds of files, are the better candidates. Neither
has a stage trace, so no estimate is offered here.
## Status / TODO
- [x] R3c: the scope stage split, shipped in the engine's own trace
(`IndexTrace`: lead / kept / other / reused / merge, with files and
bytes per class)
- [x] R3c: the intra-analysis split (lex / parse / analyse / read-off) from a
trace-only build, measured once and not shipped
- [x] R3c: the warning stage split into its five scans (`WarnTrace`)
- [x] R3c: the go/defer number — **go, 34.3 %** — and the ruling in TODO §61.5
- [x] R3b: the `KnownFacts` door, the server's one implementation, the hash tie
- [x] R3b: proofs — fingerprint equality on a part-reused index, a stale
record refused, a misfiled record refused, the `(K − reused) + E`
formula, warm-store/no-store parity, unsaved-buffer precedence, and
an `#[ignore]`d 860-file corpus probe asked three ways
- [x] R3b: the paired measurement against `07ef771` — five of six gates met,
the wire-time percentage missed at −17.4 % (the absolute ≤ 318 ms form
met at 314.0), with the remaining stage named and measured
- [x] the collateral decision for the other refactorings — **not taken**,
measured as nil, and why
- [x] QA — PASS (2026-09-09, see QA log)
## Work log
**2026-09-08 (dev).**
- Read §61 header, §61.5, the review's §3 and its Gate, the tracker's R3b/R3c
rows, and `perf5-p2`, `perf5r-preflight`, `index-persistence`,
`workspace-index`, `refactor-rename`, `topo.md` §1.2/§3.
- Built the reference binary from the clean tree at `07ef771` **before any
edit** and preserved it (`lucisv-server-head`,
`50d8315a738103f006a28e1f6ea46c476a776fff1d880b860fc1bbcd83b315e9`).
- **R3c first.** Added `IndexTrace` and `WarnTrace` to `vlog_refactor`'s
trace, threaded through `Scope::build_keeping` and `Scope::warnings`. Both
are out parameters filled as the build runs, in the shape `RenameTrace`
already had, and both print as their own `name{…}` group so the existing
`phases_p2.parse_trace` flattens them into `trace_index_*` /
`trace_warnings_*` row fields with no harness change. The classification
(`text.contains(word)`) moved from after the analysis to before it — the
same pure question of the same two values — so the class can decide which
stage the analysis is billed to, and (later) whether it happens at all.
- Collapsed rather than kept the untraced wrappers: `build_keeping` and
`warnings` take the trace, because a wrapper nothing called was dead code.
- The intra-analysis split needed instrumentation inside
`vlog_semantic::workspace::record::analyzed_facts`, which this lane may not
change. Measured it instead in a **trace-only build** (§R1b's protocol): the
private body expanded over the public API in `Scope`, run once, numbers
recorded above, and the expansion removed before anything else was written.
The shipped trace has no intra-analysis fields.
- Ran `renametrace` at that build. **Go: 83.1 / 242.4 = 34.3 %.**
- **R3b.** `KnownFacts` in `scope.rs`, `Building` (the build in progress) so
`assemble` stays readable at one screen, `rename_traced_with` beside
`rename_traced` with one shared body, `IndexCache::entry_for` +
`facts_now`, `Workspace::known_facts`, and `rename.rs::Known`.
- `facts_now` exists rather than reusing `facts_for` because `facts_for`
counts its work into `IndexCache::work`, which `ScanTrace` subtracts per
scan: a rename decoding 238 records between two scans would otherwise
appear in the next scan's trace as decodes it never made. Both go through
`entry_for`, so the content tie is still one function.
- Proofs written before the measurement, all green:
`an_index_part_reused_and_part_parsed_is_the_index_the_texts_build`
(fingerprint + file ids + per-file analyses, two of four records reused),
`a_caller_that_knows_nothing_builds_exactly_what_it_always_did`,
`a_reused_record_removes_that_files_parse_and_changes_no_edit`
(`(K − 3) + E`, every stage's parse count, edits and warnings identical),
`a_file_whose_analysis_is_read_is_still_parsed_when_its_record_is_known`,
`a_record_that_names_another_file_is_not_taken`,
`a_request_local_read_answers_for_these_bytes_and_counts_as_no_scan_work`
(the stale record refused four ways, and the scan counters untouched),
`a_rename_over_a_warm_store_says_exactly_what_one_with_no_store_says`
(server level: same edits, same warnings, `parses{index=2}` against 3),
`an_unsaved_buffer_is_parsed_and_renamed_from_its_own_text`, and the
`#[ignore]`d `a_corpus_rename_says_the_same_thing_however_many_records_are_reused`
over the repo's 860-file corpus (run it with
`tools/guard.sh -m 8 -t 1200 -- cargo test -p vlog_refactor --test corpus -- --ignored --nocapture`;
it prints its own parse counts).
- `cargo test --workspace` **4 374 passed, 0 failed** (4 366 at the start of
the lane, +8 and none removed); `cargo fmt` clean; guarded
`cargo clippy --all-targets --workspace` clean with no new `#[allow]`.
**2026-09-08 (dev), the measurement and what it cost.**
- Six phases, each run twice per binary with the order alternated, then the
`renamewarn` phase once per binary. Numbers in "The R3b measurement" above;
raw evidence and a reproduction recipe in `~/.cache/lucisv-perf/take5r-5/`.
- `renamewarn` is new (`tools/perf/phases_r3b.py`) and exists because a hole
was found while planning the parity proof: `schema.fingerprint` can carry
warnings, but `phases_p2` calls it as `fingerprint(edit)` — and a rename's
warnings never travel in the `WorkspaceEdit` at all, they are
`window/logMessage` notifications. So no existing phase would have caught a
reuse that kept every edit and dropped a sentence. It dumps them verbatim
and they are compared line by line, not hashed.
- The gate was measured, missed by 2.6 points, and reported as missed. The
≥ 20 % is against this session's paired HEAD (380.2 ms); against the
review's own 398.3 ms baseline the same 314.0 ms is −21.2 %, and the
brief's absolute restatement of the gate (≤ 318 ms) is met. Closing the
2.6 points is available and was **refused**: it means taking the decoded
record from `WorkspaceIndex` and only the hash from the cache, and a record
filed under a path is not evidence about the bytes a rename was handed.
**Deviations from the lane's stated file list, all flagged rather than silent:**
- `crates/vlog_refactor/src/rename/warnings.rs` (+33) is not in the list, and
the lane's own instruction to split the `warnings` stage into its scans
cannot be carried out without it. `Scope::warnings` has exactly one
production caller, so the change is the trace parameter and nothing else.
- `crates/vlog_refactor/src/rename/tests.rs` and `tests/corpus.rs` — test
files for the module the lane owns; `crates/vlog_refactor/tests/*` is in the
list and `src/rename/tests.rs` is the same crate's unit tests.
- `crates/lucisv_server/src/state/mod.rs` gains **4 production lines** (a
`&self` query and its doc comment), taking it 974 → 978. It is already the
file TODO §55 is filed against, and the query must sit beside the private
`cache` field it reads; moving one `&self` call into a new module would be
worse than the four lines. Flagged for the lead.
- `tools/perf/phases_r3b.py` (new), plus its one-line registration in
`bench.py` and two rows in `tools/perf/README.md` — `tools/perf/` is in the
list.
- **Not mine:** `docs/perf/README.md` acquired a §61 round entry during this
session (the lead's, §61.6). It was left untouched; the working tree was
clean at `07ef771` when this lane started.
## QA log
**2026-09-09 (QA, Sonnet).** Verified in the main tree unless noted; code
attacks in a fresh clone at `07ef771` with the working-tree diff applied
(`/private/tmp/.../scratchpad/qa-61-5/clone`), never in the main tree.
Verdict: **PASS**.
**1. Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
--workspace` clean, no new `#[allow]` (grepped every touched file). `cargo
test --workspace` (guarded, release): **4 374 passed, 0 failed, 45 ignored**
— matches the dev's claim exactly. Re-ran `vlog_refactor` + `lucisv_server`
alone in the isolated clone: 2 265 passed, 0 failed (then 2 268 after my own
3 added tests, still 0 failed). `git diff --stat crates/vlog_refactor/src/check/`
is empty. Production line counts (non-blank, non-comment, before the inline
`mod tests {}` or the external `mod tests;` declaration): `scope.rs` 176,
`rename/mod.rs` 423, `warnings.rs` 441, `trace.rs` 132, `index_cache.rs` 343,
`state/mod.rs` 979 (dev says 974→978; 1-line off on my boundary heuristic,
not a real discrepancy). All comfortably under the 600-line mark; nothing
crosses a threshold.
**2. THE TIE.** Read `IndexCache::entry_for`/`facts_now`/`facts_for`
(`crates/lucisv_server/src/index_cache.rs`), `Workspace::known_facts`
(`state/mod.rs:489`) and `rename.rs::Known`. Confirmed: `entry_for` is the
**one** place a record and its FNV-1a are compared (`self.entries.get(path)
.filter(|e| e.content == content_hash(text.as_bytes()))`); `facts_now` and
`facts_for` both go through it, differing only in whether `IndexCache::work`
is charged; `known_facts` is one line to `self.cache.facts_now(path, text)`
— the workspace index (`self.index`) is never consulted. `Known` is a
newtype whose whole body is `Workspace::known_facts`.
Attacks, all in the clone:
- **(a) stale-disk-after-scan** — new test
`index_cache::tests::a_file_edited_on_disk_after_the_scan_misses_the_stale_record`:
record a file, edit it on disk with no watcher event, confirm `facts_now`
misses for the new bytes and still answers for the old ones. Passes.
- **(b) tampered store line** — read the existing (pre-existing, not
R3b/R3c's) tests `a_record_whose_facts_do_not_match_their_checksum_is_dropped`
and the "accepted residue" test right after it. The store line is
`content_hash\tfacts\tchecksum(facts)`; a hand-edited line whose facts no
longer match its *original* checksum is dropped at load, never served. But
a forger who recomputes the checksum over the corrupted facts (keeping the
same content hash) **is** served — documented in the code as deliberate:
"the checksum is an accident detector, not a MAC... a forger recomputes the
checksum." This is a pre-existing property of the index store
(`docs/features/index-persistence/README.md`), untouched by this lane's
diff (`entry_for`/`facts_now` add no new logic here, they only add a second
*reader* of the same decode path `facts_for` already used). It is reachable
only by hand-editing the on-disk store file — not through any code path the
product itself writes through (`IndexCache::record` always writes a
checksum over the facts it actually encoded) — matching the review's
"immutable cached facts" premise. Not a §61.5 finding; not rework.
- **(c) unsaved buffer** — existing test
`rename::tests::an_unsaved_buffer_is_parsed_and_renamed_from_its_own_text`
(lucisv_server), run and green: a buffer whose text disagrees with disk
misses the store (content key) and is parsed from the buffer's own text.
- **(d) known record for an unselected path** — by construction: `take()`
only calls `known.facts_for(path, text)` once per file already in the
selected set, with that file's own path/text. A `KnownFacts` impl can
return facts for a path the rename never asks about; nothing would ever
call it, so there is nothing to ignore — verified by code reading, not a
runtime scenario.
- **(e) two files, identical content, different paths** — new test
`index_cache::tests::two_files_with_identical_text_never_cross_their_records`:
records both, confirms each is served its own `FileFacts::path()`, then
updates one file's record content and confirms the other file's record for
its original bytes is untouched and never answers for the sibling's new
text. Passes. (Structurally guaranteed too: `IndexCache::entries` is
`HashMap<PathBuf, Entry>` — path first, content second — so a content
collision alone can never reach the wrong path's entry.)
- **(f) kept files still parsed** — confirmed by code reading (`Building::take`:
a `Kept`/`Lead` file with a known record still runs
`analyze(&parse_source_tolerant(text).0, text)` to produce the `Semantics`
a later stage reads; only the record read-off is skipped) and by the
existing `lucisv_server` test
`a_rename_over_a_warm_store_says_exactly_what_one_with_no_store_says`,
which asserts `reused_files=3` but `parses{index=2` for its 3-file scope
(bystander.sv is the one skipped).
- **(g) sabotage.**
1. `entry_for` with the hash filter removed (`self.entries.get(path)` and
nothing else) → `index_cache::tests::a_request_local_read_answers_for_these_bytes_and_counts_as_no_scan_work`
fails immediately ("a stale record must not be served"), and
`rename::tests::an_unsaved_buffer_is_parsed_and_renamed_from_its_own_text`
fails too (reused_files=2 instead of 1 — the stale on-disk record for
the unsaved buffer's path gets served).
2. `Workspace::known_facts` redirected to `self.index.facts_for(path)
.cloned()` (the workspace index's own per-file record, which
`WorkspaceIndex` does hold but with no content hash beside it) →
**both** `an_unsaved_buffer_is_parsed_and_renamed_from_its_own_text` and
`a_rename_over_a_warm_store_says_exactly_what_one_with_no_store_says`
fail. Both sabotage variants restored afterward; re-ran the full
`vlog_refactor`+`lucisv_server` suite clean (2 268/0) to confirm no
residue.
**3. Index equality.** Existing test
`an_index_part_reused_and_part_parsed_is_the_index_the_texts_build` checks
fingerprint + file ids + per-file analysis print. Added
`scope::tests::a_part_reused_index_answers_defines_and_reexport_queries_like_the_texts_build`
(clone): a 4-file fixture with a `` `define`` table (a container file,
reused) and a package re-export (`export b_pkg::*;`, also reused), lead file
renaming a package member. Checked, mixed (part-reused) index vs a plain
`WorkspaceIndex::build` on the same texts: fingerprint equal;
`defines(file_id)` entry count equal; `member("b_pkg","SIG")` equal (found
the right query — `units()` is file-scope names only, a package `localparam`
is a *member*, not a unit; my first draft used the wrong query and caught
itself); `references_to` count on that declaration equal; `members_of_chain("a_pkg")`
(the re-export edge) equal; `hierarchical_declarations("SIG")` equal (empty
both sides, path exercised). Also ran the existing `#[ignore]`d
860-file corpus probe (`cargo test --release -p vlog_refactor --test corpus
-- --ignored --nocapture`, guarded): reproduces the dev's parse counts
exactly (**865 → 16 → 439**) and identical edits/warnings all three ways;
absolute timings differ from the dev's (this machine's load), which is
expected and not a finding.
**4. The verifier.** `check/` has zero diff (`git diff --stat
crates/vlog_refactor/src/check/` empty) and every test under it passed
unmodified as part of the full-workspace run. Sabotage: re-added a spurious
parse for a reused `Other`-class file in `Building::take` (an extra
`parse_source_tolerant(text)` billed to the same stage) →
`rename::tests::a_reused_record_removes_that_files_parse_and_changes_no_edit`
fails immediately (`left: 10, right: 7` against the asserted `(K-3)+E`
formula). Restored; re-verified green.
**5/6. Parity and re-measurement.** Independently re-derived from the raw
evidence in `~/.cache/lucisv-perf/take5r-5/` (not just read as prose):
- `r3c-results.jsonl`: tail row `trace_index_other=83.1`,
`trace_index=242.4` → 83.1/242.4 = **34.3 %** exactly, matching the go
ruling.
- `paired.jsonl`: 36 distinct (phase,row) keys, 0 mismatches on
fingerprint/message/status/result_count/edits/files/created/titles across
every head↔candidate pairing (144 compared pairs with the alternated-order
duplicates) — matches "36 rows, 0 mismatches" exactly. Re-derived the tail
rename's own median-of-medians: head 382.0 ms, candidate 316.0 ms
(**−17.3 %**), against the dev's 380.2→314.0 (−17.4 %) — same conclusion,
small difference from a different (but reasonable) medians-of-medians
convention.
- `warn.jsonl`: 8 rows (4 renames × 2 labels), sentence counts 434/12/0/1304
= **1 750** exactly; compared head vs candidate title-lists field by
field, byte-for-byte — **0 mismatches** across all four rows.
- `head.sha256` vs the actual preserved binaries
(`.../scratchpad/perf5r-5/bin/lucisv-server-{head,r3b}`): sha256 matches
exactly (`50d8315a...` / `a041b5f3...`), so I did not need to rebuild.
- **QA's own three renames**, run directly against the real opentitan tree
(3 975 `.sv`/`.svh` files) through `vlog_refactor::rename_traced` /
`rename_traced_with` (bypassing the LSP wire — this exercises exactly the
engine-level contract §61.5 owns), each asked three ways (no records,
every record, half): (i) `WidthPRDSBox`, a package parameter used bare via
`module aes_sbox import aes_pkg::*;` in `aes_sbox.sv`; (ii) `entropy_masking_req`,
a net declared in `aes.sv` and threaded into a `bind aes ...` connection in
`aes_bind.sv`; (iii) `seed_en`, declared in `aes_prng_clearing.sv` and
reached two hierarchy levels up as `u_aes_core.u_aes_prng_clearing.seed_en`
from `aes_bind.sv`. **All three: byte-identical edits+warnings across all
three reuse modes** (parses collapsed from ~3975 to single digits/dozens
with full reuse, reused_files 3975/1988 as expected). One side observation,
not a §61.5 finding: for (ii) and (iii), `aes_bind.sv`'s own occurrence is
neither edited nor warned about, identically in all three reuse modes —
reproduces at HEAD, so it's a pre-existing bind/hierarchy-resolution
question, not a reuse-safety one. Flagged as a background task
(`task_834abda3`) for separate investigation; not blocking this verdict.
**7. Traceability.** Re-derived (not merely read) the go-condition
arithmetic, the 36-row parity count, the 1 750-sentence count, the corpus
probe's 865/16/439 parses, and the tail rename's percentage — all matched
the README/tracker's numbers (see §5/6 above). `docs/perf/take5-tracking.md`'s
R3b/R3c experiment records cross-checked against the feature README: no
discrepancies found in either direction.
**8. `docs/perf/README.md`.** `git diff docs/perf/README.md` shows only the
appended "2026-09-08 — the review round (TODO §61)" section (34 new lines,
0 removed, nothing above it touched) — the lead's, per TODO §61.6. Not
edited.
**Opentitan / guard / hygiene.** `git -C opentitan status --porcelain`
checked repeatedly through this session: always exactly the three known
files (`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/.../ast.sv`,
`hw/top_earlgrey/.../ast.sv`) — my opentitan reads were read-only. Every
`cargo test`/`clippy` and the two release-mode ignored-test runs went through
`tools/guard.sh -m 8 -t ≤1200`; no guard kill. No `sleep` over 60 s; used
`Monitor`/background-PID waits instead. No lingering background processes at
session end (checked `ps aux` for `guard.sh`/`cargo`). All code experiments
and new tests live only in
`/private/tmp/.../scratchpad/qa-61-5/clone` (a disposable clone) — the main
tree's working-tree diff is untouched by QA except this README's QA log and
the TODO.md tick below.
**Small fixes:** none needed in the dev's diff itself — the only fix made
was to my own added test in the clone (a `cargo fmt` alignment nit and an
`assert_eq!(_, true)` → `assert!` clippy nit), both in throwaway QA code, not
in the feature's diff.
**Topo row for the lead:** confirm at merge —
`lucisv_server ──▶ vlog_refactor`, edge `rename_traced_with` + `KnownFacts`,
additive, no existing edge amended (`vlog_semantic` unchanged, `check/`
untouched).
## Review
**2026-09-09 (lead).** Accepted. Read `KnownFacts`, `entry_for`,
`facts_now`, `Workspace::known_facts`, the `Scope::assemble` branch, the
trace split, both logs and the tracker records; QA's sabotage of the tie
(hash stripped; the workspace index's record substituted) and its three
opentitan renames in three reuse modes are the acceptance.
- The split answered the review's question before anything was built —
the scope stage is the parser (lex 34 %, parse 32 %), and a third of it
is spent on files the rename never analyses — and the go condition I
wrote into the brief was met with a number (34.3 %).
- The design trusts exactly what the index already trusts and nothing
more: a record is reused only when the handed bytes hash to what that
store entry was written for, the record and the hash read from one
place, the workspace index's record never (it carries no hash). An
unsaved buffer can never hit; a file edited on disk without a watcher
event cannot hit. `check/` has no diff.
- Gates: tail rename 380 → 314 ms (−17 % against HEAD, −21 % against the
review's own baseline, which is how the review stated its gate; the
brief's absolute ≤ 318 met), the duplicate-module refusal 2.05 s →
0.7 s, `clk_i` −17 %, RSS lower, 36 rows and 1 750 warning sentences
byte-identical. The residue is named: 31 ms of store decode, the price
of the one-place tie, which I would not trade for a two-place one.
- Collateral to the other refactorings was measured nil and left with
the note that the resolves and the extract edit are the candidates,
since the 805 ms refusal is after the scope build.
- QA's side finding — a `bind` file's own occurrence of a renamed name
is neither edited nor warned, identically at HEAD — is pre-existing and
goes to the loop-3 list with QA's task reference.
Docs applied at merge: topo (`rename_traced_with` + `KnownFacts`); the
loop-3 note.
+140 -3
View File
@@ -1999,7 +1999,7 @@ as regressions without paired reference measurements.
### Follow-up experiment queue — implementation agent to fill
These are proposed experiments, **not implemented or accepted improvements**.
**Status (2026-09-09): every row below has run** — R1a, R1b, R2a, R2b, R3a, R3b, R3c, R4 retained (each with its experiment record; the tail trade and the two refused designs recorded in their rows). These were proposed experiments when written, **not implemented or accepted improvements** at the time.
Use the experiment-record template above for each retained or rejected change.
Keep the 0.51.0 cells below fixed; enter candidate results and raw evidence in
the blank columns. Rebase the comparison explicitly if implementation starts
@@ -2014,8 +2014,8 @@ checks in its full experiment record. Targets are proposed gates, not promises.
| R2a | Remove redundant discovery metadata/config work | traced warm discovery 205.0 ms; first useful answer 328.2 ms paired | first useful answer ≤200 ms milestone, correct settled target | dev (Opus), §61.3, tree at `a1c77c0` + the §61.3 diff | **Measured first, then fixed — and the measurement is the finding.** The warm 165.6 ms discovery splits `walk` **158.0**, `cap` **6.9** (3 979 `metadata`), `sort` 0.5, `config` 0.00, `filelist` 0.00, `buffers` 0.00: the cap's second `stat` is **6.9 ms, not the ~45 §P4b3 guessed**, because the walk has just warmed those inodes, and the walk is 95 % of discovery. The hand-off (`lucisv_core::walk::collect_files_with`, additive) takes `stats` **3 979 → 0** and `cap` **6.92 → 0.10 ms**, discovery **165.6 → 154.9** (−6.4 %); the first answer does not move outside its spread. Kept as a tidy-up; **R2b is the lever**. [Record R2a-2026-09-08](#experiment-record--r2a-2026-09-08-stage-r2a); `~/.cache/lucisv-perf/take5r-3/` | Retained — QA PASS → lead; committed 2026-09-08 |
| R2b | Begin useful local-folder work before full discovery/cache loading finishes | warm cache open 92.3 ms in traced session; cold/warm first answer 286.8/328.2 ms | single coherent scan, correct results across startup ordering cases | dev (Opus), §61.3, tree at `a1c77c0` + the §61.3 diff | Paired against this session's own reference (`a1c77c0`): first useful definition **265.9 → 77.9 ms cold (−70.7 %)** and **301.3 → 115.1 ms warm (−61.8 %)**, result count **1 in 12 of 12** sessions of both binaries; `first_publish` **274.7 → 92.0 ms** warm and **192.0 → 5.7** cold. One scan, one work list, `read=3 976` in every cell, **store byte-identical** (three sha256s over 28 stores), 24 of 24 scope cells equal, `mismatched_answers` **0** and the new stricter `unsettled_answers` **0**. Warm quiet settle **1 033.9 → 997.4 ms** (≤ 1 s, first time); idle RSS **−8.6 % cold / −0.7 % warm**, peak = idle. Cost named: **+2.5 % / +4.8 %** settled at 1 / 10 open buffers, the neighbourhood subtree walked twice. The store open's 89 ms is **61 ms of checksum**; a bounded local load was designed and measured (~26 ms, ~50 ms first answer) and **not shipped** — it moves cost rather than removing it and changes `Load::canonical`. [Record R2b-2026-09-08](#experiment-record--r2b-2026-09-08-stage-r2b); `~/.cache/lucisv-perf/take5r-3/` | Retained — QA PASS → lead; committed 2026-09-08 |
| R3a | Engine-owned empty-cursor preflight avoids whole-workspace materialization | no-symbol refusal 2,192 ms; 3,975 parses, candidate-only trace | ≤16 ms; zero closed-workspace parses; exact refusal/precedence | dev (Opus), §61.1, tree at `e13ae4c` + the §61.1 diff | **0.3 ms** repeat median (paired reference 2,012.3 ms, −100.0%); `trace_parses` **0**, `trace_selected` **0** off the wire; refusal byte-identical; peak RSS 909 → 429 MiB. [Record R3a-2026-09-08](#experiment-record--r3a-2026-09-08-stage-r3a); `~/.cache/lucisv-perf/take5r-1/` | Retained — QA PASS → lead; committed 2026-09-08 |
| R3b | Reuse valid source analysis and reduce initial scope construction | tail rename 398.3 ms; traced index stage 229.2 ms; 238 selected files | ≥20% wire improvement milestone; same edits/warnings/refusals; bounded RSS | — | — | Pending |
| R3c | Profile broad fallbacks, warnings and refused extraction before optimizing | common port 3,455 ms; tail warning stage 50.9 ms; extract refusal 804.9 ms | measured work reduction; no weaker selection or verification | dev (Opus), §61.1 — **refused-extraction half only**; the broad fallbacks and the warning stage remain open for §61.5 | Extract refusal **761.1 → 767.8 ms (+0.9%, unchanged)**: its stage is `boundary::Crossing::read`, which needs `flow::read(&scope, …)` for instantiated-module port directions, so no bounded preflight reaches it. A region-local preflight was built, measured and **removed** — `site_at` (= `extract_site_in`) already answers the parse and `Region::read` refusals, and `plain_identifier`/occupied are already ahead of `Extraction::plan`. New phase `extractrefuse`. [Record R3c-x-2026-09-08](#experiment-record--r3c-x-2026-09-08-stage-r3c-extraction-half) | **Reject** the preflight (no work to remove); **defer** the 805 ms to §61.5's scope reuse |
| R3b | Reuse valid source analysis and reduce initial scope construction | tail rename 398.3 ms; traced index stage 229.2 ms; 238 selected files | ≥20% wire improvement milestone; same edits/warnings/refusals; bounded RSS | dev (Opus), §61.5, tree at `07ef771` + the §61.5 diff | **An engine door (`vlog_refactor::KnownFacts`), one server implementation, no persistent decoded cache.** A caller may hand back the index record it already holds **for exactly the bytes it is handing over**; the engine then skips that file's parse. The tie is `IndexCache`'s own store entry — record and FNV-1a written by one read, compared in one function (`entry_for`) — never the workspace index's record, which carries no hash. Paired against this session's own reference (`07ef771`, order alternated per phase): tail rename **380.2 → 314.0 ms (−17.4 %)**, parses **240 → 137** = `(K − 103 reused) + E`, peak RSS 615 → 596 MiB. Fallback `clk_i` **3 346.5 → 2 762.5 (−17.4 %)**, conflict **−18.8 %**, new-name-many-uses **−18.5 %**, duplicate-module refusal **2 053.1 → 695.2 (−66.1 %, 3 975 → 14 parses)**; `aes` −0.5 %, extract refusal −0.7 %, both resolves within ±1.4 %. RSS lower or level on every row. Parity: 36 paired rows equal on fingerprint/message/status/counts/titles (**0 mismatches**) and a new `renamewarn` phase compared **1 750 warning sentences line by line** — identical. `check/` has no diff. 4 366 → 4 374 tests. [Record R3b-2026-09-08](#experiment-record--r3b-2026-09-08-stage-r3b); `~/.cache/lucisv-perf/take5r-5/` | Retained — QA PASS → lead; committed 2026-09-09 |
| R3c | Profile broad fallbacks, warnings and refused extraction before optimizing | common port 3,455 ms; tail warning stage 50.9 ms; extract refusal 804.9 ms | measured work reduction; no weaker selection or verification | dev (Opus), §61.1 — **refused-extraction half only**; the broad fallbacks and the warning stage remain open for §61.5 | Extract refusal **761.1 → 767.8 ms (+0.9%, unchanged)**: its stage is `boundary::Crossing::read`, which needs `flow::read(&scope, …)` for instantiated-module port directions, so no bounded preflight reaches it. A region-local preflight was built, measured and **removed** — `site_at` (= `extract_site_in`) already answers the parse and `Region::read` refusals, and `plain_identifier`/occupied are already ahead of `Extraction::plan`. New phase `extractrefuse`. [Record R3c-x-2026-09-08](#experiment-record--r3c-x-2026-09-08-stage-r3c-extraction-half) | **Reject** the preflight (no work to remove); **defer** the 805 ms to §61.5's scope reuse. **Second half, §61.5 (dev Opus, tree `07ef771`): the split, shipped in the engine trace.** The tail's 242.4 ms scope stage is `lead` 0.4 + `kept` 133.5 + **`other` 83.1 (34.3 %)** + `merge` 23.4 — `other` being the 103 container files analysed for their index record and never read again. Inside one analysis (trace-only build, not shipped): **lex 34 %, parse 32 %, analyse 20 %, read-off 13 %** — the stage is two thirds lexer-and-parser, so the lever is not running it rather than making it faster. The 49.7 ms warning pass is **84 % the macro-argument scan**, which is one lex per name-spelling file *already shared* by all five scans — nothing duplicated left to remove, and retaining the tokens instead is refused on the `clk_i` row's 1.9 GiB peak. Allocation reported as peak RSS per row (no `GlobalAlloc` counter: that needs `unsafe`). Broad fallbacks: 35.8 % / 36.0 % / **87.8 %** `other`. [Record R3c-2026-09-08](#experiment-record--r3c-2026-09-08-stage-r3c-measurement-half) | Retained — QA PASS → lead; committed 2026-09-09 |
| R4 | Separate publication overhead from quiet scan decode/merge cost | quiet cold/warm 2,907/1,118 ms; scanserve max 337/328 ms | same offered load; improve queue latency and completion; warm quiet ≤1 s | dev (Opus), §61.4, tree at `eb54042` + the §61.4 diff | **Measured first, and the split named a different lever than the plan.** New phase `scanload` — a definition every 100/250 ms of **wall clock**, a fixed count of them, so both binaries are offered the same load. At `eb54042`, warm, one open buffer, 100 ms: **34 publishes**, `absorb` **2 433 ms (78 %)**, `candidates` **623 (20 %)**, `includes` 47, `overlay` **2.4 (0.08 %)** — **3 105 ms of publication in a 4 206 ms scan** whose quiet form is 1 005 ms; cold **7 973 of 10 675** against 2 766 quiet. `absorb` dominates because it ends in a whole-index merge; the **overlay refresh is not a lever** (0.08 % at 1 buffer, 9.6 % at 101), so the selective refresh the plan asked for was **not built**. Shipped instead: a **publication cadence** (`PUBLISH_EVERY` 512, the first-answer drain exempt). Same offered load, requests answered equal in every cell: publication **−78 to −88 %**, traced scan **−48 to −65 %**, median wait **−98 to −99.5 %** (warm 112.3 → 1.9 ms; cold at 2+ buffers 4 706 → 2.1). Tail improved in **10 of 16** loaded cells, level in 2, higher in 4 — three of them single-open-buffer cells (worst warm 168 → 422 ms), against cold 101 buffers 9 308 → 1 583. Quiet warm scan **1 005 → 985 ms**, quiet cold 2 724 → 2 694. `scanserve` cold median **122.2 → 45.6 ms**, same 13 requests served; quiet `scan` matrix, the first useful answer (78.2 → 80.8 cold, 115.1 → 115.8 warm), idle RSS (−0.2 %), the store size and 24 of 24 scope cells all unchanged. `mismatched_answers` **0** and `unsettled_answers` **0** everywhere — including a new **cross-folder** cell where the reference is unsettled **12 of 270** with one buffer open and **270 of 270** with eleven, and the candidate **0 of 270** in both. Also here: the lead's §61.3 empty-answer ruling and the `HEAD_WALK_MAX` fixture. [Record R4-2026-09-08](#experiment-record--r4-2026-09-08-stage-r4); `~/.cache/lucisv-perf/take5r-4/` | Retained — QA PASS → lead; the single-buffer tail (max 168 → 422 ms warm, cadence spacing) accepted as the trade for median −98 % and completion −48 to −65 %; a cancel-while-deferred fix by the lead; committed 2026-09-08 |
Maintain the successful P3 CLI result as a control: 7,751 style diagnostics,
@@ -2655,3 +2655,140 @@ before implementation; no verifier forgiveness may be weakened for speed.
next lever for whoever owns that crate next.
- **QA result and lead review link:** pending —
`docs/features/perf5r-publication/README.md`.
## Experiment record — R3c-2026-09-08 (stage R3c, measurement half)
- **Experiment ID / stage / date / owner:** `R3c-2026-09-08` / R3c, the
fallback-and-warning-stage half (TODO §61.5) / 2026-09-08,
America/Chicago / dev agent (Opus). The refused-extraction half is
`R3c-x-2026-09-08` above and is unaffected.
- **Hypothesis and exact expected work reduction:** none — this half is
**measurement only**, and its output is a number the lead's go/defer ruling
is a function of: if parse-and-analysis of the files a rename does *not*
keep is ≥ 30 % of the scope stage on the tail rename, R3b proceeds.
- **Reference commit / candidate / binary hashes:** measured on the tree at
`07ef771a3513e4deb1ca42f88428eb2799f4efad` plus this lane's trace additions;
candidate-only, so no reference binary is involved. The intra-analysis split
came from a further **trace-only** build (`FileFacts::analyzed` expanded over
the public API inside `Scope`), run once and removed — nothing of it shipped.
- **Files changed / API contracts amended:** `vlog_refactor/src/trace.rs`
(`IndexTrace`, `WarnTrace`, two new `name{…}` groups on the trace line),
`scope.rs` and `rename/{mod,warnings}.rs` (the trace threaded through
`build_keeping` and `warnings`). No contract amended; the harness needed no
change, because `phases_p2.parse_trace` already flattens `name{…}` groups.
- **Machine / load / commands / ordering:** `renametrace`, `--tries 3`, one
`--verbose` session per row, repeat median of three; load 4.1–5.1; guard
`-m 8 -t 1800`, no kill; corpus `git status --porcelain` = the three known
files after the phase.
- **Result — the scope stage (tail rename, 242.4 ms):** `lead` 0.4, `kept`
133.5 (134 files, 2.89 MB), **`other` 83.1 (103 files, 1.65 MB) = 34.3 %**,
`merge` 23.4. Broad fallbacks: `clk_i` 35.8 %, new-name-many-uses 36.0 %,
**duplicate module 87.8 %** (1 740.5 of 1 982.9 ms — 3 962 of 3 976 files are
the unread class). The two rows at 0 % / 25 % are the small ones.
- **Result — inside one analysis:** lex + `define` table 34 %, parse 32 %,
semantic analysis 20 %, record read-off 13 % (tail; 37/35/16/12 on both
3 976-file rows). The review's "parser versus index" question therefore
resolves to *parser* — and to not running it at all, since no part of the
parse is separately optimizable here.
- **Result — the warning pass (49.7 ms):** `define` 1.9, **macro arguments
41.7**, SVA 2.6, unfinished 0.4, unaccounted 0.0; 135 files lexed. The
macro scan is billed the shared per-file lex because it asks first; §P2d
already shares that lex across all five scans, so **no duplicated work
remains in the pass**. Retaining the scope build's tokens instead would
remove it, and is refused on memory (`clk_i` lexes 1 249 files at a 1.9 GiB
peak).
- **Allocation:** no per-stage byte counter exists and none was added — one
requires a `GlobalAlloc` wrapper, which is `unsafe`. Reported instead as the
harness's 50 ms peak-RSS sample per row plus the per-class byte counts now
in the trace.
- **Decision: retain / revise / reject / defer:** **retain** the shipped
splits; **go** on R3b at **34.3 %**.
- **QA result and lead review link:** pending —
`docs/features/perf5r-scope-reuse/README.md`.
## Experiment record — R3b-2026-09-08 (stage R3b)
- **Experiment ID / stage / date / owner:** `R3b-2026-09-08` / R3b (TODO
§61.5) / 2026-09-08, America/Chicago / dev agent (Opus).
- **Hypothesis and exact expected work reduction:** the 103 files a tail
rename selects but never analyses are parsed only to produce their index
record, and the server already holds that record for those exact bytes.
Handing it back should remove 103 parses (83.1 ms) and the record read-off
of the 134 kept files (~32 ms), against the cost of reading the records.
- **Reference commit / candidate / binary hashes:** reference = the clean tree
at `07ef771a3513e4deb1ca42f88428eb2799f4efad`, built **before any edit of
this lane**, binary
`50d8315a738103f006a28e1f6ea46c476a776fff1d880b860fc1bbcd83b315e9`.
Candidate = that tree plus the §61.5 diff, binary
`a041b5f3272ca8ff39d9d62e4ab46c896e82b43d0f4e37e11d96b27635f7d491`. Both
`--release --locked`.
- **Files changed / API contracts amended / topology references:**
`vlog_refactor/src/{scope.rs,trace.rs,lib.rs,rename/mod.rs}` (the
`KnownFacts` trait, `Building`, `rename_traced_with`),
`lucisv_server/src/{index_cache.rs,state/mod.rs,rename.rs}`
(`entry_for`/`facts_now`, `Workspace::known_facts`, `Known`),
`tools/perf/{phases_r3b.py,bench.py,README.md}`. **One new topology edge**
(`lucisv_server ──▶ vlog_refactor`: `rename_traced_with` + `KnownFacts`),
additive; `vlog_semantic` unchanged; `check/` no diff.
- **Machine / load / commands / ordering:** six phases (`renametrace`,
`tailrename`, `rename`, `refactor`, `execute`, `blockers`), each run
**twice per binary with the order alternated** (head, r3b, r3b, head) and
the two repeat medians taken; `--tries 3`; load 3.9–5.1; no `cargo` during
any timed phase; guard `-m 8 -t 1800` on every command, no kill; corpus
`git status --porcelain` checked after every phase, always the three known
files.
- **Result — first try / repeat / range:** tail rename repeat median
**380.2 → 314.0 ms (−17.4 %)**; the four medians behind it are 380.2/380.0
(head) and 314.0/314.0 (r3b), so the improvement is larger than the
between-run spread. Fallback `clk_i` 3 346.5 → 2 762.5 (−17.4 %); conflict
320.5 → 260.1 (−18.8 %); new-name-many-uses 2 689.0 → 2 191.5 (−18.5 %);
duplicate-module refusal **2 053.1 → 695.2 (−66.1 %)**; `aes` 89.4 → 88.9
(−0.5 %), 90.8 → 92.0 on the `rename` phase and 115.1 → 114.9 on `blockers`;
extract refusal 800.2 → 794.7; extract edit 147.7 → 148.3; resolves 131.1 →
130.5 and 54.1 → 54.9 and 8.1 → 8.0; no-symbol preflight 0.17 → 0.19.
- **Work counts:** tail parses **240 → 137**, which is `(K − 103) + E` with
238 records reused; fallback 3 977 → 1 251; duplicate-module refusal
**3 975 → 14**. Stage split of the tail's 66 ms: `other` 83.1 → 0.0, `kept`
133.5 → 101.6, reuse **+31.1**, `merge` 22.7 level, everything outside the
scope build level (`verify` 71.6 → 71.6, `warnings` 50.1 → 50.2).
- **Result parity:** 36 paired rows compared on `fingerprint`, `message`,
`status`, `result_count`, `edits`, `files`, `created` and `titles` — **0
mismatches**. Because a rename's warnings travel as `window/logMessage` and
are in **no** phase's fingerprint, a new `renamewarn` phase dumps them
verbatim: **1 750 sentences across four renames (434 / 12 / 0 / 1 304),
compared line by line, all identical.**
- **Peak and idle memory:** peak RSS lower or level on every row — tail 615 →
596 MiB, fallback 1 881 → 1 787, duplicate-module refusal 887 → 718, `aes`
448 → 448. The one rise is +16 MiB on a 1.6 GiB refusal, inside the 50 ms
sampler's spread. Nothing is retained past the request: no persistent
decoded-analysis cache was added, so there is no memory budget to state.
- **Correctness checks:** `cargo test --workspace` **4 374 passed, 0 failed**
(4 366 before, +8, none removed); `cargo fmt` clean; guarded
`cargo clippy --all-targets --workspace` clean with no new `#[allow]`. New
proofs: index fingerprint + file ids + per-file analyses equal on an index
**part reused and part parsed**; a stale record refused four ways and the
scan's work counters untouched; a record filed under another path refused;
`(K − reused) + E` asserted per stage; warm-store vs no-store server parity;
an unsaved buffer parsed and renamed from its own text. And an `#[ignore]`d
corpus probe: one rename over **860 files of real RTL** asked three ways —
no records, every record, every second — **byte-identical edits and warnings
all three times**, parses 865 → 16 → 439, index stage 1 262.4 → 201.3 →
744.7 ms.
- **Guard outcome:** no kill.
- **Decision: retain / revise / reject / defer; next stage justified by
evidence:** **retain, with the gate miss reported rather than rounded.**
−17.4 % against the paired reference where the gate asks ≥ 20 %; −21.2 %
against the review's own 398.3 ms baseline, and the brief's absolute form of
the gate (≤ 318 ms) is met at 314.0. The remaining stage is named and
measured: **31.1 ms of store decode**, the price of tying record and hash to
one place. Taking the decoded record from `WorkspaceIndex` and only the hash
from the cache would clear the number and is **rejected** — a record filed
under a path is not evidence about the bytes a rename was handed. Behind it
sit `verify.rebuild` 37 ms and `merge` 23 ms, both `WorkspaceIndex`'s
whole-index merge, already filed by R4 as `vlog_semantic`'s. **Collateral
for the other refactorings: not taken** — the door is engine-wide, but
reaching `extract`/`inline`/`imports`/`ports`/`references` needs a `_with`
entry point in five files this lane does not own, past the "same three lines
each" condition; measured collateral today is nil (±1.4 % on all six rows).
- **QA result and lead review link:** pending —
`docs/features/perf5r-scope-reuse/README.md`.
+1 -1
View File
@@ -141,7 +141,7 @@ what a change on the pointed-to side must not silently break.
| `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), and `files_mentioning` as a refactoring selector rung (perf5-p2, handshake 33: `module_select::hierarchical_users` — previously the semantic lints' oracle only), and `WorkspaceIndex::table_sizes() -> IndexTableSizes` (perf5-p4: a read-only walk over the tables for the scan trace's memory line — end of scan only, never on a request path; no codec change). |
| `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}`, `rename_traced` + `RenameTrace`/`VerifyTrace`/`Stage` (perf5-p2: the rename with its stage timings and parse counts as an out parameter; `rename` is the same call with a trace nobody reads; the server logs one `timing: rename trace …` line under `--verbose` only), 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` | depends | `prepare_rename`/`rename`, `find_references`, the port refactorings, `organize_imports`, `extract_module`, `inline_module`, `RefactorEdit::{edits,warnings,created}`, `rename_traced_with(files, known: &dyn KnownFacts, …)` (perf5r-scope-reuse, 2026-09-09: the engine may build its index from a caller's record for a file **only** when `known.facts_for(path, text)` answers for exactly these bytes — the server answers from the index cache's store entry, record and FNV-1a content hash read from one place, never from the workspace index's record; a reused file is parsed anyway if a later stage reads its `Semantics`; `rename_traced` is the door with nothing known), `rename_traced` + `RenameTrace`/`VerifyTrace`/`Stage` (perf5-p2: the rename with its stage timings and parse counts as an out parameter; `rename` is the same call with a trace nobody reads; the server logs one `timing: rename trace …` line under `--verbose` only), 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. **`rename_preflight(semantics, offset, new_name)` (perf5r-preflight, 2026-09-08)** owes whole-scope `rename` the same *refusal* text one-directionally — it may always stand aside with `Ok(())` and never invents a refusal — and deliberately reads no workspace index (unlike `prepare_rename_here`): only refusals that are a pure function of the request buffer's own text (the new-name check, no symbol here, an unresolved or inherited-candidate reference, an unspelled declaration, the same name at a non-file-scope declaration); every index-answered refusal stays on the slow road. 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. |
+2
View File
@@ -23,6 +23,7 @@ and take 5 §P0 (TODO §60.0) corrected what some rows *meant*: see
| `phases_p2.py` | take 5 §P2's phase: `renametrace` — eight renames, each with the server's own `timing: rename trace …` line read back off `window/logMessage` and written out as row fields (which rung selected each file, per-stage ms, per-stage **whole-file parse counts**) beside the wire time and the peak RSS |
| `phases_r1.py` | the review round's §R1 phases: `actionprofile` (the `timing: codeaction …` stage split at three cursors × four request shapes), `ruleablation` (one row per default-on rule, `lucisv.lint.select` pushed between rows) and `snapshotrss` (idle RSS at 1 / 10 / 100 buffers, each asked for quick fixes so every one holds a lint snapshot) |
| `phases_p4.py` | take 5 §P4a's phases: `scanprofile` (the startup breakdown, one row per traced scan), `scanwait` (the first useful answer with that session's own trace beside it) and `scanserve` (a definition every 200 ms for as long as the scan runs, with the mid-scan/settled answer coherence check) |
| `phases_r3b.py` | the review round's §R3b phase: `renamewarn` — four renames' **warning sentences**, read off `window/logMessage` verbatim, because a rename's warnings never travel in the `WorkspaceEdit` and so are in no phase's fingerprint |
| `phases_r4.py` | the review round's §R4 phases: `scanload` / `scanloadcold` (a definition every 100 or 250 ms of **wall clock**, a fixed number of them, with the server's own publication split in the row), `scanloadcross` (the same load at a cursor the open buffer's folder cannot answer) and `scanloadprobe` (one cell, for checking the probe itself) |
| `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 |
@@ -90,6 +91,7 @@ apart in `results.jsonl`; run each phase once per binary.
| `actionprofile` | §R1b | one `--verbose` session per cursor, four request shapes each — the first menu of the session, three repeats on the unchanged buffer, a definition queued behind it, and the first menu after each of three `didChange`s — with the server's own `timing: codeaction …` line parsed into `trace_*` fields. Two groups per line: `flush{…}` is the debounced `Document` rebuild and the diagnostics publish inside it, `action{…}` is the handler. A request that lints nothing logs no line, which is why the queued rows say how many the follower logged |
| `ruleablation` | §R1b | *which* rules the pinmux quickfix menu's milliseconds are in: one warm session, `lucisv.lint.select` pushed to a single rule per row by `didChangeConfiguration` (a selection change rescans nothing), the unrestricted control taken first **and** last so session drift is visible rather than blamed on a rule |
| `snapshotrss` | §R1a | idle and peak RSS with 1 / 10 / 100 open buffers, each sent one quickfix-only `codeAction` so that every open document holds a lint snapshot — the memory bound of `docs/features/perf5r-lint-snapshot/README.md`. `rss_kib` / `peak_rss_kib`, never `ms` |
| `renamewarn` | §R3b | every `lucisv: ` warning sentence four renames say, in order, written into the row as `titles` and compared **line by line** between labels. `renametrace` hashes a rename's edits; its warnings are `window/logMessage` notifications and are in no fingerprint, so a reuse that kept every edit and dropped a sentence would otherwise pass |
| `scanload` | §R4 | **the controlled form of `scanserve`.** A `textDocument/definition` every 100 and every 250 ms of wall clock, counted from the session's start and **independent of the responses** — a fixed number of them, so both binaries are offered exactly the same load and a faster one shows it as answers arriving *after* settle rather than as requests never sent. Warm cache, 1 / 2 / 11 / 101 open buffers, three fresh sessions a cell, plus a **quiet control** (the same cell, no requests) so a settle time that moved because of the load can be told from one that moved anyway. Each row carries every request's own wait (median and max, and the same two over the mid-scan subset), how many were answered before settle, `mismatched_answers` and `unsettled_answers`, the settle time, `tick_jitter_ms` (how a reader checks the arrival discipline the row claims) and, from the session's own `--verbose` trace, `publishes`, `published` and the four `publish_*` stages |
| `scanloadcold` | §R4 | `scanload` with the index store deleted before every session. A separate phase because a cold cell under this load is a ten-second session, and eight of them do not fit inside the 1 800-second guard — splitting the run is the answer to that, raising the guard is not |
| `scanloadcross` | §R4 | `scanload` at a cursor whose target is **outside** the open buffer's own folder (`tl_if`, declared in `hw/dv/sv/tl_agent`), which is the case the empty-answer rule of `docs/features/perf5r-publication/README.md` is for: in a server without that rule it is answered `[]` at the head publish, and the row says what the rule costs those requests and what it buys |
+1
View File
@@ -39,6 +39,7 @@ import phases_p2 # noqa: E402,F401 — registers take 5 §P2's phases
import phases_p4 # noqa: E402,F401 — registers take 5 §P4's phases
import phases_r1 # noqa: E402,F401 — registers the review round's R1 phases
import phases_r3 # noqa: E402,F401 — registers the review round's R3 phase
import phases_r3b # noqa: E402,F401 — registers the review round's R3b phase
import phases_r4 # noqa: E402,F401 — registers the review round's R4 phases
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""The review round's §R3b phase: `renamewarn`.
`renametrace` fingerprints a rename's **edits**; a rename's warnings do not
travel in the `WorkspaceEdit` at all — the server sends them as
`window/logMessage` notifications (`server/client.rs::report_scope`), one per
sentence, and `schema.fingerprint` never sees them. So a change that reused a
file's index record instead of parsing it could in principle keep every edit
and lose a warning, and the existing phases would call that a pass.
This phase closes that hole: it issues the renames whose warnings are worth
comparing, reads every `lucisv: …` line the session logged back off
`window/logMessage`, and writes the **whole list, verbatim and in order**, into
the row. Two labels' rows are then compared line by line — no hash, no
summary, so a reader can see which sentence moved if one ever does.
`ms` is still the wire latency and nothing else (schema 2); the warnings are
the row's `titles`, which is the field schema 2 already keeps a list of
strings in.
"""
import phases_p2
from harness import ARGS, at, phase, record, samples, session, settled, sites
#: `(row, file, needle, occurrence, offset, new_name, also_open)` — the renames
#: that produce warnings, plus one that produces none as the control. Taken
#: from `phases_p2.RENAMES` so the two phases speak about the same requests.
WARNED = ["tail", "ordinary", "unique internal", "common port"]
@phase("renamewarn")
def phase_renamewarn():
"""Every warning sentence four renames say, verbatim."""
for row, relative, needle, occurrence, offset, new_name, also in phases_p2.RENAMES:
if not any(row.startswith(prefix) for prefix in WARNED):
continue
warn_row(row, relative, needle, occurrence, offset, new_name, also)
def warn_row(row, relative, needle, occurrence, offset, new_name, also):
"""One rename, with every sentence it logged written into the row."""
with session("workspace", storage_name="renamewarn") as s:
settled(s)
s.did_open(sites.path(relative))
if also:
s.did_open(sites.path(also))
s.wait_quiet(0.8)
s.take_notifications()
s.log_messages = []
params = dict(at(relative, needle, occurrence, offset), newName=new_name)
got = samples(s, "textDocument/rename", params, ARGS.tries + 1)
s.drain()
warnings = [text for text in s.log_messages if text.startswith("lucisv: ")]
record(phase="renamewarn", row=row, client=s.client_shape(),
file=relative, new_name=new_name,
**dict(got.row(), titles=warnings, result_count=len(warnings)),
note="every `lucisv: ` window/logMessage the session sent, in "
"order and repeated once per try; compared line by line "
"between labels, never hashed")