Repository navigation
fix: parse and compile deeply nested templates on any thread without crashing - #343
Merged
Merged
Conversation
…crashing The parser's passes over the finished tree, the compiler, and copying, comparing, printing and freeing the tree all call themselves once per nesting level. On a 256 KiB thread a debug build ran out at about 60 levels when copying a template, and at a few hundred levels in the passes and the compiler, and the process crashed. Threads started after a small `threading.stack_size()`, and threads on musl Linux (128 KiB by default), have small stacks. - Each function that starts a walk over the tree runs its work through `stacker::maybe_grow`, with a 100 KiB red zone and 1 MiB segments, as Ruff does: the passes for used variables, bindings and fills, the checks that walk a subtree when a tag closes, the parse of a template inside an attribute value, and the compiler body. - Parsing one embedded expression gets a 256 KiB red zone, because reporting an invalid one needed about 100 KiB more stack than parsing a valid one, enough to crash a 128 KiB thread at any depth. - `Template` gets its own `Clone`, `Drop`, `PartialEq` and `Debug`, which go through the same guard for bodies that hold child nodes. Copying measured about 4 KB per level in a debug build; a template parsed from an attribute value is freed while the parser still reads the tag that holds it; and Python reaches `==` and `repr()`. Bodies with only text and expressions skip the guard, which keeps ordinary templates within about 1 to 2% of before over 123 docs and benchmark templates. `Debug` prints exactly what the derived one did. - `LangSpecArgument` frees its children without recursion. The derived drop ran out at 200 levels of control flow on a 128 KiB thread. - `compile_template` and `_compile_prepared_template` borrow the template (`PyRef`) instead of letting PyO3 copy it while it converts the argument. Python sees the same parameter type. tests/deep_nesting.rs parses, copies, compares, prints, compiles and frees nine shapes on 256 KiB and 128 KiB threads, up to 512 tags deep: 512 for plain elements, 256 for control flow and components. Every shape aborted before this change, and the test aborts again when the guard, the expression guard or the drop change is removed. A Python test runs five of those shapes, and an invalid expression, on a 128 KiB thread in a subprocess. This adds no nesting limit; that comes later for #272. Part of #272. Co-Authored-By: Claude Opus 5.5 <[email protected]>
JuroOravec
force-pushed
the
fix/stack-safety
branch
from
October 24, 2026 22:14
e88682e to
97c8fcd
Compare
This was referenced Oct 24, 2026
Merged
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 PR (C1 in the plan for #272) lets the Rust parser and compiler handle deeply nested templates on any thread, instead of crashing the process. It adds no nesting limit; that comes later in the plan (C2).
What was wrong
These all call themselves once per nesting level:
Threads started after a small
threading.stack_size()have small stacks, and so do threads on musl Linux (128 KiB by default). In a debug build, on main:Clone)<c-if>(freeing the compiler's argument tree){{ x + }}, at any depthDrop)Past those depths the process crashed (SIGSEGV or a stack-overflow abort). Every shape in the new test aborted on main.
What changes
citry_template_parser/src/stack.rs). Each entry the plan lists runs its work throughstacker::maybe_grow, with a 100 KiB red zone and 1 MiB segments, the sizes Ruff uses. When less than 100 KiB of stack is left, stacker runs the rest on a new stack taken from the heap. The guarded entries:recompute_template_used_variables,validate_template_bindings,extract_fill_nodesandcollect_template_binding_tokens;find_ignored_content_problem,_contains_only_fills_and_control_flowandvalidate_fill_group_content;process_template_string;compile_template_body_with_mode.process_expression). Reporting an invalid expression needed about 100 KiB more stack than parsing a valid one (148 KiB against 48 KiB for{{ x + }}and{{ x }}). So the call into the expression parser keeps a 256 KiB red zone.Templatego through the guard (ast.rs). The plan expected their frames to be small. Measured, copying costs about 4 KB per level in a debug build. Freeing fits on its own, but a template parsed from an attribute value is freed while the parser is still reading the tag that holds it, outside any guarded pass, and there it ran out at 192 levels. Python also reaches==andrepr(), and pytest callsrepr()on a failed comparison; on main those crashed on a 128 KiB thread at 512 and 100 levels. SoTemplategets its ownClone,Drop,PartialEqandDebug:Debugprints exactly what the derived one did, and a test checks this.LangSpecArgumentfrees its children without recursion (lang/lang.rs). The compiler builds one argument per level of control flow, and the derived drop needed about 650 bytes per level. The type and theLangImpltrait are unchanged. The one place that moved a string out of an argument by pattern now usesstd::mem::take.citry_core_py/src/template_parser.rs).compile_templateand_compile_prepared_templatetakePyRef<'_, Template>, so PyO3 doesn't copy the whole tree while it converts the argument. Python sees the same parameter type.Rust code can no longer move a field out of a
Templateor aLangSpecArgument, because both types now have aDrop. The five places in this repository that did so now usestd::mem::take: four in the crate, and one in its shared test helper. No other crate does this.Evidence
citry_template_parser/tests/deep_nesting.rsparses, copies, compares, prints, compiles (both outputs) and frees nine shapes on 256 KiB and 128 KiB threads. The shapes go up to 512 tags deep: 512 for plain elements, 256 for control flow and components. The shapes:<c-if>;<c-for>tags that each bind a name the body reads;#c-ignore;Every shape aborted on main. The test aborts again in each of these cases:
LangSpecArgument's drop is put back to the derived one;Another test checks that an invalid expression gives a clean error on a 128 KiB thread, at the top level, in an attribute template and under 256
<c-if>tags.citry_core/tests/test_template_parser_deep_nesting.pyruns five of the shapes on a 128 KiB Python thread, in a subprocess. Each one is parsed and compiled,==andrepr()run on it, and a field is read so PyO3 copies a subtree there. The same file checks an invalid expression on that thread. I did not run this test against main's extension, because that would need two more extension builds. The Rust test covers the same code.The generated code is unchanged: the locked compile tests pass with no edits.
Speed, parse plus compile in release over 123 docs and benchmark templates plus the plan's two synthetic files, best of 45 runs each, before and after interleaved:
<br>1.8% to 2.3% slower.The machine was shared with other builds, so single small templates swung by up to 2x between rounds, in both directions. The totals stayed within the plan's 5%. Without the shortcut for bodies with no child nodes, the total was 5.2% slower and the flat file 7%.
Focused checks:
cargo testfor citry_template_parser and citry_template_formatter (647), plus clippy and fmt;By agreement, the full local gate was not run, because disk is short. PR CI runs it.
Differences from the plan
CloneandDropto fit at the limit and to need a change only if test 7 failed. Test 7 failed forClone, for the attribute-templateDrop, and forLangSpecArgument's drop, so all three changed. The review then found==,repr()and the invalid-expression path crashing on small threads, soPartialEq,Debugand the expression guard were added too. The plan listed none of these.Known limits
RecursionErrorin the Python walkers. That is the next part of the plan (PR E, Follow-up to #272: forwarded slot chains and simple='vue' components still use Python frames per level #299).body, still gets a copy. It now runs through the guard, but it is still a copy of the whole subtree.threading.stack_size()as the amount committed rather than reserved, so the Python test probably does not get a 128 KiB stack there. The Rust test sets the size itself.🤖 Generated with Claude Code