Repository navigation
Description
What happens
A template with many nested <c-if> blocks fails in three different ways,
depending on depth. Measured on origin/main 88d7e4869, macOS arm64, main
thread (8 MB stack):
Nested <c-if> |
Component render | What the user sees |
|---|---|---|
| up to 49 | works | the rendered page |
| 50 to about 1,000 | fails | SyntaxError: In template ...::Deep: too many nested parentheses (<string>, line 2) |
| about 1,030 and up | process dies | segmentation fault (exit code 139), no Python traceback |
The crash depth depends on how citry_core was built and on the stack
size. With a release build (Python 3.12.15) the compiler works at 1,000 and
crashes at 1,030. With a debug build (Python 3.14.9) it already crashes at 446. The 49-level limit is the same in
both.
Calling the parser alone (parse_template) goes deeper: the release build
works at 6,500 and crashes by 8,000 (debug build: 2,060 and 2,120). Nested
<div> elements hit the parser crash at a similar depth, so the parser
limit is not specific to <c-if>.
Two things make this worse than a plain limit:
- The SyntaxError at 50 levels names
<string>, line 2, which is Citry's
generated Python code, not the template. Nothing tells the user that depth
is the problem. - The segfault takes the whole worker process down. A template that comes
from user input or a code generator can kill a server.
Parsing time also grows with the square of the depth. With the release
build, 1,000 levels take 0.12 s, 2,000 take 0.49 s, and 4,000 take 1.96 s.
Reproduction
import sys
from typing import Any
from citry import Citry, Component
n = int(sys.argv[1])
engine = Citry(secret="x" * 32, autodiscover=False)
class Deep(Component):
citry = engine
def template_data(self, kwargs: Any, slots: Any) -> dict[str, Any]:
return {"x": True}
template = '<c-if cond="x">' * n + "deep" + "</c-if>" * n
try:
html = Deep().render().serialize()
print(n, "ok")
except BaseException as e:
print(n, type(e).__name__, str(e)[:200])$ python deep.py 49
49 ok
$ python deep.py 50
50 SyntaxError In template deep.py::Deep:
too many nested parentheses (<string>, line 2)
$ python deep.py 1100; echo "exit=$?"
exit=139
The compiler alone, without a component:
from citry_core.template_parser import compile_template, parse_template
n = 1030
src = '<c-if cond="x">' * n + "x" + "</c-if>" * n
# Release build: works at 1,000, exit 139 at 1,030.
compile_template(parse_template(src))With the debug build, running the same parse and compile in a thread
created after threading.stack_size(256 * 1024 * 1024) succeeds at 600
levels (the main thread crashes at 446), and with 1 GiB at 2,000 levels.
So the crash is a stack overflow in Rust, not an infinite loop or a Pest
error.
Cause
There are two separate limits.
-
Generated code nests 4 brackets per
<c-if>. The compiler writes the
whole body as one Python expression. Each<c-if>adds
IfNode(source, (((...), (...), [ ... ], ...around its children, so 49
levels use 199 open brackets and 50 levels use 203, past CPython's limit
of 200 per expression. Python's tokenizer then rejects the generated
module with "too many nested parentheses". Two nested<c-if>already compile to:body = [IfNode(source, (((0, 48,), (ExprHtmlAttr(...),), [IfNode(source, (((15, 41,), (ExprHtmlAttr(...),), ["""deep""",], (),),), ("x",)),], (),),), ("x",)),]Both the prepared output (
compile_prepared_template,
crates/citry_template_parser/src/compiler.rs:148) and the HTML output
(compile_template,compiler.rs:137) have this shape. -
The Rust compiler and parser recurse once per nesting level without a
depth limit.- Compiler:
compile_template_body_with_mode(compiler.rs:205) calls
compile_control_flow_node(compiler.rs:324), which calls
compile_template_body_with_modeagain for the branch body
(compiler.rs:1561). On the 8 MB main-thread stack this runs out at
about 1,030 levels with a release build (roughly 8 KB of stack per
level) and 446 with a debug build. - Parser: the Pest grammar itself is flat (start and end tags are
separatetemplate_elements,grammar.pest:47-64) and nesting is
tracked with an explicittag_stack. The recursion is in the passes over
the finished tree:recompute_template_used_variablesand
validate_template_variable_shadowing
(crates/citry_template_parser/src/parser.rs:258-259), and
extract_fill_nodes(parser.rs:4846), whichfinalize_noderuns on
every closed tag (parser.rs:455) and which recurses into nested
control flow tags. I could not attach a debugger here, so the
exact frame that overflows is not confirmed. - For
<c-if>,extract_fill_nodesalone makes parse time grow with the
square of the depth: each closing tag walks every<c-if>nested below
it. But nested<div>elements with no expressions grow the same way
(release build: 500 levels 6 ms, 1,000 levels 23 ms), and
extract_fill_nodesstops at a<div>, so other per-tag work is
involved. I did not find it;finalize_node(parser.rs:446) and
validate_node(parser.rs:1638) are the likely places.
- Compiler:
No depth guard exists in the crate, grammar.rs, or citry_core_py
(searched for recursion, depth, stack_size, stacker).
Does it affect both render paths?
Yes. With CITRY_NATIVE_RENDER=0 the component fails with the same
SyntaxError at 50 and the same segfault (release build at 1,100 levels,
debug build at 500). Both limits are hit while
the template is compiled, before either renderer runs.
Suggested fix
- Give the parser a nesting limit and report it as an ordinary template
SyntaxErrorthat points at the tag where the limit was exceeded
("templates can nest at most N tags"). Pick N well below the depth where
the parser or compiler overflows on the smallest stack Citry runs on
(worker threads can have less than 8 MB). This turns the segfault into an
error. - Make the generated code handle the depth Citry allows. For example, the
compiler can assign each nested body to a local variable
(_b1 = [...], thenIfNode(..., _b1, ...)) after a fixed depth, so no
single expression goes over 200 brackets. Otherwise the documented limit
has to be 49, which real templates can reach. - If the limit stays near 49 for a while, catch the "too many nested
parentheses" error in_exec_template_codeand replace it with a message
about template nesting depth. - Separately, find and remove the per-tag work that makes parse time
grow with the square of the depth, so deep templates are not also slow.
Found while shipping the native render levels (#263, #265-#269).
Activity
fix: parse and compile deeply nested templates on any thread without …
feat: add a driver that runs recursive walks without a call per level
perf: precompute constant template parts without one call per level
perf: compile Vue leaf programs without one call per level
perf: write a leaf's generated evaluator without one call per level
perf: transform i18n bindings and leaf operations without one call pe…
perf: build a leaf's read set without one call per level
perf: transform events bindings without one call per level
perf: resolve foreign bodies and compile leaf operations without one …
perf: check simple='vue' support without one call per level
perf: build simple='vue' row plans without one call per level
test: check that first renders of deeper templates use the same Pytho…
test: cover Const, chained-loop and simple='vue' first renders at depth
fix: walk render output with the same Python frames at any template d…
test: confirm templates at the logic limit fit a fixed Python frame b…
test: confirm templates at the logic limit fit a fixed Python frame b…