Skip to content

fix(analysis): guard TypeScript oxc parses with a nesting budget and large-stack worker (#4101) - #4111

Merged
EffortlessSteven merged 4 commits into
mainfrom
fix/ts-parse-depth-budget-4101
Sep 26, 2026
Merged

EffortlessSteven merged 4 commits into
mainfrom
fix/ts-parse-depth-budget-4101

Conversation

@EffortlessSteven

Copy link
Copy Markdown
Member

Closes #4101 (delivery of the claimed design; do not auto-merge — see review note).

Red witness (pre-fix, exact base 129987bea)

Running the unguarded binary on the retained probe fixture
(C:/Users/szim9/AppData/Local/Temp/ts-output/probes/e_unchanged_deep/ —
400 balanced parens in unchanged deep.ts + benign diff on ok.ts):

thread 'main' (12644) has overflowed its stack
EXIT=127, 0 bytes of output

Deterministic, matches the issue. Because Phase 1 parses every discovered
.ts/.tsx/.js/.jsx file, one deep file anywhere in the workspace killed
every ripr check — including Rust-only diffs with TS enabled.

Production delta

The oxc 0.130 recursive-descent parser bounds recursion only by the thread
stack it runs on. Two coordinated changes, in parse.rs (+ two call-site
routings):

  1. Large-stack parse worker (PARSE_WORKER_STACK_BYTES = 256 MiB,
    parse_on_worker): every oxc parse in the adapter now runs on a
    dedicated worker thread with an explicit stack, together with the AST
    walk that consumes the parse result, so parser recursion no longer
    depends on the caller's (1 MiB Windows main) stack. Reservation is
    address-space only; at most one worker is alive at a time (Phase 1
    parses sequentially). All three production parse sites route through it:
    parse_error_reason, extract_owners (owners.rs), and
    ReExportIndex::build (related_tests.rs — this one was the surviving
    main-thread abort during bring-up). A worker that cannot spawn or dies
    (oxc panic) is disclosed as typed parse_worker_unavailable /
    parse_worker_failed static limits — never retried on the small stack.
  2. Pre-parse nesting budget (PARSE_NESTING_BUDGET = 2,000): a cheap
    single-pass byte scan estimates deepest expression nesting as
    bracket depth ((/[/{) + open ternary chain + prefix-operator runs
    (!/~, prefix +/-, prefix await/typeof/void/delete/new),
    reporting the running maximum. Comments, string/template literals, and
    regex literals are skipped; iterative binary/member chains count zero.
    Past the budget the parse is refused with a typed
    expression_nesting_budget static-limit reason riding the existing
    unsupported_syntax finding + language_scope_unsupported limitation
    plumbing — the refusal is disclosed exactly like a parser error, and no
    input can abort the process.

Budget numbers (measured, Windows debug = worst frame sizes)

Depth (balanced parens, changed file) Unguarded main thread 256 MiB worker
350 / 400 parses / aborts (issue; red witness) parses, classifies normally
1,000 … 64,000 — parses, exit 0, classified (ladder run)
128,000 — overflows (measured worker limit)
  • Budget 2,000 is 5x above the historical abort threshold (400): every
    historically aborting input is now refused with a typed disclosure
    instead of parsed on a small stack.
  • Budget 2,000 is ≥32x below the worker's measured overflow floor
    (64,000)
    : nothing under the budget can approach the worker's own
    limit, on any runner.
  • Real-world code: legitimate deep nesting is dominated by iterative
    binary/member chains (not counted); paren/ternary/unary recursion at
    2,000+ levels is generated/minified pathology, not reviewable source.
    Depth-400 files that previously killed the run now parse and classify.

Evidence delta

  • 6 discriminating unit tests (parse_depth_tests in parse.rs): scan
    shapes counted (parens/brackets/braces/ternary/unary runs);
    string/comment/template/regex/division ignored; budget+1 balanced
    source refused with the typed reason
    (the worker would parse it
    cleanly — only the budget explains the refusal); budget-depth source
    admitted and parsed cleanly on the worker stack
    ; depth-400
    parse+owner-extraction; budget reason rendered through
    unsupported_syntax_finding.
  • fixtures/ts_parse_depth_budget/ (RIPR-SPEC-0177): control ok.ts,
    changed depth-400 file (classifies normally — "fails before, passes
    after"), changed over-budget balanced file (typed limitation), and an
    unchanged over-budget file reproducing the issue's exact blast-radius
    shape. expected/check.json pins the typed
    expression_nesting_budget evidence + language_scope_unsupported
    limitation.
  • docs/specs/RIPR-SPEC-0177-typescript-parse-depth-budget.md + specs
    README index + .ripr/traceability.toml entry (tests/fixtures/code).

Proof (local, Windows Git Bash, debug)

  • cargo fmt --check; cargo check -p ripr
  • cargo clippy -p ripr --all-targets -- -D warnings
  • cargo test -p ripr --lib typescript:: — 313 passed (incl. 6 new)
  • cargo xtask check-fixture-contracts; cargo xtask fixtures ts_parse_depth_budget — zero drift
  • cargo xtask goldens check — full corpus, zero drift (worker re-routing is behavior-preserving)
  • check-spec-format, check-spec-numbering, check-traceability, check-no-panic-family, check-architecture, check-covered-by, check-workspace-shape, check-public-api, check-output-contracts, check-file-policy, check-static-language, check-executable-files, check-generated-clean, check-badge-diff-policy, check-dependencies — pass
  • Hosted required checks + independent review

Relationship to open PRs

Non-goals / residual risks

  • Type-position nesting (deep generics) does not count toward the estimate;
    catastrophic generated type nesting beyond the worker's measured capacity
    could still overflow the worker (abort). Same residual class exists
    upstream in oxc 0.130 (no recursion limit available); pinned at
    crates/ripr/Cargo.toml:42-45.
  • The regex-vs-division and ternary-colon tracking are lexical heuristics;
    pathological inputs can move the estimate in either direction by bounded
    amounts. Bracket terms keep coverage; the failure direction is a bounded
    estimate error or a disclosed refusal, never a wrong result or an
    in-budget abort.
  • Unchanged over-budget files are refused and skipped per the existing
    unchanged-file parse-failure policy (no per-file limitation entry);
    disclosing those in the limitations list lives in the Phase-1 loop this
    branch deliberately does not touch (fix(analysis): cap TypeScript file reads and bound workspace discovery #4098's surface).
  • ripr MSRV/toolchain unchanged; no new dependencies; no public API
    change; check-public-api green.

…large-stack worker

Issue #4101 (CRITICAL): any discovered .ts/.tsx/.js/.jsx file with deep
expression nesting aborted the whole process during Phase-1 parse —
balanced paren nesting of 400 overflowed the 1 MiB Windows debug main
stack (exit 127, no report), even for files not in the diff. Red witness
reproduced 1:1 on the retained e_unchanged_deep probe fixture.

- parse_on_worker: every oxc parse in the adapter now runs on a dedicated
  worker thread with an explicit 256 MiB stack (address-space reservation;
  at most one worker alive; the AST walk joins it), so parser recursion no
  longer depends on the caller's stack. All three parse sites route
  through it: parse_error_reason, extract_owners, ReExportIndex::build.
- PARSE_NESTING_BUDGET (2,000): a cheap single-pass byte scan estimates
  deepest expression nesting (bracket depth + open ternary chain + prefix
  operator runs; comments/strings/templates/regexes skipped; iterative
  binary/member chains do not count). Past the budget the parse is refused
  with a typed static limit 'expression_nesting_budget' riding the
  existing unsupported_syntax finding / language_scope_unsupported
  limitation plumbing — every refusal is disclosed, never an abort.
- Budget placement: 5x above the historical abort threshold (400) so every
  historically aborting input is refused, and >=32x below the worker's
  measured overflow depth (survives 64,000 balanced levels on Windows
  debug, the worst frame sizes observed; aborts at 128,000).
- Worker death (spawn failure or oxc panic) is disclosed as typed
  parse_worker_unavailable / parse_worker_failed static limits.

Discriminating proof:
- 6 unit tests in parse_depth_tests: scan shapes, lexical shells ignored,
  budget+1 typed refusal (balanced source the worker would parse), budget
  admitted and parsed on the worker, depth-400 parse+extract, finding
  renders the budget reason.
- fixtures/ts_parse_depth_budget: benign control, changed depth-400 file
  classifying normally, changed over-budget file emitting the typed
  limitation, unchanged over-budget file surviving discovery (the issue's
  exact blast-radius shape). goldens check: zero drift corpus-wide.
- docs/specs/RIPR-SPEC-0177 + traceability entry.

mod.rs is intentionally untouched to stay textually clear of open #4098.
@gemini-code-assist

Copy link
Copy Markdown

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 51 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: e0acbcdb-a8d5-4e5d-acf7-11ae8ef38078

📥 Commits

Reviewing files that changed from the base of the PR and between cccf141 and 54d2749.

📒 Files selected for processing (18)
  • .ripr/traceability.toml
  • crates/ripr/src/analysis/language/typescript/owners.rs
  • crates/ripr/src/analysis/language/typescript/parse.rs
  • crates/ripr/src/analysis/language/typescript/related_tests.rs
  • crates/ripr/src/analysis/language/typescript/tests_extract.rs
  • docs/specs/README.md
  • docs/specs/RIPR-SPEC-0177-typescript-parse-depth-budget.md
  • fixtures/ts_parse_depth_budget/SPEC.md
  • fixtures/ts_parse_depth_budget/diff.patch
  • fixtures/ts_parse_depth_budget/expected/CHANGELOG.md
  • fixtures/ts_parse_depth_budget/expected/check.json
  • fixtures/ts_parse_depth_budget/expected/human.txt
  • fixtures/ts_parse_depth_budget/input/ripr.toml
  • fixtures/ts_parse_depth_budget/input/src/deep_over_budget.ts
  • fixtures/ts_parse_depth_budget/input/src/deep_over_budget_unchanged.ts
  • fixtures/ts_parse_depth_budget/input/src/deep_under_budget.ts
  • fixtures/ts_parse_depth_budget/input/src/ok.ts
  • policy/doc-artifacts.toml

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed findings

  • PR claims goldens check zero drift across full corpus from worker re-routing but only one new fixture was added; residual goldens risk is acceptable since the change is a worker thread swap with identical parse semantics.
  • Worker reservation is address-space only (256 MiB); on Linux default 8 MiB thread stack limit, spawn may succeed but VM growth occurs lazily. No hard upper bound, but budget 2,000 vs measured ≥16,000 keeps work within budget.

Verification questions

  • Confirm sibling PR #4108 brackets-only scan (cap=128) under-trips on the documented depth-400 abort and does not see unary/ternary chains. PR #4111 is a strict superset for the abort surface; the two conflict textually in parse.rs and related_tests.rs per PR body.
  • Confirm max_expression_nesting_estimate regex-vs-division falls back to Mode::Code only on newline and otherwise skips the entire literal; a regex like /(((((...))))) (healed by closing parens before slash) on one line would be lexed as a regex and skip parens — under-counting depth. Conversely /return /foo/g style could over-count via expression_position mismatch. Bounded heuristic per spec, but no test pins this adversarial shape.
  • Confirm worker closure in related_tests.rs captures workspace_root, alias_map, and a vec of entries via a closure that must be Send+'static; alias_map Clone inside the closure borrows the cloned ref fine, but the outer parse_on_worker generic F requires FnOnce(&Path,&str,&Allocator)->T + Send + 'static. With T = Vec<(Key,(String,String))> and the move closure capturing worker_root/worker_alias, this is sound, but only verified by the typed builder signature — worth a Send static assertion.
  • Confirm fixture SPEC says Produces no limitation for deep_over_budget_unchanged.ts and the process survives; but parse_on_worker currently refuses the budget BEFORE attempting parse, so a discovered unchanged over-budget file generates parse_error_reason=Some(budget_reason) and would surface in the limitation pipeline if anyone queries it. The expected/check.json limitation only lists deep_over_budget.ts. The pre-existing unchanged-file skip policy must be wired upstream of parse_on_worker, or this fixture's 'no limitation for unchanged' claim is load-bearing on Phase-1 code this branch does NOT touch (#4098).
  • Confirm closure passed to parse_on_worker in related_tests.rs clones workspace_root and alias_map via to_path_buf/cloned, then re-borrows as_path/as_ref inside. Smallest-complete-fix shape — no extra sync primitives or shared state introduced; Scoped to FnOnce.

Refuted

  • parse_on_worker should live in a separate typescript/parse_worker.rs module to avoid parse.rs bloat; refuted because: helper is 50 lines, single-responsibility (budget + spawn + join), and is the only consumer of PARSE_WORKER_STACK_BYTES/PARSE_NESTING_BUDGET. Keeping it adjacent to parse_error_reason preserves locality; splitting would force two imports for every call site with no boundary benefit.
  • Worker thread leak / DoS: an adversarial source could keep a worker alive indefinitely.; refuted because: No I/O, no network, no allocation proportional to wall time occurs inside the worker closure beyond the oxc parse and AST walk; handle is joined in the same function and dropped on return.
  • Worker thread per parse creates N threads (one per file) which would be a smoke-only test that doesn't verify the at-most-one-alive invariant; refuted because: Workers are spawned inline per parse_on_worker call; the sequential Phase-1 claim is structural (adapter parses workspace files sequentially), not asserted. But this is a non-test-oracle property (concurrency / resource accounting), not a test-discrimination gap. Tests assert behavior on each route, not threading invariants. The spec's at-most-one-alive is enforced by call-site sequencing, not by a test. Demoted from test-gap to parked-follow-up.

Evidence gaps

  • Model proof intent was rejected by deterministic validation.

Parked follow-ups

  • No external sibling helper (compression, crypto, runtime alloc) is implicated by this diff: the change is bounded to oxc parse entry points in the TypeScript preview adapter. Scope-confined, no broadened follow-up required.

@EffortlessSteven

Copy link
Copy Markdown
Member Author

Review finding from the #4108 lane (evidence-backed, one correction + one defect).

Correction of the supersession premise. #4108 head e6e9823 guards every production parse path, not only parse.rs: nesting_budget_trip runs inside parse_error_reason (parse.rs), unconditionally in the Phase-1 loop before the test/prod branch (mod.rs), and in ReExportIndex::build (related_tests.rs). analyze_repo is a no-parse stub (mod.rs), and extract_owners/extract_tests are reachable only post-gate on byte-identical input that already fully parsed — for the bracket family the gate caps depth at 128, far below the main-thread abort floor, so the re-parse is safe. The stated abort reproduction against #4108 cannot hold on that head for bracket nesting; the disclosed residual there is non-bracket chains, not unguarded call sites.

Defect in #4111 (blocker): extract_tests (tests_extract.rs:20) is untouched by this PR and mod.rs is untouched, so Phase-1 still calls the unwrapped extract_tests on the main thread for every test file that passes the gate. Kill chain: a *.test.ts file with bracket nesting in (main-thread abort floor, 2000] — e.g. 500-deep parens — passes parse_error_reason (worker parses it fine under the 2000 budget, no errors), then extract_tests runs Parser::new(...).parse() on the same bytes on the 1 MiB main-thread stack and aborts exactly as in #4101. Drill: copy the deep_over_budget shape into a *.test.ts file and run the debug binary. The same band threatens any gate-passed file re-parsed on the caller thread; extract_owners was wrapped but extract_tests was not.

Suggested reconciliation (either, not both): wrap extract_tests in parse_on_worker like extract_owners, or adopt a loop-level trip so gate-passed-but-main-thread-unsafe inputs never re-parse on a small stack. The 128-vs-2000 calibration debate is otherwise yours; with the hole closed the worker design is coherent. Happy to re-verify the drill against a revised head.

Keep the nesting budget and large-stack oxc worker, including main's
first-parser-diagnostic text and the Phase-1 source cache on
ReExportIndex::build. Route extract_tests and
detect_partial_test_extraction through the same worker so a file under
the 2000 budget cannot overflow the caller stack on the second parse.
RIPR-SPEC-0177 states no tier change but did not reference
docs/status/SUPPORT_TIERS.md, so check-support-tiers failed
source-of-truth.
@EffortlessSteven

Copy link
Copy Markdown
Member Author

Evidence on the open question "does #4111 cover the extract_tests main-thread abort" — inspected head 54d274973:

Yes. All production second-parse sites route through parse_on_worker (parse.rs), which refuses over-budget sources with a typed expression_nesting_budget static limit BEFORE parsing and runs the parse on the 256 MiB worker thread:

  • tests_extract.rs extract_tests — parse_on_worker closure ("the second parse must not run on the main thread"); reached from discovery.rs:385 and mod.rs:185
  • tests_extract.rs detect_partial_test_extraction — same wrapper
  • owners.rs extract_owners — same wrapper
  • related_tests.rs:84 — same wrapper
  • parse.rs:63 — the canonical guarded entry itself

Remaining direct Parser::new uses are unit tests in tests.rs with small inline sources (no workspace-file input), so no production main-thread parse path remains in the TS adapter.

Caveat (not a blocker): the worker guards depth, not CPU/time — a file just under the 2,000-level budget still pays full parse cost on the worker. That is the disclosed safety-envelope design (budget far below measured worker overflow depth), not a residual abort path.

@EffortlessSteven
EffortlessSteven merged commit d99a756 into main Sep 26, 2026
24 checks passed
@EffortlessSteven
EffortlessSteven deleted the fix/ts-parse-depth-budget-4101 branch September 26, 2026 02:50

@EffortlessSteven EffortlessSteven left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reviewed_head_sha: 54d2749
integration_basis: origin/main 8e25967 (merge-tree clean). The branch merge commit parents are 745ee36 and cccf141; the spec link is 54d2749.
claim_boundary: #4101. Every production oxc parse goes through parse_on_worker: budget 2000, then a 256 MiB ripr-ts-oxc-parse thread. Over-budget changed files disclose expression_nesting_budget on the existing unsupported_syntax contract. Unchanged over-budget files are skipped without a new limitation, matching the fixture. No tier change.
changed_surfaces_and_semantic_owners_inspected: parse.rs parse_on_worker and parse_error_reason (keeps main's first diagnostic text); owners.rs extract_owners; tests_extract.rs extract_tests and detect_partial_test_extraction; related_tests.rs ReExportIndex::build using the Phase-1 source cache plus the worker. Fixture fixtures/ts_parse_depth_budget and RIPR-SPEC-0177, which now links docs/status/SUPPORT_TIERS.md.
blocking_findings: none. The earlier main-thread extract_tests hole is closed on this head: the second parse is inside parse_on_worker, and span starts are computed before the 'static closure.
non_blocking_suggestions: the blessed fixture does not include a deep test file. A local drill (1800 nested parens, changed production file plus a test file) completed and classified owner deep with the related test. That drill is not a committed fixture.
refuted_or_stale_findings: the #4108 supersession comment's extract_tests blocker applied to 745ee36. It does not apply to 54d2749.
proof_and_ci_observed: source-of-truth success (run 36208250212) after the SUPPORT_TIERS link. Ripr Rust Small Result success (run 36208250507, 21m19s). ub-review success. Local fixture JSON and human output matched expected/check.json and human.txt before the merge commit was pushed. Combined merge-tree with #4114 keeps both the spread check and the worker wraps.
proof_or_review_missing: CodeRabbit/Gemini quota skipped. Required approving review count is 0. No unresolved threads.
affected_currentness_dimensions: production, fixture oracle, spec/public claim, conflict resolution against main, candidate head.
residual_assumptions_and_non_claims: a file just under the budget can still be expensive; that is the disclosed envelope, not an abort path. Does not close #3552 or #1160. Does not promote TypeScript off preview.
disposition: REVIEW_READY

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

analysis(ts): CRITICAL stack-overflow abort from deep expression nesting in any discovered workspace file

1 participant