Compare commits

...
7 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
lucioandClaude Fable 5 17214ac8db Release 0.13.1 — the F12-latency release
ci / checks (push) Successful in 44s
ci / corpus (push) Successful in 20s
release / build-and-publish (push) Successful in 4m37s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 16:31:47 -07:00
lucioandClaude Fable 5 d4eb8f48ff The stack fits the nesting limit by construction, on every thread
ci / checks (push) Successful in 42s
ci / corpus (push) Successful in 19s
MAX_NESTING_DEPTH turns over-deep input into a parse error only on a
stack big enough to reach level 64, and that was an unenforced README
assumption: debug frames drifted to ~94 KiB/level under rustc 1.97
(worst family nested case, 5.9 MiB at the limit), so a default 2 MiB
spawned thread aborted around level 30 with the limiter never firing.
New vlog_parser::PARSE_STACK_SIZE (16 MiB, 2.7x the re-measured worst
case) is applied at every parse-reaching site: both binaries' work
moved onto named spawned threads (a main stack is the OS's to size —
1 MiB on win32; pre-fix lucisv aborts under ulimit -s 1024, fixed one
diagnoses), rayon pool workers resized, forwarder and lsp-server IO
threads audited parse-free. Deep-nesting suites across four crates on
controlled stacks, sabotage-verified; caller-side stack contract added
to every public parse entry point's rustdoc. analyze measured at
71 KiB on a max-legal tree — no second bound needed.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 16:26:06 -07:00
lucioandClaude Fable 5 cf32e92e58 A rescan reuses what open buffers already analyzed
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 21s
A scope-widening didOpen re-parsed every open buffer's text twice —
once for its index facts, once for its completion words — 210 ms of a
223 ms rescan for one 1.4 MB top.sv. FileFacts::of and words_in each
split so their post-parse half is callable on a finished analysis
(facts_from_analysis, words_of_tokens; one implementation per path, so
the routes cannot drift), and collect_sources hands the index and
candidates builds each open buffer's held analysis instead of its
text, on the whole-rebuild path and didSave's. ~228 ms -> ~23 ms.
Equivalence pinned: encoded facts and fingerprints byte-identical
between the two routes over the corpus and 16 crafted non-corpus
shapes; unsaved-edit, didClose-revert, size-cap and large-file
threshold boundaries tested both directions. IndexEvent::Analyzed
keeps "from cache" meaning the persistent store.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 15:28:27 -07:00
lucioandClaude Fable 5 097498da23 References stop sweeping the whole open buffer per request
The open-document overlay loop in indexed_references did two index
lookups and a scope walk for every reference in every open buffer.
A spelled-name prefilter (sound: every Def is filed under exactly its
own declared name, so a mismatched name can never match the target)
plus a hoisted file_id take a 70k-reference open top from 3.2 ms to
110 us per request, both directions. In-file references and
documentHighlight batch-convert spans through the walker (1.76 ms ->
1.18 ms / 917 us on a 10k-use signal). Answers byte-identical; the
refactor-walk equivalence suite extended with a unit-vs-member
same-spelling case. Measurements also acquitted references of the
owner-reported direction asymmetry: the felt cost is the didOpen
scope-widening rescan re-parsing open buffers (210 of 223 ms), filed
as a Handshake for the next round.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 14:02:15 -07:00
41 changed files with 7030 additions and 313 deletions

No files matched your search

+74
View File
@@ -4,6 +4,80 @@ 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
open file, found by measurement and removed, plus a stack-safety hole
closed.
### References stop sweeping the open buffer
The open-document overlay in find-references did index lookups for
every reference in every open buffer. A spelled-name prefilter and a
hoisted file lookup take a 70 000-reference open `top.sv` from 3.2 ms
to **0.11 ms** per request, both directions; in-file references and
occurrence highlighting on a heavily used signal drop ~40 %. Answers
are byte-identical — the old refactor walk remains the tested oracle.
### A rescan reuses what open buffers already analyzed
Jumping into a folder the index scope had not reached triggered a
rescan that re-parsed every open buffer's text twice — once for index
facts, once for completion words. Both now come from the analysis the
buffer already holds (one implementation per path, byte-identical facts
pinned over the corpus): the folder-widening jump drops from **228 ms
to 23 ms**, and didSave's incremental update rides the same reuse.
### The stack now fits the nesting limit by construction
The parser's 64-level nesting limit only turns over-deep input into an
error on a stack big enough to reach level 64 — an assumption that had
drifted out from under the 2026-08 measurement (~94 KiB per level in
debug under rustc 1.97; a default 2 MiB thread aborted near level 30).
`PARSE_STACK_SIZE` (16 MiB) is now applied at every parse-reaching
thread, both binaries' work included — the CLI previously aborted under
a 1 MiB main stack (`ulimit`, win32 default) on 500 nested `begin`s and
now emits an ordinary diagnostic. Deep-nesting suites across four
crates pin it, sabotage-verified.
## 0.13.0 — 2026-08-28
Editor responsiveness, and hover for old-style ports.
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.13.0"
version = "0.14.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.13.0"
version = "0.14.0"
[[package]]
name = "lucisv_server"
version = "0.13.0"
version = "0.14.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.13.0"
version = "0.14.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.13.0"
version = "0.14.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.13.0"
version = "0.14.0"
[[package]]
name = "vlog_refactor"
version = "0.13.0"
version = "0.14.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.13.0"
version = "0.14.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.13.0"
version = "0.14.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+37 -2
View File
@@ -149,8 +149,8 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
- [x] **[R] Parallel file processing.** ruff's speed story is embarrassing
parallelism over files. `main.rs` formats serially; use `rayon`
par_iter over the collected file list (formatting is already pure).
→ `crates/lucisv/src/main.rs`; pool sizing (8 MiB worker stacks, per the
recursion-limit handshake), the reworked panic hook and the
→ `crates/lucisv/src/main.rs`; pool sizing (`vlog_parser::PARSE_STACK_SIZE`
worker stacks, per the recursion-limit handshake), the reworked panic hook and the
ordered-reporting determinism argument in
`docs/features/parallel-files/README.md`. `--threads N` pins the worker
count; output is byte-identical at any count. 3.6× on 10 cores.
@@ -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
@@ -622,6 +648,10 @@ section only tracks the milestones.
**the open files' own folders since 2026-08-27 (index-scope), with the
workspace walk behind `lucisv.index.scope: "workspace"`; the filelist
still outranks both. See `docs/features/index-scope/README.md`.**
**Since 2026-08-28 a rescan no longer re-parses the buffers it already
analyzed** — an open buffer's index facts and completion words come from the
analysis it holds — so a scope-widening `didOpen` with a 1.4 MB buffer open
costs ~23 ms rather than ~228 ms.
- [x] **M2 `refactor-rename`** — new crate `vlog_refactor`; LSP
`prepareRename`/`rename` for every symbol kind `vlog_semantic` resolves,
cross-file, whole-edit-or-nothing verified by re-parse.
@@ -804,6 +834,11 @@ and are not gaps.
persistent index cache logs `cached:` rather than `indexing:` and is counted
in the `end` message — `860 files indexed, 860 from cache` — so a rescan that
flew past says why.
→ **Extended once more, 2026-08-28**
(`docs/features/index-scope/README.md`): a file that went into the index from
an open buffer's own finished analysis — no parse, no store — logs
`analyzed:` and adds nothing to the `end` message, so "from cache" still
means the persistent store alone.
→ **The other half of the size story, 2026-08-27**
(`docs/features/large-file-mode/README.md`): the walk cap covers files
nobody opened, and `lucisv.largeFile.threshold` (4 MiB) now covers the file
+37 -11
View File
@@ -32,12 +32,7 @@ use lucisv_core::config::Discovery;
use lucisv_core::filelist;
use lucisv_core::walk::{collect_files, EXTENSIONS};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
/// Worker stack size. `docs/features/recursion-limit/README.md` measured
/// the full pipeline's worst-case peak at ~3.9 MiB in a debug build on
/// input that trips the parser's nesting limit; rayon's own default is
/// 2 MiB, which would put that crash back.
const WORKER_STACK: usize = 8 * 1024 * 1024;
use vlog_parser::PARSE_STACK_SIZE;
fn main() -> ExitCode {
let opts = match args::parse() {
@@ -50,10 +45,40 @@ fn main() -> ExitCode {
// Once, before any worker thread exists, so nothing ever races on it.
install_panic_hook();
// Nothing parses on the main thread, because its stack is not ours to
// state: 8 MiB on a stock macOS or Linux, whatever `ulimit -s` says in a
// container, 1 MiB on Windows. The parser's nesting limit only turns
// over-deep input into an error on a stack of at least
// `PARSE_STACK_SIZE` — below that the overflow, which aborts the
// process, comes first. A thread we spawn is the one stack whose size is
// ours to guarantee. The pool's workers cover the file-at-a-time paths
// (`build_pool`), but not the ones that never reach it: `-` reads and
// formats a buffer right here, and so does `lucisv check -`.
let spawned = std::thread::Builder::new()
.name("lucisv".to_string())
.stack_size(PARSE_STACK_SIZE)
.spawn(move || run(&opts));
let handle = match spawned {
Ok(handle) => handle,
Err(e) => {
eprintln!("error: could not start the worker thread: {e}");
return ExitCode::from(2);
}
};
match handle.join() {
Ok(code) => code,
// An uncontained panic, already printed by the hook above. 101 is
// what the same panic on the main thread would have exited with.
Err(_) => ExitCode::from(101),
}
}
/// The run itself, on the stack `main` sized for it.
fn run(opts: &Options) -> ExitCode {
match opts.command {
Command::Format if opts.is_stdin() => run_stdin(&opts),
Command::Format => run_files(&opts),
Command::Check => run_check(&opts),
Command::Format if opts.is_stdin() => run_stdin(opts),
Command::Format => run_files(opts),
Command::Check => run_check(opts),
}
}
@@ -272,11 +297,12 @@ fn entry_for(content: u64, config: &Config) -> Entry {
}
/// Builds rayon's global pool. Worker stacks are sized for the parser's
/// recursion limit (see `WORKER_STACK`); `--threads 0` lets rayon pick.
/// recursion limit (`PARSE_STACK_SIZE` — rayon's own default is 2 MiB, which
/// would put the overflow back); `--threads 0` lets rayon pick the count.
fn build_pool(opts: &Options) -> Result<(), String> {
rayon::ThreadPoolBuilder::new()
.num_threads(opts.thread_count())
.stack_size(WORKER_STACK)
.stack_size(PARSE_STACK_SIZE)
.build_global()
.map_err(|e| format!("could not start the worker pool: {e}"))
}
+30 -1
View File
@@ -407,7 +407,8 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
// costs two levels), so it parses — and needs several MiB of stack to
// do it in a debug build: without the depth limit this family died at
// 15 levels on a 2 MiB thread, which is exactly rayon's default worker
// stack. This test crashes the process if the pool's 8 MiB is dropped.
// stack. This test crashes the process if the pool's `PARSE_STACK_SIZE`
// is dropped.
let deep = format!(
"module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n",
"if (clk) begin\n".repeat(28),
@@ -425,6 +426,34 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
assert!(stdout(&out).contains("deep.sv"), "{}", stdout(&out));
}
#[test]
fn a_deeply_nested_buffer_from_stdin_is_a_diagnostic_not_a_crash() {
// The stdin path never touches the worker pool: it formats on the thread
// `main` spawned, which is the only stack whose size lucisv gets to
// state. 500 nested blocks are far past the parser's limit, so the run
// must end with an ordinary parse error — and not with a SIGABRT, which
// is what an unstated stack gives instead.
let deep = format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
"begin\n".repeat(500),
"end\n".repeat(500)
);
let out = run_with_stdin(&["-"], &deep);
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("nesting too deep"), "{}", stderr(&out));
assert!(stdout(&out).is_empty(), "a rejected buffer prints nothing: {}", stdout(&out));
// And the deepest *legal* buffer formats on that same stack.
let legal = format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
"begin\n".repeat(58),
"end\n".repeat(58)
);
let out = run_with_stdin(&["-"], &legal);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stdout(&out).contains("endmodule"), "{}", stdout(&out));
}
#[test]
fn every_file_keeps_its_own_config_when_formatted_in_parallel() {
let dir = TempDir::new("configpar");
+58 -8
View File
@@ -24,7 +24,7 @@ use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use vlog_parser::token::TokenKind;
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::tokenize;
use vlog_semantic::{SymbolKind, WorkspaceIndex};
@@ -71,14 +71,28 @@ impl Candidates {
/// `sources` is the list `Workspace::collect_sources` already produced for
/// the index, so the files are read once and the only extra work is one
/// lex per file — see the measurements in the feature README.
pub fn build(index: &WorkspaceIndex, sources: &[(PathBuf, String)]) -> Candidates {
///
/// `known` holds the words of the files whose token stream the caller
/// already has — an open buffer's, lexed when the buffer was analyzed. A
/// file listed there is not lexed again; a file absent from it is lexed
/// here, exactly as every file used to be. The two produce the same words
/// because they are the same function over the same tokens
/// ([`words_of_tokens`]).
pub fn build(
index: &WorkspaceIndex,
sources: &[(PathBuf, String)],
mut known: HashMap<PathBuf, Vec<String>>,
) -> Candidates {
let mut out = Candidates {
units: units_of(index),
macros: macros_of(index),
..Candidates::default()
};
for (path, text) in sources {
let words = words_in(text);
let words = match known.remove(path) {
Some(words) => words,
None => words_in(text),
};
for word in &words {
*out.word_files.entry(word.clone()).or_default() += 1;
}
@@ -101,9 +115,30 @@ impl Candidates {
/// so nothing else is re-lexed. The result is what a whole
/// [`Candidates::build`] over the same files would have produced.
pub fn update_file(&mut self, index: &WorkspaceIndex, path: &Path, text: &str) {
self.update_words(index, path, words_in(text));
}
/// [`Candidates::update_file`] for a file whose words the caller already
/// has — an open buffer's, read off the tokens it was analyzed from.
pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec<String>) {
self.units = units_of(index);
self.macros = macros_of(index);
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);
self.set_words(path, words_in(text));
}
/// Drop one file's contribution entirely.
@@ -209,11 +244,26 @@ 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.
let Ok(tokens) = tokenize(text) else { return Vec::new() };
words_of_tokens(&tokens)
}
/// [`words_in`] over a token stream the caller already lexed.
///
/// The whole of `words_in` after the lex, so a caller holding an open buffer's
/// tokens gets the same words without lexing the buffer again. A buffer that
/// did not lex holds no tokens and contributes nothing here either, which is
/// the same all-or-nothing rule from the other side.
pub(crate) fn words_of_tokens(tokens: &[Token]) -> Vec<String> {
let mut seen: HashSet<String> = HashSet::new();
for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) {
if !seen.contains(token.text.as_str()) {
@@ -289,7 +339,7 @@ mod tests {
fn built(files: &[(&str, &str)]) -> Candidates {
let sources = sources(files);
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
Candidates::build(&index, &sources)
Candidates::build(&index, &sources, HashMap::new())
}
#[test]
@@ -408,7 +458,7 @@ mod tests {
];
let srcs = sources(&raw);
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut candidates = Candidates::build(&index, &srcs);
let mut candidates = Candidates::build(&index, &srcs, HashMap::new());
assert_eq!(candidates.words("shared").len(), 1, "premise: two files, one word");
let mut current = index.clone();
@@ -431,7 +481,7 @@ mod tests {
let raw = [("/rtl/a.sv", "module a;\n logic w1;\nendmodule\n")];
let srcs = sources(&raw);
let index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut candidates = Candidates::build(&index, &srcs);
let mut candidates = Candidates::build(&index, &srcs, HashMap::new());
let mut current = index.clone();
let text2 = "module a;\n logic w2;\nendmodule\n";
+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
+15 -1
View File
@@ -64,6 +64,8 @@ use lsp_types::{
WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
};
use vlog_parser::PARSE_STACK_SIZE;
use crate::server::{ClientAbilities, Server};
use crate::uri::uri_to_path;
@@ -96,7 +98,19 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
};
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
Server::new(connection, roots, abilities, storage).run()?;
// The message loop parses every buffer it is handed, so it does not run
// on the main thread: that stack is whatever the OS and `ulimit -s` left
// it, and the parser's nesting limit only turns over-deep input into a
// diagnostic above `PARSE_STACK_SIZE` (below it the overflow aborts the
// whole server, taking the editor session with it). Nothing else here
// parses — `lsp-server`'s reader and writer threads move JSON, and the
// forwarder in `Server::queue` moves messages.
std::thread::Builder::new()
.name("lucisv-main".to_string())
.stack_size(PARSE_STACK_SIZE)
.spawn(move || Server::new(connection, roots, abilities, storage).run())?
.join()
.map_err(|_| "the server thread panicked")??;
io_threads.join()?;
Ok(())
}
+416 -5
View File
@@ -178,8 +178,22 @@ pub(crate) fn indexed_def_for_symbol<'a>(
doc: &Document,
symbol: &Symbol,
) -> Option<&'a Def> {
let path = doc.path.as_deref()?;
let file = ws.index().file_id(path)?;
let file = ws.index().file_id(doc.path.as_deref()?)?;
indexed_def_in_file(ws, doc, symbol, file)
}
/// [`indexed_def_for_symbol`] with the document's own [`FileId`] already in
/// hand.
///
/// Split out for `indexed_references`, which asks about every reference in one
/// buffer: the path lookup is a binary search whose comparisons are whole path
/// `cmp`s, and it answers the same thing for all of them.
fn indexed_def_in_file<'a>(
ws: &'a Workspace,
doc: &Document,
symbol: &Symbol,
file: vlog_semantic::FileId,
) -> Option<&'a Def> {
let defs = if symbol.scope == doc.semantics.file_scope() {
ws.index().units(&symbol.name)
} else {
@@ -218,9 +232,27 @@ fn indexed_references(
for (_, doc) in ws.open_documents() {
let Some(path) = doc.path.as_ref() else { continue };
// Every reference in this buffer is answered against the same indexed
// file, so the path lookup — a binary search comparing whole paths —
// is taken once per buffer rather than once per reference.
let file = ws.index().file_id(path);
for (id, reference) in doc.semantics.references().iter().enumerate() {
// A use can only name `target.def` if it spells the name that
// declaration declares, and `target.name` is exactly that name.
// One string compare replaces two index lookups and a scope walk
// for every *other* name in the buffer, which in a big top is all
// but a handful of them. The argument that this changes no answer
// is in `docs/features/references-nav/README.md`. The empty-span
// check below is deliberately *not* hoisted here: an ambiguous use
// aborts the whole collection whether or not it has a span.
if reference.name != target.name {
continue;
}
let matches = match reference.resolved().and_then(|id| doc.semantics.symbol(id)) {
Some(symbol) => indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def),
Some(symbol) => {
file.and_then(|file| indexed_def_in_file(ws, doc, symbol, file))
== Some(&target.def)
}
None => match doc.external.get(vlog_semantic::ReferenceId(id as u32)) {
Some(ExternalTarget::Resolved(def)) => def == &target.def,
Some(ExternalTarget::Ambiguous(defs)) if defs.contains(&target.def) => {
@@ -308,9 +340,14 @@ fn in_file_references(
let Some(symbol_id) = symbol_at(&doc.semantics, offset) else { return Vec::new() };
let Some(target) = path_to_uri_or_self(ws, uri) else { return Vec::new() };
let positions = doc.positions();
// `occurrences` sorts, so the spans arrive in the order a walker wants —
// the same batch conversion `locations` already does for the cross-file
// answer. A signal used ten thousand times in one file is an ordinary
// shape, and one-span-at-a-time conversion re-measures a line per span.
let mut walker = positions.walker();
occurrences(&doc.semantics, symbol_id, include_declaration)
.into_iter()
.map(|span| Location { uri: target.clone(), range: positions.range(span) })
.map(|span| Location { uri: target.clone(), range: walker.range(span) })
.collect()
}
@@ -332,11 +369,14 @@ pub fn document_highlights(doc: &Document, offset: u32) -> Option<Vec<DocumentHi
return None;
}
let positions = doc.positions();
// Sorted spans, one walker — see `in_file_references`, which converts the
// same list the same way.
let mut walker = positions.walker();
Some(
spans
.into_iter()
.map(|span| DocumentHighlight {
range: positions.range(span),
range: walker.range(span),
kind: Some(DocumentHighlightKind::TEXT),
})
.collect(),
@@ -378,6 +418,7 @@ fn occurrences(
#[cfg(test)]
mod tests {
use super::*;
use crate::perf::mean;
use std::fs;
use std::path::PathBuf;
use std::str::FromStr;
@@ -617,6 +658,56 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member() {
// A harder equivalence case than the one above: `W` is a module (a
// *unit*, filed in `units`) and, spelled identically, a package
// member (filed in `members`) — the prefilter's one string compare
// must not let either bucket answer for the other. `top.sv` is also
// edited live after opening, so the overlay's answer has to come from
// the unsaved buffer, not the file `find_references`'s own oracle
// would otherwise re-read from disk.
let dir = temp_dir("xrefs_equivalence_unit_and_member");
let w_mod = "module W;\nendmodule\n";
let w_pkg = "package p;\n localparam W = 4;\nendpackage\n";
let top_saved = "module top;\n W u_w ();\n wire [p::W-1:0] x;\nendmodule\n";
for (name, text) in [("w.sv", w_mod), ("p.sv", w_pkg), ("top.sv", top_saved)] {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let top_uri = path_to_uri(&dir.join("top.sv")).expect("uri");
// An unsaved edit: a second live instantiation of `W`, not yet saved.
let top_live = "module top;\n W u_w ();\n W u_w2 ();\n wire [p::W-1:0] x;\nendmodule\n";
ws.set_document(top_uri, top_live.to_string());
let w_uri = path_to_uri(&dir.join("w.sv")).expect("uri");
ws.set_document(w_uri.clone(), w_mod.to_string());
let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri");
ws.set_document(p_uri.clone(), w_pkg.to_string());
// The module `W`: its declaration and both live instantiations, never
// the package member spelled the same way.
let module_offset = at(w_mod, "W");
let indexed_module = references(&ws, &w_uri, module_offset, true);
let walked_module =
vlog_refactor::find_references(&ws.sources(), &dir.join("w.sv"), module_offset, true)
.expect("the walk answers");
assert_eq!(indexed_module, locations(&ws, walked_module));
assert_eq!(indexed_module.len(), 3, "declaration + 2 live instantiations, not the member");
// The package member `W`: its declaration and the one qualified use,
// never the module.
let member_offset = at(w_pkg, "W");
let indexed_member = references(&ws, &p_uri, member_offset, true);
let walked_member =
vlog_refactor::find_references(&ws.sources(), &dir.join("p.sv"), member_offset, true)
.expect("the walk answers");
assert_eq!(indexed_member, locations(&ws, walked_member));
assert_eq!(indexed_member.len(), 2, "declaration + the one qualified use, not the module");
let _ = fs::remove_dir_all(&dir);
}
#[test]
#[ignore = "manual indexed-navigation latency probe"]
fn qa_indexed_references_latency_over_a_large_workspace() {
@@ -664,6 +755,223 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
// ------------------------------------------------------------------
// latency probes for a big open buffer
//
// `#[ignore]`d, asserting nothing about duration — the house shape from
// `perf.rs`, whose `mean` they borrow so every number in this repo is
// taken the same way. The numbers they print are recorded in
// `docs/features/references-nav/README.md`.
//
// cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored \
// --nocapture --test-threads=1
// ------------------------------------------------------------------
/// A declaration small enough that nothing about it is the measurement.
const PROBE_SUB: &str =
"module sub (input logic clk, input logic [31:0] data_in);\nendmodule\n";
/// A big top level: `blocks` four-line blocks of ordinary RTL — a wire, an
/// assign, a register and its update — then `instances` instantiations of
/// `sub`. Every block declares two names and uses four, so ten thousand
/// blocks is a forty-thousand-line file carrying tens of thousands of
/// locally resolved references: exactly the buffer the open-document
/// overlay in `indexed_references` has to walk past to answer anything.
///
/// One `acc` is used by every block, so the file also carries a *local*
/// name with thousands of occurrences — the worst case for the in-file
/// fallback, which converts one span at a time.
///
/// Its own generator rather than `perf::generated_module`'s, because that
/// one instantiates nothing and a probe about instantiations needs some.
fn generated_top(blocks: usize, instances: usize) -> String {
let mut src = String::from(
"module top (\n input logic clk,\n input logic rst_n,\n \
input logic [31:0] data_in,\n output logic [31:0] data_out\n);\n \
wire acc;\n assign acc = rst_n;\n",
);
for n in 0..blocks {
src.push_str(&format!(
" wire [31:0] w_{n};\n \
assign w_{n} = data_in ^ {{32{{rst_n}}}} ^ {{32{{acc}}}};\n \
reg [31:0] r_{n};\n always @(posedge clk) r_{n} <= w_{n};\n"
));
}
for n in 0..instances {
src.push_str(&format!(" sub u_{n} (.clk(clk), .data_in(data_in));\n"));
}
src.push_str(" assign data_out = data_in;\nendmodule\n");
src
}
/// Both directions of a cross-file references request, with a big buffer
/// open — the owner's report of 2026-08-28, measured.
#[test]
#[ignore = "manual references-latency probe — see docs/features/references-nav/README.md"]
fn qa_references_latency_with_a_big_open_top() {
use std::hint::black_box;
let dir = temp_dir("refs_big_top");
let top_text = generated_top(10_000, 4);
let sub_path = dir.join("sub.sv");
let top_path = dir.join("top.sv");
fs::write(&sub_path, PROBE_SUB).expect("write");
fs::write(&top_path, &top_text).expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let top_uri = path_to_uri(&top_path).expect("uri");
let sub_uri = path_to_uri(&sub_path).expect("uri");
ws.set_document(top_uri.clone(), top_text.clone());
ws.set_document(sub_uri.clone(), PROBE_SUB.to_string());
let use_site = at(&top_text, "sub u_0");
let declaration = at(PROBE_SUB, "sub");
let local = top_text.rfind("<= w_").expect("a local use") as u32 + 3;
let common = top_text.rfind("{32{acc}}").expect("a use of acc") as u32 + 4;
let references_in_top =
ws.document(&top_uri).map(|doc| doc.semantics.references().len()).expect("top is open");
// The answers, before any timing: a measurement of a request that
// answered nothing is worthless.
assert_eq!(references(&ws, &top_uri, use_site, true).len(), 5, "declaration + 4 instances");
assert_eq!(references(&ws, &sub_uri, declaration, true).len(), 5, "the same five");
assert_eq!(definition(&ws, &top_uri, use_site).len(), 1);
assert_eq!(references(&ws, &top_uri, local, true).len(), 3, "one wire, in this file only");
assert_eq!(references(&ws, &top_uri, common, true).len(), 10_002, "`acc`, everywhere");
let runs = 20;
let from_use = mean(runs, || {
black_box(references(&ws, &top_uri, black_box(use_site), true));
});
let from_declaration = mean(runs, || {
black_box(references(&ws, &sub_uri, black_box(declaration), true));
});
let to_definition = mean(runs, || {
black_box(definition(&ws, &top_uri, black_box(use_site)));
});
let in_file = mean(runs, || {
black_box(references(&ws, &top_uri, black_box(local), true));
});
let in_file_common = mean(runs, || {
black_box(references(&ws, &top_uri, black_box(common), true));
});
let highlights = mean(runs, || {
let doc = ws.document(&top_uri).expect("open");
black_box(document_highlights(doc, black_box(common)));
});
eprintln!(
"big open top ({} KB, {references_in_top} references): \
references from the use site {from_use:?}, \
from the declaration {from_declaration:?}, \
definition from the use site {to_definition:?}, \
references on a local wire used 3× (the in-file fallback) {in_file:?}, \
on one used 10 001× {in_file_common:?}, \
documentHighlight on that one {highlights:?}",
top_text.len() / 1000,
);
let _ = fs::remove_dir_all(&dir);
}
/// The other half of the owner's report: what jumping *into* a file costs
/// when the folder it lives in was not in the index's scope yet.
#[test]
#[ignore = "manual didOpen/scope-widening latency probe — see docs/features/references-nav/README.md"]
fn qa_didopen_latency_when_a_new_folder_widens_the_scope() {
use std::hint::black_box;
let dir = temp_dir("didopen_scope");
fs::create_dir_all(dir.join("rtl")).expect("rtl dir");
fs::create_dir_all(dir.join("lib")).expect("lib dir");
for n in 0..400 {
fs::write(
dir.join("rtl").join(format!("m{n}.sv")),
format!("module m{n};\n wire w;\n assign w = 1'b0;\nendmodule\n"),
)
.expect("write");
}
fs::write(dir.join("lib").join("sub.sv"), PROBE_SUB).expect("write");
let top_text = generated_top(10_000, 4);
let top_path = dir.join("rtl").join("top.sv");
fs::write(&top_path, &top_text).expect("write");
// The default rung: the folder scope. Nothing is in scope until a
// buffer is opened, so the first `didOpen` is itself a widening.
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
let top_uri = path_to_uri(&top_path).expect("uri");
ws.set_document(top_uri.clone(), top_text.clone());
ws.rebuild_index();
let covered = ws.index().files().len();
// A `didOpen` the scope already covers: one `Document::new` and a
// publish, and `server.rs` runs no rescan at all.
let sibling = dir.join("rtl").join("m0.sv");
let sibling_uri = path_to_uri(&sibling).expect("uri");
let sibling_text = fs::read_to_string(&sibling).expect("read");
let inside = mean(20, || {
ws.set_document(sibling_uri.clone(), sibling_text.clone());
});
// A `didOpen` in a folder the scope does not cover: the same
// `Document::new`, and then the whole rescan `server.rs` runs when
// `scope_dirs()` moved — which re-reads and re-parses every file in
// the widened scope. Until 2026-08-28 the open big buffer was one of
// them; it now goes in from the analysis it already holds, which is
// what the last two pairs of numbers below are about
// (`docs/features/index-scope/README.md`).
let sub_uri = path_to_uri(&dir.join("lib").join("sub.sv")).expect("uri");
let widening = mean(5, || {
ws.set_document(sub_uri.clone(), PROBE_SUB.to_string());
black_box(ws.rebuild_index());
});
let rescan = mean(5, || {
black_box(ws.rebuild_index());
});
// Where the buffer's share goes, on the same buffer: what a rescan
// used to pay for one open file — a whole parse for the index facts,
// then a second lex for the completion words — against what it pays
// since 2026-08-28, which is the two walks over the analysis and the
// token stream the buffer already holds.
let (reparse, reused, relex, rewords) = {
let doc = ws.document(&top_uri).expect("open");
(
mean(3, || {
black_box(vlog_semantic::FileFacts::of(top_path.clone(), &top_text));
}),
mean(3, || {
black_box(doc.facts(top_path.clone()));
}),
mean(3, || {
let tokens = vlog_parser::tokenize(&top_text).expect("it lexes");
black_box(crate::candidates::words_of_tokens(&tokens));
}),
mean(3, || {
black_box(doc.words());
}),
)
};
// The same rescan with the big buffer closed, so its share of the
// rescan is a subtraction rather than a guess.
ws.close_document(&top_uri);
let without = mean(5, || {
black_box(ws.rebuild_index());
});
eprintln!(
"didOpen with a {} KB buffer already open, {covered} files in scope: \
a file the scope already covers {inside:?}; \
one in a new folder (didOpen + rescan) {widening:?}; \
the rescan alone {rescan:?}, and {without:?} with the big buffer closed. \
That buffer's own share: facts {reparse:?} parsed vs {reused:?} reused, \
words {relex:?} re-lexed vs {rewords:?} reused",
top_text.len() / 1000,
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn include_declaration_drops_the_declaration_and_nothing_else() {
let (dir, ws, uri) = instantiated("xrefs_nodecl", "sub.sv");
@@ -771,6 +1079,109 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn a_same_named_port_in_another_open_buffer_is_a_different_symbol() {
// The name prefilter's risk case, asserted from both sides: two
// modules declare a port `clk`, both files are open, and each port's
// references are its own. A prefilter that let a spelling stand in for
// an identity would merge these two answers.
let dir = temp_dir("xrefs_same_name");
let sub = "module sub (input logic clk);\nendmodule\n";
let top = "module top;\n sub u_a (.clk(1'b0));\nendmodule\n";
let other = "module other (input logic clk);\n wire w;\n assign w = clk;\nendmodule\n";
for (name, text) in [("sub.sv", sub), ("top.sv", top), ("other.sv", other)] {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let mut uri_of = |name: &str, text: &str| {
let uri = path_to_uri(&dir.join(name)).expect("uri");
ws.set_document(uri.clone(), text.to_string());
uri
};
let sub_uri = uri_of("sub.sv", sub);
uri_of("top.sv", top);
let other_uri = uri_of("other.sv", other);
assert_eq!(
places(&references(&ws, &sub_uri, at(sub, "clk"), true)),
vec![("sub.sv".to_string(), 0), ("top.sv".to_string(), 1)],
"`sub`'s port: its declaration and the connection to it"
);
assert_eq!(
places(&references(&ws, &other_uri, at(other, "clk"), true)),
vec![("other.sv".to_string(), 0), ("other.sv".to_string(), 2)],
"`other`'s port: its declaration and its own use"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn two_packages_declaring_one_name_keep_their_references_apart() {
// The same attack through the member table rather than the port table:
// `p::WIDTH` and `q::WIDTH` spell one name and are two declarations,
// and the file using both is open.
let dir = temp_dir("xrefs_two_packages");
let p = "package p;\n localparam WIDTH = 8;\nendpackage\n";
let q = "package q;\n localparam WIDTH = 16;\nendpackage\n";
let a = "module a;\n wire [p::WIDTH-1:0] x;\n wire [q::WIDTH-1:0] y;\nendmodule\n";
for (name, text) in [("p.sv", p), ("q.sv", q), ("a.sv", a)] {
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let a_uri = path_to_uri(&dir.join("a.sv")).expect("uri");
ws.set_document(a_uri.clone(), a.to_string());
let p_uri = path_to_uri(&dir.join("p.sv")).expect("uri");
ws.set_document(p_uri.clone(), p.to_string());
assert_eq!(
places(&references(&ws, &p_uri, at(p, "WIDTH"), true)),
vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)],
"`p`'s WIDTH only — `q::WIDTH` on the next line is another symbol"
);
// And from the use side, the same set.
assert_eq!(
places(&references(&ws, &a_uri, at(a, "p::WIDTH") + 3, true)),
vec![("a.sv".to_string(), 1), ("p.sv".to_string(), 1)]
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn every_in_file_occurrence_is_converted_against_its_own_line() {
// The in-file fallback converts its spans with one walker now. A
// walker handed an out-of-order span answers a stale column, so the
// shape that would catch it: many occurrences, each on a line with a
// wide character before it, plus one on the same line as another.
let mut text = String::from("module m;\n wire a;\n");
for n in 0..20 {
text.push_str(&format!(" // é 🎉 {n}\n assign b{n} = a + a;\n"));
}
text.push_str("endmodule\n");
let (ws, uri) = document(&text);
let found = references(&ws, &uri, at(&text, "wire a") + 5, true);
assert_eq!(found.len(), 41, "the declaration and two uses per block");
let doc = ws.document(&uri).expect("open");
let positions = doc.positions();
for location in &found {
let line = location.range.start.line as usize;
let offset = positions.offset(location.range.start);
assert_eq!(
text.get(offset as usize..offset as usize + 1),
Some("a"),
"line {line} must point at the name"
);
assert_eq!(location.range.end.character, location.range.start.character + 1);
}
// documentHighlight walks the same list and must agree with it.
let highlights = document_highlights(doc, at(&text, "wire a") + 5).expect("a symbol");
let ranges: Vec<_> = highlights.iter().map(|h| h.range).collect();
assert_eq!(ranges, found.iter().map(|l| l.range).collect::<Vec<_>>());
}
#[test]
fn an_unsaved_open_buffer_replaces_its_saved_reference_postings() {
let (dir, mut ws, uri) = instantiated("xrefs_unsaved_uses", "top.sv");
+171 -6
View File
@@ -58,7 +58,11 @@ fn generated_module(name: &str, lines: usize) -> String {
/// The mean of `runs` runs. One run of a millisecond-scale operation is mostly
/// scheduling noise; a mean of a handful is the number worth writing down.
fn mean(runs: u32, mut body: impl FnMut()) -> Duration {
///
/// `pub(crate)` so the probes that live beside the code they measure —
/// `nav.rs`'s references-latency probes — time themselves the same way these
/// do, rather than each growing its own stopwatch.
pub(crate) fn mean(runs: u32, mut body: impl FnMut()) -> Duration {
let start = Instant::now();
for _ in 0..runs {
body();
@@ -248,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";
@@ -275,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"]
@@ -310,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
+179
View File
@@ -3400,6 +3400,89 @@ fn the_size_cap_and_the_file_log_work_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn qa_the_analyzed_log_word_names_only_the_open_buffer_and_only_on_a_rescan() {
// QA attack (index-scope, 2026-08-28, charter item 5). No e2e test
// exercised the real `analyzed: <path>` log line at all before this one —
// `state.rs`'s unit tests only ever check the `IndexEvent::Analyzed`
// variant, never the formatted string a real client would see over
// `window/logMessage`. Two claims: the widening `didOpen`'s rescan logs
// `analyzed:` for the open buffer and `indexing:` (never `analyzed:`) for
// the file that is only ever on disk; and the follow-up `didSave` — the
// incremental one-file path — sends no log line at all, so `analyzed:`
// cannot leak onto a request that was never a scan.
let dir = temp_dir("analyzedword");
std::fs::write(
dir.join("disk_only.sv"),
"package disk_pkg;\n localparam K = 1;\nendpackage\n",
)
.expect("write");
let file = dir.join("m.sv");
let source = "module m;\nendmodule\n";
std::fs::write(&file, source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"window":{{"workDoneProgress":true}}}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(source).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let logged: Vec<&str> = messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str())
.collect();
// The `didOpen` rescan: the open buffer's own analysis, the disk file
// parsed.
assert!(
logged.iter().any(|l| l.starts_with("analyzed: ") && l.ends_with("m.sv")),
"the open buffer must be logged `analyzed:`: {logged:?}"
);
assert!(
logged.iter().any(|l| l.starts_with("indexing: ") && l.ends_with("disk_only.sv")),
"the disk-only file must still be logged `indexing:`: {logged:?}"
);
assert!(
!logged.iter().any(|l| l.starts_with("analyzed: ") && l.ends_with("disk_only.sv")),
"a file with no open buffer is never `analyzed:`: {logged:?}"
);
assert!(
!logged.iter().any(|l| l.starts_with("indexing: ") && l.ends_with("m.sv")),
"the open buffer is not reparsed, so it is never `indexing:`: {logged:?}"
);
// The `didSave` afterwards names one file the index already holds, so it
// takes the incremental `reindex_one` path — which the work log states
// sends no per-file log line at all. Confirmed here rather than assumed:
// there is exactly one `didOpen`-rescan's worth of log lines and nothing
// from the save.
assert_eq!(
logged
.iter()
.filter(|l| l.starts_with("analyzed: ") || l.starts_with("indexing: "))
.count(),
2,
"one line for each of the two files, from the rescan alone: {logged:?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_client_that_never_asked_for_progress_is_sent_none_over_the_wire() {
let dir = temp_dir("noprogress");
@@ -4742,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);
}
+8
View File
@@ -77,6 +77,11 @@ impl From<VerificationError> for FormatError {
/// The output is only returned if it re-lexes to the same token stream as the
/// input (comments included) and formatting it again is a fixed point;
/// otherwise the caller gets an error and must leave the original text alone.
///
/// Parses `source` (twice, for verification), so call this only on a thread
/// with at least `vlog_parser::PARSE_STACK_SIZE` of stack — a smaller one
/// lets sufficiently nested input abort the process instead of returning
/// `Err` (see `docs/features/recursion-limit/README.md`).
pub fn format_source(source: &str, config: &Config) -> Result<String, FormatError> {
let output = format_once(source, config).map_err(FormatError::Source)?;
verify_equivalence(source, &output)?;
@@ -93,6 +98,9 @@ pub fn format_source(source: &str, config: &Config) -> Result<String, FormatErro
/// formatter output, and both checks are global. Convergence is checked by
/// replaying the same per-item decisions against the output — see
/// `docs/features/range-formatting/README.md`.
///
/// Same stack requirement as [`format_source`]: needs a thread with at least
/// `vlog_parser::PARSE_STACK_SIZE` of stack.
pub fn format_range(
source: &str,
config: &Config,
+6 -4
View File
@@ -7,13 +7,15 @@
//! the formatter at all.
use vlog_formatter::{format_source, Config, FormatError};
use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH};
use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH, PARSE_STACK_SIZE};
/// Formatting the deepest legal tree peaks around 4 MiB of stack in an
/// unoptimized build, more than a default test thread's 2 MiB.
/// Formatting the deepest legal tree peaks around 5.9 MiB of stack in an
/// unoptimized build, more than a default test thread's 2 MiB. The size is
/// the one every production parse site is given, so these tests fail if the
/// guarantee is ever cut below what the depth limit needs.
fn format_deep(source: String) -> Result<String, FormatError> {
std::thread::Builder::new()
.stack_size(16 * 1024 * 1024)
.stack_size(PARSE_STACK_SIZE)
.spawn(move || format_source(&source, &Config::default()))
.expect("spawn formatter thread")
.join()
+1 -1
View File
@@ -14,7 +14,7 @@ pub mod token;
pub use lexer::{tokenize, LexError};
pub use line_index::LineIndex;
pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError};
pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError, PARSE_STACK_SIZE};
pub use span::TextRange;
pub use token::KEYWORDS;
+91 -13
View File
@@ -160,13 +160,40 @@ const DRIVE_STRENGTHS: &[&str] = &[
/// How deeply constructs may nest before the parser gives up.
///
/// Chosen from measured stack use, not from taste: nested statements are the
/// most expensive family at ~62 KiB of stack per level in an unoptimized
/// build, so formatting an input that trips the limit peaks at ~3.9 MiB —
/// comfortably under the 8 MiB default main-thread stack, and ~0.5 MiB in
/// an optimized build. Real RTL nests roughly an order of magnitude less
/// than this; see `docs/features/recursion-limit/README.md`.
/// most expensive family at ~94 KiB of stack per level in an unoptimized
/// build, so the whole pipeline on an input that trips the limit peaks at
/// ~5.9 MiB there and ~0.8 MiB in an optimized build. That budget is only
/// safe on a thread big enough to hold it, which is what
/// [`PARSE_STACK_SIZE`] names — this limit bounds how *many* levels run, not
/// what one costs. Real RTL nests roughly an order of magnitude less than
/// this; see `docs/features/recursion-limit/README.md`.
pub const MAX_NESTING_DEPTH: u32 = 64;
/// How much stack a thread that parses must be given.
///
/// [`MAX_NESTING_DEPTH`] turns over-deep input into a parse error instead of
/// a stack overflow, but only on a thread that can hold the levels it *does*
/// allow: the guard fires at level 64, and reaching level 64 costs stack. On
/// a smaller thread the overflow happens first, and a stack overflow is an
/// abort, not a `Result` — the whole process dies. So the stack has to fit
/// the limit; the limit is not lowered to fit some thread's stack.
///
/// Measured worst case for the full pipeline (tokenize → parse → analyze →
/// format → verify) over every nesting family, on input sized to trip the
/// limit: **~5.9 MiB unoptimized, ~0.8 MiB optimized** (nested `case`, the
/// fattest family). 16 MiB is that with 2.7× to spare, which is the margin
/// this wants: unoptimized frame sizes drift upward with the compiler — the
/// same worst case measured ~3.9 MiB in 2026-08 and ~5.9 MiB in 2026-08-28
/// on rustc 1.97 — and there is no recoverable failure mode to fall back to.
///
/// Every thread that may reach a parse is spawned with at least this:
/// `std::thread::Builder::new().stack_size(PARSE_STACK_SIZE)`, or
/// `rayon::ThreadPoolBuilder::new().stack_size(PARSE_STACK_SIZE)`. Thread
/// stacks are committed by the OS a page at a time, so an unused one costs
/// address space rather than memory. `docs/features/recursion-limit/README.md`
/// lists every site.
pub const PARSE_STACK_SIZE: usize = 16 * 1024 * 1024;
/// How many links a left-nested chain may add to the tree on one path.
///
/// Some constructs are parsed by a loop rather than by recursion — postfix
@@ -178,9 +205,9 @@ pub const MAX_NESTING_DEPTH: u32 = 64;
/// the two limits together no matter how chains and nesting are combined.
///
/// It is larger than [`MAX_NESTING_DEPTH`] because a chain link is cheap —
/// ~6 KiB of stack per link in an unoptimized build against ~62 KiB for a
/// nested statement, so a maximal chain peaks near 1.5 MiB, well under the
/// ~3.9 MiB that maximal statement nesting already costs — and because long
/// ~9 KiB of stack per link in an unoptimized build against ~94 KiB for a
/// nested statement, so a maximal chain peaks near 2.4 MiB, well under the
/// ~5.9 MiB that maximal statement nesting already costs — and because long
/// flat chains are the one shape real RTL does produce (a 256-term generated
/// sum, a 64-bit parity XOR). Raising it, unlike raising
/// [`MAX_NESTING_DEPTH`], does not move the worst case.
@@ -241,6 +268,10 @@ pub struct Parser<'a> {
/// `source` must be the exact text `tokens` were lexed from: the constructs
/// lucisv keeps verbatim (`constraint`, `covergroup` — see
/// `docs/features/classes/README.md`) copy their bytes out of it by span.
///
/// Recurses with input nesting: call this only on a thread with at least
/// [`PARSE_STACK_SIZE`] of stack, or over-deep input aborts the process
/// instead of returning `Err`.
pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
Parser::new(tokens, source, false).parse_source_file()
}
@@ -253,6 +284,10 @@ pub fn parse(tokens: Vec<Token>, source: &str) -> PResult<SourceFile> {
/// still spans the whole file. `source` must be the exact text `tokens` were
/// lexed from. On a well-formed file the tree is identical to [`parse`]'s and
/// the diagnostics are empty.
///
/// Same stack requirement as [`parse`]: needs a thread with at least
/// [`PARSE_STACK_SIZE`] of stack, recovery included — tolerant and strict
/// parses of the same over-deep input overflow at the same depth.
pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<ParseDiagnostic>) {
let mut p = Parser::new(tokens, source, true);
match p.parse_source_file() {
@@ -4898,13 +4933,15 @@ mod tests {
}
}
/// Parse on a thread with a generous stack. Nesting all the way to
/// [`MAX_NESTING_DEPTH`] peaks around 4 MiB in an unoptimized build,
/// which is more than the 2 MiB a default test thread gets — the shipped
/// binary parses on the main thread, which has 8 MiB.
/// Parse on the stack every production parse site is given. Nesting all
/// the way to [`MAX_NESTING_DEPTH`] peaks around 5.9 MiB in an
/// unoptimized build, which is more than the 2 MiB a default test thread
/// gets — hence [`PARSE_STACK_SIZE`], and hence the fact that the tests
/// spell it rather than a number of their own: what they exercise is the
/// stack the shipped binaries actually run on.
fn parse_deep(src: String) -> PResult<SourceFile> {
std::thread::Builder::new()
.stack_size(16 * 1024 * 1024)
.stack_size(PARSE_STACK_SIZE)
.spawn(move || parse(tokenize(&src).expect("lex error"), &src))
.expect("spawn parser thread")
.join()
@@ -5014,6 +5051,47 @@ mod tests {
));
}
/// `n` copies of a block opener and its closer around one statement, in
/// an `initial` — the shape generated RTL nests.
fn nested_stmt_blocks(open: &str, close: &str, n: usize) -> String {
format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
open.repeat(n),
close.repeat(n)
)
}
#[test]
fn deep_nesting_errors_for_every_block_form() {
let d = 200;
// `fork`/`join` blocks are statements like `begin`/`end`.
assert_too_deep(nested_stmt_blocks("fork\n", "join\n", d));
// `case` carries the fattest frame in the grammar; the arm's own
// statement is a second gated level per source level.
assert_too_deep(nested_stmt_blocks("case (s)\n1: ", "endcase\n", d));
// Bodies that need no closer still recurse through the body
// statement.
assert_too_deep(nested_stmt_blocks("foreach (a[j])\n", "", d));
assert_too_deep(nested_stmt_blocks("while (c)\n", "", d));
assert_too_deep(nested_stmt_blocks("for (int i = 0; i < 4; i++)\n", "", d));
// Nested module declarations (IEEE 1800 §23.4) nest items, not
// statements, so they are gated by `parse_item`.
assert_too_deep(format!("{}wire w;\n{}", "module m;\n".repeat(d), "endmodule\n".repeat(d)));
}
#[test]
fn the_fattest_block_forms_still_parse_at_the_limit() {
// The stack these tests run on is `PARSE_STACK_SIZE`, so this is the
// load-bearing direction: the deepest *legal* input in the two most
// expensive families has to fit the stack every production parse site
// is given. `module` + `initial` + `begin` + the innermost statement
// and its expression cost six levels between them.
let n = MAX_NESTING_DEPTH as usize - 6;
parse_deep(nested_stmt_blocks("fork\n", "join\n", n)).expect("legal `fork` nesting");
parse_deep(nested_stmt_blocks("case (s)\n1: ", "endcase\n", n))
.expect("legal `case` nesting");
}
#[test]
fn chain_just_below_the_limit_parses() {
parse_deep(chain(".b", MAX_CHAIN_LENGTH as usize))
+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;
+178 -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.
@@ -379,7 +417,19 @@ impl WorkspaceIndex {
/// server refreshes every overlay after it, exactly as it does after a
/// rebuild).
pub fn update_file(&mut self, path: PathBuf, src: &str) {
let facts = facts_of(path.clone(), src);
self.update_facts(facts_of(path, src));
}
/// [`WorkspaceIndex::update_file`] for a file whose facts are already
/// known — read from a cache, or from an analysis the caller already holds
/// ([`FileFacts::from_analysis`]) — so the update costs no parse at all.
///
/// Exactly [`WorkspaceIndex::update_file`] with the parse already done, the
/// same way [`IndexBuilder::add_facts`] is [`IndexBuilder::add_file`] with
/// the parse already done: same contract, same result. Whether the record
/// really describes the file is the caller's business.
pub fn update_facts(&mut self, facts: FileFacts) {
let path = facts.path.clone();
match self.facts.binary_search_by(|held| held.path.cmp(&path)) {
// The common case — a saved file the index already holds. Only the
// names this file declared before or declares now can have moved,
@@ -400,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
@@ -429,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 {
@@ -649,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,
}
}
}
@@ -726,10 +832,42 @@ impl FileFacts {
/// Read off what one file contributes to an index — the parse
/// [`IndexBuilder::add_file`] does, exposed so a caller that stores the
/// result can do the parse itself exactly once.
///
/// Parses `src` internally, so call this only on a thread with at least
/// `vlog_parser::PARSE_STACK_SIZE` of stack — a smaller one lets
/// sufficiently nested input abort the process instead of producing a
/// diagnostic (see `docs/features/recursion-limit/README.md`).
pub fn of(path: PathBuf, src: &str) -> FileFacts {
facts_of(path, src)
}
/// The same record read off an analysis the caller **already has** — the
/// tree, the `` `define`` table and the [`Semantics`] of one file — instead
/// of from that file's text.
///
/// This is the second half of [`FileFacts::of`], made callable on its own:
/// `of` is `tokenize` + `parse_tolerant` + [`analyze`] followed by exactly
/// this function, so a caller that has done that work once (a language
/// 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`, `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, lines)
}
/// The file these facts were read from.
pub fn path(&self) -> &Path {
&self.path
@@ -740,13 +878,28 @@ impl FileFacts {
fn facts_of(path: PathBuf, src: &str) -> FileFacts {
let (tree, defines) = parse_and_collect(src);
let sem = analyze(&tree, src);
// One pass over the source's newlines, so every declaration below can be
// given its line without anyone reading the file again later. It is a
// percent of the parse it sits beside (`docs/perf/README.md`).
let lines = LineIndex::new(src);
facts_from_analysis(path, &tree, defines, &sem, &lines)
}
/// Read off what one file contributes, from its finished analysis.
fn facts_from_analysis(
path: PathBuf,
tree: &SourceFile,
defines: DefineTable,
sem: &Semantics,
lines: &LineIndex,
) -> FileFacts {
let mut facts = FileFacts {
path,
defines,
units: Vec::new(),
members: Vec::new(),
instantiations: edges_of(&tree),
subclasses: inheritance_of(&tree),
instantiations: edges_of(tree),
subclasses: inheritance_of(tree),
references: Vec::new(),
};
let Some(file_scope) = sem.scope(sem.file_scope()) else {
@@ -759,8 +912,8 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts {
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
@@ -841,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;
};
@@ -852,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);
}
}
}
@@ -872,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);
+151
View File
@@ -0,0 +1,151 @@
//! Deeply nested input against the stack the parse actually runs on.
//!
//! `vlog_parser` turns nesting past `MAX_NESTING_DEPTH` into an ordinary
//! diagnostic, but only above `PARSE_STACK_SIZE`: reaching level 64 costs
//! stack, and a thread too small to hold it overflows before the guard ever
//! fires — an abort, not a `Result`. These tests run the whole indexing
//! pipeline (tokenize → tolerant parse → `analyze` → facts) on exactly that
//! stack, so they fail if either half of the contract is cut.
//!
//! Reported 2026-08-28: 500 nested `begin`/`end` through `FileFacts::of`
//! aborted the process on a default 2 MiB test thread.
use std::path::PathBuf;
use vlog_parser::PARSE_STACK_SIZE;
use vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex};
/// Run `f` on the stack every production parse site is given — the CLI's
/// worker thread and rayon pool, the language server's message loop. Not a
/// generous number picked for the test: the constant itself, so shrinking
/// the guarantee below what the depth limit needs fails here.
fn on_parse_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
std::thread::Builder::new()
.stack_size(PARSE_STACK_SIZE)
.spawn(f)
.expect("spawn a parse-sized thread")
.join()
.expect("the parse thread died")
}
/// The index one file's facts build, read off on the same stack.
fn index_of(src: String) -> WorkspaceIndex {
on_parse_stack(move || {
let mut builder = IndexBuilder::new();
builder.add_facts(FileFacts::of(PathBuf::from("/w/deep.sv"), &src));
builder.finish()
})
}
/// `n` nested `begin`/`end` inside an `initial`, in a module.
fn nested_begins(n: usize) -> String {
format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
"begin\n".repeat(n),
"end\n".repeat(n)
)
}
/// Every block-structured shape that nests, at a depth far past the limit.
/// Each is `(name, source)`; the innermost body is a statement or an item, so
/// the shape is what real generated code would produce, not a bare skeleton.
fn deep_block_shapes(n: usize) -> Vec<(&'static str, String)> {
let stmt = |open: &str, close: &str| {
format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
open.repeat(n),
close.repeat(n)
)
};
vec![
("begin/end", nested_begins(n)),
("if/begin", stmt("if (c) begin\n", "end\n")),
("fork/join", stmt("fork\n", "join\n")),
("case/endcase", stmt("case (s)\n1: ", "endcase\n")),
("foreach", stmt("foreach (a[j])\n", "")),
("while", stmt("while (c)\n", "")),
("for", stmt("for (int i = 0; i < 4; i++)\n", "")),
(
"else-if chain",
format!(
"module m;\ninitial\n{}x <= 0;\nendmodule\n",
"if (c) x <= 1; else\n".repeat(n)
),
),
(
"generate if",
format!(
"module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n",
"if (1) begin\n".repeat(n),
"end\n".repeat(n)
),
),
(
"generate for",
format!(
"module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n",
"for (i = 0; i < 2; i = i + 1) begin\n".repeat(n),
"end\n".repeat(n)
),
),
(
"nested modules",
format!("{}wire w;\n{}", "module m;\n".repeat(n), "endmodule\n".repeat(n)),
),
(
// Not legal SystemVerilog at all — a `task` cannot open inside a
// task body — so this errors early rather than on depth. It is
// here because "errors early" is a claim about the stack too.
"nested tasks",
format!(
"module m;\n{}x = 1;\n{}endmodule\n",
"task t;\n".repeat(n),
"endtask\n".repeat(n)
),
),
(
"nested functions",
format!(
"module m;\n{}f = 1;\n{}endmodule\n",
"function int f;\n".repeat(n),
"endfunction\n".repeat(n)
),
),
("nested parens", {
format!("module m;\nassign x = {}1{};\nendmodule\n", "(".repeat(n), ")".repeat(n))
}),
]
}
#[test]
fn five_hundred_nested_blocks_are_indexed_not_aborted() {
// The reported repro, verbatim in shape. The depth limit rejects the
// `initial` block, tolerant recovery turns it into an error leaf, and the
// module around it is still a fact — a graceful result, not a dead
// process.
let index = index_of(nested_begins(500));
assert_eq!(index.files().len(), 1);
assert_eq!(index.units("m").len(), 1, "the module survives the unparsable body");
}
#[test]
fn no_block_shape_can_abort_the_parse_stack() {
// 400 levels is far past `MAX_NESTING_DEPTH` for every family, so each of
// these either errors on depth or errors earlier; what is asserted is
// that the pipeline *returns* on the guaranteed stack. A regression here
// is a SIGABRT, so the assertion below is secondary — reaching it is the
// test.
for (name, src) in deep_block_shapes(400) {
let index = index_of(src);
assert_eq!(index.files().len(), 1, "{name}");
}
}
#[test]
fn nesting_just_under_the_limit_still_yields_its_facts() {
// Legal depth, so nothing is rejected and the whole 64-level tree is
// parsed, analyzed and walked on this stack — the expensive direction,
// and the one a smaller stack fails first.
let index = index_of(nested_begins(vlog_parser::parser::MAX_NESTING_DEPTH as usize - 6));
assert_eq!(index.units("m").len(), 1, "a legally deep file is indexed like any other");
}
+431 -1
View File
@@ -2,7 +2,8 @@
//! package members, and the corpus acceptance run.
use std::path::{Path, PathBuf};
use vlog_parser::parse_source_tolerant;
use vlog_parser::defines::{collect_defines, DefineTable};
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
use vlog_semantic::{
analyze, resolve_external, Def, Definition, ExternalTarget, FileFacts, FileId, Resolution,
Semantics, SymbolKind, WorkspaceIndex,
@@ -1102,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
@@ -1553,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
@@ -1658,3 +1918,173 @@ fn a_degenerate_file_still_makes_a_record() {
assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "{src:?}");
}
}
// ----------------------------------------------------------------------
// Facts from an analysis the caller already has (index-scope, 2026-08-28)
// ----------------------------------------------------------------------
/// The analysis a server holds for an open buffer, built exactly the way
/// `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, vlog_parser::LineIndex) {
let (tokens, tree) = match tokenize(src) {
Ok(tokens) => {
let (tree, _) = parse_tolerant(tokens.clone(), src);
(tokens, tree)
}
Err(_) => (Vec::new(), parse_source_tolerant(src).0),
};
let defines = collect_defines(&tokens);
let sem = analyze(&tree, src);
(tree, defines, sem, vlog_parser::LineIndex::new(src))
}
/// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two.
///
/// The record format is the comparison — the encoded line is every field the
/// index and the persistent store ever read — so a byte-equal line is the
/// whole equivalence. Two paths that could drift here would be a corruption
/// seed: the index would describe a buffer by facts its own parse disagrees
/// with.
#[test]
fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
let crafted = [
// Nothing at all, and nothing that lexes.
"",
" \n\t\n",
"this is not verilog\n",
"module m;\n \"unterminated\n",
"// just a comment\n",
// The declaration kinds `facts_of` reads off the file scope.
"package p;\n localparam W = 8;\n typedef logic [W-1:0] word_t;\n\
\x20 function int f(int a); return a; endfunction\nendpackage\n",
"module top #(parameter N = 4) (input logic clk, output logic q);\n\
\x20 sub u_a (.clk(clk));\n sub u_b (.clk(clk));\nendmodule\n",
// Classes, inheritance, and a class nested in a package.
"class base; endclass\nclass derived extends base;\n int x;\nendclass\n",
"package pkg;\n class inner extends outer_base;\n typedef int t;\n endclass\nendpackage\n",
// `define`s, including a parameterised one and an `undef`.
"`define WIDTH 8\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n`undef WIDTH\n\
module m; logic [`WIDTH-1:0] w; endmodule\n",
// External candidates: imports, scope resolution, port connections.
"import other_pkg::*;\nimport third_pkg::thing;\nmodule m;\n\
\x20 other_pkg::word_t w;\n assign w = thing;\n child u (.port_a(w));\nendmodule\n",
// An instantiation at file scope — deliberately *not* an edge — and a
// generate body, which is one site however many instances it makes.
"sub u_orphan (.clk(clk));\nmodule m;\n generate for (genvar i = 0; i < 4; i++) begin\n\
\x20 sub u_gen (.clk(clk));\n end endgenerate\nendmodule\n",
// A tree with error nodes: the tolerant parse still contributes.
"module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n",
];
for src in crafted {
let path = PathBuf::from("/w/x.sv");
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, &lines);
assert_eq!(from_analysis, from_text, "the records differ for {src:?}");
assert_eq!(
from_analysis.encode(),
from_text.encode(),
"and so do their encoded forms for {src:?}"
);
}
}
/// The same claim over every file of the real corpus, which is where the
/// constructs nobody thought to craft live.
#[test]
fn the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !root.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut files = Vec::new();
corpus_files(&root, &mut files);
files.sort();
assert!(!files.is_empty(), "corpus/ exists but holds no Verilog");
let mut checked = 0usize;
for path in &files {
let Ok(src) = std::fs::read_to_string(path) else {
continue;
};
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, &lines);
assert_eq!(
from_analysis.encode(),
from_text.encode(),
"the records differ for {}",
path.display()
);
checked += 1;
}
eprintln!("facts equivalence: {checked} corpus files, every record byte-identical");
}
fn corpus_files(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
corpus_files(&path, out);
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) {
out.push(path);
}
}
}
/// An index built from records read off analyses is the index the parses
/// build, byte for byte — the house witness, at index scale rather than at one
/// file's.
#[test]
fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from_text() {
let files = [
("/w/pkg.sv", "package p;\n localparam W = 8;\n class c; int x; endclass\nendpackage\n"),
("/w/sub.sv", "module sub (input logic clk, input logic [7:0] d);\nendmodule\n"),
(
"/w/top.sv",
"import p::*;\n`define TAG 1\nmodule top;\n logic [W-1:0] w;\n\
\x20 sub u_a (.clk(w[0]), .d(w));\n sub u_b (.clk(w[0]), .d(w));\nendmodule\n",
),
("/w/kid.sv", "class kid extends c;\nendclass\n"),
("/w/junk.sv", "module broken (;\n"),
];
let from_text = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)));
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, 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());
// And the same through the incremental door: `update_facts` must leave the
// 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, 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);
assert_eq!(updated.fingerprint(), parsed.fingerprint(), "update_facts == update_file");
}
@@ -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
+477
View File
@@ -161,6 +161,65 @@ pub fn finish(mut self) -> WorkspaceIndex; // sorts by path, dedups,
- `index_order` stays public and unchanged: the server needs the work list's
*length* before the first parse for the progress denominator.
### `vlog_semantic` — facts from an analysis the caller already has (2026-08-28)
Two additions, both "the same thing with the parse already done", in the shape
`IndexBuilder::add_facts` already had:
```rust
impl FileFacts {
pub fn from_analysis(path: PathBuf, tree: &SourceFile,
defines: &DefineTable, sem: &Semantics) -> FileFacts;
}
impl WorkspaceIndex {
pub fn update_facts(&mut self, facts: FileFacts); // update_file, no parse
}
```
- **`FileFacts::of` is now literally `parse_and_collect` + `analyze` +
`from_analysis`.** The fact walk moved into the new function and `of` calls
it, so there is one implementation and not two: the equivalence the reuse
needs holds by construction, not by care. What a caller promises is only that
`tree`, `defines` and `sem` really are the analysis of the text at `path`.
- **`update_facts` is `update_file`'s body**, with the same contract: what is
left is the index a whole build over the same file set would have produced.
`update_file` is now `self.update_facts(facts_of(path, src))`.
- No `FACTS_FORMAT` change, no new field, no new dependency: this round adds a
second *door* to the record, never a second *shape* of it.
### `lucisv_server::state` — a `Document` can hand over its own facts
- `Document::facts(path) -> FileFacts` and `Document::words() -> Vec<String>`
are **new and public**: what an open buffer contributes to the index and to
the completion word table, read off the `tree`/`defines`/`semantics` and the
`tokens` it already holds. Never called for a fast-path buffer, whose analysis
is the analysis of the empty file and which contributes nothing anyway.
- **`IndexEvent::Analyzed { done, total, path }` is a new variant** — one file
went into the index from an open buffer's own analysis. Its own variant rather
than `Cached` so that "from cache" keeps meaning the persistent store and
nothing else; `server.rs` logs `analyzed: <path>` and, deliberately, adds no
clause to the progress bar's end message (see the work log).
- `collect_sources` takes a `HeldAnalyses` argument, because it has two
callers with different needs: an index rebuild wants the buffers' records,
a refactoring reads the texts and nothing else and would be paying for
records nothing looks at.
- `collect_sources` no longer reads a file from disk when an open buffer speaks
for it. The text was read and then thrown away; the size cap is still
consulted first, so an oversized file still reports itself `Skipped` exactly
as before.
### `lucisv_server::candidates` — words from a token stream
- `Candidates::build(index, sources, known: HashMap<PathBuf, Vec<String>>)`
takes a third argument: the words of the files whose token stream the caller
already has. A file listed there is not lexed again; a file absent from it is
lexed exactly as every file used to be.
- `Candidates::update_words(index, path, words)` is `update_file` with the lex
already done, and `update_file` delegates to it.
- `words_of_tokens(tokens)` is `pub(crate)`: the whole of `words_in` after the
lex, so the two roads to a file's words are one function over one token
stream.
### `lucisv_server::settings`
- Two new fields, `index_scope: IndexScope` (`Folder` | `Workspace`, default
@@ -224,6 +283,34 @@ pub fn finish(mut self) -> WorkspaceIndex; // sorts by path, dedups,
- [x] 19 new tests (12 state, 2 server, 1 e2e, 2 vlog_semantic, 2 settings),
3 existing ones extended, 1 superseded test rewritten; every other test
in the crate that wanted the whole workspace now says so
### Round 19 — a rescan stops re-parsing what is already analyzed (2026-08-28)
- [x] Traced where a scope-widening `didOpen`'s 213 ms actually goes, per stage,
and wrote it down (work log)
- [x] An open buffer's **index facts** come from the analysis it already holds
(`FileFacts::from_analysis`), on the whole-rebuild path and on
`update_one`'s incremental one
- [x] An open buffer's **completion words** come from the tokens it was analyzed
from (`words_of_tokens`), on both paths
- [x] The disk copy of a file an open buffer speaks for is no longer read
- [x] `IndexEvent::Analyzed`, logged as `analyzed: <path>`, so "from cache"
still means the persistent store
- [x] Equivalence pinned six ways: encoded-record equality across 860 corpus
files and 13 crafted shapes, index fingerprint equality at workspace
scale, `update_facts` == `update_file`, and the server-level
"same index and same completion tables as the same bytes on disk"
- [x] **~228 ms → ~23 ms** on the same probe, with the closed-buffer floor
unmoved at ~12 ms
- [ ] **Not done, deliberately:** no incremental *widen* (index only the newly
in-scope files and keep the rest). See the work log — it cannot hold the
brief's own fingerprint-equivalence test while other buffers carry unsaved
edits, and it would not have touched the 68 ms re-lex or any rescan that a
`didOpen` did not trigger.
- [ ] **Not done, deliberately:** the remaining ~11 ms an open 1.4 MB buffer
adds to a rescan is the fact walk (1.7 ms), the word set (3.1 ms) and the
workspace-wide word table taking 40 000 identifiers back in. It is real
work over real content, not a repeat of work already done.
- [ ] **Not done, deliberately:** no `lucisv.toml` key for either setting. They
are editor-session resource settings — how much of *this machine's* time
to spend — not project style, the same reason `maxFileSize` has none.
@@ -358,6 +445,184 @@ The 19 new tests, the 3 extended and the 1 rewritten, and what each is for:
| `the_folder_scope_widens_when_a_file_in_another_folder_is_opened` (e2e) | the real binary: definition into a sibling folder empty, opening it resolves, and a `"workspace"` client resolves immediately |
| `indexing_reports_its_progress_over_the_wire` (e2e, updated) | the model on the wire: three bars, `0 files indexed` then `1 file indexed` twice |
### 2026-08-28 — dev agent (a rescan stops re-parsing what is already analyzed)
**The symptom, reproduced first.** `nav.rs`'s
`qa_didopen_latency_when_a_new_folder_widens_the_scope`, `--release`, three
runs on `HEAD`: the widening `didOpen` **227.2 / 229.3 / 229.4 ms**, the rescan
alone **224.5 / 224.7 / 225.4 ms**, and **12.5 / 13.1 / 12.6 ms** for the same
rescan with the 1.4 MB `top.sv` closed. (The closed number is the floor for a
reason worth naming: `top.sv` is 1.4 MB, over the 1 MiB default
`lucisv.index.maxFileSize`, so with no buffer open it is not walked at all. The
"13 ms" is the other 400 files, not 401.)
**Where the 210 ms actually goes.** `rebuild_index_with` timed stage by stage,
with the buffer open, per rescan:
| stage | with the buffer open | with it closed |
|---|---|---|
| `collect_sources` (401 reads) | 9.5 ms | 8.4 ms |
| the facts loop | **133.5 ms** | 1.5 ms |
| `IndexBuilder::finish` | 0.4 ms | 0.12 ms |
| `Candidates::build` | **68.5 ms** | 0.85 ms |
| `IncludeGraph::build` | 0.84 ms | 0.14 ms |
| overlay refresh | 0.12 ms | ~0 |
So the brief's "210 ms of re-lexing and re-parsing the open buffer" is right in
total and **understates the shape**: the buffer was lexed *twice* per rescan.
Once inside `FileFacts::of` (tokenize 62 ms, parse 66 ms, `analyze` 18 ms,
the fact walk under 2 ms — 133 ms in all), and again inside
`Candidates::build`, whose `words_in` re-lexes every file's text to harvest
identifiers (62 ms of the 68 ms). A third, smaller waste sat in
`collect_sources`, which read the 1.4 MB disk copy of `top.sv` and then threw
it away because the buffer overrides it. Every one of those three is work this
server had already done: the `Document` for that buffer holds the tokens, the
tree, the define table and the `Semantics`, all built from the same text by the
same functions, at the last keystroke.
**Shape taken: (b), extended to the completion words. (a) was investigated and
rejected, on two grounds.**
- **(a) cannot hold its own mandatory test.** The brief's hard requirement for
an incremental widen is that the widened index fingerprint byte-identically
to a fresh full build. It does not, in a case that is easy to reach: the
index is rebuilt on save, not on change, so between two rebuilds any open
buffer may carry unsaved edits. A *full* rebuild at the widening `didOpen`
indexes those edits (`collect_sources` overlays live buffer text); an
incremental widen that indexed only the newly in-scope files would not. That
is an answer change — type `package p;` into an open buffer, jump into a new
folder, and the two shapes disagree about whether `p` exists — and the
fingerprint test would catch it as a failure, correctly. Making (a) safe means
re-indexing the changed buffers anyway, which is (b) with a diff bolted on
in front.
- **(a) would have fixed a third of it.** It touches only the facts loop, and
only on the rescans a widen triggers. The 68 ms word re-lex is in
`Candidates::build`, which a widen rebuilds whatever the file list did; and
every *other* rescan with a big buffer open — a save that falls back to a
whole rebuild, a settings change, a folder event, a watched file — keeps
paying the full 200 ms. (b) is one rule that covers all of them: **an open
buffer's finished analysis is what the buffer contributes, wherever it is
asked.**
**The equivalence is by construction, then pinned anyway.** `facts_of` was
split: everything after `tokenize`/`parse_tolerant`/`analyze` moved into
`facts_from_analysis`, and `FileFacts::of` now calls it. So
`FileFacts::from_analysis` is not a second way of computing a record — it is
the same code entered one step later, which is the difference between an
equivalence that has to be tested for and one that has to be *broken* to fail.
The same split gives `words_of_tokens` (the whole of `words_in` after the lex)
and `WorkspaceIndex::update_facts` (the whole of `update_file` after the
parse). What is left to prove is the narrow claim that `Document::new`'s
analysis is `facts_of`'s analysis — two separate call sites of the same three
functions, including the all-or-nothing lex-failure branch — and that is what
the corpus sweeps are for.
**The reuse is wired where the override already lives.** `collect_sources` is
the one place that decides "this buffer's text beats the disk copy"; the facts
and the words are now taken from the same `Document` in the same loop
iteration, so a record and the text beside it can never describe different
bytes. `rebuild_index_with` consults that map *before* the persistent cache,
deliberately: an open buffer's own analysis is right even when the buffer has
unsaved edits, which is exactly when a content-keyed store has nothing to
offer. It still writes the record through to the store, so the next session
starts from it.
**One argument rather than one wasted walk.** `collect_sources` has a second
caller — `sources()`, which every refactoring reads the workspace through — and
it wants the texts alone. Building a record and a word set off every open buffer
for it would be ~5 ms of dead work per `prepareRename` with a 1.4 MB buffer
open, so the function takes a `HeldAnalyses` argument saying which caller it is.
A boolean would have read as `collect_sources(watch, true)` at the call site;
the two-variant enum says what the `true` means.
**`update_one` takes the same shortcut**, through the new `analysis_of`, which
finds the buffer the same way `current_text` does — so a `didSave` on a big
buffer stops re-parsing it too. That is not the brief's headline case but it is
the same waste on the path a user hits most often.
**A third event word rather than a fourth meaning for `cached`.**
`IndexEvent::Analyzed` is its own variant so "N from cache" in the progress
bar's end message keeps meaning the persistent store and nothing else — that
sentence is `index-persistence`'s, and e2e transcripts assert it. The per-file
log gains `analyzed: <path>`; the end message gains **nothing**, because one
file out of a workspace is not why a scan finished fast, and a bar that grew a
clause in every session with a file open would say less rather than more.
`Analyzed` still ticks the bar, like the other two: it is a file of the work
list.
**Two existing tests moved, both for the same honest reason.**
`the_open_files_are_indexed_first_and_the_index_cannot_tell` counted `Parsing`
events to check the *order* of the work list; it now counts all three routes,
because the open buffer it is watching no longer parses.
`the_cache_never_puts_back_a_file_the_scan_no_longer_visits` asserted its open
buffer came from the store; it now asserts it came from its own analysis, and
also that it appears on neither of the other two lists — the test's real point
(`tb/b.sv` has a record and is still not an indexed file) is untouched.
**After, same probe, three runs:** the widening `didOpen` **22.7 / 23.2 /
24.0 ms**, the rescan alone **22.6 / 23.1 / 24.7 ms**, the closed-buffer floor
**11.5 / 12.8 / 12.4 ms** — unmoved, as it must be. **~228 ms → ~23 ms, 10×**,
and the open 1.4 MB buffer's own share of a rescan went from ~212 ms to ~11 ms.
The probe now prints that share directly and permanently, so the claim is
re-measurable rather than remembered:
```
That buffer's own share: facts 140.3ms parsed vs 1.67ms reused,
words 62.9ms re-lexed vs 3.09ms reused
```
`references-nav`'s own probe is unchanged and green on the same run
(110 µs cross-file references either direction, 1.18 ms for the in-file
fallback on a name used 10 001 times), which is what says this round did not
pay for its rescan out of the request path.
**What is left, and why it is not waste.** The ~12 ms the open buffer still
adds is the fact walk over its tree (1.7 ms), the identifier set over its
tokens (3.1 ms), and `Candidates::build` taking 40 000 identifiers into the
workspace-wide word table. All three are work over content that really is in
the index; none of them repeats work already done.
**Tests added (6).** `vlog_semantic`:
`facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text`
(13 crafted shapes — empty, unlexable, tolerant-parse-with-errors, packages,
classes, nested classes, `` `define``/`` `undef``, imports and `::` paths, a
file-scope instantiation that is deliberately not an edge, a generate body),
`the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus` (860 files,
encoded records byte-identical),
`an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from_text`
(workspace scale, files added in reverse path order so the reuse cannot smuggle
an ordering in, plus `update_facts` == `update_file`). `lucisv_server`:
`an_open_buffers_analysis_indexes_to_exactly_what_its_bytes_on_disk_would`
(an **edited** buffer — bytes nowhere on disk — against the same bytes written
to disk and parsed: same fingerprint, same words, same unit candidates, and the
event lists prove the two really took different routes),
`an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus`
(the narrow claim, over real `Document::new`s — this is the one that catches
`Document::new` drifting from `facts_of`),
`a_buffer_on_the_large_file_fast_path_offers_no_analysis_to_reuse`.
**Attacked before believing.** Three deliberate mutations, each run and each
caught: giving `Document::facts` an empty `DefineTable` fails both the crafted
fingerprint test and the corpus record sweep; dropping every 97th token in
`Document::new` fails the corpus words sweep. (A mutation to `words_of_tokens`
itself is *not* caught, and correctly so — both roads go through that one
function, which is the point of the split.)
**Files touched:** `crates/vlog_semantic/src/workspace.rs`,
`crates/vlog_semantic/tests/workspace.rs`,
`crates/lucisv_server/src/state.rs`, `crates/lucisv_server/src/candidates.rs`,
`crates/lucisv_server/src/server.rs`, `crates/lucisv_server/src/nav.rs`
(the probe's own numbers), this README,
`docs/features/references-nav/README.md` (the Handshake, delivered),
`docs/features/indexing-ux/README.md` (the new log word), `TODO.md`. No new
dependency, no `FACTS_FORMAT` change, no scope-semantics change, no version
bump, no commits.
**Verification.** `cargo fmt --all -- --check`: clean. `cargo clippy
--all-targets --workspace`: zero warnings. `cargo test --workspace`: **2413
passed, 0 failed** (2407 on `HEAD`, measured — 6 new). `cargo build && node
editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`.
## QA log
### 2026-08-27 — QA agent (gates, attack surfaces, mechanical-sweep audit)
@@ -576,8 +841,220 @@ and the stale-comment LOW items are follow-up hygiene, not blockers — every
behavior they probe was independently verified correct by hand in this
session.
### 2026-08-28 — QA agent (round 19: drift, staleness, threshold and log-semantics attacks)
**Charter.** The round under review (dev work log "a rescan stops re-parsing
what is already analyzed", same date) claims an open buffer's index facts and
completion words can be read off its already-held analysis instead of
re-parsed, and that this is safe because `FileFacts::of` and
`Document::new`/`FileFacts::from_analysis` are now one code path entered at
different points. The charter was to attack exactly the seam where the two
routes could still disagree — a masked-corruption seed in CLAUDE.md's terms —
plus staleness, the large-file threshold boundary, the cap interaction, and
the new log word. **No drift, no staleness bug, and no cap regression were
found.** One real, pre-existing (round-independent) robustness gap was found
and is filed separately, not against this round.
**1. Drift attack — crafted non-corpus shapes, both facts and words.**
Traced `Document::new` (`crates/lucisv_server/src/state.rs:64-92`) against
`parse_and_collect`/`facts_of` (`crates/vlog_semantic/src/workspace.rs:773-793,
1023-1034`) line by line: same `tokenize` → `collect_defines`/`parse_tolerant`
on the `Ok` branch (same token vector, so `collect_defines` reads the same
bytes in both places), same `parse_source_tolerant` on the `Err` branch. The
one asymmetry — `Document::new` computes `collect_defines(&tokens)`
unconditionally, including when `tokens` is the empty `Vec` from a lex
failure, while `facts_of`'s `Err` arm substitutes `DefineTable::default()`
directly — cannot drift: `DefineTable` derives `Default` as `entries:
Vec::new()`, and `collect_defines(&[])` produces exactly that (confirmed by
reading `collect_defines`, `crates/vlog_parser/src/defines.rs:91-104`: the
loop never runs on an empty slice). Also confirmed `analyze(tree, text)`
(`crates/vlog_semantic/src/lib.rs:65`) takes only the tree and the text — no
workspace-index dependency — so nothing about the *workspace* state at the
moment a buffer was analyzed can make its `semantics` differ from a fresh
parse's.
Verified by construction is not verified by attack, so 16 crafted non-corpus
shapes were run through the real `Document`+`FileFacts::of` pair (encoded
facts equality and sorted-word equality), added as a permanent test:
`qa_attack_crafted_non_corpus_shapes_drift_check`
(`crates/lucisv_server/src/state.rs:3361-3441`) — a UTF-8 BOM, CRLF, BOM+CRLF,
an unterminated block comment, an unterminated attribute, an unterminated
macro call, an unterminated string, an embedded control character, deep
`begin`/`end` nesting, deep paren nesting, 500 `` `define``s, `` `include``
directives, a tree with parse-error recovery, mixed line endings, an embedded
NUL, and tabs/form-feeds. **All 16 passed — no drift.** (The BOM cases lex
clean, confirmed separately: `tokenize` silently absorbs a leading BOM rather
than erroring, so they exercise the `Ok` branch like ordinary source, not the
lex-failure one — noted so the case list isn't mistaken for dead weight.)
**One robustness finding, filed as out-of-scope, not blocking this round —
LOW/INFORMATIONAL, pre-existing.** Deep `begin`/`end` nesting
(500 levels) overflows the stack under `cargo test`'s default per-test-thread
stack (2 MiB) — and it does so calling **`FileFacts::of` alone**, no
`Document`, no reuse, nothing this round touched. Reproduced identically on
`git stash`-ed pristine `master` with the same crafted input run through a
temporary `vlog_semantic` test (`cargo test -p vlog_semantic` on unmodified
`HEAD`: same abort). Because both routes being compared fail *identically*,
this is the opposite of the drift this charter hunts for, and it is not a
regression — the recursive-descent parser/analyzer has always had this
ceiling; a real server thread's default OS stack is larger (8 MiB main-thread
default on macOS, confirmed by running the same input outside the test
harness) so this is unlikely to bite in the shipped binary at 500 levels, but
the underlying unbounded-recursion-depth issue is real and worth a filed
follow-up (a recursion-depth guard in the parser/analyzer, or running the LSP
request-handling thread with an explicit larger stack). The permanent test
above works around it by running on a dedicated 64 MiB-stack thread, which is
what let the drift comparison actually exercise 500-level nesting without
tripping the unrelated ceiling. Spun off as a background task rather than
fixed here — it is not in this round's files or in `verify.rs`, and touching
the parser's recursion handling is a bigger, separate change.
**2. Staleness attacks.** `qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan`
(`crates/lucisv_server/src/state.rs:3482-3517`, new): an open buffer edited
away from disk content (never saved) rescans from the live edit — confirmed
via the `Analyzed` route and the indexed member changing from `ON_DISK` to
`IN_BUFFER` — and, after `close_document` with no save in between, the very
next rescan reparses from disk (`Parsing` route) and the index reverts to
`ON_DISK`, with no trace of the closed buffer's analysis anywhere. Also traced
structurally: the persistent `IndexCache` is keyed by a content hash of the
exact bytes (`crates/lucisv_server/src/index_cache.rs:135-157`,
`content_hash(text.as_bytes())`), so even though `rebuild_index_with` writes
an open buffer's unsaved-edit facts through to the cache
(`state.rs`'s facts-loop, `self.cache.record(&facts, text)`), a later lookup
against disk's differently-hashed bytes cannot accidentally hit that record —
the two are different cache keys by construction, not by care. The
"`didSave` where disk write happens after the rescan reads" race cannot occur
either, traced rather than merely tested: `server.rs`'s `DidSaveTextDocument`
handler (`crates/lucisv_server/src/server.rs:1319-1334`) calls
`self.set_document` (updating the in-memory `Document` from the notification's
own text, when present) *before* `reindex_one`/`reindex`, and the reused facts
come from that in-memory `Document`, never from a disk read — so there is no
window in which the index can read disk before the save's bytes land there.
**3. Large-file threshold crossing via unsaved edits, both directions** —
the charter's explicit "break it differently" ask, since the dev's own test
only checks `doc.large` flips, not that a rescan's *event routing* follows it
mid-session. Two new tests:
`qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session`
and `qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse`
(`state.rs:3520-3596`). Small-on-disk/huge-live: a real analysis is reused
(`Analyzed`) until the buffer is edited past the threshold, at which point the
very next rescan drops it from every list (`analyzed` empty, `parsed` empty —
contributes nothing at all, matching the fast-path contract), and shrinking it
back reinstates reuse on the next rescan. Huge-on-disk/small-live: `doc.large`
is decided from the buffer's own live text length (`is_large`,
`state.rs:1298-1301`) and never from what is on disk, so the on-disk size is
provably irrelevant to the routing — the buffer is on the fast path the
instant it is opened with huge text, whatever the disk copy says, and reuse
resumes the instant it is edited back down. **No boundary bug in either
direction.**
**4. Cap interaction, unchanged in both directions.** New test
`qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before`
(`state.rs:1780-1817`): an open buffer whose file exceeds `maxFileSize` is
still reported `Skipped` once, from `collect_sources`'s disk-phase walk (the
`spoken_for` short-circuit this round added only skips the wasted *read*, not
the cap check that runs ahead of it — traced in
`collect_sources`, `state.rs:930-937`) — and it is still indexed in full
afterward, now via `Analyzed` rather than `Parsing`. Confirmed the file is
never re-parsed (`parsed` empty) and the content is indexed exactly as before
this round. The cap boundary moved in neither direction.
**5. Event/log semantics — a real gap found and closed.** No test anywhere
in the repository — not `state.rs`'s unit tests (which only check the
`IndexEvent::Analyzed` *variant*, via the `scan()` helper), not any e2e test —
exercised the actual `"analyzed: <path>"` string a real client would receive
over `window/logMessage`, despite `docs/features/indexing-ux/README.md`
documenting the exact wording. Added
`qa_the_analyzed_log_word_names_only_the_open_buffer_and_only_on_a_rescan`
(`crates/lucisv_server/tests/e2e.rs`, after `the_size_cap_and_the_file_log_work_over_the_wire`):
against the real binary, a scope-widening `didOpen` with one open buffer and
one disk-only file logs `analyzed: .../m.sv` and `indexing: .../disk_only.sv`
— never the other word for the other file — and the follow-up `didSave`
(the incremental `reindex_one` path) emits **no** log line at all, confirmed
by counting exactly two `analyzed:`/`indexing:` lines in the whole transcript.
This also incidentally re-confirms the work log's claim that `reindex_one`
sends no per-file log line, which was previously asserted only by a code
comment.
**6. Reproducing the numbers, `--release`, three fresh runs of
`qa_didopen_latency_when_a_new_folder_widens_the_scope`:** widening `didOpen`
**23.95 / 24.20 / 24.31 ms** (claimed ~23 ms), rescan alone **23.91 / 24.09 /
23.88 ms**, closed-buffer floor **12.96 / 12.83 / 12.70 ms** (claimed ~12 ms,
unmoved — confirmed unmoved). The buffer's own share, printed by the probe:
facts **144.3 ms parsed vs 1.7 ms reused**, words **65.8 ms re-lexed vs
3.1 ms reused** — matches the work log's 140.3 ms/1.67 ms and 62.9 ms/3.09 ms
within noise. `qa_references_latency_with_a_big_open_top`
(references-nav's own probe): **113 µs**/**128 µs** cross-file either
direction (claimed ~110 µs), **1.19 ms** for the in-file fallback on a name
used 10 001× (claimed 1.18 ms) — unmoved, confirming this round did not move
cost onto the request path.
**7. Gates.** `cargo fmt --all -- --check`: clean (after formatting the new
tests). `cargo clippy --all-targets --workspace`: zero warnings (two clippy
hits in QA's own new tests — `cloned_ref_to_slice_refs`,
`useless_format` — fixed before the final run). `cargo test --workspace`: all
green, 0 failed, across every crate (lucisv_server's own suite: 1204 passed,
23 ignored — the ignored set is the manual latency probes, run separately
above). `cargo build && node editors/vscode/smoke.js
target/debug/lucisv-server`: `smoke: OK`. `verify.rs`: no diff (confirmed via
`git diff --name-only`). No new `unwrap()`/`expect()`/`panic!` outside
`#[cfg(test)]` in the round's diff or in QA's additions (grepped both).
**One documentation nit, LOW, informational.** This README's Handshakes
section (`docs/features/index-scope/README.md:219`) says
`words_of_tokens(tokens)` "is `pub(crate)`"; the actual declaration
(`crates/lucisv_server/src/candidates.rs:246`) is `pub fn`. Harmless in
practice — `lucisv_server` is a `bin`-only crate with no `lib` target
(confirmed: `cargo test -p lucisv_server --lib` errors "no library targets
found"), and `candidates` is a private `mod` (`main.rs:9`), so there is no
larger scope for `pub` to leak into within this crate — but the README's
wording doesn't match the code. Worth a one-word fix (`pub` → `pub(crate)`,
or the sentence corrected) whenever this file is next touched.
**Tests added (8), all permanent, all passing.** `crates/lucisv_server/src/state.rs`:
`qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before`,
`qa_attack_crafted_non_corpus_shapes_drift_check` (+ its `_body` helper, run on
a dedicated large-stack thread),
`qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan`,
`qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session`,
`qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse`.
`crates/lucisv_server/tests/e2e.rs`:
`qa_the_analyzed_log_word_names_only_the_open_buffer_and_only_on_a_rescan`.
**Verdict: SHIP.** The round's central claim — an open buffer's held analysis
is byte-identical to a fresh parse's, so reusing it cannot corrupt the index —
held against every attack this session could construct, including shapes the
dev's own corpus sweep and crafted-shape list did not cover. Staleness, the
large-file threshold's two crossing directions, the cap interaction, and the
new log word all check out. The one real finding (stack depth) predates this
round, affects both compared routes identically, and is filed as a follow-up
rather than a blocker.
## Review
### 2026-08-28 — lead, rescan-reuse round
Reviewed the diff and both logs after QA's clean SHIP; gates re-run
independently (fmt clean, clippy silent, 2419 workspace tests green).
The dev's deviation from the brief's preferred incremental-widen shape
is correct and well-argued: a widen that skipped already-indexed files
would also skip unsaved buffer edits the full rebuild indexes, an
answer change the mandatory fingerprint test would have caught — so
shape (b) with the split constructors is the honest one, and the split
is genuinely by construction (`facts_of` = parse + `facts_from_analysis`,
`words_in` = lex + `words_of_tokens`; one implementation each). The
drift attacks QA ran — 16 crafted non-corpus shapes plus both corpus
sweeps — are the right coverage for the one risk this design carries,
and the staleness/threshold/cap boundary tests close the state-machine
edges. `IndexEvent::Analyzed` kept separate from `Cached` so the
persistence transcripts keep their meaning: good instinct. ~228 ms →
~23 ms reproduced by dev, QA and the probe's own printout. Lead fixed
QA's doc nit directly (`words_of_tokens` tightened to `pub(crate)` to
match the Handshakes prose; all callers in-crate). The pre-existing
deep-nesting overflow QA found on pristine master is correctly out of
scope and spun off. Accepted; committed by the lead.
### 2026-08-27 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself
+9
View File
@@ -216,6 +216,15 @@ pub fn build<'a>(files: …) -> WorkspaceIndex {
line reads `cached: <path>` where a parsed file's reads `indexing: <path>`,
and whose bar tick is identical — a cached file is a file of the work list,
and the bar flying through them is the point.
**Amended again (index-scope, 2026-08-28):** a third arm,
`IndexEvent::Analyzed`, for a file that went into the index from an **open
buffer's own finished analysis** rather than from a parse or from the store.
Its log line reads `analyzed: <path>`; its bar tick is identical again. It
deliberately adds **no** clause to the end message — one file out of a
workspace is not why a scan finished fast, and "N from cache" keeps meaning
the persistent store and nothing else, which is the sentence
`index-persistence`'s e2e transcripts assert. See
`docs/features/index-scope/README.md`.
- `begin` still carries **no** percentage: the first honest one is the first
file's.
+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
+17 -12
View File
@@ -30,12 +30,13 @@ same invocation, regardless of thread count.
rather than streaming. For the sizes lucisv targets (a large RTL tree is tens
of MiB of source) this is acceptable; it is the reason `--stdout` over a
huge tree is no longer incremental.
- **8 MiB of worker stack is enough.** Taken from
`docs/features/recursion-limit/README.md`, which measured the worst-case
full-pipeline peak at ~3.9 MiB in a debug build and ~0.5 MiB in release.
The pool is built with exactly that number; rayon's own default is 2 MiB,
which would silently reintroduce the stack-overflow crash that feature
fixed.
- **Worker stacks are `vlog_parser::PARSE_STACK_SIZE`, not a number of this
feature's own.** Superseded 2026-08-28: this used to assume "8 MiB is
enough", from recursion-limit's then-measured ~3.9 MiB debug peak. That
peak is now measured at ~5.9 MiB (rustc 1.97, nested `case`), so the size
is no longer this feature's to pick — `build_pool` spells the parser's
constant, and recursion-limit owns the number. rayon's own default is
2 MiB, which would silently reintroduce the stack-overflow crash.
- **The `.gitignore` support is a documented subset, not git.** It is the
`--exclude` matcher plus anchoring, directory-only and negation. See
"gitignore subset" below for exactly what is and is not honoured. It is
@@ -98,11 +99,13 @@ A path named directly on the command line is never ignored, exactly as with
## Handshakes
- **Consumes `docs/features/recursion-limit/README.md`'s request:** that
README asks whoever lands parallelism to build the rayon pool with
`stack_size(8 * 1024 * 1024)` or larger, because a 2 MiB worker cannot
reach `MAX_NESTING_DEPTH` in a debug build (~3.9 MiB measured). Done in
`main.rs::build_pool`, with a test (`deep_file_formats_under_the_pool`)
that fails if the stack size is ever removed.
README asks whoever lands parallelism to build the rayon pool with a stack
big enough to reach `MAX_NESTING_DEPTH`, because a 2 MiB worker cannot.
Done in `main.rs::build_pool`. Since 2026-08-28 the size is the parser's
own `vlog_parser::PARSE_STACK_SIZE` rather than a literal here, so a
re-measurement of the worst case moves every parse site at once; the pin
test (`a_deeply_nested_file_formats_on_a_worker_thread`) still fails if
the pool's stack size is dropped.
- **Discharges `docs/features/cli-polish/README.md`'s handshake:** that
feature's `catch_panic` swapped the process-global panic hook with
`take_hook`/`set_hook` around every call, and flagged it as sound only
@@ -126,7 +129,9 @@ A path named directly on the command line is never ignored, exactly as with
- [x] `rayon` as the workspace's first third-party dependency, pinned
exactly, justified below.
- [x] Global pool built once at startup with an 8 MiB worker stack.
- [x] Global pool built once at startup with an 8 MiB worker stack
(re-pointed at `vlog_parser::PARSE_STACK_SIZE` on 2026-08-28, when the
worst case was re-measured past what 8 MiB comfortably covers).
- [x] One panic hook installed at startup; `catch_panic` uses a thread-local
flag instead of swapping hooks.
- [x] Per-file loop parallelised; outcomes reported in input order.
+443 -15
View File
@@ -50,16 +50,28 @@ not by 64 × 256.
`parse_unary`), one nested generate `if` costs 2 (`parse_item` +
`parse_gen_if`), one `.b` or one `+` costs 1 link. The limits are a
stack-safety budget, not a style rule.
- **8 MiB of stack is available.** That is the default main-thread stack on
macOS and Linux, and `lucisv` parses on the main thread. Anything that parses
on a *spawned* thread must give it a comparable stack — the default 2 MiB
is not enough to reach the limit in an unoptimized build (see Handshakes;
the tests here spawn 16 MiB threads for exactly this reason).
- ~~**8 MiB of stack is available.**~~ **Retired 2026-08-28 — it is now
enforced, not assumed.** This used to say "8 MiB is the default main-thread
stack on macOS and Linux, and `lucisv` parses on the main thread". Both
halves were hazards: the default is not 8 MiB everywhere (`ulimit -s` in a
container, 1 MiB on Windows), and "parses on the main thread" stopped being
true the moment anything spawned. `MAX_NESTING_DEPTH` bounds how *many*
levels run, not what one costs, so the guard only converts an overflow into
an error on a stack big enough to reach level 64. That size is now a
constant — `vlog_parser::PARSE_STACK_SIZE` — and every thread that can
reach a parse is spawned with it, including the two `main`s. See "The stack
the limit needs" and the parse-site table in Handshakes.
- **Unoptimized builds are the worst case.** Debug stack frames in this
parser are large (`parse_keyword_stmt` alone is a ~50 KiB frame at
`opt-level=0`, because rustc gives every match arm's temporaries their own
slot and does not merge them). The limit is picked for debug builds, so
release builds have an order of magnitude more headroom.
- **Frame sizes drift upward, so the stack constant carries margin, not a
fit.** The same worst case measured ~3.9 MiB in 2026-08 and ~5.9 MiB on
2026-08-28 (rustc 1.97.1) without a line of the parser changing. Nothing in
the build pins a compiler version, and the failure mode is an abort rather
than a diagnostic, so `PARSE_STACK_SIZE` is set at ~2.7× the measured worst
case instead of just above it.
- **Rejecting an over-deep file is acceptable behavior.** The file is left
untouched with a diagnostic and exit 2, exactly like any other parse error.
No real RTL is expected anywhere near the limit; machine-generated
@@ -75,9 +87,16 @@ not by 64 × 256.
```
MAX_NESTING_DEPTH = 64 (crates/vlog_parser/src/parser.rs)
MAX_CHAIN_LENGTH = 256
PARSE_STACK_SIZE = 16 MiB
```
Going one past either produces an ordinary parse error:
The first two bound the input. The third bounds nothing — it is what the
first two *cost*, and it is the size every thread that can reach a parse is
spawned with. The three only work together: a depth limit on a stack too
small to reach it converts nothing, because the overflow (an abort, with no
`Result` to return) happens first.
Going one past either limit produces an ordinary parse error:
```
error: rtl/deep.sv: parse error: 32:5: nesting too deep (limit 64) (found "clk")
@@ -117,9 +136,12 @@ trips the limit (bisected the same way, minimum surviving thread stack):
| nested `{...}` / `(...)` | 983–1047 KiB | 103 KiB |
| `? :` chains, stacked `~` | 135–423 KiB | — |
So the worst case is **~3.9 MiB in a debug build, ~0.5 MiB in release**,
against an 8 MiB main-thread stack: 2× headroom in the profile with the fat
frames, 16× in the profile users actually run.
So the worst case *as measured in 2026-08* is **~3.9 MiB in a debug build,
~0.5 MiB in release**. Both the number and the stack it was compared against
have since been superseded — see "The stack the limit needs" below, which
re-measures it at ~5.9 MiB over a wider family sweep and replaces "the 8 MiB
main-thread stack" with a stated constant. The table is kept because it is
what 64 was chosen from; the choice still holds under the new numbers.
Why not larger: 128 would need ~7.9 MiB in a debug build — i.e. the CLI
integration tests, which run the *debug* binary, would still overflow before
@@ -168,6 +190,62 @@ fits). Charging chain links against `MAX_NESTING_DEPTH` instead would have
capped those at ~60 terms and rejected real code; that is why chains get
their own, larger budget rather than sharing the nesting one.
### The stack the limit needs — re-measured 2026-08-28
Same method as above (subprocess per trial, bisect the smallest thread stack
that survives), but over the *whole* consumer pipeline this time —
`tokenize` → `parse_tolerant` → `analyze` → `FileFacts`, i.e. what the
language server runs, alongside `format_source`. Two things changed since the
2026-08 numbers: the sweep now covers block families the first round did not
(`case`, `fork`, `foreach`, `while`, `for`, nested modules), and the compiler
moved (rustc 1.97.1).
Peak stack on input sized to *trip* the limit — the global worst case, since
tripping it walks one level further than any legal input can:
| family | debug | release |
|---|---|---|
| nested `case` (any flavour: `casez`, `unique`, `inside`) | **6023 KiB** | **823 KiB** |
| nested `case` + `begin` per level | 5847 KiB | 775 KiB |
| `else if` chains | 5751 KiB | 807 KiB |
| nested `if … begin` | 5735 KiB | 775 KiB |
| nested `begin`, `fork`/`join`, labelled `begin : b` | 5591 KiB | 711 KiB |
| `foreach` / `do … while` | 5447 KiB | 679 KiB |
| `while` / `repeat` / `wait` / `assert … else` | 5367 KiB | 663 KiB |
| generate `for` | 3879 KiB | 583 KiB |
| generate `if` | 1895 KiB | 343 KiB |
| nested `(...)` | 1623 KiB | 183 KiB |
| `@(posedge clk)` chains | 1255 KiB | — |
| nested `module` … `endmodule` | 103 KiB | 23 KiB |
So **~5.9 MiB debug, ~0.8 MiB release**, and ~94 KiB per gated level in a
debug build rather than the ~62 KiB measured in 2026-08. Nested `module` is
cheap because item frames are small; `case` is the ceiling because
`parse_keyword_stmt` carries the fattest frame in the grammar and a `case`
spends two of them per source level (the `case` itself, then the arm's
statement).
Three things the same sweep settles:
- **The peak is entirely in the parser.** `analyze` and `FileFacts` measured
byte-identical to `parse_tolerant` alone in every family, and `analyze` run
*by itself* on a max-legal tree (parsed and dropped on a separate large
thread) needs **71 KiB** — ~1.2 KiB per level. It does not need a bound of
its own; it is two orders of magnitude under the walk that produced the
tree. Same for the tolerant recovery: strict and tolerant parses of the
same limit-tripping input bisect to the same byte.
- **Chains still do not move the worst case.** A 256-link chain alone peaks
at 2487 KiB debug (~9 KiB per link); the same chain inside 58 nested `case`
measures 5895 KiB — identical to that nesting without any chain, because
the two peak in different phases. The additive-composition argument above
is unchanged.
- **16 MiB is the constant, and it is margin rather than a fit.** 8 MiB —
what the CLI's pool used and what a stock main thread happens to have —
is 1.33× the debug worst case, and the last two years of this number moving
(3.9 → 5.9 MiB, no parser change) say that is not enough room. 16 MiB is
2.7×, costs address space rather than memory (thread stacks are committed a
page at a time), and is the size the feature's tests already spawned.
## Where the counters sit
`Parser::enter()` / `Parser::leave()` bracket each gated function; `enter`
@@ -286,17 +364,41 @@ not inflate depth — the output of a max-depth file re-parses inside
expression it has already built — the `Box::new(previous)` shape — must
charge `link()`, or it reopens exactly the hole QA found. Loops that push
into a `Vec` widen the tree instead and need nothing.
- **Request to TODO.md §3's parallel-file-processing item (rayon):** rayon
worker threads default to 2 MiB of stack, which is *not* enough to reach
the depth limit in a debug build (~3.9 MiB needed). Whoever lands
parallelism must set `ThreadPoolBuilder::stack_size(8 * 1024 * 1024)` or
larger, otherwise this feature's guarantee silently regresses to a crash.
Same applies to any future LSP server thread that parses.
- **Promised to every consumer: `vlog_parser::PARSE_STACK_SIZE`.** The depth
limit converts an overflow into a diagnostic *only* on a stack of at least
this size. It is a `pub const` next to the two limits, so no consumer picks
a number of its own and none can drift from the measurement. The rule is
one line: **any thread that can reach `tokenize`/`parse`/`analyze` is
spawned with `stack_size(PARSE_STACK_SIZE)`** — including the thread a
`main` hands its work to, because a process's main stack is set by the OS
and `ulimit`, not by us.
- **Request to TODO.md §6's error-tolerant parsing mode:** recovery must not
reset `depth` while unwinding — it is decremented by `leave()` on the way
out of every gated frame, including error paths, and a sync-and-continue
recovery has to resume from the frame it recovered in.
### Every parse site and the stack it runs on
Audited 2026-08-28 by reading every `thread::spawn` / `thread::Builder` /
`ThreadPoolBuilder` / `par_iter` in `crates/` outside `#[cfg(test)]`. This
table is the enforcement: a new row without a stated stack is the bug.
| site | thread | stack |
|---|---|---|
| `lucisv/src/main.rs` — the whole run (`run_stdin`, `run_files`, `run_check`) | spawned `"lucisv"` | `PARSE_STACK_SIZE` |
| `lucisv/src/main.rs::build_pool` — rayon global pool, used by `run_files`' and `lint.rs`' `par_iter` | rayon workers | `PARSE_STACK_SIZE` |
| `lucisv_server/src/main.rs` — the LSP message loop, which analyses every buffer | spawned `"lucisv-main"` | `PARSE_STACK_SIZE` |
| `lucisv_server/src/server.rs::queue` — forwards `Message`s off the rendezvous channel | spawned `"lucisv-queue"` | default; **never parses** (moves messages, touches no server state) |
| `lsp-server`'s `Connection::stdio()` reader/writer | inside the dependency | default; **never parses** (JSON framing only) |
| both `main` threads | OS-given | irrelevant by construction — they only parse arguments and the LSP handshake, then hand off |
Two sites were the actual hole this round closed. The rayon pool was already
sized (`8 * 1024 * 1024`, from the older ~3.9 MiB measurement, now 1.33× a
re-measured worst case and re-pointed at the constant); the two `main`
threads were not sized at all, which is what "8 MiB of stack is available"
assumed away. `lucisv -` and `lucisv check -` format on the calling thread
and never reach the pool at all, so the CLI's spawn is not redundant with it.
## Status / TODO
- [x] Depth counter (`Parser::depth`) + `enter`/`leave` guard pair.
@@ -334,6 +436,34 @@ From QA round 1 (2026-08-19):
one).
- [x] TODO.md §1 recursion-depth item re-checked after the fix.
Round 3 — the stack the limit needs (2026-08-28, from a QA finding on
`vlog_semantic::FileFacts::of`):
- [x] Diagnosis verified by measurement, not by reading: the overflow is in
the parser's own descent, at level ~30 of an in-budget 64, on a 2 MiB
thread. `analyze`, `FileFacts` and the tolerant recovery add nothing to
the peak.
- [x] Worst case re-measured over every nesting family, debug and release,
through both the LSP pipeline and `format_source`: ~5.9 MiB / ~0.8 MiB,
~94 KiB per gated level in debug. New table above.
- [x] `analyze`'s own walk measured on a max-legal tree (71 KiB, ~1.2 KiB per
level) — no second bound needed, and no second limit constant added.
- [x] `PARSE_STACK_SIZE` (16 MiB) added next to the two limits, `pub`, with
the measured rationale and the margin argument.
- [x] Every production parse site audited and given that stack: the CLI's run
thread, the rayon pool, the language server's message loop. Table in
Handshakes; the two threads that do not parse are named there too.
- [x] `MAX_NESTING_DEPTH` left at 64 — the stack fits the limit, not the
other way round.
- [x] Regression tests on controlled stacks: the reported repro through
`FileFacts::of`, a 14-shape block sweep, at-limit parses for the two
fattest families, and the stdin path through the real binary.
- [x] Existing 16 MiB test threads re-pointed at the constant (`parse_deep`,
`format_deep`), so a shrunk guarantee fails the suite.
- [x] Batch/`catch_unwind` behaviour re-checked end-to-end after the change.
- [x] `cargo test --workspace` (2425), `cargo clippy --all-targets`,
`cargo fmt --check` all clean.
## Work log
### 2026-08-19 — dev agent
@@ -468,6 +598,104 @@ Files touched: `crates/vlog_parser/src/parser.rs`,
grew a second pathological file). `cargo clippy --all-targets` silent.
`cargo fmt --check` clean. Same files touched as the first round.
### 2026-08-28 — dev agent, the stack the limit needs
- **Reproduced first, diagnosed second.** Built a scratchpad probe crate
(path-dependencies on the real crates, never inside the repo) that runs one
shape, one depth, one phase on a thread of a chosen size, as a
*subprocess*, so a stack overflow — which aborts and cannot be caught — is
just a non-zero exit to bisect on. The reported input (500 nested `begin`
through `FileFacts::of`) dies on a 2 MiB thread exactly as reported.
- **The lead's reading is confirmed, and sharper than "64 levels is too
much".** Splitting the pipeline into phases, the minimum surviving stack is
*byte-identical* for `parse_tolerant` alone, `parse_tolerant` + `analyze`,
and the full `FileFacts::of`, in all 25 shapes measured — so the peak is
the parser's own descent, and neither `analyze` nor the record-building
adds a frame above it. Strict and tolerant parses of the same input also
bisect to the same byte, so recovery adds nothing either. At ~94 KiB per
gated level the overflow lands around level 30 of an in-budget 64: the
limiter never gets to fire. Nothing was missing a counter.
- **`analyze` measured on its own** (parse and drop the tree on a separate
256 MiB thread, analyse on the thread being bisected) to make sure the
identical numbers were not masking: **71 KiB** on a max-legal tree, ~1.2 KiB
per level. Two orders of magnitude under the parse. So no second bound and,
per the brief, no second limit constant.
- **Swept 25 shapes rather than the reported one**, because the reported one
is not the worst: nested `case` (6023 KiB debug) beats nested `begin`
(5591 KiB), and neither was in the 2026-08 table. Also measured
`casez`/`unique`/`inside` flavours, `case`+`begin` per level, `fork`/`join`,
labelled blocks, `foreach`, `while`, `for`, `repeat`, `wait`, `do … while`,
`assert … else`, `@(posedge)` chains, generate `if`/`for`, nested modules
and nested tasks. Full table above. The old ~3.9 MiB figure is now ~5.9 MiB
on rustc 1.97.1 without a parser change, which is the argument for margin
rather than a fit.
- **`PARSE_STACK_SIZE = 16 MiB`, and one constant for everything.** 8 MiB —
what the rayon pool already used, and what a stock main thread happens to
have — is 1.33× the debug worst case; 16 MiB is 2.7×, costs address space
rather than resident memory, and is the number the feature's own tests were
already spawning. Putting it in `vlog_parser` beside `MAX_NESTING_DEPTH` is
what stops it drifting: the tests now spell the constant instead of
`16 * 1024 * 1024`, so cutting the guarantee below what the limit needs
fails the suite rather than the user.
- **Audited every parse site** (`thread::spawn`, `thread::Builder`,
`ThreadPoolBuilder`, `par_iter` across `crates/`, excluding
`#[cfg(test)]`); table in Handshakes. The rayon pool was the only one that
had a stated stack. The two `main` threads had none — that is what "8 MiB
of stack is available" was assuming, and it is not true on Windows, under a
tuned `ulimit -s`, or for anyone who later moves work onto a thread. Both
`main`s now hand their work to a thread sized by the constant.
- **The CLI's spawn is not redundant with the pool.** `docs/features/
parallel-files` established (with a probe, and re-verified by QA) that
rayon's `par_iter` called from outside the pool *blocks* the caller instead
of running jobs on it. But `lucisv -` and `lucisv check -` never build a
pool at all: they format the buffer on the calling thread. That path had no
stated stack until this change, and it is the one the new CLI test covers.
- **Deliberately not done: lowering `MAX_NESTING_DEPTH`.** Per the brief, and
because it would change which real files parse. The stack fits the limit.
- **Deliberately not done: shrinking the parser's frames.** The 2026-08 round
measured that experiment (extracting one `match` arm moved
`parse_keyword_stmt` 50,528 → 47,872 B) and rejected it; nothing has
changed that calculus, and this round's fix does not need it.
- **Tests, all on controlled stacks so they cannot be flaky across
environments** — `vlog_semantic/tests/deep_nesting.rs` is new
(`five_hundred_nested_blocks_are_indexed_not_aborted` — the reported repro,
which now indexes module `m` with the unparsable body recovered;
`no_block_shape_can_abort_the_parse_stack` — 14 shapes at 400 levels
including nested modules, tasks, functions, fork/join, generate blocks and
else-if chains; `nesting_just_under_the_limit_still_yields_its_facts`).
`vlog_parser` gained `deep_nesting_errors_for_every_block_form` and
`the_fattest_block_forms_still_parse_at_the_limit`; `lucisv` gained
`a_deeply_nested_buffer_from_stdin_is_a_diagnostic_not_a_crash`.
- **Sabotage-verified the new tests the way QA does**: set
`PARSE_STACK_SIZE` to 2 MiB, rebuilt, and `cargo test -p vlog_semantic
--test deep_nesting` died with `SIGABRT` / "fatal runtime error: stack
overflow" instead of failing an assertion — i.e. the tests are pinned to
the constant, not merely passing beside it. Restored and re-ran green.
- **Re-checked the batch/`catch_unwind` claims** end-to-end with the real
debug binary on a 4-file directory (`good`, 500 nested `begin`, 400 nested
`case`, `good`): `2 files reformatted, 2 files failed to format`, exit 2,
both deep files left untouched, no abort. Also drove the real
`lucisv-server` over stdio with the 500-level buffer: `initialize`,
`didOpen`, `publishDiagnostics`, a `documentSymbol` answer naming module
`m`, clean `shutdown`/`exit` 0.
- **Touched two files outside this feature, both because they now contradict
the code:** `docs/features/parallel-files/README.md`'s "8 MiB of worker
stack is enough" assumption and its recursion-limit handshake bullet, and
the same number in TODO.md §3's parallel-file item. Only the living
contract sentences — that feature's work log and QA log are history and
were left alone.
**Results:** `cargo test --workspace` **2425 passed, 0 failed** (up 8: +2
`vlog_parser` unit, +3 `vlog_semantic` `deep_nesting`, +1 `lucisv` CLI, and
two pre-existing helpers re-pointed at the constant). `cargo clippy
--all-targets` silent. `cargo fmt --check` clean. Files touched:
`crates/vlog_parser/src/parser.rs`, `crates/vlog_parser/src/lib.rs`,
`crates/lucisv/src/main.rs`, `crates/lucisv_server/src/main.rs`,
`crates/lucisv_server/src/server.rs` (one doc comment),
`crates/vlog_formatter/tests/deep_nesting.rs`, `crates/lucisv/tests/cli.rs`,
`crates/vlog_semantic/tests/deep_nesting.rs` (new),
`docs/features/parallel-files/README.md`, `TODO.md`, this README.
## QA log
### 2026-08-19 — QA agent
@@ -884,8 +1112,208 @@ No new BLOCKING finding. No code changes made this round (the one finding
is a documentation number, not something I judged a "small unambiguous
fix" worth touching without the dev confirming their construction).
### 2026-08-28 — QA agent, the stack the limit needs
**Tooling results (verbatim):** `cargo fmt --check`: clean, exit 0.
`cargo clippy --all-targets`: silent, no warnings. `cargo test --workspace`:
every binary green, 0 failed across the run (`vlog_parser` lib 1204 passed/23
ignored, `vlog_semantic` 82 + 62 + 3 new `deep_nesting`, `vlog_formatter` 4
`deep_nesting`, `lucisv` 217 + the new stdin test, `lucisv_server` 190 + 20 +
114 + others, doc-tests all 0/0 except `vlog_linter`'s 1/1) — matches the
dev's "2425 passed, 0 failed" claim (one transient doctest failure on a first
run, `vlog_linter`'s, traced to a stale rlib left by my own concurrent
`git stash`/rebuild during the ulimit test below, not a real regression —
reran `cargo test -p vlog_linter --doc` clean on its own and the next full
`cargo test --workspace` was clean too).
**Independent audit of every thread/pool/par_iter outside `#[cfg(test)]`
(charter item 1) — matches the dev's table exactly, no missed site.**
`grep -rn "thread::spawn\|thread::Builder\|ThreadPoolBuilder\|par_iter\|\.spawn("
crates --include="*.rs"` and traced every hit:
- `lucisv/src/main.rs`'s own spawn (the "lucisv" thread) and `build_pool`
(rayon global pool): both `PARSE_STACK_SIZE`, as claimed.
- `lucisv/src/lint.rs:48`'s `jobs.par_iter()` (the `check` subcommand,
charter's "vlog_linter/vlog_refactor entry points from the CLI pool"):
confirmed it runs on the *same* rayon global pool `build_pool` sizes —
`run_check` calls `gather(opts).and_then(|jobs| build_pool(opts).map(...))`
before `lint::check_files`, same as `run_files`. `check`'s stdin path
(`lint::check_stdin`) never touches the pool at all; it runs on `run_check`
called from `run()`, which is the body of the spawned "lucisv" thread — so
it inherits `PARSE_STACK_SIZE` the same way `run_stdin` does. Not a missed
site; the dev's table entry ("the whole run") already covers it, just not
spelled out by name.
- `lucisv_server/src/main.rs`'s spawn and `server.rs::queue`'s forwarder:
match the table.
- `lucisv_server/src/index_cache.rs:921,1194` and `state.rs:3374` (a
`qa_attack_…` test spawning at a deliberate 64 MiB, with a comment citing a
*different*, pre-existing recursion ceiling filed in `index-scope`'s own
2026-08-28 QA log) — all three are inside `#[cfg(test)] mod tests`
(checked with `grep -n "#\[cfg(test)\]"` in each file), so they are
correctly outside the dev's stated audit scope ("outside `#[cfg(test)]`")
and outside production risk. Tried to find a production path to them
anyway (workspace-scan-on-`initialize`, watched-file rescans) — found none;
`index_cache`'s writers only run inside its own test module.
- `lsp-server` 0.10.0's own threads (`stdio.rs`): read the vendored source at
`~/.cargo/registry/src/…/lsp-server-0.10.0/src/stdio.rs` — reader and
writer threads only frame/deframe `Message` (JSON-RPC header parsing via
`usize::parse`, unrelated to `vlog_parser`), no `vlog_parser` symbol
anywhere in the crate. Confirms charter item 2's second half directly from
the dependency's source, not by inference.
- `server.rs::queue` (charter item 2's first half): read `queue()` and
`run()` in full. The forwarder thread's closure captures only
`source`/`sender`, does `source.recv()` → `sender.send()` → break on
`is_shutdown`/`Err`, touches no field of `Server`; `run()` and
`process_batch` are the only things that call `self.request`/
`self.notification` (which reach analysis), and they execute on the
thread `Server::run` was called on, i.e. the spawned `"lucisv-main"`
thread. The module doc at `server.rs:1` ("one burst in, one response per
request, on one thread") holds; `didChangeWatchedFiles` and every other
notification dispatch through `Server::notification` (`server.rs:1249`),
called only from `process_batch`, same thread.
No un-gated production parse-reachable spawn found. Dev's table is accurate
and complete.
**Charter item 3 (library-consumer footgun) — real gap found, fixed
directly as a small unambiguous doc fix.** The README's Handshakes section
states the contract plainly ("any thread that can reach
`tokenize`/`parse`/`analyze` is spawned with `stack_size(PARSE_STACK_SIZE)`"),
but that is an internal project document, not rustdoc — a consumer of
`vlog_parser`/`vlog_semantic`/`vlog_formatter` as a library reads the public
items' own doc comments, and none of them said anything: `vlog_parser::parse`
(`parser.rs:271`), `parse_tolerant` (`parser.rs:283`), `vlog_semantic::
FileFacts::of` (`workspace.rs:741`), `vlog_formatter::format_source`
(`format.rs:80`) and `format_range` (`format.rs:101`) — the five public
entry points that actually recurse over caller-supplied input — carried no
stack-size mention at all. Confirmed by reading each doc comment before this
fix; `tokenize` (`lexer.rs:731`) checked too and correctly excluded — it is
loop-based with no recursion on nesting, so it carries no such requirement.
Added a one- to three-line note to each of the five, referencing
`PARSE_STACK_SIZE` and (except `parse`/`parse_tolerant`, which are right next
to the constant) `docs/features/recursion-limit/README.md`. Files touched:
`crates/vlog_parser/src/parser.rs`, `crates/vlog_semantic/src/workspace.rs`,
`crates/vlog_formatter/src/format.rs`. Re-ran `cargo fmt --check` and
`cargo clippy --all-targets` after — both still clean.
**Charter item 4 (sabotage re-verify), on a scratchpad copy, never the
repo under review.**
- `PARSE_STACK_SIZE` 16 MiB → 2 MiB, rebuilt: `cargo test -p vlog_semantic
--test deep_nesting`, `cargo test -p vlog_formatter --test deep_nesting`
and `cargo test -p vlog_parser --lib` (which builds `parse_deep` on the
same constant) **all SIGABRT** ("stack overflow, aborting", signal 6) —
every deep-nesting test suite genuinely depends on the constant rather
than merely running beside it. Restored to 16 MiB and reran: all three
green again (`vlog_semantic`: 3/3, `vlog_formatter`: 4/4, `vlog_parser`
lib: full suite).
- `MAX_NESTING_DEPTH` 64 → 128, `PARSE_STACK_SIZE` left at 16 MiB (the
"double the limit, keep the stack" margin check): `vlog_semantic`'s
`deep_nesting` (3/3), `vlog_formatter`'s `deep_nesting` (4/4) and
`vlog_parser`'s `nesting_just_below_the_limit_parses`,
`chain_just_below_the_limit_parses`, `the_fattest_block_forms_still_
parse_at_the_limit` and `deep_nesting_errors_for_every_block_form` all
**passed** — including `the_fattest_block_forms_still_parse_at_the_limit`,
which now parses 122-deep `fork`/`case` nesting (`MAX_NESTING_DEPTH - 6`)
on the same 16 MiB stack that only had to reach 58 before. The 2.7×
margin is real, not illusory: it survives doubling the depth the tests
actually walk. Reverted `MAX_NESTING_DEPTH` to 64. Verified afterward that
the working tree's `parser.rs` shows only the intended diff (`grep -n
"MAX_NESTING_DEPTH: u32\|PARSE_STACK_SIZE: usize"` → `64` and
`16 * 1024 * 1024`, matching what `git status` shows for the round under
review).
**Charter item 5 (binary end-to-end) — both scenarios behave as claimed,
and the pre-fix binary was rebuilt to confirm the deviation is load-bearing,
not cosmetic.**
- Directory run: a temp dir with `good.sv` and a 500-nested-`begin` file
through `./target/debug/lucisv .`: `error: ./deep500.sv: parse error:
64:1: nesting too deep (limit 64) (found "begin")` /
`1 file left unchanged, 1 file failed to format`, exit 2. `good.sv`
untouched (it was already formatted), `deep500.sv`'s first 60 bytes
confirmed byte-identical to the input. No abort.
- `ulimit -s 1024; lucisv - < deep500.sv` (1 MiB main-thread stack) on the
**fixed** binary: `error: <stdin>: parse error: 64:1: nesting too deep
(limit 64) (found "begin")`, exit 2, no crash.
- To confirm this isn't true regardless of the fix (i.e. that the moved-main
deviation actually matters, not just the depth counter): stashed the
round's diff (`git stash`, working tree confirmed clean via `git status`),
rebuilt `lucisv`, and ran the identical `ulimit -s 1024` command against
the **pre-fix** binary: `thread 'main' (…) has overflowed its stack /
fatal runtime error: stack overflow, aborting`, exit 134 (SIGABRT) — same
input, same shell, only the binary differs. Popped the stash (`git stash
pop`, confirmed all twelve modified files and the new test file were back)
and rebuilt the fixed binary; reran the same command to reconfirm exit 2.
This is the one experiment in this round that actually falsifies "the
depth counter alone was always going to be enough" — it was not, on a
shell with a small `ulimit -s`, until `main` stopped running on the OS-given
stack.
**Charter item 5, LSP half — independently reproduced via a standalone LSP
client (not the dev's own manual verification, not the checked-in `e2e.rs`
suite, which has no test for this exact repro).** Wrote a small Python
script (framed JSON-RPC over the real `lucisv-server` binary's stdio) that
sends `initialize` → `initialized` → `didOpen` (the 500-nested-`begin` file)
→ `documentSymbol` → `shutdown` → `exit`. Result: `publishDiagnostics` with
`"nesting too deep (limit 64) (found \"begin\")"` at line 63, a second
diagnostic for the resulting `endmodule` mismatch, `documentSymbol` still
answers with module `m` (`range` spanning the whole 564-line file), clean
`shutdown` (`id: 99, result: null`) and process exit code 0. No crash, no
hang, matches the dev's manual claim independently.
**Charter item 6 (idempotency/corruption) — holds.** On the fixed binary:
a 58-nested-`begin` file (one under the dev's stated 59/60 with-statement
boundary — chosen so the *statement* inside costs its extra levels too, same
construction the boundary table uses) formats once, then formats again from
its own output: `diff` reports the two outputs identical, i.e.
`format(format(x)) == format(x)`. The 500-nested-`begin` file piped through
`lucisv -`: stdout is exactly 0 bytes (no partial output), stderr carries
the one-line diagnostic, exit 2 — the "verified-correct output or the input
unchanged with an error, never partial" invariant holds for the rejection
path on the CLI's own thread, consistent with the directory-run and
`vlog_semantic` test evidence that the tolerant/LSP path never produces a
corrupted tree either (recovery yields an `ItemKind::Error` leaf, not
partial/wrong facts).
**Verdict: SHIP.** No blocking or medium finding. One low finding (the
library-consumer stack-size contract living only in an internal README, not
in any public item's rustdoc) fixed directly per CLAUDE.md's "small
unambiguous fix" allowance — five doc comments, no behavior change, gates
re-confirmed clean after. The round's own claims all independently
reproduced: the audit table is complete, the forwarder and `lsp-server`
threads are confirmed parse-free by reading their code (not just trusting
the comment), the stack-size guarantee is real under sabotage in both
directions (shrinking it breaks the tests it should break; doubling the
depth limit under the existing stack does not), and both the CLI and LSP
binaries handle the original repro gracefully end-to-end, including the one
scenario (`ulimit -s 1024`) where the pre-fix binary provably still crashes.
## Review
**2026-08-28 — lead, stack-budget round.** Reviewed after QA's SHIP;
gates re-run independently (fmt clean, clippy silent, 2425 workspace
tests green). The round did the right thing with the diagnosis: nothing
was missing a counter — the 2026-08 feature's own "8 MiB is available"
Assumption was the unenforced hole, and its measured basis had silently
drifted (~62→~94 KiB per level under rustc 1.97, worst family now
nested `case`, never measured in the original round). Turning the
assumption into one code-enforced constant (`PARSE_STACK_SIZE`, 16 MiB,
2.7× over the re-measured worst case) applied at every parse-reaching
spawn site is the boring fix the situation wanted; the dev's deviation
of moving both binaries' work off the main thread is load-bearing, not
cosmetic — QA proved the pre-fix binary aborts under `ulimit -s 1024`
where the fixed one emits a diagnostic, and the win32 target's 1 MiB
default main stack made this a real shipped-binary risk, not just a
test-thread artifact. QA's independent spawn-site audit matched the
dev's table exactly, the sabotage runs prove the tests exercise the
guarantee (2 MiB → SIGABRT) and the margin survives doubling the depth
limit, and its doc fix — the caller-side stack contract on every public
parse entry point's rustdoc — closes the library-consumer footgun the
lead's charter flagged. Invariant 1 spot-checks (no partial output on
rejection, idempotent round-trip at depth) held. Accepted; committed by
the lead.
**2026-08-19 — lead. Verdict: accepted and committed after one rejection
and a verified rework.**
+357 -1
View File
@@ -116,10 +116,55 @@ standard capability both VS Code's built-in client and Neovim's `vim.lsp`
consume on their own once it is advertised; no extension change was needed
and none was made.
**Requested of other modules**: none.
**Requested of other modules (2026-08-28) — DELIVERED 2026-08-28** by the
index-scope round; see `docs/features/index-scope/README.md`, work log
"a rescan stops re-parsing what is already analyzed". An open buffer's index
facts and completion words now come from the analysis it already holds
(`FileFacts::from_analysis`, `words_of_tokens`), on the whole-rebuild path and
on `update_one`'s: **~228 ms → ~23 ms** on this feature's own probe. The request
as it was written:
**Requested of other modules (2026-08-28):** a scope-widening `didOpen`
re-parses every open buffer. `Workspace::collect_sources`
(`crates/lucisv_server/src/state.rs`) clones each open document's text into the
list the index is rebuilt from, so a rescan triggered by opening some *other*
file pays a full lex-and-parse of every buffer the user has open — measured at
**210 ms of a 223 ms rescan** for one 1.4 MB `top.sv`, against 13 ms for the
same 401-file scope with that buffer closed. Every open buffer already holds a
finished parse and `Semantics`; `FileFacts::of` re-does both from the text.
This is `index-scope` / `state.rs` territory, not this feature's, and the
2026-08-28 brief said measure it and stop — so it is written here rather than
changed. The obvious shape (an `IndexBuilder::add_facts` path fed from the
buffer's existing analysis instead of its text) is a real option and a separate
decision.
## Status / TODO
- [x] **References latency with a big buffer open (2026-08-28):** measure both
directions of a cross-file references request while a 1.4 MB, 40 000-line
`top.sv` is an open document, then fix what the numbers convict. Landed:
a **spelled-name prefilter** and a **hoisted `file_id`** in
`indexed_references`'s open-document overlay loop, and **walker-batched**
span conversion in the two in-file fallbacks. Release probes:
**3.20 ms → 110 µs** from the use site, **3.18 ms → 110 µs** from the
declaration (29×); the in-file fallback for a signal used 10 001 times,
**1.76 ms → 1.18 ms**, and `documentHighlight` on it **1.54 ms → 917 µs**.
No answer changes — the equivalence test against
`vlog_refactor::find_references` and the whole nav suite are untouched
and green.
- [x] **Not this feature's to fix, measured and filed (2026-08-28) — fixed
elsewhere the same day:** the owner-reported *asymmetry* is not in
`references` at all — both directions cost the same, before and after.
What is expensive is the `didOpen` that jumping into another folder's
file triggers: **220 ms**, of which **210 ms** is re-parsing the open big
buffer during the scope-widening rescan. See the work log and
Handshakes. Landed by `index-scope` on 2026-08-28 — the open buffer's
facts and words now come from its own finished analysis — and this
feature's `qa_didopen_latency_when_a_new_folder_widens_the_scope` probe
reads **~228 ms → ~23 ms**, with its closed-buffer floor unmoved at
~12 ms. The probe now also prints the buffer's own share of a rescan,
before and after, on every run.
- [x] **Indexed navigation performance (2026-08-27):** persist each file's
externally reachable reference facts beside its declarations, merge them
into declaration-to-occurrence postings in `WorkspaceIndex`, and route
@@ -165,6 +210,147 @@ and none was made.
## Work log
### 2026-08-28 — references latency with a big buffer open
The owner reported find-references from a *use site* in a big open `top.sv`
toward a module as "still very slow", and the same request from the module's
*declaration* toward its uses as fast. Both run the same
`indexed_references`, so the asymmetry was unexplained. Measured first.
**The fixture.** Two `#[ignore]`d probes in `nav.rs`'s own test module, beside
the `qa_indexed_references_latency_over_a_large_workspace` probe that has been
there since 2026-08-27, and taken with `perf::mean` (now `pub(crate)`) so every
number in this repo is timed the same way. `generated_top(10_000, 4)` is a
40 000-line, 1 374 KB module of ordinary RTL blocks — a wire, an assign, a
register and its update — carrying **70 024 references**, four instantiations
of a small `sub`, and one local `acc` used by every block so the file also has
a *local* name with 10 001 occurrences. Both files are open documents; the
index is built over the directory.
```text
cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored --nocapture --test-threads=1
```
Machine: the one `docs/perf/README.md` records — Apple M1 Max, macOS 27.0,
`--release`. Means of 20 runs (5 for the rescan rows).
| what | before | after |
|---|---|---|
| `references` from the **use site** in `top.sv`, `includeDeclaration` | **3.20 ms** | **110 µs** |
| `references` from the **declaration** in `sub.sv`, same | **3.18 ms** | **110 µs** |
| `definition` from the use site | 1.21 µs | 1.13 µs |
| `references` on a local wire used 3× (the in-file fallback) | 1.49 µs | 1.20 µs |
| `references` on a local wire used 10 001× | **1.76 ms** | **1.18 ms** |
| `documentHighlight` on that same wire | **1.54 ms** | **917 µs** |
**Hypothesis 1 is convicted, and it is symmetric.** The open-document overlay
loop was the whole 3.2 ms: for every one of the 70 024 references in the open
buffer it ran either `indexed_def_for_symbol` — a `file_id` binary search whose
comparisons are whole-path `cmp`s, plus a `units`/`member` `BTreeMap` lookup,
plus a scope-and-owner chase — or a `doc.external` hash lookup, to discard all
but five of them. It cost that whichever end the cursor was on, which is the
first thing the measurement says: **the two directions are within 1 % of each
other, before and after.** The owner's asymmetry is not in `references`.
**Hypothesis 2 registers, but only for a common local name.** The in-file
fallback and `documentHighlight` convert their spans one at a time with
`positions.range`, which re-measures a line per span. On three occurrences that
is 1.5 µs and invisible; on 10 001 it is 1.76 ms. Both now batch-convert with
`positions.walker()` over the already-sorted span list, exactly as `locations`
has done for the cross-file answer since this feature shipped — 1.5× and 1.7×.
The rest of those two figures is collecting, sorting and allocating 10 001
spans, which is the answer's own size and not something to shave here.
**Hypothesis 3 is where the felt latency actually is** — measured, and
deliberately not redesigned this round (see Handshakes). With the same 1.4 MB
buffer open and 401 files in scope:
| `didOpen` | cost |
|---|---|
| a file the folder scope **already covers** | **8.4 µs** |
| a file in a **new folder** (`didOpen` + the rescan `server.rs` then runs) | **220 ms** |
| — the rescan alone | 223 ms |
| — the same rescan with the big buffer **closed** | **13 ms** |
So the scope-widening rescan is 223 ms, and **210 ms of it is the open big
buffer**: `Workspace::collect_sources` clones every open document's text into
the source list and the index re-parses it, at full lex-and-parse cost, on a
rescan that was triggered by an entirely different file. That is the shape that
matches the owner's report: F12 or a references result *from* `top.sv` opens the
module's file, and when that file lives in a folder the folder scope had not
reached, the `didOpen` widens the scope and pays a whole rescan. The reverse
direction — standing on the declaration and listing its uses — opens nothing
new and pays nothing. Filed as a Handshake request against `index-scope` /
`state.rs`; no scope code was touched.
**The prefilter, and why it changes no answer.** The new first line of the
overlay loop is `if reference.name != target.name { continue }`. It is sound
because *a `Def` in this index determines the name it is filed under*, and both
sides of the old comparison are filed under a name the code already has in
hand:
- Every indexed `Def` is pushed into `units[name]` or `members[unit][name]`
under its own declaration's `name`, and both `facts_of` and `collect_members`
skip any declaration whose `name_span` is empty. A non-empty byte range in
one file is one identifier, spelling one name — so two different keys cannot
hold one `Def` value, and `target.def`'s key is `target.name` in both
`indexed_target` arms (the `Local` arm looks the def up *by* `symbol.name`
and stores that as `name`; the `External` arm stores the cursor reference's
own `name`, which is the only key `follow_one` looks a def up under).
- A reference that would have matched is filed under `reference.name`. In the
Local arm, a `Resolution::Resolved` comes from `lookup_local(name)` (or an
end label the binder checked spells the declaration's name), so
`symbol.name == reference.name`, and `indexed_def_in_file` looks up
`units[symbol.name]` / `members[owner][symbol.name]`. In the External arm,
`resolve_external` calls `follow_one(index, reference.name, path)`, which
only ever reads `units[reference.name]` or `member(unit, reference.name)`.
So `def == target.def` implies `reference.name == target.name`, and skipping
the name-mismatched references skips only work whose answer was `false`.
**The `Ambiguous` refusal survives it**, by the same step: the candidates in
`ExternalTarget::Ambiguous(defs)` all come out of the bucket keyed by
`reference.name`, so `defs.contains(&target.def)` can only be true for a
reference spelling `target.name` — which the prefilter always lets through. The
`name_span.is_empty()` guard was deliberately *not* hoisted into the prefilter
for the same reason: an ambiguous use aborts the whole collection whether or not
it has a span, and moving that check earlier would have been a real behaviour
change.
**The hoist.** `indexed_def_for_symbol` is now two functions: the public one
(unchanged signature, still `hover.rs`'s) resolves the document's `FileId` and
calls `indexed_def_in_file`, which takes it as an argument. The overlay loop
takes the `file_id` once per open buffer instead of once per reference.
**What is left at 110 µs** is the loop itself: 70 024 string comparisons plus
the iteration. Making that sublinear means a name-keyed reference side table in
`Semantics` — the shape `symbols_named` already has for declarations — which is
a `vlog_semantic` change this round's brief put out of scope. Not needed at
110 µs; worth naming as the next lever if a file ten times this size shows up.
**Tests added** (permanent, all three green before and after the change, which
is the point — the prefilter must change cost and not answers):
- `a_same_named_port_in_another_open_buffer_is_a_different_symbol` — two
modules declare a port `clk`, all three files open; each port's references
are its own. The prefilter's risk case, from both sides.
- `two_packages_declaring_one_name_keep_their_references_apart` — the same
attack through the member table: `p::WIDTH` and `q::WIDTH` used on adjacent
lines of one open file, asked from the declaration and from the use.
- `every_in_file_occurrence_is_converted_against_its_own_line` — 41
occurrences over 40 lines each carrying a multi-byte and an astral character;
every reported range is checked to point at the name, and
`documentHighlight`'s ranges are asserted equal to `references`'. A walker
handed spans out of order would answer stale columns here.
**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets`
zero warnings; `cargo test --workspace` **2 406 passed, 0 failed** (3 ignored
probes in `nav.rs`, one of them pre-existing). Files edited:
`crates/lucisv_server/src/nav.rs` and one `pub(crate)` on `perf::mean`. No new
dependencies, no `unsafe`, no `unwrap`/`expect` outside `#[cfg(test)]`, no new
`#[allow]`. `TODO.md` untouched — this round closes no backlog item; M7 is
already checked. Did not `git commit`/`git push`.
### 2026-08-27 — indexed navigation performance
- Began replacing the per-request `Workspace::sources()` +
@@ -270,6 +456,158 @@ Files added: `crates/vlog_refactor/src/references.rs`,
## QA log
### 2026-08-28 — QA agent, references-latency round
Adversarial charter: try to make the new spelled-name prefilter (`nav.rs:248`,
`indexed_references`) **change an answer**. Slower-but-right was already true;
only a changed answer is a defect this round.
#### Soundness of the prefilter — traced by construction, not just trusted
Read the dev's write-up's claim against the actual code that makes it true,
rather than the prose alone:
- `Def` (`crates/vlog_semantic/src/workspace.rs:33`) derives `PartialEq` over
`(file, name_span, kind, detail_span)` — it carries no name at all. Its
identity is "this declaration, right here," so `def == target.def` can only
be decided by the site it points at, never by a spelling.
- Every `Decl` is filed under exactly one key, its own declared name:
`self.units.entry(decl.name.clone())...push(decl.def(file))`
(`workspace.rs:529`) and `self.members.entry(unit.clone())...entry(decl.name.clone())...push(decl.def(file))`
(`workspace.rs:535-540`). `decl.name` traces back to `Symbol.name`
(`Decl::of`, `workspace.rs:654`), and `Symbol.name`/the scope's `names` map
key are the same `name.to_string()` written in one `declare` call
(`bind.rs:141` and `bind.rs:151`) — so a `Def` cannot be filed under a name
it wasn't declared with, and cannot be filed under two names.
- `Scope::lookup_local` (`model.rs:215`) is a plain `HashMap<String,
SymbolId>` `get` — no case-folding, no normalization. Every
`Resolution::Resolved(id)` in `resolve.rs` comes from `lookup_local(&p.name)`
(or `Target::Declaration(id)`, an end label the binder already matched to
its opener's name). `Reference.name` is `p.name.clone()` at the exact
construction site (`lib.rs:78-79`). So a **locally** resolved reference's
`.name` is *definitionally* `symbol.name` — the prefilter reads the same
field the binder used to decide the match, not a second, potentially
divergent, source of truth.
- The **external** arm is the same shape one level up: `resolve_external`
(`workspace.rs:1097`) always calls `follow_paths(index, &reference.name,
paths)`, and `follow_one` (`workspace.rs:1132`) always queries
`index.units(name)` or `index.member(unit, name)` with that same `name` —
`path` only picks *which* table, never the key. So both `Resolved(def)` and
`Ambiguous(defs)` for a reference are always drawn from the bucket keyed by
that reference's own `.name`, which makes the dev's ambiguity-survives
argument mechanical rather than incidental: `defs.contains(&target.def)`
can only be true when `defs` came from the `target.name` bucket, which only
happens when `reference.name == target.name` — exactly what the prefilter
already let through.
No escaped-identifier or case-folding attack survives this: the lexer
(`crates/vlog_parser/src/lexer.rs:304-318`) keeps an escaped identifier's
leading backslash in the token text (`\sub` and `sub` are different strings
at the token level already), and nothing between the lexer and
`Scope::names` ever folds case or strips it — so whatever the binder already
does or doesn't unify, the prefilter reads the identical field the binder
matched on. There is no code path where `reference.name` and the spelling the
binder used to resolve it can diverge, so there is no daylight for the
prefilter to exploit. Traced, not fuzzed — I did not find a construction
worth writing as a failing-if-regressed test beyond what's below, because the
invariant is enforced by there being exactly one string in play, not by a
check that could later be weakened unnoticed.
**Verdict on the prefilter: sound, no answer-changing case found.**
#### Attempts to break it anyway
- **Port connection vs. declared name, member-table variant.** Extended the
attack beyond the dev's own two tests (`a_same_named_port_in_another_open_buffer_is_a_different_symbol`,
`two_packages_declaring_one_name_keep_their_references_apart`) with a name
that is a **unit in one file and a member in another** — `module W` and
`package p; localparam W = 4;` — plus a **live unsaved edit** to the file
using both (a second instantiation added post-open, never saved). Added as
`indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member`
(`nav.rs:662`), asserted equal to `vlog_refactor::find_references` on
`ws.sources()` (which itself overlays the unsaved edit) in both directions.
Passed first try — no answer conflation between the `units` and `members`
buckets, and the unsaved instantiation is correctly counted.
- **Walker ordering/multi-byte/astral attack** on the two newly-batched
conversion sites (`in_file_references` and `document_highlights`, now both
walker-based per `nav.rs:347` and `nav.rs:374`). The dev's own
`every_in_file_occurrence_is_converted_against_its_own_line` already covers
this shape well (41 occurrences over 40 lines, each preceded by a
multi-byte and an astral character, every reported range checked against
the actual byte); I did not find a shape it misses. The walker itself
(`crates/lucisv_server/src/convert.rs`, `PositionWalker`) is pre-existing,
general-purpose infrastructure (`locations()` has used it since the
2026-08-27 round) with its own dedicated tests for out-of-order offsets,
ping-ponging between far-apart lines, and an empty document
(`the_walker_agrees_with_the_per_call_converter_on_every_shape`,
`a_walker_handed_offsets_out_of_order_still_answers_the_per_call_position`,
`a_walker_ping_ponged_between_two_far_apart_lines_still_answers_correctly`,
`a_walker_over_an_empty_document_answers_the_one_position_there_is`, all in
`convert.rs`) — so the only new risk this round is whether
`in_file_references`/`document_highlights` feed it spans in order, and they
do: both consume `occurrences()`, which sorts by `span.start`
(`nav.rs:413`) before the walker ever sees them. No out-of-order feed
exists on either path.
- **Ambiguous-abort still aborts.** Re-ran
`a_name_declared_in_two_files_degrades_references_to_the_in_file_answer`
(already in the suite, unmodified by the dev this round) and traced the
`Ambiguous(defs) if defs.contains(&target.def) => return None` arm
(`nav.rs:258-260`) by hand against the bucket argument above: an ambiguous
external use can only carry `target.def` in its candidate set when it
spells `target.name`, which is exactly when the prefilter lets it reach
this arm. Confirmed by construction, not just by the still-green test.
- **Equivalence, existing test.** `indexed_references_equal_the_refactor_walk_they_replace`
(`nav.rs:648`, pre-dating this round) still passes unmodified.
#### Measurements reproduced (release, `--release`, this machine)
```
cargo test --release -p lucisv_server nav::tests::qa_ -- --ignored --nocapture --test-threads=1
```
| what | work log | reproduced here |
|---|---|---|
| references, use site | 110 µs | 109.8 µs |
| references, declaration | 110 µs | 108.9 µs |
| definition, use site | 1.13 µs | 0.82 µs |
| in-file, wire used 3× | 1.20 µs | 1.12 µs |
| in-file, wire used 10 001× | 1.18 ms | 1.17 ms |
| documentHighlight, same wire | 917 µs | 916 µs |
| didOpen, scope already covers | 8.4 µs | 7.3 µs |
| didOpen, new folder (+ rescan) | 220 ms | 214.6 ms |
| rescan alone | 223 ms | 217.7 ms |
| rescan, big buffer closed | 13 ms | 12.5 ms |
All within the charter's 2-3× tolerance (most within 5%) — no contradiction
of the work log's order-of-magnitude claims. The pre-existing
`qa_indexed_references_latency_over_a_large_workspace` probe (2026-08-27,
untouched by this round) also still ran clean: 0.068 ms/request vs. 31.35 ms
for the old walk on this machine, consistent with that round's own numbers.
#### Gates
- `cargo fmt --all -- --check` — clean.
- `cargo clippy --all-targets --all-features` — clean, zero warnings (forced
re-check by `touch`ing the changed files first, not a cache hit).
- `cargo test --workspace` — **2 406 passed, 0 failed** before my addition,
matching the work log's count exactly; **2 407** after adding the one
permanent equivalence test above. 24 ignored across the workspace (3 in
`nav.rs`, one of those pre-existing, matching the work log).
**All gates: pass, claims confirmed.**
#### Verdict
**SHIP.** No corruption, no answer change, no crash found under the
adversarial charter. The prefilter's soundness holds by construction (one
string, read by both the binder and the prefilter, never normalized or
duplicated anywhere in between), not merely by the tests passing. One
permanent regression test added
(`indexed_references_equal_the_refactor_walk_for_a_name_thats_both_a_unit_and_a_member`,
`nav.rs:662`) for the nastier unit/member name-collision case with a live
unsaved edit, requested by the round's brief; no other findings warranted a
fix or a new test. Review section left untouched.
### 2026-08-24 — QA agent
#### Gates
@@ -522,6 +860,24 @@ correctness or safety issue in the shipped feature.
## Review
**2026-08-28 — lead, references-latency round.** Reviewed after QA's
clean SHIP; gates re-run independently (fmt clean, clippy silent, 2407
workspace tests green). Measure-first discipline held: the probes were
written and their before-numbers recorded ahead of any fix, and they
convicted the overlay loop (H1) while acquitting `references` of the
owner-reported asymmetry — which the didOpen numbers (H3) explain
instead, correctly filed as a Handshake request rather than fixed
cross-scope. The prefilter comment in `indexed_references` points at
the soundness argument, QA traced that argument to the code
(single-key filing, no name normalization anywhere between lexer and
lookup), and the unit-vs-member equivalence test QA added is the
sharpest same-spelling case the design admits. The empty-span check
deliberately left unhoisted — so a spanless ambiguous use still aborts
— is the kind of detail that separates a fast loop from a subtly
different one; noted with approval. Accepted; the scope-widening
rescan follow-up (210 ms of re-parsing open buffers) is the next
round.
**2026-08-27 — lead, indexed-navigation performance round (external dev:
codex).** Reviewed the full diff line-by-line and ran all three gates
independently (fmt clean, clippy silent, 1155 server tests + workspace
+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
+30
View File
@@ -5,6 +5,36 @@ 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.
- **Find References with a huge file open is ~30× faster** (3.2 ms →
0.11 ms on a 70 000-reference buffer), and in-file references and
occurrence highlighting on heavily used signals are ~40 % faster.
- **Jumping into a new folder is ~10× faster.** The index rescan that a
scope-widening jump triggers now reuses what your open buffers already
analyzed instead of re-parsing them: ~228 ms → ~23 ms with a 1.4 MB
file open.
- **Pathologically nested files can no longer crash the tools.** ~500
nested `begin`/`end` (or `case`, `fork`, generate…) blocks now produce
an ordinary "nesting too deep" diagnostic on every platform, including
Windows, instead of risking an abort.
## 0.13.0 — 2026-08-28
- **Typing no longer reanalyzes on every keystroke.** The buffer's analysis is
+23 -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.0**. 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,28 @@ 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:
- Find References with a big file open answers in ~0.1 ms where it took
milliseconds, and jumping into a not-yet-indexed folder costs ~23 ms
where it took ~228 ms — the rescan reuses what open buffers already
analyzed.
- Deeply nested files produce a "nesting too deep" diagnostic instead of
ever crashing the server or CLI, on every platform.
## Release 0.13.0 highlights
Version 0.13.0 is the responsiveness release. Typing no longer reanalyzes the
+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.0",
"version": "0.14.0",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",