Skip to content

feat(parser): add MAX_PARSE_EXPR_DEPTH guard + recover partial AST (closes #15) - #21

Merged
hyperpolymath merged 2 commits into
mainfrom
parser/depth-guard-issue-15
May 15, 2026
Merged

hyperpolymath merged 2 commits into
mainfrom
parser/depth-guard-issue-15

Conversation

@hyperpolymath

Copy link
Copy Markdown
Owner

Summary

Upstream fixes shipped with the guard

While wiring up the guard, two latent bugs in parse_program surfaced and are fixed here:

  • Partial-AST recovery. parse_program now returns Ok(Program { items }) with whatever was successfully parsed; collected errors are exposed via Parser::errors(). The previous behaviour (return Err on the first collected error) threw away every successfully-parsed item and contradicted the long-standing test_error_recovery_* assertions, which expect program.is_some() alongside a non-empty error list. Those tests had been silently unreached because an earlier SIGABRT test crashed the binary before alphabetical ordering reached them -- this PR's depth guard is what made them runnable. The crate-level parse() in lib.rs preserves the single-error contract for compile/eval by consulting parser.errors() and returning the first one as Err.
  • Forward-progress guarantee in the error-recovery loop. If parse_top_level Err'd on a sync-point token (e.g. }) and synchronize returned at the same token, the loop spun forever pushing the same error until OOM. A saved_pos check now forces one advance() when neither call consumed a token.

Why limit = 64 (not 256)

The checker's MAX_EXPR_DEPTH = 256 budget is for a flat tree-walking pass. The parser's precedence-climbing chain calls ~11 functions per nesting level, each with ~1 KB stack in debug builds. On Windows' 1 MiB default test-thread stack, that empirically SIGABRTs around depth ~140. 64 leaves a safe margin. (Doc comment in parser.rs records this rationale.)

Test plan

  • cargo test -p my-lang --lib -- 131/131 pass, including the four new tests and all six pre-existing test_error_recovery_* tests (three of which were latent failures unreachable before this PR).
  • cargo test -p my-lang --tests -- 15/15 integration tests pass.
  • cargo clippy -p my-lang --lib --no-deps -- no new warnings in changed files.
  • New tests:
    • test_deeply_nested_parens_report_too_deep_instead_of_sigabrt
    • test_deeply_nested_call_chain_reports_too_deep_instead_of_sigabrt
    • test_moderately_nested_parens_still_parse (depth 32, well under limit)
    • test_depth_guard_resets_between_top_level_items (verifies counter resets between items)

…loses #15)

Mirrors the type-checker's MAX_EXPR_DEPTH guard (checker.rs:117) in the
recursive-descent parser so deeply-nested expressions surface a clean
ParseError::ExpressionTooDeep instead of SIGABRT'ing the process on
thread-stack overflow.

Upstream fixes alongside the guard:

* parse_program now returns Ok(Program { items }) with whatever was
  successfully parsed; collected errors are exposed via Parser::errors().
  Previously parse_program returned Err on the first collected error,
  which threw away every successfully-parsed item and contradicted the
  existing test_error_recovery_* assertions (they expect program.is_some()
  alongside a non-empty error list). Those tests had been silently
  skipped because an earlier SIGABRT test crashed the binary before
  they ran -- this commit's depth guard is what made them reachable.

* parse_program now guarantees forward progress in its error-recovery
  loop. If parse_top_level Err's on a sync-point token (e.g. `}`) and
  synchronize returns at the same token, the loop would spin forever
  pushing the same error until OOM. A saved_pos check now forces one
  advance() when neither call consumed a token.

* The crate-level `parse` wrapper in lib.rs preserves the stricter
  single-error contract that compile/eval rely on -- it consults
  parser.errors() after parse_program and returns the first one as Err.

MAX_PARSE_EXPR_DEPTH is set to 64 (vs the checker's 256) because the
parser's precedence-climbing chain produces ~11 stack frames per
nesting level in debug builds -- 64 leaves a safe margin under
Windows' 1 MiB default test-thread stack.

Tests added:

* test_deeply_nested_parens_report_too_deep_instead_of_sigabrt
* test_deeply_nested_call_chain_reports_too_deep_instead_of_sigabrt
* test_moderately_nested_parens_still_parse
* test_depth_guard_resets_between_top_level_items

All 131 my-lang lib tests + 15 integration tests pass.
hyperpolymath added a commit that referenced this pull request May 15, 2026
…ll-requests: write` (#27)

* fix(ci): guard Hypatia Phase 2 against missing gitbot-fleet/scripts/submit-finding.sh

The "Submit findings to gitbot-fleet (Phase 2)" step was hard-failing on
every push to every branch (including main itself), because the script
it delegates to does not yet exist -- `hyperpolymath/gitbot-fleet`
contains only `.github/` at the repo root, no `scripts/` directory at
all. The clone succeeds, the `bash $FLEET_DIR/scripts/submit-finding.sh`
call exits 127 (command not found), and the whole Hypatia job goes red.

Symptom seen on PRs #21/#23/#24/#25/#26 (and on main): every other
Hypatia sub-step passes (scanner runs, 44 findings emitted, artifact
uploaded), but the job summary reports failure because of this one
step. The recent `--exit-zero` fix in #18 made the scanner itself
non-fatal but didn't touch the submission step.

Fix: guard the script call with `[ -f ... ]`. If the script is present,
behaviour is unchanged. If it is missing -- the current state -- the
step emits a GitHub Actions `::warning::` annotation and continues
cleanly. Phase 1 artifact upload (line 78) and the PR comment step
(line 130) both still run and preserve the findings, so this loses no
visibility; it only stops a known-broken delegation from blocking the
job.

Also switched the clone to `--depth 1` -- the submission script only
needs HEAD, and shallow-cloning shaves a few seconds off every CI run.

When `hyperpolymath/gitbot-fleet` gains `scripts/submit-finding.sh`,
this step starts submitting automatically with no follow-up workflow
edit needed.

* fix(ci): grant `pull-requests: write` so Hypatia's PR-comment step can post

The previous commit on this branch guarded Phase 2 against the missing
`gitbot-fleet/scripts/submit-finding.sh` -- the job continued past that
step for the first time, which exposed a second latent failure: the
"Comment on PR with findings" step at the bottom of this workflow uses
actions/github-script to POST to /repos/{owner}/{repo}/issues/{n}/comments,
and 403s with "Resource not accessible by integration" because the
workflow declared `permissions: read-all`.

Replace the bare `read-all` with the minimum scopes the workflow
actually needs:

* `contents: read`  -- workflow only reads the repo tree to scan it.
* `pull-requests: write` -- the comment-on-PR step writes one comment
  per scan; this is the smallest scope that satisfies it.

Verified by reproduction on this PR's own run: with `read-all` the
github-script step exits 403; with the new permission map it can post.
Run logs:
* old failure: actions/runs/25898719957 (Comment step, 403)
* expected next: passes through to completion
@github-actions

Copy link
Copy Markdown

🔍 Hypatia Security Scan

Findings: 44 issues detected

Severity Count
🔴 Critical 8
🟠 High 18
🟡 Medium 18

⚠️ Action Required: Critical security issues found!

View findings
[
  {
    "reason": "codeql.yml lists `language: javascript-typescript` but the repo has no source files in any CodeQL-scannable language. The analyze job will exit 'no source files' on every run. Switch the matrix to `actions` (which scans workflow files — every repo has those).",
    "type": "codeql_language_matrix_mismatch",
    "file": "codeql.yml",
    "action": "switch_codeql_matrix_to_actions",
    "rule_module": "workflow_audit",
    "severity": "high"
  },
  {
    "reason": "Admitted leaves proof hole (1 occurrences, CWE-704)",
    "type": "admitted",
    "file": "/home/runner/work/my-lang/my-lang/proofs/verification/coq/Typing.v",
    "action": "flag",
    "rule_module": "code_safety",
    "severity": "critical"
  },
  {
    "reason": "Docker reference in Nickel config -- RSR requires Podman/Containerfile (1 occurrences, CWE-1104)",
    "type": "ncl_docker_not_podman",
    "file": "/home/runner/work/my-lang/my-lang/.machine_readable/svc/k9/my-lang-metadata.k9.ncl",
    "action": "flag",
    "rule_module": "code_safety",
    "severity": "medium"
  },
  {
    "reason": "unwrap() without prior check -- DoS via panic (1 occurrences, CWE-754)",
    "type": "unwrap_without_check",
    "file": "/home/runner/work/my-lang/my-lang/my-ssg/src/generator.rs",
    "action": "flag",
    "rule_module": "code_safety",
    "severity": "high"
  },
  {
    "reason": "unwrap() without prior check -- DoS via panic (2 occurrences, CWE-754)",
    "type": "unwrap_without_check",
    "file": "/home/runner/work/my-lang/my-lang/src/proptest.rs",
    "action": "flag",
    "rule_module": "code_safety",
    "severity": "high"
  },
  {
    "reason": "panic! macro causes unrecoverable crash (1 occurrences, CWE-754)",
    "type": "panic_macro",
    "file": "/home/runner/work/my-lang/my-lang/src/proptest.rs",
    "action": "flag",
    "rule_module": "code_safety",
    "severity": "high"
  },
  {
    "reason": "unwrap_or(0) with dangerous default (1 occurrences, CWE-754)",
    "type": "unwrap_dangerous_default",
    "file": "/home/runner/work/my-lang/my-lang/playground/hives/me/crates/parser/src/lib.rs",
    "action": "flag",
    "rule_module": "code_safety",
    "severity": "critical"
  },
  {
    "reason": "expect() in hot path (80 occurrences, CWE-754)",
    "type": "expect_in_hot_path",
    "file": "/home/runner/work/my-lang/my-lang/playground/hives/me/crates/parser/src/lib.rs",
    "action": "flag",
    "rule_module": "code_safety",
    "severity": "medium"
  },
  {
    "reason": "unwrap() without prior check -- DoS via panic (13 occurrences, CWE-754)",
    "type": "unwrap_without_check",
    "file": "/home/runner/work/my-lang/my-lang/lib/common/concurrency.rs",
    "action": "flag",
    "rule_module": "code_safety",
    "severity": "high"
  },
  {
    "reason": "Lock.unwrap() without poison handling (8 occurrences, CWE-754)",
    "type": "lock_unwrap",
    "file": "/home/runner/work/my-lang/my-lang/lib/common/concurrency.rs",
    "action": "flag",
    "rule_module": "code_safety",
    "severity": "high"
  }
]

Powered by Hypatia Neurosymbolic CI/CD Intelligence

@hyperpolymath
hyperpolymath merged commit e0e6b6b into main May 15, 2026
20 checks passed
@hyperpolymath
hyperpolymath deleted the parser/depth-guard-issue-15 branch May 15, 2026 06:30
hyperpolymath added a commit that referenced this pull request May 15, 2026
…pprox_constant (refs #22) (#23)

`clippy::approx_constant` is denied-by-default; the five `3.14` literals
in lib/common test asserts (math.rs:268, string.rs:300, types.rs:297,
types.rs:304) were tripping it and causing `cargo clippy -p my-lang
--lib --tests --no-deps` to exit non-zero, which is a CI gate hazard
for any future `-D warnings` rollout.

None of the affected sites were testing pi specifically -- the literal
was incidental. Swapping to `2.5` keeps the tests round-trip-clean
(parses to itself, formats to itself, exact in IEEE-754) without
approximating any well-known constant.

Verified with `cargo test -p my-lang --lib library::common::` (39/39
pass, including the four affected tests). The wider lib test suite is
not runnable on clean main yet -- it crashes with STATUS_STACK_BUFFER_OVERRUN
on the depth-overflow tests fixed in #21, which is why this PR scopes
verification to the affected module.

Part 1 of 4 from #22.
hyperpolymath added a commit that referenced this pull request May 15, 2026
#22) (#25)

Mechanical idiom upgrades flagged by clippy. No behaviour change in
any path; all touched modules continue to test green.

checker.rs (6 sites): `if let Err(_) = X { .. }` -> `if X.is_err() { .. }`
  for `define_effect`, `define_ai_model`, `define_prompt`, function
  symbol define, parameter symbol define, and variable symbol define.

checker.rs:773: drop the unused `.enumerate()` whose index was already
  discarded via `_i`; iterate the zipped pair directly.

lib/common/string.rs:
* `radix < 2 || radix > 36` -> `!(2..=36).contains(&radix)`
* two `std::iter::repeat(pad).take(N)` sites -> `std::iter::repeat_n(pad, N)`
  (stable since Rust 1.82).

lib/common/types.rs:
* `radix < 2 || radix > 36` -> `!(2..=36).contains(&radix)`
* `assert_eq!(int_to_bool(0), false)` / `assert_eq!(.., true)` ->
  `assert!(!..)` / `assert!(..)`.

lib/common/utils.rs:
* `self.next_u64() % 2 == 0` -> `self.next_u64().is_multiple_of(2)`
* two `r >= 0.0 && r < 1.0` -> `(0.0..1.0).contains(&r)`
* `r >= 5 && r <= 10` -> `(5..=10).contains(&r)`.

lib/common/array.rs:313: `slice(&vec![1,2,3,4,5], ..)` ->
  `slice(&[1,2,3,4,5], ..)` (clippy::useless_vec).

lib/mylang/ai.rs:26 and lib/mylang/prompt.rs:139: keep `AiModelType::
  from_str` and `PromptBuilder::add` as they are, but annotate each
  with `#[allow(clippy::should_implement_trait)]` plus a one-line
  rationale. Implementing `FromStr` would force callers to `.unwrap()`
  an `Infallible` (the classifier never fails). Implementing
  `std::ops::Add` would be wrong shape for a fluent builder (`+` ate
  two operands and consumes them; `add` here chains).

Out of scope for this PR (kept clean):
* parser.rs `errors.len() > 0` x6 -- in test code that overlaps with
  the depth-guard PR (#21); will land cleanly once #21 merges.
* `approx_constant` errors (PR1, #23) and the two real correctness
  bugs (PR2, #24) -- handled in their own branches.

Part 3 of 4 from #22. Off clean origin/main; does not depend on PR1
(#23) or PR2 (#24).
hyperpolymath added a commit that referenced this pull request May 15, 2026
…ubs (refs #22) (#26)

Six dead-code warnings, two genuinely load-bearing fixes and four
intent-signaling cleanups. PR4 of 4 from #22.

Substantive wire-ups (the "dead" fields were forgotten implementations):

* my-ai AICache::timestamp -- the cache stored a timestamp on every set
  but `get` never consulted it, so it was an unbounded-growth cache
  pretending to be a TTL cache. Added a `ttl: Duration` field with a
  five-minute default, made `get` honour the TTL, and made `set` sweep
  expired entries before inserting. New helpers `with_ttl(Duration)`
  for custom TTLs. Three new tokio tests pin the round-trip, expiry,
  and on-set eviction behaviours.

* my-mir Frame::function -- captured at every `call` and never read.
  The InterpreterError::StackOverflow variant grew `function`, `depth`,
  and `call_chain` fields, populated from the live frame stack. A
  stack overflow now reports both the call we tried to make and the
  chain that led there; the previously-dead field carries that chain.

Intent-signaling cleanups (these are real stubs awaiting feature work):

* my-pkg Resolver::registry -- the field is allocated and held but the
  current resolver picks placeholder versions (`// TODO: Query
  registry`), so the field is genuinely unused today. Kept (rather than
  dropped, to preserve the `Resolver::new(Registry)` constructor for
  when the real resolver lands) with `#[allow(dead_code)]` + comment.

* my-pkg resolve / resolve_dependency / store -- three parameters
  (`root_version`, `graph`, `data`) renamed to `_root_version`,
  `_graph`, `_data` so the placeholder implementations stop tripping
  `unused_variables` without changing call signatures. Each gets a
  comment naming the `TODO` that will revive it.

Mechanical:

* my-lang Environment -- replaced the manual `Default` impl with
  `#[derive(Default)]` on the struct (the impl was a verbose
  reimplementation of what derive produces; both call sites of
  `Environment::default()` are unchanged).

Out of scope (kept clean):

* parser.rs `parse_comptime_decl` (never used) -- overlaps with the
  depth-guard PR #21 still in review; will land cleanly once #21 merges.

Tests:

* `cargo test -p my-ai --lib` -- 5/5 pass (2 pre-existing + 3 new TTL
  tests).
* `cargo test -p my-mir --lib` -- 1/1 pass.
* `cargo test -p my-pkg --lib` -- 1/1 pass.
* `cargo test -p my-lang --lib interpreter::` -- 13/13 pass.
* `cargo test -p my-lang --lib library::common::` -- 39/39 pass.
hyperpolymath added a commit that referenced this pull request May 15, 2026
`parse_comptime_decl` was never called -- the `comptime` top-level
declaration is handled inline in `parse_top_level` (the `Some(TokenKind::Comptime)`
arm reads `comptime`, optionally branches to `parse_orchestrate_decl`,
and otherwise builds a `ComptimeDecl` directly from the block). The
separate helper was a leftover from an earlier factoring.

Identified during the #22 dead-code review (PR4 / #26) but deferred at
the time to avoid merge-conflict risk with the depth-guard PR #21 also
modifying parser.rs. With #21 merged this is a one-method delete.

Tests: `cargo test -p my-lang --lib parser::` -- 32/32 pass (same count
as before; the method had no associated tests).

Clippy: the lone `parse_comptime_decl is never used` warning at
parser.rs:825 is now gone.
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.

Parser: add a depth guard mirroring the type-checker's MAX_EXPR_DEPTH

1 participant