Compare commits

...
4 Commits
Author SHA1 Message Date
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
28 changed files with 3030 additions and 107 deletions

No files matched your search

+36
View File
@@ -4,6 +4,42 @@ 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.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.13.1"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.13.0"
version = "0.13.1"
[[package]]
name = "lucisv_server"
version = "0.13.0"
version = "0.13.1"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.13.0"
version = "0.13.1"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.13.0"
version = "0.13.1"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.13.0"
version = "0.13.1"
[[package]]
name = "vlog_refactor"
version = "0.13.0"
version = "0.13.1"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.13.0"
version = "0.13.1"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.13.0"
version = "0.13.1"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+11 -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.
@@ -622,6 +622,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 +808,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");
+37 -7
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,15 @@ 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_in(text));
self.set_words(path, words);
}
/// Drop one file's contribution entirely.
@@ -214,6 +234,16 @@ fn words_in(text: &str) -> Vec<String> {
// 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 +319,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 +438,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 +461,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";
+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");
+5 -1
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();
+13 -1
View File
@@ -327,7 +327,9 @@ impl Server {
/// `handle_shutdown` reads the `exit` notification off the *connection*
/// itself — a forwarder that kept going would steal it and strand the
/// handshake for thirty seconds. It owns nothing but messages in flight
/// and touches no server state.
/// and touches no server state — and it never parses, which is why it is
/// the one thread the server spawns without
/// `vlog_parser::PARSE_STACK_SIZE` (`docs/features/recursion-limit`).
fn queue(&self) -> std::sync::mpsc::Receiver<Message> {
let (sender, receiver) = std::sync::mpsc::channel();
let source = self.connection.receiver.clone();
@@ -1948,6 +1950,16 @@ impl<'a> IndexWatch<'a> {
self.say(format!("cached: {}", path.display()));
self.tick(done, total, path);
}
// A third word, and no count in the end message: an open buffer's
// own analysis costs nothing either, but one file out of a
// workspace is not why a scan finished fast, and a bar that grew a
// clause on every session with a file open would say less, not
// more. The per-file log still names it, which is where a user
// asking "did it re-parse my huge buffer?" looks.
IndexEvent::Analyzed { done, total, path } => {
self.say(format!("analyzed: {}", path.display()));
self.tick(done, total, path);
}
IndexEvent::Skipped { path, size, cap } => {
self.skipped += 1;
self.say(format!(
+534 -16
View File
@@ -3,7 +3,7 @@
//! `docs/features/lucisv-server/README.md`; the short version is that a buffer's
//! analysis is rebuilt on every change and the index only on save.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
@@ -135,6 +135,30 @@ impl Document {
pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) {
self.external = resolve_external(&self.semantics, index);
}
/// What this buffer contributes to the workspace index, read off the
/// analysis it already holds instead of from its text.
///
/// [`FileFacts::of`] is `tokenize` + `parse_tolerant` + `analyze` followed
/// by the fact walk, and the first three are exactly what [`Document::new`]
/// already did to fill `tree`, `defines` and `semantics` — from the same
/// text, with the same functions, down to the lex-failure branch. So this
/// is `FileFacts::of(path, &self.text)` with the parse already paid for,
/// not a second way of computing it
/// (`an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus`).
///
/// Never called for a buffer on the large-file fast path: its analysis is
/// the analysis of the empty file, and such a buffer contributes nothing to
/// the index at all (see `collect_sources`).
pub fn facts(&self, path: PathBuf) -> FileFacts {
FileFacts::from_analysis(path, &self.tree, &self.defines, &self.semantics)
}
/// The completion words this buffer contributes, read off the tokens it was
/// analyzed from rather than by lexing its text a second time.
pub fn words(&self) -> Vec<String> {
crate::candidates::words_of_tokens(&self.tokens)
}
}
// ----------------------------------------------------------------------
@@ -205,10 +229,36 @@ struct Scope {
/// A `Scope` with its files read: what one index rebuild works from.
struct Sources {
texts: Vec<(PathBuf, String)>,
/// What the open buffers among `texts` already know about themselves.
analyzed: Analyzed,
incdirs: Vec<PathBuf>,
warnings: Vec<String>,
}
/// The index facts and the completion words of the entries `texts` took from an
/// **open buffer**, read off the analysis that buffer already holds.
///
/// Both maps are filled in the same loop that lets a buffer override the disk
/// copy, so an entry here is always the analysis of exactly the text beside it
/// in `texts` — the two cannot describe different bytes. A file that is not an
/// open buffer appears in neither map and is parsed and lexed as it always was.
#[derive(Default)]
struct Analyzed {
facts: HashMap<PathBuf, FileFacts>,
words: HashMap<PathBuf, Vec<String>>,
}
/// Whether a caller of `collect_sources` wants [`Analyzed`] filled in.
///
/// An index rebuild does — it is what it indexes the open buffers from. A
/// refactoring reads the texts and nothing else, and reading a record off every
/// open buffer for it would be work nothing looks at.
#[derive(PartialEq, Eq)]
enum HeldAnalyses {
Wanted,
Unused,
}
/// What an index rebuild reports about itself as it runs.
///
/// This module speaks no protocol, so an event carries numbers and paths and
@@ -226,6 +276,18 @@ pub enum IndexEvent<'a> {
/// there that differs, and a user watching a rescan fly through a
/// thousand files deserves to be told why.
Cached { done: usize, total: usize, path: &'a Path },
/// One file went into the index from the analysis an **open buffer**
/// already holds — the parse this server did when the buffer was last
/// opened or changed — instead of being parsed again. The same three
/// numbers the other two carry, for the same reason.
///
/// Its own variant rather than [`IndexEvent::Cached`] so that "from cache"
/// keeps meaning the persistent store and nothing else
/// (`docs/features/index-persistence/README.md`): a buffer's own analysis
/// is in memory, is there whether that store exists or not, and is right
/// even when the buffer has unsaved edits — which is exactly when a
/// content-keyed store has nothing to offer.
Analyzed { done: usize, total: usize, path: &'a Path },
/// A walked file was skipped without being read, because it is bigger
/// than the size cap in force.
Skipped { path: &'a Path, size: u64, cap: u64 },
@@ -603,8 +665,9 @@ impl Workspace {
/// reported: they cost a small fraction of the parse, and a bar that went
/// to 100% and then sat there would be worse than one that ends.
pub fn rebuild_index_with(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Vec<String> {
let scope = self.collect_sources(watch);
let sources = scope.texts;
let mut scope = self.collect_sources(watch, HeldAnalyses::Wanted);
let sources = std::mem::take(&mut scope.texts);
let mut analyzed = std::mem::take(&mut scope.analyzed);
// The same list the index will be built from — asked of
// `vlog_semantic` rather than re-derived here, so the count reported
// is the count parsed — with the user's own open files moved to the
@@ -619,6 +682,19 @@ impl Workspace {
self.cache = IndexCache::open(self.cache_dir());
let mut builder = IndexBuilder::new();
for (done, (path, text)) in ordered.into_iter().enumerate() {
// An open buffer's own finished analysis comes first. It describes
// the exact bytes about to be indexed — `collect_sources` took the
// record and the text from the same `Document` in the same loop —
// and it is the only source of facts that is right when the buffer
// has unsaved edits, which is precisely when the content-keyed
// cache below has nothing to offer. The record is written through
// all the same, so the next session starts from it.
if let Some(facts) = analyzed.facts.remove(&path) {
watch(IndexEvent::Analyzed { done, total, path: &path });
self.cache.record(&facts, text);
builder.add_facts(facts);
continue;
}
// The cache answers for the exact bytes about to be indexed, so a
// hit is the parse and not a guess at it. A miss — a new file, a
// changed one, a record this version cannot read — parses, and
@@ -643,7 +719,7 @@ impl Workspace {
self.cache.compact();
// Built here, from the same list, so a file the scope ladder excluded
// contributes no completion candidates either.
self.candidates = Candidates::build(&self.index, &sources);
self.candidates = Candidates::build(&self.index, &sources, analyzed.words);
// Same list again: an `` `include`` in a file the scope excluded is
// not an edge, and a file it excluded is not a hop away from anything.
self.includes = IncludeGraph::build(&sources, scope.incdirs);
@@ -685,8 +761,22 @@ impl Workspace {
}
match self.current_text(path) {
Some(text) => {
self.index.update_file(path.to_path_buf(), &text);
self.candidates.update_file(&self.index, path, &text);
// The same rule a whole rebuild follows: when the text came
// from an open buffer, that buffer's finished analysis is the
// facts and the words, and neither is derived from the text a
// second time. `current_text` answers with a buffer's text only
// when that buffer is not on the large-file fast path, so the
// analysis found here is a real one.
match self.analysis_of(path) {
Some((facts, words)) => {
self.index.update_facts(facts);
self.candidates.update_words(&self.index, path, words);
}
None => {
self.index.update_file(path.to_path_buf(), &text);
self.candidates.update_file(&self.index, path, &text);
}
}
self.includes.update_file(path, &text, self.index.files());
// Written through here too, so an hour of saves is an hour of
// work the next session does not repeat. The record is the
@@ -733,6 +823,18 @@ impl Workspace {
true
}
/// The index facts and the completion words of the open buffer backing
/// `path`, read off the analysis it already holds — `None` when no buffer
/// does, or when the one that does is on the large-file fast path and has
/// no analysis of its own text to read.
///
/// The buffer is found the same way [`Workspace::current_text`] finds the
/// text, so the two always speak for the same `Document`.
fn analysis_of(&self, path: &Path) -> Option<(FileFacts, Vec<String>)> {
let doc = self.docs.values().find(|doc| doc.path.as_deref() == Some(path))?;
(!doc.large).then(|| (doc.facts(path.to_path_buf()), doc.words()))
}
/// The text one in-scope file contributes right now, by `collect_sources`'s
/// rules — `None` when it contributes nothing at all.
fn current_text(&self, path: &Path) -> Option<String> {
@@ -770,7 +872,7 @@ impl Workspace {
/// kept: a refactoring is a rare, user-initiated request, and a second
/// copy of the workspace in memory is a high price for saving one walk.
pub fn sources(&self) -> Vec<(PathBuf, String)> {
self.collect_sources(&mut |_| {}).texts
self.collect_sources(&mut |_| {}, HeldAnalyses::Unused).texts
}
/// Read every in-scope file, with open buffers overriding disk.
@@ -786,15 +888,29 @@ impl Workspace {
/// cap keeps out of the index is also a file a workspace rename will not
/// rewrite. That is the consistent answer: the cap says which files exist
/// as far as this server is concerned.
fn collect_sources(&self, watch: &mut dyn FnMut(IndexEvent)) -> Sources {
fn collect_sources(
&self,
watch: &mut dyn FnMut(IndexEvent),
analyses: HeldAnalyses,
) -> Sources {
let scope = self.source_files();
let cap = self.client.max_file_size;
// Every path an open buffer speaks for. Reading such a file from disk
// is work thrown away — the buffer's text replaces it below, whatever
// the disk says — so the read is skipped rather than undone. The cap is
// still consulted first, so an oversized file still reports itself
// skipped exactly as it did before the buffer put its own text back.
let spoken_for: HashSet<&Path> =
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
let mut texts: Vec<(PathBuf, String)> = Vec::new();
for path in scope.files {
if let Some(size) = oversize(&path, cap) {
watch(IndexEvent::Skipped { path: &path, size, cap });
continue;
}
if spoken_for.contains(path.as_path()) {
continue;
}
if let Ok(text) = fs::read_to_string(&path) {
texts.push((path, text));
}
@@ -810,14 +926,19 @@ impl Workspace {
// longer has. See `docs/features/large-file-mode/README.md` for the
// interaction with `lucisv.index.maxFileSize`, whose "an open buffer is
// never capped" rule this is the one exception to.
let mut analyzed = Analyzed::default();
for doc in self.docs.values() {
let Some(path) = doc.path.clone() else { continue };
texts.retain(|(p, _)| p != &path);
if !doc.large {
if analyses == HeldAnalyses::Wanted {
analyzed.facts.insert(path.clone(), doc.facts(path.clone()));
analyzed.words.insert(path.clone(), doc.words());
}
texts.push((path, doc.text.clone()));
}
}
Sources { texts, incdirs: scope.incdirs, warnings: scope.warnings }
Sources { texts, analyzed, incdirs: scope.incdirs, warnings: scope.warnings }
}
/// The text of a workspace file: the open buffer if there is one, else
@@ -1655,6 +1776,49 @@ mod tests {
assert_eq!(indexed(&ws, &["huge_pkg"]), ["huge_pkg"], "the open buffer is indexed in full");
}
#[test]
fn qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before() {
// QA attack (index-scope, 2026-08-28, charter item 4: the cap
// boundary). `collect_sources` walks the scope and reports
// `Skipped` for every file over `maxFileSize` *before* it knows
// whether an open buffer speaks for that path — that ordering is
// pre-existing (the `spoken_for` short-circuit this round added only
// skips the wasted disk *read*, not the cap check ahead of it). The
// question this pins: did routing an open buffer's facts through its
// own analysis change that reporting, or the fact that the buffer
// still ends up indexed in full? It must not: the file is still
// reported `Skipped` once (the disk phase honestly saying the walked
// copy is over cap), and it still ends up indexed — now via
// `Analyzed` rather than `Parsing`, since the round's whole point is
// that an open buffer's own analysis is reused instead of reparsed.
let tree = Tree::new("capbufferqa");
fat_package(&tree, "huge.sv", "huge_pkg", 4096);
let path = tree.path.join("huge.sv");
let mut ws = Workspace::default();
ws.set_client_settings(capping(1024));
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["huge_pkg"]), Vec::<String>::new(), "premise: capped on disk");
let uri = crate::uri::path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("read");
ws.set_document(uri, text);
let mut skipped: Vec<PathBuf> = Vec::new();
let mut analyzed: Vec<PathBuf> = Vec::new();
let mut parsed: Vec<PathBuf> = Vec::new();
ws.rebuild_index_with(&mut |event| match event {
IndexEvent::Skipped { path, .. } => skipped.push(path.to_path_buf()),
IndexEvent::Analyzed { path, .. } => analyzed.push(path.to_path_buf()),
IndexEvent::Parsing { path, .. } => parsed.push(path.to_path_buf()),
IndexEvent::Cached { .. } => {}
});
assert_eq!(skipped, vec![path.clone()], "still reported skipped once, from the disk phase");
assert_eq!(analyzed, vec![path.clone()], "and indexed via its own analysis, not reparsed");
assert!(parsed.is_empty(), "never re-parsed: {parsed:?}");
assert_eq!(indexed(&ws, &["huge_pkg"]), ["huge_pkg"], "still indexed in full, unmoved");
}
#[test]
fn every_skipped_file_is_reported_with_its_size_and_the_cap() {
let tree = Tree::new("capevents");
@@ -2266,11 +2430,16 @@ mod tests {
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
open(&mut ws, &tree, "rtl/m_open.sv");
// Every file of the work list, however it got into the index: since
// 2026-08-28 the open buffer goes in from its own analysis and reports
// `Analyzed` rather than `Parsing`, and the claim under test is about
// the *order* the work list is walked in, not about who parses.
let mut seen: Vec<PathBuf> = Vec::new();
ws.rebuild_index_with(&mut |event| {
if let IndexEvent::Parsing { path, .. } = event {
seen.push(path.to_path_buf());
}
ws.rebuild_index_with(&mut |event| match event {
IndexEvent::Parsing { path, .. }
| IndexEvent::Cached { path, .. }
| IndexEvent::Analyzed { path, .. } => seen.push(path.to_path_buf()),
IndexEvent::Skipped { .. } => {}
});
assert_eq!(
seen,
@@ -2613,12 +2782,14 @@ mod tests {
}
}
/// What one whole scan did, file by file: what it parsed, and what it
/// took from the cache instead. The two together are the work list.
/// What one whole scan did, file by file: what it parsed, what it took
/// from the cache instead, and what came from an open buffer's own
/// analysis. The three together are the work list.
#[derive(Debug, Default, PartialEq, Eq)]
struct Scan {
parsed: Vec<String>,
cached: Vec<String>,
analyzed: Vec<String>,
}
/// Scan `roots` (or rescan what is already open, with `None`) and record
@@ -2629,6 +2800,7 @@ mod tests {
let mut see = |event: IndexEvent| match event {
IndexEvent::Parsing { path, .. } => out.parsed.push(file_name(path)),
IndexEvent::Cached { path, .. } => out.cached.push(file_name(path)),
IndexEvent::Analyzed { path, .. } => out.analyzed.push(file_name(path)),
IndexEvent::Skipped { .. } => {}
};
match roots {
@@ -2752,7 +2924,12 @@ mod tests {
narrow.open_roots_with(vec![tree.path.clone()], &mut |_| {});
open(&mut narrow, &tree, "rtl/a.sv");
let narrowed = scan(&mut narrow, None);
assert_eq!(narrowed.cached, ["a.sv"], "{narrowed:?}");
// `rtl/a.sv` is this session's open buffer, so it goes in from the
// analysis that buffer already holds rather than from the store —
// beside this test's point, and named so the point stays legible:
// `tb/b.sv` appears on no list at all.
assert_eq!(narrowed.analyzed, ["a.sv"], "{narrowed:?}");
assert!(narrowed.parsed.is_empty() && narrowed.cached.is_empty(), "{narrowed:?}");
assert_eq!(
indexed(&narrow, &["a_pkg", "b_pkg"]),
["a_pkg"],
@@ -3079,4 +3256,345 @@ mod tests {
}
eprintln!("hashing {bytes} bytes of {files} files: {:?} ({sink:016x})", started.elapsed());
}
// ------------------------------------------------------------------
// An open buffer's own analysis (index-scope, 2026-08-28)
// ------------------------------------------------------------------
#[test]
fn an_open_buffers_analysis_indexes_to_exactly_what_its_bytes_on_disk_would() {
// The equivalence the reuse stands on. A rescan takes an open buffer's
// facts and its words off the analysis that buffer already holds; the
// claim is that the index and the completion tables are then byte for
// byte the ones a *parse of those bytes* builds. The buffer carries
// unsaved edits on purpose — bytes that are nowhere on disk, which is
// exactly the case the content-keyed cache cannot help with and the
// one the owner's report was about.
let tree = Tree::new("openfacts");
tree.package("rtl/a.sv", "a_pkg");
tree.package("rtl/other.sv", "other_pkg");
tree.write("rtl/top.sv", "module top;\n a_sub u ();\nendmodule\n");
let edited = "`define TAG 1\nimport a_pkg::*;\npackage edited_pkg;\n \
localparam K = 1;\n class c extends a_base; int x; endclass\n\
endpackage\nmodule top;\n logic [K-1:0] w;\n \
a_sub u (.clk(w));\n a_sub v (.clk(w));\nendmodule\n";
let path = tree.path.join("rtl/top.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
ws.set_document(uri, edited.to_string());
let seen = scan(&mut ws, None);
assert_eq!(
seen.analyzed,
["top.sv"],
"the open buffer went in from its own analysis: {seen:?}"
);
assert_eq!(seen.parsed, ["a.sv", "other.sv"], "and nothing else changed route: {seen:?}");
let from_buffer = ws.index().fingerprint();
let words_from_buffer = ws.candidates().words("").to_vec();
let units_from_buffer: Vec<String> =
ws.candidates().units("").iter().map(|c| c.name.clone()).collect();
// The same bytes on disk, nothing open: the parse route, end to end.
tree.write("rtl/top.sv", edited);
let mut plain = Workspace::default();
plain.set_client_settings(wide(ClientSettings::default()));
let mut route = Scan::default();
plain.open_roots_with(vec![tree.path.clone()], &mut |event| match event {
IndexEvent::Parsing { path, .. } => route.parsed.push(file_name(path)),
IndexEvent::Cached { path, .. } => route.cached.push(file_name(path)),
IndexEvent::Analyzed { path, .. } => route.analyzed.push(file_name(path)),
IndexEvent::Skipped { .. } => {}
});
assert_eq!(route.parsed, ["a.sv", "other.sv", "top.sv"], "premise: it really parsed");
assert_eq!(from_buffer, plain.index().fingerprint(), "the same index, byte for byte");
assert_eq!(words_from_buffer, plain.candidates().words(""), "and the same words");
let units_plain: Vec<String> =
plain.candidates().units("").iter().map(|c| c.name.clone()).collect();
assert_eq!(units_from_buffer, units_plain, "and the same index-derived candidates");
// And through the incremental door as well: `update_one` takes the same
// shortcut, and `update_one_checked` holds it to a whole rebuild.
assert!(ws.update_one_checked(&path), "the buffer's file is one the index holds");
assert_eq!(ws.index().fingerprint(), from_buffer, "still the same index after an update");
}
#[test]
fn an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus() {
// `Document::new` and `FileFacts::of` each lex, parse and analyze one
// file, and the reuse is only sound while those two agree. Nothing
// enforces it at compile time — they are separate call sites — so it is
// swept over real files, in the encoded record form, which is every
// field the index and the persistent store ever read.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let empty = WorkspaceIndex::default();
let mut checked = 0usize;
for path in walk_sources(&corpus).into_iter().step_by(3) {
let Ok(text) = fs::read_to_string(&path) else { continue };
let doc = Document::new(Some(path.clone()), text.clone(), &empty);
assert!(!doc.large, "premise: a full analysis, not the fast path");
assert_eq!(
doc.facts(path.clone()).encode(),
FileFacts::of(path.clone(), &text).encode(),
"the records differ for {}",
path.display()
);
let mut from_buffer = doc.words();
let mut from_text =
crate::candidates::words_of_tokens(&tokenize(&text).unwrap_or_default());
from_buffer.sort();
from_text.sort();
assert_eq!(from_buffer, from_text, "the words differ for {}", path.display());
checked += 1;
}
assert!(checked > 100, "premise: the corpus was really swept ({checked} files)");
eprintln!("open-buffer equivalence: {checked} corpus files, facts and words identical");
}
#[test]
fn qa_attack_crafted_non_corpus_shapes_drift_check() {
// Run on a dedicated thread with a generous stack: `cargo test`'s
// default per-test-thread stack (2 MiB) is smaller than a normal
// process's main-thread stack, and a couple of the crafted shapes
// below are deep enough to overflow the smaller one even though
// `FileFacts::of` alone — no `Document`, no reuse — overflows it
// identically on pristine, unmodified `master`. That is a real,
// pre-existing recursion-depth ceiling in the parser/analyzer,
// independent of this round; it is filed separately (QA log,
// 2026-08-28) rather than blocking this round, since both routes
// being compared here fail *identically*, which is the opposite of
// the drift this test hunts for. Run at 64 MiB so the drift check
// exercises real depth without tripping that unrelated ceiling.
std::thread::Builder::new()
.stack_size(64 * 1024 * 1024)
.spawn(qa_attack_crafted_non_corpus_shapes_drift_check_body)
.expect("spawn")
.join()
.expect("no panic");
}
fn qa_attack_crafted_non_corpus_shapes_drift_check_body() {
let empty = WorkspaceIndex::default();
let cases: Vec<(&str, String)> = vec![
("bom_plain", "\u{feff}module m;\nendmodule\n".to_string()),
("crlf", "module m;\r\n logic w;\r\nendmodule\r\n".to_string()),
("bom_crlf", "\u{feff}module m;\r\n logic w;\r\nendmodule\r\n".to_string()),
("unterminated_block_comment", "module m; /* never closed\nendmodule\n".to_string()),
("unterminated_attribute", "(* foo module m; endmodule\n".to_string()),
("unterminated_macro_call", "`define M(a,b) a+b\nmodule m; logic w = `M(1,2\nendmodule\n".to_string()),
("unterminated_string", "module m; string s = \"never closed\nendmodule\n".to_string()),
("unexpected_char", "module m; logic w = \u{1}; endmodule\n".to_string()),
("deeply_nested_begin_end", {
let mut s = String::from("module m;\ninitial begin\n");
for _ in 0..500 { s.push_str("begin\n"); }
for _ in 0..500 { s.push_str("end\n"); }
s.push_str("end\nendmodule\n");
s
}),
("deeply_nested_parens", {
let mut s = String::from("module m;\n localparam int W = ");
for _ in 0..2000 { s.push('('); }
s.push('1');
for _ in 0..2000 { s.push(')'); }
s.push_str(";\nendmodule\n");
s
}),
("macro_heavy", {
let mut s = String::new();
for i in 0..500 {
s.push_str(&format!("`define M{i} {i}\n"));
}
s.push_str("module m;\nendmodule\n");
s
}),
("include_bearing", "`include \"foo.svh\"\n`include \"bar/baz.vh\"\nmodule m;\nendmodule\n".to_string()),
("parse_error_recovery", "module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n".to_string()),
("mixed_line_endings", "module m;\n logic a;\r\n logic b;\nendmodule\n".to_string()),
("null_byte", "module m;\n logic a; // \0 embedded\nendmodule\n".to_string()),
("tab_and_form_feed", "module m;\n\t\u{c}logic a;\nendmodule\n".to_string()),
];
let total = cases.len();
let mut failures = Vec::new();
for (name, text) in cases {
let path = PathBuf::from(format!("/w/{name}.sv"));
let doc = Document::new(Some(path.clone()), text.clone(), &empty);
let from_buffer = doc.facts(path.clone()).encode();
let from_text = FileFacts::of(path.clone(), &text).encode();
if from_buffer != from_text {
failures.push(format!(
"FACTS DRIFT in {name}: buffer={from_buffer:?} text={from_text:?}"
));
}
let mut wb = doc.words();
let mut wt = crate::candidates::words_of_tokens(&tokenize(&text).unwrap_or_default());
wb.sort();
wt.sort();
if wb != wt {
failures.push(format!("WORDS DRIFT in {name}: buffer={wb:?} text={wt:?}"));
}
}
assert!(failures.is_empty(), "drift found:\n{}", failures.join("\n"));
eprintln!("qa attack: {total} crafted non-corpus shapes, no drift found");
}
#[test]
fn a_buffer_on_the_large_file_fast_path_offers_no_analysis_to_reuse() {
// The one buffer whose held analysis is not an analysis of its text —
// it is the analysis of the empty file. Such a buffer contributes
// nothing to the index at all, which is what keeps the reuse from ever
// meeting it: it is absent from the work list, so it is absent from
// every list a rescan reports.
let tree = Tree::new("openfactslarge");
tree.package("rtl/a.sv", "a_pkg");
let big = format!(
"package big_pkg;\n localparam K = 1;\n{}endpackage\n",
" // filler\n".repeat(200)
);
tree.write("rtl/big.sv", &big);
let mut ws = Workspace::default();
ws.set_client_settings(wide(ClientSettings {
large_file_threshold: 100,
..Default::default()
}));
ws.open_roots_with(vec![tree.path.clone()], &mut |_| {});
let uri = crate::uri::path_to_uri(&tree.path.join("rtl/big.sv")).expect("uri");
ws.set_document(uri.clone(), big);
assert!(ws.document(&uri).expect("open").large, "premise: the fast path");
let seen = scan(&mut ws, None);
assert!(seen.analyzed.is_empty(), "nothing came from an analysis: {seen:?}");
assert_eq!(seen.parsed, ["a.sv"], "and the big buffer is on no list at all: {seen:?}");
assert_eq!(indexed(&ws, &["a_pkg", "big_pkg"]), ["a_pkg"], "nor in the index");
}
// ------------------------------------------------------------------
// QA attacks (index-scope, 2026-08-28): staleness and threshold crossing
// ------------------------------------------------------------------
#[test]
fn qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan() {
// Charter attack 2 (staleness). An open buffer's *unsaved* edits must
// win a rescan (the whole reason the reuse is sound even though the
// content-keyed cache has nothing to key unsaved bytes by), and
// closing the buffer without saving must let the next rescan see disk
// again — nothing about the buffer's now-gone analysis may linger.
let tree = Tree::new("qastaleness");
tree.write("rtl/p.sv", "package p;\n localparam ON_DISK = 1;\nendpackage\n");
let path = tree.path.join("rtl/p.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "premise: disk's member");
// Open the buffer and edit it — never saved, so disk still says
// `ON_DISK` — then rescan.
ws.set_document(
uri.clone(),
"package p;\n localparam IN_BUFFER = 1;\nendpackage\n".into(),
);
let seen = scan(&mut ws, None);
assert_eq!(seen.analyzed, ["p.sv"], "the live buffer's own analysis went in: {seen:?}");
assert!(seen.parsed.is_empty() && seen.cached.is_empty(), "{seen:?}");
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 1, "the live edit is indexed");
assert_eq!(ws.index().member("p", "ON_DISK").len(), 0, "disk's stale member is gone");
// Close without saving. Disk still says `ON_DISK`; the buffer's
// analysis of `IN_BUFFER` no longer exists anywhere to be reused.
ws.close_document(&uri);
let seen = scan(&mut ws, None);
assert_eq!(seen.parsed, ["p.sv"], "reparsed from disk, not reused: {seen:?}");
assert!(seen.analyzed.is_empty(), "no buffer left to analyze from: {seen:?}");
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "back to disk's member");
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0, "the unsaved edit is gone");
}
#[test]
fn qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session() {
// Charter attack 3 (large-file path), the direction the dev's own
// test does not cover: small **on disk**, edited **huge in the
// buffer** without saving. `doc.large` is re-decided on every
// `set_document`, so the very next rescan must drop the buffer from
// the analyzed-reuse route (and from the index) the moment the edit
// crosses the threshold — not one rescan later.
let tree = Tree::new("qathreshgrow");
tree.write("rtl/p.sv", "package p;\n localparam SMALL = 1;\nendpackage\n");
let path = tree.path.join("rtl/p.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
let mut ws = Workspace::default();
ws.set_client_settings(wide(ClientSettings {
large_file_threshold: 200,
..Default::default()
}));
ws.open_roots_with(vec![tree.path.clone()], &mut |_| {});
ws.set_document(uri.clone(), "package p;\n localparam SMALL = 1;\nendpackage\n".into());
assert!(!ws.document(&uri).expect("open").large, "premise: a real analysis");
let seen = scan(&mut ws, None);
assert_eq!(seen.analyzed, ["p.sv"], "small buffer reused: {seen:?}");
assert_eq!(ws.index().member("p", "SMALL").len(), 1);
// Edited past the threshold, never saved.
ws.set_document(uri.clone(), filler(1_000));
assert!(ws.document(&uri).expect("open").large, "now on the fast path");
let seen = scan(&mut ws, None);
assert!(seen.analyzed.is_empty(), "the now-huge buffer offers no analysis: {seen:?}");
assert!(seen.parsed.is_empty(), "and disk is not read in its place either: {seen:?}");
assert_eq!(ws.index().member("p", "SMALL").len(), 0, "contributes nothing at all");
// And back under the threshold: a real analysis again, reused again.
ws.set_document(uri.clone(), "package p;\n localparam SMALL = 1;\nendpackage\n".into());
assert!(!ws.document(&uri).expect("open").large, "shrank back");
let seen = scan(&mut ws, None);
assert_eq!(seen.analyzed, ["p.sv"], "reused again: {seen:?}");
assert_eq!(ws.index().member("p", "SMALL").len(), 1);
}
#[test]
fn qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse() {
// The other direction of charter attack 3: **huge on disk** (over the
// fast-path threshold if it were read fresh — moot here, since a
// buffer's `large` flag is decided from its own live text, never
// disk), edited down **small in the buffer**. Included for the
// opposite-direction symmetry the brief asks for; the on-disk size is
// irrelevant to `doc.large` by construction (`is_large` reads
// `text.len()`), so this is really the same claim from the other
// starting point.
let tree = Tree::new("qathreshshrink");
let huge_on_disk = filler(1_000);
tree.write("rtl/p.sv", &huge_on_disk);
let path = tree.path.join("rtl/p.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
let mut ws = Workspace::default();
ws.set_client_settings(wide(ClientSettings {
large_file_threshold: 200,
..Default::default()
}));
ws.open_roots_with(vec![tree.path.clone()], &mut |_| {});
// Disk alone: `filler` is real Verilog (`module m; wire a; ...`), well
// under no cap, so it is walked and parsed whole — the large-file
// threshold applies to *buffers*, not to the walk.
let seen = scan(&mut ws, None);
assert_eq!(seen.parsed, ["p.sv"], "disk copy parsed in full: {seen:?}");
// Opened as a buffer with that same huge text: the fast path, same as
// any buffer over the threshold.
ws.set_document(uri.clone(), huge_on_disk);
assert!(ws.document(&uri).expect("open").large, "premise: fast path from the live text");
// Edited down to something small, never saved.
ws.set_document(uri.clone(), "package p;\n localparam SHRUNK = 1;\nendpackage\n".into());
assert!(!ws.document(&uri).expect("open").large, "back to a real analysis");
let seen = scan(&mut ws, None);
assert_eq!(seen.analyzed, ["p.sv"], "the shrunk buffer's own analysis is reused: {seen:?}");
assert_eq!(ws.index().member("p", "SHRUNK").len(), 1);
}
}
+83
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");
+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))
+52 -4
View File
@@ -379,7 +379,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,
@@ -726,10 +738,36 @@ 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` and `sem` are the analysis of
/// the text `path` currently holds.
pub fn from_analysis(
path: PathBuf,
tree: &SourceFile,
defines: &DefineTable,
sem: &Semantics,
) -> FileFacts {
facts_from_analysis(path, tree, defines.clone(), sem)
}
/// The file these facts were read from.
pub fn path(&self) -> &Path {
&self.path
@@ -740,13 +778,23 @@ impl FileFacts {
fn facts_of(path: PathBuf, src: &str) -> FileFacts {
let (tree, defines) = parse_and_collect(src);
let sem = analyze(&tree, src);
facts_from_analysis(path, &tree, defines, &sem)
}
/// Read off what one file contributes, from its finished analysis.
fn facts_from_analysis(
path: PathBuf,
tree: &SourceFile,
defines: DefineTable,
sem: &Semantics,
) -> 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 {
@@ -760,7 +808,7 @@ fn facts_of(path: PathBuf, src: &str) -> FileFacts {
continue;
}
facts.units.push(Decl::of(unit));
collect_members(&sem, unit, &mut facts.members);
collect_members(sem, unit, &mut facts.members);
}
let exported: HashSet<(u32, u32)> = facts
.units
+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");
}
+163 -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,
@@ -1658,3 +1659,164 @@ 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) {
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)
}
/// `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) = as_a_server_analyzes(src);
let from_text = FileFacts::of(path.clone(), src);
let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem);
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) = as_a_server_analyzes(&src);
let from_text = FileFacts::of(path.clone(), &src);
let from_analysis = FileFacts::from_analysis(path.clone(), &tree, &defines, &sem);
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) = as_a_server_analyzes(src);
builder.add_facts(FileFacts::from_analysis(PathBuf::from(*path), &tree, &defines, &sem));
}
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) = as_a_server_analyzes(changed);
updated.update_facts(FileFacts::from_analysis(
PathBuf::from("/w/pkg.sv"),
&tree,
&defines,
&sem,
));
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");
}
+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.
+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
+16
View File
@@ -5,6 +5,22 @@ 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.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
+12 -1
View File
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
then open a Verilog or SystemVerilog file. There is no separate server or CLI
setup.
The current release is **0.13.0**. Its platform packages include both
The current release is **0.13.1**. Its platform packages include both
`lucisv-server` and the `lucisv` command-line tool:
| Package target | Machines |
@@ -320,6 +320,17 @@ Every nesting color is a proper VS Code theme color:
}
```
## Release 0.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.13.1",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",