diff --git a/crates/vfmt_server/src/inline.rs b/crates/vfmt_server/src/inline.rs
index a7c7d9ea..6f7b944 100644
--- a/crates/vfmt_server/src/inline.rs
+++ b/crates/vfmt_server/src/inline.rs
@@ -511,12 +511,12 @@ endmodule
// module never walks that tree — `triggered`/`unfinished` read
// `doc.tokens` and `pairs::analyze`, both flat loops over the token
// stream, so neither can overflow the stack the way the parser once
- // did. QA find, 2026-08-25: those flat loops are not all *linear*,
- // though — `pairs::analyze` is quadratic in the depth of rainbow
- // nesting (`pairs.rs:157`), which this module now calls on every
- // keystroke inside an unclosed `begin`. 3,000 is past where that
- // shows up in a debug build (tens of ms) without making this test
- // itself slow; see the QA log for the full characterization.
+ // did. QA find, 2026-08-25: `pairs::analyze` was quadratic in the
+ // depth of rainbow nesting back then, which mattered because this
+ // module calls it on every keystroke inside an unclosed `begin`. It
+ // is linear now — `Stack`'s running counts in `pairs.rs`, whose own
+ // tests pin the scaling — and this depth stands guard on the caller's
+ // side of that contract.
let depth = 3_000;
let mut text = String::from("module top;\n");
for _ in 0..depth {
diff --git a/crates/vfmt_server/src/pairs.rs b/crates/vfmt_server/src/pairs.rs
index 3eab47c..94e478d 100644
--- a/crates/vfmt_server/src/pairs.rs
+++ b/crates/vfmt_server/src/pairs.rs
@@ -116,12 +116,105 @@ pub struct ScopeAnalysis {
/// An open scope, waiting for its closer.
struct Frame {
rule: &'static Rule,
+ /// The rule's position in [`RULES`], carried so a frame leaving the stack
+ /// can find the count it has to give back without searching for it.
+ rule_index: usize,
span: TextRange,
/// Enclosing rainbow scopes at the moment this one was pushed — see
/// [`Pair::depth`], which is where it ends up.
depth: u32,
}
+/// The open scopes, with the two running counts that keep [`analyze`] linear.
+///
+/// Both counts answer a question the frames could answer by themselves, and
+/// that is the point: asking the frames costs a walk of the whole stack, once
+/// per token, which is quadratic in nesting depth. A file that opens ten
+/// thousand `begin`s — a generate ladder, or a half-typed one — took seconds
+/// that way, on a path the inline-completion gate runs at every keystroke.
+///
+/// **The invariant, maintained by this type and nowhere else:** `rainbow` is
+/// the number of frames on the stack whose opener [`is_rainbow`], and
+/// `per_rule[i]` is the number of frames the rule at `RULES[i]` has on it.
+/// Both survive the middle-of-stack removal in [`close`], which is why every
+/// removal goes through [`Stack::drain_above`] or [`Stack::pop`].
+struct Stack {
+ frames: Vec,
+ rainbow: u32,
+ per_rule: [u32; RULES.len()],
+}
+
+impl Stack {
+ fn new() -> Self {
+ Stack { frames: Vec::new(), rainbow: 0, per_rule: [0; RULES.len()] }
+ }
+
+ /// Open a scope. Its [`Pair::depth`] is the rainbow count as it stands —
+ /// the enclosing rainbow scopes, not counting itself.
+ fn push(&mut self, rule_index: usize, rule: &'static Rule, span: TextRange) {
+ let depth = self.rainbow;
+ if is_rainbow(rule.open) {
+ self.rainbow += 1;
+ }
+ if let Some(count) = self.per_rule.get_mut(rule_index) {
+ *count += 1;
+ }
+ self.frames.push(Frame { rule, rule_index, span, depth });
+ }
+
+ /// The topmost frame `closer` can close, if the stack holds one.
+ ///
+ /// The counts are consulted first, so a closer that matches nothing — a
+ /// stray `endcase` under a thousand open `begin`s — is answered by a walk
+ /// of the twenty-one-entry rule table rather than of the stack. When there
+ /// *is* a match, the frames the scan walks past are exactly the ones
+ /// [`close`] then removes, so the scan pays for itself and the whole pass
+ /// stays linear.
+ fn match_index(&self, closer: &'static str) -> Option {
+ let reachable =
+ RULES.iter().zip(self.per_rule).any(|(r, n)| n > 0 && r.close.contains(&closer));
+ if !reachable {
+ return None;
+ }
+ self.frames.iter().rposition(|f| f.rule.close.contains(&closer))
+ }
+
+ /// Remove every frame above `index`, in source order — the middle-of-stack
+ /// pop the mismatch recovery performs. `index` is one this stack produced,
+ /// so the range is always in bounds.
+ fn drain_above(&mut self, index: usize) -> std::vec::Drain<'_, Frame> {
+ let Stack { frames, rainbow, per_rule } = self;
+ for frame in frames.iter().skip(index + 1) {
+ if is_rainbow(frame.rule.open) {
+ *rainbow = rainbow.saturating_sub(1);
+ }
+ if let Some(count) = per_rule.get_mut(frame.rule_index) {
+ *count = count.saturating_sub(1);
+ }
+ }
+ frames.drain(index + 1..)
+ }
+
+ /// Close the innermost scope.
+ fn pop(&mut self) -> Option {
+ let frame = self.frames.pop()?;
+ if is_rainbow(frame.rule.open) {
+ self.rainbow = self.rainbow.saturating_sub(1);
+ }
+ if let Some(count) = self.per_rule.get_mut(frame.rule_index) {
+ *count = count.saturating_sub(1);
+ }
+ Some(frame)
+ }
+
+ /// Give up the stack at end of stream: whatever is left never closed.
+ /// Consuming the whole `Stack` rather than draining it is deliberate — it
+ /// leaves no counter behind for a later reader to trust.
+ fn into_frames(self) -> Vec {
+ self.frames
+ }
+}
+
/// Match every scope keyword in a token stream.
///
/// Never panics and never gives up: a stream that is unbalanced in any
@@ -129,7 +222,7 @@ struct Frame {
/// missing `end` halfway down a file from un-colouring everything below it.
pub fn analyze(tokens: &[Token]) -> ScopeAnalysis {
let mut analysis = ScopeAnalysis::default();
- let mut stack: Vec = Vec::new();
+ let mut stack = Stack::new();
// Raised by `PROTOTYPE_STARTERS`, dropped at the `;` that ends the
// statement. Everything between the two opens nothing.
let mut prototype = false;
@@ -147,15 +240,12 @@ pub fn analyze(tokens: &[Token]) -> ScopeAnalysis {
prototype = true;
continue;
}
- if let Some(rule) = opener_rule(text) {
+ if let Some((rule_index, rule)) = opener_rule(text) {
if !prototype && opens_a_scope(tokens, i) {
- // Count only the enclosing scopes the rainbow actually draws.
- // Scanning the stack rather than keeping a running counter is
- // both trivially cheap (it is a dozen frames deep at worst on
- // the whole corpus) and immune to the mismatch recovery in
- // `close`, which pops frames from the middle.
- let depth = stack.iter().filter(|f| is_rainbow(f.rule.open)).count() as u32;
- stack.push(Frame { rule, span: token.span, depth });
+ // `Stack::push` takes the depth off the running rainbow count;
+ // see the invariant on `Stack` for why it is a count and not a
+ // scan of the frames.
+ stack.push(rule_index, rule, token.span);
}
} else if let Some(closer) = closer_keyword(text) {
close(&mut analysis, &mut stack, closer, token.span);
@@ -163,7 +253,7 @@ pub fn analyze(tokens: &[Token]) -> ScopeAnalysis {
}
// Whatever is still open never closed.
- for frame in stack {
+ for frame in stack.into_frames() {
analysis.unmatched_open.push(Unmatched {
span: frame.span,
keyword: frame.rule.open,
@@ -184,13 +274,8 @@ pub fn analyze(tokens: &[Token]) -> ScopeAnalysis {
/// nothing at all is reported on its own and leaves the stack untouched.
/// Popping blindly would make one missing `end` cascade into every enclosing
/// scope.
-fn close(
- analysis: &mut ScopeAnalysis,
- stack: &mut Vec,
- closer: &'static str,
- span: TextRange,
-) {
- let Some(index) = stack.iter().rposition(|f| f.rule.close.contains(&closer)) else {
+fn close(analysis: &mut ScopeAnalysis, stack: &mut Stack, closer: &'static str, span: TextRange) {
+ let Some(index) = stack.match_index(closer) else {
analysis.unmatched_close.push(Unmatched {
span,
keyword: closer,
@@ -198,7 +283,7 @@ fn close(
});
return;
};
- for frame in stack.drain(index + 1..) {
+ for frame in stack.drain_above(index) {
analysis.unmatched_open.push(Unmatched {
span: frame.span,
keyword: frame.rule.open,
@@ -215,9 +300,10 @@ fn close(
}
}
-/// The rule an opener keyword names, if it is one.
-fn opener_rule(text: &str) -> Option<&'static Rule> {
- RULES.iter().find(|r| r.open == text)
+/// The rule an opener keyword names, with its position in [`RULES`], which is
+/// what [`Stack`]'s per-rule counts are keyed by.
+fn opener_rule(text: &str) -> Option<(usize, &'static Rule)> {
+ RULES.iter().enumerate().find(|(_, r)| r.open == text)
}
/// The closer keyword `text` is, as a `'static` string from the table.
@@ -825,6 +911,463 @@ mod tests {
assert!(missing_end_diagnostics(&doc).is_empty(), "and says nothing about it");
}
+ // ------------------------------------------------------------------
+ // the running counts on `Stack`
+ // ------------------------------------------------------------------
+
+ /// The pre-counter algorithm, kept here as an oracle: the same matcher
+ /// with `depth` scanned off the stack at every push, which is how the code
+ /// computed it before the running count replaced the scan. Returns
+ /// `(opener start, depth)` for every pair it closes.
+ ///
+ /// The old comment claimed the scan was "immune to the mismatch recovery
+ /// in `close`, which pops frames from the middle". That immunity is now
+ /// `Stack`'s job, so the claim is worth a second implementation to check
+ /// against rather than a hand-written expectation.
+ fn scanned_pairs(tokens: &[Token]) -> Vec<(u32, u32)> {
+ struct Slow {
+ rule: &'static Rule,
+ start: u32,
+ depth: u32,
+ }
+ let mut stack: Vec = Vec::new();
+ let mut pairs: Vec<(u32, u32)> = Vec::new();
+ let mut prototype = false;
+ for (i, token) in tokens.iter().enumerate() {
+ if token.is_sym(";") {
+ prototype = false;
+ continue;
+ }
+ if token.kind != TokenKind::Keyword {
+ continue;
+ }
+ let text = token.text.as_str();
+ if PROTOTYPE_STARTERS.contains(&text) {
+ prototype = true;
+ continue;
+ }
+ if let Some((_, rule)) = opener_rule(text) {
+ if !prototype && opens_a_scope(tokens, i) {
+ let depth = stack.iter().filter(|f| is_rainbow(f.rule.open)).count() as u32;
+ stack.push(Slow { rule, start: token.span.start, depth });
+ }
+ } else if let Some(closer) = closer_keyword(text) {
+ let Some(index) = stack.iter().rposition(|f| f.rule.close.contains(&closer)) else {
+ continue;
+ };
+ stack.drain(index + 1..);
+ if let Some(frame) = stack.pop() {
+ pairs.push((frame.start, frame.depth));
+ }
+ }
+ }
+ pairs.sort_unstable();
+ pairs
+ }
+
+ /// `analyze`'s own answer in the oracle's shape.
+ fn counted_pairs(tokens: &[Token]) -> Vec<(u32, u32)> {
+ let mut pairs: Vec<(u32, u32)> =
+ analyze(tokens).pairs.iter().map(|p| (p.open.start, p.depth)).collect();
+ pairs.sort_unstable();
+ pairs
+ }
+
+ #[test]
+ fn the_running_depth_count_agrees_with_a_fresh_scan_of_the_stack() {
+ // Every fixture puts rainbow and non-rainbow scopes in the same nest
+ // and then makes `close` remove frames from the middle, which is the
+ // only way a running counter can drift from a scan.
+ let cases = [
+ (
+ // A `join` that closes the `fork` below the top: the `begin`
+ // and the `case` above it are drained, and the `begin` after
+ // must land at depth 1 (inside the outer `begin` alone), not
+ // at 3.
+ concat!(
+ "module m;\n",
+ " initial begin\n",
+ " fork\n",
+ " begin\n",
+ " case (x)\n",
+ " join\n",
+ " begin\n",
+ " y = 1;\n",
+ " end\n",
+ " end\n",
+ "endmodule\n",
+ ),
+ "a join draining two rainbow frames out of the middle",
+ ),
+ (
+ // The mirror: a non-rainbow frame closes with rainbow frames
+ // stacked on top of it, so the drain has to give back counts
+ // for frames that are not the one being closed.
+ concat!(
+ "module m;\n",
+ " case (x)\n",
+ " 1: begin\n",
+ " fork\n",
+ " endcase\n",
+ " initial begin\n",
+ " end\n",
+ "endmodule\n",
+ ),
+ "an endcase draining a begin and a fork above it",
+ ),
+ (
+ // A closer that matches nothing must leave the counts exactly
+ // as it found them, or the `begin` after it shifts colour.
+ concat!(
+ "module m;\n",
+ " initial begin\n",
+ " begin\n",
+ " join_none\n",
+ " begin\n",
+ " end\n",
+ " end\n",
+ " end\n",
+ "endmodule\n",
+ ),
+ "a stray join_none between two pushes",
+ ),
+ (
+ // Recovery twice over, with the outer scopes still closing.
+ concat!(
+ "module m;\n",
+ " function f;\n",
+ " fork\n",
+ " begin\n",
+ " case (y)\n",
+ " endfunction\n",
+ " task t;\n",
+ " begin\n",
+ " fork\n",
+ " begin\n",
+ " end\n",
+ " join\n",
+ " end\n",
+ " endtask\n",
+ "endmodule\n",
+ ),
+ "two recoveries in one file",
+ ),
+ ];
+ for (text, what) in cases {
+ let tokens = tokenize(text).expect("the fixtures all lex");
+ let counted = counted_pairs(&tokens);
+ assert!(!counted.is_empty(), "{what}: the fixture matched nothing at all");
+ assert_eq!(counted, scanned_pairs(&tokens), "{what}: the counter drifted from a scan");
+ }
+ // And on every fixture the rest of this module already uses, so a
+ // drift anywhere in the corpus of shapes above fails here too.
+ for text in [
+ "module m;\n initial begin\n fork\n begin\n end\n join\n end\nendmodule\n",
+ "module m;\n initial begin\n case (x)\n 1: begin\n end\n endcase\n end\nendmodule\n",
+ "module m;\n initial begin\n if (x) begin\n y = 1;\n end\nendmodule\n",
+ ] {
+ let tokens = tokenize(text).expect("lexes");
+ assert_eq!(counted_pairs(&tokens), scanned_pairs(&tokens), "{text}");
+ }
+ }
+
+ #[test]
+ fn analysis_is_linear_in_nesting_depth_not_quadratic() {
+ // Two of these three shapes were O(n²) until the running counts landed:
+ // the depth of a push was scanned off the whole stack, and a closer
+ // that matched no frame scanned the whole stack to find that out. The
+ // third is not a shape that was ever slow — it is here so that the
+ // per-rule counts have to be *given back*, not merely taken: a drain
+ // that forgets to decrement leaves the guard permanently answering
+ // "maybe", which quietly restores the second quadratic.
+ //
+ // The budget is wall clock, which is coarse on purpose. Measured on
+ // the dev machine (debug build) at this N: the three shapes cost 5 ms,
+ // 41 ms and 44 ms with the counts, against roughly 7 s, 17 s and 15 s
+ // for the quadratic version of each. Two seconds is therefore ~45×
+ // the honest cost — room for a machine several times slower than this
+ // one, under load — while still being a small fraction of what any of
+ // the three quadratics needs.
+ const N: usize = 30_000;
+ const BUDGET: std::time::Duration = std::time::Duration::from_secs(2);
+
+ let deep = "begin\n".repeat(N);
+ let tokens = tokenize(&deep).expect("lexes");
+ let started = std::time::Instant::now();
+ let analysis = analyze(&tokens);
+ let elapsed = started.elapsed();
+ assert_eq!(analysis.unmatched_open.len(), N, "premise: all {N} really are open at once");
+ assert!(elapsed < BUDGET, "{N} nested begins took {elapsed:?}");
+
+ // `endcase` can close nothing on a stack of `begin`s, so every one of
+ // them is the no-match case.
+ let mut stray = "begin\n".repeat(N);
+ stray.push_str(&"endcase\n".repeat(N));
+ let tokens = tokenize(&stray).expect("lexes");
+ let started = std::time::Instant::now();
+ let analysis = analyze(&tokens);
+ let elapsed = started.elapsed();
+ assert_eq!(analysis.unmatched_close.len(), N, "premise: none of them matched");
+ assert_eq!(analysis.unmatched_open.len(), N, "premise: and none of the begins closed");
+ assert!(elapsed < BUDGET, "{N} never-matching closers took {elapsed:?}");
+
+ // `endcase` closes the `case` at the bottom and drains N `begin`s out
+ // of the middle on the way — so by the time the N `case`s below the
+ // `end`s are on the stack, no `begin` is open and every `end` must be
+ // declined without a scan. It is declined either way; the question is
+ // whether the counts remember that the drained `begin`s are gone.
+ let mut given_back = String::from("case (x)\n");
+ given_back.push_str(&"begin\n".repeat(N));
+ given_back.push_str("endcase\n");
+ given_back.push_str(&"case (x)\n".repeat(N));
+ given_back.push_str(&"end\n".repeat(N));
+ let tokens = tokenize(&given_back).expect("lexes");
+ let started = std::time::Instant::now();
+ let analysis = analyze(&tokens);
+ let elapsed = started.elapsed();
+ assert_eq!(analysis.pairs.len(), 1, "premise: only the outer case/endcase pairs");
+ assert_eq!(analysis.unmatched_open.len(), 2 * N, "premise: N drained begins, N open cases");
+ assert_eq!(analysis.unmatched_close.len(), N, "premise: no end can close a case");
+ assert!(elapsed < BUDGET, "{N} closers over drained frames took {elapsed:?}");
+ }
+
+ // ------------------------------------------------------------------
+ // QA (2026-08-25, perf fix) — independent full-fidelity differential
+ // check against the pre-`Stack` algorithm. Kept as a permanent
+ // regression test, unlike the dev's own oracle
+ // (`the_running_depth_count_agrees_with_a_fresh_scan_of_the_stack`),
+ // which only compares `(open start, depth)`: this one diffs every field
+ // of `ScopeAnalysis` — both unmatched lists included — and adds
+ // adversarial fixtures the dev's own tests do not cover (shared-closer
+ // priority, deep mixed-rainbow drains with more pushes/closes
+ // afterward, prototype interleavings, closers before any opener) plus a
+ // fixed-seed fuzz sweep.
+ // ------------------------------------------------------------------
+
+ /// HEAD's `Frame`, transcribed from `git show HEAD:.../pairs.rs`, before
+ /// `Stack` existed.
+ struct OldFrame {
+ rule: &'static Rule,
+ span: TextRange,
+ depth: u32,
+ }
+
+ /// HEAD's `close`, transcribed verbatim (modulo the `Vec` type).
+ fn old_close(
+ analysis: &mut ScopeAnalysis,
+ stack: &mut Vec,
+ closer: &'static str,
+ span: TextRange,
+ ) {
+ let Some(index) = stack.iter().rposition(|f| f.rule.close.contains(&closer)) else {
+ analysis.unmatched_close.push(Unmatched {
+ span,
+ keyword: closer,
+ expected: opener_of(closer),
+ });
+ return;
+ };
+ for frame in stack.drain(index + 1..) {
+ analysis.unmatched_open.push(Unmatched {
+ span: frame.span,
+ keyword: frame.rule.open,
+ expected: frame.rule.close[0],
+ });
+ }
+ if let Some(frame) = stack.pop() {
+ analysis.pairs.push(Pair {
+ open: frame.span,
+ close: span,
+ keyword: frame.rule.open,
+ depth: frame.depth,
+ });
+ }
+ }
+
+ /// HEAD's `analyze`, transcribed verbatim (modulo `opener_rule`'s new
+ /// `(usize, &Rule)` signature, whose index this oracle ignores).
+ fn old_analyze(tokens: &[Token]) -> ScopeAnalysis {
+ let mut analysis = ScopeAnalysis::default();
+ let mut stack: Vec = Vec::new();
+ let mut prototype = false;
+ for (i, token) in tokens.iter().enumerate() {
+ if token.is_sym(";") {
+ prototype = false;
+ continue;
+ }
+ if token.kind != TokenKind::Keyword {
+ continue;
+ }
+ let text = token.text.as_str();
+ if PROTOTYPE_STARTERS.contains(&text) {
+ prototype = true;
+ continue;
+ }
+ if let Some((_, rule)) = opener_rule(text) {
+ if !prototype && opens_a_scope(tokens, i) {
+ let depth = stack.iter().filter(|f| is_rainbow(f.rule.open)).count() as u32;
+ stack.push(OldFrame { rule, span: token.span, depth });
+ }
+ } else if let Some(closer) = closer_keyword(text) {
+ old_close(&mut analysis, &mut stack, closer, token.span);
+ }
+ }
+ for frame in stack {
+ analysis.unmatched_open.push(Unmatched {
+ span: frame.span,
+ keyword: frame.rule.open,
+ expected: frame.rule.close[0],
+ });
+ }
+ analysis.pairs.sort_by_key(|p| p.open.start);
+ analysis.unmatched_open.sort_by_key(|u| u.span.start);
+ analysis.unmatched_close.sort_by_key(|u| u.span.start);
+ analysis
+ }
+
+ /// Every field of `ScopeAnalysis` that matters, in one comparable value —
+ /// not just `(open start, depth)` the dev's own oracle checks.
+ #[allow(clippy::type_complexity)]
+ fn qa_fingerprint(
+ a: &ScopeAnalysis,
+ ) -> (
+ Vec<(u32, u32, &'static str, u32)>,
+ Vec<(u32, &'static str, &'static str)>,
+ Vec<(u32, &'static str, &'static str)>,
+ ) {
+ (
+ a.pairs.iter().map(|p| (p.open.start, p.close.start, p.keyword, p.depth)).collect(),
+ a.unmatched_open.iter().map(|u| (u.span.start, u.keyword, u.expected)).collect(),
+ a.unmatched_close.iter().map(|u| (u.span.start, u.keyword, u.expected)).collect(),
+ )
+ }
+
+ fn qa_assert_identical(text: &str, what: &str) {
+ let tokens = tokenize(text).unwrap_or_else(|e| panic!("{what}: fixture must lex: {e:?}"));
+ let old = qa_fingerprint(&old_analyze(&tokens));
+ let new = qa_fingerprint(&analyze(&tokens));
+ assert_eq!(old, new, "{what}: old and new algorithms disagree on:\n{text:?}");
+ }
+
+ #[test]
+ fn qa_old_and_new_algorithms_agree_field_for_field() {
+ // Empty input.
+ qa_assert_identical("", "empty input");
+
+ // Every closer keyword, alone and before any opener at all — every
+ // closer in RULES, not just `end`.
+ for rule in RULES {
+ for closer in rule.close {
+ qa_assert_identical(closer, &format!("bare closer {closer}"));
+ qa_assert_identical(
+ &format!("{closer} {closer} {closer}"),
+ &format!("three bare {closer} in a row"),
+ );
+ }
+ }
+
+ // Shared-closer priority: several rules accept the same closer
+ // keyword. `endcase` is accepted by case/casex/casez/randcase (4
+ // rules); `endmodule` by module/macromodule (2). Nest mismatched
+ // openers that share a closer and confirm both algorithms pick the
+ // same *topmost* frame (the `rposition` scan's priority), not merely
+ // "some frame that fits".
+ qa_assert_identical(
+ "case casex casez randcase endcase endcase endcase endcase",
+ "endcase closes topmost-first across 4 sharing rules",
+ );
+ qa_assert_identical(
+ "module macromodule endmodule endmodule",
+ "endmodule closes topmost-first across 2 sharing rules",
+ );
+ qa_assert_identical(
+ "module begin fork case casex endcase join begin end endmodule",
+ "a shared-closer rule interleaved with rainbow frames, drained and not",
+ );
+
+ // Interleaved rainbow / non-rainbow scopes, closers reaching deep
+ // below the top and draining a mix of both kinds, with more
+ // pushing/closing continuing afterward (so a stale count would show
+ // up on the *next* pair, not just the one being closed).
+ qa_assert_identical(
+ "begin fork case begin fork begin join begin end endcase begin end join end begin end end",
+ "deep mixed drain (join draining case+begin+fork) then more begins after",
+ );
+ qa_assert_identical(
+ "module function task begin fork case endcase join endtask endfunction begin end endmodule",
+ "drain across 3 non-rainbow frames and 2 rainbow frames in one closer, then a fresh pair after",
+ );
+ qa_assert_identical(
+ "begin begin begin endcase begin end end end end",
+ "a non-matching closer (endcase) between two begins changes nothing, more begins follow",
+ );
+
+ // Prototype mode interleaved with opens and closes: the flag must
+ // drop at the next `;` regardless of what real scopes are doing
+ // around it.
+ qa_assert_identical(
+ "extern function ; begin fork join end pure task ; begin end import function ; class endclass",
+ "prototype starters interleaved with real opens/closes",
+ );
+ qa_assert_identical(
+ "begin extern module ; fork join end typedef class ; begin end",
+ "a prototype flag raised and dropped while a rainbow frame is already open",
+ );
+
+ // Unmatched closers of every flavor stacked back to back with no
+ // openers anywhere, then a real pair afterward.
+ qa_assert_identical(
+ "end join join_any join_none endcase endmodule endfunction begin end",
+ "a run of unmatched closers of every closer family, then one real pair",
+ );
+
+ // Closers before any opener, mixed with a later real pair.
+ qa_assert_identical(
+ "end end join begin end",
+ "closers before any opener, then a real pair",
+ );
+
+ // A small xorshift PRNG (no external dependency, per CLAUDE.md) over
+ // a vocabulary that exercises every `opens_a_scope` guard
+ // (interface/property/sequence/clocking/fork/function) as well as
+ // plain opens, closes, prototype starters and `;`.
+ let vocab: Vec<&str> = RULES
+ .iter()
+ .flat_map(|r| std::iter::once(r.open).chain(r.close.iter().copied()))
+ .chain(PROTOTYPE_STARTERS.iter().copied())
+ .chain([
+ "with", "disable", "wait", "virtual", "class", "(", ",", "@", "posedge", "x", "cb",
+ ";",
+ ])
+ .collect();
+
+ let mut state: u64 = 0x2545_F491_4F6C_DD1D;
+ let mut next = || {
+ state ^= state << 13;
+ state ^= state >> 7;
+ state ^= state << 17;
+ state
+ };
+
+ for round in 0..500u32 {
+ let len = 10 + (next() % 40) as usize;
+ let mut text = String::new();
+ for _ in 0..len {
+ let word = vocab[(next() as usize) % vocab.len()];
+ text.push_str(word);
+ text.push(' ');
+ }
+ // Not every random token soup lexes (e.g. a lone `@` needs
+ // nothing special, but skip anything the lexer itself rejects —
+ // this test is about matcher agreement, not lexer coverage).
+ if let Ok(tokens) = tokenize(&text) {
+ let old = qa_fingerprint(&old_analyze(&tokens));
+ let new = qa_fingerprint(&analyze(&tokens));
+ assert_eq!(old, new, "fuzz round {round}: old and new disagree on:\n{text:?}");
+ }
+ }
+ }
+
// ------------------------------------------------------------------
// documentHighlight
// ------------------------------------------------------------------
diff --git a/docs/features/editor-scopes/README.md b/docs/features/editor-scopes/README.md
index ff9abfd..37b8029 100644
--- a/docs/features/editor-scopes/README.md
+++ b/docs/features/editor-scopes/README.md
@@ -72,13 +72,25 @@ keyword in an error red.
alone. A user or a theme may still override a `vfmt.rainbow*` id with
anything they like — including transparent — and that is their decision, not
a default of ours.
-- **Analysis is cheap enough to redo per request.** `analyze` is one pass over
- the token vector with a small stack, so nothing is cached and no invalidation
- rule can go stale. Measured, because `vfmt/scopePairs` arrives on a debounce
- timer rather than on a user gesture: sweeping the corpus, the worst single
- `scope_pairs` call is **2.1 ms** (`picorv32.v`, the largest file), against a
- 250 ms debounce. If a profile ever says otherwise, the result belongs next to
- `tokens` in `Document`, computed once per change like everything else there.
+- **Analysis is cheap enough to redo per request, and that now rests on
+ `analyze` being linear rather than on real files being shallow.** `analyze`
+ is one pass over the token vector with a small stack, so nothing is cached
+ and no invalidation rule can go stale. Measured, because `vfmt/scopePairs`
+ arrives on a debounce timer rather than on a user gesture: sweeping the
+ corpus, the worst single `scope_pairs` call is **2.1 ms** (`picorv32.v`, the
+ largest file), against a 250 ms debounce. Until 2026-08-25 the *shape* of the
+ cost was quadratic in nesting depth and only the corpus's shallowness hid it
+ — see the work log entry for that date, which is also where the assumption
+ "a dozen frames deep at worst" stopped being load-bearing. `Stack`'s two
+ running counts make the pass linear in the token count, so a pathological
+ file is now slow only in proportion to its size. If a profile ever says
+ otherwise, the result belongs next to `tokens` in `Document`, computed once
+ per change like everything else there.
+- **`RULES` stays small enough that a walk of it is a constant.** The
+ no-match fast path in `Stack::match_index` walks the whole rule table (21
+ entries) instead of the stack. That is a constant only in the sense that the
+ table does not grow with the document; if `RULES` ever grew to hundreds of
+ entries the walk would want an index keyed by closer keyword instead.
- **The client repaints; the server never pushes.** LSP has no "decorate these
ranges" notification, so the extension asks after every settled edit. That
makes a stale answer possible — the reply describes the version that was
@@ -315,6 +327,11 @@ saturated pure red, and only ever on screen while a block is half-typed.
default to transparent and were painting depths 3–5 invisible.
- [x] **0.3.1:** `unmatched` on the wire, painted `vfmt.rainbowUnmatched`, so a
half-typed `begin` is bright red rather than uncoloured.
+- [x] **2026-08-25:** `analyze` is linear in nesting depth. Both quadratic
+ scans — the depth scan at every push and the whole-stack search for a
+ closer that matches nothing — are answered from running counts on a new
+ `Stack` type, with the depth-equivalence and scaling tests to hold them
+ there.
- [ ] Not done, deliberately: no check that a labeled `end : outer` agrees with
its `begin : outer`. That is a lint rule with its own fix and its own
opinion, not part of matching.
@@ -675,6 +692,133 @@ failed**; `node --check` on `extension.js` and `smoke.js` clean; `node smoke.js
outside `#[cfg(test)]`, no `#[allow]` added, and `TODO.md` and
`docs/features/refactor/README.md` were not touched.
+### 2026-08-25 — `analyze` is linear in nesting depth
+
+**The finding, and who found it.** The inline-templates QA round (its QA log,
+Finding 2 — read, not edited) measured `pairs::analyze` as O(depth²) and filed
+it, because the new `textDocument/inlineCompletion` gate calls `analyze` on
+every keystroke rather than on a click or a save. Their numbers, debug build,
+*n* consecutive `begin` lines: depth 1000 → 19 ms, 2000 → 49 ms, 4000 → 155 ms,
+8000 → 619 ms, and one full inline request at depth 50 000 took **24 seconds**.
+Reproduced here before touching anything: 16.9 / 53.4 / 157.5 / 629.1 ms — the
+4× per doubling that says quadratic.
+
+**Two quadratics, not one.** The filed one is the depth scan at every push
+(`pairs.rs:157`). The lead suspected a second in `close`, and it is real: a
+closer that matches **nothing** ran `stack.iter().rposition(...)` over the
+entire stack and then removed nothing, so *n* opens followed by *n* stray
+closers of a kind not on the stack was O(n²) too. When a closer *does* match,
+the frames the scan walks past are exactly the ones the drain then removes, so
+that case was already amortized linear — only the no-match case leaks.
+
+Measured, rather than assumed, because it had to be told apart from the first
+quadratic: with the depth fix in and the no-match guard **temporarily disabled**
+so only path 2 remained, `n` `begin`s + `n` `endcase`s cost 28.7 / 79.4 /
+302.8 ms / 1.194 s for n = 1000 / 2000 / 4000 / 8000. Same 4× signature, so
+path 2 was fixed too.
+
+**The fix — one type that owns the bookkeeping.** A `Stack` struct now holds
+the frames plus two running counts, and every removal goes through it:
+
+- `rainbow` — frames on the stack whose opener `is_rainbow`. This *is* the next
+ push's `Pair::depth`, so `push` reads it instead of scanning.
+- `per_rule[i]` — frames the rule at `RULES[i]` has on the stack. `match_index`
+ consults these first and answers the no-match case with a walk of the
+ 21-entry rule table instead of the stack. `Frame` carries its `rule_index`
+ so a frame leaving the stack can give its count back without a search, and
+ `opener_rule` returns `(index, rule)`.
+
+Both counts are decremented in `pop` **and** in `drain_above`, which is the
+mismatch recovery's middle-of-stack removal — the exact hazard the old comment
+cited as its reason for scanning ("immune to the mismatch recovery in `close`,
+which pops frames from the middle"). That comment is gone; the invariant is now
+stated on `Stack` itself, and `analyze`'s end-of-stream drain calls
+`into_frames(self)`, consuming the whole `Stack` so no counter survives the
+loop for a later reader to trust.
+
+**This reverses M5's stated reasoning, not its behaviour.** M5 chose the scan
+deliberately and wrote down why: "The stack is seven frames deep at worst
+across the whole corpus, so the cost is nothing, and a counter would have to be
+unwound correctly by the mismatch recovery in `close` … a second thing to get
+right for no gain." Both clauses were true of the corpus and of M5's callers.
+Neither survived a caller that runs per keystroke on a buffer the user is
+midway through typing, where "seven frames deep at worst" is a statement about
+finished files. The counter is indeed a second thing to get right; it is got
+right in one type, and pinned by the tests below.
+
+**Behaviour: bit-for-bit identical, demonstrated rather than argued.** A
+throwaway sweep (added, run, removed — not in the committed tree) ran the whole
+corpus through `analyze` and wrote a fingerprint of the *complete*
+`ScopeAnalysis` — every pair's open/close offsets, keyword and depth, and every
+entry of both unmatched lists — then the same sweep was grafted onto `HEAD`'s
+`pairs.rs` and run again. **859 files, 11 201 pairs, both fingerprints md5
+`cc8284afb91a71ceaed8f04bc58ca62c`, `diff` reports identical.**
+
+**Numbers, before and after** (debug build, `analyze` alone, tokenizing outside
+the timer):
+
+| shape | n | before | after |
+|---|---|---|---|
+| nested `begin`s (path 1) | 1000 | 16.9 ms | 1.4 ms |
+| | 2000 | 53.4 ms | 0.7 ms |
+| | 4000 | 157.5 ms | 1.4 ms |
+| | 8000 | 629.1 ms | 2.3 ms |
+| `n` opens + `n` never-matching closers (both paths) | 1000 | 28.8 ms | 2.3 ms |
+| | 2000 | 113.9 ms | 3.9 ms |
+| | 4000 | 455.3 ms | 7.1 ms |
+| | 8000 | 1.889 s | 12.2 ms |
+
+At the size the new scaling test uses, n = 30 000: 5 ms / 41 ms / 44 ms for the
+three shapes it measures, against roughly 7 s / 17 s / 15 s for the quadratic
+version of each.
+
+**Two tests added, both mutation-checked.**
+
+1. `the_running_depth_count_agrees_with_a_fresh_scan_of_the_stack` — the old
+ scan, reimplemented in the test module as `scanned_pairs` and used as the
+ oracle. Four fixtures put rainbow and non-rainbow scopes in one nest and
+ then force `close` to remove frames from the middle (a `join` draining a
+ `begin` and a `case`; an `endcase` draining a `begin` and a `fork`; a stray
+ `join_none` that must leave the counts alone; two recoveries in one file),
+ plus three of this module's existing shapes. This is the regression test for
+ the property the deleted comment claimed for free.
+2. `analysis_is_linear_in_nesting_depth_not_quadratic` — 30 000 nested
+ `begin`s; 30 000 `begin`s followed by 30 000 `endcase`s; and a third shape
+ whose only job is to make the counts be *given back* — an `endcase` that
+ drains 30 000 `begin`s out of the middle, then 30 000 `case`s pushed and
+ 30 000 `end`s that must be declined without a scan. Budget is 2 s per shape,
+ ~45× the honest cost and a small fraction of any of the three quadratics;
+ the reasoning and the measured numbers are in the test's own comment. The
+ third shape was added *because* the mutation check below showed the first
+ two did not cover a leaked `per_rule` count.
+
+**Mutation check** — five deliberate breakages, each run against the full
+`vfmt_server` suite and then reverted (`pairs.rs` restored from a copy and
+`diff`-verified byte-identical after each):
+
+| mutation | caught by |
+|---|---|
+| `drain_above` skips the `rainbow` decrement | `the_running_depth_count_…` **only** — no pre-existing test sees it |
+| `pop` skips the `rainbow` decrement | `the_running_depth_count_…` + 2 existing depth tests |
+| `drain_above` skips the `per_rule` decrement (over-count → the guard says "maybe" forever) | `analysis_is_linear_…`, via the third shape; nothing else, because an over-count costs speed and not correctness |
+| `pop` decrements `per_rule` twice (under-count → the guard wrongly says "no frame") | 8+ existing tests across pairs, highlights and diagnostics |
+| `push` goes back to scanning the frames for `depth` | `analysis_is_linear_…` |
+
+The first row is the point of test 1, and the third row is why test 2 grew a
+third shape rather than staying at two.
+
+**Scope.** Only `crates/vfmt_server/src/pairs.rs` and this README were touched;
+`inline.rs` and `docs/features/inline-templates/` were not. No new
+dependencies, no `unsafe`, no `unwrap`/`expect`/`panic!` outside `#[cfg(test)]`,
+no `#[allow]` added. `TODO.md` was not touched — this fixes a defect inside an
+already-checked item rather than completing a listed one; the checklist entry
+went in this feature's own Status/TODO instead.
+
+**Verification.** `cargo fmt --all -- --check` clean; `cargo clippy
+--all-targets --workspace` **0 warnings**; `cargo test --workspace` **1616
+passed, 0 failed, 4 ignored** (was 1614 — the two new tests). `vfmt_server`
+alone: 533 unit + 29 e2e + 3 grammar, all green.
+
## QA log
### 2026-08-24 — QA round 1 (M2): pairs.rs, documentHighlight, missing-end gate
@@ -1238,6 +1382,186 @@ negative-depth modulo gap) — it cannot fire against this server as shipped,
so it does not block 0.3.1, but the work log's defensive-reads claim should
either be corrected or the code tightened next time this file is touched.
+### 2026-08-25 — QA round 6 (perf fix): `analyze` linear in nesting depth
+
+Charter: the dev's claim that replacing the bare `Vec` stack with the
+counting `Stack` type makes `analyze` linear without changing any observable
+answer — bit-identical corpus fingerprint, 1616 tests green, two new tests.
+Scope: uncommitted working tree, diff vs `HEAD` — `crates/vfmt_server/src/pairs.rs`
+and this README only. `crates/vfmt_server/src/inline.rs` and
+`docs/features/inline-templates/` were read for context (the motivating QA
+find lives there) but not touched, per charter. Verdict: **PASS**, no
+blocking findings, one non-blocking cross-feature finding (item 8).
+
+**Method, and one deliberate departure from rounds 1–5's discipline.** Every
+previous round in this log added throwaway tests to `pairs.rs`'s own
+`#[cfg(test)] mod tests`, ran them, and removed them before writing the log
+entry. This round's charter asked instead for regression tests to be added
+permanently, so `qa_old_and_new_algorithms_agree_field_for_field`
+(`pairs.rs:1141`) stays in the committed tree — see item 2. Everything else
+(the mutation-check copies, the temporary perf-ratio measurement) followed
+the usual add-run-remove-and-md5-verify pattern.
+
+**1. Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --workspace
+--all-targets`: clean, 0 warnings (re-run after `touch`ing `pairs.rs` to
+defeat incremental caching, both before and after adding QA's own test).
+`cargo test --workspace`: **1617 passed, 0 failed** (summed every crate's
+`test result:` line independently — 1616 + the one new differential test);
+`vfmt_server` alone: 530 unit + 4 ignored + 29 e2e + 3 grammar, matching the
+Work Log's 533 unit count plus QA's addition.
+
+Timed the dev's own scaling test in isolation:
+`analysis_is_linear_in_nesting_depth_not_quadratic` — **0.23 s total for all
+three 30 000-element shapes**, against a 2 s-per-shape (6 s total) budget.
+That is roughly **26× headroom** on this machine; on the numbers embedded in
+the test's own comment (5/41/44 ms on the dev's machine, 2 s budget ≈ 45×
+that), the two measurements agree the budget is not tight. A budget with this
+much margin is safe against ordinary CI/debug-build variance — it would take
+almost an order-of-magnitude slowdown per shape to flake, not the 2–3×
+jitter a loaded CI runner typically adds. Judgment: **safe as written**.
+
+**2. Independent differential check — not just trusting the corpus
+fingerprint.** Added a full-fidelity oracle to `pairs.rs`'s test module,
+transcribed verbatim from `git show HEAD:crates/vfmt_server/src/pairs.rs`
+(the exact pre-`Stack` `analyze`/`close`, copied as `old_analyze`/`old_close`
+over a local `OldFrame` stack) — a second, independently-typed
+implementation of the algorithm being replaced, not a rederivation from
+memory. Unlike the dev's own oracle
+(`the_running_depth_count_agrees_with_a_fresh_scan_of_the_stack`, which
+compares only `(open start, depth)` for matched pairs),
+`qa_old_and_new_algorithms_agree_field_for_field` (`pairs.rs:1141`) diffs
+**every field of `ScopeAnalysis`** — both unmatched lists, `close` spans and
+`keyword`/`expected` included — via a `qa_fingerprint` helper, on:
+
+- every closer keyword in `RULES`, bare and before any opener (the "closers
+ before any opener" and "unmatched closers of every flavor" charter items);
+- **shared-closer priority**, the charter's specific worry: `endcase` is
+ accepted by `case`/`casex`/`casez`/`randcase` (4 rules) and `endmodule` by
+ `module`/`macromodule` (2). `"case casex casez randcase endcase endcase
+ endcase endcase"` and the `module`/`macromodule` equivalent assert the
+ *topmost* frame closes each time, matching the old `rposition` scan's
+ priority — this is not automatically implied by `match_index`'s `reachable`
+ fast-path being correct in the aggregate;
+- deep mixed-rainbow drains (a `join` draining a `case`+`begin`+`fork` out of
+ the middle, an `endcase` draining a `begin`+`fork`) **with more
+ pushing/closing continuing afterward**, so a stale count would surface on
+ the *next* pair rather than only at the point of the drain;
+- prototype-mode interleaved with real opens/closes, including a prototype
+ flag raised and dropped while a rainbow frame is already open;
+- a fixed-seed (no external dependency — a 15-line xorshift64) fuzz sweep,
+ 500 rounds over a vocabulary built from every `RULES` opener/closer plus
+ the tokens needed to exercise every `opens_a_scope` guard
+ (`interface`/`property`/`sequence`/`clocking`/`fork`/`function`).
+
+Result: **all fixtures and all 500 fuzz rounds agree, field for field.**
+
+**Mutation-checked the differential test itself**, since a differential test
+that never fails is worth nothing. Two independent breakages, each built,
+run against QA's own test, confirmed caught, then reverted (`pairs.rs`
+restored from a saved copy, `md5` confirmed identical before/after both
+times — `7ba458a24bcdc313da957b7d420fab62`, the snapshot taken right after
+the differential test was added and before `cargo fmt` reflowed its longer
+lines; the final, formatted file committed here is
+`a501394b065228eb069f62e4e12fd753`, reverified clean against `cargo fmt
+--all -- --check` and identical to this snapshot after both mutations):
+
+| mutation | caught by |
+|---|---|
+| `drain_above` stops decrementing `rainbow` (kept `per_rule` decrement) | the deep-mixed-drain fixture — depths `3/2/0` came back `4/4/2` |
+| `match_index`'s `reachable` fast-path zipped `RULES` against `per_rule` shifted by one index | the shared-closer-priority fixture (`case casex casez randcase` × 4 `endcase`) — the first `case`/`endcase` pair vanished into `unmatched` instead of closing |
+
+Both are shapes the dev's own oracle cannot see (it never touches
+`unmatched_open`/`unmatched_close`, and it has no shared-closer fixture), so
+this is genuine additional coverage, not a restatement of the dev's test.
+
+**3. Attacking the counters directly, beyond the differential fixtures
+above.** Every `drain_above`/`pop` call site was read against the rule "every
+removal from `frames` goes through one of these two, both of which decrement
+`rainbow` and `per_rule` together" (`pairs.rs:150-213`) — confirmed by
+`grep`, `.frames` is touched nowhere else in the module outside `Stack`'s own
+`impl` block (`push`, `match_index`, `drain_above`, `pop`, `into_frames`),
+including in the test module's own `scanned_pairs`/`old_analyze`, which use
+their own independent `Vec`-based stacks. `into_frames` consumes `self` by
+value, so the type system — not a convention — prevents a call site from
+reading `rainbow`/`per_rule` after the frames are taken; there is no live
+`Stack` left to query once `analyze`'s end-of-stream loop runs.
+
+**4. `Pair::depth` semantics and the rainbow consumer.** `scope_pairs`
+(`pairs.rs:449-475`) is untouched by this diff — confirmed directly against
+the diff, not assumed — and reads `p.depth` straight off `analyze`'s output,
+so the field-for-field differential above (which includes `depth` in its
+`pairs` fingerprint) is a direct proof the wire value is unchanged.
+`editors/vscode/extension.js` is not in `git diff --stat` at all. Ran the
+full `vfmt_server` suite's scope-pairs and depth tests
+(`scope_pairs_depths_nest_and_forks_are_included`,
+`only_begins_and_forks_stack_up_the_colours`,
+`no_hidden_scope_counts_toward_the_depth`,
+`the_scope_pairs_wire_shape_is_what_the_extension_reads`, and the rest of the
+M5 depth suite): all green, unedited by this diff.
+
+**5. Perf, reproduced independently rather than taken on the dev's numbers.**
+A temporary test (added, run, removed — `md5` confirmed
+`a501394b065228eb069f62e4e12fd753`, the final formatted file, before and
+after) ran `old_analyze` and `analyze` back to back on `n` nested `begin`s,
+debug build:
+
+| n | old (`Vec` scan) | new (`Stack`) |
+|---|---|---|
+| 8 000 | 618.7 ms | 1.30 ms |
+| 16 000 | 2.466 s | 2.56 ms |
+
+Doubling `n` roughly **quadruples** the old time (3.99×) and roughly
+**doubles** the new one (1.97×) — the quadratic-to-linear signature the work
+log claims, reproduced independently rather than trusted. In the same
+ballpark as the dev's own debug-build numbers (629.1 ms / 2.3 ms at n =
+8000), close enough that the two runs are clearly measuring the same thing on
+similar hardware.
+
+**6. Scope.** `git diff --stat` vs `HEAD`: `crates/vfmt_server/src/pairs.rs`
+and `docs/features/editor-scopes/README.md` only (plus this entry). Grepped
+every added line for `unwrap(`, `expect(`, `panic!`, `unsafe` — all six hits
+are inside `#[cfg(test)] mod tests` (five `tokenize(...).expect(...)` calls
+the dev added and one `panic!` inside QA's own `unwrap_or_else` for a
+fixture-lex failure message); none outside the test module. The old comment
+this fix removes — "trivially cheap ... a dozen frames deep at worst" — is
+confirmed gone (`grep -n "trivially cheap\|dozen frames"` finds nothing), and
+the invariant it used to justify is now stated as a doc comment on `Stack`
+itself (`pairs.rs:130-140`).
+
+**7. `TODO.md`.** Grepped for `quadratic`, `O(n`, `scope.pair`, `pairs.rs`,
+`editor.scope`, `documentHighlight`, `scopePairs` (case-insensitive): no
+hits. The one `analyze` mentioned in `TODO.md` (§5, around line 457) is
+`vlog_semantic::analyze`, an unrelated planned module for a rowan-style
+green tree — not this feature's `pairs::analyze`. The dev's claim that
+nothing in the backlog covers this fix holds.
+
+**8. Non-blocking, cross-feature finding — not fixed, `inline.rs` is out of
+scope for this dispatch.** `crates/vfmt_server/src/inline.rs:514-519`, the
+doc comment on
+`a_deeply_nested_file_neither_crashes_nor_misses_the_trigger`, still reads:
+*"those flat loops are not all linear, though — `pairs::analyze` is
+quadratic in the depth of rainbow nesting (`pairs.rs:157`), which this
+module now calls on every keystroke... 3,000 is past where that shows up in
+a debug build (tens of ms)."* Both the claim and the line number are stale
+after this fix — `pairs.rs:157` is no longer where the depth is computed,
+and `analyze` is no longer quadratic there. The test itself still passes (it
+asserts no crash and a correct trigger, not a timing bound), so this is a
+documentation staleness, not a behavioral regression, and it sits in a file
+this dispatch was explicitly told not to touch. Filed for whoever next
+touches `inline.rs` or `docs/features/inline-templates/README.md`.
+
+**Verdict: PASS.** No blocking findings. The dev's central claim — behavior
+is bit-identical, only the shape of the cost changed — held under an
+independently-typed oracle (not a rederivation of the dev's own code),
+adversarial fixtures the dev's own tests do not cover (shared-closer
+priority across multiple rules, deep mixed-rainbow drains with continued
+use afterward), a 500-round fixed-seed fuzz sweep, and two deliberately
+injected regressions that the new differential test caught and the dev's own
+oracle would not have. The scaling test's 2 s budget has roughly 26–45×
+headroom on the machines it has been measured on. One non-blocking
+documentation-staleness finding is filed against `inline.rs` (item 8),
+outside this dispatch's scope to fix.
+
## Review
### 2026-08-24 — lead review of M2 (after QA round 1)
@@ -1310,3 +1634,21 @@ myself: the depth guard now also rejects negative integers
(extension.js:188), so a hostile depth can never throw mid-repaint.
Gates re-run after that one-liner: 1268 tests, 0 failures, smoke OK.
Accepted; ships as 0.3.1.
+
+### 2026-08-25 — lead review of the linear-analyze fix (after QA round 6)
+
+Read the whole `pairs.rs` diff. The `Stack` type is the right shape: the
+invariant is stated once, on the type, and every removal path — `pop` and
+the mismatch recovery's `drain_above` — goes through it, which is exactly
+the property the old comment said a counter couldn't have. The second
+quadratic (a never-matching closer rescanning the whole stack) was my
+find at brief time; the `per_rule` reachability check answers it with a
+walk of the constant rule table, and the drain-then-reopen shape in the
+scaling test is what keeps those counts honest. Evidence accepted:
+dev's corpus fingerprint (859 files, md5-identical to HEAD), QA's
+independent field-for-field oracle with a 500-round fuzz sweep, and
+mutation checks on both oracles from both agents. 8000-deep nesting:
+629ms → 2.3ms. I applied QA's one leftover myself: the stale
+"analyze is quadratic" comment in `inline.rs`'s deep-nesting test now
+records the fix instead (that file is otherwise untouched). Gates re-run
+by the lead after that comment edit. Accepted.