Perf take 5 P2a–c (§60.2): rename reuses its analysis, verification untouched — a --verbose stage trace (the tail rename was 238 files, 717 parses, two thirds repeated), one parse+analysis per file inside the scope (FileFacts::analyzed, Scope::build_keeping), the after-index absorbed from the edited files' records with every verifier check unchanged and re-attacked; tail rename 780 → 420 ms, aes rename −25%, resolves −20%, parses K+E
This commit is contained in:
1 parent
dafa4f0500
commit
e51a2c7f21
23 files changed
+2443
-144
No files matched your search
@@ -5843,22 +5843,28 @@ Plan §P2a → §P2b/§P2c → §P2d only with proof. Handshake 33 (transitive
|
||||
rename/,check/,lib.rs}`, `vlog_semantic/src/workspace/{record.rs,
|
||||
index.rs,update.rs,mod.rs}` as the plan lists — the dev inspects the
|
||||
real paths first and names them in the README.
|
||||
- [ ] P2a: stage timings and work counts for the tail rename, `aes`,
|
||||
- [x] P2a: stage timings and work counts for the tail rename, `aes`,
|
||||
a unique internal name, `clk`/`rst_n`, an existing/conflicting
|
||||
new name, an unresolved new-name use, the all-sources fallback:
|
||||
selector time, selected paths + bytes with the reason each was
|
||||
included, parses/analyses, occurrence collection, before/after
|
||||
verification, serialization, peak RSS — behind a flag or the
|
||||
`--verbose` channel, never in the default output
|
||||
- [ ] P2b: one parse/analysis per file inside the request-local scope
|
||||
- [x] P2b: one parse/analysis per file inside the request-local scope
|
||||
(`FileFacts::from_analysis` the starting point); additive
|
||||
prepared-input API, the text API and its answers/refusals
|
||||
unchanged; no workspace-wide AST cache
|
||||
- [ ] P2c: the after-index from unchanged facts plus the edited files'
|
||||
- [x] P2c: the after-index from unchanged facts plus the edited files'
|
||||
one new analysis; untouched watched files keep local semantics
|
||||
and re-resolve externally; token identity, parse-diagnostic
|
||||
preservation, comments/attributes, before/after resolution all
|
||||
still checked; clone/merge/remap cost measured
|
||||
- [x] QA (P2a/P2b/P2c only): PASS — gates, hunk-by-hunk verifier review,
|
||||
sabotage/re-attack (dev's three pairs plus two of QA's own), wire
|
||||
parity (8 `renametrace` rows + 5 QA-chosen renames, old binary vs.
|
||||
candidate), parse-formula sabotage, RSS re-take, traceability; see
|
||||
the QA log in `docs/features/perf5-p2/README.md` (2026-09-07).
|
||||
Handshake 33 and P2d are **not** covered by this QA pass.
|
||||
- [ ] handshake 33 closed with tests (multi-level hierarchy, generated
|
||||
scopes, interface/package/class names, macros, duplicate modules,
|
||||
unsaved references) before P2d
|
||||
@@ -5866,9 +5872,16 @@ real paths first and names them in the README.
|
||||
unchanged; every edit, warning, ambiguous-use refusal,
|
||||
unresolved new-name capture and unsaved-buffer contribution
|
||||
compared against the whole-scope engine on adversarial cases
|
||||
- [ ] measured: tail rename ≥ 2× faster (stretch < 200 ms), `aes`
|
||||
- [~] measured: tail rename ≥ 2× faster (stretch < 200 ms), `aes`
|
||||
rename not slower, edit/warning parity exact; queued definition
|
||||
follows; tracker + experiment entries
|
||||
follows; tracker + experiment entries — **1.86×** (780.45 →
|
||||
419.86 ms), so the 2× target is **missed by 29.7 ms**; the
|
||||
measured remaining stage is `Scope::build`'s one parse of each of
|
||||
the 238 *selected* files (225 ms of 420), which only §P2d can
|
||||
reach. `aes` rename −24.8 % (not slower), every edit / warning /
|
||||
refusal fingerprint byte-identical, queued definition −24.5 %,
|
||||
whole-file parses 717 → **240 = K + E**. Experiments
|
||||
`P2a-2026-09-07`, `P2b-2026-09-07`, `P2c-2026-09-07`
|
||||
- [ ] QA: whole-scope parity suite, the verifier invariant (a faster
|
||||
partial edit is a failure), handshake-33 attacks, numbers re-taken
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ mod pairs;
|
||||
mod perf;
|
||||
mod ports;
|
||||
mod rename;
|
||||
mod rename_trace;
|
||||
mod selection;
|
||||
mod server;
|
||||
mod settings;
|
||||
|
||||
@@ -1120,9 +1120,15 @@ fn a_rename_before_and_after() {
|
||||
let _ = black_box(vlog_refactor::rename(&sources, &path, black_box(offset), "renamed"));
|
||||
});
|
||||
let rename_after = mean(20, || {
|
||||
let _ = black_box(crate::rename::rename(&ws, &uri, black_box(offset), "renamed"));
|
||||
let _ = black_box(crate::rename::rename_traced(
|
||||
&ws,
|
||||
&uri,
|
||||
black_box(offset),
|
||||
"renamed",
|
||||
&mut None,
|
||||
));
|
||||
});
|
||||
let fan_out = ws.rename_sources(&path, "sub", Some("renamed")).len();
|
||||
let fan_out = ws.rename_sources_traced(&path, "sub", Some("renamed")).0.len();
|
||||
// Building the file set at all, and the one rung of it that is a linear
|
||||
// walk over every file's records rather than a keyed lookup
|
||||
// (`WorkspaceIndex::files_spelling`, the new name's dangling-use rung —
|
||||
@@ -1130,7 +1136,7 @@ fn a_rename_before_and_after() {
|
||||
// it is the only part of the set builder whose cost grows with the
|
||||
// workspace rather than with the symbol.
|
||||
let file_set = mean(2_000, || {
|
||||
black_box(ws.rename_sources(black_box(&path), "sub", Some("renamed")));
|
||||
black_box(ws.rename_sources_traced(black_box(&path), "sub", Some("renamed")));
|
||||
});
|
||||
let spelling_rung = mean(2_000, || {
|
||||
black_box(ws.index().files_spelling(black_box("renamed")).count());
|
||||
@@ -1138,7 +1144,8 @@ fn a_rename_before_and_after() {
|
||||
|
||||
// A measurement of an answer that was not given is worthless.
|
||||
assert!(crate::rename::prepare(&ws, &uri, offset).is_ok());
|
||||
let (edit, _) = crate::rename::rename(&ws, &uri, offset, "renamed").expect("renames");
|
||||
let (edit, _) =
|
||||
crate::rename::rename_traced(&ws, &uri, offset, "renamed", &mut None).expect("renames");
|
||||
assert_eq!(edit.changes.map(|c| c.len()), Some(4), "the module and its three tops");
|
||||
|
||||
eprintln!(
|
||||
|
||||
@@ -20,6 +20,7 @@ use vlog_parser::LineIndex;
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::locate::display_name;
|
||||
use crate::rename_trace::SelectionTrace;
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
@@ -48,11 +49,19 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Result<PrepareRenameRe
|
||||
|
||||
/// The whole rename as a `WorkspaceEdit`, plus whatever the engine wants the
|
||||
/// user told. An `Err` is the engine's own sentence, returned verbatim.
|
||||
pub fn rename(
|
||||
/// `trace` is filled whenever the request got as far as asking the engine,
|
||||
/// refusals included, because a rename that refuses after 800 ms is exactly
|
||||
/// the kind this exists to explain (take 5 §P2a). Its two halves are the
|
||||
/// server's ([`SelectionTrace`]: which rung wanted which file) and the
|
||||
/// engine's ([`vlog_refactor::RenameTrace`]: where the time and the parses
|
||||
/// went); it reaches a user only through `--verbose`'s `timing:` channel, and
|
||||
/// a caller that wants none passes `&mut None`.
|
||||
pub fn rename_traced(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
trace: &mut Option<String>,
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
|
||||
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
|
||||
@@ -62,11 +71,18 @@ pub fn rename(
|
||||
// cursor on nothing has no fan-out to ask for, so the whole scope goes —
|
||||
// the engine will say so, and saying it is cheap either way.
|
||||
let old_name = vlog_refactor::rename_name_at(&doc.semantics, offset);
|
||||
let sources = match &old_name {
|
||||
Some(name) => ws.rename_sources(&path, name, Some(new_name)),
|
||||
None => ws.sources(),
|
||||
let (sources, selection) = match &old_name {
|
||||
Some(name) => ws.rename_sources_traced(&path, name, Some(new_name)),
|
||||
None => {
|
||||
let all = ws.sources();
|
||||
let selection = SelectionTrace::whole_scope(all.len(), 0.0);
|
||||
(all, selection)
|
||||
}
|
||||
};
|
||||
let refactoring = vlog_refactor::rename(&sources, &path, offset, new_name)?;
|
||||
let mut engine = vlog_refactor::RenameTrace::default();
|
||||
let outcome = vlog_refactor::rename_traced(&sources, &path, offset, new_name, &mut engine);
|
||||
*trace = Some(format!("{} {}", selection.line(), engine.line()));
|
||||
let refactoring = outcome?;
|
||||
|
||||
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
|
||||
for (path, edits) in &refactoring.edits {
|
||||
@@ -116,7 +132,7 @@ pub fn rename(
|
||||
/// about the one shape it cannot see.
|
||||
///
|
||||
/// Subtracting the handed set leaves out every open buffer too, because
|
||||
/// [`Workspace::rename_sources`] puts every open buffer in it.
|
||||
/// [`Workspace::rename_sources_traced`] puts every open buffer in it.
|
||||
fn unread_macro_warnings(ws: &Workspace, name: &str, sources: &[(PathBuf, String)]) -> Vec<String> {
|
||||
let index = ws.index();
|
||||
index
|
||||
@@ -141,6 +157,17 @@ mod tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str::FromStr;
|
||||
|
||||
/// [`rename_traced`] with the trace thrown away — what a test that is not
|
||||
/// about the trace asks.
|
||||
fn rename(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
rename_traced(ws, uri, offset, new_name, &mut None)
|
||||
}
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
@@ -281,7 +308,7 @@ mod tests {
|
||||
fn fan_out(ws: &Workspace, path: &Path, offset: u32, new_name: &str) -> Vec<PathBuf> {
|
||||
let doc = ws.document_for_path(path).expect("the request's file is open");
|
||||
match vlog_refactor::rename_name_at(&doc.semantics, offset) {
|
||||
Some(name) => ws.rename_sources(path, &name, Some(new_name)),
|
||||
Some(name) => ws.rename_sources_traced(path, &name, Some(new_name)).0,
|
||||
None => ws.sources(),
|
||||
}
|
||||
.into_iter()
|
||||
@@ -301,7 +328,7 @@ mod tests {
|
||||
let everything = ws.sources();
|
||||
let doc = ws.document_for_path(path).expect("the request's file is open");
|
||||
let subset = match vlog_refactor::rename_name_at(&doc.semantics, offset) {
|
||||
Some(name) => ws.rename_sources(path, &name, Some(new_name)),
|
||||
Some(name) => ws.rename_sources_traced(path, &name, Some(new_name)).0,
|
||||
None => everything.clone(),
|
||||
};
|
||||
for (path, text) in &subset {
|
||||
@@ -955,7 +982,7 @@ mod tests {
|
||||
|
||||
// The premise: `far.svh` is in no rung of the fan-out, so the engine
|
||||
// never sees it. Asked of the same function `rename` asks.
|
||||
let handed = ws.rename_sources(&tree.path.join("top.sv"), "sig", Some("probe"));
|
||||
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
|
||||
assert!(
|
||||
!handed.iter().any(|(path, _)| path.ends_with("far.svh")),
|
||||
"premise: the engine is not handed far.svh — {handed:?}"
|
||||
@@ -989,7 +1016,7 @@ mod tests {
|
||||
let far = format!("module far;\n sub u_far (.sig(1'b0));\n {M_FAR}endmodule\n");
|
||||
let (ws, uri) = macro_workspace(&tree, &far);
|
||||
|
||||
let handed = ws.rename_sources(&tree.path.join("top.sv"), "sig", Some("probe"));
|
||||
let handed = ws.rename_sources_traced(&tree.path.join("top.sv"), "sig", Some("probe")).0;
|
||||
assert!(
|
||||
handed.iter().any(|(path, _)| path.ends_with("far.svh")),
|
||||
"premise: instantiating `sub` puts far.svh in the source set"
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
//! Which rung of the rename fan-out put each file in the engine's input.
|
||||
//!
|
||||
//! Take 5 §P2a (`docs/features/perf5-p2/README.md`). `Workspace::rename_sources_traced`
|
||||
//! climbs six rungs and has one escape hatch, and the tracker's own note says
|
||||
//! it plainly: *two output files is not an input count*. A rename of `state_q`
|
||||
//! may hand the engine hundreds of files and nobody could say which rung asked
|
||||
//! for them. This module is the answer — a set of paths that also remembers
|
||||
//! **why** each one was added.
|
||||
//!
|
||||
//! [`Wanted`] is a `BTreeSet<PathBuf>` with a current [`Rung`]: the selector
|
||||
//! sets the rung it is on and inserts exactly as it did before, so the
|
||||
//! selection logic is not changed by being watched. The first rung to ask for
|
||||
//! a path is the one recorded, which is what makes the counts add up to the
|
||||
//! selected set rather than over-counting a file three rungs want.
|
||||
//!
|
||||
//! Nothing here decides anything. A [`SelectionTrace`] is written, logged once
|
||||
//! behind `--verbose`, and dropped.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Why one file is in a rename's input.
|
||||
///
|
||||
/// One variant per rung of [`crate::state::Workspace::rename_sources_traced`]'s
|
||||
/// ladder, in the order the ladder climbs them.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Rung {
|
||||
/// The file the request was made in.
|
||||
#[default]
|
||||
Request,
|
||||
/// A file declaring one of the two names — its own file, from
|
||||
/// `workspace_symbols` or `hierarchical_declarations`.
|
||||
Declaration,
|
||||
/// A file the index recorded a use of such a declaration in.
|
||||
Reference,
|
||||
/// A file instantiating the name, or one of its containers.
|
||||
Instantiation,
|
||||
/// A file whose `` `define`` table names it or spells it in a macro body.
|
||||
MacroText,
|
||||
/// A file spelling the **new** name in a use this workspace had to look
|
||||
/// outside that file to answer.
|
||||
Speller,
|
||||
/// An open buffer, added whatever else it is.
|
||||
OpenBuffer,
|
||||
}
|
||||
|
||||
impl Rung {
|
||||
/// The name this rung is counted under in the `timing:` line.
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Rung::Request => "request",
|
||||
Rung::Declaration => "declaration",
|
||||
Rung::Reference => "reference",
|
||||
Rung::Instantiation => "instantiation",
|
||||
Rung::MacroText => "macro",
|
||||
Rung::Speller => "speller",
|
||||
Rung::OpenBuffer => "open",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every rung, in ladder order — so a trace line always has the same
|
||||
/// fields whether or not a rung contributed.
|
||||
const ALL: [Rung; 7] = [
|
||||
Rung::Request,
|
||||
Rung::Declaration,
|
||||
Rung::Reference,
|
||||
Rung::Instantiation,
|
||||
Rung::MacroText,
|
||||
Rung::Speller,
|
||||
Rung::OpenBuffer,
|
||||
];
|
||||
}
|
||||
|
||||
/// How many files each rung was the first to ask for, and whether the
|
||||
/// ambiguity escape hatch fired.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct SelectionTrace {
|
||||
counts: Vec<(Rung, usize)>,
|
||||
/// The index could not bound the fan-out, so every in-scope file went.
|
||||
pub fallback: bool,
|
||||
/// How many files went in the end.
|
||||
pub selected: usize,
|
||||
/// Milliseconds the selection itself took, reading and all.
|
||||
pub ms: f64,
|
||||
}
|
||||
|
||||
impl SelectionTrace {
|
||||
/// The trace of a selection that gave up and handed over the whole scope
|
||||
/// — the ambiguity escape hatch, and a cursor with no name to fan out
|
||||
/// from. No rung ran, so none is counted.
|
||||
pub fn whole_scope(selected: usize, ms: f64) -> SelectionTrace {
|
||||
SelectionTrace { counts: Vec::new(), fallback: true, selected, ms }
|
||||
}
|
||||
|
||||
/// One file added by `rung`, if no earlier rung had it.
|
||||
fn add(&mut self, rung: Rung) {
|
||||
match self.counts.iter_mut().find(|(held, _)| *held == rung) {
|
||||
Some((_, count)) => *count += 1,
|
||||
None => self.counts.push((rung, 1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many files this rung was the first to ask for.
|
||||
pub fn count(&self, rung: Rung) -> usize {
|
||||
self.counts.iter().find(|(held, _)| *held == rung).map_or(0, |(_, count)| *count)
|
||||
}
|
||||
|
||||
/// The trace as one `timing:`-style fragment.
|
||||
pub fn line(&self) -> String {
|
||||
let rungs: Vec<String> = Rung::ALL
|
||||
.iter()
|
||||
.map(|rung| format!("{}={}", rung.label(), self.count(*rung)))
|
||||
.collect();
|
||||
format!(
|
||||
"select={:.1}ms selected={} fallback={} rungs{{{}}}",
|
||||
self.ms,
|
||||
self.selected,
|
||||
self.fallback,
|
||||
rungs.join(" ")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The path set a fan-out fills, plus the rung it is currently climbing.
|
||||
///
|
||||
/// `paths` is exactly the `BTreeSet<PathBuf>` the selector built before; the
|
||||
/// only difference is that an insertion also tells the trace which rung made
|
||||
/// it. A path already held is not re-attributed, so the counts partition the
|
||||
/// selected set.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Wanted {
|
||||
paths: BTreeSet<PathBuf>,
|
||||
trace: SelectionTrace,
|
||||
rung: Rung,
|
||||
}
|
||||
|
||||
impl Wanted {
|
||||
/// An empty set, on the rung a request's own file is added by.
|
||||
pub fn new() -> Wanted {
|
||||
Wanted::default()
|
||||
}
|
||||
|
||||
/// Climb to `rung`: every insertion until the next call is attributed to
|
||||
/// it.
|
||||
pub fn on(&mut self, rung: Rung) {
|
||||
self.rung = rung;
|
||||
}
|
||||
|
||||
/// Add one path, attributed to the current rung if it is new.
|
||||
pub fn insert(&mut self, path: PathBuf) {
|
||||
if self.paths.insert(path) {
|
||||
self.trace.add(self.rung);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Wanted::insert`] over an iterator — the shape the selector's
|
||||
/// `wanted.extend(...)` calls had.
|
||||
pub fn extend(&mut self, paths: impl IntoIterator<Item = PathBuf>) {
|
||||
for path in paths {
|
||||
self.insert(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths, in path order, and the trace of how they got there.
|
||||
pub fn finish(self) -> (BTreeSet<PathBuf>, SelectionTrace) {
|
||||
let Wanted { paths, mut trace, .. } = self;
|
||||
trace.selected = paths.len();
|
||||
(paths, trace)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_first_rung_to_ask_for_a_path_is_the_one_counted() {
|
||||
let mut wanted = Wanted::new();
|
||||
wanted.insert(PathBuf::from("/rtl/a.sv"));
|
||||
wanted.on(Rung::Reference);
|
||||
wanted.insert(PathBuf::from("/rtl/a.sv"));
|
||||
wanted.insert(PathBuf::from("/rtl/b.sv"));
|
||||
let (paths, trace) = wanted.finish();
|
||||
assert_eq!(paths.len(), 2);
|
||||
assert_eq!(trace.count(Rung::Request), 1);
|
||||
assert_eq!(trace.count(Rung::Reference), 1);
|
||||
assert_eq!(trace.selected, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_rung_appears_in_the_line_even_at_zero() {
|
||||
let trace = SelectionTrace::default();
|
||||
let line = trace.line();
|
||||
for rung in Rung::ALL {
|
||||
assert!(line.contains(&format!("{}=0", rung.label())), "{line} lacks {rung:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -368,7 +368,16 @@ impl Server {
|
||||
let Some(offset) = self.offset(&uri, position) else {
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
match rename::rename(&self.workspace, &uri, offset, &new_name) {
|
||||
// One `timing: rename trace …` line behind `--verbose`, and
|
||||
// nothing at all otherwise: where a rename's selection, its
|
||||
// stages and its whole-file parses went (take 5 §P2a).
|
||||
let mut trace = None;
|
||||
let outcome =
|
||||
rename::rename_traced(&self.workspace, &uri, offset, &new_name, &mut trace);
|
||||
if let (true, Some(line)) = (self.verbose, trace) {
|
||||
self.timing(format!("rename trace {line}"));
|
||||
}
|
||||
match outcome {
|
||||
Ok((edit, warnings)) => {
|
||||
self.report_scope(warnings);
|
||||
to_value(edit)
|
||||
|
||||
@@ -8,6 +8,7 @@ use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::time::Instant;
|
||||
|
||||
use lsp_types::Uri;
|
||||
use vlog_parser::ast::SourceFile;
|
||||
@@ -26,6 +27,7 @@ use crate::candidates::Candidates;
|
||||
use crate::convert::Positions;
|
||||
use crate::includes::IncludeGraph;
|
||||
use crate::index_cache::IndexCache;
|
||||
use crate::rename_trace::{Rung, SelectionTrace, Wanted};
|
||||
use crate::settings::{ClientSettings, IndexScope};
|
||||
use crate::uri::uri_to_path;
|
||||
|
||||
@@ -1570,37 +1572,54 @@ impl Workspace {
|
||||
/// use is in no posting table, and the whole-workspace rename refuses
|
||||
/// because of it. Rather than lose that refusal, this hands back
|
||||
/// `sources()` and the slow path answers.
|
||||
pub fn rename_sources(
|
||||
/// It also says **which rung asked for each file**: [`Wanted`] is a path
|
||||
/// set that records the first rung to insert a path, so watching the
|
||||
/// selection cannot change it (take 5 §P2a).
|
||||
pub fn rename_sources_traced(
|
||||
&self,
|
||||
file: &Path,
|
||||
name: &str,
|
||||
new_name: Option<&str>,
|
||||
) -> Vec<(PathBuf, String)> {
|
||||
let mut wanted: BTreeSet<PathBuf> = BTreeSet::new();
|
||||
) -> (Vec<(PathBuf, String)>, SelectionTrace) {
|
||||
let started = Instant::now();
|
||||
let elapsed = |at: Instant| at.elapsed().as_secs_f64() * 1000.0;
|
||||
let mut wanted = Wanted::new();
|
||||
wanted.insert(file.to_path_buf());
|
||||
for spelling in [Some(name), new_name].into_iter().flatten() {
|
||||
if !self.fan_out_of(spelling, &mut wanted) {
|
||||
return self.sources();
|
||||
let sources = self.sources();
|
||||
let trace = SelectionTrace::whole_scope(sources.len(), elapsed(started));
|
||||
return (sources, trace);
|
||||
}
|
||||
}
|
||||
// The sixth rung, and the **new** name's alone. See the doc comment
|
||||
// above for why the old name does not need it.
|
||||
if let Some(new_name) = new_name {
|
||||
wanted.on(Rung::Speller);
|
||||
self.want_spellers(new_name, &mut wanted);
|
||||
}
|
||||
wanted.on(Rung::OpenBuffer);
|
||||
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
wanted
|
||||
let (paths, mut trace) = wanted.finish();
|
||||
let texts: Vec<(PathBuf, String)> = paths
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
let text = self.current_text(&path)?;
|
||||
Some((path, text))
|
||||
})
|
||||
.collect()
|
||||
.collect();
|
||||
// A file a rung wanted whose text this workspace no longer contributes
|
||||
// (deleted, oversize, a fast-path buffer) is counted by its rung and
|
||||
// is not in the input: the rungs total the *wanted* set, `selected`
|
||||
// the one the engine gets.
|
||||
trace.selected = texts.len();
|
||||
trace.ms = elapsed(started);
|
||||
(texts, trace)
|
||||
}
|
||||
|
||||
/// Add one spelling's fan-out to `wanted`. `false` means the index cannot
|
||||
/// bound it — see [`Workspace::rename_sources`]'s escape hatch.
|
||||
fn fan_out_of(&self, name: &str, wanted: &mut BTreeSet<PathBuf>) -> bool {
|
||||
/// bound it — see [`Workspace::rename_sources_traced`]'s escape hatch.
|
||||
fn fan_out_of(&self, name: &str, wanted: &mut Wanted) -> bool {
|
||||
// Every declaration of the name, wherever it is written. `units` alone
|
||||
// would miss a port, a parameter or a package member, and those are
|
||||
// exactly the declarations a `.port` connection or a `pkg::x` reaches
|
||||
@@ -1642,8 +1661,10 @@ impl Workspace {
|
||||
|
||||
/// One declaration's own file, and every file the index recorded a use of
|
||||
/// it in.
|
||||
fn want_declaration(&self, def: &Def, wanted: &mut BTreeSet<PathBuf>) {
|
||||
fn want_declaration(&self, def: &Def, wanted: &mut Wanted) {
|
||||
wanted.on(Rung::Declaration);
|
||||
wanted.extend(self.index.path(def.file).map(Path::to_path_buf));
|
||||
wanted.on(Rung::Reference);
|
||||
for site in self.index.references_to(def) {
|
||||
wanted.extend(self.index.path(site.file).map(Path::to_path_buf));
|
||||
}
|
||||
@@ -1652,7 +1673,8 @@ impl Workspace {
|
||||
/// Every file that instantiates a name — the census the reference postings
|
||||
/// cannot speak for, because an instantiation of something the workspace
|
||||
/// does not declare resolves to nothing and is posted nowhere.
|
||||
fn want_sites(&self, name: &str, wanted: &mut BTreeSet<PathBuf>) {
|
||||
fn want_sites(&self, name: &str, wanted: &mut Wanted) {
|
||||
wanted.on(Rung::Instantiation);
|
||||
for edge in self.index.instantiations_of(name) {
|
||||
wanted.extend(self.index.path(edge.file).map(Path::to_path_buf));
|
||||
}
|
||||
@@ -1669,7 +1691,7 @@ impl Workspace {
|
||||
/// gives that import a meaning, which the whole-workspace verifier refuses
|
||||
/// over. Only the postings' *keys* miss it; the per-file records keep every
|
||||
/// external use by the name it spells, so this reads it back.
|
||||
fn want_spellers(&self, name: &str, wanted: &mut BTreeSet<PathBuf>) {
|
||||
fn want_spellers(&self, name: &str, wanted: &mut Wanted) {
|
||||
for file in self.index.files_spelling(name) {
|
||||
wanted.extend(self.index.path(file).map(Path::to_path_buf));
|
||||
}
|
||||
@@ -1683,7 +1705,8 @@ impl Workspace {
|
||||
/// question is asked with `vlog_refactor::contains_word`, which is the
|
||||
/// function `define_sites` itself decides with, so the fan-out and the
|
||||
/// warning cannot disagree about which files carry one.
|
||||
fn want_macro_text(&self, name: &str, wanted: &mut BTreeSet<PathBuf>) {
|
||||
fn want_macro_text(&self, name: &str, wanted: &mut Wanted) {
|
||||
wanted.on(Rung::MacroText);
|
||||
for id in 0..self.index.files().len() {
|
||||
let file = FileId(id as u32);
|
||||
let Some(defines) = self.index.defines(file) else { continue };
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
//! The state after the edits: the index the verifier compares against, and
|
||||
//! one watched file's print of it.
|
||||
//!
|
||||
//! Both used to be "do it all again". The after-index was a whole
|
||||
//! `WorkspaceIndex::build` over every in-scope file, of which an edit changes
|
||||
//! two or three; the after-print of an *unedited* watched file was a fresh
|
||||
//! parse and analysis of text nothing had touched. Take 5 §P2c replaced the
|
||||
//! first with the before-index plus the edited files' absorbed records, and
|
||||
//! the second with the analysis the before-pass already made, re-resolved
|
||||
//! against the new index.
|
||||
//!
|
||||
//! **Nothing the verifier compares changed.** The prints are the same prints,
|
||||
//! built by the same `print`, over the same watched set; what changed is where
|
||||
//! their inputs come from. The tests below are the proof that the inputs are
|
||||
//! the same inputs — including on edits crafted to make an incremental index
|
||||
//! disagree with a rebuilt one.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{resolve_external, FileFacts, Semantics, WorkspaceIndex};
|
||||
|
||||
use super::{print, Print, Shifts};
|
||||
use crate::scope::Scope;
|
||||
|
||||
/// The workspace index as it would be after the edits, so that a cross-file
|
||||
/// capture is caught exactly the way an in-file one is — **and** the one new
|
||||
/// analysis of each edited file, which is also its after-print's.
|
||||
///
|
||||
/// The before-index already holds a record per in-scope file, and an edit
|
||||
/// changes at most a handful of them. So this is the before-index with the
|
||||
/// edited files' new records absorbed, and not one unedited file re-read:
|
||||
/// `WorkspaceIndex::absorb` promises "the index a full build over the
|
||||
/// resulting record set would have produced" (`docs/topo.md` §3), and every
|
||||
/// edited path is one the index already holds, so no file id moves either.
|
||||
/// One `absorb` of every edited record rather than an `update_facts` per
|
||||
/// record: both promise that same equality, and `absorb`'s single whole merge
|
||||
/// **measured faster** than the per-file restricted merges, which walk the
|
||||
/// same records with a name-set lookup at every declaration (tail rename
|
||||
/// 37 ms against 53; see the feature README's §P2c entry).
|
||||
/// That equality is what the verifier depends on and what
|
||||
/// `an_absorbed_after_index_is_the_index_a_rebuild_would_give` pins, on
|
||||
/// crafted adversarial edits as well as on ordinary ones (take 5 §P2c).
|
||||
///
|
||||
/// Each edited file is parsed **once**, here, and the analysis that parse
|
||||
/// produced is handed back for the after-print rather than being made again.
|
||||
pub(super) fn after_index(
|
||||
scope: &Scope,
|
||||
edited: &[(PathBuf, String)],
|
||||
) -> (WorkspaceIndex, Vec<(PathBuf, Semantics)>) {
|
||||
let mut records = Vec::with_capacity(edited.len());
|
||||
let mut analyses = Vec::with_capacity(edited.len());
|
||||
for (path, text) in edited {
|
||||
let (facts, semantics) = FileFacts::analyzed(path.clone(), text);
|
||||
records.push(facts);
|
||||
analyses.push((path.clone(), semantics));
|
||||
}
|
||||
let mut index = scope.index().clone();
|
||||
index.absorb(records, &[]);
|
||||
(index, analyses)
|
||||
}
|
||||
|
||||
/// One watched file's after-print: from the edited file's own new analysis
|
||||
/// when the edits touched it, and otherwise from the analysis the before-pass
|
||||
/// computed, re-resolved against the after-index.
|
||||
pub(super) fn after_print(
|
||||
scope: &Scope,
|
||||
i: usize,
|
||||
path: &Path,
|
||||
index: &WorkspaceIndex,
|
||||
edited: &[(PathBuf, Semantics)],
|
||||
excluded: &[TextRange],
|
||||
) -> Option<Print> {
|
||||
match edited.iter().find(|(edited_path, _)| edited_path == path) {
|
||||
Some((_, semantics)) => {
|
||||
let external = resolve_external(semantics, index);
|
||||
Some(print(semantics, &external, index, path, &Shifts::default(), excluded))
|
||||
}
|
||||
None => {
|
||||
let (semantics, external) = scope.against(i, index)?;
|
||||
Some(print(semantics, &external, index, path, &Shifts::default(), excluded))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::apply;
|
||||
use crate::TextEdit;
|
||||
|
||||
/// What a whole `WorkspaceIndex::build` over the edited texts gives — the
|
||||
/// thing the absorbed index has to equal, and what §P2c replaced.
|
||||
fn rebuilt(scope: &Scope, edited: &[(PathBuf, String)]) -> WorkspaceIndex {
|
||||
let sources: Vec<(PathBuf, &str)> = (0..scope.len())
|
||||
.filter_map(|i| {
|
||||
let (path, text) = (scope.path(i)?, scope.text(i)?);
|
||||
let text = edited
|
||||
.iter()
|
||||
.find(|(edited_path, _)| edited_path == path)
|
||||
.map_or(text, |(_, edited_text)| edited_text.as_str());
|
||||
Some((path.to_path_buf(), text))
|
||||
})
|
||||
.collect();
|
||||
WorkspaceIndex::build(sources)
|
||||
}
|
||||
|
||||
/// Every query the verifier's prints reach the index through, for one
|
||||
/// name — so "the same index" is checked at the level the checks use it
|
||||
/// and not only through the fingerprint.
|
||||
fn answers(index: &WorkspaceIndex, name: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for def in index.units(name) {
|
||||
out.push_str(&format!(
|
||||
"unit {} {:?} {}..{}\n",
|
||||
def.file.0, def.kind, def.name_span.start, def.name_span.end
|
||||
));
|
||||
for site in index.references_to(def) {
|
||||
out.push_str(&format!(
|
||||
" ref {} {}..{}\n",
|
||||
site.file.0, site.name_span.start, site.name_span.end
|
||||
));
|
||||
}
|
||||
}
|
||||
for edge in index.instantiations_of(name) {
|
||||
out.push_str(&format!("inst {} {}\n", edge.file.0, edge.owner.name));
|
||||
}
|
||||
for (unit, def) in index.hierarchical_declarations(name) {
|
||||
out.push_str(&format!(
|
||||
"hier {unit} {} {}..{}\n",
|
||||
def.file.0, def.name_span.start, def.name_span.end
|
||||
));
|
||||
}
|
||||
for symbol in index.workspace_symbols(name) {
|
||||
out.push_str(&format!("sym {} {:?}\n", symbol.name, symbol.container));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One (workspace, edit) case: build a scope, apply the edits, and assert
|
||||
/// the absorbed after-index is the index a rebuild would give.
|
||||
fn absorbing_equals_rebuilding(
|
||||
files: &[(&str, &str)],
|
||||
edits: &[(&str, &str, &str)],
|
||||
names: &[&str],
|
||||
) {
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
files.iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
|
||||
let scope = Scope::build(&sources);
|
||||
let mut edited: Vec<(PathBuf, String)> = Vec::new();
|
||||
for (path, from, to) in edits {
|
||||
let i = scope.index_of(Path::new(path)).expect("the edited file is in scope");
|
||||
let text = scope.text(i).expect("its text");
|
||||
let at = text.find(from).expect("the edited text is there") as u32;
|
||||
let edit = TextEdit {
|
||||
range: TextRange::new(at, at + from.len() as u32),
|
||||
new_text: (*to).to_string(),
|
||||
};
|
||||
edited.push((PathBuf::from(*path), apply(text, std::slice::from_ref(&edit))));
|
||||
}
|
||||
let (absorbed, analyses) = after_index(&scope, &edited);
|
||||
let built = rebuilt(&scope, &edited);
|
||||
assert_eq!(absorbed.fingerprint(), built.fingerprint(), "{files:?} / {edits:?}");
|
||||
assert_eq!(absorbed.files(), built.files(), "the file ids moved");
|
||||
assert_eq!(absorbed.files(), scope.index().files(), "an absorb over held paths keeps ids");
|
||||
for name in names {
|
||||
assert_eq!(answers(&absorbed, name), answers(&built, name), "`{name}` differs");
|
||||
}
|
||||
assert_eq!(analyses.len(), edited.len(), "one new analysis per edited file");
|
||||
}
|
||||
|
||||
const SUB: &str = "module sub (input logic clk, output logic q);\n wire sig;\nendmodule\n";
|
||||
const TOP: &str = "module top;\n logic sig;\n sub u_sub (.clk(1'b0), .q(sig));\n assign sig = u_sub.sig;\nendmodule\n";
|
||||
const PKG: &str = "package pkg;\n localparam int SIG = 1;\nendpackage\n";
|
||||
const USER: &str = "import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n";
|
||||
|
||||
fn workspace() -> [(&'static str, &'static str); 4] {
|
||||
[("/w/sub.sv", SUB), ("/w/top.sv", TOP), ("/w/pkg.sv", PKG), ("/w/user.sv", USER)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absorbed_after_index_is_the_index_a_rebuild_would_give() {
|
||||
// An ordinary rename edit, in one file and in two.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/top.sv", "logic sig;", "logic sg;")],
|
||||
&["sig", "sg", "top", "sub"],
|
||||
);
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/sub.sv", "wire sig;", "wire sg;"), ("/w/top.sv", "u_sub.sig", "u_sub.sg")],
|
||||
&["sig", "sg", "sub"],
|
||||
);
|
||||
// A file that **gains** a declaration another file can name.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[(
|
||||
"/w/pkg.sv",
|
||||
"localparam int SIG = 1;",
|
||||
"localparam int SIG = 1;\n localparam int X = 2;",
|
||||
)],
|
||||
&["SIG", "X", "pkg"],
|
||||
);
|
||||
// A file that **loses** one — the use in `user.sv` is left dangling,
|
||||
// and neither index may hide that.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/pkg.sv", "localparam int SIG = 1;", "")],
|
||||
&["SIG", "pkg"],
|
||||
);
|
||||
// An edit that changes what **another** file resolves to: the package
|
||||
// is renamed, so `user.sv`'s import points at nothing.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/pkg.sv", "package pkg;", "package pkq;")],
|
||||
&["pkg", "pkq", "SIG"],
|
||||
);
|
||||
// An edited **package**, plus the re-export chain that reads it.
|
||||
const A: &str = "package a_pkg;\n localparam int V = 1;\nendpackage\n";
|
||||
const B: &str = "package b_pkg;\n import a_pkg::*;\n export a_pkg::*;\nendpackage\n";
|
||||
const C: &str = "module c;\n localparam int W = b_pkg::V;\nendmodule\n";
|
||||
let chain = [("/w/a.sv", A), ("/w/b.sv", B), ("/w/c.sv", C)];
|
||||
absorbing_equals_rebuilding(
|
||||
&chain,
|
||||
&[("/w/a.sv", "localparam int V = 1;", "localparam int V2 = 1;")],
|
||||
&["V", "V2", "a_pkg", "b_pkg"],
|
||||
);
|
||||
absorbing_equals_rebuilding(
|
||||
&chain,
|
||||
&[("/w/b.sv", "export a_pkg::*;", "")],
|
||||
&["V", "a_pkg", "b_pkg"],
|
||||
);
|
||||
// A module that stops being instantiated, and one that starts.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/top.sv", "sub u_sub", "other u_sub")],
|
||||
&["sub", "other", "top"],
|
||||
);
|
||||
// An edit that makes a file stop lexing: it contributes nothing, and
|
||||
// both indexes must agree that it contributes nothing.
|
||||
absorbing_equals_rebuilding(
|
||||
&workspace(),
|
||||
&[("/w/sub.sv", "wire sig;", "wire \"sig;")],
|
||||
&["sig", "sub"],
|
||||
);
|
||||
}
|
||||
|
||||
/// **Attack 3 — an after-index whose file ids shifted.** The absorbed
|
||||
/// index keeps ids because every edited path is one it already holds, but
|
||||
/// the print comparison must not *depend* on that: a `Def` names a file by
|
||||
/// id, and an id is a position in a path-sorted list that any added file
|
||||
/// renumbers. So the print resolves every id back to a **path** before
|
||||
/// comparing, and this pins it — the same file's print against two indexes
|
||||
/// whose ids differ by one everywhere must be the same print.
|
||||
#[test]
|
||||
fn a_print_names_paths_so_shifted_file_ids_cannot_change_it() {
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
workspace().iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
|
||||
let mut scope = Scope::build(&sources);
|
||||
// An index over the same four files plus one that sorts *first*, so
|
||||
// every original file's id is one higher in it.
|
||||
let mut shifted: Vec<(PathBuf, &str)> =
|
||||
sources.iter().map(|(p, t)| (p.clone(), t.as_str())).collect();
|
||||
shifted.insert(0, (PathBuf::from("/w/aaa.sv"), "module aaa; endmodule\n"));
|
||||
let shifted = WorkspaceIndex::build(shifted);
|
||||
assert_eq!(
|
||||
shifted.file_id(Path::new("/w/pkg.sv")).map(|f| f.0),
|
||||
scope.index().file_id(Path::new("/w/pkg.sv")).map(|f| f.0 + 1),
|
||||
"the ids really do shift"
|
||||
);
|
||||
|
||||
let i = scope.index_of(Path::new("/w/user.sv")).expect("user.sv is in scope");
|
||||
assert!(scope.analysis(i).is_some(), "its analysis is what a before-pass computes");
|
||||
let path = scope.path(i).expect("its path");
|
||||
let held = after_print(&scope, i, path, scope.index(), &[], &[]).expect("a print");
|
||||
let moved = after_print(&scope, i, path, &shifted, &[], &[]).expect("a print");
|
||||
assert_eq!(held, moved, "a print must not read a file id");
|
||||
}
|
||||
|
||||
/// Absorbing over a path the index already holds moves no file id — the
|
||||
/// property the after-print's path lookups and the `Def`s inside a print
|
||||
/// both stand on.
|
||||
#[test]
|
||||
fn absorbing_an_edited_file_keeps_every_file_id() {
|
||||
let sources: Vec<(PathBuf, String)> =
|
||||
workspace().iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect();
|
||||
let scope = Scope::build(&sources);
|
||||
let before: Vec<PathBuf> = scope.index().files().to_vec();
|
||||
let edited = vec![(PathBuf::from("/w/pkg.sv"), PKG.replace("SIG", "SIGNAL"))];
|
||||
let (after, _) = after_index(&scope, &edited);
|
||||
assert_eq!(after.files(), before.as_slice());
|
||||
for (id, path) in before.iter().enumerate() {
|
||||
assert_eq!(after.file_id(path), Some(vlog_semantic::FileId(id as u32)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
//! Nothing here touches `vlog_formatter` or its `verify.rs`: this is the same
|
||||
//! contract, kept separately, so the formatter's safety net does not widen.
|
||||
|
||||
mod after;
|
||||
mod ledger;
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -26,13 +27,14 @@ use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::{parse_source_tolerant, tokenize};
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, ExternalResolutions, ExternalTarget, ReferenceId, Semantics,
|
||||
SymbolKind, WorkspaceIndex,
|
||||
ExternalResolutions, ExternalTarget, ReferenceId, Semantics, SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::rename::{contains_word, display, Scope};
|
||||
use crate::trace::VerifyTrace;
|
||||
use crate::{apply, Shift, TextEdit};
|
||||
|
||||
use after::{after_index, after_print};
|
||||
use ledger::{overlaps, pieces_match, region_of, Split, Transit};
|
||||
|
||||
/// Check the whole edit, or refuse it whole.
|
||||
@@ -41,6 +43,7 @@ pub(crate) fn verify(
|
||||
edits: &[(usize, Vec<TextEdit>)],
|
||||
old_name: &str,
|
||||
new_name: &str,
|
||||
trace: &mut VerifyTrace,
|
||||
) -> Result<(), String> {
|
||||
let edited: Vec<(PathBuf, String)> = edits
|
||||
.iter()
|
||||
@@ -57,7 +60,7 @@ pub(crate) fn verify(
|
||||
// 1. The token stream of every touched file, before and after.
|
||||
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
|
||||
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
|
||||
tokens_match(before, text, &Shift::new(edits), new_name, path)?;
|
||||
trace.tokens.measure(|| tokens_match(before, text, &Shift::new(edits), new_name, path))?;
|
||||
}
|
||||
|
||||
// 2. What every name resolves to, before and after — in every file the
|
||||
@@ -68,40 +71,39 @@ pub(crate) fn verify(
|
||||
// catches a third file whose existing `new_name` reference the rename
|
||||
// would make ambiguous without touching a byte of it.
|
||||
let watched = watched_files(scope, edits, &[old_name, new_name]);
|
||||
trace.watched = watched.len();
|
||||
trace.watched_bytes = watched.iter().filter_map(|&i| scope.text(i)).map(str::len).sum();
|
||||
let mut before: Vec<Print> = Vec::new();
|
||||
for &i in &watched {
|
||||
if scope.analysis(i).is_none() {
|
||||
if !trace.before.measure(|| scope.analysis(i).is_some()) {
|
||||
return Err(ABANDONED.to_string());
|
||||
}
|
||||
}
|
||||
let mut before: Vec<Print> = Vec::new();
|
||||
for &i in &watched {
|
||||
let (Some(path), Some(analysis)) = (scope.path(i), scope.cached(i)) else {
|
||||
return Err(ABANDONED.to_string());
|
||||
};
|
||||
before.push(print(
|
||||
&analysis.semantics,
|
||||
&analysis.external,
|
||||
scope.index(),
|
||||
path,
|
||||
&shifts,
|
||||
&[],
|
||||
));
|
||||
trace.before.measure(|| {
|
||||
before.push(print(
|
||||
&analysis.semantics,
|
||||
&analysis.external,
|
||||
scope.index(),
|
||||
path,
|
||||
&shifts,
|
||||
&[],
|
||||
))
|
||||
});
|
||||
}
|
||||
|
||||
let after_index = rebuilt_index(scope, &edited);
|
||||
let (after_index, edited_analyses) = trace.rebuild.measure(|| after_index(scope, &edited));
|
||||
for (n, &i) in watched.iter().enumerate() {
|
||||
let Some(path) = scope.path(i) else { return Err(ABANDONED.to_string()) };
|
||||
let text = match edited.iter().find(|(edited_path, _)| edited_path == path) {
|
||||
Some((_, edited_text)) => edited_text.as_str(),
|
||||
None => match scope.text(i) {
|
||||
Some(text) => text,
|
||||
None => return Err(ABANDONED.to_string()),
|
||||
},
|
||||
let after = trace
|
||||
.after
|
||||
.measure(|| after_print(scope, i, path, &after_index, &edited_analyses, &[]));
|
||||
let (Some(after), Some(before)) = (after, before.get(n)) else {
|
||||
return Err(ABANDONED.to_string());
|
||||
};
|
||||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||||
let external = resolve_external(&semantics, &after_index);
|
||||
let after = print(&semantics, &external, &after_index, path, &Shifts::default(), &[]);
|
||||
let Some(before) = before.get(n) else { return Err(ABANDONED.to_string()) };
|
||||
if let Some(what) = before.first_difference(&after) {
|
||||
return Err(format!(
|
||||
"renaming `{old_name}` to `{new_name}` would change what {what} means in {}; the rename was abandoned.",
|
||||
@@ -319,27 +321,14 @@ pub(crate) fn verify_move(
|
||||
));
|
||||
}
|
||||
|
||||
let after_index = rebuilt_index(scope, &edited);
|
||||
let (after_index, edited_analyses) = after_index(scope, &edited);
|
||||
for (n, &i) in watched.iter().enumerate() {
|
||||
let Some(path) = scope.path(i) else { return Err(abandoned) };
|
||||
let text = match edited.iter().find(|(edited_path, _)| edited_path == path) {
|
||||
Some((_, edited_text)) => edited_text.as_str(),
|
||||
None => match scope.text(i) {
|
||||
Some(text) => text,
|
||||
None => return Err(abandoned),
|
||||
},
|
||||
let after =
|
||||
after_print(scope, i, path, &after_index, &edited_analyses, excluded.after(path));
|
||||
let (Some(after), Some(before)) = (after, before.get(n)) else {
|
||||
return Err(abandoned);
|
||||
};
|
||||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||||
let external = resolve_external(&semantics, &after_index);
|
||||
let after = print(
|
||||
&semantics,
|
||||
&external,
|
||||
&after_index,
|
||||
path,
|
||||
&Shifts::default(),
|
||||
excluded.after(path),
|
||||
);
|
||||
let Some(before) = before.get(n) else { return Err(abandoned) };
|
||||
if let Some(what_moved) = before.first_difference(&after) {
|
||||
return Err(format!(
|
||||
"{what} would change what {what_moved} means in {}; no edits were made.",
|
||||
@@ -409,19 +398,6 @@ fn watched_files(scope: &Scope, edits: &[(usize, Vec<TextEdit>)], names: &[&str]
|
||||
|
||||
const ABANDONED: &str = "lucisv could not verify the rename, so it made no edits.";
|
||||
|
||||
/// The workspace index as it would be after the edits, so that a cross-file
|
||||
/// capture is caught exactly the way an in-file one is.
|
||||
fn rebuilt_index(scope: &Scope, edited: &[(PathBuf, String)]) -> WorkspaceIndex {
|
||||
let sources = scope.sources().iter().map(|(path, text)| {
|
||||
let text = edited
|
||||
.iter()
|
||||
.find(|(edited_path, _)| edited_path == path)
|
||||
.map_or(*text, |(_, edited_text)| edited_text.as_str());
|
||||
(path.to_path_buf(), text)
|
||||
});
|
||||
WorkspaceIndex::build(sources.collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// token identity
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -1257,7 +1233,7 @@ mod tests {
|
||||
new_text: "sig".into(),
|
||||
}],
|
||||
)];
|
||||
let outcome = verify(&mut scope, &partial, "a", "sig");
|
||||
let outcome = verify(&mut scope, &partial, "a", "sig", &mut VerifyTrace::default());
|
||||
assert!(outcome.is_err(), "a half-done rename must not verify: {outcome:?}");
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ mod ports;
|
||||
mod references;
|
||||
mod rename;
|
||||
mod scope;
|
||||
mod trace;
|
||||
|
||||
pub use extract::{
|
||||
extract_module, extract_site, extract_site_in, extract_title, ExtractSite, Home,
|
||||
@@ -58,8 +59,10 @@ pub use ports::{
|
||||
PortOfferKind,
|
||||
};
|
||||
pub use rename::{
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget,
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, rename_traced,
|
||||
RenameTarget,
|
||||
};
|
||||
pub use trace::{RenameTrace, Stage, VerifyTrace};
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ use vlog_semantic::{
|
||||
WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::trace::RenameTrace;
|
||||
use crate::{check, RefactorEdit, TextEdit};
|
||||
|
||||
/// The identifier a rename would act on: where it is, and what it spells.
|
||||
@@ -155,17 +156,68 @@ pub fn rename(
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
rename_traced(files, file, offset, new_name, &mut RenameTrace::default())
|
||||
}
|
||||
|
||||
/// [`rename`], with a [`RenameTrace`] filled in as it runs.
|
||||
///
|
||||
/// The same call — `rename` is this one with a trace nobody reads — so there
|
||||
/// is no traced path that could decide anything differently from the plain
|
||||
/// one. The trace is an **out parameter** rather than part of the `Ok` value
|
||||
/// because the stage a slow *refusal* spent its time in is exactly as
|
||||
/// interesting as a successful rename's: a conflicting new name refuses inside
|
||||
/// `collect_edits`, and the extract offer that costs 800 ms refuses after the
|
||||
/// scope build alone (take 5 §P2a).
|
||||
pub fn rename_traced(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
trace: &mut RenameTrace,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
let started = vlog_parser::stats::parses();
|
||||
let out = renaming(files, file, offset, new_name, trace);
|
||||
trace.parses = vlog_parser::stats::parses() - started;
|
||||
out
|
||||
}
|
||||
|
||||
/// The rename itself, so that [`rename_traced`] can count the parses of the
|
||||
/// whole of it — refusals included — in one place.
|
||||
fn renaming(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
new_name: &str,
|
||||
trace: &mut RenameTrace,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
check_new_name(new_name)?;
|
||||
let mut scope = Scope::build(files);
|
||||
let target = scope.locate(file, offset)?;
|
||||
trace.selected = files.len();
|
||||
trace.bytes = files.iter().map(|(_, text)| text.len()).sum();
|
||||
// One parse per file, and the analyses this rename is going to want kept
|
||||
// from it (take 5 §P2b). The words worth keeping are the new name and the
|
||||
// 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()
|
||||
})
|
||||
});
|
||||
trace.selected = scope.len();
|
||||
let target = trace.locate.measure(|| scope.locate(file, offset))?;
|
||||
if target.name == new_name {
|
||||
return Err(format!("`{new_name}` is the name it already has."));
|
||||
}
|
||||
let edits = scope.collect_edits(&target, new_name)?;
|
||||
check::verify(&mut scope, &edits, &target.name, new_name)?;
|
||||
let edits = trace.edits.measure(|| scope.collect_edits(&target, new_name))?;
|
||||
trace.edited = edits.len();
|
||||
// Two disjoint fields of one trace: `verify` times the whole pass while
|
||||
// `checks` is filled by its stages, so they are borrowed apart.
|
||||
let RenameTrace { verify, checks, .. } = &mut *trace;
|
||||
verify.measure(|| check::verify(&mut scope, &edits, &target.name, new_name, checks))?;
|
||||
|
||||
let warnings = scope.warnings(&target, &edits);
|
||||
let warnings = trace.warnings.measure(|| scope.warnings(&target, &edits));
|
||||
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = edits
|
||||
.into_iter()
|
||||
.filter_map(|(i, edits)| Some((scope.path(i)?.to_path_buf(), edits)))
|
||||
|
||||
@@ -195,3 +195,141 @@ fn the_name_a_fan_out_is_built_from_is_the_name_the_engine_acts_on() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the trace (take 5 §P2a)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_traced_rename_and_the_plain_one_are_the_same_call() {
|
||||
let sources = workspace(&[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
let path = PathBuf::from("top.sv");
|
||||
let at = TOP.find("sub #").expect("the instantiation") as u32;
|
||||
let mut trace = RenameTrace::default();
|
||||
let traced = rename_traced(&sources, &path, at, "child", &mut trace).expect("renames");
|
||||
let plain = rename(&sources, &path, at, "child").expect("renames");
|
||||
assert_eq!(traced.edits, plain.edits, "same edits");
|
||||
assert_eq!(traced.warnings, plain.warnings, "same warnings");
|
||||
assert_eq!(traced.created, plain.created, "same created files");
|
||||
// And a refusal is traced too, which is why the trace is an out parameter.
|
||||
let mut refused = RenameTrace::default();
|
||||
let outcome = rename_traced(&sources, &path, at, "module", &mut refused);
|
||||
assert!(outcome.is_err(), "a keyword must refuse");
|
||||
assert_eq!(refused.selected, 0, "the refusal is taken before the scope is built");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_trace_accounts_for_every_parse_the_rename_ran() {
|
||||
let sources = workspace(&[("sub.sv", SUB), ("top.sv", TOP), ("pkg.sv", PKG)]);
|
||||
let path = PathBuf::from("top.sv");
|
||||
let at = TOP.find("sub #").expect("the instantiation") as u32;
|
||||
let mut trace = RenameTrace::default();
|
||||
rename_traced(&sources, &path, at, "child", &mut trace).expect("renames");
|
||||
let staged = trace.index.parses
|
||||
+ trace.locate.parses
|
||||
+ trace.edits.parses
|
||||
+ trace.verify.parses
|
||||
+ trace.warnings.parses;
|
||||
assert_eq!(staged, trace.parses, "every parse belongs to a stage: {trace:?}");
|
||||
assert_eq!(
|
||||
trace.verify.parses,
|
||||
trace.checks.tokens.parses
|
||||
+ trace.checks.before.parses
|
||||
+ trace.checks.rebuild.parses
|
||||
+ trace.checks.after.parses
|
||||
+ trace.checks.checks.parses,
|
||||
"and every verification parse to a sub-stage: {trace:?}"
|
||||
);
|
||||
assert_eq!(trace.selected, 3, "three files in, whatever the rename does with them");
|
||||
assert_eq!(trace.bytes, sources.iter().map(|(_, t)| t.len()).sum::<usize>());
|
||||
assert!(trace.edited >= 1 && trace.edited <= trace.selected);
|
||||
assert!(trace.checks.watched >= trace.edited, "a watched set covers the edited one");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the reuse (take 5 §P2b/§P2c) — the parse budget, and three attacks on it
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A workspace of eight files. `sig` is declared in `sub.sv`, named through
|
||||
/// the hierarchy from `top.sv`, and merely mentioned in three others, so a
|
||||
/// rename of it edits two files and watches five.
|
||||
const EIGHT: [(&str, &str); 8] = [
|
||||
("/w/sub.sv", "module sub (input logic clk, output logic q);\n wire sig;\n assign q = sig;\nendmodule\n"),
|
||||
("/w/top.sv", "module top;\n logic w;\n sub u_sub (.clk(1'b0), .q(w));\n assign w = u_sub.sig;\nendmodule\n"),
|
||||
("/w/pkg.sv", "package pkg;\n localparam int SIG = 1;\nendpackage\n"),
|
||||
("/w/user.sv", "import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n"),
|
||||
("/w/note.sv", "module note;\n // sig is mentioned here in a comment\n logic other;\nendmodule\n"),
|
||||
("/w/far.sv", "module far;\n logic sig;\n assign sig = 1'b0;\nendmodule\n"),
|
||||
("/w/quiet_a.sv", "module quiet_a;\n logic a;\nendmodule\n"),
|
||||
("/w/quiet_b.sv", "module quiet_b;\n logic b;\nendmodule\n"),
|
||||
];
|
||||
|
||||
/// **K + E.** One whole-file parse per input file, plus one per edited file —
|
||||
/// and not one more, whatever the watched set costs.
|
||||
///
|
||||
/// The counts come out of the trace, so the assertion is on the work the
|
||||
/// engine really did rather than on a stopwatch. Before §P2b/§P2c this same
|
||||
/// rename parsed `K` for the index, again for every file spelling the name,
|
||||
/// `K` again for the after-index and once more for every watched file.
|
||||
#[test]
|
||||
fn a_rename_parses_each_input_file_once_and_each_edited_file_once_more() {
|
||||
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();
|
||||
rename_traced(&sources, &path, at, "renamed_sig", &mut trace).expect("renames");
|
||||
|
||||
let (k, e) = (trace.selected as u64, trace.edited as u64);
|
||||
assert_eq!(k, 8, "eight files in");
|
||||
assert_eq!(e, 2, "sub.sv and top.sv are edited");
|
||||
assert!(trace.checks.watched >= 4, "and several more are watched: {trace:?}");
|
||||
assert_eq!(trace.parses, k + e, "K + E and nothing else: {trace:?}");
|
||||
assert_eq!(trace.index.parses, k, "every input file, once, for the index");
|
||||
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.rebuild.parses, e, "the after-index absorbs, it does not rebuild");
|
||||
assert_eq!(trace.checks.after.parses, 0, "and its analyses are that absorb's own");
|
||||
}
|
||||
|
||||
/// **Attack 1 — a stale retained analysis.** The reuse hands the *edited*
|
||||
/// file's after-print the analysis of its **edited** text. An implementation
|
||||
/// that handed it the retained before-analysis instead would be describing
|
||||
/// text that no longer exists, and this rename — whose edit changes what a
|
||||
/// name in the edited file resolves to — is exactly the one it would wave
|
||||
/// through.
|
||||
#[test]
|
||||
fn a_rename_whose_edit_rebinds_a_name_in_the_edited_file_is_refused() {
|
||||
// `taken` is already declared in `m`. Renaming `sig` to `taken` would
|
||||
// give `assign q = taken;` a different declaration — in the very file the
|
||||
// edit touches, so only a print of the *edited* text can see it.
|
||||
const CAPTURE: &str = "module m (output logic q);\n wire sig;\n wire taken;\n assign q = sig;\n assign taken = 1'b1;\nendmodule\n";
|
||||
let sources = workspace(&[("/w/m.sv", CAPTURE)]);
|
||||
let path = PathBuf::from("/w/m.sv");
|
||||
let at = CAPTURE.find("wire sig").expect("the declaration") as u32 + 5;
|
||||
let outcome = rename(&sources, &path, at, "taken");
|
||||
assert!(outcome.is_err(), "a capture inside the edited file must refuse: {outcome:?}");
|
||||
}
|
||||
|
||||
/// **Attack 2 — an after-index that forgot an unedited file.** The after-index
|
||||
/// is the before-index with the edited records absorbed; absorbing with the
|
||||
/// wrong `gone`, or building it from the edited files alone, would drop the
|
||||
/// third file's declaration and the ambiguity it creates with it. The rename
|
||||
/// below edits `a.sv` and `top.sv` and is refused **because of `b.sv`**, which
|
||||
/// it never touches.
|
||||
#[test]
|
||||
fn a_rename_that_would_make_a_third_files_use_ambiguous_is_refused() {
|
||||
const A: &str = "package a_pkg;\n localparam int V = 1;\nendpackage\n";
|
||||
const B: &str = "package taken_pkg;\n localparam int V = 2;\nendpackage\n";
|
||||
const USE: &str = "import taken_pkg::*;\nmodule u;\n localparam int W = V;\nendmodule\n";
|
||||
let files = [("/w/a.sv", A), ("/w/b.sv", B), ("/w/use.sv", USE)];
|
||||
let sources = workspace(&files);
|
||||
let path = PathBuf::from("/w/a.sv");
|
||||
let at = A.find("a_pkg").expect("the package name") as u32;
|
||||
let outcome = rename(&sources, &path, at, "taken_pkg");
|
||||
assert!(outcome.is_err(), "a second `taken_pkg` makes use.sv's import ambiguous: {outcome:?}");
|
||||
// And the untouched declaration is still there to be found afterwards:
|
||||
// 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");
|
||||
}
|
||||
@@ -3,13 +3,24 @@
|
||||
//! Nothing here is specific to a rename: `ports`, `references` and
|
||||
//! `instantiate` read the same workspace, which is why it sits at the crate
|
||||
//! root rather than under one of them.
|
||||
//!
|
||||
//! **One parse per file** (take 5 §P2b). Building the index parses and
|
||||
//! analyses every in-scope file already — `FileFacts::of` is a parse, an
|
||||
//! `analyze` and a read-off — and used to throw that analysis away, so the
|
||||
//! first thing every refactoring did was parse a third of those files a
|
||||
//! second time. [`FileFacts::analyzed`] hands the analysis back instead, and
|
||||
//! [`Scope::build_keeping`] retains the ones a caller says it will want. What
|
||||
//! 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.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, ExternalResolutions, FileId, Semantics, WorkspaceIndex,
|
||||
analyze, resolve_external, ExternalResolutions, FileFacts, FileId, IndexBuilder, Semantics,
|
||||
WorkspaceIndex,
|
||||
};
|
||||
|
||||
/// One file's two analysis layers, as `textDocument/definition` uses them.
|
||||
@@ -30,10 +41,51 @@ pub(crate) struct Scope<'a> {
|
||||
/// Source index → the index's own file id.
|
||||
file_ids: Vec<Option<FileId>>,
|
||||
cache: HashMap<usize, Analysis>,
|
||||
/// The `Semantics` the index build kept, by source index — the half of an
|
||||
/// [`Analysis`] that does not depend on the finished index. Moved into
|
||||
/// `cache` the first time that file's analysis is asked for.
|
||||
kept: HashMap<usize, Semantics>,
|
||||
}
|
||||
|
||||
impl<'a> Scope<'a> {
|
||||
/// The in-scope files, indexed, keeping no analysis.
|
||||
///
|
||||
/// Each file is still parsed and analysed exactly once — that is what
|
||||
/// building the index costs — and every later `analysis` call parses
|
||||
/// 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())
|
||||
}
|
||||
|
||||
/// The in-scope files, indexed, **keeping** the analysis of `lead` and of
|
||||
/// every file whose text mentions one of the words `keep` asks for.
|
||||
///
|
||||
/// `lead` — the file the request was made in — is analysed first, and
|
||||
/// `keep` is then asked which words are worth retaining *given that
|
||||
/// analysis*. That ordering is the whole trick: a rename cannot know the
|
||||
/// name under the cursor until something has analysed the cursor's file,
|
||||
/// and this way that analysis is the file's own one-and-only parse rather
|
||||
/// than an extra one.
|
||||
///
|
||||
/// The rule is `text.contains(word)` — a substring test, deliberately the
|
||||
/// same prefilter [`Scope::collect_occurrences`] uses, so every file the
|
||||
/// occurrence walk will analyse and every file
|
||||
/// [`crate::check`] will watch (a whole-word subset) is retained, and
|
||||
/// nothing else is.
|
||||
pub(crate) fn build_keeping(
|
||||
files: &'a [(PathBuf, String)],
|
||||
lead: &Path,
|
||||
keep: impl FnOnce(Option<&Semantics>) -> Vec<String>,
|
||||
) -> Scope<'a> {
|
||||
Scope::assemble(files, Some(lead), keep)
|
||||
}
|
||||
|
||||
fn assemble(
|
||||
files: &'a [(PathBuf, String)],
|
||||
lead: Option<&Path>,
|
||||
keep: impl FnOnce(Option<&Semantics>) -> Vec<String>,
|
||||
) -> Scope<'a> {
|
||||
let mut sources: Vec<(&Path, &str)> =
|
||||
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
|
||||
// The same normalization `WorkspaceIndex::build` applies: a stable
|
||||
@@ -41,7 +93,31 @@ impl<'a> Scope<'a> {
|
||||
sources.sort_by(|a, b| a.0.cmp(b.0));
|
||||
sources.dedup_by(|a, b| a.0 == b.0);
|
||||
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.to_path_buf(), *t)));
|
||||
let mut builder = IndexBuilder::new();
|
||||
let mut kept: HashMap<usize, Semantics> = HashMap::new();
|
||||
// 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);
|
||||
}
|
||||
let words = keep(first.and_then(|i| 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);
|
||||
}
|
||||
}
|
||||
|
||||
let index = builder.finish();
|
||||
let ids: HashMap<&Path, FileId> = index
|
||||
.files()
|
||||
.iter()
|
||||
@@ -49,7 +125,7 @@ impl<'a> Scope<'a> {
|
||||
.map(|(i, path)| (path.as_path(), FileId(i as u32)))
|
||||
.collect();
|
||||
let file_ids = sources.iter().map(|(path, _)| ids.get(path).copied()).collect();
|
||||
Scope { sources, index, file_ids, cache: HashMap::new() }
|
||||
Scope { sources, index, file_ids, cache: HashMap::new(), kept }
|
||||
}
|
||||
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
@@ -64,10 +140,6 @@ impl<'a> Scope<'a> {
|
||||
self.sources.get(i).map(|(_, text)| *text)
|
||||
}
|
||||
|
||||
pub(crate) fn sources(&self) -> &[(&'a Path, &'a str)] {
|
||||
&self.sources
|
||||
}
|
||||
|
||||
pub(crate) fn file_id(&self, i: usize) -> Option<FileId> {
|
||||
self.file_ids.get(i).copied().flatten()
|
||||
}
|
||||
@@ -77,11 +149,17 @@ impl<'a> Scope<'a> {
|
||||
}
|
||||
|
||||
/// The two analysis layers for one file, computed on first use.
|
||||
///
|
||||
/// The local half is the one the index build already made, when it was
|
||||
/// kept; otherwise it is parsed here, exactly as it always was. The
|
||||
/// external half is this scope's index resolved against it, and is
|
||||
/// computed here either way — it cannot exist before the index does.
|
||||
pub(crate) fn analysis(&mut self, i: usize) -> Option<&Analysis> {
|
||||
let Scope { sources, index, cache, .. } = self;
|
||||
let Scope { sources, index, cache, kept, .. } = self;
|
||||
let text = sources.get(i).map(|(_, text)| *text)?;
|
||||
Some(cache.entry(i).or_insert_with(|| {
|
||||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||||
let semantics =
|
||||
kept.remove(&i).unwrap_or_else(|| analyze(&parse_source_tolerant(text).0, text));
|
||||
let external = resolve_external(&semantics, index);
|
||||
Analysis { semantics, external }
|
||||
}))
|
||||
@@ -93,6 +171,27 @@ impl<'a> Scope<'a> {
|
||||
self.cache.get(&i)
|
||||
}
|
||||
|
||||
/// One watched file's after-print inputs: the local analysis the
|
||||
/// before-pass already computed, and its uses resolved against `index`.
|
||||
///
|
||||
/// A file the edits did not touch has the same declarations and the same
|
||||
/// uses afterwards — its text did not change — so only what the workspace
|
||||
/// answers *for* those uses can have moved, and re-resolving is the whole
|
||||
/// of the difference. Re-parsing it to learn that is the work take 5 §P2c
|
||||
/// removes.
|
||||
///
|
||||
/// `None` when that file's local analysis has not been computed. The
|
||||
/// caller's own before-pass is what computes it, so that is a
|
||||
/// contradiction rather than a fallback.
|
||||
pub(crate) fn against(
|
||||
&self,
|
||||
i: usize,
|
||||
index: &WorkspaceIndex,
|
||||
) -> Option<(&Semantics, ExternalResolutions)> {
|
||||
let semantics = &self.cached(i)?.semantics;
|
||||
Some((semantics, resolve_external(semantics, index)))
|
||||
}
|
||||
|
||||
/// The workspace index the edits were computed against.
|
||||
pub(crate) fn index(&self) -> &WorkspaceIndex {
|
||||
&self.index
|
||||
@@ -104,3 +203,110 @@ impl<'a> Scope<'a> {
|
||||
pub(crate) fn display(path: &Path) -> String {
|
||||
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FILES: [(&str, &str); 4] = [
|
||||
("/w/sub.sv", "module sub (input logic clk, output logic q);\n wire sig;\n assign q = sig;\nendmodule\n"),
|
||||
("/w/top.sv", "module top;\n logic sig;\n sub u_sub (.clk(1'b0), .q(sig));\n assign u_sub.sig = 1'b0;\nendmodule\n"),
|
||||
("/w/pkg.sv", "package pkg;\n localparam int SIG = 1;\nendpackage\n"),
|
||||
("/w/user.sv", "import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n"),
|
||||
];
|
||||
|
||||
fn files() -> Vec<(PathBuf, String)> {
|
||||
FILES.iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect()
|
||||
}
|
||||
|
||||
/// Every declaration and use one analysis holds, as comparable text — the
|
||||
/// whole observable of a `Semantics` plus its overlay.
|
||||
fn print(analysis: &Analysis) -> String {
|
||||
let mut out = String::new();
|
||||
for symbol in analysis.semantics.symbols() {
|
||||
out.push_str(&format!(
|
||||
"sym {} {:?} {}..{}\n",
|
||||
symbol.name, symbol.kind, symbol.name_span.start, symbol.name_span.end
|
||||
));
|
||||
}
|
||||
for (id, reference) in analysis.semantics.references().iter().enumerate() {
|
||||
out.push_str(&format!(
|
||||
"ref {} {}..{} -> {:?} / {:?}\n",
|
||||
reference.name,
|
||||
reference.name_span.start,
|
||||
reference.name_span.end,
|
||||
reference.resolution,
|
||||
analysis.external.get(vlog_semantic::ReferenceId(id as u32))
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The scope's index is the index a plain `WorkspaceIndex::build` gives —
|
||||
/// same fingerprint, same file ids — however the scope was assembled.
|
||||
#[test]
|
||||
fn assembling_the_scope_file_by_file_builds_the_same_index() {
|
||||
let files = files();
|
||||
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()]);
|
||||
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");
|
||||
assert_eq!(plain.path(i), keeping.path(i));
|
||||
}
|
||||
}
|
||||
|
||||
/// A retained analysis is the analysis the on-demand path would compute.
|
||||
/// This is the whole of §P2b's correctness: what is kept is not a second
|
||||
/// opinion, it is the same one, not thrown away.
|
||||
#[test]
|
||||
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()]
|
||||
});
|
||||
for i in 0..plain.len() {
|
||||
let one = plain.analysis(i).map(print);
|
||||
let two = keeping.analysis(i).map(print);
|
||||
assert_eq!(one, two, "file {i} analyses differently when it is retained");
|
||||
}
|
||||
}
|
||||
|
||||
/// The lead file's analysis is made **before** the rest are parsed, which
|
||||
/// is what lets a caller read the cursor's name off it and ask for that
|
||||
/// name to be kept — without a second parse of anything.
|
||||
#[test]
|
||||
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()
|
||||
});
|
||||
assert_eq!(seen, Some(2), "`user` and `X` are what user.sv declares");
|
||||
assert_eq!(scope.len(), 4);
|
||||
}
|
||||
|
||||
/// 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]
|
||||
fn a_lead_outside_the_scope_retains_nothing_and_still_builds() {
|
||||
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()]
|
||||
});
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Where a rename's time and its whole-file parses went.
|
||||
//!
|
||||
//! Take 5 §P2a (`docs/features/perf5-p2/README.md`): the tail rename costs
|
||||
//! ~780 ms and nobody could say which stage that is. A stopwatch on the wire
|
||||
//! cannot, because every stage of a rename is "read the workspace" in some
|
||||
//! form. So the engine says it itself — one value the caller fills as it goes,
|
||||
//! carrying a wall time and a *parse count* per stage.
|
||||
//!
|
||||
//! **Nothing here changes what a rename decides.** A trace is written to, read
|
||||
//! once and dropped; no branch anywhere reads a field of it. The counters are
|
||||
//! `vlog_parser::stats::parses()` deltas, which is a thread-local `Cell` read,
|
||||
//! and the timers are `Instant`s taken at stage boundaries — the cost of the
|
||||
//! whole instrument is a few dozen nanoseconds on a request measured in
|
||||
//! hundreds of milliseconds.
|
||||
//!
|
||||
//! The counts are the honest half. A wall time moves with the machine's load;
|
||||
//! "this rename parsed 5 200 whole files where 1 300 would do" does not, which
|
||||
//! is why the parse-count assertions in the tests are written against these
|
||||
//! fields rather than against a stopwatch.
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
/// A stage's wall time and the whole-file parses it ran.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct Stage {
|
||||
/// Milliseconds spent inside the stage.
|
||||
pub ms: f64,
|
||||
/// Whole-file parses the stage ran — a `vlog_parser::stats::parses()`
|
||||
/// delta, so a lex failure (which parses nothing) is not counted.
|
||||
pub parses: u64,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
/// Run `work`, recording its wall time and its parses into `self`.
|
||||
///
|
||||
/// Additive: a stage measured twice accumulates, which is what the
|
||||
/// per-file loops want.
|
||||
pub(crate) fn measure<T>(&mut self, work: impl FnOnce() -> T) -> T {
|
||||
let (started, parses) = (Instant::now(), vlog_parser::stats::parses());
|
||||
let out = work();
|
||||
self.ms += started.elapsed().as_secs_f64() * 1000.0;
|
||||
self.parses += vlog_parser::stats::parses() - parses;
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// What the verification pass did, stage by stage.
|
||||
///
|
||||
/// The five sub-stages of [`crate::check`]'s `verify`, in the order it runs
|
||||
/// them. `checks` is the comments/attributes ledger and the parse-diagnostic
|
||||
/// comparison — zero for a rename, which runs neither (a rename may not change
|
||||
/// the token stream at all, which is a stronger statement than the ledger's).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct VerifyTrace {
|
||||
/// Token identity over every edited file, before against after.
|
||||
pub tokens: Stage,
|
||||
/// How many files the resolution check watches, and their total bytes.
|
||||
pub watched: usize,
|
||||
/// Bytes of those watched files.
|
||||
pub watched_bytes: usize,
|
||||
/// The pre-edit analysis of every watched file (cached ones are free).
|
||||
pub before: Stage,
|
||||
/// Building the index as it would be after the edits.
|
||||
pub rebuild: Stage,
|
||||
/// The post-edit analysis of every watched file, and the comparison.
|
||||
pub after: Stage,
|
||||
/// The ledger and parse-diagnostic checks a splice runs; zero for a
|
||||
/// rename.
|
||||
pub checks: Stage,
|
||||
}
|
||||
|
||||
/// Where one rename's work went: the input it was given, the time and parses
|
||||
/// of each stage, and what came out.
|
||||
///
|
||||
/// Filled by [`crate::rename_traced`] as it runs. Every field is written
|
||||
/// exactly once except the [`Stage`]s inside `verify`, which accumulate over
|
||||
/// their per-file loops.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct RenameTrace {
|
||||
/// Files handed to the engine, after the scope's own dedup.
|
||||
pub selected: usize,
|
||||
/// Their total bytes.
|
||||
pub bytes: usize,
|
||||
/// Building the request-local scope: the index over every selected file.
|
||||
pub index: Stage,
|
||||
/// Resolving the cursor to the declaration the rename acts on.
|
||||
pub locate: Stage,
|
||||
/// Collecting every occurrence and turning it into edits.
|
||||
pub edits: Stage,
|
||||
/// The whole verification pass.
|
||||
pub verify: Stage,
|
||||
/// Its five sub-stages.
|
||||
pub checks: VerifyTrace,
|
||||
/// Describing the occurrences the rename deliberately left alone.
|
||||
pub warnings: Stage,
|
||||
/// Files the rename edits.
|
||||
pub edited: usize,
|
||||
/// Whole-file parses over the entire request, from the first byte of the
|
||||
/// scope build to the last warning.
|
||||
pub parses: u64,
|
||||
}
|
||||
|
||||
impl RenameTrace {
|
||||
/// One line, in the server's `timing:` style — the whole trace, in the
|
||||
/// order the stages ran.
|
||||
pub fn line(&self) -> String {
|
||||
format!(
|
||||
"selected={} bytes={} edited={} index={:.1}ms locate={:.1} edits={:.1} \
|
||||
verify{{total={:.1} tokens={:.1} watched={} watched_bytes={} before={:.1} \
|
||||
rebuild={:.1} after={:.1} checks={:.1}}} warnings={:.1} \
|
||||
parses={} parses{{index={} locate={} edits={} before={} rebuild={} after={}}}",
|
||||
self.selected,
|
||||
self.bytes,
|
||||
self.edited,
|
||||
self.index.ms,
|
||||
self.locate.ms,
|
||||
self.edits.ms,
|
||||
self.verify.ms,
|
||||
self.checks.tokens.ms,
|
||||
self.checks.watched,
|
||||
self.checks.watched_bytes,
|
||||
self.checks.before.ms,
|
||||
self.checks.rebuild.ms,
|
||||
self.checks.after.ms,
|
||||
self.checks.checks.ms,
|
||||
self.warnings.ms,
|
||||
self.parses,
|
||||
self.index.parses,
|
||||
self.locate.parses,
|
||||
self.edits.parses,
|
||||
self.checks.before.parses,
|
||||
self.checks.rebuild.parses,
|
||||
self.checks.after.parses,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -201,6 +201,25 @@ impl FileFacts {
|
||||
facts_of(path, src)
|
||||
}
|
||||
|
||||
/// [`FileFacts::of`], handing back the [`Semantics`] the record was read
|
||||
/// off instead of dropping it.
|
||||
///
|
||||
/// The mirror of [`FileFacts::from_analysis`]: that one is for a caller
|
||||
/// who already has an analysis, this one for a caller who is about to want
|
||||
/// the analysis it makes anyway. [`FileFacts::of`] parses the file,
|
||||
/// analyses it, reads the record off that analysis and drops it — so a
|
||||
/// caller who then wants the analysis pays for a second whole-file parse
|
||||
/// of text nothing has touched. A request-local refactoring scope wants
|
||||
/// exactly both (take 5 §P2b, `docs/features/perf5-p2/README.md`).
|
||||
///
|
||||
/// The two are **one function**: `of` is this one with the analysis
|
||||
/// discarded, so the record cannot depend on which was called. The same
|
||||
/// stack requirement applies — call it on a thread with at least
|
||||
/// `vlog_parser::PARSE_STACK_SIZE`.
|
||||
pub fn analyzed(path: PathBuf, src: &str) -> (FileFacts, Semantics) {
|
||||
analyzed_facts(path, src)
|
||||
}
|
||||
|
||||
/// The same record read off an analysis the caller **already has** — the
|
||||
/// tree, the `` `define`` table and the [`Semantics`] of one file — instead
|
||||
/// of from that file's text.
|
||||
@@ -275,13 +294,20 @@ impl Census {
|
||||
|
||||
/// Parse one file and read off what it declares and what it points at.
|
||||
pub(super) fn facts_of(path: PathBuf, src: &str) -> FileFacts {
|
||||
analyzed_facts(path, src).0
|
||||
}
|
||||
|
||||
/// [`facts_of`], keeping the analysis — the one body both it and
|
||||
/// [`FileFacts::analyzed`] are, so the record is the same either way.
|
||||
fn analyzed_facts(path: PathBuf, src: &str) -> (FileFacts, Semantics) {
|
||||
let (tree, defines, census) = parse_and_collect(src);
|
||||
let sem = analyze(&tree, src);
|
||||
// One pass over the source's newlines, so every declaration below can be
|
||||
// given its line without anyone reading the file again later. It is a
|
||||
// percent of the parse it sits beside (`docs/perf/README.md`).
|
||||
let lines = LineIndex::new(src);
|
||||
facts_from_analysis(path, &tree, defines, &sem, src, &lines, census)
|
||||
let facts = facts_from_analysis(path, &tree, defines, &sem, src, &lines, census);
|
||||
(facts, sem)
|
||||
}
|
||||
|
||||
/// Read off what one file contributes, from its finished analysis.
|
||||
|
||||
@@ -2192,16 +2192,12 @@ fn as_a_server_analyzes(
|
||||
(tree, defines, sem, vlog_parser::LineIndex::new(src), tokens)
|
||||
}
|
||||
|
||||
/// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two.
|
||||
///
|
||||
/// The record format is the comparison — the encoded line is every field the
|
||||
/// index and the persistent store ever read — so a byte-equal line is the
|
||||
/// whole equivalence. Two paths that could drift here would be a corruption
|
||||
/// seed: the index would describe a buffer by facts its own parse disagrees
|
||||
/// with.
|
||||
#[test]
|
||||
fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
|
||||
let crafted = [
|
||||
/// The crafted files the two record-equality tests and the §P2b analysis
|
||||
/// tests all read: nothing, nothing that lexes, every file-scope declaration
|
||||
/// kind, macros, external candidates, a file-scope instantiation, a generate
|
||||
/// body and a tree with error nodes.
|
||||
fn crafted_sources() -> &'static [&'static str] {
|
||||
&[
|
||||
// Nothing at all, and nothing that lexes.
|
||||
"",
|
||||
" \n\t\n",
|
||||
@@ -2228,8 +2224,19 @@ fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
|
||||
\x20 sub u_gen (.clk(clk));\n end endgenerate\nendmodule\n",
|
||||
// A tree with error nodes: the tolerant parse still contributes.
|
||||
"module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n",
|
||||
];
|
||||
for src in crafted {
|
||||
]
|
||||
}
|
||||
|
||||
/// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two.
|
||||
///
|
||||
/// The record format is the comparison — the encoded line is every field the
|
||||
/// index and the persistent store ever read — so a byte-equal line is the
|
||||
/// whole equivalence. Two paths that could drift here would be a corruption
|
||||
/// seed: the index would describe a buffer by facts its own parse disagrees
|
||||
/// with.
|
||||
#[test]
|
||||
fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
|
||||
for src in crafted_sources() {
|
||||
let path = PathBuf::from("/w/x.sv");
|
||||
let (tree, defines, sem, lines, tokens) = as_a_server_analyzes(src);
|
||||
let from_text = FileFacts::of(path.clone(), src);
|
||||
@@ -2244,6 +2251,75 @@ fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `FileFacts::analyzed` is `FileFacts::of` keeping its analysis (take 5 §P2b).
|
||||
///
|
||||
/// Two claims, both over the same crafted set the record-equality test uses:
|
||||
/// the record is the record `of` gives, byte for byte in its encoded form; and
|
||||
/// the `Semantics` handed back is the one a caller would have computed for
|
||||
/// itself with `analyze(&parse_source_tolerant(src).0, src)` — which is what
|
||||
/// makes retaining it instead of re-parsing a pure saving rather than a second
|
||||
/// opinion. `Semantics` has no `PartialEq`, so the comparison is every
|
||||
/// declaration and every use it holds, with its span, kind and resolution.
|
||||
#[test]
|
||||
fn analyzed_gives_the_record_of_gives_and_the_analysis_a_caller_would_compute() {
|
||||
for src in crafted_sources() {
|
||||
let path = PathBuf::from("/w/x.sv");
|
||||
let (facts, sem) = FileFacts::analyzed(path.clone(), src);
|
||||
let from_text = FileFacts::of(path, src);
|
||||
assert_eq!(facts, from_text, "the records differ for {src:?}");
|
||||
assert_eq!(facts.encode(), from_text.encode(), "and their encoded forms for {src:?}");
|
||||
let alone = semantics(src);
|
||||
assert_eq!(print_of(&sem), print_of(&alone), "the analyses differ for {src:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every declaration and every use one analysis holds, as comparable text.
|
||||
fn print_of(sem: &Semantics) -> String {
|
||||
let mut out = String::new();
|
||||
for symbol in sem.symbols() {
|
||||
out.push_str(&format!(
|
||||
"sym {} {:?} {}..{} decl {}..{} type {:?}\n",
|
||||
symbol.name,
|
||||
symbol.kind,
|
||||
symbol.name_span.start,
|
||||
symbol.name_span.end,
|
||||
symbol.decl_span.start,
|
||||
symbol.decl_span.end,
|
||||
symbol.type_name
|
||||
));
|
||||
}
|
||||
for reference in sem.references() {
|
||||
out.push_str(&format!(
|
||||
"ref {} {}..{} -> {:?}\n",
|
||||
reference.name,
|
||||
reference.name_span.start,
|
||||
reference.name_span.end,
|
||||
reference.resolution
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An index built file-by-file from `FileFacts::analyzed` is the index a whole
|
||||
/// `WorkspaceIndex::build` over the same texts gives — same fingerprint, which
|
||||
/// is the workspace's own witness for "the same index".
|
||||
#[test]
|
||||
fn an_index_from_analyzed_facts_is_the_index_a_build_gives() {
|
||||
let files: Vec<(PathBuf, &str)> = crafted_sources()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, src)| (PathBuf::from(format!("/w/{i}.sv")), *src))
|
||||
.collect();
|
||||
let built = WorkspaceIndex::build(files.iter().map(|(p, s)| (p.clone(), *s)));
|
||||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||||
for (path, src) in &files {
|
||||
builder.add_facts(FileFacts::analyzed(path.clone(), src).0);
|
||||
}
|
||||
let assembled = builder.finish();
|
||||
assert_eq!(assembled.fingerprint(), built.fingerprint());
|
||||
assert_eq!(assembled.files(), built.files(), "and the same file ids");
|
||||
}
|
||||
|
||||
/// The same claim over every file of the real corpus, which is where the
|
||||
/// constructs nobody thought to craft live.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,693 @@
|
||||
# perf5-p2 — rename reuses its analysis, verification untouched
|
||||
|
||||
Take 5 §P2 (`docs/performance_take5.md`), TODO §60.2. Stages P2a → P2b → P2c.
|
||||
**P2d (source-set narrowing) and topology handshake 33 are not this lane's**;
|
||||
no source set is narrowed or shared here.
|
||||
|
||||
## Goal
|
||||
|
||||
A hierarchical rename on OpenTitan costs about **780 ms** and nobody could say
|
||||
which stage that is. This lane first *measures* it (P2a: an additive trace
|
||||
carrying per-stage wall time and per-stage **whole-file parse counts**), then
|
||||
removes the repeated work the measurement names — the same file parsed and
|
||||
analysed two, three, four times inside one request — without touching a single
|
||||
one of the verifier's checks. P2b makes the request-local scope parse and
|
||||
analyse each file **once** and keep what later stages need; P2c builds the
|
||||
after-edit index from the unchanged files' existing facts plus the edited
|
||||
files' one new analysis, and re-resolves the untouched watched files against it
|
||||
rather than re-analysing them.
|
||||
|
||||
What the user sees must not move at all: the same edits, the same warnings, the
|
||||
same refusal sentences, the same fingerprints. A faster partial edit is a
|
||||
failure, and so is a faster refusal that refuses something else.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A rename is answered on one thread.** `vlog_parser::stats::parses()` is
|
||||
thread-local, so a stage's parse delta is that stage's own work. This is
|
||||
§P1's assumption too, and the server is single-threaded per request.
|
||||
- **`FileFacts::of(path, src)` and the `Semantics` its own read-off was made
|
||||
from describe the same text.** P2b keeps that `Semantics` instead of dropping
|
||||
it; it does not recompute it, so the two cannot disagree. The additive
|
||||
`FileFacts::analyzed` is literally `facts_of`'s body with the analysis handed
|
||||
back rather than dropped.
|
||||
- **`parse_source_tolerant(src).0` and `parse_and_collect(src).0` are the same
|
||||
tree.** `parse_source_tolerant` is `tokenize` + `parse_tolerant`, with
|
||||
`parser::error_file` on a lex failure; `parse_and_collect` is the same two
|
||||
branches. So the `Semantics` a scope retains is the one
|
||||
`Scope::analysis` used to compute for itself.
|
||||
- **Retention is a cache, never an oracle.** A file whose analysis was not
|
||||
retained is analysed on demand exactly as before, so a retention rule that
|
||||
guesses wrong costs time and can never change an answer.
|
||||
- **`contains_word(text, name)` implies `text.contains(name)`.** The verifier's
|
||||
watched set is the whole-word one and the occurrence walk's prefilter is the
|
||||
substring one, so every watched file is one the substring rule retains.
|
||||
- The corpus is OpenTitan `00981352642fb65ef2b6c47143a0f6bb31fd4a97` with the
|
||||
three pre-existing modified files, read-only, as in §P0/§P1.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed.**
|
||||
|
||||
- `vlog_parser::stats::parses()` — §P1's per-thread whole-file parse counter.
|
||||
This lane counts deltas around stages and asserts formulas on them.
|
||||
- `vlog_semantic::workspace`: `FileFacts::of` / `IndexBuilder::{new, add_facts,
|
||||
finish}` / `WorkspaceIndex::{build, absorb, fingerprint}` and the contract in
|
||||
`docs/topo.md` §3 that **`absorb` must equal one build over the resulting
|
||||
record set**. P2c depends on exactly that sentence and pins it by test.
|
||||
- `lucisv_server::state::Workspace::rename_sources`' rung ladder — climbed
|
||||
unchanged; only the sink it inserts into changed.
|
||||
|
||||
**Promised / requested (topo edges for the lead).**
|
||||
|
||||
1. `vlog_refactor ──▶ vlog_semantic`: **new additive API
|
||||
`FileFacts::analyzed(path, src) -> (FileFacts, Semantics)`** — `FileFacts::of`
|
||||
handing back the analysis it read the record off instead of dropping it. No
|
||||
codec change; `FACTS_FORMAT` untouched (nothing new is persisted).
|
||||
2. `vlog_refactor` public surface: **`rename_traced` and the `RenameTrace` /
|
||||
`VerifyTrace` / `Stage` values**. Additive; `rename` is `rename_traced` with
|
||||
a trace nobody reads, so there is no second rename path.
|
||||
3. `lucisv_server ──▶ vlog_refactor`: `rename::rename_traced` replaces
|
||||
`rename::rename` at the one call site (`server/dispatch.rs`), and
|
||||
`Workspace::rename_sources_traced` replaces `rename_sources`. Both are the
|
||||
old function with an out parameter; the ladder and the engine are unchanged.
|
||||
4. `lucisv_server` internal: new module `rename_trace.rs` (`Rung`, `Wanted`,
|
||||
`SelectionTrace`) — the path set the fan-out fills, which now remembers
|
||||
which rung filled it.
|
||||
|
||||
**Not touched.** `check::verify` / `verify_splice` / `verify_move` compare
|
||||
exactly what they compared before: token identity, the resolution-identity
|
||||
print, the comments/attributes ledger, parse-diagnostic preservation. Every
|
||||
hunk in `check/` changes an **input** to a check — where a `Semantics` or an
|
||||
index came from — and none changes a comparison. `module_sources`,
|
||||
`offer_sources` and `imports::sources` are untouched; no selector is narrowed
|
||||
or shared, so handshake 33 stays P2d's prerequisite and is not reached here.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] **P2a** — `RenameTrace` in `vlog_refactor` (`trace.rs`), `SelectionTrace`
|
||||
in `lucisv_server` (`rename_trace.rs`), one `timing: rename trace …` line
|
||||
behind `--verbose`, the `renametrace` harness phase, eight renames
|
||||
measured with peak RSS, tracker rows and experiment `P2a-2026-09-07`.
|
||||
- [x] **P2b** — one parse + analysis per file inside the request-local scope
|
||||
(`FileFacts::analyzed`, `Scope::build_keeping`), experiment
|
||||
`P2b-2026-09-07`.
|
||||
- [x] **P2c** — the after-index from unchanged facts plus the edited files'
|
||||
one new analysis; untouched watched files re-resolve rather than
|
||||
re-analyse (`check/after.rs`), experiment `P2c-2026-09-07`.
|
||||
- [x] measured: **`K + E` whole-file parses, asserted**; the tail rename
|
||||
**1.86×** faster (**target ≥2× missed by 28 ms** — the remaining stage
|
||||
is named below); `aes` rename **25 % faster**, not slower; every edit,
|
||||
warning and refusal fingerprint identical to the §P0 REF; the queued
|
||||
definition down 24.5 %; peak RSS unchanged or lower on all eight rows.
|
||||
- [ ] QA.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-07 — dev, P2a: the instrument
|
||||
|
||||
**Files.** New `crates/vlog_refactor/src/trace.rs` (`Stage`, `VerifyTrace`,
|
||||
`RenameTrace`); `rename/mod.rs` gains `rename_traced` with `rename` delegating
|
||||
to it; `check/mod.rs::verify` gains a `&mut VerifyTrace` parameter and times
|
||||
its five sub-stages; `lib.rs` re-exports. New
|
||||
`crates/lucisv_server/src/rename_trace.rs`; `state.rs`'s five rung functions
|
||||
take a `&mut Wanted` instead of a `&mut BTreeSet<PathBuf>` and say which rung
|
||||
they are on (**+23 lines net in `state.rs`** — `git diff --numstat` 35/12, all of it
|
||||
the traced entry point and five `wanted.on(…)` lines; no selection logic
|
||||
changed);
|
||||
`server/dispatch.rs` logs one line when `--verbose`; new
|
||||
`tools/perf/phases_p2.py` with the `renametrace` phase and a `RSTMGR` site.
|
||||
|
||||
**Deviations from the brief, and why.**
|
||||
|
||||
- The trace is an **out parameter** (`&mut RenameTrace`,
|
||||
`&mut Option<String>`) rather than half of the `Ok` value. A rename that
|
||||
*refuses* after 2.1 s is one of the seven rows the plan asks for, and a
|
||||
`Result<(Edit, Trace), String>` throws the trace away on exactly those rows.
|
||||
- `Workspace::rename_sources` and `lucisv_server::rename::rename` were
|
||||
**collapsed into their traced forms** rather than kept as one-line wrappers:
|
||||
with the production path on the traced form the wrappers are dead code in a
|
||||
non-test build, and `#[allow(dead_code)]` on a public method to keep a
|
||||
wrapper alive is worse than the four mechanical `.0`s it saves. The call
|
||||
sites updated are two benchmarks in `perf.rs` (outside the brief's file list
|
||||
— flagged here) and four test helpers.
|
||||
|
||||
**What the 780 ms tail rename is.** Repeat medians of four requests, release
|
||||
binary `bf584aa0daf6…`, `renametrace` row *tail: state_q → state_q_x*, wire
|
||||
**781.7 ms**:
|
||||
|
||||
| Stage | ms | whole-file parses |
|
||||
|---|---:|---:|
|
||||
| selection (`rename_sources`, server) | 13.4 | 0 |
|
||||
| `Scope::build` — the index over the input | 228.5 | **238** |
|
||||
| `locate` | 0.5 | 1 |
|
||||
| `collect_edits` (the occurrence walk) | 116.3 | **134** |
|
||||
| `verify` — token identity | 4.3 | 0 |
|
||||
| `verify` — before-prints (analyses already cached) | 14.0 | 0 |
|
||||
| `verify` — `rebuilt_index` | **228.4** | **238** |
|
||||
| `verify` — after analyses + compare | 71.5 | **106** |
|
||||
| `warnings` | 83.6 | 0 |
|
||||
| **total** | **760.5** of 781.7 | **717** |
|
||||
|
||||
- The **input is 238 files / 4.55 MB**, not the two the edit touches. The rungs:
|
||||
request 1, declaration 95, reference 122, instantiation 19, macro 0,
|
||||
speller 0, open buffer 1. So the "2 files" of the tracker's output row is
|
||||
0.8 % of the input, and the fan-out is dominated by the declaration and
|
||||
reference rungs of `state_q` — a name 95 files declare.
|
||||
- **717 whole-file parses over 238 files.** Every file is parsed for the index,
|
||||
134 again by the occurrence walk, all 238 again by `rebuilt_index`, and 106
|
||||
again for the after-prints. `K + E` — one parse per input file plus one per
|
||||
edited file — is **240**. The other 477 are the duplication §P2b/§P2c exist
|
||||
to remove.
|
||||
- **The two 228 ms stages are the same work twice**: `Scope::build` and
|
||||
`rebuilt_index` are both `WorkspaceIndex::build` over 238 texts, and only two
|
||||
of those texts differ between them.
|
||||
- The 83.6 ms of `warnings` runs **zero** parses: it is tokenizing, not
|
||||
parsing, and it is out of P2b/P2c's reach.
|
||||
|
||||
**The other six rows, in one paragraph each's worth of numbers.** The ordinary
|
||||
`aes` rename: 13 files / 400 KB, 51 parses, 140.5 ms — index 23.4, edits 19.2,
|
||||
verify 63.3 (rebuild 22.4, after 20.3), warnings 23.4. A **unique internal
|
||||
name** (`cipher_alert`, 4 files): 10 parses, 22.3 ms — the shape the fan-out is
|
||||
built for. A **common port name** (`clk_i` at its declaration): the fan-out's
|
||||
ambiguity hatch fires, the input is the **whole workspace** — 3 976 files /
|
||||
35.8 MB, **10 399 parses**, **7 142 ms**, peak RSS **1 864 MiB**; the edit is
|
||||
still 2 edits in 2 files. The **conflict** row (`state_q` → `state_d`) refuses
|
||||
correctly after 634 ms, having done 638 parses. A new name a great many
|
||||
external uses spell (`cipher_alert` → `clk_i`) refuses after 5 291 ms and 9 229
|
||||
parses. A **duplicate module name** (`rstmgr_por`, declared in four files)
|
||||
takes the same hatch and refuses after 2 116 ms — of which 1 837 ms is a
|
||||
whole-workspace `Scope::build` and 242 ms the selection, and **none** of it is
|
||||
the refusal, which `locate` reaches in 1.8 ms. A cursor on **no symbol at all**
|
||||
is the same shape through a different door (`rename.rs` hands `ws.sources()`
|
||||
over when there is no name to fan out from): 2 111 ms, 3 976 parses.
|
||||
|
||||
**Where the answer is that the 780 ms goes.** 29 % `Scope::build`, 29 %
|
||||
`rebuilt_index` (the same build again), 15 % the occurrence walk's re-parses,
|
||||
9 % the after analyses, 11 % warnings, 2 % selection. **73 % of it is
|
||||
whole-file parsing, and two thirds of that parsing is repeated work.**
|
||||
|
||||
**Reference agreement.** Every §P0 REF row was re-taken on this binary and
|
||||
every fingerprint is byte-identical: tail rename `b39defb21265…` (817.5 /
|
||||
789.5–782.2 ms against REF 813.4 / 778.8–782.1), `aes` rename `fa7e31c78382…`
|
||||
(168.4 / 141.3–140.1 against 167.6 / 140.5–142.1), connect-missing-ports
|
||||
`4b534a16bca7…` (174.9 / 164.9–162.8 against 171.4 / 165.8–167.5),
|
||||
expand-wildcard `8f3a26dd147b…` (78.4 / 69.8–71.1 against 73.6 / 71.7–73.0),
|
||||
organize-imports resolve `0ee027e37d07…`, the extract capture `090e92e7736e…`
|
||||
(258.5 / 245.0–243.4 against 257.3 / 245.1–247.0), the definition behind the
|
||||
rename 159.0 / 158.9 / 154.3 (against 163.4 / 161.6 / 161.1). The
|
||||
instrumentation costs nothing measurable, which is what a stage timer and a
|
||||
`Cell` increment should cost.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-07 — QA (Sonnet), P2a/P2b/P2c verification
|
||||
|
||||
**Scope.** TODO §60.2's P2a/P2b/P2c only. Handshake 33 and P2d are not this
|
||||
lane's and are not touched or judged here. Read CLAUDE.md, `docs/topo.md`,
|
||||
`docs/performance_take5.md` §P2, `docs/perf/take5-tracking.md`'s P2 rows and
|
||||
experiments, `docs/features/refactor-rename/README.md`'s verification story,
|
||||
the working-tree diff, and the evidence in `~/.cache/lucisv-perf/take5-p2/`.
|
||||
Note early: the dev's P2b/P2c work-log entries (§P2b at line 206, §P2c at
|
||||
line 271 of this file) landed *after* this QA log/Review heading pair instead
|
||||
of under Work log — a structural slip, not a content problem (nothing in
|
||||
them belongs in Review). Flagged for the lead; not reordered here since
|
||||
moving another agent's prose is not a "small unambiguous fix."
|
||||
|
||||
**1. Gates, guarded, in the main tree.** `tools/guard.sh -m 8 -t 1800 --
|
||||
cargo fmt --all -- --check`: clean. `cargo clippy --all-targets`: clean,
|
||||
0.12 s (cache already warm from the dev's own build); no `#[allow]` anywhere
|
||||
in `git diff`. `cargo test --workspace`: **4231 passed, 0 failed**, matches
|
||||
the dev's count exactly; zero guard kills. Load 3.46/4.62/5.07 before, no
|
||||
spike.
|
||||
|
||||
Per-crate/binary counts, candidate vs. a HEAD (`dafa4f0`, the pre-P2 P1c
|
||||
commit) build in a disposable clone
|
||||
(`/private/tmp/.../scratchpad/qa-p2/head-clone`), both **full** `cargo test
|
||||
--workspace` runs (not `-p`-restricted, so this is the true baseline):
|
||||
HEAD **4215 passed, 0 failed**, matching the tracker's stated pre-lane count
|
||||
exactly. Deltas, all growth, none dropped: `vlog_refactor` unittests 123→135
|
||||
(+12: 4 in `scope::tests`, 3 in `check::after::tests`, 5 in
|
||||
`rename::tests`); `vlog_refactor` `tests/rename.rs` 70→70 (unchanged, as
|
||||
claimed — the refusal-list tests were not touched); `vlog_semantic`
|
||||
unittests 36→36 (unchanged); `vlog_semantic` `tests/workspace.rs` 87→89 (+2:
|
||||
`analyzed_gives_the_record_of_gives_and_the_analysis_a_caller_would_compute`,
|
||||
`an_index_from_analyzed_facts_is_the_index_a_build_gives`); `lucisv_server`
|
||||
unittests 1545→1547 (+2, `rename_trace`'s own tests). Every other crate
|
||||
(`vlog_parser`, `vlog_linter`, `vlog_formatter`, `lucisv`, `lucisv_core`)
|
||||
unchanged. 4215+16=4231 ties out exactly to every individual diff above —
|
||||
no test was quietly removed and replaced.
|
||||
|
||||
Production line counts: `check/mod.rs` **405** (measured: everything before
|
||||
`#[cfg(test)]` at line 603, non-blank non-comment), `after.rs` **39**
|
||||
(before `#[cfg(test)]` at line 86) — both match the dev's claim exactly.
|
||||
Nothing over 600. `state.rs` `git diff --numstat`: 35 insertions / 12
|
||||
deletions = **net +23**, inside the "~20 lines" the brief allowed and
|
||||
matching the dev's own count; the diff is exactly the traced entry point
|
||||
(`rename_sources_traced`) plus the six `wanted.on(Rung::...)` lines — no
|
||||
selection-logic line changed.
|
||||
|
||||
**2. The verifier, hunk by hunk.** Read `git diff crates/vlog_refactor/src/
|
||||
check/mod.rs` end to end plus the new `after.rs`. Confirmed: `Print`,
|
||||
`print`, `anchor_of`, `Shifts`, `Excluded`, `watched_files`, `tokens_match`,
|
||||
`first_difference`, `check/ledger.rs` (not in the diff at all — zero
|
||||
changes) and the parse-diagnostic comparison in `verify_move` are
|
||||
byte-identical in logic; the diff only threads a `&mut VerifyTrace`/
|
||||
`Stage::measure` through the same call sequence and replaces the inline
|
||||
`rebuilt_index`/re-`analyze` block with calls to `after::{after_index,
|
||||
after_print}`. No comparison changed; only where a `Semantics`/index comes
|
||||
from did.
|
||||
|
||||
**Pre-existing verifier attacks, re-run.** `check::tests`' `tokens_match`
|
||||
pairs (8), `check/ledger.rs`'s ~19 `_is_rejected`/`_is_refused` tests,
|
||||
`removing_an_import_a_reference_needs_is_rejected`,
|
||||
`crates/vlog_refactor/tests/rename.rs`'s ~15 refusal tests — all still
|
||||
refuse (covered by the full-workspace green run above; spot-ran
|
||||
`check::ledger::tests` and `tests/rename.rs` individually too, both clean).
|
||||
|
||||
**Sabotage, in a fresh clone (`sabotage-clone`, `git diff` patch applied +
|
||||
untracked files copied — verified `git status --porcelain` matched the
|
||||
working tree before any sabotage) — each reverted immediately after and
|
||||
`vlog_refactor --lib` re-run clean (135/135) to confirm the revert:**
|
||||
|
||||
- **(i) stale retained analysis for an edited file.** Forced `after_print`
|
||||
to always take the retained/before-edit analysis, even for edited files
|
||||
(`let _ = edited; { scope.against(i, index)... }`). Result: **4 tests
|
||||
failed** — `a_rename_parses_each_input_file_once_and_each_edited_file_once_more`,
|
||||
`the_traced_rename_and_the_plain_one_are_the_same_call`,
|
||||
`the_trace_accounts_for_every_parse_the_rename_ran`, and (for a revealing
|
||||
reason) `a_rename_that_would_make_a_third_files_use_ambiguous_is_refused`
|
||||
— whose "an unclaimed name still renames" half now fails because *every*
|
||||
edited-file rename refuses. The dev's own named target test
|
||||
(`a_rename_whose_edit_rebinds_a_name_in_the_edited_file_is_refused`)
|
||||
still shows `ok`, but only because the sabotage's collateral over-refusal
|
||||
masks the narrow capture case — not proof of that one check in isolation.
|
||||
**Finding, not blocking:** the target attack test alone is not a clean
|
||||
isolation test for this sabotage; the *real* signal is the 4-test
|
||||
collateral failure, which is unambiguous. Recommend the dev split
|
||||
"capture inside the edited file" from "index/print machinery" more
|
||||
finely if this needs a sharper single-assertion pin later — not required
|
||||
for this lane's merge.
|
||||
- **(ii) after-index forgetting facts.** Two variants: (a) literal reading
|
||||
of the brief — `index.absorb(records, &edited_paths_as_gone)` — is a
|
||||
**no-op** (`gone` is dropped, then the same paths are immediately
|
||||
reinserted from `records`); all tests still pass. This is a finding: the
|
||||
brief's literal phrasing does not describe a real bug in this API's
|
||||
semantics. (b) the doc comment's own named rejected alternative — drop
|
||||
every *unedited* file from the cloned index before absorbing (`gone` =
|
||||
every in-scope path not in `edited`) — **fails 2 tests**:
|
||||
`an_absorbed_after_index_is_the_index_a_rebuild_would_give` and
|
||||
`absorbing_an_edited_file_keeps_every_file_id`, both immediately and
|
||||
clearly. The dev's named target,
|
||||
`a_rename_that_would_make_a_third_files_use_ambiguous_is_refused`, still
|
||||
passes under this sabotage too — traced why: dropping `b.sv` entirely
|
||||
makes `use.sv`'s `taken_pkg::V` resolve unambiguously to the wrong
|
||||
file (`a.sv`, freshly re-added) instead of ambiguously, and the
|
||||
resolution-identity check's anchor comparison catches *that* difference
|
||||
independently (defense in depth) — a legitimate positive finding, but it
|
||||
means the "third file" test is not the one that actually detects index
|
||||
forgetting; the fingerprint/rebuild-equality tests are. Recommend the
|
||||
README's claim ("an after-index built from the edited files alone... —
|
||||
would have forgotten the third file's declaration") cite
|
||||
`an_absorbed_after_index_is_the_index_a_rebuild_would_give` as the pin,
|
||||
not (only) the third-file rename test.
|
||||
- **(iii) print keyed by FileId, not path.** `anchor_of`'s
|
||||
`index.path(def.file)` replaced with `PathBuf::from(format!("#{}",
|
||||
def.file.0))`. Fails exactly and only the named target,
|
||||
`a_print_names_paths_so_shifted_file_ids_cannot_change_it`, cleanly (left
|
||||
`"#0"`, right `"#1"` for the same file across two indexes with an
|
||||
inserted-first file). Precise, as predicted.
|
||||
|
||||
**Two attack pairs of my own**, added to the sabotage clone (not merged;
|
||||
disposable), both pass on the real code:
|
||||
- `qa_after_print_of_an_edited_file_reflects_its_own_edited_text` — an
|
||||
ordinary one-file rename's returned edits must rename *both* the
|
||||
declaration and the use; passes.
|
||||
- `qa_a_file_retained_only_by_the_substring_rule_never_changes_the_answer`
|
||||
— a third file (`third.sv`) spelling `outsig` (contains `sig` as a
|
||||
substring, never as a whole word: `contains_word(THIRD, "sig")` is
|
||||
false, `THIRD.contains("sig")` is true) is retained by
|
||||
`Scope::build_keeping`'s substring rule but excluded from
|
||||
`watched_files`'s whole-word rule. Confirms by direct assertion (not just
|
||||
reasoning) that its presence, retained or entirely removed from the
|
||||
workspace, produces byte-identical edits and warnings — the superset
|
||||
claim (retained ⊇ watched) holds and is harmless where it is a strict
|
||||
superset. Passes.
|
||||
- Adversarial after-index case of my own, in `check/after.rs`'s test
|
||||
module: `qa_an_edited_file_that_declares_a_name_another_file_already_has_is_ambiguous_like_a_rebuild`
|
||||
— editing `sub.sv` to add a *second* `package pkg;` (an unrelated file,
|
||||
`pkg.sv`, already declares `pkg`) and asserting the absorbed after-index
|
||||
reports `pkg` exactly as ambiguous as a full rebuild does (fingerprint +
|
||||
file list + per-name `answers()` all equal). Passes — `absorb`'s
|
||||
`merge(None)` is a full re-derivation by construction, so this holds by
|
||||
the same argument `an_absorbed_after_index_is_the_index_a_rebuild_would_give`
|
||||
already pins, but it is now pinned on this specific adversarial shape too.
|
||||
|
||||
**4. Parse-count formula, sabotaged.** Re-added a redundant
|
||||
`parse_source_tolerant(text)` call inside `Scope::analysis` unconditionally
|
||||
(even when `kept.remove(&i)` would hit). `a_rename_parses_each_input_file_once_and_each_edited_file_once_more`
|
||||
fails immediately: `left: 14, right: 10` (the `K+E=10` formula breaks the
|
||||
moment `locate`/`edits` stop being free). Reverted; test green again.
|
||||
|
||||
**5. Fingerprint/FileId proofs.** Read
|
||||
`an_absorbed_after_index_is_the_index_a_rebuild_would_give` (9 cases) and
|
||||
`absorbing_an_edited_file_keeps_every_file_id` — both sound, both already
|
||||
covered above under sabotage (ii-b), which is exactly the sabotage these
|
||||
two tests are built to catch. Added my own 10th adversarial case (above,
|
||||
"an edited file that adds a second declaration of a package already
|
||||
declared elsewhere"); passes.
|
||||
|
||||
**3. Wire parity, old vs. new — 8 `renametrace` rows + 5 of my own.** Built
|
||||
`dafa4f0` (pre-P2, post-P1c) release server in the disposable clone; ran
|
||||
`tools/perf/phases_p2.py`'s `renametrace` phase against it and against the
|
||||
candidate `target/release/lucisv-server` (sha256
|
||||
`1601b13a9bacda47095cb23580e475ac8f33a171f446875484439ec67d58eb31` —
|
||||
**matches the tracker's P2c entry exactly; no rebuild performed**, satisfying
|
||||
item 7's binary-identity check for the re-measurement below too). All 8
|
||||
rows' fingerprints and refusal sentences byte-identical between the two
|
||||
binaries and equal to the tracker's REF/P2a-c values: `b39defb21265…`,
|
||||
`fa7e31c78382…`, `5f53e977da59…`, `31aadc134628…`, and the shared refusal
|
||||
fingerprint `96f32d4243b1…` on all three refusal rows plus the no-symbol
|
||||
row's message. Candidate-side trace fields also reproduce the tracker's
|
||||
numbers exactly (tail: parses 240 = 238+2, `rungs_declaration=95
|
||||
rungs_reference=122 rungs_instantiation=19`; `clk_i` fallback: 3977 parses,
|
||||
fallback=true, selected=3976).
|
||||
|
||||
Five renames of my own (`tools/perf`-style script, run from the QA
|
||||
scratchpad, not committed to the dev's tree): a **port**
|
||||
(`entropy_clearing_ack_i` in `aes_core.sv`, connected from `aes.sv`), a
|
||||
**parameter** (`SecStartTriggerDelay`, used in `aes.sv`/`aes_control.sv`/
|
||||
`aes_core.sv`), a **package member** (`aes_pkg::AES_OP_WIDTH`, used from
|
||||
`aes_cov_if.sv`/`aes_core_fi_vseq.sv`), a **module with many
|
||||
instantiations** (`prim_flop_2sync`, the 128-file fan-out cursor from
|
||||
`sites.FANOUT_CURSORS`), and a **name inside a generate block**
|
||||
(`delay_cntr_q` in `tlul_delayer.sv`'s `gen_delay_logic` block). All 5
|
||||
succeeded (no refusals) on both binaries and all 5 fingerprints are
|
||||
byte-identical HEAD vs. candidate.
|
||||
|
||||
`git -C ~/repo/opentitan status --porcelain` checked after every phase
|
||||
(the 8-row runs ×2 binaries, the 5-row runs ×2 binaries, the P0-run for
|
||||
per-crate test counts does not touch opentitan): unchanged, always exactly
|
||||
the three pre-existing modified files.
|
||||
|
||||
**6. Memory, re-taken on the candidate.** `clk_i` fallback peak RSS:
|
||||
**1574 MiB** (mine) vs. the dev's P2c **1830 MiB** — lower, not higher (no
|
||||
"exceeds by >10%" concern; if anything the gap the other way is larger than
|
||||
10%, plausibly host load variance between runs — flagged, not blocking,
|
||||
since "lower" cannot itself be a corruption or perf regression). Tail
|
||||
rename peak RSS: **584 MiB** (mine) vs. dev's **593 MiB** — within 2%.
|
||||
Neither approaches the 8 GiB guard (fallback is 19% of it).
|
||||
|
||||
**7. Re-measured on the P2c binary.** Binary confirmed byte-identical to
|
||||
the tracker's P2c entry by sha256 (above) — no rebuild. `renametrace`'s
|
||||
ms medians on my run: tail 421.0 (dev 419.9, +0.3%), `aes` 106.8 (dev
|
||||
106.3, +0.5%), `clk_i` fallback 3882.7 (dev 3860.1, +0.6%) — all within
|
||||
±10%, fingerprints identical (above). Did not re-run `tailrename` /
|
||||
`rename` / `blockers` / `refactor` / `execute` as separately-named `bench.py`
|
||||
phases beyond `renametrace`'s own tail/`aes` rows and the fingerprint
|
||||
survey in item 3, given time budget; the tracker's own P2c figures for
|
||||
those rows are independently corroborated by the traceability check below
|
||||
(item 8) reading the same raw evidence files the dev's prose quotes.
|
||||
|
||||
**8. Traceability — 15+ numbers cross-checked against
|
||||
`~/.cache/lucisv-perf/take5-p2/*.jsonl` directly (not just the README's
|
||||
prose):** `results-p2a.jsonl`'s tail row: `trace_parses_index=238,
|
||||
trace_parses_locate=1, trace_parses_edits=134, trace_parses_rebuild=238,
|
||||
trace_parses_after=106`, summing to **717**, matching `trace_parses=717`
|
||||
exactly. `results-p2c.jsonl`'s tail row: `238+0+0+2+0` = **240**, matching
|
||||
`trace_parses=240`. `results-probe-updatefacts.jsonl`'s
|
||||
`trace_verify_rebuild`: tail 53.3, `aes` 40.2, `clk_i` 400.9 — exactly the
|
||||
"two `update_facts`" numbers the README's P2c work-log quotes.
|
||||
`results-p2c.jsonl`'s own `trace_verify_rebuild` for the same three rows:
|
||||
37.2, 23.4, 269.7 — exactly the "one `absorb`" numbers the same paragraph
|
||||
quotes. All eight `renametrace` fingerprints (item 3). The P2c sha256
|
||||
(item 7/3). Stage-sum arithmetic (this item). That is 8 (fingerprints) + 6
|
||||
(rebuild-cost pairs) + 1 (sha256) + the two parse sums = well over 15
|
||||
independent numbers, all reproduced from the raw `.jsonl`, not taken on
|
||||
faith from the README's prose.
|
||||
|
||||
**9. The `--verbose` trace line.** Ran the tail rename twice from a
|
||||
disposable script: once with `verbose=False` (0 `timing: rename trace`
|
||||
lines in `window/logMessage`), once with `verbose=True` (exactly 1 line,
|
||||
419 characters, no embedded newline, fields in the documented order).
|
||||
Confirms the line is verbose-gated and single-line as claimed.
|
||||
|
||||
**Guard / resource notes.** Every `cargo` command and every server session
|
||||
above went through `tools/guard.sh -m 8 -t 1800`. **Zero guard kills**
|
||||
across the whole QA pass. No `cargo` command ran concurrently with a timed
|
||||
phase (checked `ps` before each; the one background `cargo build --release`
|
||||
for the HEAD comparison binary completed before any timed harness run
|
||||
started). Peak RSS on every row stayed far under the 8 GiB limit (worst
|
||||
case ~1.6 GiB).
|
||||
|
||||
**Verdict: PASS**, for P2a/P2b/P2c only. Findings above are non-blocking
|
||||
(one documentation-structure slip, two notes about which existing test
|
||||
actually pins which sabotage class, one note that the dev's cited
|
||||
literal-`gone` sabotage reading is a no-op) and are recorded for the lead
|
||||
and for whoever picks up P2d/handshake 33 next, not required fixes for this
|
||||
merge. Handshake 33 and P2d remain open and are not judged here.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-07 (lead, P2a–P2c).** Accepted. Read `scope.rs`'s assemble /
|
||||
`build_keeping` / `against`, `check/after.rs` and every hunk of
|
||||
`check/mod.rs`, `trace.rs`, `rename_trace.rs`, the tracker's three
|
||||
experiment entries and both logs; QA's independent HEAD baseline (4215 →
|
||||
4231, no test dropped) and its wire parity over thirteen renames are the
|
||||
acceptance.
|
||||
|
||||
- P2a is the finding that shaped the rest: "2 files" was 238 input files,
|
||||
4.55 MB and 717 whole-file parses, two thirds of them repeated — one
|
||||
`WorkspaceIndex::build` over 238 files twice, and every watched file
|
||||
twice more. The trace makes that visible on the `--verbose` channel and
|
||||
nowhere else, which is the right place.
|
||||
- P2b/P2c are the boring version of the fix: the index build hands back
|
||||
the analysis it already made (`FileFacts::analyzed`, `of` = `.0` so no
|
||||
drift), the request's own file is analysed first so the cursor's name is
|
||||
known before the rest are parsed, retention is a cache and never an
|
||||
oracle, and the after-index is the before-index plus the edited files'
|
||||
absorbed records. Every hunk in `check/` moves an input; no comparison
|
||||
changed, and the three new attack pairs plus QA's two say so. K + E
|
||||
parses, asserted from the trace, is the invariant the next round inherits.
|
||||
- Target: tail rename 780 → 420 ms (1.86× against the 2× goal, short by
|
||||
30 ms); the remaining 225 ms is one parse of each of the 238 *selected*
|
||||
files, so the lever left is the selection — P2d, behind handshake 33, in
|
||||
its own lane. `aes` rename −25%, both resolves −20%, the extract
|
||||
capture −39%; the `aes_wrap.sv` extract refusal unchanged because it is
|
||||
selection (a package name's `module_sources`), the same lever.
|
||||
- QA's non-blocking findings noted: attack (i) is caught by collateral
|
||||
refusals rather than by its named test alone, and attack (ii)'s literal
|
||||
form is a no-op while its stronger form fails the pinning tests — both
|
||||
are defence in depth working, and the named tests stay as the pins.
|
||||
- Memory: peak RSS moved by less than 20 MiB everywhere and fell on the
|
||||
two heaviest renames; the fallback stays at 1.8 GiB, the number P2d
|
||||
should also bring down.
|
||||
- Deviations accepted: the trace as an out parameter (refusals traced
|
||||
too), the collapse of the untraced wrappers, the two touched files
|
||||
outside the list (`perf.rs` call sites, one `mod` line).
|
||||
|
||||
Docs applied at merge: topo edges (1)–(4) from Handshakes.
|
||||
|
||||
### 2026-09-07 — dev, P2b: one parse per file inside the scope
|
||||
|
||||
**The additive semantic API.** `FileFacts::analyzed(path, src) -> (FileFacts,
|
||||
Semantics)` (`vlog_semantic/src/workspace/record.rs`). `facts_of`'s body is now
|
||||
this function, and `facts_of` is `analyzed_facts(path, src).0` — so the record
|
||||
cannot depend on which was called, and there is no second read-off to drift.
|
||||
No codec change: nothing new is persisted and `FACTS_FORMAT` is untouched. The
|
||||
approach the brief named first — rebuilding a record with
|
||||
`FileFacts::from_analysis` — was rejected because that constructor needs the
|
||||
token slice the parser consumes, so a caller would have to clone every file's
|
||||
tokens to feed it; handing back the analysis the read-off already used costs
|
||||
nothing and cannot disagree.
|
||||
|
||||
**The scope.** `Scope::assemble` replaces `WorkspaceIndex::build` with an
|
||||
`IndexBuilder` loop over `FileFacts::analyzed`, so each file is parsed and
|
||||
analysed exactly once and the analysis is *kept* rather than dropped.
|
||||
`Scope::build(files)` keeps none — every existing caller (`ports`, `imports`,
|
||||
`extract`, `inline`, `references`) behaves and costs exactly as before.
|
||||
`Scope::build_keeping(files, lead, keep)` is the rename's: it analyses `lead`
|
||||
(the request's own file) **first**, hands that analysis to `keep`, and retains
|
||||
every file whose text `contains` one of the words `keep` names.
|
||||
`Scope::analysis(i)` takes the retained `Semantics` when there is one and
|
||||
parses otherwise, so **retention is a cache and never an oracle**.
|
||||
|
||||
**Why the lead-first ordering.** The words worth keeping are the new name and
|
||||
the name under the cursor, and the cursor's name is only knowable from the
|
||||
cursor file's analysis. Analysing it first makes that analysis the file's own
|
||||
one-and-only parse instead of an extra one, which is what keeps the budget at
|
||||
`K` rather than `K + 1`. The name is read with `rename_name_at` — the same
|
||||
function the server's fan-out is built from, whose agreement with the target
|
||||
the rename acts on is already pinned by
|
||||
`the_name_a_fan_out_is_built_from_is_the_name_the_engine_acts_on`.
|
||||
|
||||
**Why a substring test and not `contains_word`.** `collect_occurrences`'
|
||||
prefilter is `text.contains(&target.name)` and the verifier's watched set is
|
||||
`contains_word`, which is a subset of it. Retaining on the substring rule
|
||||
therefore covers every file either of them will ask for, and nothing else.
|
||||
|
||||
**Memory, which is why retention is not unconditional.** §P2a measured the
|
||||
all-sources fallback (`clk_i`, 3 976 files / 35.8 MB) at **1 864 MiB** peak
|
||||
while holding ~1 250 analyses. Retaining all 3 976 would have been roughly
|
||||
0.8 MiB × 3 976 ≈ 3.9 GiB on top of the index — inside the 8 GiB guard but a
|
||||
2× regression on a row that is already the worst. The `keep` rule holds the
|
||||
retained set to exactly the files the request was going to analyse anyway, and
|
||||
the measurement says so: the fallback's peak went **1 864 → 1 840 → 1 830 MiB**
|
||||
across §P2a/§P2b/§P2c, and the `cipher_alert → clk_i` row **1 809 → 1 695 →
|
||||
1 590**. No row's peak rose by more than 20 MiB.
|
||||
|
||||
**Measured** (release `e555e6c79d8d…`, repeat medians of four requests, load
|
||||
5.1 → 3.8, corpus unchanged after every phase, zero guard kills). Tail rename
|
||||
**781.7 → 676.6 ms**, parses **717 → 582** — `locate` 1 → 0 and the occurrence
|
||||
walk 134 → 0. `aes` rename **140.5 → 122.6**, parses 51 → 38. Every fingerprint
|
||||
unchanged.
|
||||
|
||||
**Tests.** `analyzed_gives_the_record_of_gives_and_the_analysis_a_caller_would_compute`
|
||||
(`vlog_semantic/tests/workspace.rs`) — the record and its encoded form against
|
||||
`FileFacts::of`, and the analysis against
|
||||
`analyze(&parse_source_tolerant(src).0, src)`, over the crafted set the
|
||||
existing `from_analysis` equality test uses (which is now a shared
|
||||
`crafted_sources()`); `an_index_from_analyzed_facts_is_the_index_a_build_gives`
|
||||
— fingerprint and file list. In `vlog_refactor`, four `scope::tests`:
|
||||
the same index however it is assembled, a retained analysis equal to the
|
||||
on-demand one file by file, the lead's analysis available to the retention
|
||||
rule, and a lead outside the scope retaining nothing without failing.
|
||||
|
||||
### 2026-09-07 — dev, P2c: the after-index from unchanged facts
|
||||
|
||||
**New module `crates/vlog_refactor/src/check/after.rs`** (39 production
|
||||
lines), holding the two functions that build the state after the edits, out of
|
||||
`check/mod.rs` (**427 → 405** production lines) so each file keeps one
|
||||
sentence.
|
||||
|
||||
- `after_index(scope, edited)` — the before-index **cloned and absorbed**, plus
|
||||
the edited files' one new analysis each, handed back for their after-prints.
|
||||
It replaces `rebuilt_index`, which was `WorkspaceIndex::build` over every
|
||||
in-scope text.
|
||||
- `after_print(scope, i, path, index, edited, excluded)` — the edited file's
|
||||
own new analysis when the edits touched it, and otherwise the analysis the
|
||||
before-pass already computed, re-resolved against the after-index
|
||||
(`Scope::against`). It replaces the `analyze(&parse_source_tolerant(text).0,
|
||||
text)` both `verify` and `verify_move` ran for **every** watched file.
|
||||
|
||||
**Every hunk changes an input, never a check.** `verify` still compares token
|
||||
identity over each edited file, the before-print against the after-print for
|
||||
every watched file, and (in `verify_move`) the comments/attributes ledger and
|
||||
the parse-diagnostic count. `Print`, `print`, `Shifts`, `Excluded`,
|
||||
`watched_files`, `tokens_match` and `first_difference` are untouched. The
|
||||
refusal sentences are the same strings.
|
||||
|
||||
**`absorb` against `update_facts`, measured.** The plan warned that an
|
||||
incremental-looking API may still rebuild global tables, and `absorb` does:
|
||||
`merge(None)` clears every table and re-pushes from all records.
|
||||
`update_facts` per record uses the restricted merge instead. It is **slower**:
|
||||
the tail rename's rebuild stage was **37.2 ms with one `absorb`** and
|
||||
**53.3 ms with two `update_facts`**, the `aes` rename's 23.4 against 40.2, the
|
||||
`clk_i` fallback's 269.7 against 400.9 — the restricted merge walks the same
|
||||
records and pays a name-set lookup at every declaration, which costs more than
|
||||
the push it skips. `absorb` kept; the probe's rows are in
|
||||
`~/.cache/lucisv-perf/take5-p2/results-probe-updatefacts.jsonl`. Either way the
|
||||
parse saving stands: the after-index costs **E** parses, not **K**.
|
||||
|
||||
**Measured** (release `1601b13a9bac…`, repeat medians of four requests, load
|
||||
5.2 → 2.8, corpus unchanged after every phase, zero guard kills).
|
||||
|
||||
| Row | §P0 REF | §P2a | §P2b | §P2c | vs REF |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| tail rename (`tailrename`) | 780.45 | 784.19 | 674.68 | **419.86** | **−46.2 %** |
|
||||
| `aes` rename (`rename`) | 141.30 | 140.15 | 123.08 | **106.31** | **−24.8 %** |
|
||||
| definition behind the rename (`blockers`, mean of pipelines 2–3) | 161.33 | 156.48 | 141.64 | **121.85** | **−24.5 %** |
|
||||
| connect missing ports resolve | 166.51 | 164.91 | 165.29 | **132.72** | **−20.3 %** |
|
||||
| expand wildcard resolve | 71.89 | 70.31 | 70.29 | **54.91** | **−23.6 %** |
|
||||
| extract command executed (`execute`) | 246.03 | 244.53 | 244.78 | **149.25** | **−39.3 %** |
|
||||
| extract refused at `aes_wrap.sv` 66:2 | ~801 | 802.03 | 802.07 | **801.23** | **0 %** |
|
||||
| organize-imports resolve | 9.45 | 11.99 | 11.18 | **8.51** | −10 % |
|
||||
|
||||
Whole-file parses on the tail rename: **717 → 240**, which is `K + E` =
|
||||
238 + 2, asserted as a formula by
|
||||
`a_rename_parses_each_input_file_once_and_each_edited_file_once_more`. On the
|
||||
all-sources fallback: **10 399 → 3 977**. Every fingerprint on every row is
|
||||
byte-identical to the §P0 REF's (`b39defb21265…`, `fa7e31c78382…`,
|
||||
`4b534a16bca7…`, `8f3a26dd147b…`, `0ee027e37d07…`, `090e92e7736e…`), and the
|
||||
three refusal rows carry the same sentences and the same empty-edit
|
||||
fingerprint `96f32d4243b1…`.
|
||||
|
||||
**The target that was missed, and the stage that is left.** ≥2× on the tail
|
||||
rename needed **390.2 ms**; the measurement is **419.9**, i.e. **1.86×**, short
|
||||
by 29.7 ms. The trace says exactly where the remaining 418 ms is:
|
||||
|
||||
| Stage | ms | share | parses |
|
||||
|---|---:|---:|---:|
|
||||
| `Scope::build` — one parse of each of the 238 selected files | **225.1** | 54 % | 238 |
|
||||
| `warnings` — a **token** scan of every file spelling the name | **83.3** | 20 % | 0 |
|
||||
| `verify` | 73.0 | 17 % | 2 |
|
||||
| … of which the after-index (clone + absorb) | 37.2 | 9 % | 2 |
|
||||
| … before-prints | 14.0 | 3 % | 0 |
|
||||
| … token identity | 4.5 | 1 % | 0 |
|
||||
| … after-prints | 7.9 | 2 % | 0 |
|
||||
| selection (server fan-out) | 13.4 | 3 % | 0 |
|
||||
| `collect_edits` | 12.1 | 3 % | 0 |
|
||||
| server + transport + position conversion | ~11 | 3 % | — |
|
||||
|
||||
**There is no duplicated parsing left to remove.** The 225 ms is the *first*
|
||||
and only parse of each selected file, and the only way past it is to select
|
||||
fewer files (§P2d, which is not this lane) or to hand the engine records the
|
||||
server's own index already holds (a step §P2b's plan deliberately defers,
|
||||
because file ids and the subset's resolution universe differ). The 83 ms of
|
||||
`warnings` is `tokenize` + `LineIndex` per file that spells the name — not a
|
||||
parse, already guarded by the same prefilter, and untouched by this lane.
|
||||
|
||||
**Tests.** `check::after::tests` — `an_absorbed_after_index_is_the_index_a_rebuild_would_give`
|
||||
compares fingerprint, file list **and** a query-level print (`units`,
|
||||
`references_to`, `instantiations_of`, `hierarchical_declarations`,
|
||||
`workspace_symbols`) against a full rebuild on nine cases: an ordinary
|
||||
one-file and two-file rename edit, a file that gains a declaration, one that
|
||||
loses it and leaves a dangling use, an edit that changes what *another* file
|
||||
resolves to, an edited package under a re-export chain, an `export`ed chain
|
||||
losing its export, a module that stops being instantiated, and an edit that
|
||||
makes a file stop lexing. `absorbing_an_edited_file_keeps_every_file_id` pins
|
||||
id stability.
|
||||
|
||||
**The three new attack pairs**, aimed at the reuse itself:
|
||||
|
||||
1. `a_rename_whose_edit_rebinds_a_name_in_the_edited_file_is_refused` — an
|
||||
edited file whose after-print came from the *before* analysis would describe
|
||||
text that no longer exists. The rename gives `sig` the name of an existing
|
||||
`taken` in the same file, which only a print of the **edited** text can
|
||||
catch; it is refused.
|
||||
2. `a_rename_that_would_make_a_third_files_use_ambiguous_is_refused` — an
|
||||
after-index built from the edited files alone (or absorbed with a wrong
|
||||
`gone`) would have forgotten the untouched `b.sv`. The rename renames
|
||||
`a_pkg` to a package `b.sv` already declares, and the refusal is *about*
|
||||
`use.sv`, which is neither edited nor mentioned by the edits. The same test
|
||||
asserts an unclaimed new name still renames, so the refusal is not blanket.
|
||||
3. `a_print_names_paths_so_shifted_file_ids_cannot_change_it` — the same file's
|
||||
print against two indexes whose `FileId`s differ by one everywhere must be
|
||||
the same print, so the comparison cannot start depending on the id stability
|
||||
`absorb` happens to give.
|
||||
|
||||
Every existing verifier attack is untouched and still refuses:
|
||||
`check::tests`' eight `tokens_match` pairs, the ledger attacks in
|
||||
`check/ledger.rs`, `removing_an_import_a_reference_needs_is_rejected`, and the
|
||||
rename refusals in `rename/tests.rs` and `tests/rename.rs`.
|
||||
|
||||
**Test counts.** 4 215 before this lane → 4 225 after §P2b → **4 231** after
|
||||
§P2c; no test was removed or weakened. `cargo fmt --all -- --check` clean,
|
||||
guarded `cargo clippy --all-targets` clean with **no new `#[allow]`**, guarded
|
||||
`cargo test --workspace` green before each of the three release builds. No
|
||||
`cargo` command ran during any timed phase; **zero guard kills**;
|
||||
`git -C ~/repo/opentitan status --porcelain` showed the same three files after
|
||||
every one of the nineteen timed phases.
|
||||
|
||||
**Deviations and things the lead should rule on.**
|
||||
|
||||
- `Scope::sources()` was deleted: `rebuilt_index` was its only caller.
|
||||
- `crates/lucisv_server/src/perf.rs` (outside the brief's list) — two benchmark
|
||||
call sites moved to `rename_traced` / `rename_sources_traced`, mechanical.
|
||||
- `crates/lucisv_server/src/main.rs` (outside the brief's list) — one line,
|
||||
`mod rename_trace;`, which is how the new module is reachable at all.
|
||||
- **Not done, deliberately:** the extract refusal at `aes_wrap.sv` 66:2 is
|
||||
still ~801 ms. It refuses immediately after `Scope::build`, so there is no
|
||||
repeated analysis to remove; its cost is `module_sources` selecting hundreds
|
||||
of files for a *package* name, which is the §P1 finding filed for §P2d and
|
||||
handshake 33.
|
||||
+275
-25
@@ -35,10 +35,10 @@ The order follows the plan. Later stages are conditional on the preceding measur
|
||||
| P1a | Gate lint/fence/config by requested kinds; avoid fence work without fixes | P0 | dev (Opus) → QA PASS → lead; committed 2026-09-07 | Done | `docs/features/perf5-p1/README.md`; experiment `P1a-2026-09-07` below. Pinmux `only: []` 82.80 → **0.064 ms**; quickfix 84.13 → **23.53**; all families 309.60 → **258.06**. Separates the base at last: lint+config **23.5 ms**, fence parse **59.3 ms** |
|
||||
| P1b | Shared parsed selectors; revision-bound fence reuse; invalidate any additional cache correctly | P1a | dev (Opus) → QA PASS → lead; committed 2026-09-07 | Done | Same README; experiment `P1b-2026-09-07`. Pinmux all families **24.02 ms** (−92.2% on REF), queued definition **24.61** (−92.0%). Lint-result reuse **not done** — reason and number in the experiment entry |
|
||||
| P1c | Engine-owned lightweight ports/import offers | Reprofile P1b | dev (Opus) → QA REWORK on one documentation point, ruled and applied by the lead → committed 2026-09-07 | Done | `docs/features/perf5-p1/README.md`; experiment `P1c-2026-09-07` below. `aes_reg_top` lazy offer 21.83 → **5.46 ms**, its ports family 21.15 → **3.27**; `aes` 7.76 → **1.74**; the organize-imports offer 15.39 (REF) → **4.88**. **All three targets met.** Answers identical to P1b on 50 rows and to the REF on 65, field by field; the three resolve fingerprints unchanged |
|
||||
| P2a | Rename per-stage timings and selected/watched/input counts | P0 | — | Not started | — |
|
||||
| P2b | Reuse per-file input analysis in request-local scope | P2a | — | Not started | — |
|
||||
| P2c | Reuse unchanged after-facts/semantics; re-resolve external references | P2b | — | Not started | — |
|
||||
| P2d | Exact-name postings; source-set narrowing only with whole-scope proof | Reprofile P2c; topology 33 for shared module selector | — | Not started | — |
|
||||
| P2a | Rename per-stage timings and selected/watched/input counts | P0 | dev (Opus); release `bf584aa0daf6…` → QA PASS → lead; committed 2026-09-07 | Done | `docs/features/perf5-p2/README.md`; experiment `P2a-2026-09-07` below. The tail rename's 780 ms is **238 input files / 4.55 MB and 717 whole-file parses**: `Scope::build` 228.5 ms, the occurrence walk 116.3, `rebuilt_index` 228.4 (the same build again), the after analyses 71.5, warnings 83.6, selection 13.4. 73 % of the request is whole-file parsing and two thirds of that parsing is repeated |
|
||||
| P2b | Reuse per-file input analysis in request-local scope | P2a | dev (Opus); release `e555e6c79d8d…` → QA PASS → lead; committed 2026-09-07 | Done | Same README; experiment `P2b-2026-09-07`. Additive `FileFacts::analyzed`; `Scope::build_keeping` analyses the request's file first, reads the cursor's name off it and retains the analyses the rest of the request will ask for. Tail rename 781.7 → **676.6 ms**, parses 717 → **582**; peak RSS unchanged or lower on all eight rows |
|
||||
| P2c | Reuse unchanged after-facts/semantics; re-resolve external references | P2b | dev (Opus); release `1601b13a9bac…` → QA PASS → lead; committed 2026-09-07 | Done | Same README; experiment `P2c-2026-09-07`. New `vlog_refactor/src/check/after.rs`: the after-index is the before-index cloned and **absorbed**, and an untouched watched file's after-print is its existing analysis re-resolved. Tail rename **419.9 ms (−46.2 % on REF, 1.86×)**, parses **240 = K + E**; every fingerprint identical. **Target ≥2× missed by 29.7 ms**; the remaining stage is `Scope::build`'s one parse of each of the 238 *selected* files (225 ms), which only §P2d can reach |
|
||||
| P2d | Exact-name postings; source-set narrowing only with whole-scope proof | Reprofile P2c; topology 33 for shared module selector | — | Not started | Reprofiled: after §P2c the tail rename is 419.9 ms of which **225 ms is one parse of each selected file** and 83 ms a token scan. There is no duplicated parsing left; the next lever is the size of the selected set |
|
||||
| P3 | Reuse CLI census parse for package exports/interfaces | P0; coordinate semantic ownership | — | Not started | — |
|
||||
| P4a | Attribute scan/prelude/table-build/cache/RSS cost | P0 | — | Not started | — |
|
||||
| P4b | Implement the dominant measured startup/memory fix | P4a; serialize with state/index changes | — | Not started | — |
|
||||
@@ -82,19 +82,23 @@ REF and part of each delta is §P1b's.
|
||||
| `aes` lazy offer (`codeaction`) | 12.39 / 8.15–9.11 ms; 1 action | Repeated <5 ms | **REF** 13.87 / 7.33–9.66 ms; 1 action — REF median **8.17**. **P1a** 14.30 / 7.21–9.60, median 7.92. **P1b** 11.41 / 7.11–9.70, median **7.76**; 1 action in every try. **P1c** 2.72 / 1.60–2.03, median **1.74**; 1 action in every try | REF vs baseline −8.0%. **P1a −3.1%, P1b −5.0%, P1c −77.6% on P1b** | **Target <5 ms met at P1c.** The other three fan-out cursors fall with it: 42 → **0.77**, 67 → **1.78**, 128 → **1.38** ms lazy |
|
||||
| `aes_reg_top` lazy offer (`codeaction`) | 32.81 / 22.45–25.09 ms; 2 actions | Repeated <10 ms | **REF** 30.64 / 22.72–24.42 ms; 2 actions — REF median **23.31**. **P1a** 32.24 / 22.08–24.17, median 23.60. **P1b** 31.50 / 20.93–24.42, median **21.83**; 2 actions in every try. **P1c** 6.92 / 4.80–5.62, median **5.46**; 2 actions in every try | REF vs baseline +1.0%. **P1a +1.3% (no change), P1b −6.3%, P1c −75.0% on P1b (−76.6% on REF)** | **Target <10 ms met at P1c.** P1b's residue was the discarded ports plan; §P1c replaced it with a predicate. The 5.46 ms left is dominated by the one parse of `aes_reg_top.sv` (52 461 B, 2.16–2.43 ms standalone) |
|
||||
| `aes_reg_top` ports-only offer (`offer-breakdown`) | 21.72 / 21.55–21.78 ms; 0 port actions | Remove throwaway edit computation | **REF (`offerkinds`)** 22.27 / 22.46–22.56 ms; 0 port actions — REF median **22.47**. **P1a** 21.68 / 21.28–21.89, median 21.84. **P1b** 20.86 / 21.14–21.48, median **21.15**; 0 port actions. **P1c** 3.51 / 3.08–3.45, median **3.27**; 0 port actions | REF vs baseline +3.3%. **P1a −2.8%, P1b −5.8%, P1c −84.6% on P1b (−85.5% on REF)** | The row P1c existed for. All four planners refuse at *plan* time here, and the offer used to pay four `WorkspaceIndex::build`s (3.89 ms each, measured) to be told so. The all-family cell at the same cursor is 21.79 → **4.70** |
|
||||
| `state_q` tail rename (`tailrename`) | 821.59 / 789.50–809.83 ms; 2 files | At least 2× faster; stretch <200 ms | **REF** 813.44 / 778.77–782.13 ms; **5 edits / 2 files / 0 created**, fingerprint `b39defb21265…` | −1.4% | Agrees; reference for P2, now with an edit fingerprint to compare against |
|
||||
| Ordinary `aes` rename (`rename`) | 168.67 / 139.34–140.35 ms; 9 files | No regression; exact edit/warning parity | **REF** 167.60 / 140.46–142.13 ms; **14 edits / 9 files / 0 created**, fingerprint `fa7e31c78382…` | +1.2% | Agrees; reference for P2 |
|
||||
| Definition behind ordinary rename (`blockers`) | 145.99–168.79 ms, 3 pipelines | Falls with rename work | **REF** 163.43 / 161.55 / 161.11 ms, 3 pipelines (now `follower_ms.definition`) | inside the baseline range | Agrees |
|
||||
| Connect missing ports resolve (`refactor`) | 170.77 / 164.79–165.82 ms; 1 file | Measure collateral benefit; exact edit parity | **REF** 171.37 / 165.77–167.45 ms; 1 file, REF median **166.51**, fingerprint `4b534a16bca7…`. **P1c** 168.01 / 165.15–209.85, median **169.13**; 1 file, 2 edits, **fingerprint identical** | REF vs baseline +0.4%; **P1c +1.6% on REF** | Agrees. The click path is untouched by §P1c and its edit is byte-identical |
|
||||
| Expand wildcard resolve (`refactor`) | 73.02 / 70.35–70.73 ms; 1 file, 32 connections | No lost connections/refusals | **REF** 73.61 / 71.67–73.01 ms; 1 file, 32 connections, REF median **71.89**, fingerprint `8f3a26dd147b…`. **P1c** 76.61 / 69.34–71.40, median **70.22**; 1 file, 32 connections, **fingerprint identical** | REF vs baseline +2.2%; **P1c −2.3% on REF** | Agrees; no connection and no refusal moved |
|
||||
| `state_q` tail rename (`tailrename`) | 821.59 / 789.50–809.83 ms; 2 files | At least 2× faster; stretch <200 ms | **REF** 813.44 / 778.77–782.13 ms; **5 edits / 2 files / 0 created**, fingerprint `b39defb21265…` — REF repeat median **780.45**. **P2a** 817.45 / 789.49–782.21, median 784.19. **P2b** 706.50 / 676.19–673.57, median **674.68**. **P2c** 451.54 / 421.27–419.86, median **419.86**; 5 edits / 2 files / 0 created, **fingerprint identical** | REF vs baseline −1.4%. **P2a +0.5% (no change), P2b −13.6%, P2c −46.2% on REF** | **Target ≥2× missed**, at **1.86×**; stretch <200 ms not approached. The measured remaining stage is `Scope::build` — one parse of each of the **238 selected files**, 225 ms of the 420 — plus 83 ms of `warnings`, a token scan. Whole-file parses fell **717 → 240 = K + E** |
|
||||
| Ordinary `aes` rename (`rename`) | 168.67 / 139.34–140.35 ms; 9 files | No regression; exact edit/warning parity | **REF** 167.60 / 140.46–142.13 ms; **14 edits / 9 files / 0 created**, fingerprint `fa7e31c78382…` — REF repeat median **141.30**. **P2a** 168.44 / 141.31–140.15, median 140.15. **P2b** 142.71 / 123.11–123.08, median **123.08**. **P2c** 126.13 / 107.15–105.95, median **106.31**; 14 edits / 9 files, **fingerprint identical** | REF vs baseline +1.2%. **P2a −0.8%, P2b −12.9%, P2c −24.8% on REF** | Goal was *no regression*; it is **25 % faster**, with byte-identical edits and warnings. Parses 51 → **22 = K + E** |
|
||||
| Common port name `clk_i` at its declaration (`renametrace`, **new**) | not measured | Measure the fan-out's escape hatch | **P2a** 7 249.73 / 7 158.16–7 142.58, median **7 158.16**; the ambiguity hatch fires, so the input is the **whole workspace** — 3 976 files / 35.8 MB, 10 399 parses, peak RSS 1 864 MiB; 2 edits / 2 files, fingerprint `31aadc134628…`. **P2b** median 6 286.13, 9 150 parses, 1 840 MiB. **P2c** 3 985.94 / 3 888.95–3 860.05, median **3 860.05**, **3 977 parses**, 1 830 MiB, **fingerprint identical** | **P2c −46.1% on P2a** | New row, new phase. The worst rename on this corpus, and the one the fallback's cost is really made of. Still 3.9 s: 1 826 ms of it is one parse of each of the 3 976 files, 848 ms `warnings`, 245 ms selection |
|
||||
| Unique internal name (`renametrace`, **new**) | not measured | The shape the fan-out is built for | **P2a** median **23.05 ms**; 4 files / 68 KB, 10 parses, fingerprint `5f53e977da59…`. **P2b** 21.84, 9 parses. **P2c** median **19.84**, **5 parses**, **fingerprint identical** | −13.9% | New row. `cipher_alert` in `aes_core.sv` — the case the six rungs exist to make cheap, and they do |
|
||||
| Conflicting new name, refused (`renametrace`, **new**) | not measured | A refusal is timed as a refusal | **P2a** median **640.81 ms**, 638 parses, `status: refused`. **P2b** 530.26, 498 parses. **P2c** median **331.18**, **244 parses**; same sentence, same empty-edit fingerprint `96f32d4243b1…` | **−48.3%** | New row. `state_q → state_d` in `entropy_src_main_sm.sv`; the verifier still refuses, in the same words, in half the time |
|
||||
| All-sources fallback, ambiguous references (`renametrace`, **new**) | not measured | Do not lose the refusal it exists for | `rstmgr_por` (declared in four files): **P2a** median 2 146.63 ms, **P2c** **2 137.42**; 3 975 parses at both, peak 922 → 927 MiB, same refusal sentence. A cursor on **no symbol** takes the same road through `rename.rs`: 2 136.20 → **2 160.63** | ~0 % | New rows, both unmoved — and correctly so. Both refuse inside `locate`, having paid one whole-workspace `Scope::build` (1 840 ms) and nothing else; there is no repeated work in either for §P2b/§P2c to remove |
|
||||
| Definition behind ordinary rename (`blockers`) | 145.99–168.79 ms, 3 pipelines | Falls with rename work | **REF** 163.43 / 161.55 / 161.11 ms, 3 pipelines (now `follower_ms.definition`) — REF mean of pipelines 2–3 **161.33**. **P2a** 158.88 / 158.80 / 154.17 (mean 2–3 = 156.48). **P2b** 148.86 / 138.02 / 145.25 (141.64). **P2c** 130.87 / 123.37 / 120.32 (**121.85**) | REF inside the baseline range; **P2c −24.5% on REF** | The queued definition follows its blocker exactly as the plan predicted |
|
||||
| Connect missing ports resolve (`refactor`) | 170.77 / 164.79–165.82 ms; 1 file | Measure collateral benefit; exact edit parity | **REF** 171.37 / 165.77–167.45 ms; 1 file, REF median **166.51**, fingerprint `4b534a16bca7…`. **P1c** 168.01 / 165.15–209.85, median **169.13**; 1 file, 2 edits, **fingerprint identical**. **P2a** median 164.91, **P2b** 165.29, **P2c** 142.25 / 131.21–132.72, median **132.72**; 1 file, 2 edits, **fingerprint identical** | REF vs baseline +0.4%; P1c +1.6%; **P2c −20.3% on REF** | The collateral the plan asked to be measured: `verify_splice` reaches the same after-index and the same re-resolution §P2c gave the rename, and the edit is byte-identical |
|
||||
| Expand wildcard resolve (`refactor`) | 73.02 / 70.35–70.73 ms; 1 file, 32 connections | No lost connections/refusals | **REF** 73.61 / 71.67–73.01 ms; 1 file, 32 connections, REF median **71.89**, fingerprint `8f3a26dd147b…`. **P1c** 76.61 / 69.34–71.40, median **70.22**; 1 file, 32 connections, **fingerprint identical**. **P2a** median 70.31, **P2b** 70.29, **P2c** 66.31 / 54.91–55.85, median **54.91**; 1 file, 32 connections, **fingerprint identical** | REF vs baseline +2.2%; P1c −2.3%; **P2c −23.6% on REF** | Agrees; no connection and no refusal moved, and the same §P2c collateral |
|
||||
| Eager 128-fan-out offer (`codeaction`) | 518.32 / 495.60–499.69 ms | Compatibility/perf guardrail; not first priority | **REF** 523.16 / 495.13–496.77 ms; 2 actions — REF median **496.24**. **P1b** 519.49 / 492.71–494.57, median **493.92**; 2 actions. **P1c** 516.78 / 492.51–496.34, median **492.54**; 2 actions | REF vs baseline +0.1%. **P1b −0.5%, P1c −0.3%** | Unchanged, which is the guardrail: the eager path's cost is the module's fan-out, and neither P1b nor P1c touched it — `code_actions` still computes and verifies every plan |
|
||||
| Port-actions **offer**, `aes_wrap.sv` 78:2 (`refactor`, **new**) | not measured as a row — take 4's §6b prose only | Repeated <5 ms; identical titles | **REF (P0)** 38.79 / 24.57–27.80 ms; 2 actions, REF median **24.84**. **P1c** 1.53 / 1.13–1.45, median **1.19**; 2 actions, same titles | **−95.2% on REF** | New row. The site that actually offers a port refactoring on opentitan. Part of the delta is §P1b's gate (0.06–0.14 ms per family), the rest is §P1c. Not run at P1a/P1b |
|
||||
| Organize-imports **offer**, `aes_sbox_canright_masked.sv` 42:2 (`refactor`, **new**) | not measured as a row — take 4 §6c put it at 30.1 / 13.8–19.5 | Repeated <5 ms; identical counts | **REF (P0)** 32.25 / 13.70–18.04 ms; 2 actions, REF median **15.39**. **P1c** 8.42 / 4.69–6.59, median **4.88**; 2 actions, title `lucisv: organize imports (removes 1, sorts 1)` unchanged | **−68.3% on REF** | New row. **Target <5 ms met.** The residue is one `Scope::build` over the buffer and its two packages (2.05 ms standalone); the buffer's own share of it is the handshake request in `perf5-p1`'s README |
|
||||
| Organize-imports **resolve** (`refactor`, **new**) | not measured | No lost removal, sort or refusal | **REF (P0)** 9.87 / 9.45–10.15 ms; 1 file, 1 edit, fingerprint `0ee027e37d07…`, REF median **9.45**. **P1c** 14.62 / 9.96–11.97, median **11.03**; 1 file, 1 edit, **fingerprint identical** | +16.7% on REF, inside this document's ±20% band for a 1–20 ms row | New row. The resolve path is unchanged by §P1c — `organize`'s middle was lifted into `planned` and it still verifies the splice |
|
||||
| First offer after a `didChange`, same cursor (`offeredit`, **new**) | not measured — the gap the P0 entry named | Track separately from the repeated offer | **P1a** pinmux 383.61 / 366.93–369.71 (median 368.32); `aes_reg_top` instance 35.82 / 23.38–26.30 (24.84); `tb.sv` comment 4.80 / 3.28–3.42 (3.35). **P1b** pinmux 152.88 / 132.68–135.04 (median **133.86**); `aes_reg_top` 28.82 / 22.58–22.75 (**22.66**); `tb.sv` 2.29 / 1.90–2.00 (**1.95**) | P1a → P1b: pinmux **−63.7%**, `aes_reg_top` −8.8%, `tb.sv` −41.8% | New row, new phase `offeredit`. Each try is the *first* `codeAction` after its own `didChange`, so the document rebuild is inside the number; the paired "repeated offer on the unchanged buffer" rows sit beside them in the same session (P1b: pinmux **24.18**, `aes_reg_top` **21.65**, `tb.sv` **0.54**). No REF exists — P0 could not measure it |
|
||||
| Extract command actually executed (`execute`, **new**) | not measured — take 4's `extract-module resolve` rows are invalid | Measure the command, not a refusal | **REF** `lucisv.extractModule` at `aes.sv` 220:0–222:53: **257.33 / 245.05–247.00 ms** executeCommand→applyEdit; 2 edits / 2 files / **1 created**; `deliver_ms` 0.015–0.033; status `capture`; fingerprint `090e92e7736e…` | new row | The gap the tracker's work-count table named is closed |
|
||||
| Extract command actually executed (`execute`, **new**) | not measured — take 4's `extract-module resolve` rows are invalid | Measure the command, not a refusal | **REF** `lucisv.extractModule` at `aes.sv` 220:0–222:53: **257.33 / 245.05–247.00 ms** executeCommand→applyEdit; 2 edits / 2 files / **1 created**; `deliver_ms` 0.015–0.033; status `capture`; fingerprint `090e92e7736e…` — REF median **246.03**. **P2a** median 244.53, **P2b** 244.78, **P2c** 161.41 / 149.25–149.86, median **149.25**; 2 edits / 2 files / 1 created, **fingerprint identical** | new row; **P2c −39.3% on REF** | The gap the tracker's work-count table named is closed — and §P2c's `verify_move` reuse is worth 39 % of the one refactoring command that really runs |
|
||||
| Inline command actually executed (`execute`, **new**) | not measured | Measure the command, not a refusal | `lucisv.inlineModule` at `aes_wrap.sv` 66:2 is **refused** (`generate` construct); 6.58 / 5.87–6.20 ms. Not a timing of an inline | new row | Refusal recorded as `refused`; **not quotable** as an inline cost |
|
||||
| Extract offered at the inline cursor, refused (`execute`, **new**) | not measured | — | `lucisv.extractModule` at `aes_wrap.sv` 66:2 refused after **817.37 / 793.77–809.07 ms** | new row | A second ~800 ms user-command path; filed as a finding, not fixed |
|
||||
| Extract offered at the inline cursor, refused (`execute`, **new**) | not measured | — | `lucisv.extractModule` at `aes_wrap.sv` 66:2 refused after **817.37 / 793.77–809.07 ms** — REF median ~801. **P2a** 802.03, **P2b** 802.07, **P2c** median **801.23** | new row; **0 % at P2c** | Unchanged, and correctly so: it refuses *immediately after* `Scope::build`, so there is no repeated analysis for §P2b/§P2c to remove. Its cost is `module_sources` selecting hundreds of files for a **package** name — §P2d and handshake 33 territory |
|
||||
| Cold workspace scan (`scan`, 3 fresh sessions) | 2830.30–2853.06 ms; mean 2843.00 | Investigation goal <2300 ms | **REF** 2860.12–2868.45 ms; mean 2863.85 | +0.7% on means | Agrees |
|
||||
| Warm workspace scan (`scan`, 3 fresh sessions) | 1322.24–1344.03 ms; mean 1332.41 | Investigation goal <1000 ms | **REF** 1346.02–1352.80 ms; mean 1348.94 | +1.2% on means | Agrees |
|
||||
| First useful answer during the scan (`scan`, **new**, 3 fresh sessions) | not measured | Stay responsive during a scan (P4) | **REF** cold **84.42–85.87 ms**, warm **206.12–218.72 ms**; 1 location in every session | new row | Warm is 2.5× *slower* than cold to first answer — carried to P4a |
|
||||
@@ -121,15 +125,15 @@ REF and part of each delta is §P1b's.
|
||||
| Additional parses per no-offer all-family action | 5 text-parse entry points confirmed in source; no runtime counter | Still no runtime counter — P0 is harness-only and adds no production instrumentation. The wire-side attribution is reproduced (`offerkinds`): 82.80 ms shared base at the pinmux cursor, +52.7 to +57.6 ms for any one selector family | **Counter added and asserted on.** `vlog_parser::stats::parses()` counts whole-file parses (thread-local; a request is answered on one thread). At a no-offer cursor a *repeated* all-family `codeAction` performs **0** parses, an `only: []` request **0**, and the first request after a `didChange` **≤2** (the document's own parse, plus the fence answer when a fix exists) — `server::tests::code_action`. On the wire the five parses are gone: a single selector family fell from 58.6–59.7 ms to **0.06–0.14 ms** at the pinmux cursor. **P1c:** at a cursor that *does* offer, a repeated ports offer performs **1** parse — the instantiated module's declaring file — and a repeated organize-imports offer **3**, one `Scope::build` over the buffer and the two packages it imports. Both are asserted by count in `server::tests::code_action` against a `resolveSupport` client, which is the path the offer predicates are on |
|
||||
| Lint/config/fence time separately | About 80 ms combined on generated file; unseparated | Reproduced but still unseparated: pinmux `only: []` 82.80 ms, quickfix 84.13 ms. Separating them needs P1's counters | **Separated by P1a's gates.** `only: []` now answers in **0.064 ms**, so none of the 82.8 ms was unavoidable. Quickfix-only is **23.53 ms** — the configuration read plus the lint pass. The difference, **59.3 ms, was the fence parse**, and it vanished at this cursor because no finding in `pinmux_reg_top.sv` carries a fix, so §P1a's "no fix, no fence" gate skips it outright |
|
||||
| Selector time by family and file size | Filtered ablations preserved in raw data | **Promoted to the committed `offerkinds` phase**: 7 families × 5 cursors × 4 requests, result counts in every row. All-family repeat medians by cursor — tb 1.54 / aes-reg-instance 23.51 / aes-core 10.42 / spi 14.43 / pinmux 309.60 ms. Pinmux by family: `[]` 82.80, quickfix 84.13, extract 140.42, inline 136.37, ports 137.97, organizeImports 135.45 | **P1b, same phase.** All-family repeat medians by cursor — tb **0.60** / aes-reg-instance **21.79** / aes-core **2.30** / spi **3.16** / pinmux **24.02** ms. Pinmux by family: `[]` **0.053**, quickfix **24.05**, extract **0.107**, inline **0.074**, ports **0.063**, organizeImports **0.060** — every selector family is now under a seventh of a millisecond on a 1.3 MB buffer. The one family that did not move is ports **at an offering cursor** (aes-reg-instance 22.47 → **21.15**), which is P1c's row. **P1c, same phase:** aes-reg-instance all families **4.70**, its ports family **3.27** — the last selector family to be measured in whole milliseconds at an offering cursor is now measured in fractions of one, and the 3.27 is dominated by the single parse of the 52 KB declaring file |
|
||||
| Tail rename selected paths / input bytes / selection reasons | Not measured; **2 output files is not input count** | Still not measured (needs P2a's server-side instrumentation). What P0 adds is the **output** side, exactly: 5 edits / 2 files / 0 created, fingerprint `b39defb21265…` | — |
|
||||
| Tail rename watched vs edited paths | Edited 2; watched unmeasured | Edited 2, confirmed by `files`; watched still unmeasured — P2a | — |
|
||||
| Tail rename index / parse / analysis / resolution / verification stage times | Not measured | Not measured — P2a | — |
|
||||
| Ordinary rename selected bytes / stages | Edited 9; other counts unmeasured | Edited 9 confirmed (14 edits, fingerprint `fa7e31c78382…`); stages unmeasured — P2a | — |
|
||||
| Ambiguous-use all-sources fallback frequency | Not measured | Not measured — P2a | — |
|
||||
| Tail rename selected paths / input bytes / selection reasons | Not measured; **2 output files is not input count** | Still not measured (needs P2a's server-side instrumentation). What P0 adds is the **output** side, exactly: 5 edits / 2 files / 0 created, fingerprint `b39defb21265…` | **Measured, §P2a.** **238 files / 4 554 326 bytes**, by rung: request 1, declaration 95, reference 122, instantiation 19, macro text 0, speller 0, open buffer 1, fallback **false**. So the input is 119× the output, and it is the declaration and reference rungs of a name 95 files declare. Unchanged at §P2b/§P2c — this lane narrows nothing |
|
||||
| Tail rename watched vs edited paths | Edited 2; watched unmeasured | Edited 2, confirmed by `files`; watched still unmeasured — P2a | **Measured, §P2a: watched 106 files / 1 919 528 bytes**, edited 2. Before §P2c all 106 were re-parsed for the after-print; now 2 are (the edited ones) and 104 are re-resolved from the analysis the before-pass made |
|
||||
| Tail rename index / parse / analysis / resolution / verification stage times | Not measured | Not measured — P2a | **Measured, §P2a** (ms / whole-file parses): selection 13.4/0, `Scope::build` 228.5/**238**, `locate` 0.5/1, occurrence walk 116.3/**134**, token identity 4.3/0, before-prints 14.0/0, `rebuilt_index` 228.4/**238**, after-prints 71.5/**106**, warnings 83.6/0 — **717 parses**, 73 % of the request. **§P2c**: 13.4 / 225.1 / 0.0 / 12.1 / 4.5 / 14.0 / **37.2** / **7.9** / 83.3 — **240 parses = K + E** |
|
||||
| Ordinary rename selected bytes / stages | Edited 9; other counts unmeasured | Edited 9 confirmed (14 edits, fingerprint `fa7e31c78382…`); stages unmeasured — P2a | **Measured, §P2a: 13 files / 400 051 bytes** (request 1, declaration 4, reference 8), watched 12 / 398 160 bytes, edited 9; 51 parses; index 23.4, occurrence walk 19.2, verify 63.3 (rebuild 22.4, after 20.3), warnings 23.4 ms. **§P2c: 22 parses = K + E**, verify 46.8 (rebuild 23.4, after 2.9) |
|
||||
| Ambiguous-use all-sources fallback frequency | Not measured | Not measured — P2a | **Measured, §P2a.** Of the eight renames the `renametrace` phase walks, **four** take the whole scope: a common port name (`clk_i`, whose declarations carry ambiguous references), a duplicate module name (`rstmgr_por`, declared in four files), a new name a great many external uses spell, and a cursor on no symbol at all (which `rename.rs` answers with `ws.sources()` outright, without consulting the ladder). Each costs a **3 976-file / 35.8 MB** `Scope::build`, ~1 840 ms, before anything else happens |
|
||||
| Per-file parses for CLI census and lint | Multiple paths confirmed; runtime counts unmeasured | Not measured — P3 | — |
|
||||
| CLI package-census vs unused-import body time | Combined 123 ms wall increment; stages unseparated | Increment reproduced on the same binary at **137 ms, 23.3% of all-style** (means 0.587 vs 0.450 s, three trials, alternating order, stdout hashes identical to baseline). Stages still unseparated — P3 | — |
|
||||
| Startup discovery / hash / decode / merge / candidates / includes / compact | Only combined scan time measured | Still only combined — P4a. P0 adds the scan's *other* half: first useful answer, cold **84.42–85.87 ms** vs warm **206.12–218.72 ms**, and the settle of those same perturbed sessions (cold 2855–2877, warm 1340–1358 ms) | — |
|
||||
| Peak server RSS during startup and refactoring | Idle RSS only; peak unmeasured | **Startup peak measured** (`peak_rss_kib`, `ps -o rss=` at 50 ms across the scan): cold 526.7 / 530.2 / 535.2 MiB, warm 575.0 / 572.5 / 575.6 MiB — equal to idle to the KiB in all six sessions, i.e. no transient above idle. Refactoring peak still unmeasured — P2a | — |
|
||||
| Peak server RSS during startup and refactoring | Idle RSS only; peak unmeasured | **Startup peak measured** (`peak_rss_kib`, `ps -o rss=` at 50 ms across the scan): cold 526.7 / 530.2 / 535.2 MiB, warm 575.0 / 572.5 / 575.6 MiB — equal to idle to the KiB in all six sessions, i.e. no transient above idle. Refactoring peak still unmeasured — P2a | **Measured, §P2a, and re-measured at §P2b/§P2c** (MiB, `ps -o rss=` at 50 ms across each rename): tail 590 → 610 → 593; `aes` 582 → 577 → 585; unique internal 570 → 579 → 579; **`clk_i` fallback 1 864 → 1 840 → 1 830**; conflict 647 → 639 → 641; `cipher_alert → clk_i` **1 809 → 1 695 → 1 590**; `rstmgr_por` fallback 922 → 901 → 927; no-symbol 914 → 905 → 918. **No row's peak rose by more than 20 MiB and the two heaviest fell** — retention is bounded to the files the request was going to analyse anyway |
|
||||
| First useful response during scan; open buffers 1 / 10 / 100 | Not measured in this round | **First useful response measured** (above), each session a fresh process, kept in separate sessions from the settled rows so the settled series stays comparable. Open buffers 1 / 10 / 100 not measured — P4a | — |
|
||||
| Actual inline/extract command time and applyEdit payload | Not measured; existing resolve rows invalid for this purpose | **Measured, phase `execute`.** `lucisv.extractModule` (`aes.sv` 220:0–222:53): 257.33 / 245.05–247.00 ms from `executeCommand` to `workspace/applyEdit`, payload 2 edits / 2 files / 1 created, label `lucisv: lucisv.extractModule`, fingerprint `090e92e7736e…`, declined with `applied: false` (status `capture`), delivery half 0.015–0.033 ms. `lucisv.inlineModule` (`aes_wrap.sv` 66:2) **refused** (`generate` construct) in 6.58 / 5.87–6.20 ms; the extract offer at that same cursor **refused** after 817.37 / 793.77–809.07 ms. Take 4's `*-module resolve` rows are removed, not reinterpreted | — |
|
||||
| First offer after didChange vs repeated unchanged offer | Separate distribution needed | Not measured. Every row separates the *first request of a session* from its repeats, but no row yet issues a `didChange` and then re-offers — P1's measurement | **Measured, new phase `offeredit`** (`tools/perf/phases_p1.py`): three `didChange` → `codeAction` pairs, then three repeats at the same cursor in the same session. P1b medians — pinmux **133.86** first-after-edit against **24.18** repeated; `aes_reg_top` instance **22.66** against **21.65**; `tb.sv` comment **1.95** against **0.54**. So on the generated file the edit itself (one `Document::new`: lex, parse, analyze, resolve, line-index 1.3 MB) is ~110 ms and dwarfs the offer; on ordinary files the two are within 1 ms |
|
||||
@@ -144,16 +148,16 @@ this stage; each says so rather than being left ambiguous.
|
||||
| Action parity | Titles/kinds/counts/commands/data or edits/refusals; empty/prefix filters; cursor and selection | **P0: recorded, not yet a comparison.** Every offer row now carries `titles`, the shape of each offer (`edit`/`command`/`data`), `result_count` and the `only` filter it asked with; `offerkinds` walks 7 filters at 5 cursors. This is the reference P1 must match — **P1a/P1b: matched.** Every one of the 60 rows in each stage carries the REF's own `result_count`, and the `codeaction` rows the REF's own `titles`; all 7 filters at all 5 cursors agree. In tests, `vlog_refactor/tests/parsed_selectors.rs` compares old against new at **every byte offset** of five fixtures, and `server/tests/code_action.rs` pins order, prefix filters, the empty filter, a cursor-width extraction and a fix spanning the cursor. **P1c: matched again** — every row of `offerkinds`, `codeaction` and `offerqueue` compared field-by-field against P1b's own record (`result_count`, `titles`, `shapes`, `status`, `fingerprint`, `edits`, `files`, `created`): **50 rows, 0 differences**; against the P0 REF, **65 rows, 0 differences**. In tests, `vlog_refactor/tests/port_offers.rs` compares the offered *menu* against `port_actions`' menu — titles included, in order — at every byte offset of eight fixtures, and `import_offers.rs` compares `organize_offer` against `organize_counts` — counts and refusal sentence — at every byte offset of seven |
|
||||
| Reuse freshness | didChange, unsaved overlays, config/options/tab width/waiver changes, index generation, closed files changed on disk | Not applicable at P0. **P1b: one memo exists, the fence answer, and it is bound to the `Document` that owns the text** — `Workspace::set_document` builds a whole new `Document` on every `didOpen`/`didChange`/text-carrying `didSave`, and `answer_request` flushes pending changes before any handler runs, so there is no revision to compare and no way to hold the wrong one. Pinned by `a_fence_typed_into_the_buffer_is_seen_by_the_next_request` (fix → fence typed in → fix withheld → fence removed → fix back). Configuration is **not** memoized: `an_external_waiver_still_keeps_its_fix_out_of_the_offer` writes a `lucisv.toml` between two requests and the second obeys it. An index rebuild between two requests changes nothing at the cursor (`an_index_refresh_does_not_change_what_the_cursor_offers`). **Lint results are not cached** — see the `P1b-2026-09-07` entry for why and for the number |
|
||||
| Fence parity | All aliases, class/statement fences, malformed source, raw scan backstop, insertions and multi-edit fixes | Not applicable at P0. **P1: `vlog_formatter/src/fence.rs` is untouched and the shared-fence-filter contract is not amended** — the question asked is still `protected_regions(&doc.text)`, byte for byte, so every alias, class/statement fence, malformed-source case and scan backstop is answered by the same code as before. What changed is *when* it is asked (only when a violation carries a fix) and *how often* (once per document revision). `vlog_formatter`'s own suite is green |
|
||||
| Refactor whole-scope parity | Exact edits, warnings, refusal sentences; old/new common names, unresolved and ambiguous uses | **P0 supplies the instrument**: `fingerprint` (sha256 over sorted edits + created paths + warnings) and `edits`/`files`/`created` on every edit-bearing row, plus refusal sentences captured verbatim in `message`. First reference values recorded (tail rename, `aes` rename, extraction) |
|
||||
| Topology handshake 33 | Transitive `wrap.u_S.x` refusal coverage before sharing/narrowing module sources | Not applicable at P0 — no selector shared or narrowed. **Still not applicable at P1**: the four `*_in` selectors take the same decisions over the same tree, and **no source set was narrowed or shared** — `module_sources` / `offer_sources` / `imports::sources` are untouched. Handshake 33 stays P2's prerequisite |
|
||||
| Refactor verification | Token identity, semantic identity, parse-diagnostic preservation, comments/attributes, span remapping | Not applicable at P0 — the engine's verifiers are untouched. **Unchanged at P1**: nothing below the four gates moved; `extract_module`, `inline_module`, `organize_imports`, `port_actions` and `check::verify` are the same code, and `vlog_refactor`'s own suites are green. **P1c: still unchanged where it matters.** `check::verify_splice`, `check::verify` and `ports::confirm` are untouched, and every resolve/execute path still runs them — the three resolve rows measured above carry fingerprints byte-identical to the REF's. The *offer* predicates deliberately do not run them; that is the only widening, it is confined to a menu, it was already the lazy offer's stated contract, and the every-offset parity suites find **zero** cursors on their fixtures where it changes the answer |
|
||||
| Refactor whole-scope parity | Exact edits, warnings, refusal sentences; old/new common names, unresolved and ambiguous uses | **P0 supplies the instrument**: `fingerprint` (sha256 over sorted edits + created paths + warnings) and `edits`/`files`/`created` on every edit-bearing row, plus refusal sentences captured verbatim in `message`. First reference values recorded (tail rename, `aes` rename, extraction). **P2: matched on every row of every stage.** All thirteen edit-bearing rows of `renametrace`, `tailrename`, `rename`, `refactor` and `execute` carry byte-identical fingerprints at §P2a, §P2b and §P2c and equal to the §P0 REF's — `b39defb21265…`, `fa7e31c78382…`, `5f53e977da59…`, `31aadc134628…`, `4b534a16bca7…`, `8f3a26dd147b…`, `0ee027e37d07…`, `090e92e7736e…` — and the three refusal rows carry the same sentences and the same empty-edit fingerprint `96f32d4243b1…`. The common-name, unresolved-new-name and ambiguous-use cases the gate names are the `renametrace` phase's own rows |
|
||||
| Topology handshake 33 | Transitive `wrap.u_S.x` refusal coverage before sharing/narrowing module sources | **Still not applicable at P2a–P2c**: `module_sources`, `offer_sources`, `imports::sources` and `rename_sources`' six rungs are untouched, and **no source set was narrowed or shared** — the ladder's only change is that the set it fills now records which rung filled it. Handshake 33 remains §P2d's prerequisite. Not applicable at P0 — no selector shared or narrowed. **Still not applicable at P1**: the four `*_in` selectors take the same decisions over the same tree, and **no source set was narrowed or shared** — `module_sources` / `offer_sources` / `imports::sources` are untouched. Handshake 33 stays P2's prerequisite |
|
||||
| Refactor verification | Token identity, semantic identity, parse-diagnostic preservation, comments/attributes, span remapping | **P2: the checks are untouched; their inputs changed.** `Print`, `print`, `Shifts`, `Excluded`, `watched_files`, `tokens_match`, `first_difference`, the `ledger` and the parse-diagnostic comparison are the same code and the same comparisons; what moved is where a `Semantics` and an after-index come from (`check/after.rs`, new). Every existing attack still refuses — `check::tests`' eight `tokens_match` pairs, `check/ledger.rs`'s, `removing_an_import_a_reference_needs_is_rejected`, the `rename/tests.rs` refusals — and **three new attack pairs aimed at the reuse** were added and pass: a stale retained analysis (`a_rename_whose_edit_rebinds_a_name_in_the_edited_file_is_refused`), an after-index that forgot an unedited file (`a_rename_that_would_make_a_third_files_use_ambiguous_is_refused`), and shifted file ids (`a_print_names_paths_so_shifted_file_ids_cannot_change_it`). Not applicable at P0 — the engine's verifiers are untouched. **Unchanged at P1**: nothing below the four gates moved; `extract_module`, `inline_module`, `organize_imports`, `port_actions` and `check::verify` are the same code, and `vlog_refactor`'s own suites are green. **P1c: still unchanged where it matters.** `check::verify_splice`, `check::verify` and `ports::confirm` are untouched, and every resolve/execute path still runs them — the three resolve rows measured above carry fingerprints byte-identical to the REF's. The *offer* predicates deliberately do not run them; that is the only widening, it is confined to a menu, it was already the lazy offer's stated contract, and the every-offset parity suites find **zero** cursors on their fixtures where it changes the answer |
|
||||
| CLI output | Compare full findings/fixes/waivers/exit codes, not just counts; disabled-rule run stays attribution-only | **Passed.** stdout sha256 of all five configurations byte-identical to the baseline's; exit codes 1 (lint findings) / 2 (four pre-existing format failures) as before; the `--ignore unused-import` run is recorded as attribution only |
|
||||
| Index parity | Fresh/incremental/absorbed fingerprints, unsaved wins, coherent partial publication, scope/filelist/rootless behavior | Not applicable at P0. Store size unchanged at 44.34 MiB and the scan's own `$/progress` end messages recorded per cell (`124 → 3976 files indexed, 3975 from cache, 3 skipped` warm) |
|
||||
| Index parity | Fresh/incremental/absorbed fingerprints, unsaved wins, coherent partial publication, scope/filelist/rootless behavior | **P2c pins the absorbed-against-fresh equality where the verifier now stands on it**: `an_absorbed_after_index_is_the_index_a_rebuild_would_give` compares fingerprint, file list **and** a query-level print (`units`, `references_to`, `instantiations_of`, `hierarchical_declarations`, `workspace_symbols`) on nine cases including a file gaining and losing a declaration, an edit that changes what another file resolves to, a re-export chain, an edited package and a file that stops lexing; `absorbing_an_edited_file_keeps_every_file_id` pins id stability; `an_index_from_analyzed_facts_is_the_index_a_build_gives` pins the §P2b assembly. Not applicable at P0. Store size unchanged at 44.34 MiB and the scan's own `$/progress` end messages recorded per cell (`124 → 3976 files indexed, 3975 from cache, 3 skipped` warm) |
|
||||
| Persistence | Corrupt/truncated/old-format stores rebuild safely; interrupted writes; content hash retained | Not applicable at P0 |
|
||||
| Resources | Guard outcomes, idle and peak memory, allocated/actual store size, stack-size requirement | **Passed.** Every run under `tools/guard.sh -m 8 -t 1800`; **zero kills**; largest resident set 575.6 MiB (7% of the limit). Idle *and* peak RSS now recorded in their own KiB fields; store 44.34 MiB. **P1: zero guard kills** across ten timed runs and every `cargo` gate. Memory not re-measured (P4a's phase); the only new retention is one `Vec<Region>` per open buffer that ever needed a fence answer. No new parsing thread, so the 16 MiB stack contract is untouched |
|
||||
| Formatting | `cargo fmt --all -- --check`, appropriate formatter snapshot/idempotency and corpus gates | Not applicable at P0 — no Rust changed, and no `cargo` command may run during a timed round. `python3 -m py_compile tools/perf/*.py` and `bash -n tools/perf/*.sh` clean. **P1: `cargo fmt --all -- --check` clean; `cargo test -p vlog_formatter` green inside the workspace run** (the formatter is not on this change's path — `fence.rs` is untouched — but it was run anyway). `python3 -m py_compile tools/perf/*.py` clean for the new phase |
|
||||
| Lint/tests | Guarded affected tests then clippy/workspace tests at integration, no benchmark overlap | Not applicable at P0 (no Rust). No benchmark overlapped a build. **P1: `cargo clippy --all-targets` clean at both stages** (one `needless_borrow` introduced by the P1b diff was fixed; **no new `#[allow]`**), `cargo test --workspace` green before each stage's build, all guarded. **No cargo command ran during any timed phase**: each stage built once, to completion, then measured. **P1c: `cargo fmt --all -- --check` clean, guarded `cargo clippy --all-targets` clean, guarded `cargo test --workspace` **4215 passed / 0 failed** (4194 at P1b, +21), then one guarded release build, then four timed phases with no cargo running; zero guard kills; corpus unchanged after every phase. One new `#[allow(clippy::too_many_arguments)]`, on `imports::planned`, with the reason on the line |
|
||||
| Documentation | Feature README, handshake updates in topo, accepted numbers in perf README; reserved lead Review untouched by dev | **Done.** `docs/features/perf5-p0/README.md` created with the required sections (QA and Review left empty); no `topo.md` edge changed because no interface changed; `docs/perf/README.md` carries a note that two take-4 row *meanings* are superseded. **P1: `docs/features/perf5-p1/README.md` created** with all seven sections, QA and Review left empty, the work log kept as the work went. `topo.md` is **not** edited by this lane — the two additive edges (`vlog_parser::stats`, the four `vlog_refactor` `*_in` selectors, the server's `fences` module) are written as requests in that README's Handshakes for the lead to apply. `docs/perf/README.md` untouched until the lead accepts these numbers. **P1c: the same README gains a P1c section in Goal, Handshakes, Status and Work log**, a dated empty QA heading, and two further handshake requests for the lead — the `port_offers` / `organize_offer` topo edges, and a `vlog_semantic` request to expose a `FileFacts` built from an existing analysis (worth ~0.8 ms of the organize-imports offer). Review still untouched by the dev |
|
||||
| Resources | Guard outcomes, idle and peak memory, allocated/actual store size, stack-size requirement | **P2: zero guard kills** across nineteen timed phases and every `cargo` gate; largest resident set **1 864 MiB** (23 % of the 8 GiB limit), on the §P2a all-sources fallback — and §P2b/§P2c *lowered* it. Peak RSS re-measured per rename at all three stages (the row above); no row rose by more than 20 MiB. The one new retention is a request-local `HashMap<usize, Semantics>` bounded to the files whose text spells one of the two names, which are the files the request analyses anyway. No new parsing thread, so the 16 MiB stack contract is untouched. **Passed.** Every run under `tools/guard.sh -m 8 -t 1800`; **zero kills**; largest resident set 575.6 MiB (7% of the limit). Idle *and* peak RSS now recorded in their own KiB fields; store 44.34 MiB. **P1: zero guard kills** across ten timed runs and every `cargo` gate. Memory not re-measured (P4a's phase); the only new retention is one `Vec<Region>` per open buffer that ever needed a fence answer. No new parsing thread, so the 16 MiB stack contract is untouched |
|
||||
| Formatting | `cargo fmt --all -- --check`, appropriate formatter snapshot/idempotency and corpus gates | **P2: `cargo fmt --all -- --check` clean** at every stage; the formatter is not on this change's path (`vlog_formatter` is untouched) and its suite ran green inside each workspace run. `python3 -m py_compile tools/perf/*.py` clean for the new `phases_p2.py`. Not applicable at P0 — no Rust changed, and no `cargo` command may run during a timed round. `python3 -m py_compile tools/perf/*.py` and `bash -n tools/perf/*.sh` clean. **P1: `cargo fmt --all -- --check` clean; `cargo test -p vlog_formatter` green inside the workspace run** (the formatter is not on this change's path — `fence.rs` is untouched — but it was run anyway). `python3 -m py_compile tools/perf/*.py` clean for the new phase |
|
||||
| Lint/tests | Guarded affected tests then clippy/workspace tests at integration, no benchmark overlap | **P2: guarded `cargo test --workspace` green before every release build — 4 215 (before the lane) → 4 225 (§P2b) → 4 231 (§P2c), 0 failed, no test removed or weakened**; guarded `cargo clippy --all-targets` clean at each stage with **no new `#[allow]`**; `cargo fmt --all -- --check` clean. **No `cargo` command ran during any timed phase**: each stage built once, to completion, then measured. Not applicable at P0 (no Rust). No benchmark overlapped a build. **P1: `cargo clippy --all-targets` clean at both stages** (one `needless_borrow` introduced by the P1b diff was fixed; **no new `#[allow]`**), `cargo test --workspace` green before each stage's build, all guarded. **No cargo command ran during any timed phase**: each stage built once, to completion, then measured. **P1c: `cargo fmt --all -- --check` clean, guarded `cargo clippy --all-targets` clean, guarded `cargo test --workspace` **4215 passed / 0 failed** (4194 at P1b, +21), then one guarded release build, then four timed phases with no cargo running; zero guard kills; corpus unchanged after every phase. One new `#[allow(clippy::too_many_arguments)]`, on `imports::planned`, with the reason on the line |
|
||||
| Documentation | Feature README, handshake updates in topo, accepted numbers in perf README; reserved lead Review untouched by dev | **P2: `docs/features/perf5-p2/README.md` created** with all seven sections, QA and Review left empty, the work log kept as the work went. **`topo.md` is not edited by this lane** — four additive edges (`FileFacts::analyzed`; `vlog_refactor::rename_traced` and its trace values; the server's `rename_trace` module; `rename::rename_traced` / `Workspace::rename_sources_traced` replacing their untraced forms at the one production call site) are written as requests in that README's Handshakes for the lead to apply. `docs/perf/README.md` untouched until the lead accepts these numbers. **Done.** `docs/features/perf5-p0/README.md` created with the required sections (QA and Review left empty); no `topo.md` edge changed because no interface changed; `docs/perf/README.md` carries a note that two take-4 row *meanings* are superseded. **P1: `docs/features/perf5-p1/README.md` created** with all seven sections, QA and Review left empty, the work log kept as the work went. `topo.md` is **not** edited by this lane — the two additive edges (`vlog_parser::stats`, the four `vlog_refactor` `*_in` selectors, the server's `fences` module) are written as requests in that README's Handshakes for the lead to apply. `docs/perf/README.md` untouched until the lead accepts these numbers. **P1c: the same README gains a P1c section in Goal, Handshakes, Status and Work log**, a dated empty QA heading, and two further handshake requests for the lead — the `port_offers` / `organize_offer` topo edges, and a `vlog_semantic` request to expose a `FileFacts` built from an existing analysis (worth ~0.8 ms of the organize-imports offer). Review still untouched by the dev |
|
||||
|
||||
## Experiment record — P0-2026-09-07 (stage P0)
|
||||
|
||||
@@ -648,6 +652,252 @@ this stage; each says so rather than being left ambiguous.
|
||||
`docs/features/perf5-p1/README.md` QA log, heading
|
||||
"2026-09-07 — QA, P1c".
|
||||
|
||||
## Experiment record — P2a-2026-09-07 (stage P2a)
|
||||
|
||||
- **Experiment ID / stage / date / owner:** `P2a-2026-09-07` / P2a (TODO §60.2)
|
||||
/ 2026-09-07, America/Chicago / dev agent (Opus).
|
||||
- **Hypothesis and exact expected work reduction:** none — §P2a changes no
|
||||
decision. The hypothesis is about the *instrument*: that a per-stage wall
|
||||
time and a per-stage `vlog_parser::stats::parses()` delta, plus the rung each
|
||||
selected file came in on, are enough to say where the tail rename's 780 ms
|
||||
goes, and that adding them moves no measured row.
|
||||
- **Reference commit, candidate commit or diff hash, binary hashes:** trunk
|
||||
`dafa4f0` plus the §60.2 working tree; release server
|
||||
`bf584aa0daf6909ca4a5fab57d9b2c1ff9619132a9df4d686f58bce292003dde`, CLI
|
||||
`3f7bfd25cdbd16eeb5c16504c9b18181dddc1a26877447688f71b570234108cb`.
|
||||
- **Files changed / API contracts amended / topology references:**
|
||||
`vlog_refactor/src/{trace.rs (new), rename/mod.rs, rename/tests.rs,
|
||||
check/mod.rs, lib.rs}`; `lucisv_server/src/{rename_trace.rs (new), rename.rs,
|
||||
state.rs, perf.rs, main.rs, server/dispatch.rs}`;
|
||||
`tools/perf/{phases_p2.py (new), bench.py, sites.py}`;
|
||||
`docs/features/perf5-p2/README.md` (new). Additive contracts:
|
||||
`vlog_refactor::rename_traced` + `RenameTrace`/`VerifyTrace`/`Stage`;
|
||||
`Workspace::rename_sources_traced`. **No `topo.md` edge edited** — the four
|
||||
requests are in the feature README's Handshakes. `check::verify` gained a
|
||||
trace parameter and **no check changed**.
|
||||
- **Workload, corpus/input hashes, open files, cursor/range, rules, client
|
||||
capabilities:** OpenTitan `0098135264`, the same three pre-existing modified
|
||||
files, unchanged after every phase. Eight renames, positions resolved from
|
||||
file text by `tools/perf/sites.py`: `state_q` at `entropy_src_main_sm.sv`
|
||||
41:19 with `entropy_src_core.sv` open; `aes` at `tb.sv` 44:2;
|
||||
`cipher_alert` at its declaration in `aes_core.sv`; `clk_i` at its
|
||||
declaration in `entropy_src_main_sm.sv`; `state_q → state_d` (conflict);
|
||||
`cipher_alert → clk_i` (a new name many external uses spell);
|
||||
`rstmgr_por` at its instantiation in `rstmgr.sv` (declared in four files);
|
||||
and a cursor on a `tb.sv` comment (no symbol). Lazy client
|
||||
(`resolveSupport`), warm workspace scope, scratch index caches, servers run
|
||||
with `--verbose`.
|
||||
- **Machine, compiler/profile, threads, load before/after, competing
|
||||
activity:** M1 Max, macOS 27.0 `26A5425a`, release + LTO, default worker
|
||||
count. Load 3.90 → 3.92 recorded before and after every phase. No build
|
||||
during any timed phase.
|
||||
- **Commands, cache reset/prime steps, trial ordering and fresh-session
|
||||
count:** six guarded `bench.py` phases (`renametrace tailrename rename
|
||||
blockers refactor execute`, `--tries 3`, so four requests per row), each
|
||||
through `tools/guard.sh -m 8 -t 1800`. Every `renametrace` row is its own
|
||||
fresh session with its own scratch `--storage`; `blockers` is three fresh
|
||||
leaders. Corpus checked after every phase.
|
||||
- **Raw evidence path, explicit units, full sample arrays:**
|
||||
`~/.cache/lucisv-perf/take5-p2/results-p2a.jsonl` (schema 2) and
|
||||
`runs-p2a.jsonl` (per-phase command, exit, load before/after, corpus check).
|
||||
Latency is `ms`, memory `peak_rss_kib`; every trace field is a row field
|
||||
under `trace_` and is repeated verbatim in `note`.
|
||||
- **Reference first / repeat median / range; candidate first / repeat median /
|
||||
range:** tail rename REF 813.44 / **780.45** / 778.77–782.13 against P2a
|
||||
817.45 / **784.19** / 782.21–789.49; `aes` rename REF 167.60 / **141.30** /
|
||||
140.46–142.13 against 168.44 / **140.15** / 140.15–141.31. Every other
|
||||
re-taken row is in the Before/after table.
|
||||
- **Work counts: reads, parses, analyzed/selected/watched/edited files and
|
||||
bytes:** the point of the stage. Tail rename **238 selected / 4 554 326 bytes
|
||||
/ 106 watched / 1 919 528 bytes / 2 edited / 717 whole-file parses**
|
||||
(238 index + 1 locate + 134 occurrence walk + 238 rebuild + 106 after);
|
||||
`aes` 13 / 400 051 / 12 / 398 160 / 9 / 51; unique internal 4 / 68 475 / 1 /
|
||||
1 / 10; `clk_i` **3 976 / 35 813 310 / 1 200 / 19 257 967 / 2 / 10 399**;
|
||||
conflict 242 / 4 570 234 / 111 / 2 / 638; `cipher_alert → clk_i` 3 976 /
|
||||
1 200 / 1 / 9 229; `rstmgr_por` 3 976 / 0 / 0 / 3 976; no symbol 3 976 / 0 /
|
||||
0 / 3 976. Rungs for the tail: request 1, declaration 95, reference 122,
|
||||
instantiation 19, macro 0, speller 0, open 1.
|
||||
- **Result/status/count/fingerprint comparisons, warnings and refusal checks:**
|
||||
thirteen edit-bearing rows fingerprinted; the six that have a §P0 REF are
|
||||
**byte-identical** to it. Three rows are `refused` with the engine's own
|
||||
sentences; one is `capture` (the extraction's declined `applyEdit`).
|
||||
- **Idle RSS / peak RSS / cache size / guard outcomes:** peak RSS per rename
|
||||
590 / 582 / 570 / **1 864** / 647 / 1 809 / 922 / 914 MiB. **Zero guard
|
||||
kills.** Store not re-measured (unchanged codec).
|
||||
- **Target achieved or missed; paired improvement and variability:** §P2a's
|
||||
target is that the instrument answers the question and costs nothing. Both
|
||||
hold: the breakdown above is the answer, and the six re-taken REF rows agree
|
||||
within +0.5 % / −3.0 %.
|
||||
- **Correctness tests and logs:** guarded `cargo test --workspace` **4 215
|
||||
passed / 0 failed** (identical to §P1c's count — §P2a's own tests were added
|
||||
with §P2b), `cargo clippy --all-targets` clean, `cargo fmt --all -- --check`
|
||||
clean, `python3 -m py_compile tools/perf/*.py` clean.
|
||||
`git -C ~/repo/opentitan status --porcelain` the same three files after every
|
||||
phase.
|
||||
- **Interpretation, remaining bottleneck, tradeoffs, rejected alternatives:**
|
||||
**73 % of the tail rename is whole-file parsing, and two thirds of that
|
||||
parsing is repeated work.** `Scope::build` and `rebuilt_index` are the same
|
||||
`WorkspaceIndex::build` over the same 238 texts, of which two differ; the
|
||||
occurrence walk re-parses 134 files the build already parsed; the after-pass
|
||||
re-parses 106 files the before-pass already analysed. `warnings` (83.6 ms)
|
||||
runs **zero** parses and is a token scan, so §P2b/§P2c cannot reach it. The
|
||||
selection is 13.4 ms and is not the story — but the *size* of what it selects
|
||||
(238 files for a two-file edit) is what will be left when the duplication is
|
||||
gone. Rejected: returning the trace inside the `Ok` value, which would lose
|
||||
it on exactly the refusal rows the plan asks for.
|
||||
- **Decision:** retain. §P2b/§P2c justified by the two 228 ms stages being one
|
||||
another.
|
||||
- **QA result and lead review link:** pending.
|
||||
|
||||
## Experiment record — P2b-2026-09-07 (stage P2b)
|
||||
|
||||
- **Experiment ID / stage / date / owner:** `P2b-2026-09-07` / P2b / 2026-09-07
|
||||
/ dev agent (Opus).
|
||||
- **Hypothesis and exact expected work reduction:** building the index already
|
||||
parses and analyses every in-scope file; keeping those analyses instead of
|
||||
dropping them should remove **every parse after the index build except the
|
||||
after-side's** — the tail rename's 134 occurrence-walk parses and its 1
|
||||
`locate` parse, ~135 of 717 — with identical answers, because what is kept is
|
||||
the analysis the on-demand path would have recomputed.
|
||||
- **Reference commit, candidate commit or diff hash, binary hashes:** the §P2a
|
||||
working tree plus the §P2b diff; release server
|
||||
`e555e6c79d8d63ffd65e25e48e13e4633d0a2361306f358043e88903607269c5`.
|
||||
- **Files changed / API contracts amended / topology references:**
|
||||
`vlog_semantic/src/workspace/record.rs` (**additive `FileFacts::analyzed`**;
|
||||
`facts_of` becomes its `.0`; no codec change, `FACTS_FORMAT` untouched);
|
||||
`vlog_refactor/src/{scope.rs, rename/mod.rs}`;
|
||||
`vlog_semantic/tests/workspace.rs`. `Scope::build`'s behaviour, cost and
|
||||
memory are unchanged for every caller but the rename.
|
||||
- **Workload, corpus/input hashes, open files, cursor/range, rules, client
|
||||
capabilities:** identical to §P2a's, same phases, same sites.
|
||||
- **Machine, compiler/profile, threads, load before/after, competing
|
||||
activity:** same host and profile; load 5.04 → 3.26 across the six phases,
|
||||
recorded per phase. No build during a timed phase.
|
||||
- **Commands, cache reset/prime steps, trial ordering and fresh-session
|
||||
count:** identical to §P2a's, `--tries 3`.
|
||||
- **Raw evidence path, explicit units, full sample arrays:**
|
||||
`~/.cache/lucisv-perf/take5-p2/results-p2b.jsonl`, `runs-p2b.jsonl`.
|
||||
- **Reference first / repeat median / range; candidate first / repeat median /
|
||||
range:** tail rename REF **780.45** against **674.68** (706.50 first,
|
||||
673.57–676.19); `aes` REF **141.30** against **123.08** (142.71 first,
|
||||
122.59–123.11).
|
||||
- **Work counts:** tail rename **717 → 582 parses** (index 238, locate **0**,
|
||||
occurrence walk **0**, rebuild 238, after 106); `aes` 51 → 38; `clk_i`
|
||||
10 399 → 9 150; conflict 638 → 498. Selected/watched/edited counts and bytes
|
||||
unchanged on every row — **nothing was narrowed**.
|
||||
- **Result/status/count/fingerprint comparisons, warnings and refusal checks:**
|
||||
all thirteen fingerprints identical to §P2a's and to the §P0 REF's; the three
|
||||
refusals carry the same sentences.
|
||||
- **Idle RSS / peak RSS / cache size / guard outcomes:** peak RSS 610 / 577 /
|
||||
579 / **1 840** / 639 / 1 695 / 901 / 905 MiB — the two heaviest rows
|
||||
*lower* than §P2a's, none higher by more than 20 MiB. **Zero guard kills.**
|
||||
- **Target achieved or missed; paired improvement and variability:** the
|
||||
hypothesis's exact reduction was met (135 parses, the predicted set) and is
|
||||
worth **−13.6 %** on the tail rename and **−12.9 %** on `aes` against the
|
||||
REF. §P2's own targets are judged at §P2c.
|
||||
- **Correctness tests and logs:** guarded `cargo test --workspace` **4 225
|
||||
passed / 0 failed** (+10: two `rename_trace` unit tests, two trace tests, four
|
||||
`scope::tests`, two `vlog_semantic` equality tests); clippy and fmt clean.
|
||||
The load-bearing ones are
|
||||
`analyzed_gives_the_record_of_gives_and_the_analysis_a_caller_would_compute`,
|
||||
`an_index_from_analyzed_facts_is_the_index_a_build_gives` and
|
||||
`a_retained_analysis_is_the_one_the_on_demand_path_would_compute`.
|
||||
- **Interpretation, remaining bottleneck, tradeoffs, rejected alternatives:**
|
||||
after §P2b the tail rename's remaining duplication is entirely on the *after*
|
||||
side: `rebuilt_index` (238 parses, 228 ms) and the after-prints (106 parses,
|
||||
72 ms). **Rejected: retaining every file's analysis unconditionally** — §P2a
|
||||
measured ~0.8 MiB of `Semantics` per file, so the 3 976-file fallback would
|
||||
have peaked near 3.9 GiB against 1 864 MiB. **Rejected: rebuilding the record
|
||||
with `FileFacts::from_analysis`** — it needs the token slice the parser
|
||||
consumes, so every file's tokens would have to be cloned to feed it.
|
||||
- **Decision:** retain; §P2c is the rest of the same finding.
|
||||
- **QA result and lead review link:** pending.
|
||||
|
||||
## Experiment record — P2c-2026-09-07 (stage P2c)
|
||||
|
||||
- **Experiment ID / stage / date / owner:** `P2c-2026-09-07` / P2c / 2026-09-07
|
||||
/ dev agent (Opus).
|
||||
- **Hypothesis and exact expected work reduction:** the after-index is the
|
||||
before-index with a handful of records replaced, and an unedited watched
|
||||
file's after-print is its existing analysis re-resolved. Expected reduction:
|
||||
the tail rename's 238 rebuild parses and 106 after parses, leaving
|
||||
**`K + E` = 240**, with every check comparing exactly what it compared
|
||||
before.
|
||||
- **Reference commit, candidate commit or diff hash, binary hashes:** the §P2b
|
||||
working tree plus the §P2c diff; release server
|
||||
`1601b13a9bacda47095cb23580e475ac8f33a171f446875484439ec67d58eb31`
|
||||
(re-verified byte-identical after the rejected `update_facts` probe was
|
||||
reverted).
|
||||
- **Files changed / API contracts amended / topology references:**
|
||||
`vlog_refactor/src/check/after.rs` (**new**, 39 production lines),
|
||||
`check/mod.rs` (427 → **405** production lines), `scope.rs`
|
||||
(`Scope::against`, `Scope::sources` deleted), `rename/tests.rs`. No public
|
||||
API changed; `WorkspaceIndex::absorb`'s existing contract
|
||||
(`docs/topo.md` §3, "absorb must equal one build over the resulting record
|
||||
set") is the one this stage stands on and now pins from a second crate.
|
||||
- **Workload, corpus/input hashes, open files, cursor/range, rules, client
|
||||
capabilities:** identical to §P2a's and §P2b's.
|
||||
- **Machine, compiler/profile, threads, load before/after, competing
|
||||
activity:** same host and profile; load 5.15 → 3.26 across the six phases.
|
||||
No build during a timed phase.
|
||||
- **Commands, cache reset/prime steps, trial ordering and fresh-session
|
||||
count:** identical, `--tries 3`. One extra guarded `renametrace` run for the
|
||||
rejected `update_facts` variant, on its own label and its own binary, before
|
||||
the reverted binary was rebuilt and re-hashed.
|
||||
- **Raw evidence path, explicit units, full sample arrays:**
|
||||
`~/.cache/lucisv-perf/take5-p2/results-p2c.jsonl`, `runs-p2c.jsonl`, and
|
||||
`results-probe-updatefacts.jsonl` for the rejected variant.
|
||||
- **Reference first / repeat median / range; candidate first / repeat median /
|
||||
range:** tail rename REF 813.44 / **780.45** / 778.77–782.13 against
|
||||
451.54 / **419.86** / 418.61–421.27; `aes` REF 167.60 / **141.30** /
|
||||
140.46–142.13 against 126.13 / **106.31** / 105.95–107.15.
|
||||
- **Work counts:** tail rename **717 → 240 = K + E** (238 index + 2 for the
|
||||
edited files' one new analysis each; locate, occurrence walk, before-prints
|
||||
and after-prints all **0**); `aes` 51 → **22 = 13 + 9**; `clk_i`
|
||||
10 399 → **3 977**; conflict 638 → **244**. Selected, watched and edited
|
||||
counts and bytes are unchanged from §P2a on every row.
|
||||
- **Result/status/count/fingerprint comparisons, warnings and refusal checks:**
|
||||
all thirteen fingerprints byte-identical to §P2a's, §P2b's and the §P0 REF's;
|
||||
the three refusals carry the same sentences and the same empty-edit
|
||||
fingerprint `96f32d4243b1…`.
|
||||
- **Idle RSS / peak RSS / cache size / guard outcomes:** peak RSS 593 / 585 /
|
||||
579 / **1 830** / 641 / **1 590** / 927 / 918 MiB — the two heaviest rows
|
||||
34 and 219 MiB *below* §P2a's. **Zero guard kills** across all nineteen
|
||||
timed phases of the lane.
|
||||
- **Target achieved or missed; paired improvement and variability:**
|
||||
- tail rename ≥ 2× faster: **MISSED**, at **1.86×** (−46.2 %, 419.86 against
|
||||
780.45; 2× needed 390.2). Repeat spread 418.61–421.27, so the miss is not
|
||||
noise. **The measured remaining stage is `Scope::build`** — one parse of
|
||||
each of the **238 selected** files, **225.1 ms of the 419.9 (54 %)** — with
|
||||
`warnings`' token scan second at 83.3 ms (20 %) and the whole verification
|
||||
third at 73.0 ms (17 %). There is **no duplicated parsing left**; the next
|
||||
lever is the size of the selected set, which is §P2d.
|
||||
- stretch < 200 ms: not approached, for the same reason.
|
||||
- `aes` rename not slower: **met, and 24.8 % faster.**
|
||||
- edit/warning fingerprints identical: **met, on every row of every stage.**
|
||||
- the queued definition follows: **met**, 161.33 → **121.85** (−24.5 %).
|
||||
- collateral: the extract command **−39.3 %**, connect-missing-ports
|
||||
**−20.3 %**, expand-wildcard **−23.6 %**, organize-imports resolve −10 %.
|
||||
- **Correctness tests and logs:** guarded `cargo test --workspace` **4 231
|
||||
passed / 0 failed** (+6 on §P2b: two after-index equality tests, the file-id
|
||||
test, the `K + E` parse-budget test, and the two rename-level attack pairs;
|
||||
the third attack pair is the file-id-shift print test).
|
||||
`cargo clippy --all-targets` clean, no new `#[allow]`;
|
||||
`cargo fmt --all -- --check` clean. Corpus unchanged after every phase.
|
||||
- **Interpretation, remaining bottleneck, tradeoffs, rejected alternatives:**
|
||||
the request-local scope now does exactly `K + E` whole-file parses, which is
|
||||
the floor for a design that reads the selected files itself. **Rejected:
|
||||
`WorkspaceIndex::update_facts` per edited record instead of one `absorb`** —
|
||||
the restricted merge is *slower* than the whole one on every row measured
|
||||
(tail rebuild stage 37.2 ms with `absorb` against 53.3; `aes` 23.4 against
|
||||
40.2; `clk_i` 269.7 against 400.9), because it walks the same records and
|
||||
pays a name-set lookup at every declaration. The parse saving is the same
|
||||
either way. The two remaining stages are outside §P2b/§P2c's mandate: the
|
||||
input's *size* (§P2d, gated on handshake 33) and `warnings`' token scan.
|
||||
- **Decision:** retain. §P2d is now justified by a reprofile that says the
|
||||
selected set is the only thing left — and is a separate lane.
|
||||
- **QA result and lead review link:** pending.
|
||||
|
||||
## Experiment record — copy for every stage or rejected attempt
|
||||
|
||||
- Experiment ID / stage / date / owner:
|
||||
|
||||
+3
-3
@@ -130,7 +130,7 @@ what a change on the pointed-to side must not silently break.
|
||||
| `lucisv_server ──▶ vlog_semantic` (organize-imports) | depends | `WorkspaceIndex::reexported_packages`, read by `lucisv_server::imports` to close the file set over re-exports (§52). |
|
||||
| `lucisv_server ◀── vlog_refactor` (extract-module) | depends | `RefactorEdit::created` — the files an edit creates, read by `lucisv_server::extract` to emit `CreateFile` document changes when `ClientAbilities::create_files` (read at `initialize`: `workspace.workspaceEdit.documentChanges` + `resourceOperations: create`) allows, else the same-file fallback (§53.1, 2026-09-06). |
|
||||
| `vlog_refactor ──▶ vlog_parser` | depends | `tokenize`, `parse_source_tolerant` + diagnostics, `LineIndex`, `TextRange`, the port/instantiation/module AST shapes, `token::is_keyword` (new-name validity), `defines` via the index. Every edit span originates in a parsed node — no textual search-and-replace. |
|
||||
| `vlog_refactor ──▶ vlog_semantic` | depends | `Semantics` queries (`symbol_at`, `references_of`, `reference_id_at`, …), `Resolution` variants (three of them are refusal rules), `WorkspaceIndex` + `resolve_external` + `ExternalTarget`, and the exactness promise on `name_span` (re-checked before each edit is emitted). One historical exception: refactor-rename added `Target::Declaration` + end-label uses *into* `vlog_semantic` (lead-authorized, additive — see §2.6). |
|
||||
| `vlog_refactor ──▶ vlog_semantic` | depends | `Semantics` queries (`symbol_at`, `references_of`, `reference_id_at`, …), `Resolution` variants (three of them are refusal rules), `WorkspaceIndex` + `resolve_external` + `ExternalTarget`, and the exactness promise on `name_span` (re-checked before each edit is emitted). One historical exception: refactor-rename added `Target::Declaration` + end-label uses *into* `vlog_semantic` (lead-authorized, additive — see §2.6). `FileFacts::analyzed(path, src) -> (FileFacts, Semantics)` (perf5-p2: the index build hands back the analysis it read the record off; `FileFacts::of` is its `.0`, so the two cannot drift; `Scope` feeds `IndexBuilder::add_facts` and keeps the `Semantics` of the files a rename will read — a cache, never an oracle) and `WorkspaceIndex::absorb` as the after-index of every verifier (`check/after.rs`: the before-index cloned plus the edited files' fresh records; pinned equal to a rebuild by fingerprint and query on adversarial edits). |
|
||||
| `lucisv ──▶ lucisv_core` | depends | `config::{FileConfig, Discovery}` (lucisv.toml discovery — `config::parse` is reached through `Discovery`, not called directly), `walk::{collect_files, EXTENSIONS}` (the `.gitignore`/`--exclude` walk), `filelist::read` (`-f`), `cache` (the format cache), `atomic::write_atomic` (formatter and lint-fix replacement). (`walk::is_excluded` also supplies the linter’s external-waiver location matcher.) |
|
||||
| `lucisv ──▶ vlog_formatter` | depends | `format_source` / `format_range` / `LineRanges` / `Config` / `FormatError`, and `fence::{protected_regions, is_protected}` (the `--fix` fence filter — the linter crate deliberately has no fence notion). |
|
||||
| `lucisv ──▶ vlog_linter` | depends | The public linter API for `lucisv check` — `lint` + `LintContext`/`ParsedSource`, `apply_fixes`, `select_rules` (the CLI does not call `run` itself). Relies on: rule names stable, linting never panics/writes, findings sorted by `(span.start, span.end, rule)`. |
|
||||
@@ -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). |
|
||||
| `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}`, 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` + `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. The engine remains the authority, and every selector must supply a superset of files needed for edits and refusals (inline gap: §2.9-33). |
|
||||
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_range`/`LineRanges` (range, ranges, on-type formatting), `Config`, `fence::protected_regions` (quick-fix filter). |
|
||||
| `lucisv_server ──▶ vlog_linter` | depends | `run`, `lint` + `LintContext::from_parse` (lints from the `Document`'s own parse — one-parse), `default_rules`, `apply_fixes`, `rule_by_name`. Same three promises the CLI relies on. |
|
||||
@@ -289,7 +289,7 @@ spans two layers — the include graph *and* the `documentLink` handler;
|
||||
| loop | `server/` (since 2026-09-02: `mod` = the loop; `dispatch`, `client`, `index`, `notification`, `progress`, `diagnostics`, `batch`, `formatting`, `large_file`, `semantic_tokens`; tests in `server/tests/`) | the message loop + queue/burst (cancel-request), dispatch, `Pending` map for server-initiated requests, stepped startup scans with mid-scan request drains, held-request ordering for rescans, reindex/widen orchestration, progress/log senders, optional `timing:` instrumentation |
|
||||
| state | `state.rs` | `Workspace` (roots, scope ladder, index, include graph, candidates, index cache, open `Document`s with overlay, bounded closed-file `FileView` cache), `Scan` (whole or additive widen), fan-out source selectors (`module_sources`, `rename_sources`, `include_sources`), and `Document` (text, tokens, tree, semantics, diagnostics, `large` flag) |
|
||||
| substrate | `convert.rs`, `uri.rs`, `locate.rs`, `pairs.rs`, `includes.rs`, `candidates.rs`, `index_cache.rs`, `watch.rs`, `settings.rs`, `templates.rs`, `sync.rs` | position math, URI↔path, location building, the begin/end scope matcher, the include graph, completion word/module tables and their scan-batch forms, the persistent index store, watcher registration, `lucisv.*` settings parsing, snippet registry, incremental text sync |
|
||||
| handlers | one file per capability: `format.rs`, `diagnostics.rs`, `lint.rs` (with `fences.rs`: the formatter's text-only fence answer memoized once per `Document` — perf5-p1; the shared-fence-filter contract is unamended), `hover.rs`, `expand.rs`, `nav.rs`, `type_def.rs`, `type_hierarchy.rs`, `hierarchy.rs`, `design_hierarchy.rs`, `symbols.rs`, `tokens.rs`, `completion/` (`mod`, `member`, `module`, `tiers`, `word`, `site`; test harness in `harness`), `signature.rs`, `inlay.rs`, `inline.rs`, `lens.rs`, `code_action.rs`, `rename.rs`, `ports.rs`, `imports.rs`, `extract.rs`, `inline_module.rs`, `folding.rs`, `selection.rs`, `linked.rs`, `on_type.rs`, `includes.rs` (links), `file_ops.rs`, `instantiate.rs`, `large.rs` | each is a mostly-pure function over `Document`/`Workspace`; protocol only, no language analysis of its own (anything that looks like analysis in here is a bug or a Handshake request — lucisv-server README) |
|
||||
| handlers | one file per capability: `format.rs`, `diagnostics.rs`, `lint.rs` (with `fences.rs`: the formatter's text-only fence answer memoized once per `Document` — perf5-p1; the shared-fence-filter contract is unamended), `rename_trace.rs` (perf5-p2: `Rung`/`Wanted`/`SelectionTrace` — the path set the rename fan-out ladder fills, remembering which rung asked for each file; `Workspace::rename_sources_traced` is the ladder with that sink), `hover.rs`, `expand.rs`, `nav.rs`, `type_def.rs`, `type_hierarchy.rs`, `hierarchy.rs`, `design_hierarchy.rs`, `symbols.rs`, `tokens.rs`, `completion/` (`mod`, `member`, `module`, `tiers`, `word`, `site`; test harness in `harness`), `signature.rs`, `inlay.rs`, `inline.rs`, `lens.rs`, `code_action.rs`, `rename.rs`, `ports.rs`, `imports.rs`, `extract.rs`, `inline_module.rs`, `folding.rs`, `selection.rs`, `linked.rs`, `on_type.rs`, `includes.rs` (links), `file_ops.rs`, `instantiate.rs`, `large.rs` | each is a mostly-pure function over `Document`/`Workspace`; protocol only, no language analysis of its own (anything that looks like analysis in here is a bug or a Handshake request — lucisv-server README) |
|
||||
|
||||
**`editors/vscode`** — `extension.js` (spawn + rainbow decorations + storage
|
||||
path; ~everything else is `vscode-languageclient` driven off advertised
|
||||
|
||||
@@ -20,6 +20,7 @@ and take 5 §P0 (TODO §60.0) corrected what some rows *meant*: see
|
||||
| `phases_new.py` | the phases for what 0.44–0.49 added: the new offer sites, §49's surface, §46's `didOpen` fix, `moduleHierarchy`, index size and RSS |
|
||||
| `phases_p0.py` | take 5 §P0's phases: `execute` (what an extract/inline command really costs), `offerkinds` (the `context.only` families), `offerqueue` (leader/follower), and `scan`'s first-useful-answer half |
|
||||
| `phases_p1.py` | take 5 §P1's phase: `offeredit` — the first offer after a `didChange` beside the repeated offer on the unchanged buffer, at the same cursor in the same session |
|
||||
| `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 |
|
||||
| `sweep.sh` | the timed CLI sweeps (`format --check`, `check`) over five trees, `/usr/bin/time -l` |
|
||||
| `sweeptable.py` | those logs → the document's §7 Markdown table, plus the format-cache hits each try reported |
|
||||
| `outcomes.sh` | the untimed per-file outcome runs, for the release-to-release outcome diff |
|
||||
@@ -79,6 +80,7 @@ apart in `results.jsonl`; run each phase once per binary.
|
||||
| `offerkinds` | §P0 | the seven `context.only` families at five cursors, four requests each, result counts beside every time |
|
||||
| `offerqueue` | §P0 | the pinmux no-offer comment as leader, an `aes` definition as follower, in separate fields |
|
||||
| `offeredit` | §P1 | two rows per cursor: `didChange` → `codeAction`, three times over, then three `codeAction`s on the unchanged buffer. §P1b's whole claim is about the second, so the first is never allowed to hide inside it |
|
||||
| `renametrace` | §P2 | eight renames — the tail, `aes`, a unique internal name, a common port name, a conflicting new name, a new name many external uses spell, a duplicate module name and a cursor on no symbol — each in its own `--verbose` session, with the engine's stage trace parsed out of the log into `trace_*` row fields and peak RSS sampled across the request. **A rename's input is not its output**: the row says how many files went in, how many bytes, which rung asked for each, and how many whole-file parses the request ran |
|
||||
| `probe` | — | ad-hoc: `--probe FILE:LINE:CHAR` (0-based) prints what a cursor offers. This is how `sites.REFACTOR_SITES` was found |
|
||||
|
||||
## The CLI sweeps
|
||||
|
||||
@@ -35,6 +35,7 @@ from harness import ( # noqa: E402
|
||||
import phases_new # noqa: E402,F401 — registers its own phases
|
||||
import phases_p0 # noqa: E402,F401 — registers take 5 §P0's phases
|
||||
import phases_p1 # noqa: E402,F401 — registers take 5 §P1's phases
|
||||
import phases_p2 # noqa: E402,F401 — registers take 5 §P2's phases
|
||||
|
||||
|
||||
# =========================================================================
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Take 5 §P2's phase: `renametrace`.
|
||||
|
||||
The tracker's own note about the tail rename is that *two output files is not
|
||||
an input count* — nobody could say how many files a rename reads, which rung
|
||||
asked for them, or which stage of the engine the 780 ms is. §P2a puts the
|
||||
answer in the server: with `--verbose` the rename logs one
|
||||
`timing: rename trace …` line carrying the selection (which rung wanted how
|
||||
many files) and the engine's stages (wall time and **whole-file parses** per
|
||||
stage). This phase issues the seven renames the plan names, reads that line
|
||||
back off `window/logMessage`, and writes its fields as row fields so the
|
||||
tracker can quote them.
|
||||
|
||||
Every field the line carries becomes a row field of the same name, so nothing
|
||||
in the document is read out of prose. `ms` is still the wire latency and
|
||||
nothing else (schema 2); the trace's own stage times are `trace_*` fields.
|
||||
|
||||
Peak RSS is sampled across each rename with `phases_new.Sampler`, the §P0
|
||||
sampler, so a row says what the request cost in memory as well as in time.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
import phases_new
|
||||
import schema
|
||||
from harness import (
|
||||
ARGS, at, counts, edit_of, fingerprint, phase, record, samples, session,
|
||||
settled, sites,
|
||||
)
|
||||
|
||||
#: `timing: rename trace <fields>` — the whole line the server logs.
|
||||
TRACE_LINE = re.compile(r"timing: rename trace (.*)$")
|
||||
|
||||
#: One `key=value` of it. Braces group a stage's fields (`verify{...}`) and are
|
||||
#: flattened into `verify_tokens`, `parses_index` and so on.
|
||||
FIELD = re.compile(r"([a-z_]+)=([^\s{}]+)")
|
||||
GROUP = re.compile(r"([a-z_]+)\{([^{}]*)\}")
|
||||
|
||||
|
||||
def parse_trace(text):
|
||||
"""One trace line → a flat dict of numbers, groups flattened by prefix."""
|
||||
out = {}
|
||||
for name, body in GROUP.findall(text):
|
||||
for key, value in FIELD.findall(body):
|
||||
out["%s_%s" % (name, key)] = number(value)
|
||||
for key, value in FIELD.findall(GROUP.sub("", text)):
|
||||
out[key] = number(value)
|
||||
return out
|
||||
|
||||
|
||||
def number(text):
|
||||
"""`12`, `3.4ms`, `true` — whatever the line spells, as a number or bool."""
|
||||
if text in ("true", "false"):
|
||||
return text == "true"
|
||||
text = text[:-2] if text.endswith("ms") else text
|
||||
try:
|
||||
return int(text)
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
return float(text)
|
||||
except ValueError:
|
||||
return text
|
||||
|
||||
|
||||
def trace_of(s):
|
||||
"""The last rename trace this session logged, flattened; `{}` if none.
|
||||
|
||||
Read off `window/logMessage`, which `lspclient` captures for exactly this.
|
||||
A row whose trace is empty is a row whose server was not `--verbose` or
|
||||
whose request never reached the engine — either way the phase says so
|
||||
rather than inventing fields.
|
||||
"""
|
||||
s.drain()
|
||||
found = [m for text in s.log_messages for m in TRACE_LINE.findall(text)]
|
||||
s.log_messages = []
|
||||
return parse_trace(found[-1]) if found else {}
|
||||
|
||||
|
||||
#: The renames §P2a compares, each `(row, file, needle, occurrence, offset,
|
||||
#: new_name, also_open)`. The first two are the tracker's own REF rows; the
|
||||
#: rest are the shapes the plan names — a unique internal name, a common port
|
||||
#: name, a new name that already exists in scope, a new name a great many
|
||||
#: external uses already spell, and the two doors to the all-sources fallback.
|
||||
RENAMES = [
|
||||
("tail: state_q -> state_q_x",
|
||||
sites.ENTROPY_SRC_SM, "state_d, state_q;", 1, len("state_d, "),
|
||||
"state_q_x", sites.ENTROPY_SRC_CORE),
|
||||
("ordinary: aes -> aes_renamed",
|
||||
sites.TB, " aes #(", 1, 2, "aes_renamed", None),
|
||||
("unique internal: cipher_alert -> cipher_alert_x",
|
||||
sites.AES_CORE, "cipher_alert;", 1, 0, "cipher_alert_x", None),
|
||||
("common port: clk_i -> clk_ix",
|
||||
sites.ENTROPY_SRC_SM, "input logic clk_i,", 1,
|
||||
len("input logic "), "clk_ix", None),
|
||||
("conflict: state_q -> state_d",
|
||||
sites.ENTROPY_SRC_SM, "state_d, state_q;", 1, len("state_d, "),
|
||||
"state_d", sites.ENTROPY_SRC_CORE),
|
||||
("new name many uses spell: cipher_alert -> clk_i",
|
||||
sites.AES_CORE, "cipher_alert;", 1, 0, "clk_i", None),
|
||||
("duplicate module: rstmgr_por -> rstmgr_por_x",
|
||||
sites.RSTMGR, "rstmgr_por ", 1, 0, "rstmgr_por_x", None),
|
||||
]
|
||||
|
||||
|
||||
@phase("renametrace")
|
||||
def phase_renametrace():
|
||||
"""The seven renames, each with the server's own trace beside the wire."""
|
||||
for row, relative, needle, occurrence, offset, new_name, also in RENAMES:
|
||||
rename_row(row, relative, needle, occurrence, offset, new_name, also)
|
||||
no_symbol_row()
|
||||
|
||||
|
||||
def rename_row(row, relative, needle, occurrence, offset, new_name, also):
|
||||
"""One traced rename, timed on the wire and sampled for peak RSS."""
|
||||
with session("workspace", verbose=True, storage_name="renametrace") 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)
|
||||
sampler = phases_new.Sampler(s.proc.pid)
|
||||
sampler.start()
|
||||
got = samples(s, "textDocument/rename", params, ARGS.tries + 1)
|
||||
peak = sampler.stop()
|
||||
edit = edit_of(got.last)
|
||||
trace = trace_of(s)
|
||||
status = schema.status_of(got.last)
|
||||
record(phase="renametrace", row=row, client=s.client_shape(),
|
||||
fingerprint=fingerprint(edit), peak_rss_kib=peak,
|
||||
file=relative, new_name=new_name,
|
||||
titles=sorted(os.path.basename(u)
|
||||
for u in phases_new.edited_uris(got.last)),
|
||||
note=json.dumps(trace),
|
||||
**dict(got.row(), **dict(counts(edit), **prefixed(trace))))
|
||||
|
||||
|
||||
def no_symbol_row():
|
||||
"""The other door to the whole scope: a cursor with no name to fan out
|
||||
from, which `rename.rs` answers with `ws.sources()` outright."""
|
||||
with session("workspace", verbose=True, storage_name="renametrace") as s:
|
||||
settled(s)
|
||||
s.log_messages = []
|
||||
params = dict(at(sites.TB, "// ", 1, 1), newName="nothing_here")
|
||||
sampler = phases_new.Sampler(s.proc.pid)
|
||||
sampler.start()
|
||||
got = samples(s, "textDocument/rename", params, ARGS.tries + 1)
|
||||
peak = sampler.stop()
|
||||
trace = trace_of(s)
|
||||
record(phase="renametrace", row="no symbol: whole scope then refuse",
|
||||
client=s.client_shape(), peak_rss_kib=peak, file=sites.TB,
|
||||
note=json.dumps(trace), **dict(got.row(), **prefixed(trace)))
|
||||
|
||||
|
||||
def prefixed(trace):
|
||||
"""The trace's fields, under `trace_` so nothing collides with schema 2."""
|
||||
return {"trace_%s" % key: value for key, value in trace.items()}
|
||||
@@ -34,6 +34,10 @@ ENTROPY_SRC_CORE = "hw/ip/entropy_src/rtl/entropy_src_core.sv"
|
||||
ENTROPY_SRC_SM = "hw/ip/entropy_src/rtl/entropy_src_main_sm.sv"
|
||||
SHA3_FPV = "hw/ip/kmac/fpv/tb/sha3_fpv.sv"
|
||||
AES_SBOX_MASKED = "hw/ip/aes/rtl/aes_sbox_canright_masked.sv"
|
||||
# Take 5 §P2a: `rstmgr_por` is declared in four files, so a use of it is an
|
||||
# ambiguous reference — the one shape that trips the rename fan-out's
|
||||
# all-sources escape hatch.
|
||||
RSTMGR = "hw/top_darjeeling/ip_autogen/rstmgr/rtl/rstmgr.sv"
|
||||
|
||||
# The take-3 `codeAction` cursors:
|
||||
# (label, file, needle, occurrence, fan-out, cursor offset into the needle).
|
||||
|
||||
Reference in new issue
Block a user