Repository navigation
fix: raise SyntaxError for deeply nested expressions instead of crashing - #337
Merged
Merged
Conversation
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]>
This was referenced Oct 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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()andformat_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 raisesSyntaxError: expression is nested too deeply. That is about 97 chained+or 65 nested lists. An ordinary expression such asa.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, andcitry_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 throughstacker::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{raisesSyntaxError. 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:citry_template_parser/tests/deep_expressions.rs, on a 256 KiB thread:{below and past the brace limit;{"}",{'}'and{# }repeated, whose}the grammar skips;<style>, which still parse;{{ }}and in ac-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):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:
cargo testfor python_safe_eval, citry_template_parser and citry_template_formatter (967 tests), plus clippy and fmt;--platform linux).By agreement, the full local gate was not run, because disk is short. PR CI runs it.
Known limits
parse_templatethat 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.{, 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.{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.🤖 Generated with Claude Code