# recursion-limit ## Goal `vlog_parser` is a recursive-descent parser, so nesting in the input becomes nesting on the call stack. Deeply nested input therefore did not produce a parse error — it overflowed the stack and killed the process (SIGABRT). A stack overflow is not a panic, so `catch_unwind` in `crates/lucisv/src/main.rs` could not contain it: the run died mid-batch, every file after the offending one went unprocessed, and there was not even an exit-code-2 summary (cli-polish QA finding, `docs/features/cli-polish/README.md`). This feature adds an explicit nesting-depth counter to the parser so that input nested past a documented limit becomes an ordinary `ParseError` with a position, the file is left untouched, and the rest of the batch still gets formatted. It also audits the formatter's recursive walk, which turns out to be bounded by the parser's limit and needs no counter of its own. ## The invariant > **No input can make AST depth exceed `MAX_NESTING_DEPTH + MAX_CHAIN_LENGTH` > (64 + 1024 = 1088 layers) on any root-to-leaf path**, so every recursive walk > over the tree — the formatter's, the `Doc` tree's, and the implicit > recursive `Drop` — is bounded too. Two things can add a layer to the tree, and each has a counter, both accumulated *along a path* and released when the construct that opened them finishes: | | counter | limit | charged by | |---|---|---|---| | **Nesting** — one parser recursion per layer | `depth` | `MAX_NESTING_DEPTH` = 64 | the 5 gated `parse_*` functions | | **Chains** — a loop that wraps what it already built | `links` | `MAX_CHAIN_LENGTH` = 1024 | postfix segments, binary/`inside` operator chains, a bare event control's path | The chain counter exists because a loop can deepen the AST without deepening the parser: `a.b.b.b…` costs `parse_postfix` a single frame but builds one `Expr::Member` per segment, and the *formatter* then recurses once per layer. That gap crashed the formatter on a 3 KiB file until this second budget landed (QA finding, 2026-08-19). Because both counters accumulate along a path rather than per construct, nesting and chains cannot multiply: a chain inside another chain's operand stacks on top of it, so `f(a.b…)(a.b…)…` is bounded by the same 1088 layers, not by 64 × 1024. ## Assumptions - **The limits count AST layers, not source constructs.** Different constructs spend a different number of levels per source construct: one nested `begin` costs 1 depth, one nested `(...)` costs 2 (`parse_ternary` + `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.**~~ **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 expression chains are the plausible outlier, which is why the limit is set well above hand-written depths rather than at the smallest safe value. - **The formatter is only reachable through `format_source(&str)`.** There is no public API that takes an AST, so every tree the formatter walks came from the gated parser. If an AST-taking entry point is ever exposed, the formatter audit below has to be revisited. ## The limits ``` MAX_NESTING_DEPTH = 64 (crates/vlog_parser/src/parser.rs) MAX_CHAIN_LENGTH = 1024 (was 256 until 2026-08-29) PARSE_STACK_SIZE = 32 MiB (was 16 MiB until 2026-08-29) ``` 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") error: rtl/chain.sv: parse error: 2:525: expression chain too long (limit 1024) (found ".") ``` ### Why 64 — measured, not guessed Method: a scratchpad copy of the workspace with a probe binary (`examples/depth_probe.rs`, never committed) that runs the *whole* pipeline (`format_source`: parse → doc build → print → verify's re-parse and re-format) on a thread with a chosen stack size, over generated inputs for eight nesting families. Bisecting the thread stack size gives the worst-case peak usage. Without any limit, the deepest input that survived a 2 MiB thread: | family | debug | release | |---|---|---| | nested `if`/`begin` statements | **15 levels** | 136 | | `else if` chains | 29 | 253 | | nested generate `if` | 52 | 256 | | nested `(...)` / `{...}` | 63–67 | 553–677 | | `? :` chains / stacked `~` | 345 | 3461 | That is ~140 KiB of stack per nested statement in a debug build — the reason the cli-polish repro (150 levels) died. Per *depth-counter level* the worst family costs ~72 KiB (debug) / ~8 KiB (release). With the limit in place, the peak stack of the full pipeline on input that trips the limit (bisected the same way, minimum surviving thread stack): | family | debug peak | release peak | |---|---|---| | `else if` chains (worst) | **3959 KiB** | 487 KiB | | nested `if`/`begin` | 3847 KiB | 455 KiB | | nested generate `if` | 1239 KiB | 183 KiB | | nested `{...}` / `(...)` | 983–1047 KiB | 103 KiB | | `? :` chains, stacked `~` | 135–423 KiB | — | 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 the limit ever tripped. Why not smaller: 64 levels comfortably covers generated code, while hand-written RTL rarely passes 10. What 64 buys, per construction (all verified against the binary — the exact number depends on what else is on the path, which is why each is spelled out): | construction | deepest that parses | |---|---| | `module` → `initial` → nested `begin`, innermost block **empty** | 62 (63 errors) | | `module` → `initial` → nested `begin`, innermost holds `x <= 1;` | 59 (60 errors) | | `module` → `assign x =` nested `(…)` | 30 parens (31 errors) | | `module` → nested generate `if … begin` | 30 (31 errors; corrected by lead per re-QA measurement) | | `? :` chain in an `assign` | ~60 arms | The two `begin` rows differ because a statement inside the innermost block costs three more levels (the statement plus `parse_ternary`/`parse_unary` for its expression). The parser's own boundary unit tests use the empty-block construction (62/63); `vlog_formatter`'s use the ones with content. ### Why 256 for chains — superseded 2026-08-29, see "Why 1024" below Same method, measuring inputs sized to sit exactly *at* the limits so the formatter really walks them (min surviving thread stack, debug / release): | exactly-legal worst case | debug | release | |---|---|---| | 256-link chain alone | 1511 KiB | 119 KiB | | 30 nested parens with a 256-link chain inside | 1703 KiB | 135 KiB | | 29 nested generate `if` with a 256-link chain inside | 1671 KiB | — | | 59 nested `begin` with a 256-link chain inside | 3655 KiB | 423 KiB | | 58-deep `else if` chain with a 256-link chain inside | **3895 KiB** | 487 KiB | A link costs ~6 KiB of stack in a debug build, an order of magnitude less than a nested statement (~62 KiB), and the two peaks land in *different phases* — deep statements peak while parsing, long chains while formatting — so the chain budget does not move the global worst case at all (3895 KiB with the chain, 3959 KiB without it). That makes 256 a free choice on the stack side, and it is the side of the trade-off that matters for acceptance: long flat chains are the one deep shape real RTL genuinely produces (a 64-bit parity XOR is 63 links, a 128-term generated sum is 127, a 256-term one 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. ### Why 1024 for chains — 2026-08-29 **256 was not enough for real code.** OpenTitan's generated register files build one `|` chain per register file, `(addr_hit[N] & (|(PERMIT[N] & ~reg_be))) | …`, so the chain length tracks the register count. A high-water probe over all 3,943 files (a scratchpad copy with the limit raised out of the way and `links` recorded; never built inside the repo) says what they need: | file | links | |---|---| | `top_earlgrey/ip_autogen/pinmux/rtl/pinmux_reg_top.sv` | **567** | | `top_englishbreakfast/…/pinmux_reg_top.sv` | 519 | | `top_darjeeling/…/pinmux_reg_top.sv` | 502 | | `top_darjeeling/…/alert_handler_reg_top.sv` | 397 | | `top_earlgrey/…/alert_handler_reg_top.sv` | 353 | | `rv_dm/rtl/rv_dm_mem_reg_top.sv` | 280 | | `top_darjeeling/…/rv_core_ibex_cfg_reg_top.sv` | 266 | 3,932 of the 3,943 files stay under 128; five sit in 257–512 and two pass 512. Seven files were rejected outright at 256, which is the acceptance failure this budget exists to avoid. **What a link costs, re-measured at the new sizes** (same method: one trial per subprocess, bisect the smallest surviving thread stack, whole `format_source`; rustc 1.97.1): | shape | debug | release | |---|---|---| | postfix chain (`a.b…`), 640 links | 5 911 KiB | 375 KiB | | postfix chain, 768 | 7 079 KiB | 455 KiB | | postfix chain, **1024** | **9 430 KiB** | 615 KiB | | postfix chain, 1280 | 11 798 KiB | 775 KiB | | `+` chain / the real `or_chain` shape, 2048 terms | 567 KiB | 183 KiB | | 28 nested `case` + a 1024-link postfix chain inside | **9 894 KiB** | 727 KiB | | 64 nested `case` (trips depth) + a 1024-link chain inside | 5 959 KiB | 775 KiB | Per link, from the slope: **9.20 KiB debug**, 0.63 KiB release — consistent with the ~9 KiB the 2026-08-19 round measured at 256. Binary-operator chains, which is what the generated files actually contain, are ~40× cheaper because `binary_chain` flattens the left spine; the *postfix* chain is what the budget has to be safe for. **Two things this changes.** 1. **Chains now set the global worst case.** At 256 a maximal chain peaked at ~2.4 MiB against nesting's ~5.9, which is why both earlier rounds could say "the chain budget does not move the worst case". At 1024 it peaks at ~9.4 MiB alone and **9 894 KiB** inside nesting, so that sentence is retired: `PARSE_STACK_SIZE` is now measured against the chain. 2. **The additive-composition argument is unchanged, and the measurement shows it directly.** 64 nested `case` *with* a 1024-link chain inside bisects to exactly the same byte as without it (5 959 KiB), because tripping the depth limit peaks in the parser while a chain peaks in the formatter. Nothing multiplies. **Why 1024 and not 640.** 640 would clear today's largest file by 13 % — a fit, not a margin, on a number that grows with design size, and this limit has now been outgrown once. 1024 is 1.8× the measured maximum and costs 3.5 MiB of debug stack over 640, which the constant below absorbs. ### The stack the limit needs — re-measured 2026-08-28, and again 2026-08-29 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.**~~ **Retired 2026-08-29.** It was true at `MAX_CHAIN_LENGTH = 256`: a 256-link chain alone peaked at 2487 KiB debug (~9 KiB per link), and the same chain inside 58 nested `case` measured 5895 KiB — identical to that nesting without any chain, because the two peak in different phases. At 1024 the chain peaks at ~9.4 MiB and *is* the worst case. The phase argument still holds; only the ranking changed. - ~~**16 MiB is the constant.**~~ **Superseded 2026-08-29 by 32 MiB**, for the same reason 16 replaced 8: the margin, not the fit, is the point. The measured worst case is now **~9.7 MiB debug** (a maximal chain inside nesting, 9 894 KiB) rather than ~5.9; 16 MiB would be 1.65× of that, below the 2.7× this feature settled on for a failure mode that aborts instead of returning. 32 MiB is **3.3×**, costs address space rather than memory (thread stacks are committed a page at a time), and is what the feature's tests now spawn. The full 2026-08-29 measurement is under "Why 1024 for chains" above and in `docs/features/clocking-wave/README.md`. ## Where the counters sit `Parser::enter()` / `Parser::leave()` bracket each gated function; `enter` returns the parse error instead of incrementing when the limit is reached, so the guard rides the existing `?` propagation: ```rust fn parse_stmt(&mut self) -> PResult { self.enter()?; let out = self.parse_stmt_inner(); self.leave(); out } ``` Chain links use the same shape, except that the release restores the count the chain started from rather than subtracting one — so a chain nested inside another chain's operand stacks on top of it, while sibling chains each start from their enclosing level: ```rust fn parse_postfix(&mut self) -> PResult { let outer_links = self.links; let out = self.parse_postfix_inner(); // calls self.link()? per segment self.links = outer_links; out } ``` Five functions are gated for nesting. Every unbounded recursion cycle in the grammar passes through at least one of them: | gated function | cycles it cuts | |---|---| | `parse_item` | module/package/generate-region bodies, generate blocks (`parse_gen_block` → `parse_item`) | | `parse_stmt` | `begin`/`fork` blocks and every compound statement (`if`, `for`, `while`, `do`, `repeat`, `forever`, `foreach`, `wait`, `assert`, case items, timing controls), including `else if` chains | | `parse_gen_if` | generate `else if` chains, which recurse directly without passing through `parse_item` | | `parse_ternary` | the entire expression grammar: `parse_expr` delegates here, and parens, concatenations, replications, assignment patterns, call arguments, index/range expressions, `inside` ranges, dimensions, casts and delay values all recurse back through `parse_expr`. Also the `? :` else-chain, which recurses into `parse_ternary` directly | | `parse_unary` | stacked prefix operators (`~~~~x`), which recurse directly without passing through `parse_ternary` | Two loops charge chain links instead, because they deepen the tree without deepening the parser (this is the hole the first round of this feature missed): | chain site | shapes | |---|---| | `parse_postfix` | `a.b`, `a::b`, `a[i]`, `a[m:l]`, `a(args)`, `a'(x)`, `a++`/`a--` — one link per segment | | `parse_binary` | `a + b + c…` (one link per operator, any precedence) and `a inside {…} inside {…}` | | `parse_bare_event_name` | `@a.b.c`, `@a["k"].b` — the `.name` / `[expr]` segments of a paren-less event control's hierarchical path (added 2026-08-29; the `.name` half of this loop existed un-charged before, which was the last instance of the hole below) | Not charged at all, and why: - `parse_binary(min_prec)`'s *recursion* (with `min_prec + 1`) is self-bounded by the 11-level precedence table (≤ 12 frames per operand); it is the loop in the same function, not the recursion, that needs the link budget. - `parse_dims`, `parse_declarators`, `parse_expr_list`, `parse_connections`, `parse_tf_body`, `parse_source_file`, the enum/struct member loops and the instance/connection loops are iterative *and* collect into a `Vec`, so an extra iteration widens the tree instead of deepening it. Verified by checking every `Box::new` site in `parser.rs`: outside `parse_postfix` and `parse_binary`, all of them run once per gated recursive call. - `parse_opt_data_type` / `parse_type_expr` reach `parse_expr` through `parse_dims`; typedefs cannot nest inside typedefs. - `scan_matching` (lookahead) is a loop that builds nothing. ## Formatter audit (no gate needed) `crates/vlog_formatter` walks the AST the parser produced, and every recursive path descends into a *child node* of its argument, so the formatter walk is bounded by AST depth — which is what the two counters above bound. Note the order of the argument: the formatter is safe *because* AST depth is bounded, so the invariant at the top of this file is load-bearing, not a nicety. When only parser *recursion* was bounded (first round of this feature), chain-built AST slipped through and the formatter still crashed; the premise has to cover every way a layer can be added to the tree. - `format.rs`: `item`/`item_kind`, `stmt`/`stmt_kind`/`stmt_as_body`/ `block_doc`, `if_stmt` (recurses once per `else if`, i.e. once per gated `parse_stmt` level), `expr`, `expr_compact`, `parens`, `expr_list`, `delimited`, `gen_for`/`gen_case`/`gen_block`, `typedef`, `connection`, `sens_list`, `timing_control`, `for_step` — all structural descents. `binary_chain`'s inner `walk` recurses down the left spine of one same-precedence operator chain, again a strict descent. `gen_if` is *iterative* over `else if` chains (a `while` loop), so it is strictly shallower than the parser was. - No formatter path synthesizes nesting: nothing wraps a node in a variable number of `Group`/`Indent` layers, and `binary_chain` and `gen_if` actively flatten. The `Doc` tree is therefore a constant factor deeper than the AST, not more. - `printer.rs`: `print` and `fits` are iterative — explicit work stacks, not recursion. `contains_hard_line` is recursive over the `Doc` tree, i.e. bounded by that same constant factor. The implicit recursive `Drop` of the AST (`Box`/`Box` chains) and of the `Doc` tree is bounded the same way. The measured numbers back the argument up: both peak-stack tables above are for `format_source`, i.e. parse + doc build + print + the verification re-parse and re-format, and `crates/vlog_formatter/tests/deep_nesting.rs` formats trees at *exactly* the maximum legal depth and the maximum legal chain length and checks they converge. Those tests also prove formatting does not inflate depth — the output of a max-depth file re-parses inside `format_source` without tripping either limit. ## Handshakes - **Consumed from `vlog_parser`:** nothing new. `parse()` keeps its signature; the limit shows up as a normal `ParseError`, so `vlog_formatter` and `lucisv` report it through the paths they already had (`FormatError:: Source` → `error: : parse error: …` → exit 2). - **Promised to `vlog_formatter`:** AST depth on any path is bounded by `vlog_parser::parser::MAX_NESTING_DEPTH + MAX_CHAIN_LENGTH` (both public, so tests and any future consumer can reference them instead of hard-coding 64 and 1024). The formatter may keep its recursive walk as long as every path is a structural descent and no public API accepts an externally built AST. - **Requirement on future `vlog_parser` work:** any new loop that wraps the 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. - **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. - [x] Gate the five self-recursive entry points (`parse_item`, `parse_stmt`, `parse_gen_if`, `parse_ternary`, `parse_unary`); audit the rest. - [x] `MAX_NESTING_DEPTH = 64` chosen from measured stack headroom in debug *and* release builds; rationale recorded above. - [x] Error message `nesting too deep (limit 64)` carries line:col like every other parse error. - [x] Formatter audit: bounded by the parser's limit, no gate added; reasoning and evidence recorded above. - [x] Parser unit tests: at limit / past limit, one per construct family. - [x] Formatter tests (`tests/deep_nesting.rs`): max-legal depth formats and converges; past-limit input surfaces as a parse error. - [x] CLI test (`crates/lucisv/tests/cli.rs`): the cli-polish repro (150 levels) exits 2, is left untouched, and files after it are still formatted. - [x] `cargo test --workspace`, `cargo clippy --all-targets`, `cargo fmt --check` all clean. From QA round 1 (2026-08-19): - [x] **Blocking:** chain-built AST (`a.b.b…`, `a::b…`, `a[0]…`, `a()…`, `a++…`, `a + a…`, `a inside {…}…`) is bounded too — second counter, `MAX_CHAIN_LENGTH = 256`, charged by `parse_postfix` and `parse_binary`. QA's 1500-segment repro now exits 2 instead of SIGABRT. - [x] Re-audited every `Box::new` site in the parser for the same shape; the two loops above were the only ones. - [x] **Medium:** the release-discipline test now covers all five gates *and* both link sites — verified by deleting each of the seven release statements in turn and confirming a test fails each time (it did not before: deleting `parse_unary`'s `leave()` used to pass). - [x] **Low:** boundary prose now names the construction it counts (59 vs 62 nested `begin` blocks differ only by what sits inside the innermost 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. Round 4 — the chain budget real code outgrew (2026-08-29, from the testbench-syntax wave's round 2; see `docs/features/clocking-wave/README.md`): - [x] Measured what real code needs before choosing anything: a per-file high-water probe over all 3,943 OpenTitan files. Longest chain **567** (`pinmux_reg_top.sv`); seven files were rejected at 256. - [x] Re-measured the per-link stack cost across four lengths so the slope is measured rather than assumed: **9.20 KiB per postfix link** in a debug build, 0.63 KiB in release. - [x] `MAX_CHAIN_LENGTH` 256 → **1024** (1.8× the measured maximum), and the invariant restated: 64 + 1024 = **1088 layers**. - [x] `PARSE_STACK_SIZE` 16 → **32 MiB**, from the re-measured worst case (**9 894 KiB** debug: a maximal chain inside statement nesting) at the same 2.7×-or-better margin the 2026-08-28 round argued for. - [x] The "chains do not move the worst case" claim retired with the measurement that retires it; the phase argument that makes the two counters additive re-verified at the new size (64 nested `case` with and without a 1024-link chain bisect to the same byte). - [x] The last un-charged chain loop found and closed: `parse_sens_list`'s paren-less `@a.b.c` path boxed a layer per `.name` without charging `link()`. Now `parse_bare_event_name`, charging both segment kinds and restoring the count it started from, with a test. - [x] `deep_nesting.rs` gained the combined worst case (`a_maximal_chain_inside_deep_nesting_formats`), and its past-the-limit case now spells `MAX_CHAIN_LENGTH + 1` instead of a hard-coded 1500. - [x] `MAX_NESTING_DEPTH` left at 64: nothing in this round changes which nesting a file may use. ## Work log ### 2026-08-19 — dev agent - Read CLAUDE.md, README.md, TODO.md §1 and the cli-polish QA log first. Baseline: `cargo test --workspace` green (70 tests), `cargo fmt --check` clean, `cargo clippy --all-targets` **silent** (the 4 warnings the cli-polish QA log mentions have since been fixed) — so "keep clippy silent" was the bar. - **Measured before choosing anything.** Copied the workspace to the scratchpad (never building probes inside the repo), added a `depth_probe` example that runs `format_source` on generated deep inputs on a thread with a settable stack size, and bisected two things: the deepest input that survives a 2 MiB thread with no limit, and (after the limit landed) the smallest stack that survives limit-tripping input. Both tables are above. The first surprise was how expensive debug frames are — 15 levels of `if…begin` exhaust 2 MiB — so I also instrumented per-function frame sizes by printing the address of a local at each entry: `parse_keyword_stmt` 50,528 B, `parse_keyword_item` 20,832 B, `parse_primary` 12,240 B, `parse_stmt_kind` 6,480 B in debug. - **Considered and rejected: splitting the giant `match` functions** to shrink those frames. An experiment (extracting the `begin` arm of `parse_keyword_stmt` into its own function) moved the frame only 50,528 → 47,872 B, so the win is spread across ~25 arms and would take a large, risky refactor of the parser — and it would *not* change the conclusion, because even after it a debug test thread's 2 MiB still could not reach a generous limit. Kept the parser as it is and spent the budget on measuring instead. - **Limit = 64**, from the debug worst case (~72 KiB per level → ~3.9 MiB peak) against the 8 MiB main-thread stack. 128 was the suggested starting point but measures at ~7.9 MiB in debug, which would leave the debug-binary CLI test overflowing before the guard fired — the exact failure this feature exists to remove. - Guard shape: `enter()?` / `leave()` around a renamed `*_inner` body. An RAII guard would have to hold `&mut Parser` and would then block every `self.` call inside the function body; a closure-taking helper would force rewriting each body around a `|p|` parameter. The wrapper keeps the grammar functions untouched and reads top-to-bottom, which matches the file's style. - Gated `parse_ternary` rather than the public `parse_expr` (which just delegates to it) because the `? :` else-chain recurses into `parse_ternary` directly; same reason `parse_unary` and `parse_gen_if` are gated individually — both have direct self-recursion that bypasses their usual entry point. - Verified every gated family end-to-end with the **real debug binary** on 16 adversarial files (200–400 levels of parens, unary, ternary, concat, calls, assignment patterns, dims, statements, `else if`, fork, case, generate `if`/`for`/`else if`, task bodies): all 16 now report `parse error: L:C: nesting too deep (limit 64)` and exit 2 — no crashes, no `SIGABRT`, no missing summary. Confirmed the boundary is exact by bisecting with the binary: 59 nested `begin` blocks format, 60 error; 30 nested parens format, 31 error. - The scratchpad copy and probe binaries were used only for measurement and live outside the repo; nothing generated by them was committed. **Results:** `cargo test --workspace` **80 passed, 0 failed** (up from 70: +6 `vlog_parser` unit, +3 `vlog_formatter` `deep_nesting`, +1 `lucisv` CLI). `cargo clippy --all-targets` silent. `cargo fmt --check` clean. Files touched: `crates/vlog_parser/src/parser.rs`, `crates/vlog_formatter/tests/deep_nesting.rs` (new), `crates/lucisv/tests/cli.rs` (one test), `TODO.md` (one checkbox), this README. ### 2026-08-19 (later) — dev agent, answering QA round 1 - **The blocking finding is correct and was reproduced first thing**: `./target/debug/lucisv` on `assign x = a` + `.b`×1500 died with SIGABRT (exit 134). Bisected the crash with the real binary before touching anything, and swept the whole shape class rather than just the reported one — crash thresholds on the default 8 MiB main-thread stack, debug: `a.b…` / `a[0]…` / `a++…` **1392 segments** (2.8 KB file), `a inside {1}…` 1392, `a+a…` in a dimension **5824**, `a + a…` in an expression **40448**. So the hole was wider than member chains: every loop that wraps what it has already built. - **Root cause, stated precisely:** the five gates bound *parser recursion*, and the audit's premise was *AST depth*. Those coincide only when every layer of tree costs a parser frame. `parse_postfix` and `parse_binary` build layers in a loop, so they broke the premise; the formatter, which recurses per layer, was the thing that actually died. Re-derived the invariant in the new section at the top of this README so the premise is stated where it can be checked, not left implicit. - **Fix: a second path-accumulated counter** (`links`, `MAX_CHAIN_LENGTH`) charged per postfix segment and per binary/`inside` operator, released by restoring the count the chain started from. Considered and rejected two alternatives: (a) charging chain links against `MAX_NESTING_DEPTH`, which is what "reuse the same limit" would mean — it caps flat operator chains at ~60 terms, so a 64-bit parity XOR or a 128-term generated sum would start failing to parse, a real acceptance regression; (b) making the formatter's `binary_chain::walk` and `expr_compact` iterative instead — that fixes two call sites but leaves AST depth itself unbounded (the recursive `Drop` of a deep `Box` chain would still abort), i.e. it treats a symptom. The counter restores the invariant for every consumer at once. - **Restore-by-assignment, not decrement**, because a chain's length is not known in advance and early `?` returns are everywhere; `self.links = outer_links` is correct on every path and makes nesting compose properly — an inner chain stacks on the outer one (so `a.b…(a.b…(…))` cannot multiply the budget) while siblings each start fresh. Both properties have tests. - **Re-audited the parser for the same shape** by listing every `Box::new` site (38 of them) and checking which sit inside a loop: only the six in `parse_postfix` and the two in `parse_binary`. Everything else boxes once per gated recursive call, and the list-building loops collect into `Vec`s, which widen the tree rather than deepening it. Recorded as a requirement on future parser work in Handshakes. - **Chose 256 by measuring, again** (new "Why 256 for chains" table). Because deep statements peak during parsing and long chains during formatting, the chain budget does not add to the global worst case: 3895 KiB with a maximal chain inside maximal nesting versus 3959 KiB for nesting alone. So the constant was chosen for acceptance, not stack: 256 covers a 256-term generated sum. - **QA's medium finding fixed and verified the way QA found it**: rewrote the release-discipline test around a unit that exercises every gate and both chain sites, then deleted each of the seven release statements in turn and re-ran `cargo test -p vlog_parser`. Before: 0 of 7 caught for `parse_unary` (QA's example). Now: 7 of 7 caught. The last one to fall was `parse_postfix`'s restore, which `parse_binary`'s restore masks — it only shows up on sibling chains *inside one expression*, so the test now has `a.b×200 + c.d×200` (legal at 200 each, over budget if they accumulate). - **QA's low finding fixed**: the boundary prose is now a table that names each construction, including both `begin` shapes (62/63 empty, 59/60 with a statement inside) and which test uses which. - Re-ran the full adversarial sweep with the real debug binary on 15 files (all chain families at 1500, nested-index and nested-call chains, a chain inside 200 nested `begin`s, nested assignment patterns) — every one exits 2 with a clean `nesting too deep` or `expression chain too long`, none crash. Batch survival re-checked with QA's exact repro in a 3-file directory: `2 files reformatted, 1 file failed to format`, exit 2, the chain file byte-identical. Legal maxima still format: a 128-term wide sum, 10,000 sequential statements, and 59 nested `begin`s holding a 250-link chain. **Results:** `cargo test --workspace` **86 passed, 0 failed** (up from 80: +4 `vlog_parser` unit, +1 `vlog_formatter` `deep_nesting`; the CLI batch test 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. ### 2026-08-29 — dev, the chain budget real code outgrew Written as part of the testbench wave's round 2; the full narrative, the whole-tree distribution and the probe method are in `docs/features/clocking-wave/README.md`. What matters here: - **The trigger was acceptance, not a crash.** Seven real OpenTitan files — generated register tops — were being *rejected* with `expression chain too long (limit 256)`. The 2026-08-19 round chose 256 for exactly this reason ("256 covers a 256-term generated sum") against a smaller tree; the tree grew. Measured the whole 3,943-file distribution rather than the seven, so the new number is chosen against the shape of real generated code (max 567, five files in 257–512, two over 512) instead of against the failures. - **Re-measured the slope, did not extrapolate the old number.** Four chain lengths (640/768/1024/1280), debug and release, bisected one trial per subprocess. 9.20 KiB per postfix link debug — close to the ~9 KiB measured at 256, so the cost is genuinely linear and 1024 lands where arithmetic says. - **The honest finding: this round breaks one of the feature's own claims.** Both earlier rounds concluded that raising the chain budget is free on the stack, because chains peaked at 2.4 MiB against nesting's 5.9. At 1024 a maximal chain peaks at 9.4 MiB alone and 9.9 MiB inside nesting, so the chain is now the global worst case and the claim is retired above rather than quietly left standing. What survives — and was re-verified, not assumed — is the *reason* it was ever true: the two peak in different phases, so they compose additively. 64 nested `case` with and without a 1024-link chain inside bisect to the identical 5 959 KiB. - **`PARSE_STACK_SIZE` follows the measurement, as designed.** 16 MiB is 1.65× the new worst case; the constant's whole argument is margin over fit, so it moves to 32 MiB (3.3×). No consumer changes: every parse site already spells the constant, which is exactly what round 3 put it there for. - **One un-charged chain loop found while working nearby.** `parse_sens_list`'s paren-less `@a.b.c` path built one `Expr::Member` per segment in a loop without charging `link()` — the `Box::new(previous)` shape this README's Handshakes makes a standing requirement, missed because the loop lives in the event-control code rather than in `parse_postfix`. Lifted into `parse_bare_event_name`, charging both segment kinds and restoring the count it started from; `a_bare_event_control_charges_the_chain_budget` pins it. - Files touched here: `crates/vlog_parser/src/parser.rs` (three doc comments, the two constants, the new chain site), `crates/vlog_formatter/tests/deep_nesting.rs`, this README. ## QA log ### 2026-08-19 — QA agent **Tooling results (verbatim):** - `cargo test --workspace`: **80 passed, 0 failed** (8 test binaries: 18 + 13 + 3 + 1 + 3 + 2 + 19 + 21, doc-tests 0 + 0). Matches the claimed count exactly. - `cargo clippy --all-targets`: silent, no warnings. - `cargo fmt --check`: clean, exit 0. **Claim 4 (150-level repro, batch survival) — CONFIRMED**, checked two ways: - `cargo test -p lucisv deeply_nested_file_does_not_kill_the_batch` passes. - Independently, ran the real debug `lucisv` binary (not the test harness) on a 3-file batch (`good`, 150-level `if…begin` repro, `good`) in the scratchpad: exit 2, `error: b_deep.sv: parse error: 32:5: nesting too deep (limit 64) (found "clk")`, `2 files reformatted, 1 file failed to format`, `b_deep.sv` byte-identical to the original, both `a_before.sv` and `c_after.sv` reformatted. Exactly as claimed, for this specific repro. **BLOCKING — an un-gated recursion cycle exists; it defeats the feature for a whole class of input.** `parse_postfix` (`crates/vlog_parser/src/parser.rs:1854`) is a `while` loop, not a gated recursive function, and the five gates guard *parser call depth*, not *AST depth*. For every postfix chain the loop builds iteratively — member access (`.name`), scope resolution (`::name`), index (`[expr]`), and a call with no arguments (`()`) — each additional segment costs the parser **zero** depth (`enter`/`leave` never fire for the chain itself; only a bracket's *contents* go through the gate, and those contents return to baseline before the loop's next iteration). The loop instead builds `Expr::Member{base: Box, ..}` /`Index`/`Scope`/`Call` one layer deeper per segment, so **the AST it produces is exactly as deep as the input, with no limit at all.** `vlog_formatter`'s `Fmt::expr` (`crates/vlog_formatter/src/format.rs:1460`) then recurses structurally into that AST — `Expr::Member => concat(vec![ self.expr(base), ...])` and the same pattern for `Index`/`Scope`/`Call`/ `Postfix` (lines 1479–1494, 1546) — so formatting one of these chains recurses once per input segment, unbounded by `MAX_NESTING_DEPTH`. This falsifies the Handshakes promise ("AST depth is bounded by `MAX_NESTING_DEPTH`") and the formatter-audit conclusion in this same README: the audit's premise ("every recursive path descends into a child node ... bounded by AST depth, which the parser now bounds") is true as an implication but the antecedent is false for chain-built AST, so the conclusion doesn't hold. Confirmed with the real debug binary, not just a probe: ``` python3 -c " n = 1500 s = 'module m;\nassign x = a' + '.b'*n + ';\nendmodule\n' open('member_chain_1500.sv','w').write(s)" ./target/debug/lucisv member_chain_1500.sv # thread 'main' (NNNN) has overflowed its stack # fatal runtime error: stack overflow, aborting # exit code 134 (SIGABRT) ``` A 3 KiB file, ~1500 `.b` segments (`a.b.b.b...`), crashes on the default 8 MiB main-thread stack — no artificial thread-size trick needed, well within a plausible generated-code size. Bisected the crash threshold at n=8, stack=8 MiB: fails between n=1200 (OK) and n=1400 (crash); same order of magnitude for `::name` scope chains, `[0]` index chains, and `()` empty call chains (all confirmed crashing at n=1500 with `Fmt::expr` on the call stack — `parse_source` alone survives to n≥3000 on the same stack, so the formatter's recursion is the earlier failure point, not the parser's Drop glue). `f(g(h(...)))` (nested *non-empty* calls) and `(((...)))` (nested parens) are **not** part of this hole — those go through `parse_expr` for each level and are correctly gated. **Reproduces the original bug this feature exists to fix**, via batch processing: 3-file batch (`good`, `a.b.b...` ×1500, `good`) through the debug CLI aborts with SIGABRT (exit 134, no exit-2 summary), the file *before* the crash was already applied in place, and the file *after* it was never reached — the exact "mid-batch death, uncatchable by `catch_unwind`" failure the Goal section describes. This directly falsifies **claim 1** ("every unbounded recursion cycle passes through one of the five gates") as stated: the cycle exists in the *formatter*, seeded by an un-gated *parser* loop, and no gate anywhere sees it. Recommend gating either `parse_postfix`'s loop (cap the chain length, or route it through `enter`/`leave` per segment) or the formatter's `expr` recursion directly (an explicit depth counter or an iterative work-stack, matching how `printer.rs` already avoids recursion). The five *parser-recursion* gates are otherwise sound — see below — this is specifically an AST-shape gap the current design doesn't cover. **Independent gate-coverage audit (parser call graph) — otherwise sound.** Traced every function in `parser.rs` that calls back into item/stmt/expr parsing. `parse_binary` is genuinely self-bounded (confirmed by reading the precedence-climbing logic: same-precedence operators loop in the *same* frame via `while`, only a strictly higher-precedence RHS recurses, capped at 11 levels). All list/loop functions (`parse_dims`, `parse_declarators`, `parse_expr_list`, `parse_connections`, `parse_tf_body`, `parse_source_file`, and the postfix loop discussed above) are iterative and only recurse *into* a gated function per iteration — with the one exception above, where the "into" is actually "next to" (AST-building without a parser call). Tried and confirmed correctly gated (clean `nesting too deep` error, no crash, at 200–400 levels): nested assignment patterns (`'{a: '{a: ...}}`), nested replications (`{2{{2{...}}}}`), stacked casts (`int'(int'(...))`), event-expression nesting (`@((((posedge clk)))`), alternating concat/ternary (`{{{1}?1:0,1}?1:0,...}`), and dimension-expression nesting (`[a[a[a[...]]]]`). Hierarchical names (`a.b.c...`) are, per the task's question, confirmed **iterative** — which is exactly the problem, not a mitigation, per the blocking finding above. **leave() discipline — code is correct, but the "sibling-nesting" test's claimed coverage is overstated.** All five gated wrappers use the same `enter()?; let out = …_inner(); leave(); out` shape, which — read carefully — cannot leak: `leave()` runs unconditionally once `enter()` succeeds, with no `?` between them, on every path including `parse_X_inner`'s internal errors. So there is no live leak in the shipped code. Empirically tested the claim that `depth_is_released_on_the_way_out` "would catch a missing `leave()`" (`crates/vlog_parser/src/parser.rs`, in `mod tests`): temporarily deleted `self.leave();` from `parse_unary` (reverted afterward via `git diff` — repo now shows the original 195 insertions / 2 deletions again, confirmed clean), reran `cargo test -p vlog_parser`. **All 21 tests still passed, including `depth_is_released_on_the_way_out`.** The sibling test's 200×40 nested `begin`/`end` blocks contain no expressions and no generate constructs, so it only exercises `parse_item`/`parse_stmt`; a missing `leave()` in `parse_ternary`, `parse_unary`, or `parse_gen_if` would sail through undetected by any committed test. Suggest either broadening that test to include repeated sibling expressions/generates, or narrowing the Status/ TODO claim to "catches a leak in the statement-nesting gates." Separately confirmed the general (non-adversarial) case: a file with 10,000 sequential (non-nested, depth-1) statements parses and formats fine (`1 file reformatted`, exit 0) — no depth accumulation across siblings for the common case. **Boundary numbers — both exact, but the README's prose number doesn't match what the committed unit test encodes.** Verified with the real debug binary, cleanly bisected: - Parens: **30 nested `(...)` format, 31 error** — matches the README exactly, and matches `vlog_formatter/tests/deep_nesting.rs`'s `nested_parens(MAX_NESTING_DEPTH/2 - 2)` = 30. Arithmetic checks out: each paren level costs 2 gate-entries (`parse_ternary` discovers the `(`, recurses into a fresh `parse_expr` → `parse_ternary`+`parse_unary` for the contents), plus a fixed 2-deep baseline (module item + assign item), so `2·(d+1) + 2 ≤ 64 ⇒ d ≤ 30`. Exact. - Begin blocks: the README's "Why not smaller" prose says **"59 nested `begin` blocks"**; I get exactly **59 OK / 60 error** too, *but only when there's a real statement inside the innermost block* (`x <= 1;` — this costs 2 more gate-entries, since parsing "1" itself enters `parse_ternary`+`parse_unary`). The parser's own committed unit tests (`nesting_just_below_the_limit_parses` / `..._past_the_limit_is_a_parse_error`) use `nested_begins()`, which has an **empty** innermost block (no statement at all), and that construction's real boundary is **62 OK / 63 error** — confirmed by running both `begin62.sv`/`begin63.sv` and `begin59.sv`/`begin60.sv` through the debug binary directly. Both pairs of numbers are internally consistent with the code (verified the arithmetic: `n + 2 ≤ 64` for the empty-block case, `n + 5 ≤ 64` for the case with a statement), but the README states "59" as *the* boundary without saying which construction it's measuring, and it doesn't match what the shipped test actually checks (62/63). Not a code bug — a documentation-precision gap that could mislead whoever next tunes `MAX_NESTING_DEPTH`. Left as-is (not a "small unambiguous fix" — the dev should pick one canonical construction and re-measure/re-word intentionally, this isn't mine to arbitrate). **16 MiB test-thread trick — confirmed necessary and correctly confined.** Verified with a stack-size probe: parsing *and merely dropping* (no formatting at all) the worst-case family (nested `begin`/statement) at its exact legal max depth (59, with a real statement inside) already overflows a 2 MiB *and* a 1 MiB thread — confirming the README's claim that Drop of a deep AST, not just the recursive format walk, needs the generous stack. By contrast, the parens family at its legal max (30) survives fine on a 2 MiB thread even through full `format_source` — so the "worst family" ranking in the measurement table (statements > generate > parens/concat > ternary/unary) checks out relative to each other. Confirmed by grep that the stack-size tricks (`std::thread::Builder::new().stack_size(16 * 1024 * 1024)`) appear only in `#[cfg(test)]` code (`parser.rs`'s `mod tests`, `vlog_formatter/tests/deep_nesting.rs`) — never in library or `main.rs` code — and are documented inline at each call site. **Formatter audit spot check — the "structural descent" claim itself holds** for genuinely-recursed AST (`format.rs`/`printer.rs` grepped for direct self-recursion beyond a child argument: none found: `item`, `stmt`, `expr`, `gen_if` — iterative — and friends all descend into a field of their own argument). `printer.rs`'s `print`/`fits` are genuinely iterative (explicit `Vec`-based work stack, confirmed by reading the loop); `contains_hard_line` is the one recursive function there, over the `Doc` tree, which inherits the same unbounded-depth problem as the blocking finding for chain-built AST (a `Doc::Concat` chain as deep as the AST). The audit's *method* is sound; its *conclusion* is undermined by the blocking finding, because the premise ("AST depth is bounded") isn't actually true for the AST shapes `parse_postfix` builds. **CLAUDE.md compliance:** - `MAX_NESTING_DEPTH` is `pub`, documented with rationale (`crates/vlog_parser/src/parser.rs:67-75`). Good. - Error message carries `line:col` and names the limit (`nesting too deep (limit 64)`) — actionable. Good. - No `unwrap()`/`expect()`/`panic!` added in library code by this diff (checked every line of the parser.rs diff outside `#[cfg(test)]` — none). Good. - No `Cargo.toml`/`Cargo.lock` changes — no new dependency. Good. - README has all required sections (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA log, Review). Good. - TODO.md checkbox: "Recursion-depth limit in the parser" is checked off. Given the blocking finding above, this is **premature as a general claim** — the specific repro that motivated the item (150 levels of `if`/`begin`) is genuinely fixed, but "recursion-depth limit in the parser" as a general guarantee against stack-overflow-by-nesting is not yet true, since the formatter can still be crashed by parser-accepted input. Flagging for the lead's judgment on whether to uncheck pending a fix, or check with a caveat. **Severity summary:** - **BLOCKING**: un-gated postfix-chain cycle (member/scope/index/empty-call) lets the formatter stack-overflow on parser-accepted input; reproduces the original mid-batch-death bug. See repro above. - **Medium**: `depth_is_released_on_the_way_out`'s claimed coverage ("would catch a missing `leave()`") is overstated — empirically verified it does not catch a leak in `parse_unary`/`parse_ternary`/`parse_gen_if`. - **Low**: README's "59 nested begin blocks" prose doesn't match the boundary the committed unit test actually encodes (62/63) — both numbers are correct for their own (different, undisclosed) input shape. - No findings on: tool results (all clean, counts match exactly), parser-recursion gate coverage for genuinely-recursive constructs, the 16 MiB test-thread rationale, `unwrap`/`expect` hygiene, new dependencies, or README structure. No fixes applied to `crates/` — the blocking finding needs a design decision (gate the postfix loop vs. gate the formatter's `expr` walk) that's the dev agent's / lead's call, not a "small unambiguous fix." ### 2026-08-19 (later) — QA agent, re-verification of the chain-budget fix **Tooling results (verbatim):** `cargo test --workspace`: **86 passed, 0 failed** (8 binaries: 18 + 13 + 3 + 1 + 4 + 2 + 20 + 25, doc-tests 0 + 0) — matches the dev's claimed count exactly, up 6 from round 1 (+2 parser unit, +1 formatter `deep_nesting`, CLI batch test gained a second pathological file so its own count is unchanged but its assertions grew). `cargo clippy --all-targets`: silent. `cargo fmt --check`: clean, exit 0. **Job 1 — original blocking repros: CONFIRMED FIXED.** Rebuilt the debug binary fresh (touched `parser.rs` to force a rebuild, confirmed via the binary's mtime) and reran all four original crash shapes at n=1500 through the real `lucisv`, default 8 MiB stack: ``` member1500.sv -> parse error: 2:525: expression chain too long (limit 256) (found ".") exit 2 scope1500.sv -> parse error: 2:781: expression chain too long (limit 256) (found "::") exit 2 index1500.sv -> parse error: 2:781: expression chain too long (limit 256) (found "[") exit 2 emptycall1500.sv -> parse error: 2:525: expression chain too long (limit 256) (found "(") exit 2 ``` No SIGABRT, no artificial thread-size trick. Batch survival re-checked with my exact original 3-file layout (`good`, `member1500.sv`, `good`): `2 files reformatted, 1 file failed to format`, exit 2, `b_deep.sv` byte-identical to the original, both the file before and the file after it were reformatted. Also ran the dev's own new CLI test (`deeply_nested_file_does_not_kill_the_batch`, now a 4-file batch combining the 150-level statement repro *and* a 1500-segment chain in the same run): passes. **Job 2 — tried to break the depth+links=320 invariant: no hole found.** Worked the arithmetic first, then verified every case on the real debug binary. The mechanism: `self.links` is one Parser-wide counter: `link()` always checks and increments the *current* total (whatever's accumulated from every not-yet-returned `parse_postfix`/`parse_binary` frame on the current call stack), and each frame's own wrapper restores it to exactly what it was when that frame was entered, on every return path (no `?` between the inner call and the restore — same shape as `enter`/`leave`). That makes `self.links` at any instant equal to the sum of links open *on the current root-to-position path* — never per-subtree, never per-sibling — so nested chains stack (additive) and sibling chains don't (independent budgets), which is exactly what a recursive tree-walk's stack usage needs: sibling subtrees are visited sequentially, so only one branch's depth is ever live on the stack at once, and a single path's cost is `depth_used + links_used`, never a product. `depth` and `links` are separate counters, so there is no cross term at all — one budget being 64 and the other 256 cannot become 64×256 because nothing ever multiplies them; they just both have to stay under their own ceiling on the same path. Tried to defeat that empirically anyway, all on the real debug binary, default stack, no crashes found — every case either formatted (within budget) or errored cleanly citing the correct limit name: | construction | result | |---|---| | nested calls, each arg its own chain (`a.b×5(a.b×5(...×60 levels)))`) | correctly rejected — `nesting too deep` (60 nested call-args cost 120 depth via repeated fresh `parse_expr` entries, hits the depth ceiling before the ~360 combined links would) | | same, milder (1–32 call levels × 10–300 links/level) | correctly rejected — `expression chain too long`, additive as predicted | | 30 grouping parens wrapping one 256-link chain | **accepted** (286 total layers, under 320) — `parenswrap_30_256.sv` | | 60 stacked `~` feeding a 250/256-link postfix chain | **accepted** — depth and links both independently near their ceiling, sum under 320 | | `a inside {b inside {c inside {...}}}` , 100/128/129/130 deep | correctly rejected — `nesting too deep` (each level costs a fresh `parse_expr` = 2 depth; links stay near 1 because deeper levels self-restore before the current level's own `link()` fires) | | `[a+a+a+...+a:0]` dimension binary chain | **256/257 terms accepted, 300/6000 rejected** with `expression chain too long` — down from the pre-fix 5824-term crash threshold reported in the dev's sweep; confirmed fixed, not just moved | | postfix chain on a concat result (`{a}.b×n`) | 250 accepted, 260/300 rejected — gated the same regardless of what the primary was | | postfix chain on a replication result (`{2{a}}.b×n`) | 250 accepted, 260 rejected — same | | stacked casts `a'(a'(a'(...)))`, 60/300 deep | correctly rejected — `nesting too deep` (each cast's inner content is a fresh `parse_expr`, so this is depth-gated, not links-gated) | | postfix `++` chain, 300 deep | correctly rejected — `expression chain too long` | | 59 nested `begin` holding a 250- and a 256-link chain | both **accepted** — matches the dev's claimed combined worst case; 60 nested `begin` with a 250-link chain correctly rejected on depth before the chain is even reached | | 109 KB file, 500 mixed constructs (chains, parens, unary, `inside`, wide sums), each individually within budget | **accepted**, no false positive, no crash | No construction pushed AST depth past what the two independent ceilings allow, and nothing multiplied them. Claim 2 (the new invariant) holds under adversarial pressure. **Job 3 — sabotage-verified 3 of the 7 release sites myself (not just trusting the dev's 7/7 claim).** Picked `parse_unary`'s `leave()` (my own round-1 finding — this one used to pass undetected), `parse_postfix`'s `self.links = outer_links` restore, and one of `parse_binary`'s restore. For each: deleted the release statement, ran `cargo test -p vlog_parser`, recorded the failure, then restored the exact original line and reran to confirm 25/25 pass again before moving to the next site. - `parse_unary` `leave()` deleted → **2 tests fail**: `long_chains_error` and `depth_and_links_are_released_on_the_way_out` (both now trip `nesting too deep` where they shouldn't). This is the one round 1 found *undetected* — now caught, confirming the medium finding is fixed. - `parse_postfix` restore deleted → **1 test fails**, and specifically the right one: `depth_and_links_are_released_on_the_way_out` panics with `"sibling chains in one expression must not accumulate links"` — i.e. the `a.b×200 + c.d×200` assertion the dev's work log says was added because it's the one case that catches this particular release site (a chain that fully finishes and gets re-parsed as a fresh sibling wouldn't expose it; two chains *within one expression* do). Verified the dev's specific claim about which assertion matters, not just that some assertion fails. - `parse_binary` restore deleted → **1 test fails**, same test, this time via a plain long binary chain (`+`) tripping the length check early. All three reverted by hand back to the exact original three lines (no stray edits — confirmed via `grep -c "QA SABOTAGE" parser.rs` = 0 after each revert and a full `cargo test -p vlog_parser` pass in between). Final state: `git diff --stat crates/vlog_parser/src/parser.rs` shows the same 346 insertions / 6 deletions as before I started sabotaging, and all 25 parser tests pass. I did not test the other 4 sites (`parse_item`, `parse_stmt`, `parse_gen_if`, `parse_ternary` `leave()`s), but given the 3/3 result and that they share the exact same wrapper shape, I have no reason to doubt the dev's 7/7 claim for the rest. **Job 4 — legal acceptance: no regression found.** All on the real debug binary: a 128-term flat sum (`a0+a1+...+a127`) — accepted; a realistic-looking RTL file (parameterized pipeline module, `generate for`, `always_ff`, `case`) — accepted; the committed `small_cases` fixture suite (~190 table-driven cases across `tests/cases/*.cases`) — all pass; 59 nested `begin` holding a 250-link chain — accepted (see table above); 10,000 sequential (non-nested) statements — accepted. No false positives. **Job 5 — boundary table spot-check: 3 of 5 rows checked, one is wrong.** - Parens row (`30` OK / `31` errors): **matches exactly**, reconfirmed with fresh files. - `begin` + statement row (`59` OK / `60` errors): **matches exactly**. Also reconfirmed the empty-`begin` row (`62`/`63`, used by the parser's own boundary unit tests) for good measure — also matches. - Generate-`if` row, claimed **"29 (30 errors)"**: **does not match.** Measured `30` OK / `31` errors on the real binary, for both the natural reading of the row (`if (1) begin ... end`, nested, innermost holding `wire w;`) and the empty-innermost-block variant — both give the same 30/31 boundary, not 29/30: ``` genif29.sv (29 levels) -> 1 file reformatted (exit 0) genif30.sv (30 levels) -> 1 file reformatted (exit 0) genif31.sv (31 levels) -> nesting too deep (limit 64) (exit 2) ``` This table row is off by one. Low severity — the underlying mechanism is still correctly and safely bounded (nothing crashes either side of the true boundary), it's the documented number that's wrong. No committed test asserts this specific boundary (unlike the parens and `begin` rows, which are pinned by `deep_nesting.rs`/the parser's own unit tests), which is presumably how a manually-bisected number went stale or was mistyped. Did not fix it myself — one-line table edit, but I'd rather the dev re-bisect and confirm the exact construction they measured matches what's in the table, same reasoning as round 1's begin-boundary finding. **Job 6 — standard checks, all pass:** - `MAX_CHAIN_LENGTH` is `pub`, documented with rationale (why 256, why larger than `MAX_NESTING_DEPTH`, ~6 KiB/link vs ~62 KiB/statement) at `crates/vlog_parser/src/parser.rs:77-94`. - No `unwrap()`/`expect()`/`panic!` added in library code (checked every line of the new diff outside `#[cfg(test)]`, including `link()` and both new wrappers — none). - `## The invariant` section is present near the top of this README, states the bound precisely (`MAX_NESTING_DEPTH + MAX_CHAIN_LENGTH` = 320) and explains why the two counters compose additively rather than multiplicatively — this is the section job 2 above set out to break, and couldn't. - TODO.md §1's checkbox is `[x]` again, with the round-1-era "in progress, QA found postfix chains unbounded" caveat text removed now that the gap it described is closed. Given job 1/2's results, this is honest. - `verify.rs` / `tests/verification.rs` changed since my first pass, per the lead's note (unrelated committed lead fix, diagnostic escaping) — did not investigate further, out of scope for this feature. - Confirmed no changes outside `crates/`, `TODO.md`, and this README; `tools/`, `corpus/`, and `docs/features/corpus-check/` untouched by me. **Verdict per fix:** - **Blocking (round 1, postfix/binary chain-built AST unbounded): FIXED.** Verified with the exact original repros plus 20+ new adversarial combinations designed to defeat the additive-composition claim specifically. No crash found anywhere. - **Medium (round 1, `leave()`-leak test coverage overstated): FIXED.** Sabotage-verified 3 of 7 sites myself; all 3 now caught (my own `parse_unary` example included), where round 1 showed 0 of them were. - **Low (round 1, begin-boundary prose ambiguity): FIXED** — replaced with a table that names each construction; both begin rows reconfirmed exact. - **New — Low (this round): generate-`if` boundary row states "29 (30 errors)"; measured boundary is 30 OK / 31 errors.** Not blocking, not a code defect — a stale/mistyped number in a table that has no committed test pinning it. Repro above. 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: : 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.** This feature is the best demonstration yet of why the dev/QA split exists. Round 1 shipped a measurement-driven parser gate that was genuinely good work — and still carried a fatal blind spot: bounding *parser recursion* is not bounding *AST depth*, and the formatter dies on the latter. QA earned its keep twice: first by finding the postfix hole empirically (a 3 KiB crashing file), then by proving the leak test didn't cover three of the five gates via sabotage. The rework earned the acceptance: the dev widened QA's finding to `parse_binary`/`inside` before touching code, chose the two-budget design for *acceptance* reasons (a single budget would have rejected legal 128-term sums — correctness includes not rejecting valid input), stated the invariant precisely (path depth ≤ 64 + 256), and made the leak tests sabotage-complete (7/7). Re-QA then attacked the additive-composition claim directly — the one load-bearing piece of arithmetic — and it held. Points I reviewed and accept: 1. **Restore-by-assignment over decrement** for the chain budget: right call — it is correct on every `?` early-return path by construction, where paired decrements have to be right at every exit. 2. **The 38-site `Box::new` audit** distinguishing depth-growing loops (8 sites, all now charged) from width-growing `Vec` collectors: this is the analysis round 1 should have had, and it is now a standing Handshake requirement on future parser work. 3. **Limits as constants of the public API** (`MAX_NESTING_DEPTH`, `MAX_CHAIN_LENGTH`, both pub and documented) with boundary numbers tied to named constructions in the README table. 4. The lead corrected the one remaining nit (generate-if boundary row, 29/30 → measured 30/31) directly in the table above. Standing handshakes reaffirmed for future rounds: rayon workers need ≥8 MiB stacks (TODO §3); error-tolerant parsing must not reset `depth` or `links` during recovery (TODO §6); any new parser loop that boxes a base expression per iteration must charge the chain budget.