Skip to content

fix: raise SyntaxError for deeply nested expressions instead of crashing - #337

Merged
JuroOravec merged 4 commits into
mainfrom
fix/deep-expressions
Oct 24, 2026
Merged

JuroOravec merged 4 commits into
mainfrom
fix/deep-expressions

Conversation

@JuroOravec

Copy link
Copy Markdown
Member

Part of #272. This is the fourth PR for #272: deep expressions and deeply nested { now end in a clean error instead of crashing the process.

What was wrong

An expression with many thousands of chained operators or nested brackets crashed the process (SIGSEGV) in safe_eval(), parse_template() and format_template(). Each chain crashed at 50,000 to 100,000 terms (1+1+..., not not ... x, - - ... 1, a.b.b..., f()()..., lambda a, b: lambda a, b: ..., 1 if x else ...), and nested lists at 10,000 [. Ruff's parser grows its own stack, but the passes after it (the keyword check, the sandbox transformer, code generation, the formatter) call themselves once per level of the syntax tree. A template that nests { thousands of levels deep crashed in the Pest grammar the same way.

What changes

  • A depth bound from the tokens (python_safe_eval/src/nesting.rs). python_safe_eval is the crate that checks and compiles each Python expression. Before parsing, it reads the expression's tokens once and computes a depth bound, a number meant never to be smaller than the depth of the tree. It counts operators, keywords, ., and call and subscript brackets. Commas start a new part, except between a lambda's parameters. Past 200, the call raises SyntaxError: expression is nested too deeply. That is about 97 chained + or 65 nested lists. An ordinary expression such as a.b(c[d] + 1) has a depth bound of 16.

    This rejects some input that used to be accepted, such as 150 chained +; both changelogs say so.

  • Enough stack on any thread (src/stack.rs, and citry_template_formatter/src/python.rs). Without a guard, on a 256 KiB thread a debug build handled only about 28 levels (about 9 KB per level), and a release build about 213 (about 1.2 KB). So a limit alone could not be both safe on small threads and large enough to be useful. Each python_safe_eval entry point, and the formatter's Python passes, now run through stacker::maybe_grow. When less than 2 MiB of stack is left (4 MiB for the formatter, whose frames are larger), stacker runs the work on a new stack taken from the heap.

  • The formatter never writes an expression the depth check would refuse. Ruff can add parentheses, which raise the depth bound even though the tree stays the same. When that would push an expression past the limit, the formatter keeps it as the author wrote it.

  • Deep { nesting in templates (citry_template_parser/src/parser.rs). The grammar opens one level per { inside an expression, and it skips a } inside a Python string or comment. So the parser counts every { in the source, which is never below the grammar's depth, and sizes the grammar's stack from that count: 4 KiB per { (1.7 KB measured, doubled and rounded up). A template with more than 100,000 { raises SyntaxError. Making the grammar loop instead of recurse, which would remove the limit, is recorded on Follow-up to #272: walk the template tree with an explicit stack in the Rust parser and compiler, for the planned JS binding #300.

The plan for #272 proposed a pre-scan that counted brackets only. That would have left every chain without brackets crashing, so the token bound above replaces it.

Evidence

  • python_safe_eval/tests/nesting.rs:

    • the bound is never below the real tree depth, for 2,000 random expressions and for a pure chain of each of 26 nesting constructs;
    • on a 256 KiB thread, every accepted expression goes through every pass, and every rejected one gets the clean error.
  • citry_template_parser/tests/deep_expressions.rs, on a 256 KiB thread:

    • deep { below and past the brace limit;
    • {"}", {'}' and {# } repeated, whose } the grammar skips;
    • braces in a <style>, which still parse;
    • the crash shapes in {{ }} and in a c- attribute.
  • citry_template_formatter/tests/deep_expressions.rs: the deepest accepted expression of each shape formats on a 256 KiB thread.

  • I removed each of these in turn (each stack guard, the call-and-subscript rule, the lambda rule, and the total brace count); each removal made these tests fail or abort.

  • Python (citry_core/tests/test_deep_expressions.py):

    • the clean errors from all three entry points;
    • the 10,000-level shapes in subprocesses (exit 0, a clean error from each call);
    • the deepest accepted list parsed and formatted on a 256 KiB Python thread.
  • Pyodide: the release smoke script now evaluates, parses and formats the largest accepted expressions, and checks the error one level past them. A native release build used about 1.2 KB per level, so about 240 KB at the limit if WebAssembly frames cost about the same. Pyodide's exact call-stack size is not confirmed. The qualify workflow, which runs that script inside Pyodide, only accepts a commit on main, so it can't run for this branch. The first proof comes at the next citry-core qualify run, and docs/codebase.md now says so in the release section.

  • Focused checks:

    • Rust: cargo test for python_safe_eval, citry_template_parser and citry_template_formatter (967 tests), plus clippy and fmt;
    • Python: the citry_core suite (516), 549 citry runtime tests on expressions and templates, ruff, and mypy (also --platform linux).

    By agreement, the full local gate was not run, because disk is short. PR CI runs it.

Known limits

  • On wasm32, stacker can't tell how much stack is left, so each outermost guarded call takes a stack from the heap and frees it again. For parse_template that is 256 KiB plus 4 KiB per { in the template, up to about 391 MiB at the brace limit, which could fail inside Pyodide's memory limit. The cost is not measured.
  • On native, the most expensive accepted template (about 100,000 nested {, 200 KB of input) raised its clean error in 0.24 s, but peaked at about 207 MB of memory, against 29 MB at baseline.
  • On wasm32, the grammar's recursion over nested { runs on the engine's own call stack, which stacker cannot grow. A template with a few thousand nested { may therefore still fail fatally in Pyodide. That is unproven. Making the grammar loop instead of recurse (Follow-up to #272: walk the template tree with an explicit stack in the Rust parser and compiler, for the planned JS binding #300) removes it.
  • Building a template error over a span of many lines costs time in proportion to the line count times the input length, inside Pest's error builder. A 20,000-line expression with an error takes about 75 s in a debug build. That is a separate problem and is not fixed here.

🤖 Generated with Claude Code

JuroOravec and others added 4 commits October 24, 2026 18:39
An expression with many thousands of chained operators (`1+1+...`,
`not not ... x`, `a.b.b...`, `f()()...`, `1 if x else ...`) or nested
brackets crashed the process with a segmentation fault in safe_eval(),
parse_template() and format_template(). Ruff's parser grows its own
stack, but the passes after it (the keyword check, the sandbox
transformer, code generation, the formatter) and dropping the tree call
themselves once per tree level. A template that nests `{` thousands of
levels deep crashed in the Pest grammar the same way.

- python_safe_eval, the crate that checks and compiles template
  expressions, reads an expression's tokens before parsing it and computes
  a depth bound, a number meant never to be smaller than the tree's depth.
  It counts operators, keywords, `.`, brackets, calls and subscripts, and
  scores each comma-separated item separately, except a lambda's
  parameters. Past 200 (about 97 chained `+` or 65 nested lists) it
  raises "expression is nested too deeply". Tests check the bound against
  the real depth of 2,000 random expressions and of a pure chain of each
  of 26 common nesting constructs.
- Each python_safe_eval entry point, and the formatter's Python passes,
  run their work through `stacker::maybe_grow`, sized from the measured
  debug-build cost per level. So on a 256 KiB thread every accepted
  expression is fully processed; the tests on such a thread abort when
  a guard is removed.
- The formatter keeps an expression as written when the parentheses Ruff
  would add push its depth bound past the limit, so it never writes an
  expression the depth check would refuse.
- The template parser counts every `{` before the grammar runs. The
  grammar can never open more levels than that, even when a `}` sits in a
  string or comment, which it skips. Past 100,000 `{` it raises a clean
  error; below that, the grammar runs with a stack sized for the count.
  Making the grammar loop instead of recurse is tracked in #300.
- The release smoke script, which also runs inside Pyodide, evaluates,
  parses and formats the largest accepted expressions and checks the
  clean error one level past them.

Input just past the new limits used to be accepted and now raises; both
changelogs say so.

The plan for #272 proposed a pre-scan that counted brackets only. That
would have left every chain without brackets crashing, so it was replaced
by the token bound above.

Part of #272.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The 10,000-level cases built a -c argument of 40 to 120 KB, longer than
a Windows command line allows (WinError 206 on windows-latest).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@JuroOravec
JuroOravec merged commit bda8db9 into main Oct 24, 2026
22 of 27 checks passed
@JuroOravec
JuroOravec deleted the fix/deep-expressions branch October 24, 2026 20:36
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.

1 participant