Compare commits

...
3 Commits
Author SHA1 Message Date
lucioandClaude Fable 5 b7a934080a Release 0.14.0 — the first-hover release
ci / checks (push) Successful in 52s
ci / corpus (push) Successful in 22s
release / build-and-publish (push) Successful in 4m54s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 20:22:30 -07:00
lucioandClaude Fable 5 172a034c67 The startup scan answers requests as it goes
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 21s
A request sent right after initialized waited out the whole startup
scan — 780 ms cold, 287 ms warm over 200 files, against 26-64 us once
the scan was done. The scan is now a value (Scan: begin/step/publish/
finish; rebuild_index_with is the same three-line loop, so one-shot
and interleaved are structurally the same code and fingerprint
identically), fed to the live index with one WorkspaceIndex::absorb
per drain — per-file merging measured quadratic, 11.7 s over 800
files — and the message queue drains between files: the first hover of
a session answers in 15.5 ms cold / 12.8 ms warm against the index so
far, open file first, scan totals inside noise. Order contract kept:
only the startup scan answers mid-way (must_wait holds requests queued
behind any rescan), scans under 64 files stay one-shot (a count, not a
clock), mid-scan rescan requests coalesce into exactly one follow-up,
shutdown stops the scan where it stands. All three tables publish
together. QA pinned the INTERLEAVE_ABOVE boundary, the absorb
duplicate-path edge and the mid-scan didOpen double-publish; the whole
pre-existing suite passes unmodified, stable over repeated runs.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 20:20:20 -07:00
lucioandClaude Fable 5 20567e1a7f The index carries every declaration's line, and hover stops re-reading files
ci / checks (push) Successful in 40s
ci / corpus (push) Successful in 18s
The owner's first-level cache, realized on the carrier the index
already had: DeclLines (name line + detail line) on every Decl/Def,
computed at index time from the LineIndex the analysis already holds —
tens of KB for 20k modules, FACTS_FORMAT 3->4, old stores discarded
whole. A closed file's hover heading now costs zero I/O (it survives
the file being deleted), and the snippet's one remaining read is
served from a bounded FileView LRU (4 entries / 8 MiB, newest kept,
dropped on set_document/close/update_one/rebuild): repeat hovers into
a 12 MB file go 5.8 ms -> ~1 us, cross-file hover means 40/157 us ->
4.7/12.9 us. Ports ride the same member entries, so their lines came
free. Stale-disk edits leave heading and snippet stale together, the
spells_exactly guard still omits rather than lies, and QA pinned the
pair. Measured and filed, not fixed here: the first request of a
session waits 287-780 ms behind the startup scan (handshake for the
next round).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 18:04:38 -07:00
27 changed files with 4042 additions and 248 deletions

No files matched your search

+38
View File
@@ -4,6 +4,44 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.14.0 — 2026-08-28
The first-hover release: the owner's "hover is really slow on first
try," traced to three costs and each one removed. Hover's steady state
was already microseconds; now the firsts are too — or as close as
physics allows.
### The index carries every declaration's line
Each indexed declaration — modules, and ports/parameters through the
same member entries — now records its line number(s), computed at index
time for a `u32` per name (+68 KB over the 860-file corpus). A hover
heading into a closed file costs zero I/O: it survives the file being
deleted. The persisted facts format moved to 4; an older cache is
discarded whole and rebuilt once (~175 ms on the corpus).
### Closed files are read once, not per hover
The snippet's one remaining read is served from a small bounded view
cache (4 files / 8 MiB, newest kept, invalidated on every path that can
change a file's text): a repeat hover into a 12 MB closed file goes
5.8 ms → ~1 µs, and mean cross-file hover 40/157 µs → 4.7/12.9 µs.
A stale view can only ever omit a snippet — the wrong-line guard is
unchanged.
### The startup scan answers requests as it goes
A request sent right after `initialized` used to wait out the whole
scan: 780 ms cold / 287 ms warm over 200 files. The scan now feeds the
live index incrementally and drains the message queue between files —
the first hover of a session answers in ~15 ms against the index so
far, with the open file indexed first. One merge per drain (per-file
merging measured quadratic: 11.7 s over 800 files), scans under 64
files stay one-shot, only the startup scan answers mid-way so the
request-order contract holds, and the finished index fingerprints
byte-identical to the old all-at-once scan. Scan totals unchanged
within noise.
## 0.13.1 — 2026-08-28
The F12-latency release: the two costs behind a slow jump out of a big
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.13.1"
version = "0.14.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.13.1"
version = "0.14.0"
[[package]]
name = "lucisv_server"
version = "0.13.1"
version = "0.14.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.13.1"
version = "0.14.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.13.1"
version = "0.14.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.13.1"
version = "0.14.0"
[[package]]
name = "vlog_refactor"
version = "0.13.1"
version = "0.14.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.13.1"
version = "0.14.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.13.1"
version = "0.14.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+26
View File
@@ -585,6 +585,32 @@ later:
salsa question is ever reopened, that is the number it has to beat —
incremental *lexing and parsing*, not incremental queries over a whole-file
parse, and it lands squarely on `CLAUDE.md`'s hard invariants 1 and 2.
**A fourth piece answered without salsa, 2026-08-28**
(`docs/features/hover-line-index/README.md`): a derived fact a query used to
recompute — the *line* a declaration is written on, which cost a whole file
read and a whole `LineIndex` per request — is now computed once when the
file is indexed and stored beside the span (`Def::lines`, `FACTS_FORMAT`
3 → 4), and the one thing still needing that file's text is served from a
small bounded cache of closed files. A repeat hover into a 12 MB closed file
goes 5.75 ms → 0.95 µs; a whole scan is unchanged and the store grows 2.9 %.
Still no query graph: what is cached is a value, invalidated at four named
points, not a node in a dependency graph. **The larger number the same round
measured is not an incrementality problem at all**: the first request of a
session waits out the startup scan (780 ms cold, 287 ms warm), because
`Server::new` scans before the message loop starts. Filed there, not fixed.
→ **Fixed 2026-08-28** (`docs/features/scan-interleave/README.md`): the scan
is now per-file steps with the message queue drained between them, so a
startup scan of more than 64 files answers requests while it runs — 780 ms →
**15.5 ms** cold, 287 ms → **12.8 ms** warm, with the scan's own total moving
under a percent (860-file corpus: 351 → 353 ms cold, 187 → 189 ms warm). The
merge cost was measured first and ruled per-file feeding out: a merge is a
pass over the whole index, so one per file would have cost 631 ms of merging
on 200 files against 464 ms of parsing. Records are staged per file and folded
in with one `WorkspaceIndex::absorb` per *drain*, and a drain only happens
when a message is waiting — so a scan nobody is waiting on pays nothing.
Answers given mid-scan read the index as of that moment, and only the startup
scan gives them: a request queued behind a message that asked for a rescan
waits for that rescan, which is the order contract the loop always kept.
- [x] **Release prep.** `LICENSE` (MIT), `CHANGELOG.md` (v0.2.0), version
bumped to 0.2.0 across the workspace and the extension, `tools/release.sh`
(release binaries + `.vsix` + `SHA256SUMS` into a gitignored `dist/`) and
+21 -1
View File
@@ -126,6 +126,21 @@ impl Candidates {
self.set_words(path, words);
}
/// [`Candidates::update_words`] for a batch of files — the form a scan
/// publishing what it has indexed so far uses.
///
/// One re-derivation of the two index tables for the whole batch rather
/// than one per file: they are read off the index and nothing else, so
/// doing it once at the end of the batch is doing it once with the same
/// answer. The word table is patched per file exactly as it is there.
pub fn absorb(&mut self, index: &WorkspaceIndex, batch: Vec<(PathBuf, Vec<String>)>) {
for (path, words) in batch {
self.set_words(&path, words);
}
self.units = units_of(index);
self.macros = macros_of(index);
}
/// Drop one file's contribution entirely.
pub fn remove_file(&mut self, index: &WorkspaceIndex, path: &Path) {
self.units = units_of(index);
@@ -229,7 +244,12 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
/// orders of magnitude more identifier *tokens* than distinct identifiers
/// (900k against 17k over this repo's corpus), and copying every one of them
/// only to sort the copies away costs more than the lexing does.
fn words_in(text: &str) -> Vec<String> {
///
/// `pub(crate)` because a scan lexes each file as it reaches it rather than in
/// one pass at the end: no part of a scan may be longer than one file, or the
/// message queue goes unanswered for the length of it
/// (`docs/features/scan-interleave/README.md`).
pub(crate) fn words_in(text: &str) -> Vec<String> {
// A file that does not lex contributes nothing rather than being guessed
// at with a regex — the same all-or-nothing rule the lexer gives every
// other consumer.
+130 -52
View File
@@ -179,11 +179,6 @@ fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
// `declaration_snippet` checks the other file's text against.
let name = doc.semantics.reference_at(offset).map(|r| r.name.as_str());
let mut parts = Vec::with_capacity(defs.len());
// One read per *file*, not per card: a closed file's heading line
// and its snippet below both come from this memoized view, and a
// hover can name the same file several times (two modules with
// one name, a package and its member).
let mut disk: Option<(std::path::PathBuf, String, LineIndex)> = None;
for def in defs {
let label = kind_label(def.kind);
let path = ws.index().path(def.file).map(|p| p.to_path_buf());
@@ -192,28 +187,34 @@ fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
if let Some(path) = path.as_ref() {
if ws.document_for_path(path).is_some() {
// The live path reads the open buffer — `live_symbol`
// resolves the current span, and its guards stay.
// resolves the current span, and its guards stay. The
// line comes from that buffer's own index rather than
// from `def.lines`, because the buffer may hold
// unsaved edits the index has not seen.
where_ = line_number(ws, path, def.name_span.start)
.map(|line| format!("{}:{line}", display_name(path)));
snippet = name.and_then(|name| declaration_snippet(ws, def, name));
} else if let Some((text, index)) = disk_view(ws, path, &mut disk) {
// The disk path: the same read serves the heading and
// the snippet, under the same `spells_exactly` guard
// `declaration_snippet` applies.
where_ = Some(format!(
"{}:{}",
display_name(path),
index.line_col(def.name_span.start).0
));
snippet = name.and_then(|name| {
spells_exactly(text, def.name_span, name)
} else {
// The heading costs nothing: the line was recorded
// when the file was indexed, from the same text the
// span came from (`vlog_semantic::DeclLines`). Only
// the snippet still wants the file's text, and that
// comes from the workspace's shared view — one read
// per file per generation, so a card naming one file
// twice, and the next hover into it, are both free.
where_ = Some(format!("{}:{}", display_name(path), def.lines.name));
snippet = name.zip(ws.file_view(path)).and_then(|(name, view)| {
spells_exactly(&view.text, def.name_span, name)
.then(|| {
fenced_sections(text, index, def.name_span, def.detail_span)
fenced_sections(
&view.text,
&view.lines,
def.name_span,
def.detail_span,
)
})
.flatten()
});
} else {
where_ = Some(display_name(path));
}
}
let where_ = where_.unwrap_or_else(|| "the workspace".to_string());
@@ -385,11 +386,11 @@ const SNIPPET_CHARS: usize = 400;
/// The source of a declaration in an **open** buffer, fenced for the card.
///
/// The index holds only `{file, name_span, kind}` and no text
/// (`docs/features/workspace-index/README.md`), so the line is fetched here,
/// at hover time, from whichever text the span is actually valid against.
/// A closed file is read by the caller's `disk_view` memo instead — one read
/// per hover — so this function never touches the disk.
/// The index holds spans, kinds and lines but no text
/// (`docs/features/workspace-index/README.md`), so the *source* is fetched
/// here, at hover time, from whichever text the span is actually valid
/// against. A closed file is served by `Workspace::file_view` in the caller
/// instead, so this function never touches the disk.
///
/// `None` — no snippet, today's card unchanged — wherever the two could
/// disagree: the span the live buffer does not cover, or a span covering
@@ -414,23 +415,6 @@ fn declaration_snippet(ws: &Workspace, def: &Def, name: &str) -> Option<String>
)
}
/// One closed file, read once per hover: the memo `symbol_hover` keys the
/// heading line and the snippet off, so a card never pays for the same file
/// twice. `None` for an unreadable file, which the caller renders as a bare
/// heading — exactly the card it always showed.
fn disk_view<'a>(
ws: &Workspace,
path: &std::path::Path,
memo: &'a mut Option<(std::path::PathBuf, String, LineIndex)>,
) -> Option<(&'a str, &'a LineIndex)> {
if !memo.as_ref().is_some_and(|held| held.0 == path) {
let text = ws.text_of(path)?;
let index = LineIndex::new(&text);
*memo = Some((path.to_path_buf(), text, index));
}
memo.as_ref().map(|(_, text, index)| (text.as_str(), index))
}
/// The live symbol in an open buffer that *is* this indexed declaration.
///
/// Only the declarations spelling `name` are probed — `indexed_def_for_symbol`
@@ -1201,6 +1185,92 @@ endmodule
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read() {
// The round's central claim: `file:line` for an indexed declaration is
// `Def::lines`, recorded when the file was scanned, so the heading
// costs no read at all. Proved by removing the file from under the
// index — a heading that still names the line cannot have read it.
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("headingfromindex", &[("sub.sv", PORTS), ("top.sv", top)]);
fs::remove_file(dir.join("sub.sv")).expect("remove");
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert!(body.contains("**port** — declared in `sub.sv:2`"), "got {body}");
// The snippet is the half that really wanted the text, and it is
// dropped rather than guessed at — exactly as it always was for a
// file that cannot be read.
assert!(!body.contains("```systemverilog"), "no snippet without text: got {body}");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_second_hover_into_one_closed_file_reads_nothing() {
// The other half: the snippet's read is shared through
// `Workspace::file_view`, so the file is read once and the next hover
// into it — the same card, or another name in the same file — is
// served from what that read left behind. Observed the only honest
// way: rewrite the file behind the server's back and require the
// second card to be the first one. Stale text can only ever *omit* a
// snippet (the `spells_exactly` guard), never show a wrong line.
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("viewshared", &[("sub.sv", PORTS), ("top.sv", top)]);
let first = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert!(first.contains("input logic [7:0] addr"), "premise: got {first}");
fs::write(dir.join("sub.sv"), "module sub (\n input logic [15:0] addr\n);\nendmodule\n")
.expect("write");
let second = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert_eq!(second, first, "the second hover did not read the file again");
let _ = fs::remove_dir_all(&dir);
}
/// QA (2026-08-28): the staleness window the README's Assumptions section
/// claims — "a line is a fact about the same snapshot the span is... where
/// the file has changed on disk with nothing telling the server, both are
/// stale together" — reproduced rather than taken on faith, and in the
/// one shape that could actually disagree: the index was built from the
/// *original* `sub.sv`, but `sub.sv` is rewritten on disk — no `didSave`,
/// no watcher event, no `update_one`/`rebuild_index` call, so the index is
/// never told — **before the view cache ever reads it**, so the first
/// hover's disk read sees the *new* bytes under the *old* span and offset.
/// The heading must still show the line the index recorded at the last
/// scan (stale, not a fresh-read line the index never computed), and the
/// snippet, reading the genuinely current text, must find the old span no
/// longer spells `addr` there and drop itself via `spells_exactly` rather
/// than show whatever now sits at that byte range.
#[test]
fn an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet() {
let top = "module top;\n sub u (.addr(8'h0));\nendmodule\n";
let (dir, ws, uri) = included("staleheading", &[("sub.sv", PORTS), ("top.sv", top)]);
// Edited behind the server's back, before any hover has read this
// file at all: four lines inserted above the module, so `addr`'s true
// line is now 6 — and the byte offset the index still holds for it
// (from the *original* `sub.sv`) now lands inside a comment, not
// `addr`. The view cache is empty for this path, so the hover below
// is a genuinely fresh disk read of the edited bytes.
fs::write(
dir.join("sub.sv"),
"// one\n// two\n// three\n// four\nmodule sub (\n input logic [7:0] addr,\n\
\x20 output logic ready\n);\nendmodule\n",
)
.expect("write");
let after = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
assert!(
after.contains("**port** — declared in `sub.sv:2`"),
"the heading must show the line the index recorded, not the file's true current \
line (6), until something reindexes it: got {after}"
);
assert!(
!after.contains("```systemverilog"),
"the snippet must be dropped, not show the comment the stale span now lands on: \
got {after}"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_package_member_shows_its_declaration_line() {
let pkg =
@@ -1737,15 +1807,18 @@ mod qa_hover_declarations {
let _ = fs::remove_dir_all(&dir);
}
/// Angle 7 (perf smell): a hover resolving into a large *closed* file
/// reads the whole file from disk and builds a fresh `LineIndex` over it.
/// Before the per-hover `disk_view` memo this happened **twice** — once
/// inside `locate::line_number` for the heading and once for the snippet —
/// and the memo's whole reason to exist is that it is now once. Not a
/// Angle 7 (perf smell): the **first** hover resolving into a large
/// *closed* file reads the whole file from disk and builds a fresh
/// `LineIndex` over it. It once did that twice — heading and snippet
/// independently — then once, through a per-hover memo, and since
/// `hover-line-index` (2026-08-28) it does it once *per file per
/// generation of that file*: the heading no longer wants any text at all
/// (`Def::lines`), and the snippet's read is held in
/// `Workspace::file_view` for the next hover. So this number is the first
/// touch, which is the one that still costs; the repeat is measured in
/// `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`. Not a
/// correctness assertion, just the number; run with `cargo test --release
/// -p lucisv_server large_closed -- --ignored --nocapture` to see it. The
/// same read, measured against the hover it serves, is in
/// `perf::hovering_across_files_into_a_closed_file`.
/// -p lucisv_server large_closed -- --ignored --nocapture` to see it.
#[test]
#[ignore = "perf measurement, not a correctness assertion — see QA log"]
fn hovering_into_a_large_closed_file_reads_it_once() {
@@ -1776,10 +1849,15 @@ mod qa_hover_declarations {
let body = text_of(&hover(&ws, &uri, at(top, "addr(8")).expect("hover"));
let elapsed = start.elapsed();
assert!(body.contains("[7:0] addr"), "got {body}");
let start = std::time::Instant::now();
let _ = hover(&ws, &uri, at(top, "addr(8")).expect("hover");
let again = start.elapsed();
eprintln!(
"hover into a {:.1} MB closed file took {:?} (one read + one LineIndex, shared by heading and snippet)",
"hover into a {:.1} MB closed file took {:?} the first time (one read + one \
LineIndex, for the snippet alone) and {:?} the second (nothing read)",
sub.len() as f64 / 1_000_000.0,
elapsed
elapsed,
again
);
let _ = fs::remove_dir_all(&dir);
}
+24
View File
@@ -144,6 +144,30 @@ impl IncludeGraph {
};
}
/// [`IncludeGraph::update_file`] for a batch of files, with the `+incdir+`s
/// the scope resolves to right now — the form a scan publishing what it
/// has indexed so far uses.
///
/// `known` is the scan's whole work list rather than the files it has
/// reached, so the known-file and folded-spelling tables are complete from
/// the first publish: which files *exist* is settled the moment the scope
/// is resolved, and only the edges are discovered file by file. One
/// `relearn` for the batch, for the same reason
/// [`Candidates::absorb`](crate::candidates::Candidates::absorb) re-derives
/// its index tables once.
pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]) {
self.incdirs = incdirs.to_vec();
self.relearn(known);
for (path, text) in batch {
let targets: Vec<PathBuf> =
scan(text).iter().filter_map(|include| self.resolve(Some(path), include)).collect();
match targets.is_empty() {
true => self.edges.remove(*path),
false => self.edges.insert(path.to_path_buf(), targets),
};
}
}
/// Drop one file from the graph: its own edges, and its place among the
/// known files.
pub fn remove_file(&mut self, path: &Path, known: &[PathBuf]) {
+52 -16
View File
@@ -569,27 +569,46 @@ mod tests {
}
#[test]
fn a_store_from_the_previous_facts_format_is_dropped_not_misread() {
// Simulates a store written by the released 0.12.1 (FACTS_FORMAT 2,
// before detail_span). Same CACHE_FORMAT and VERSION as today — only
// FACTS_FORMAT differs — so the only thing that can catch it is the
// FACTS_FORMAT field in the header line. QA finding for
// docs/features/port-detail-spans/README.md: the format bump 2 → 3
// had no regression test of its own; this is that test.
let dir = TempDir::new("factsformat2");
fn a_store_from_any_previous_facts_format_is_dropped_not_misread() {
// Every `FACTS_FORMAT` this build is not, with today's `CACHE_FORMAT`
// and `VERSION` — so the header's format field is the only thing that
// can catch them. Written as a loop rather than against one number so
// it cannot go stale the next time a record grows a field: it was
// pinned at 2 for the `detail_span` bump (QA finding,
// `docs/features/port-detail-spans/README.md`) and would have gone on
// testing 2 forever.
let dir = TempDir::new("factsformats");
let file = dir.file("m.sv", M);
let encoded = facts(&file, M).encode().expect("encodes");
let old_format_store = format!(
"lucisv-index-cache\t{CACHE_FORMAT}\t2\t{VERSION}\n{}\n",
line(content_hash(M.as_bytes()), &encoded)
);
std::fs::write(dir.path.join(FILE), old_format_store).expect("write");
for format in 1..FACTS_FORMAT {
let old_format_store = format!(
"lucisv-index-cache\t{CACHE_FORMAT}\t{format}\t{VERSION}\n{}\n",
line(content_hash(M.as_bytes()), &encoded)
);
std::fs::write(dir.path.join(FILE), old_format_store).expect("write");
let cache = IndexCache::open(Some(dir.path.clone()));
assert!(
cache.facts_for(&file, M).is_none(),
"a format-{format} record must not be read as a format-{FACTS_FORMAT} one"
);
}
let mut cache = IndexCache::open(Some(dir.path.clone()));
// And the belt to that brace: a record really written in the previous
// format — this one is a format-3 record, which is today's minus the
// two per-declaration line fields `hover-line-index` added — does not
// decode as one of today's *even if* something served it past the
// header. Field-shifting is what the length prefixes and the
// end-of-record check exist to make impossible.
let format_3 = strip_the_line_fields(&encoded);
assert_ne!(format_3, encoded, "premise: the fixture has a declaration to strip");
assert!(
cache.facts_for(&file, M).is_none(),
"a format-2 record must not be read as a format-3 one"
FileFacts::decode(&format_3).is_none(),
"a format-3 record decoded as a format-4 one: {format_3}"
);
// Finally, the store is replaced under this build's header rather than
// appended to, and reopening reads the fresh record back.
let mut cache = IndexCache::open(Some(dir.path.clone()));
cache.record(&facts(&file, M), M);
let text = dir.store_text();
assert!(
@@ -602,6 +621,23 @@ mod tests {
);
}
/// Today's encoded record, minus the two line fields every declaration
/// gained in `FACTS_FORMAT` 4 — i.e. what format 3 wrote for the same
/// file. `M` declares exactly one unit and no members, so the fields to
/// drop are the two immediately after that unit's four span offsets.
fn strip_the_line_fields(encoded: &str) -> String {
let mut fields: Vec<&str> = encoded.split('\t').collect();
let Some(units) = fields.iter().position(|f| *f == "U") else {
return encoded.to_string();
};
// U, count, name, kind, name_span×2, detail×2, then the two lines.
let lines_at = units + 8;
if fields.len() > lines_at + 1 {
fields.drain(lines_at..lines_at + 2);
}
fields.join("\t")
}
#[test]
fn an_empty_store_is_a_claim_to_finish_rather_than_a_store_to_replace() {
// The one shape `create_new` introduces: a zero-byte store, left by a
+17 -11
View File
@@ -3,12 +3,15 @@
//! The workspace index deliberately keeps no file contents
//! (`docs/features/workspace-index/README.md`), so a span in another file has
//! to be converted against that file's text, fetched here with the same
//! open-buffer-beats-disk precedence the index rebuild uses.
//! open-buffer-beats-disk precedence the index rebuild uses — from the
//! buffer's own line index when there is one, and otherwise through
//! `Workspace::file_view`, which reads a closed file at most once per
//! generation of it rather than once per question about it.
use std::path::Path;
use lsp_types::Location;
use vlog_parser::{LineIndex, TextRange};
use vlog_parser::TextRange;
use crate::convert::Positions;
use crate::state::Workspace;
@@ -17,25 +20,28 @@ use crate::uri::path_to_uri;
/// The location of a byte span inside a workspace file.
pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location> {
let uri = path_to_uri(path)?;
let text = ws.text_of(path)?;
let index = LineIndex::new(&text);
let range = Positions::new(&text, &index).range(span);
Some(Location { uri, range })
if let Some(doc) = ws.document_for_path(path) {
return Some(Location { uri, range: doc.positions().range(span) });
}
let view = ws.file_view(path)?;
Some(Location { uri, range: Positions::new(&view.text, &view.lines).range(span) })
}
/// The 1-based line a byte offset falls on, for hover text that names a file
/// and a line rather than jumping to it.
///
/// An open buffer answers from the line index it already carries; a closed
/// file is read and indexed here — which is why a hover that names one file
/// twice reads it through the per-request memo in `hover::symbol_hover`, not
/// through two calls here.
/// file answers from the shared view cache. **An indexed declaration should
/// not come here at all** — `Def::lines` already holds its line, recorded when
/// the file was indexed, and that answer costs nothing
/// (`docs/features/hover-line-index/README.md`). What is left for this
/// function is the spans the index records no line for, which today is a
/// `` `define``'s.
pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
if let Some(doc) = ws.document_for_path(path) {
return Some(doc.line_index.line_col(offset).0);
}
let text = ws.text_of(path)?;
Some(LineIndex::new(&text).line_col(offset).0)
Some(ws.file_view(path)?.lines.line_col(offset).0)
}
/// How a file is named in hover text: its file name, which is what a Verilog
+166 -5
View File
@@ -252,10 +252,14 @@ fn hovering_a_local_declaration() {
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn hovering_across_files_into_a_closed_file() {
// The disk path: the target file is closed, so the card's heading line and
// its snippet both come out of one read (`hover::disk_view`). The second
// read that memo removed is measured beside it — it is the whole file
// again, plus a whole `LineIndex` again.
// The disk path: the target file is closed, so the card's heading line
// comes from the index (`Def::lines`, no read at all) and its snippet from
// the workspace's shared view of that file — read once, then held. This
// is a *mean of twenty*, so nineteen of the runs are the held case: it is
// the steady-state hover, not the first touch (which
// `hovering_into_a_big_closed_file_first_touch_and_repeat` reports on its
// own). Measured beside it is the read the first touch pays and every
// later one does not.
for lines in SIZES {
let sub = generated_module("sub", lines);
let top = "module top;\n sub u (.data_in(32'h0));\nendmodule\n";
@@ -279,12 +283,73 @@ fn hovering_across_files_into_a_closed_file() {
assert!(format!("{card:?}").contains("sub.sv"), "{card:?}");
eprintln!(
"hover, closed cross-file target: {lines} lines took {took:?} \
(one read + LineIndex of that file: {one_read:?}, which is what the memo saves)"
(one read + LineIndex of that file: {one_read:?}, which only the first touch pays)"
);
let _ = std::fs::remove_dir_all(&dir);
}
}
/// `cargo test --release -p lucisv_server perf::hovering_into_a_big -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn hovering_into_a_big_closed_file_first_touch_and_repeat() {
// The owner's report, measured: hovering an *instantiation* and hovering
// one of its *ports* into a closed file that is big — the netlist-adjacent
// shape a real workspace has one of. Two numbers per hover: the first
// touch of that file in the session, and the touch after it, which is the
// one a text cache can make free.
//
// "First touch" is cold to *this process* and to nothing else: the file
// was written moments ago, so the OS page cache still holds it and the
// read below is the cheap kind. A genuinely cold disk is worse than this,
// never better.
let sub = big_module("sub", 12_000_000);
let top = "module top;\n sub u (.data_in(32'h0));\nendmodule\n";
let dir = scratch("bighover", &[("sub.sv", sub.as_str()), ("top.sv", top)]);
let uri = path_to_uri(&dir.join("top.sv")).expect("uri");
let instantiation = top.find("sub u").expect("an instantiation") as u32;
let port = top.find("data_in(").expect("a port connection") as u32;
for (what, offset) in [("instantiation", instantiation), ("port", port)] {
// A fresh workspace per measurement, so "first touch" really is one.
let mut ws = Workspace::default();
ws.set_client_settings(crate::settings::ClientSettings {
max_file_size: 100_000_000,
..Default::default()
});
ws.open_whole_workspace(vec![dir.clone()]);
ws.set_document(uri.clone(), top.to_string());
let start = Instant::now();
let card = hover(&ws, &uri, black_box(offset)).expect("a cross-file card");
let first = start.elapsed();
assert!(format!("{card:?}").contains("sub.sv"), "{card:?}");
let repeat = mean(10, || {
black_box(hover(&ws, &uri, black_box(offset)));
});
eprintln!(
"hover on a {what} into a {:.1} MB closed file: first touch {first:?}, \
repeat {repeat:?}",
sub.len() as f64 / 1_000_000.0
);
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A module of at least `bytes` bytes: a small ANSI header — the declaration a
/// hover actually lands on — behind a wall of filler lines, which is the shape
/// of the files the owner's report is about.
fn big_module(name: &str, bytes: usize) -> String {
let mut src = format!("module {name} (\n input logic [31:0] data_in\n);\n");
let mut n = 0;
while src.len() < bytes {
src.push_str(&format!(" // filler line {n} of a big netlist-shaped file\n"));
n += 1;
}
src.push_str("endmodule\n");
src
}
/// `cargo test --release -p lucisv_server perf::reindexing -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
@@ -314,6 +379,102 @@ fn reindexing_one_changed_file() {
}
}
/// `cargo test --release -p lucisv_server perf::what_a_scan -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn what_a_scan_does_before_its_first_file() {
// The floor under a mid-scan answer's latency. A scan answers messages
// between two *files*, so whatever it does before the first one is a
// block no drain can break up: resolving the scope, reading every
// in-scope file, and opening the persistent store. Measured because
// `docs/features/scan-interleave/README.md` files "read the files lazily"
// as a deliberate not-done, and a not-done is only honest with a number.
let files: Vec<(String, String)> =
(0..200).map(|n| (format!("m{n}.sv"), generated_module(&format!("m{n}"), 1_000))).collect();
let refs: Vec<(&str, &str)> =
files.iter().map(|(name, text)| (name.as_str(), text.as_str())).collect();
let dir = scratch("scanhead", &refs);
let mut workspace = Workspace::default();
workspace.set_client_settings(crate::settings::ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
});
workspace.adopt_roots(vec![dir.clone()]);
let started = Instant::now();
let mut scan = workspace.begin_scan(&mut |_| {});
let head = started.elapsed();
let started = Instant::now();
workspace.scan_step(&mut scan, &mut |_| {});
let one = started.elapsed();
let started = Instant::now();
while workspace.scan_step(&mut scan, &mut |_| {}) {}
let rest = started.elapsed();
let started = Instant::now();
workspace.finish_scan(scan);
let tail = started.elapsed();
eprintln!(
"scan of {} files of 1k lines: before the first file {head:?}, \
one file {one:?}, the other {} {rest:?}, finishing {tail:?}",
files.len(),
files.len() - 1
);
let _ = std::fs::remove_dir_all(&dir);
}
/// `cargo test --release -p lucisv_server perf::publishing -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn publishing_a_half_built_index_mid_scan() {
// What an interleaved scan's *publish* costs, against the per-file work it
// is interleaved with. `docs/features/scan-interleave/README.md` chose the
// publish rhythm from these numbers: a merge is a whole-index pass, so one
// per file would be quadratic and one per drain is not.
for files in [50usize, 200, 800] {
let sources: Vec<(PathBuf, String)> = (0..files)
.map(|n| (PathBuf::from(format!("m{n}.sv")), generated_module(&format!("m{n}"), 1_000)))
.collect();
let records: Vec<vlog_semantic::FileFacts> = sources
.iter()
.map(|(path, src)| vlog_semantic::FileFacts::of(path.clone(), src))
.collect();
let parse = mean(3, || {
let (path, src) = &sources[0];
black_box(vlog_semantic::FileFacts::of(black_box(path.clone()), black_box(src)));
});
let build = mean(3, || {
let mut builder = vlog_semantic::IndexBuilder::new();
for facts in &records {
builder.add_facts(facts.clone());
}
black_box(builder.finish());
});
let clone = mean(3, || {
black_box(records.clone());
});
let index = WorkspaceIndex::build(
sources.iter().map(|(path, src)| (path.clone(), src.as_str())).collect::<Vec<_>>(),
);
let held = mean(10, || {
let mut index = index.clone();
index.update_facts(black_box(records[files / 2].clone()));
black_box(index);
});
let index_clone = mean(10, || {
black_box(index.clone());
});
eprintln!(
"{files} files of 1k lines: one file's parse {parse:?}; \
one whole merge {:?} (build {build:?} less {clone:?} of record cloning); \
one update_facts on a held file {:?} (less {index_clone:?} of index cloning); \
per-file feeding would cost {:?} of merging against {:?} of parsing",
build.saturating_sub(clone),
held.saturating_sub(index_clone),
held.saturating_sub(index_clone) * files as u32,
parse * files as u32,
);
}
}
/// `cargo test --release -p lucisv_server perf::looking_up -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+96
View File
@@ -4825,3 +4825,99 @@ fn a_keystroke_round_trip_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
}
/// `cargo test --release -p lucisv_server --test e2e a_hover_issued -- --ignored --nocapture --test-threads=1`
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
fn a_hover_issued_during_the_initial_scan_is_answered_during_it() {
// The probe the hover-latency round left behind, now measuring the other
// side of the change it filed for. It used to read
// `..._waits_for_it`, because `Server::new` ran the whole startup scan
// *before* `run()`'s message loop took its first message and anything a
// client sent the moment it had sent `initialized` sat in the OS pipe
// until that scan was done: 780 ms cold / 287 ms warm over these 200
// files. The scan now answers messages between its files
// (`docs/features/scan-interleave/README.md`), so what this prints is
// one file's step and not a whole scan.
//
// A `lucisv.toml` naming a filelist is what makes the startup scan index
// the whole tree: it is the top rung of the scope ladder and the only one
// that answers before any buffer has been opened.
let dir = temp_dir("firsthover");
let files = 200usize;
let mut list = String::new();
for n in 0..files {
let name = format!("m{n}.sv");
std::fs::write(dir.join(&name), generated_module(&format!("m{n}"), 1_000)).expect("write");
list.push_str(&format!("{name}\n"));
}
std::fs::write(dir.join("files.f"), &list).expect("write");
let top = "module top;\n m7 u (.data_in(32'h0));\nendmodule\n";
let top_path = dir.join("top.sv");
std::fs::write(&top_path, top).expect("write");
std::fs::write(dir.join("lucisv.toml"), "filelist = \"files.f\"\n").expect("write");
// `top.sv` is not in the filelist, so it is not indexed — but it is what
// the hover is *issued from*, and a buffer is indexed by being opened.
std::fs::write(dir.join("files.f"), format!("{list}top.sv\n")).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", top_path.display());
let hover = |id: u32| {
format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":3}}}}}}"#
)
};
// Two whole sessions over the same storage folder: the first fills the
// persistent index cache, the second reads it. Both are measured, because
// "does the cache fix this?" is the second half of the question — it makes
// the scan cheaper, and the first hover still waits out whatever is left.
let mut took = Vec::new();
for session in 0..2 {
let mut live = Live::start();
// The progress capability is what makes "the scan is over" observable
// to the client, and therefore to the second measurement below.
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}},"initializationOptions":{{"storagePath":"{}"}}}}}}"#,
dir.join("storage").display()
));
live.wait_for(|m| m["id"] == 1);
// Everything a client sends the instant the handshake is done, in one
// go — which is exactly what VS Code does with the editor already open.
let started = std::time::Instant::now();
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(top).expect("json")
));
live.send(&hover(2));
live.wait_for(|m| m["id"] == 2);
let queued_behind_the_scan = started.elapsed();
// The same hover, with the scan long finished — which is where the
// cross-file answer is required, because *that* one reads a finished
// index. The mid-scan one above reads the index as of the moment it
// was asked, and `m7.sv` sorts a long way down 200 paths.
live.wait_for(|m| m["params"]["value"]["kind"] == "end");
let started = std::time::Instant::now();
live.send(&hover(3));
let done = live.wait_for(|m| m["id"] == 3);
let after_the_scan = started.elapsed();
assert!(
format!("{done:#?}").contains("m7.sv"),
"the hover must really answer across files once the scan is done: {done:#?}"
);
live.finish();
took.push((session, queued_behind_the_scan, after_the_scan));
}
for (session, behind, after) in took {
let store = if session == 0 { "cold store" } else { "warm store" };
eprintln!(
"hover issued the moment `initialized` was sent, over {files} files of 1k lines \
({store}): {behind:?}; the same hover once the scan is done: {after:?}"
);
}
let _ = std::fs::remove_dir_all(&dir);
}
+17 -3
View File
@@ -20,13 +20,13 @@ use vlog_parser::defines::{Define, DefineKind, DefineTable};
use vlog_parser::span::TextRange;
use crate::model::SymbolKind;
use crate::workspace::{Decl, DeclSite, FileFacts, ReferenceFact, SiteFact};
use crate::workspace::{Decl, DeclLines, DeclSite, FileFacts, ReferenceFact, SiteFact};
/// The version of the encoding below. Bump it on **any** change to what a
/// record holds or to how it is written: a store stamped with another number
/// is discarded whole, which is the only way a reader can be sure it is not
/// reading last month's field order as this month's.
pub const FACTS_FORMAT: u32 = 3;
pub const FACTS_FORMAT: u32 = 4;
impl FileFacts {
/// These facts as one line's worth of fields, tab-separated.
@@ -197,6 +197,13 @@ impl Writer {
self.num(0);
}
}
// The declaration's lines, on the same unconditional-pair rule: the
// name's line, then the detail span's or `0` for the `None` above.
// `FACTS_FORMAT` is bumped for these two fields, so a store written
// before them is discarded rather than read short by two
// (`docs/features/hover-line-index/README.md`).
self.num(decl.lines.name);
self.num(decl.lines.detail.unwrap_or(0));
}
fn site(&mut self, site: &DeclSite) {
@@ -317,7 +324,14 @@ impl<'a> Reader<'a> {
let start = self.num()?;
let end = self.num()?;
let detail_span = (start != 0 || end != 0).then_some(TextRange::new(start, end));
Some(Decl { name, name_span, kind, detail_span })
// A line is 1-based, so `0` is the `None` here too — and a detail line
// is present exactly when a detail span is, which a record written by
// this format always agrees with.
let name_line = self.num()?;
let detail_line = self.num()?;
let lines =
DeclLines { name: name_line, detail: (detail_line != 0).then_some(detail_line) };
Some(Decl { name, name_span, kind, detail_span, lines })
}
fn site(&mut self) -> Option<DeclSite> {
+3 -3
View File
@@ -31,9 +31,9 @@ pub use model::{
SymbolId, SymbolKind,
};
pub use workspace::{
index_order, resolve_external, DeclSite, Def, Definition, DefinitionKey, ExternalResolutions,
ExternalTarget, FileFacts, FileId, IndexBuilder, IndexCounts, InheritanceEdge,
InstantiationEdge, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
index_order, resolve_external, DeclLines, DeclSite, Def, Definition, DefinitionKey,
ExternalResolutions, ExternalTarget, FileFacts, FileId, IndexBuilder, IndexCounts,
InheritanceEdge, InstantiationEdge, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
};
use std::collections::HashMap;
+130 -17
View File
@@ -19,7 +19,7 @@ use std::path::{Path, PathBuf};
use vlog_parser::ast::SourceFile;
use vlog_parser::defines::{collect_defines, Define, DefineKind, DefineTable};
use vlog_parser::span::TextRange;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex};
use crate::model::{ReferenceId, Resolution, Symbol, SymbolKind};
use crate::{analyze, classes, instantiations, Semantics};
@@ -41,6 +41,44 @@ pub struct Def {
/// non-ANSI port's body `input wire clk;`. A cross-file hover shows these
/// lines; `None` for every declaration complete where it is named.
pub detail_span: Option<TextRange>,
/// Which lines those spans fall on, read while the file was indexed.
pub lines: DeclLines,
}
/// Where a declaration sits in its file, counted in **lines**, computed when
/// that file is indexed.
///
/// The index keeps no file text, so before this every `file:line` a server
/// printed for an indexed declaration cost a read of the declaring file and a
/// whole [`LineIndex`] over it — the thing a cross-file hover into a closed
/// file was mostly spending its time on. A line is four bytes per declaration,
/// a few tens of KB for a workspace of 20 000 modules, and it is the whole of
/// what a heading needs.
///
/// **One value per declaration, so it extends by gaining a field.** Members
/// are [`Decl`]s exactly as units are, so a module's ports already carry their
/// own lines here; a column, or a rendered preview, is another field written
/// beside these two — plus the [`crate::FACTS_FORMAT`] bump any change to a
/// record owes — and not a second table to keep in step with this one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DeclLines {
/// 1-based line the declared name is on.
pub name: u32,
/// 1-based line the `detail_span` starts on, `None` exactly when there is
/// no detail span.
pub detail: Option<u32>,
}
impl DeclLines {
/// The lines a declaration's spans fall on, read off its file's line
/// index. 1-based, so `name` is what `LineIndex::line_col` reports and
/// what a `file:line` prints.
fn of(lines: &LineIndex, name_span: TextRange, detail_span: Option<TextRange>) -> DeclLines {
DeclLines {
name: lines.line_col(name_span.start).0,
detail: detail_span.map(|span| lines.line_col(span.start).0),
}
}
}
/// Stable identity of one indexed declaration inside the current index.
@@ -412,6 +450,52 @@ impl WorkspaceIndex {
}
}
/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for
/// many files at once — and for **one** merge rather than one each.
///
/// Same contract as both — what comes out is the index a full
/// [`WorkspaceIndex::build`] over the records it now holds would have
/// produced — **provided each path appears once in `records`**. It holds
/// for the same reason theirs does: the records are kept path-sorted and
/// one file to a path, and [`WorkspaceIndex::merge`] is then the same loop
/// [`IndexBuilder::finish`] runs over the same list. A batch that names
/// one path twice is an update applied twice, so the **last** record wins,
/// where a `build` over the same duplicated input keeps the *first*
/// (`index_order` dedups) — the update semantic is the right one for an
/// "absorb what changed" API, and the one caller that feeds a scan
/// (`Scan::work`) is deduped before anything is staged. QA pinned the
/// divergence
/// (`absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records`).
///
/// One merge, because a merge is a pass over **every** record the index
/// holds: a scan that merged after each of its files would be quadratic in
/// the size of the workspace, which is measured rather than argued in
/// `docs/features/scan-interleave/README.md`. A caller feeding a scan
/// therefore batches — it stages records as it takes them and folds a
/// batch in only when something is about to read the index.
///
/// `gone` is dropped first, so a path in both lists ends up held: a file
/// that moved out of one scan's scope and back into the next's is one
/// file, not a removal that happens to run second.
pub fn absorb(&mut self, records: Vec<FileFacts>, gone: &[PathBuf]) {
for path in gone {
if let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) {
self.files.remove(at);
self.facts.remove(at);
}
}
for facts in records {
match self.facts.binary_search_by(|held| held.path.cmp(&facts.path)) {
Ok(at) => self.facts[at] = facts,
Err(at) => {
self.files.insert(at, facts.path.clone());
self.facts.insert(at, facts);
}
}
}
self.merge(None);
}
/// Drop one file from the index, reporting whether it was there.
///
/// Same contract as [`WorkspaceIndex::update_file`]: what is left is the
@@ -441,13 +525,15 @@ impl WorkspaceIndex {
}
for symbol in self.workspace_symbols("") {
out.push_str(&format!(
"sym {} in {:?} {:?} {}:{}..{}\n",
"sym {} in {:?} {:?} {}:{}..{} line={} detail={:?}\n",
symbol.name,
symbol.container,
symbol.def.kind,
symbol.def.file.0,
symbol.def.name_span.start,
symbol.def.name_span.end
symbol.def.name_span.end,
symbol.def.lines.name,
symbol.def.lines.detail
));
}
for (definition, sites) in &self.reference_sites {
@@ -661,20 +747,28 @@ pub(crate) struct Decl {
pub(crate) name_span: TextRange,
pub(crate) kind: SymbolKind,
pub(crate) detail_span: Option<TextRange>,
pub(crate) lines: DeclLines,
}
impl Decl {
fn of(symbol: &Symbol) -> Decl {
fn of(symbol: &Symbol, lines: &LineIndex) -> Decl {
Decl {
name: symbol.name.clone(),
name_span: symbol.name_span,
kind: symbol.kind,
detail_span: symbol.detail_span,
lines: DeclLines::of(lines, symbol.name_span, symbol.detail_span),
}
}
fn def(&self, file: FileId) -> Def {
Def { file, name_span: self.name_span, kind: self.kind, detail_span: self.detail_span }
Def {
file,
name_span: self.name_span,
kind: self.kind,
detail_span: self.detail_span,
lines: self.lines,
}
}
}
@@ -757,15 +851,21 @@ impl FileFacts {
/// server holding an open buffer's finished analysis) gets the record the
/// parse would have produced without paying for the parse a second time.
/// The two paths are the same code and cannot drift; what the caller
/// promises is only that `tree`, `defines` and `sem` are the analysis of
/// promises is only that `tree`, `defines`, `sem` and `lines` all describe
/// the text `path` currently holds.
///
/// `lines` is asked for rather than built here because a caller with a
/// finished analysis in hand — a server holding an open buffer — already
/// has one, and because a record now carries each declaration's line
/// ([`DeclLines`]).
pub fn from_analysis(
path: PathBuf,
tree: &SourceFile,
defines: &DefineTable,
sem: &Semantics,
lines: &LineIndex,
) -> FileFacts {
facts_from_analysis(path, tree, defines.clone(), sem)
facts_from_analysis(path, tree, defines.clone(), sem, lines)
}
/// The file these facts were read from.
@@ -778,7 +878,11 @@ impl FileFacts {
fn facts_of(path: PathBuf, src: &str) -> FileFacts {
let (tree, defines) = parse_and_collect(src);
let sem = analyze(&tree, src);
facts_from_analysis(path, &tree, defines, &sem)
// 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, &lines)
}
/// Read off what one file contributes, from its finished analysis.
@@ -787,6 +891,7 @@ fn facts_from_analysis(
tree: &SourceFile,
defines: DefineTable,
sem: &Semantics,
lines: &LineIndex,
) -> FileFacts {
let mut facts = FileFacts {
path,
@@ -807,8 +912,8 @@ fn facts_from_analysis(
if !is_unit(unit.kind) || unit.name_span.is_empty() {
continue;
}
facts.units.push(Decl::of(unit));
collect_members(sem, unit, &mut facts.members);
facts.units.push(Decl::of(unit, lines));
collect_members(sem, unit, lines, &mut facts.members);
}
let exported: HashSet<(u32, u32)> = facts
.units
@@ -889,7 +994,12 @@ fn inheritance_of(tree: &SourceFile) -> Vec<(String, DeclSite)> {
}
/// Read off the names another file may reach *into* this unit for.
fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>) {
fn collect_members(
sem: &Semantics,
unit: &Symbol,
lines: &LineIndex,
out: &mut Vec<(String, Decl)>,
) {
let Some(scope) = unit.child_scope.and_then(|c| sem.scope(c)) else {
return;
};
@@ -900,13 +1010,13 @@ fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>
if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() {
continue;
}
out.push((unit.name.clone(), Decl::of(member)));
out.push((unit.name.clone(), Decl::of(member, lines)));
// A class nested in a package (the dominant UVM shape) is not a unit,
// but an external `cls::x` candidate looks its members up under the
// *class's* name — register them there too. The scope tree is acyclic,
// so this recursion terminates.
if member.kind == SymbolKind::Class {
collect_members(sem, member, out);
collect_members(sem, member, lines, out);
}
}
}
@@ -920,10 +1030,13 @@ fn collect_members(sem: &Semantics, unit: &Symbol, out: &mut Vec<(String, Decl)>
/// the first file is parsed. Getting that ordering from here rather than
/// re-deriving it is what keeps a watched build and a plain
/// [`WorkspaceIndex::build`] the same index in the same order.
pub fn index_order<'a>(
files: impl IntoIterator<Item = (PathBuf, &'a str)>,
) -> Vec<(PathBuf, &'a str)> {
let mut sources: Vec<(PathBuf, &str)> = files.into_iter().collect();
///
/// Generic in what rides beside the path — a borrowed `&str` for a caller that
/// holds the texts, an owned `String` for one that is handing them over — so a
/// scan that owns its work list gets the same ordering from the same function
/// rather than sorting for itself.
pub fn index_order<T>(files: impl IntoIterator<Item = (PathBuf, T)>) -> Vec<(PathBuf, T)> {
let mut sources: Vec<(PathBuf, T)> = files.into_iter().collect();
sources.sort_by(|a, b| a.0.cmp(&b.0));
// A path handed over twice is one file; the first copy wins.
sources.dedup_by(|a, b| a.0 == b.0);
+277 -9
View File
@@ -1103,6 +1103,122 @@ fn removing_a_file_gives_the_index_a_whole_build_would_have() {
assert!(!ws.remove_file(Path::new("a.sv")), "and removing it again says so");
}
#[test]
fn absorbing_a_batch_gives_the_index_a_whole_build_would_have() {
// The batch form the interleaved scan feeds
// (`docs/features/scan-interleave/README.md`), against the same witness
// every other incremental path is held to. Every shape at once: a file
// replaced, two files added — one of which sorts *first*, so every id
// moves — and one dropped.
let held = [
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
("gone.sv", "module gone;\nendmodule\n"),
];
let mut ws = index(&held);
assert_eq!(ws.files().len(), 3, "premise");
let batch = [
("a.sv", "module sub;\nendmodule\n"),
("m.sv", "module m;\n sub u1 ();\n sub u2 ();\nendmodule\n"),
("zz.sv", "class leaf extends base;\nendclass\n"),
];
ws.absorb(
batch.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(),
&[PathBuf::from("gone.sv")],
);
let mut expected: Vec<(&str, &str)> = vec![("z.sv", held[1].1)];
expected.extend(batch);
assert_eq!(
ws.fingerprint(),
index(&expected).fingerprint(),
"a batch folded in is the index a whole build over what is left would have"
);
assert_eq!(ws.files()[0], PathBuf::from("a.sv"), "the added file took FileId(0)");
assert!(ws.units("gone").is_empty(), "and the dropped one is gone");
assert_eq!(ws.instantiations_of("sub").len(), 2, "the replaced file's new edges are in");
assert_eq!(ws.subclasses_of("base").len(), 1);
}
#[test]
fn absorbing_one_batch_and_absorbing_it_in_pieces_are_the_same_index() {
// What makes a *publish* free of consequence: the scan folds records in
// whenever it happens to be asked a question, so how the same records are
// grouped into batches must not reach the result.
let records = |files: &[(&str, &str)]| -> Vec<FileFacts> {
files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect()
};
let files = [
("a.sv", "module sub;\nendmodule\n"),
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
("dup.sv", "module m;\nendmodule\n"),
];
let mut whole = WorkspaceIndex::default();
whole.absorb(records(&files), &[]);
let mut piecemeal = WorkspaceIndex::default();
for one in &files {
piecemeal.absorb(records(std::slice::from_ref(one)), &[]);
}
assert_eq!(whole.fingerprint(), piecemeal.fingerprint());
assert_eq!(whole.fingerprint(), index(&files).fingerprint(), "and both are a whole build");
assert_eq!(piecemeal.units("m").len(), 2, "the duplicate name is still disambiguated");
}
#[test]
fn absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records() {
// QA attack (`docs/features/scan-interleave/README.md`, absorb attacks):
// a duplicate path inside one batch. Not constructible through the scan
// that actually feeds `absorb` — `Scan::work` is built from `index_order`,
// which already dedupes by path — but `absorb` is a public entry point on
// `WorkspaceIndex`, and its doc comment claims "what comes out is the
// index a full build over the records it now holds would have produced."
// `WorkspaceIndex::build` goes through `index_order`, which keeps the
// *first* of a duplicate path (`Vec::dedup_by`'s contract). `absorb`'s own
// loop walks `records` left to right and overwrites on a hit, keeping the
// *last*. So handed the exact same two records for one path, the two
// entry points disagree — the claimed equivalence does not hold for a
// batch with a duplicate path. Filed as a finding, not fixed here: which
// one should win is a design call, not a QA fix.
let files = [
("a.sv", "module first_shape;\nendmodule\n"),
("a.sv", "package second_shape;\nendpackage\n"),
];
let built = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)));
let mut absorbed = WorkspaceIndex::default();
absorbed.absorb(files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(), &[]);
assert_eq!(absorbed.files().len(), 1, "one file survives either way");
assert_ne!(
built.fingerprint(),
absorbed.fingerprint(),
"build (first-wins) and absorb (last-wins) disagree on a duplicate path in one batch"
);
// Naming what absorb actually did, so a fix that changes this is a
// deliberate, visible diff rather than a silent behavior change.
assert_eq!(
absorbed.fingerprint(),
index(&[("a.sv", files[1].1)]).fingerprint(),
"absorb kept the second (last) record for the duplicate path"
);
}
#[test]
fn absorbing_nothing_changes_nothing() {
// A publish with nothing staged and a finish with nothing left are both
// this call, and neither may disturb an index that is already right.
let files = [("a.sv", "module a;\nendmodule\n")];
let mut ws = index(&files);
let before = ws.fingerprint();
ws.absorb(Vec::new(), &[]);
assert_eq!(ws.fingerprint(), before);
ws.absorb(Vec::new(), &[PathBuf::from("never_held.sv")]);
assert_eq!(ws.fingerprint(), before, "dropping a file the index never held is harmless");
}
#[test]
fn removing_a_file_moves_the_disambiguation_winner() {
// The sharpest thing a removal can do to a *derived* answer: the file that
@@ -1554,6 +1670,149 @@ fn a_records_every_field_survives_the_round_trip() {
assert_eq!(back.encode(), Some(line), "and re-encodes byte for byte");
}
/// Every indexed declaration carries the line it is written on, so a caller
/// printing `file:line` never has to read the file
/// (`docs/features/hover-line-index/README.md`). The awkward offsets are the
/// point: line 1 has no newline before it, the last line has none after it,
/// and both are where an off-by-one lives.
#[test]
fn every_declared_names_line_is_recorded_when_the_file_is_indexed() {
// No trailing newline, so `last_t` really is on the file's last line.
let src = "module first;\nendmodule\n\n// a comment\npackage p;\n localparam W = 8;\n\
endpackage\ntypedef int last_t;";
let index = index(&[("/w/m.sv", src)]);
let line_of = |name: &str| index.units(name).first().expect(name).lines.name;
assert_eq!(line_of("first"), 1, "a declaration on line 1");
assert_eq!(line_of("p"), 5);
assert_eq!(line_of("last_t"), 8, "the last line, with no newline after it");
assert_eq!(index.member("p", "W").first().expect("W").lines.name, 6, "members too");
// The line really is the line the text says it is: every recorded line's
// range, sliced out of the source, contains the name it was recorded for.
for (name, line) in [("first", 1), ("p", 5), ("last_t", 8)] {
let text = src.lines().nth(line as usize - 1).expect("that many lines");
assert!(text.contains(name), "line {line} is {text:?}, which does not declare {name}");
}
}
/// A `\r\n` file and multi-byte text before a declaration do not shift its
/// line: lines are counted in newlines, not in bytes or in characters.
#[test]
fn crlf_and_multibyte_text_do_not_shift_a_declarations_line() {
let crlf = "// one\r\n// two\r\nmodule m;\r\nendmodule\r\n";
assert_eq!(index(&[("/w/c.sv", crlf)]).units("m").first().expect("m").lines.name, 3);
// Three-byte characters and a four-byte emoji ahead of the declaration:
// the byte offset of `m` is far past 3, its line is not.
let wide = "// héllo ✓ 🎉\n// ünïcödé\nmodule m;\nendmodule\n";
assert!(wide.find("module m").expect("a module") > 20, "premise: the bytes are wide");
assert_eq!(index(&[("/w/w.sv", wide)]).units("m").first().expect("m").lines.name, 3);
}
/// A non-ANSI port is named in the header and finished in the body, and the
/// carrier holds a line for each — the extension the shape was chosen for:
/// richer per-declaration position data is another field on `DeclLines`, not
/// another table.
#[test]
fn a_split_ports_two_lines_ride_the_same_carrier() {
let src = "module m (\n clk\n);\n input wire clk;\nendmodule\n";
let split = index(&[("/w/s.sv", src)]);
let def = split.member("m", "clk").first().expect("the port");
assert!(def.detail_span.is_some(), "premise: this port is split");
assert_eq!(def.lines.name, 2, "the header names it on line 2");
assert_eq!(def.lines.detail, Some(4), "and the body finishes it on line 4");
// An ANSI port is complete where it is named, and says so in both fields.
let ansi = index(&[("/w/a.sv", "module m (\n input wire clk\n);\nendmodule\n")]);
let def = ansi.member("m", "clk").first().expect("the port");
assert_eq!(def.detail_span, None);
assert_eq!((def.lines.name, def.lines.detail), (2, None));
}
/// The lines survive the record format, which is what makes them free on a
/// cached scan rather than only on a parsed one.
#[test]
fn a_declarations_lines_survive_the_record_round_trip() {
let src = "module m (\n clk\n);\n input wire clk;\nendmodule\n";
let facts = FileFacts::of(PathBuf::from("/w/s.sv"), src);
let line = facts.encode().expect("encodes");
let back = FileFacts::decode(&line).expect("decodes");
assert_eq!(back, facts, "every field, lines included");
let mut builder = vlog_semantic::IndexBuilder::new();
builder.add_facts(back);
let restored = builder.finish();
let def = restored.member("m", "clk").first().expect("the port");
assert_eq!((def.lines.name, def.lines.detail), (2, Some(4)));
}
/// QA (2026-08-28): the single-decl fixture `index_cache`'s own format-bump
/// test strips is not the only shape a genuine format-3 record could take —
/// a file declaring *two* units is the shape where a field-shift attack would
/// actually have somewhere plausible to land: if stripping the first decl's
/// two line fields shifted every read two fields early, the fields it would
/// then misread as `(name_line, detail_line)` are the *second* decl's own
/// `name` and `kind` strings. Both are always non-numeric — a Verilog
/// identifier cannot start with a digit and `kind_name` writes only letters —
/// so `Reader::num` fails on them and `decode` returns `None` rather than
/// quietly building a `Decl` out of someone else's fields. Proved directly
/// here, generalizing `index_cache`'s stripper to more than one declaration,
/// rather than only argued.
#[test]
fn a_format_3_record_with_two_declarations_is_rejected_not_misread() {
let src = "module a; endmodule\nmodule b; endmodule\n";
let facts = FileFacts::of(PathBuf::from("/w/two.sv"), src);
let encoded = facts.encode().expect("encodes");
let format_3 = strip_every_decls_line_fields(&encoded, 2, 0);
assert_ne!(format_3, encoded, "premise: fields were actually removed");
assert!(
FileFacts::decode(&format_3).is_none(),
"a two-unit format-3 record decoded as a format-4 one: {format_3}"
);
// The mixed case: one unit with a member that has a real detail span (a
// split port), so the decls being stripped are not even the same width
// of *content* — only of field count, which is what the format promises.
let split = "module m (\n clk\n);\n input wire clk;\nendmodule\n\
module other; endmodule\n";
let facts = FileFacts::of(PathBuf::from("/w/mixed.sv"), split);
let encoded = facts.encode().expect("encodes");
let format_3 = strip_every_decls_line_fields(&encoded, 2, 1);
assert_ne!(format_3, encoded, "premise: fields were actually removed");
assert!(
FileFacts::decode(&format_3).is_none(),
"a mixed unit+member format-3 record decoded as a format-4 one: {format_3}"
);
}
/// The generalization of `index_cache`'s `strip_the_line_fields`: remove the
/// two trailing (`name_line`, `detail_line`) fields from every one of
/// `units` unit-decls and `members` member-decls in an encoded record —
/// i.e. what `FACTS_FORMAT` 3 wrote for the same file. Assumes `D0` (no
/// `` `define``s), which every fixture here satisfies, so the `U` tag's
/// field index is fixed and decl positions can be computed directly rather
/// than parsed.
fn strip_every_decls_line_fields(encoded: &str, units: usize, members: usize) -> String {
let mut fields: Vec<&str> = encoded.split('\t').collect();
let units_at = fields.iter().position(|f| *f == "U").expect("a U tag");
assert_eq!(fields[units_at + 1], units.to_string(), "premise: unit count");
// decl = name, kind, name_span×2, detail_span×2, line×2 — 8 fields.
let unit_decls_end = units_at + 2 + units * 8;
let members_at = unit_decls_end;
assert_eq!(fields[members_at], "M", "premise: members tag follows the units");
assert_eq!(fields[members_at + 1], members.to_string(), "premise: member count");
// A member entry is the owning unit's name (one text field) plus a decl.
let member_decl_starts: Vec<usize> = (0..members).map(|m| members_at + 2 + m * 9 + 1).collect();
let unit_decl_starts: Vec<usize> = (0..units).map(|u| units_at + 2 + u * 8).collect();
// Highest index first, so removing one strip does not move the others.
let mut starts: Vec<usize> = unit_decl_starts.into_iter().chain(member_decl_starts).collect();
starts.sort_unstable_by(|a, b| b.cmp(a));
for start in starts {
fields.drain(start + 6..start + 8);
}
fields.join("\t")
}
#[test]
fn an_index_built_from_records_is_the_index_the_parse_would_have_given() {
// The claim the cache rests on: facts through the record format and back
@@ -1668,7 +1927,9 @@ fn a_degenerate_file_still_makes_a_record() {
/// `lucisv_server::state::Document::new` builds it — one lex, the tree from a
/// clone of that token stream, the define table off the same tokens, and the
/// same all-or-nothing lex-failure branch.
fn as_a_server_analyzes(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable, Semantics) {
fn as_a_server_analyzes(
src: &str,
) -> (vlog_parser::ast::SourceFile, DefineTable, Semantics, vlog_parser::LineIndex) {
let (tokens, tree) = match tokenize(src) {
Ok(tokens) => {
let (tree, _) = parse_tolerant(tokens.clone(), src);
@@ -1678,7 +1939,7 @@ fn as_a_server_analyzes(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable
};
let defines = collect_defines(&tokens);
let sem = analyze(&tree, src);
(tree, defines, sem)
(tree, defines, sem, vlog_parser::LineIndex::new(src))
}
/// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two.
@@ -1720,9 +1981,9 @@ fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
];
for src in crafted {
let path = PathBuf::from("/w/x.sv");
let (tree, defines, sem) = as_a_server_analyzes(src);
let (tree, defines, sem, lines) = as_a_server_analyzes(src);
let from_text = FileFacts::of(path.clone(), src);
let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem);
let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem, &lines);
assert_eq!(from_analysis, from_text, "the records differ for {src:?}");
assert_eq!(
from_analysis.encode(),
@@ -1750,9 +2011,9 @@ fn the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus() {
let Ok(src) = std::fs::read_to_string(path) else {
continue;
};
let (tree, defines, sem) = as_a_server_analyzes(&src);
let (tree, defines, sem, lines) = as_a_server_analyzes(&src);
let from_text = FileFacts::of(path.clone(), &src);
let from_analysis = FileFacts::from_analysis(path.clone(), &tree, &defines, &sem);
let from_analysis = FileFacts::from_analysis(path.clone(), &tree, &defines, &sem, &lines);
assert_eq!(
from_analysis.encode(),
from_text.encode(),
@@ -1799,8 +2060,14 @@ fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from
let mut builder = vlog_semantic::IndexBuilder::new();
// Deliberately not path order: the reuse must not smuggle an ordering in.
for (path, src) in files.iter().rev() {
let (tree, defines, sem) = as_a_server_analyzes(src);
builder.add_facts(FileFacts::from_analysis(PathBuf::from(*path), &tree, &defines, &sem));
let (tree, defines, sem, lines) = as_a_server_analyzes(src);
builder.add_facts(FileFacts::from_analysis(
PathBuf::from(*path),
&tree,
&defines,
&sem,
&lines,
));
}
let from_analyses = builder.finish();
assert_eq!(from_analyses.fingerprint(), from_text.fingerprint());
@@ -1809,12 +2076,13 @@ fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from
// index `update_file` would have left.
let mut updated = from_text.clone();
let changed = "package p;\n localparam W = 16;\n class c; int y; endclass\nendpackage\n";
let (tree, defines, sem) = as_a_server_analyzes(changed);
let (tree, defines, sem, lines) = as_a_server_analyzes(changed);
updated.update_facts(FileFacts::from_analysis(
PathBuf::from("/w/pkg.sv"),
&tree,
&defines,
&sem,
&lines,
));
let mut parsed = from_text.clone();
parsed.update_file(PathBuf::from("/w/pkg.sv"), changed);
@@ -64,6 +64,10 @@ entirely whenever it could be the wrong line.
bumps `FACTS_FORMAT` 2 → 3, so a store written before *that* round is
discarded. This round's own promise held while it was this round's to
make; the index is text-free either way (a span is not text).
**Superseded again 2026-08-28 by `docs/features/hover-line-index/README.md`**,
which adds `Def::lines` (each declaration's line number) and bumps
`FACTS_FORMAT` 3 → 4. Same reading: a line number is not text either, and
it is what makes this feature's heading free.
- The heading line `**label** — declared in `file:line`` is unchanged, so a
client (or a test) reading only that half sees exactly what it saw before.
@@ -131,6 +135,10 @@ The character cap counts `char`s and cuts on a boundary.
tie-break pinned by test.
- [x] **2026-08-28**: a CRLF file's snippet no longer carries an interior
`\r` into the fence; QA finding 2 closed.
- [x] **2026-08-28** (`docs/features/hover-line-index/README.md`): the disk
path's heading costs no read at all (`Def::lines`) and its snippet's
read is shared across hovers, so the second hover into a closed file is
free. `disk_view` is gone, subsumed by `Workspace::file_view`.
## Work log
@@ -230,6 +238,32 @@ with less work. Numbers in `docs/perf/README.md`.
- Cost: four bytes per symbol. Measured saving on the lookup alone:
8.41 µs → 133 ns over a 5 001-symbol file (`docs/perf/README.md`).
### 2026-08-28 — dev (the heading stops reading the file at all)
Round `hover-line-index` — full argument, measurements and tests in
`docs/features/hover-line-index/README.md`. What changed *here*:
- **The `External` arm's disk branch no longer reads anything for the
heading.** `Def` now carries `lines: DeclLines`, recorded when the file was
indexed, so `**port** — declared in `sub.sv:2`` is a field lookup. The live
branch is untouched and still asks the open buffer's own line index, because
that buffer may hold unsaved edits the index has not seen — the same reason
`declaration_snippet` matches a `Def` to a live symbol logically.
- **`disk_view` was deleted.** Its job — one read per file per hover — is now
`Workspace::file_view`'s, which does it once per file per *generation of that
file*, so the next hover into the same file reads nothing. The four points
that drop a held view are listed in that round's Handshakes.
- **`spells_exactly` and both caps are untouched**, and a stale held view can
only ever make a snippet vanish. Every existing test in this file passed
unmodified.
- **One corner moved deliberately**: a closed file that cannot be *read* now
still gets its line in the heading (`sub.sv:2` rather than a bare `sub.sv`),
because the line no longer depends on the read. Pinned by
`a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read`.
- Measured: a hover into a 12 MB closed file, 6.2 ms → **0.95 µs** on the
second hover; the 31.7 MB probe above, 17.0 ms → **4.4 µs** on the second.
The first touch is unchanged, because the snippet genuinely wants the text.
### 2026-08-28 — dev (CRLF, closing QA finding 2)
- Finding 2 below — a CRLF file's multi-line snippet keeping an interior
+543
View File
@@ -0,0 +1,543 @@
# hover-line-index
## Goal
The owner's report (2026-08-28): hovering a module instantiation is slow, and
hovering one of its ports — to see the port's own declaration — is slow on the
**first** try. Both land on the same code: a hover whose target is declared in
a *closed* file read that whole file and built a whole `LineIndex` over it, for
two things at once — the heading's `file:line`, and the fenced snippet of the
declaration. On a netlist-adjacent file that read is milliseconds, and nothing
was kept, so the *next* hover into the same file paid it again. The owner's
design, which this round implements: put each declared name's **line number**
into the index itself, where it costs a `u32` per declaration and is computed
once when the file is scanned. The heading then costs no file access at all,
and only the snippet still wants text — served from a small bounded cache of
closed files' text in `Workspace`, so the first touch pays one read and no
touch after it pays anything.
The shape of what that buys, measured below: a hover into a 12 MB closed file
goes **6.2 ms → 0.9 µs on the second hover** and stays 6.2 ms on the first;
the steady-state cross-file hover on a 10 000-line file goes **157 µs →
13 µs**. The round also *measured the other suspect* and did not fix it — see
Handshakes.
## Assumptions
- **A line is a fact about the same snapshot the span is.** `Def::name_span`
and `Def::lines.name` are read off one text in one pass, so a heading and a
snippet can never name different generations of a file. Where the file has
changed on disk with nothing telling the server, both are stale together,
which is strictly better than the previous shape — a stale *offset* looked
up in *fresh* text, whose line was arbitrary.
- **Lines are 1-based, and are exactly what `LineIndex::line_col` reports.**
That is what `locate::line_number` returned before, so the same headings come
out.
- **`FileFacts::from_analysis`'s caller has a line index already.** It is a
server holding an open buffer's finished `Document`, which carries one. So
the extra parameter costs the caller nothing, and `FileFacts::of` builds its
own — one pass over the source's newlines, about 1 % of the parse it sits
beside (`docs/perf/README.md`: `LineIndex::new` 115 µs against
`parse_tolerant` 14.3 ms at 10 000 lines).
- **The view cache is a cache and never a correctness input.** Every entry can
be dropped at any moment with no change to any answer; a *stale* entry can
only ever make a snippet disappear, never make it wrong, because
`hover::spells_exactly` still checks the text at the span against the hovered
name before anything is shown. That guard is unchanged and is still the last
line of defence.
- **Only closed files are cached.** `Workspace::file_view` returns `None` for a
path an open buffer speaks for: that buffer's `Document` already holds its
text and line index, and a second copy here would be a second opinion.
- **The index is still text-free.** A line number is not text, exactly as a
span is not text (`docs/features/workspace-index/README.md`'s promise, and
the same reading `port-detail-spans` took for `detail_span`).
## Handshakes
### `vlog_semantic` — `DeclLines`, and the carrier's extension story
```rust
/// Where a declaration sits in its file, counted in lines.
pub struct DeclLines {
pub name: u32, // 1-based line of the declared name
pub detail: Option<u32>, // 1-based line the detail span starts on
}
pub struct Def {
pub file: FileId,
pub name_span: TextRange,
pub kind: SymbolKind,
pub detail_span: Option<TextRange>,
pub lines: DeclLines, // new
}
// One added parameter, because a record now carries lines:
impl FileFacts {
pub fn from_analysis(path, tree, defines, sem, lines: &LineIndex) -> FileFacts;
}
pub const FACTS_FORMAT: u32 = 4; // was 3
```
**The carrier is one value per declaration, and it extends by gaining a
field.** That is the owner's explicit ask ("keep the implementation flexible so
we might even cache the port location") answered structurally rather than
promised:
- **Ports already ride it.** A module's ports and parameters are indexed as
*members*, and a member is a `Decl` exactly as a unit is — so
`index.member("sub", "addr").lines.name` is that port's line, recorded in the
same pass, with no extra table, no extra pass and no extra decision about
"small projects". The owner's optional second step was already paid for by
the first.
- **A split port's two lines ride it too.** A non-ANSI port is named in the
header and finished in the body (`detail_span`,
`docs/features/port-detail-spans/README.md`), and `DeclLines::detail` is that
body's line — the second position datum, already present, in the same value.
- **A third one is a field.** A column, a rendered preview, an end line: add it
to `DeclLines`, write it in `Writer::decl`, read it in `Reader::decl`, bump
`FACTS_FORMAT`. Nothing else moves, because nothing else knows how many
fields a `DeclLines` has. A *parallel table* keyed by declaration was the
alternative and was rejected: it would have to be kept in step with `Decl`
through every merge, every incremental update and every record round-trip,
and there is no second consumer to justify the indirection
(`CLAUDE.md`, "Simplicity first").
### `vlog_semantic` — `FACTS_FORMAT` 3 → 4, justified
A record's per-declaration group grew two fields. The rule written at the
constant is that **any** change to what a record holds bumps the format, and
the reason it is a whole-store discard rather than a migration is
`docs/features/index-persistence/README.md`'s: a reader that guessed at an
older layout would read last month's field order as this month's. Concretely,
a format-3 record read as a format-4 one would shift every field after the
first declaration by two — which is why the format field in the store's header
catches it first, and why `decode` rejects it even if something served it past
the header (both pinned, see Tests). The cost is one re-parse of the workspace
on the first scan after upgrading; the corpus measurement below says that is
about 175 ms.
### `vlog_semantic` — fingerprint
`WorkspaceIndex::fingerprint`'s `sym` line now carries `line=` and `detail=`.
That is what makes the house witness — incremental index == fresh build —
cover the new field rather than ignore it; every existing equivalence test
(`update_file`, `update_facts`, `add_facts` from records, the corpus sweep)
now compares lines as well as spans, and all of them stayed green unmodified.
### `lucisv_server::state` — the closed-file view cache
```rust
pub struct FileView { pub path: PathBuf, pub text: String, pub lines: LineIndex }
impl Workspace {
pub fn file_view(&self, path: &Path) -> Option<Rc<FileView>>;
}
```
Bounded by **four entries** and **8 MiB of text**, newest first, oldest
evicted. Two bounds because they answer two questions: how many files one
answer can name (a card names one or two; a references list walks a handful
before moving on), and how much memory a netlist-shaped file may cost. The
newest entry is kept whatever it weighs — one file can exceed the whole byte
budget on its own, and a cache that refused to hold it would be useless for
exactly the file it exists for — so a huge file simply evicts everything else.
**Every invalidation point, in full.** A view is dropped when:
| event | what is dropped | why |
|---|---|---|
| `set_document(uri, text)` — `didOpen`, `didChange`, a text-carrying `didSave` | that path's view | the buffer becomes the authority, and the held disk copy may predate the edits it carries |
| `close_document(uri)` | that path's view | disk is the authority again, and the view predates every save that buffer made |
| `update_one(path)` | that path's view | re-indexing one file *is* the claim its bytes moved |
| `rebuild_index_with(..)` | **all** views | a rescan says nothing about which file moved |
Those four are every path in the server that can change what a file holds:
`server.rs` reaches the first two directly from the sync notifications, and the
last two through `reindex_one` / `reindex`, which is where a save, a watched
file change, a client file operation and a settings change all land.
What survives all four is a file changed on disk with nothing telling this
server — and there the *index* is stale by the same event, which is precisely
what `spells_exactly` exists for.
### `lucisv_server::locate` — the sweep
`locate::line_number` and `locate::location` were the only two functions that
read a whole file to answer a position question, and `line_number`'s only
callers were `hover.rs`'s two. Both now take an open buffer's own line index
when there is one and the shared view otherwise; neither reads a file directly
any more. `location`'s open-buffer arm also stops cloning the whole buffer text
(`text_of` returns a `String`) on the way to a range. Mechanical, no behaviour
change: `location` is what `textDocument/definition`, references, the lens and
the hierarchies build their `Location`s from, and a references list over one
file now reads that file once instead of once per site.
An indexed declaration's line no longer goes through `line_number` at all —
`Def::lines` is the answer. What is left for it is the spans the index records
no line for, which today is a `` `define``'s (the macro hover card's
`defined in file:line`). Those ride the shared view, so a second macro hover
into one file is free; giving `Define` its own line would mean a field in
`vlog_parser`'s `Define` and is filed rather than done — it buys the first
touch of one card and costs a second crate a field.
### Suspect 2 — **reported, not fixed here; DELIVERED 2026-08-28** by `docs/features/scan-interleave/README.md`
The brief named a second suspect and asked for it to be measured and filed
rather than redesigned. It is real, and on the owner's own complaint it is by
far the larger of the two:
`Server::new` runs the whole startup scan **before** `run()`'s message loop
takes its first message. `main.rs` answers `initialize` (through
`initialize_finish`, which also consumes `initialized`) and only then builds
the `Server` — so everything a client sends the instant the handshake is done
sits in the OS pipe until the scan is over. Measured over a 200-file, 1 000-
line-each workspace with a filelist (so the startup scan really indexes it):
| the first hover of a session | cold store | warm store |
|---|---:|---:|
| issued the moment `initialized` was sent | **780 ms** | **287 ms** |
| the same hover once the scan is done | 64 µs | 61 µs |
Four orders of magnitude, and this round does not touch it: fixing it means
answering requests during the scan (or scanning on another thread), which is a
change to request scheduling and to what an answer *means* while the index is
half-built. `docs/features/index-persistence`'s store already takes it from
780 ms to 287 ms; the rest is the read, the completion word table's lex and
the include scan, which that feature's README already names as uncached.
**Request to whoever owns the message loop next:** this is where "the first
hover is really slow" mostly lives, and the probe that measures it is
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it`.
**DELIVERED, 2026-08-28.** `docs/features/scan-interleave/README.md` took the
scan apart into per-file steps and drains the message queue between them, so a
startup scan long enough to be worth it answers requests while it runs. The
same probe, flipped and renamed
(`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`), now
reports **15.5 ms cold / 12.8 ms warm** where the table above says 780 / 287 —
and the scan's own total moved by under a percent. The request is closed; what
that round did *not* do (the files are still read eagerly, a rescan still makes
requests wait) is filed in its own Status/TODO with numbers.
## Measured
Machine and method are `docs/perf/README.md`'s: Apple M1 Max, macOS 27.0,
`--release`, `#[ignore]`d probes, `--test-threads=1`, means where the numbers
are small enough to need one. Every figure below was taken on 2026-08-28,
before and after, in the same session.
### Suspect 1 — the per-hover read
| what | before | after |
|---|---:|---:|
| hover on an **instantiation** into a 12 MB closed file, first touch | 6.47 ms | 6.23 ms |
| — the same hover again | 5.75 ms | **0.95 µs** |
| hover on a **port** into the same file, first touch | 5.85 ms | 5.92 ms |
| — the same hover again | 5.71 ms | **0.99 µs** |
| hover into a 31.7 MB closed file, first touch (QA's own probe) | 17.0 ms | 16.8 ms |
| — the same hover again | 17.0 ms | **4.4 µs** |
| cross-file hover, 1 000-line target, mean of 20 | 39.8 µs | **4.7 µs** |
| cross-file hover, 10 000-line target, mean of 20 | 157 µs | **12.9 µs** |
| — one read + `LineIndex` of that file, for comparison | 149 µs | 158 µs |
Read the table as two claims. **The first touch is unchanged**, and it should
be: the snippet genuinely wants that file's text, and reading it is what the
6.2 ms is. **Every touch after it is free**, which is the shape the owner's
"slow on the FIRST try" report describes — and the heading half is free even
on the first touch, which is why a card with no snippet (an unreadable file, a
guard miss) now costs nothing at all.
### The price paid for it
| | before | after |
|---|---:|---:|
| whole 860-file corpus scan, no cache | 338 ms | 343 ms |
| — cold, filling the store | 372 ms | 374 ms |
| — warm, every file from the store | 197 ms | 200 ms |
| the store, 860 files | 2 312 802 B | 2 380 790 B |
The scan times are inside their own run-to-run noise: the added work is one
`LineIndex::new` per parsed file, which the flush breakdown puts at under 1 %
of that file's parse. The store grows **68 KB over 860 files — 2.9 %**, which
is the two decimal numbers per declaration over roughly 13 000 declarations,
and is the owner's "a few KB for 20 000 modules" measured on real source.
## Status / TODO
- [x] Measure both suspects before touching anything; both recorded above.
- [x] `DeclLines` on `Decl` and on `Def`, computed in `facts_from_analysis`
from the file's own `LineIndex`.
- [x] `FileFacts::from_analysis` takes the line index; `FileFacts::of` builds
one.
- [x] Record codec: two fields per declaration, `FACTS_FORMAT` 3 → 4, with the
justification above.
- [x] `WorkspaceIndex::fingerprint` carries the lines, so incremental == fresh
covers them.
- [x] `Workspace::file_view` — bounded, LRU, four named invalidation points.
- [x] `hover.rs`: heading from `Def::lines`, snippet from the shared view; the
per-request `disk_view` memo is gone, subsumed.
- [x] `locate.rs` swept onto the buffer's index / the shared view.
- [x] Tests (11 new, listed in the work log) and two new `#[ignore]`d probes.
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
- [ ] **Not done, deliberately: `` `define``s get no indexed line.** A
`Define` is `vlog_parser`'s, and giving it a line means a field in
another crate's public type plus its own record fields, to save the
*first* macro hover into one file and nothing after it. The shared view
already covers the repeat.
- [ ] **Not done, deliberately: the other `text_of` callers are untouched.**
`rename`, `ports`, `hierarchy`, `type_hierarchy`, `completion`,
`signature`, `inlay` and `nav` read whole files because they want whole
files, not a line — the sweep was for the position-only readers. Routing
them through the view cache would mean `text_of` handing out an `Rc`
instead of a `String`, which is a different change with a different
argument.
- [x] **Reported, not fixed *here*: the first request of a session waits out
the startup scan.** Numbers and the filed request are in Handshakes;
**delivered 2026-08-28** by `docs/features/scan-interleave/README.md`
(780 ms → 15.5 ms cold, 287 ms → 12.8 ms warm).
## Work log
### 2026-08-28 — dev
**Measured first, both suspects, before a line of the fix was written.** Two
new probes were needed and are part of the round:
`perf::hovering_into_a_big_closed_file_first_touch_and_repeat` (an
instantiation and a port, into a 12 MB file, first touch and repeat separately
— the existing probes all reported means, which hide exactly the first/repeat
split the owner's report is about) and
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it` (over the wire,
against the real binary, two whole sessions so the persistent store is cold in
one and warm in the other). The second answered the brief's question about
suspect 2 with a number four orders of magnitude larger than suspect 1's, which
is worth saying plainly even though this round could not act on it.
**The carrier: a struct, not a bare `u32`.** `DeclLines { name, detail }`
rather than `line: u32` on `Decl`, because the *second* datum already exists —
a split port's body line — and because the owner asked for room for more. The
alternative shapes were both worse: a bare `u32` would have needed a second
field the day `detail` was wanted (and `detail` was wanted on day one), and a
parallel table keyed by declaration would have to be kept in step with `Decl`
through the merge, the incremental update and the record round-trip, for no
consumer that exists. `Option<u32>` for `detail` rather than a `0` sentinel in
the *type*, even though the *record* writes `0` for `None`: the record's
sentinel is a framing decision (the stream stays flat, exactly as
`detail_span`'s `0 0` already does) and the type's is an API decision, and
those two should not be forced to be the same thing.
**`from_analysis` grew a parameter rather than growing a `&str`.** It could
have taken `src: &str` and built its own index, but its one real caller —
`Document::facts` — already holds a `LineIndex` over exactly that text, and
handing it over is both cheaper and more honest about what the function needs.
The test helper `as_a_server_analyzes` grew a fourth return value for the same
reason.
**`FACTS_FORMAT` 3 → 4, not 2 → 3 as the brief said.** The brief was written
against a tree where `port-detail-spans` had not yet been counted; the constant
was already at 3 when this round started. Same rule, next number.
**The heading now comes from the index on the disk path, and that is a small
behaviour change in one corner.** Before, a closed file that could not be read
produced a bare `` `sub.sv` `` heading with no line; now it produces
`` `sub.sv:2` ``, because the line no longer depends on the file being
readable. That is more information and not less, it is the line the index
recorded from the text it indexed, and it is pinned by
`a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read` — which
deletes the file and requires the heading to survive. Every other card is
byte-identical: the full suite passed unmodified before a single new test was
added, including the stale-span, guard, CRLF, cap and ambiguity tests.
**The live path was deliberately left alone.** An open buffer's heading still
comes from that buffer's own line index and *not* from `Def::lines`, because
the buffer may hold unsaved edits the index has not seen — the same reason
`declaration_snippet` matches a `Def` to a live symbol logically instead of
reading at the indexed span (`docs/features/hover-declarations/README.md`).
Zero I/O either way, so there is nothing to win by unifying them and a
correctness property to lose.
**`disk_view` is gone, subsumed.** Its whole job — one read per file per hover
— is now the view cache's, which does the same thing per *session* instead of
per request. The per-request memo would have been a second cache in front of
the first.
**Files touched.** `crates/vlog_semantic/src/{workspace.rs,facts.rs,lib.rs}`,
`crates/vlog_semantic/tests/workspace.rs`,
`crates/lucisv_server/src/{state.rs,locate.rs,hover.rs,index_cache.rs,perf.rs}`,
`crates/lucisv_server/tests/e2e.rs`, this README,
`docs/features/{hover-declarations,workspace-index,index-persistence}/README.md`,
`docs/perf/README.md`, `TODO.md`. No new dependency, no `unsafe`, no
`#[allow]`, no version bump, no commits.
**Tests added.**
| test | where | pins |
|---|---|---|
| `every_declared_names_line_is_recorded_when_the_file_is_indexed` | `vlog_semantic/tests/workspace.rs` | line 1, a middle line, the last line with no trailing newline, and a member's line — each checked against the source line's own text |
| `crlf_and_multibyte_text_do_not_shift_a_declarations_line` | same | `\r\n` line endings, and three- and four-byte characters ahead of the declaration |
| `a_split_ports_two_lines_ride_the_same_carrier` | same | the extension story: a non-ANSI port's header line *and* body line, and an ANSI port's `None` |
| `a_declarations_lines_survive_the_record_round_trip` | same | encode → decode → equal, and through `IndexBuilder` to a `Def` |
| `a_store_from_any_previous_facts_format_is_dropped_not_misread` | `lucisv_server/src/index_cache.rs` | **rewritten**: every format `1..FACTS_FORMAT` is discarded by the header, *and* a genuine format-3 record (today's minus the two line fields) fails `decode` even served past the header. Was pinned at the literal `2` and would have gone on testing 2 forever |
| `a_closed_files_text_is_read_once_and_then_reused` | `lucisv_server/src/state.rs` | the cache exists: the file is rewritten behind the server's back and the second view is the first |
| `a_file_an_open_buffer_speaks_for_has_no_view_of_its_own` | same | closed files only |
| `every_way_a_files_text_can_move_drops_its_view` | same | all four invalidation points, each by the same warm-change-event-check experiment |
| `the_view_cache_holds_a_handful_of_files_and_a_bounded_amount_of_text` | same | both bounds, LRU order, and that a file over the whole byte budget is still cached and evicts the rest |
| `a_closed_files_heading_line_comes_from_the_index_and_not_from_a_read` | `lucisv_server/src/hover.rs` | the round's central claim: the file is deleted and the heading still names its line, snippet correctly dropped |
| `a_second_hover_into_one_closed_file_reads_nothing` | same | the snippet's read is shared: the file is rewritten and the second card is the first |
Two `#[ignore]`d probes added (`perf::hovering_into_a_big_closed_file_first_touch_and_repeat`,
`e2e::a_hover_issued_during_the_initial_scan_waits_for_it`); one existing probe
(`hovering_into_a_large_closed_file_reads_it_once`) grew a second timing so it
reports the repeat beside the first touch.
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
--workspace` silent. `cargo test --workspace` green, 0 failed. The counts, by
binary: `lucisv_server`'s unit tests **1 210 passed / 24 ignored** (+6 passing,
+1 `#[ignore]`d probe), its `e2e` suite **56 passed / 2 ignored** (+1
`#[ignore]`d probe), `vlog_semantic`'s `workspace` suite **66 passed** (+4).
One test was renamed rather than added
(`a_store_from_the_previous_facts_format_is_dropped_not_misread` →
`a_store_from_any_previous_facts_format_is_dropped_not_misread`), so nothing
was quietly dropped.
## QA log
### 2026-08-28 — QA
Verdict: **SHIP.** No correctness bug found in the round's own code — every
finding below is a test-coverage gap, closed in this pass with permanent
regression tests. All seven charter items checked; details follow.
**1. Heading staleness — reproduced, and the documented window holds.**
Constructed the exact attack: index `sub.sv` from its original text, then
rewrite it on disk (`addr` moved from line 2 to line 6, and the byte offset
the index still holds for it now lands inside a comment) with no `didSave`, no
watcher event and no `update_one`/`rebuild_index` call — before any hover has
ever read the file, so the view cache is empty and the read the snippet does
is genuinely against the *new* bytes. Result: the heading still shows
`sub.sv:2` (the index's last-scanned line, not the file's true current one),
and the snippet is dropped by `spells_exactly` rather than showing whatever
now sits at that byte range — no wrong line and no wrong snippet, matching the
README's Assumptions ("both are stale together") exactly. Pinned:
`hover::tests::an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet`
(`crates/lucisv_server/src/hover.rs`). The docs (this README's Assumptions
section, and `Workspace::file_view`'s doc comment at
`crates/lucisv_server/src/state.rs:1043`) already state this honestly — no
doc fix needed.
**2. `DeclLines` correctness — dev's tests already cover the awkward
offsets** (line 1, the last line with no trailing newline, CRLF, multi-byte
text ahead of the declaration, a split port's two lines, an ANSI port's
`None`) and check each recorded line against the source line's own text, not
just against a hand-computed expectation. No drift found; ran unmodified.
**3. View-cache attacks — three untested-but-correct paths, now covered.**
The cache's own logic (`trim_views`, `cached_view`,
`crates/lucisv_server/src/state.rs:349` and `:1061`) was already right by
inspection and by trace, but three of the charter's named attacks had no
regression test, meaning a future refactor could break any of them silently:
- *Recency, not insertion order.* `cached_view`'s `rotate_right` had no test
at all. Added
`state::tests::re_hovering_the_oldest_cached_file_saves_it_from_eviction`:
fills the cache, re-touches the oldest entry, adds a fifth file, and
requires the just-touched file to survive while the untouched one is what
falls off instead.
- *`update_one` selectivity.* Every existing invalidation test warms one
file's view at a time, so a hypothetical `update_one` that widened to
`views.clear()` would still pass all of them. Added
`state::tests::updating_one_file_leaves_another_files_cached_view_alone`.
- *A second oversized file.* The existing bound test caches exactly one
file over the byte budget; it never tries a second one. Added
`state::tests::a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it`,
confirming the cache stays at one entry (the newest) rather than
accumulating unbounded huge files.
All three pass against the round's code unmodified — genuine coverage gaps,
not bugs.
**4. Format bump — the single-decl test's premise checked, and generalized.**
`index_cache`'s `a_store_from_any_previous_facts_format_is_dropped_not_misread`
genuinely constructs a format-3 record (verified by hand: `strip_the_line_
fields` removes exactly the two trailing fields of the one declaration `M`
has, and the record that results is what format 3 actually wrote — not merely
a v3 header over v4 bytes). That fixture has only one declaration, so it could
not have caught a field-shift that landed on a *second* declaration's fields
rather than on a tag literal. Added
`vlog_semantic::tests::workspace::a_format_3_record_with_two_declarations_is_
rejected_not_misread`, generalizing the stripper to N declarations (both units
and members) and covering a two-unit file and a mixed unit+split-port-member
file. Both decode to `None`, confirming the structural reason this is safe in
general: a field-shift by exactly one declaration's two line-fields always
lands either on a tag literal (`"M"`, `"I"`, …) or on the next declaration's
`name`/`kind` string fields, and a Verilog identifier can never parse as
`u32`, so `Reader::num` fails and `decode` returns `None` rather than building
a `Decl` out of someone else's fields. No misread constructed; the
"guilty until proven innocent" bar is met.
**5. Equivalence — confirmed, not just claimed.** `cargo test --workspace`
green with 0 failures both before and after this pass's additions (dev's
counts: `lucisv_server` 1210 passed/24 ignored, `vlog_semantic` `workspace` 66
passed — both unmodified by this pass except for the new tests below). Read
the `hover.rs` and `locate.rs` diffs directly: the live-buffer branch is
untouched, `location()`'s open-buffer arm is a straight substitution
(`doc.positions()` for the old `Positions::new(&text, &index)` built from a
clone of the same text), and the disk branch is the only place behavior can
differ — which is exactly the one documented corner (an unreadable closed
file now shows its indexed line). No other behavior change found.
**6. Numbers reproduced**, `--release`, this machine, this session:
- `perf::hovering_into_a_big_closed_file_first_touch_and_repeat`: first
touch 5.75 ms (instantiation) / 5.65 ms (port), repeat 1.35 µs / 1.89 µs —
same order as the README's 6.23 ms / 0.95 µs and 5.92 ms / 0.99 µs; run-
to-run noise, not drift.
- `state::tests::qa_perf_cold_warm_and_half_warm_scans` (860-file corpus):
store size **2 380 790 bytes** — an exact match to the README's "after"
figure, confirming the +68 KB / 2.9 % growth claim against the real
corpus rather than trusting the doc's arithmetic. Scan times (325 / 350 /
186 ms) were in the same band as the README's (343 / 374 / 200 ms);
machine noise, no regression.
- `e2e::a_hover_issued_during_the_initial_scan_waits_for_it`: 748.7 ms cold
/ 274.0 ms warm for the first hover issued the moment `initialized` is
sent, vs. 26.3 µs / 40.2 µs once the scan is done — the same four-orders-
of-magnitude gap the README reports (780 / 287 ms vs. 64 / 61 µs). The
test genuinely exercises the wait (it asserts the answer resolves
correctly across files, and the two timings are taken across the real
wire protocol against the shipped binary) — the Handshake in this
README's "Suspect 2" section is accurate and not overstated.
**7. Full gates**, run after adding the tests above:
- `cargo fmt --all -- --check`: clean (after formatting the new tests —
two blocks needed `cargo fmt`'s wrapping, applied).
- `cargo clippy --all-targets --workspace`: clean, no warnings.
- `cargo test --workspace`: green. `lucisv_server` unit tests **1214
passed** (dev's 1210 + this pass's 4), `vlog_semantic` `workspace` suite
**67 passed** (dev's 66 + this pass's 1). 0 failed anywhere in the
workspace, including doctests.
- `node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`.
**Tests added this pass** (5, all permanent regressions, all green):
`hover::tests::an_unreindexed_disk_edit_leaves_a_stale_heading_and_no_wrong_snippet`,
`state::tests::re_hovering_the_oldest_cached_file_saves_it_from_eviction`,
`state::tests::updating_one_file_leaves_another_files_cached_view_alone`,
`state::tests::a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it`
(all `crates/lucisv_server/src/`), and
`vlog_semantic::tests::workspace::a_format_3_record_with_two_declarations_is_rejected_not_misread`
(`crates/vlog_semantic/tests/workspace.rs`).
## Review
**2026-08-28 — lead.** Reviewed after QA's SHIP; gates re-run
independently (fmt clean, clippy silent, 2440 workspace tests green).
This round is the owner's design implemented at the right altitude:
`DeclLines` as a field on the carrier the index already had — not a
parallel table — so ports got their lines for free through the member
entries and the extension story is "add a field, bump the format",
exactly the flexibility the owner asked for. The +68 KB store growth
on the 860-file corpus scales to the owner's 20 000-module thought
experiment at the few-tens-of-KB order they predicted. The `FileView`
cache is honest about its one unwatchable staleness case and leans on
`spells_exactly` correctly (a stale view omits, never lies); QA's
staleness repro pins the heading/snippet pair going stale *together*.
The dev's rewrite of the format-discard test from a pinned literal to
all-previous-formats is the kind of fix that outlives the round.
Suspect 2 — the first request of a session waiting 287–780 ms behind
the startup scan — is confirmed genuine by dev and QA independently
and is the dominant remainder of the owner's "slow on first try";
correctly filed as a Handshake, next round's work. Accepted; committed
by the lead.
+19 -2
View File
@@ -216,7 +216,18 @@ impl WorkspaceIndex {
- Since indexed navigation (2026-08-27), the private facts also carry compact
local/external reference records used to rebuild declaration-to-occurrence
postings. That encoding change bumped `FACTS_FORMAT` from 1 to 2; no cache
migration is attempted or needed.
migration is attempted or needed. **2 → 3** (2026-08-28,
`docs/features/port-detail-spans/README.md`): each declaration gained its
`detail_span`. **3 → 4** (2026-08-28,
`docs/features/hover-line-index/README.md`): each declaration gained its two
*line numbers*, which is what lets a server print `file:line` for an indexed
declaration without reading that file. Same rule each time, same
consequence: the store is discarded whole on the first scan after the
upgrade and rewritten — measured at about 175 ms over the 860-file corpus,
once. `a_store_from_any_previous_facts_format_is_dropped_not_misread` now
checks **every** format this build is not, rather than the one literal
number it was pinned at, so the next bump inherits the test.
The store grew 68 KB (2.9 %) for the lines.
- `record_path` is public separately because a store keyed by path reads that
field out of every record it holds and decodes only the ones it is asked
for.
@@ -350,7 +361,13 @@ name span `19..20`), no members, one instantiation edge (of `sub`, owned by
`m` whose name is at `19..20` and whose declaration runs `12..41`, with the
site's own name span `22..25`), no subclasses, and one external reference fact
(`e`, name `sub`, one resolution path also named `sub`, occurrence `22..25`),
then the checksum. The record is what lies between the hash field and the
then the checksum. **The example is written at `FACTS_FORMAT` 2 and is kept
for its shape, not its field count**: since then every declaration also
carries its detail span (`0 0` when there is none, format 3) and its two line
numbers (format 4), so a real record today has four more numbers per
declaration than the one above. The framing — one line, tab-separated,
length-prefixed lists, checksum last — is what the example is for and is
unchanged. The record is what lies between the hash field and the
checksum; both hashes above are illustrative.
**Any change to what a record holds or how it is written bumps
+14 -1
View File
@@ -28,7 +28,7 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it. **Declined with an error on a buffer over `lucisv.largeFile.threshold`** (2026-08-27): VS Code marks a model whose document provider answered *anything* as complete and then never asks its range provider again, so an empty answer would cost a 100 MB file all of its colour — see `docs/features/large-file-mode/README.md` |
| `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md`. On a buffer over `lucisv.largeFile.threshold` this is the **only** request that colours anything, and it lexes the window itself (0.25 ms for a viewport of a 100 MB file) rather than filtering a token stream that was never built |
| `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README |
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md`. A **non-ANSI port** — named in the module header, completed in the body by `input signed [31:0] data_in;`, and likewise an old-style task or function argument — shows both places as two fenced sections, each carrying every comment that documents it (above, beside and below, where nothing else claims them): `docs/features/port-detail-spans/README.md` |
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md`. A **non-ANSI port** — named in the module header, completed in the body by `input signed [31:0] data_in;`, and likewise an old-style task or function argument — shows both places as two fenced sections, each carrying every comment that documents it (above, beside and below, where nothing else claims them): `docs/features/port-detail-spans/README.md`. The `file:line` half of a cross-file heading costs **no file access**: the line is recorded when the file is indexed (`Def::lines`), so only the snippet still reads, once per file per generation of it through `Workspace::file_view`: `docs/features/hover-line-index/README.md` |
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. A non-ANSI port answers two locations, its body declaration first — the same two the hover card shows, in the same order (`docs/features/port-detail-spans/README.md`). See `docs/features/include-nav/README.md` |
| `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` |
| `textDocument/linkedEditingRange` | `linked`, over `Document.tree` | SV's closing labels, edited as one name: the cursor on either half of `module m ... endmodule : m` (and of `endfunction`/`endtask`/`endclass`/`endpackage`/`endinterface`/`endclocking`, a named `begin`/`fork`, a generate block, and the prefix-labelled `b : begin ... end : b`) answers **both** ranges plus the SV `wordPattern`. The pair comes off one AST node — `name_span` with `end_label_span` — never off a text match, so four identical names at two nesting levels still pair syntactically. Two `null`s on purpose: a closer with **no** label (nothing to co-edit, and this never offers to create one) and a **mismatched** one (the spec requires identical text; linking would silently rewrite broken code). Escaped identifiers are excluded. See `docs/features/linked-editing/README.md` |
@@ -270,6 +270,19 @@ folder brings it into scope. `"lucisv.index.scope": "workspace"` restores the
pre-2026-08-27 behaviour in full. Rules, the clamp, the close decision and the
one `.gitignore` gap: `docs/features/index-scope/README.md`.
**And scope-relative in *time*, since 2026-08-28** (scan-interleave). A
**startup** scan of more than 64 files no longer blocks the message loop: it
indexes one file at a time and answers whatever the client has already sent
between two of them, so the first request of a session comes back in
milliseconds instead of waiting out the whole scan (780 ms → 15.5 ms cold over
200 files). The price is that such an answer reflects the index **as of that
moment** — a declaration in a file the scan has not reached yet does not exist
yet, in exactly the sense a declaration outside the scope does not exist. Two
narrowings keep that from reaching anywhere it is not worth it: a scan of 64
files or fewer runs one shot as it always did, and a request queued *behind* a
message that asked for a rescan waits for that rescan, so the loop's order
contract is unchanged. `docs/features/scan-interleave/README.md`.
**Open buffers override disk** in every index rebuild: the scope is walked,
each file read, and then every open document with a path replaces the disk
copy (adding itself if it exists only in the editor). So the index never
+592
View File
@@ -0,0 +1,592 @@
# scan-interleave
## Goal
`Server::new` ran the whole startup scan before `run()`'s message loop took its
first message, so everything a client sent the instant the handshake was done
sat in the OS pipe until the scan was over: **780 ms cold store / 287 ms warm**
over a 200-file workspace, against 26–64 µs for the same hover once the scan
had finished (filed as "suspect 2" in
`docs/features/hover-line-index/README.md`, and the larger half of the owner's
"hover is really slow on first try"). This round takes the scan apart into
per-file steps and drains the message queue between them, so a scan long enough
for a person to notice answers questions while it runs. The first hover of a
session now comes back in **15.5 ms cold / 12.8 ms warm** on the same fixture —
a 50× and 22× improvement — and the scan's own total is unchanged inside
run-to-run noise.
## Assumptions
- **An answer given mid-scan reads the index as of that moment.** It is
scope-relative in *time* exactly the way every answer is already
scope-relative in *space* (`crates/lucisv_server/README.md`): a declaration in
a file the scan has not reached yet is a declaration this server does not know
about yet, and it says so by answering nothing rather than by making the
client wait. Which files that means depends on how far the scan got, so a
mid-scan answer is genuinely **not reproducible** — which is why the rule
below narrows the cases it can happen in to the one where it is worth it.
- **Only a scan nobody asked for answers mid-way.** The message loop has always
promised that everything queued *ahead* of a request is applied before that
request is answered. A `didOpen` that widened the scope, a `didSave`, a
changed setting or an added workspace folder ask for a rescan, and "applied"
for those means the rescan has **run** — one message at a time, the server
would have finished it before ever taking the request. So requests that arrive
during a rescan wait for it, and only the *startup* scan — which nothing was
queued ahead of — answers from a half-built index. See `Server::must_wait`.
- **And only a scan long enough to be worth it.** A scan of at most
`INTERLEAVE_ABOVE` (64) files is over in a few milliseconds and runs exactly as
it always did, one shot, no drains: trading a complete answer for those
milliseconds would be a bad bargain. A count rather than a clock, because a
rule about elapsed time makes what a server answers depend on how loaded the
machine is — which is a property neither a test suite nor a bug report can
work with.
- **The scan indexes the text each file had when its work list was taken.** A
`didOpen` or a `didChange` answered mid-scan changes the *buffer* and not the
index — exactly as it does when it lands a millisecond after the scan
finished, because neither notification touches the index (a save is what
does). So a message answered in the middle of a scan cannot move that scan's
result.
- **A record written through is a record kept.** A scan a `shutdown` interrupts
leaves every file it had already parsed in the persistent store, because the
store is appended to per file (`docs/features/index-persistence/README.md`).
That was already true of a scan a `kill` interrupted; it is now reachable
through the protocol as well.
## Handshakes
### `vlog_semantic` — `WorkspaceIndex::absorb`
```rust
/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for
/// many files at once — and for **one** merge rather than one each.
pub fn absorb(&mut self, records: Vec<FileFacts>, gone: &[PathBuf]);
// generic in what rides beside the path, so an owning caller gets the same order
pub fn index_order<T>(files: impl IntoIterator<Item = (PathBuf, T)>) -> Vec<(PathBuf, T)>;
```
`absorb` keeps the same promise `update_facts` does — what comes out is the
index a full `build` over the records it now holds would have produced — and for
the same structural reason: the records stay path-sorted and one file to a path,
and `merge` is then the loop `IndexBuilder::finish` runs over the same list. It
exists because **a merge is a pass over every record the index holds**, which is
measured below and is the difference between a linear scan and a quadratic one.
`index_order`'s lifetime parameter became a type parameter. Every existing
caller passes `&str` and is unchanged; the scan passes `String`, because it owns
its work list.
### `lucisv_server::state` — the scan as a value
```rust
pub struct Scan { /* work list, how far through it, what is staged */ }
impl Scan {
pub fn skipped(&self) -> usize;
pub fn cached(&self) -> usize;
pub fn total(&self) -> usize;
pub fn index_next(&mut self, path: &Path) -> bool;
}
impl Workspace {
pub fn adopt_roots(&mut self, roots: Vec<PathBuf>);
pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Scan;
pub fn scan_step(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool;
pub fn publish_scan(&mut self, scan: &mut Scan);
pub fn finish_scan(&mut self, scan: Scan) -> Vec<String>;
}
```
**A value rather than a loop, because a callback cannot be handed the workspace
it is called from.** `rebuild_index_with` held `&mut self` for the whole scan,
so its watcher callback could reach the connection (a disjoint field) but never
the workspace — and answering a message needs exactly that. Splitting the loop
puts the scan's state somewhere the server can own it, and `rebuild_index_with`
is now literally
```rust
let mut scan = self.begin_scan(watch);
while self.scan_step(&mut scan, watch) {}
self.finish_scan(scan)
```
so "one shot" and "interleaved" are not two scans that have to be kept in step:
they are this loop with and without a drain in it. That is what makes the
fingerprint equivalence structural rather than tested-and-hoped.
`skipped`/`cached` moved from `IndexWatch` to `Scan`: they are facts about the
scan, and `IndexWatch` is now purely the thing that speaks protocol.
`open_roots_with` and `rebuild_index_with` are `#[cfg(test)]` now — the server
drives the three calls itself, and every test that just wants an index still
calls the one-shot form.
### `lucisv_server::candidates`, `::includes` — the batch forms
```rust
impl Candidates {
pub fn absorb(&mut self, index: &WorkspaceIndex, batch: Vec<(PathBuf, Vec<String>)>);
}
impl IncludeGraph {
pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]);
}
```
Both are the batch form of the incremental update each already had
(`update_words`, `update_file`), doing the whole-table half once for the batch
instead of once per file. **All three tables are published together, never one
of them**: an index that had seen a scanned file while a completion or an
include link could not would make "the workspace as far as it has been scanned"
three different things at once.
`candidates::words_in` became `pub(crate)`, because a scan lexes each file's
completion words as it reaches it rather than in one pass at the end. That moves
work rather than adding it — `Candidates::build` at the end of the scan now
finds every file's words already in hand and lexes nothing — and it is what
keeps the *tail* of a scan from being an unbroken block longer than one file.
### `docs/features/hover-line-index` — suspect 2, **DELIVERED**
That round measured the wait, filed it as a request to "whoever owns the message
loop next" and named the probe. This is that round; the probe is flipped and
renamed (`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`)
and its before-numbers are the ones in the table below.
## Measured
Machine and method are `docs/perf/README.md`'s: Apple M1 Max, macOS 27.0,
`--release`, `#[ignore]`d probes, `--test-threads=1`. Taken 2026-08-28, before
and after, in the same session.
### The merge cost, measured before the design was chosen
`perf::publishing_a_half_built_index_mid_scan`, files of 1 000 lines:
| workspace | one file's parse | one whole merge | one `update_facts` | per-file feeding would cost | against parsing |
|---|---:|---:|---:|---:|---:|
| 50 files | 2.35 ms | 0.73 ms | 0.66 ms | 32.8 ms | 117.6 ms |
| 200 files | 2.32 ms | 3.35 ms | 3.15 ms | **630.7 ms** | 464.4 ms |
| 800 files | 2.23 ms | 15.90 ms | 14.66 ms | **11.73 s** | 1.78 s |
**So: not per file.** A merge is linear in the whole workspace, so feeding the
live index one file at a time is quadratic — at 200 files it would have *more
than doubled* the scan, and at 800 files multiplied it by seven. The decision
the numbers make is **deferred**: records are staged as they are taken and
folded in with one `absorb` per *drain*, and a drain only happens when the queue
is not empty. A scan nobody is waiting on therefore pays nothing beyond one
`try_recv` per file, and a scan somebody is waiting on pays 3.35 ms per burst at
200 files — one and a half files' worth of parse.
### The latency the round is about
`e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`, 200 files
of 1 000 lines with a filelist, over the wire against the real binary:
| the first hover of a session | before | after |
|---|---:|---:|
| issued the moment `initialized` was sent, cold store | 780 ms | **15.5 ms** |
| — warm store | 287 ms | **12.8 ms** |
| the same hover once the scan is done | 64 / 61 µs | 191 / 151 µs |
Two honest caveats on that table. The "after" figures move with how busy the
machine is — a second run minutes later, with the corpus suite running beside
it, reported 19.8 ms and 14.0 ms — so read them as *tens of milliseconds
against hundreds*, which is the claim, and not as three significant figures.
And the last row is the same answer either way, measured differently now: the
"after" run waits for the progress bar to come down before asking, which is
what makes it a *post*-scan measurement rather than a race with the scan. Both
are microseconds and neither is what the round moved.
### What the scan's total cost
`state::tests::qa_perf_cold_warm_and_half_warm_scans`, the 860-file corpus,
before and after on the same machine minutes apart:
| | before | after |
|---|---:|---:|
| no cache | 321.5 ms | 322.0 ms |
| cold, filling the store | 351.3 ms | 353.4 ms |
| warm, every file from the store | 187.0 ms | 188.6 ms |
| the store | 2 380 790 B | 2 380 790 B |
**+0.2 % / +0.6 % / +0.9 %**, which is well under the "a few percent" this
round was allowed — and inside the run-to-run band, which is worth stating with
a number of its own: the same "after" measurement taken again on a busier
machine reported 357 / 375 / 201 ms, so the pair above is only meaningful
*because* it was taken minutes apart in one session on one tree. Nothing was added to the
per-file path; the completion word lex moved into it from the tail, and the
index is folded in with the same number of merges a one-shot scan always did
(one) when nothing is waiting.
### The floor under a mid-scan answer
`perf::what_a_scan_does_before_its_first_file`, 200 files of 1 000 lines:
| | quiet machine | busy machine |
|---|---:|---:|
| before the first file (resolve the scope, read every file, open the store) | 6.9 ms | 9.8 ms |
| one file | 4.0 ms | 5.7 ms |
| the other 199 | 682 ms | 723 ms |
| finishing (last merge, completion tables, include graph, overlays) | 10.7 ms | 10.9 ms |
So the 15.5 ms above is the first two rows plus the handshake and the message's
own travel, and it is **not** the "single digit ms" the brief hoped for. The
first row is one block no drain can break up, and reading the files lazily is
what would break it up — filed as a deliberate not-done below with this number
attached.
## Status / TODO
- [x] Measure the merge cost before choosing a rhythm; per-file feeding
rejected on the numbers above, deferred-and-batched chosen.
- [x] `WorkspaceIndex::absorb`, with the fresh-build equivalence tested three
ways (a batch of every shape, one batch against the same records in
pieces, and an empty batch).
- [x] `Scan` + `begin_scan`/`scan_step`/`publish_scan`/`finish_scan`, with
`rebuild_index_with` rewritten as the loop over them.
- [x] The server drives the scan and drains the queue between files; the
queue moved onto `Server` so a scan and `run` share it.
- [x] Order preserved: `Server::must_wait` holds a request (and everything
behind it) that is queued behind a rescan, and `run` answers what was
held before it takes anything newer — keeping its place among messages
the rescan itself held, and carrying its `$/cancelRequest` with it.
- [x] Coalescing: a rescan asked for mid-scan is a flag, and
`scan_until_settled` is a loop — never a scan inside a scan.
- [x] Shutdown mid-scan stops the scan where it stands and `run` returns
without taking another message.
- [x] The completion tables and the include graph are published with the
index, so a mid-scan answer is one generation and not three.
- [x] A file opened mid-scan is indexed next (`Scan::index_next`).
- [x] The startup scan republishes and refreshes lenses when a buffer was
opened during it — a debt that did not exist before this round.
- [x] The e2e probe flipped and renamed; the before-numbers kept above.
- [x] `cargo fmt` / `cargo clippy --all-targets --workspace` / `cargo test
--workspace` / `node editors/vscode/smoke.js`.
- [ ] **Not done, deliberately: the files are still read eagerly.** The 6.9 ms
before the first file is mostly 200 `read_to_string`s. Reading each file
in `scan_step` instead would take the mid-scan floor to single digits,
and it costs a work list of `Option<String>` and a decision about what a
file that turns out to be unreadable does to the progress bar's `total`
(today such a file never joins the work list at all, because the read
that fails happens before the list is taken). Worth doing; not worth
guessing at inside a round that is already changing when answers happen.
- [ ] **Not done, deliberately: a scan of a few very large files still
blocks.** `INTERLEAVE_ABOVE` counts files, and 20 netlist-shaped files
can take a second. A second rule on elapsed time would catch it and would
make what the server answers depend on machine load; the honest fix is a
cost estimate from the sizes the cap already reads (`oversize` does a
`metadata` call per walked file), which is a design, not a patch.
- [ ] **Not done, deliberately: a rescan still makes requests wait.** The
brief named later rescans as blocking the loop the same way, and they
still block *requests* — notifications, cancels and responses are
processed throughout. Answering a request from a half-updated index would
break the order contract the loop has always kept, and no measurement
says a rescan is where the pain is: the owner's report is about the first
request of a session.
## Work log
### 2026-08-28 — dev
**Measured the merge first, and the number chose the design.** The brief left
per-file / chunked / deferred open and asked for numbers. `update_facts` on an
already-held file is 3.15 ms at 200 files and 14.7 ms at 800, because
`merge_references` re-resolves every reference in the workspace; one per file is
630 ms and 11.7 s of pure merging. The rhythm that survives is **stage per
file, fold in per drain, and drain only when something is waiting** — which
makes the cost of interleaving zero for a scan nobody is waiting on and one
merge per burst for a scan somebody is. There is no chunk size to tune, which
is the nicest property of it: the client's own traffic sets the rhythm.
**The scan had to become a value before it could be interrupted.** The
blocker was borrowing, not design: `rebuild_index_with(&mut self)` holds the
workspace for the whole scan, and a message answered from inside it needs that
same workspace. `Scan` owns the work list and the staged records, so
`scan_step(&mut self, scan: &mut Scan)` borrows two separate things and the
server can put whatever it likes between two calls. `rebuild_index_with` is now
three lines over the same three methods, which is what makes "the interleaved
scan is the one-shot scan with a drain in it" a fact about the code rather than
a claim in a document.
**The hard part was not latency, it was the order contract.** The first
working version answered requests mid-scan unconditionally, and sixteen e2e
tests began failing *intermittently* — which is the real finding, not the
failures. Those sessions pipeline a whole conversation into the pipe
(`initialize`, `initialized`, a `didOpen` that widens the scope, three
requests, `shutdown`), so whether a request saw a finished index depended on
whether the forwarder thread got scheduled before the scan ended. Three
decisions came out of that:
1. **`must_wait`.** A request queued behind a message that asked for a rescan
waits for that rescan, because that is what one message at a time would have
done, and once one request is waiting every later one waits too. Held
messages keep their arrival order and are answered by `run` before it takes
anything newer. `shutdown` waits with them: a request sent before a shutdown
is a request the client is still owed an answer to.
2. **Only the startup scan answers mid-way.** A scan a *message* asked for has
that message queued ahead of everything else, so nothing arriving during it
may be answered from a half-updated index. The startup scan has nothing
queued ahead of it, and it is the one the owner's report is about.
3. **`INTERLEAVE_ABOVE`.** Even the startup scan should not trade a complete
answer for milliseconds. Sixty-four files is the line: below it the scan runs
exactly as it always did, which is also why the whole existing suite passes
unmodified — every fixture in it is a handful of files. A count and not a
clock, so that what the server answers never depends on how busy the machine
was.
**All three tables, or none.** After `must_wait` there were still failures
where a macro hover and an include link came back empty mid-scan: the index was
being published but `Candidates` and `IncludeGraph` were still built whole at
the end. Publishing one of three tables makes "as far as the scan has got" mean
three different things at once, so both grew a batch `absorb` and all three are
folded in together. The include graph's known-file table is relearned from the
scan's **whole work list** rather than the files it has reached, because which
files *exist* is settled the moment the scope is resolved and only the edges are
discovered file by file.
**Coalescing: finish, then rescan again — not abort and restart.** A message
answered mid-scan sets `rescan_wanted`; `scan_until_settled` is a loop that
scans again while the flag is set, and `reindex`/`reindex_one` set the flag
instead of running when `scanning`. Finishing was chosen over aborting because
it needs no way to unwind a half-published index and cannot loop forever: the
follow-up scan reads the persistent store for every file the abandoned one had
already parsed. Each scan keeps its own progress token, which is what a client
showing a bar expects of two scans. `reindex_one` returns `true` when it defers,
because its caller's fallback is "rebuild the whole thing right now", which is
precisely what must not happen.
**Two debts this round created and paid.** A buffer can now be *opened* during
the startup scan, so `Server::started` owes what `reindex` has always owed at
the end of a scan — a code-lens refresh, a generation bump and a republish —
and pays it when any buffer is open (which is nothing at all for a session
whose client did not get a `didOpen` in edgeways). And `reindex_one` can no
longer patch one file mid-scan without the scan overwriting it with older bytes
a moment later, so it defers too.
**A test seam, named as one.** `Server::started` grew a `queued: Vec<Message>`
parameter — what the client had already sent when the server was built, put
straight onto the queue the startup scan drains. `Server::new` passes an empty
one. The alternative was for the test to send on the client end and race the
forwarder thread for it, which made the first version of
`a_request_the_client_had_already_sent_is_answered_during_the_startup_scan`
pass alone and fail under a loaded suite. A coin-toss test is worse than no
test.
**Files touched.** `crates/vlog_semantic/src/workspace.rs`,
`crates/vlog_semantic/tests/workspace.rs`,
`crates/lucisv_server/src/{server.rs,state.rs,candidates.rs,includes.rs,perf.rs}`,
`crates/lucisv_server/tests/e2e.rs`, this README,
`docs/features/hover-line-index/README.md`, `docs/perf/README.md`, `TODO.md`.
No new dependency, no `unsafe`, no `#[allow]`, no version bump, no commits.
Single-threaded throughout: the only thread this round touches is the message
forwarder, which existed already and still only moves messages.
**Tests added** (14).
| test | where | pins |
|---|---|---|
| `absorbing_a_batch_gives_the_index_a_whole_build_would_have` | `vlog_semantic/tests/workspace.rs` | the house witness for the new entry point: a file replaced, two added (one sorting first, so every id moves), one dropped |
| `absorbing_one_batch_and_absorbing_it_in_pieces_are_the_same_index` | same | what makes a publish free of consequence — how records are grouped into batches cannot reach the result |
| `absorbing_nothing_changes_nothing` | same | the empty publish and the empty finish |
| `publishing_between_every_file_leaves_what_a_one_shot_scan_leaves` | `lucisv_server/src/state.rs` | the round's central invariant, over index **and** completion tables **and** include graph, publishing after every single file |
| `a_rescan_that_publishes_as_it_goes_still_drops_what_left_the_scope` | same | a publish only folds records *in*, so the removal a rescan owes has to survive every publish before it |
| `a_buffer_opened_or_changed_mid_scan_does_not_change_what_the_scan_indexes` | same | fingerprint equality with a `didChange` injected mid-scan |
| `a_file_opened_mid_scan_is_indexed_next_and_the_index_cannot_tell` | same | `Scan::index_next` moves it, does not move it twice, refuses a file not waiting — and the finished index is byte-identical |
| `a_scan_reports_the_same_events_in_the_same_order_however_it_is_driven` | same | progress and log continuity: interleaving adds drains between events, never events |
| `a_request_the_client_had_already_sent_is_answered_during_the_startup_scan` | `lucisv_server/src/server.rs` | the point of the round, over the real dispatch: the response goes out before the bar comes down |
| `a_scan_short_enough_to_wait_for_answers_nothing_in_the_middle_of_itself` | same | the other side of `INTERLEAVE_ABOVE` |
| `a_request_queued_behind_a_rescan_waits_for_that_rescan` | same | the order contract: the request sees the index the push asked for, not the one it was sent into |
| `a_held_request_keeps_its_place_and_takes_its_cancel_with_it` | same | the two corners holding creates: a burst's own request stays in front of one the scan it started held later, and a cancel consumed on the way in goes back with what it cancels |
| `a_rescan_asked_for_mid_scan_is_coalesced_into_exactly_one_more_scan` | same | three settings pushes inside one scan cost one more scan, two bars, two tokens, no nesting |
| `a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands` | same | the bar never comes down, the index is short, `run` returns at once |
Two `#[ignore]`d probes added
(`perf::publishing_a_half_built_index_mid_scan`,
`perf::what_a_scan_does_before_its_first_file`); one existing probe flipped and
renamed (`e2e::a_hover_issued_during_the_initial_scan_waits_for_it` →
`..._is_answered_during_it`), which is the before/after pair this README's
latency table is read from.
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
--workspace` silent. `cargo test --workspace` green, 0 failed:
`lucisv_server`'s unit tests **1 225 passed / 26 ignored** (+11 tests, +2
`#[ignore]`d probes), its `e2e` suite **56 passed / 2 ignored** (unmodified
except the flipped probe), `vlog_semantic`'s `workspace` suite **70 passed**
(+3). `node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`.
## QA log
### 2026-08-28 — QA
Read `CLAUDE.md`, the dev brief, and this README's Handshakes/Work log before
attacking. Traced `process_batch`'s held-message splice, `must_wait`,
`scan_until_settled`/`scan_once`/`answer_what_is_waiting`, `Scan`, and
`WorkspaceIndex::absorb` line by line against the charter's five attack
classes, then exercised the parts a trace alone couldn't settle. Two real
findings, both narrow; one confirmed-correct-but-untested behavior now pinned;
gates and numbers reproduced.
**Finding 1 (low, doc-contract) — `WorkspaceIndex::absorb` does not dedupe a
duplicate path in one batch the way `WorkspaceIndex::build` does.**
`crates/vlog_semantic/src/workspace.rs:472-489` (`absorb`). `build` goes
through `index_order`, which keeps the *first* of a duplicate path
(`Vec::dedup_by`'s contract, `crates/vlog_semantic/src/workspace.rs:1034`).
`absorb`'s own loop walks `records` left to right and overwrites on a
`binary_search` hit, keeping the *last*. `absorb`'s doc comment claims "what
comes out is the index a full build over the records it now holds would have
produced" — that equivalence does not hold for a batch with a duplicate path.
Not reachable through the scan that actually feeds `absorb` today: `Scan::work`
is built from `index_order` before the scan starts, so it can never contain two
entries for the same path, and `scan_step` therefore never stages a duplicate.
But `absorb` is `pub` on `WorkspaceIndex`, its doc comment states the
equivalence unconditionally, and a future caller (or a future change to how
`Scan::work` is assembled) could reintroduce the gap silently. Repro and
permanent regression test added and passing:
`crates/vlog_semantic/tests/workspace.rs`,
`absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records`
— builds `[("a.sv", module first_shape), ("a.sv", package second_shape)]` both
ways and asserts the fingerprints differ, then pins which one `absorb` actually
keeps (the last). Not fixed here — whether `absorb` should match `build`'s
first-wins or the doc comment should be narrowed to describe last-wins is a
design call, not a QA fix. Verified harmless in production as things stand
today, precisely because the scan can't construct the input that trips it.
**Finding 2 (very low, stale doc comment) — `refresh_code_lenses`'s doc comment
contradicts what this round now does.**
`crates/lucisv_server/src/server.rs:1979-1984`: "Nothing is sent at startup
either: no buffer is open there, so there are no lenses to invalidate." That
was true before this round; `Server::started` now calls exactly this method at
the end of construction whenever a `didOpen` answered mid-scan left a buffer
open (`crates/lucisv_server/src/server.rs:347-354`), and the new test below
confirms it fires. The comment should say client-refresh-capable + a buffer
open, no longer "never at startup." Not fixed here per QA's remit not to edit
outside the change's own tests, but it is a one-line fix the dev should make in
the same file the round already touched.
**Verified correct, previously untested — the two-publish behavior for a file
opened mid-startup-scan.** Traced through `Server::started`'s new "pay the
`reindex` debt" block and found it produces *two* `publishDiagnostics` for the
file a mid-scan `didOpen` opens: one from `didOpen`'s own always-existing
handler (against the half-built index, mid-scan — correct, not new), and one
from the debt-payment block after the bar comes down (against the finished
index — the new behavior). That is correct, not a duplicate-publish bug, but
it was unverified by any test in the round's own "Tests added" table. Added
`crates/lucisv_server/src/server.rs`,
`a_buffer_opened_during_the_startup_scan_is_published_and_lenses_refreshed_once`:
asserts exactly two publishes for the opened file, the first before the `end`
progress event and the second after it, and exactly one `workspace/codeLens/refresh`
(also after `end`, implicitly, since it can only fire once open_uris is
non-empty at the end of construction). Passes.
**Also added, no bug found — `INTERLEAVE_ABOVE` exact-boundary test.** The
charter asked for the 64/65 edge explicitly; the round's own tests exercise
`INTERLEAVE_ABOVE + 6` and `4`, neither of which pins the `>` vs `>=` choice in
`scan_once`. Added
`crates/lucisv_server/src/server.rs`,
`interleave_above_is_a_hard_boundary_at_the_file_count_not_before_or_after`: a
scan of exactly 64 files answers nothing mid-construction (one-shot), a scan of
65 answers before the bar comes down (interleaved). Passes as written — no
off-by-one found, now locked in.
**Attacks traced and found sound, not turned into new tests (existing coverage
or structurally excluded):**
- *Order-contract, cancel-through-a-wait*: traced `process_batch`'s
`consumed_cancels` splice by hand against
`a_held_request_keeps_its_place_and_takes_its_cancel_with_it`
(`crates/lucisv_server/src/server.rs:2985`-ish) with a constructed batch
where a cancel's target is answered *before* the wait point is reached — the
stale cancel does get re-queued into `held`, but `cancelled_in` re-filters by
the ids actually present in the replayed batch, so it is inert on replay,
never mis-cancels an unrelated request. Not a bug; not worth a dedicated
test since it changes nothing observable.
- *Gone-file races during a scan that also answers mid-way*: `finish_scan`
defers the `gone` computation to one `absorb` call at the very end, so a
file leaving scope is not removed from the live index until the scan
finishes. This only matters if a mid-scan answer could see a file that
should already be gone — and every scan capable of having `gone` files
non-empty is a *rescan* (`answering_a_rescan = true`), which `must_wait`
already blocks from answering anything mid-way. The startup scan (the only
one that answers mid-way) always starts from an empty index, so it can never
have a `gone` file. Structural, not incidental — traced through
`scan_until_settled`'s `asked_for` threading, not tested further.
- *Include graph's `known` set includes not-yet-scanned files mid-scan*:
intentional per the Handshakes section ("which files exist is settled the
moment the scope is resolved"); this can make an `` `include `` targeting an
unscanned file resolve to a path with no edges of its own yet, which is the
same "not there yet" story the index already tells for symbols. Not a
divergence from the round's own stated contract.
- *Shutdown delivered twice (queue-injection copy + forwarder-relayed copy) in
`a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands`*: the test
deliberately sends the same logical `shutdown` through two paths and says so
in its own comment ("whichever of the two ... the scan stops here"). Traced
the `forward`/`handle_shutdown` interaction and confirmed the real `exit`
notification can never be stolen by the forwarder (it stops at the first
shutdown it relays and never reads again), so the raciness is a test-harness
artifact for reaching the scenario at all, not a client-facing bug. Ran the
test 20x in a loop (`cargo test ... -- --test-threads=1`, repeated) with no
flake.
**Gates.** `cargo fmt --all -- --check` clean (after formatting the one test I
added that needed it). `cargo clippy --all-targets --workspace` silent.
`cargo test --workspace` run 3x after all QA additions: **0 failures each run,
2457 total passed each run**, identical every time. One transient failure seen
*before* the final 3-run check
(`large::tests::references_on_one_giant_line_locate_their_hits_in_linear_time`,
a pre-existing wall-clock perf gate unrelated to any file this round touches)
under self-inflicted contention (I had a background `cargo test` and a 3-run
loop racing on the same machine at once); reproduced clean on both master
(pre-round, 3/3) and this round's tree (3/3) once run without that
contention — not a regression, not flagged further.
`node editors/vscode/smoke.js ./target/debug/lucisv-server`: `smoke: OK`.
**Numbers reproduced**, same machine, `--release`, `--test-threads=1`:
- `e2e::a_hover_issued_during_the_initial_scan_is_answered_during_it`: 16.1 ms
cold / 14.0 ms warm (README claims 15.5 / 12.8, and says a rerun elsewhere
saw 19.8 / 14.0 — this sits inside that band).
- `perf::publishing_a_half_built_index_mid_scan`, all three sizes including
800 (not skipped — it ran in 5.4s, not slow): 200-file whole merge 3.85 ms
(claimed 3.35 ms), 800-file per-file-feeding-would-cost 12.9 s (claimed
11.7 s) against 2.06 s of parsing (claimed 1.78 s) — same shape, same
conclusion (deferred-batched, not per-file), numbers within normal
machine-to-machine variance.
- `state::tests::qa_perf_cold_warm_and_half_warm_scans`: no-cache 347 ms /
cold 387 ms / warm 203 ms (claimed 322/353/189) — store size **exactly**
2 380 790 bytes, matching the README bit for bit, which is the number that
actually matters (deterministic index size, unaffected by machine noise).
**Verdict: SHIP.** No masked-corruption, no order-contract violation, no
non-settling loop found across five attack classes and direct code tracing.
Two findings filed above are both low severity, both narrow (one is
structurally unreachable through the round's own code paths today, the other
is a one-line stale comment), and neither touches the hard invariants
(never-corrupt, idempotent, comments-preserved) or the round's own claimed
equivalences in the paths actually exercised. Three regression tests added,
all passing, all documenting real (if narrow) findings or previously-untested
correct behavior — none required a design change.
## Review
**2026-08-28 — lead.** Reviewed after QA's SHIP; gates re-run
independently (fmt clean, clippy silent, 2457 workspace tests green,
QA ran the suite ×3 with identical results). This was the riskiest
round of the wave — interleaving is where order contracts go to die —
and the two rules that survived the dev's own 16-test intermittent
failure (`must_wait`, so only the startup scan answers mid-way; and
`INTERLEAVE_ABOVE` as a count, not a clock) are the reason the whole
existing suite passes unmodified and deterministic. The measure-first
discipline paid again: per-file merging looked obvious and would have
been quadratic (11.7 s over 800 files); one absorb per non-empty-queue
drain costs the idle scan a `try_recv` per file and nothing else. The
structural fingerprint argument — one-shot and interleaved are
literally the same three-line loop over `Scan` — is the strongest
equivalence guarantee of the wave. First hover of a session:
780 → 15.5 ms cold, 287 → 12.8 ms warm, scan totals inside noise; the
remaining 6.9 ms of eager pre-scan reads is measured and filed, not
hidden. QA's two low findings were the lead's to settle and are fixed
in this commit: `absorb`'s doc now states the distinct-paths
precondition and why last-wins is the right update semantic (behavior
unchanged — the one production caller feeds deduped work, and QA's
divergence test pins the edge), and `refresh_code_lenses`' comment
caught up with `started`. The double-publish for a buffer opened
mid-scan (half-built answer, then finished answer) is correct by the
scope-relative-in-time doctrine and now pinned. Accepted; committed by
the lead.
+26 -1
View File
@@ -44,7 +44,10 @@ impl WorkspaceIndex {
fn counts(&self) -> IndexCounts;
}
struct Def { file: FileId, name_span: TextRange, kind: SymbolKind }
struct Def { file: FileId, name_span: TextRange, kind: SymbolKind,
detail_span: Option<TextRange>, // 2026-08-28, port-detail-spans
lines: DeclLines } // 2026-08-28, hover-line-index
struct DeclLines { name: u32, detail: Option<u32> } // 1-based source lines
struct WorkspaceSymbol<'a> { name: &'a str, container: Option<&'a str>, def: &'a Def }
struct IndexCounts { files, modules, packages, typedefs, members, defines }
@@ -275,6 +278,15 @@ unchanged by where the span comes from. Nothing here needs revisiting when
order in every returned slice, regardless of iteration order.
- `Def.name_span` is a non-empty byte range in `Def.file` that slices back to
exactly the name that was looked up (asserted over the whole corpus).
- `Def.lines` (2026-08-28, `docs/features/hover-line-index/README.md`) is the
1-based line each of those spans falls on, read off the same text the span
was read from, in the same pass. It is what lets a consumer print
`file:line` for an indexed declaration with no file access at all. **A line
is not text**: the index still keeps no file contents, exactly as it keeps
no contents for the spans it has always held. The field is a struct rather
than a bare number so richer per-declaration position data extends it by
gaining a field — members are `Decl`s like units are, so a module's ports
already carry their own lines here.
- `resolve_external` does not mutate `Semantics` and holds no borrow of the
index in its result.
@@ -424,6 +436,19 @@ and more than half of all external candidates answered on clean files.
## Work log
**2026-08-28 — declaration lines** (`docs/features/hover-line-index/README.md`).
`Def` and the per-file `Decl` gained `lines: DeclLines { name, detail }`, the
1-based source lines of `name_span` and of `detail_span`, computed in
`facts_from_analysis` from a `LineIndex` over the file being indexed.
`FileFacts::from_analysis` takes that index as a parameter (its one real caller
already holds one); `FileFacts::of` builds its own. The record format grew two
fields per declaration and `FACTS_FORMAT` went **3 → 4**.
`WorkspaceIndex::fingerprint`'s `sym` line carries the lines, so the
incremental-equals-fresh witness covers them — every existing equivalence test
stayed green unmodified. Cost, measured over the corpus: the whole scan is
unchanged inside its noise (one `LineIndex::new` per parsed file, under 1 % of
that file's parse) and the persistent store grows 68 KB over 860 files, 2.9 %.
**2026-08-27 — indexed navigation.** `FileFacts` gained compact local and
external reference records and its persisted format moved to version 2.
`WorkspaceIndex` resolves them into reverse postings after declaration tables
+109
View File
@@ -264,11 +264,106 @@ touched this round, so the flush table above is a baseline rather than an
after. The reasons each candidate was refused, with its number, are in the
next section.
## Before / after — round 3 (2026-08-28)
`docs/features/hover-line-index/README.md` — the owner's report that hovering
an instantiation, and a port on that instantiation, is slow on the first try.
Two suspects were measured before anything was changed; the numbers said which
one this round could fix and which it could only file.
**D1 — the heading stopped reading the file, and the snippet's read is
shared.** Each indexed declaration now carries its line (`Def::lines`,
`FACTS_FORMAT` 3 → 4), so `file:line` costs nothing; the snippet still wants
that file's text, and takes it from a four-entry / 8 MiB LRU of closed files'
text in `Workspace`. So the *first* touch of a file still pays one read and
every touch after it pays nothing.
| | before | after |
|---|---:|---:|
| hover on an instantiation into a 12 MB closed file, first touch | 6.47 ms | 6.23 ms |
| — the same hover again | 5.75 ms | **0.95 µs** |
| hover on a port into the same file, first touch | 5.85 ms | 5.92 ms |
| — the same hover again | 5.71 ms | **0.99 µs** |
| the 31.7 MB probe above, first touch | 17.0 ms | 16.8 ms |
| — the same hover again | 17.0 ms | **4.4 µs** |
| `perf::hovering_across_files_into_a_closed_file`, 1k / 10k (mean of 20) | 39.8 / 157 µs | **4.7 / 12.9 µs** |
The cost, over the 860-file corpus: one `LineIndex::new` per parsed file, which
leaves every scan figure inside its own noise (no cache 338 → 343 ms, cold
372 → 374 ms, warm 197 → 200 ms), and 68 KB more store — 2.9 %.
**D2 — the first request of a session waits out the startup scan.
Measured, filed, not fixed.** `Server::new` runs the whole scan before the
message loop takes its first message, so anything a client sends the instant
the handshake finishes sits in the OS pipe until the scan ends. Over 200 files
of 1 000 lines, through the shipped binary
(`tests/e2e.rs::a_hover_issued_during_the_initial_scan_waits_for_it`):
| the first hover of a session | cold store | warm store |
|---|---:|---:|
| issued the moment `initialized` was sent | **780 ms** | **287 ms** |
| the same hover once the scan is done | 64 µs | 61 µs |
This is four orders of magnitude larger than D1 and is where "the first hover
is slow" mostly lives. Fixing it is a change to request scheduling — answering
while the index is half-built, or scanning off the message-loop thread — and
was explicitly out of this round's scope.
## Before / after — round 4 (2026-08-28)
`docs/features/scan-interleave/README.md`: D2, answered. The scan is per-file
steps with the message queue drained between them, so a startup scan of more
than 64 files answers requests while it runs — single-threaded, interleaved,
not scanned off-thread. Same fixture, same probe, flipped and renamed
(`tests/e2e.rs::a_hover_issued_during_the_initial_scan_is_answered_during_it`):
| the first hover of a session | before | after |
|---|---:|---:|
| issued the moment `initialized` was sent, cold store | **780 ms** | **15.5 ms** |
| — warm store | **287 ms** | **12.8 ms** |
| the same hover once the scan is done | 64 / 61 µs | 191 / 151 µs |
The "after" figures are tens of milliseconds, not three significant figures: a
second run on a busier machine reported 19.8 / 14.0 ms. The claim is the order
of magnitude, and the post-scan row is measured after waiting for the progress
bar rather than racing the scan.
**What it cost the scan: under a percent.** The merge was measured before the
design was chosen, and the numbers ruled out the obvious shape — a merge is a
pass over the whole index, so folding each file in as it is taken would be
quadratic (`perf::publishing_a_half_built_index_mid_scan`, 200 files of 1k
lines: 630 ms of merging against 464 ms of parsing; 800 files: 11.7 s against
1.78 s). Records are staged and folded in once per *drain* instead, and a drain
only happens when a message is waiting:
| 860-file corpus | before | after |
|---|---:|---:|
| no cache | 321.5 ms | 322.0 ms |
| cold, filling the store | 351.3 ms | 353.4 ms |
| warm, every file from the store | 187.0 ms | 188.6 ms |
The floor under the 15.5 ms is one block no drain can break up:
`perf::what_a_scan_does_before_its_first_file` puts **6.9 ms** before the first
file (resolve the scope, read all 200 files, open the store) against 4.0 ms for
one file — so reading the files lazily is what a single-digit number would take,
and it is filed as a deliberate not-done in that feature's README.
## What it would take to go faster
Ranked by what the measurements above say is there, with what each would
cost. None of these were attempted; each is a future round.
0. **Answer requests during the startup scan — 780 ms cold, 287 ms warm, on
the first request of a session.** New in round 3's measurements (D2 above)
and the largest single number on this page. It is not a code-speed problem:
the work is already as fast as the persistent cache can make it, and what
costs the user is that the message loop has not started yet. Any fix is a
change to what an answer *means* while the index is half-built, so it needs
a design round, not an optimisation.
→ **Done in round 4**, 780 → 15.5 ms cold and 287 → 12.8 ms warm; the
design round it needed is `docs/features/scan-interleave/README.md`, and
what an answer means mid-scan is written down there. What is left of this
item is 6.9 ms of eager file reading before the scan's first file.
1. **Incremental lexing and parsing — 24.5 ms of a 31 ms flush at 10 000
lines (79 %).** This is the only large lever left. It is also the one
change that runs straight into `CLAUDE.md`'s hard invariants 1 and 2: the
@@ -318,7 +413,21 @@ cost. None of these were attempted; each is a future round.
- [x] **Added in round 2:** one flush stage by stage, including the
`diagnostics::all` pass that runs on every publish and that round 1's
table did not account for.
- [x] **Added in round 3 (2026-08-28):** a hover into a big closed file with
the **first touch and the repeat reported separately**
(`perf::hovering_into_a_big_closed_file_first_touch_and_repeat`) — every
earlier hover probe reported a mean, which hides exactly the split the
owner's report was about — and the first request of a session against
the shipped binary, with a cold store and a warm one
(`tests/e2e.rs::a_hover_issued_during_the_initial_scan_waits_for_it`).
`perf::breaking_down_one_flushed_keystroke`.
- [x] **Added in round 4 (2026-08-28):** what one mid-scan publish costs
against the per-file parse it is interleaved with
(`perf::publishing_a_half_built_index_mid_scan`, at 50 / 200 / 800
files), and what a scan does *before* its first file — the block no
drain can break up (`perf::what_a_scan_does_before_its_first_file`).
The e2e probe above was flipped to
`a_hover_issued_during_the_initial_scan_is_answered_during_it`.
- [ ] **Round 1's second open TODO, restated and still open:** memory.
Nothing in the repo measures resident size. Round 2 added no data
structure — two free functions and no state — so the figure it would
+14
View File
@@ -5,6 +5,20 @@ for you. The extension and its bundled language server share one version
number; the full engineering notes live in the
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
## 0.14.0 — 2026-08-28
The first-hover release.
- **The first hover of a session answers in ~15 ms**, not hundreds —
the server now answers requests while the workspace scan is still
running, with your open file indexed first.
- **Repeat hovers into closed files are ~1 µs.** Declaration line
numbers live in the index (a few KB even for tens of thousands of
modules, ports included), and a closed file's text is read once and
cached, not re-read per hover.
- **One-time index rebuild** on first open after updating — the index
format gained the line numbers.
## 0.13.1 — 2026-08-28
The F12-latency release.
+12 -1
View File
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
then open a Verilog or SystemVerilog file. There is no separate server or CLI
setup.
The current release is **0.13.1**. Its platform packages include both
The current release is **0.14.0**. Its platform packages include both
`lucisv-server` and the `lucisv` command-line tool:
| Package target | Machines |
@@ -320,6 +320,17 @@ Every nesting color is a proper VS Code theme color:
}
```
## Release 0.14.0 highlights
Version 0.14.0 is the first-hover release:
- Hover on instantiations and ports is now fast on the *first* try: the
server answers during the startup scan (~15 ms instead of waiting
hundreds), declaration lines live in the index, and closed files are
read once, then cached.
- The index cache format changed: the first open after updating
re-scans once, then persistent caching resumes.
## Release 0.13.1 highlights
Version 0.13.1 is the F12-latency release:
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
"version": "0.13.1",
"version": "0.14.0",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",