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]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-28 16:26:06 -07:00
1 parent cf32e92e58
commit d4eb8f48ff
13 files changed
+809 -61

No files matched your search

+2 -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.
+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");
+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(())
}
+3 -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();
+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))
+5
View File
@@ -738,6 +738,11 @@ 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)
}
+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");
}
+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.**