Skip to content

fix: parse and compile deeply nested templates on any thread without crashing - #343

Merged
JuroOravec merged 1 commit into
mainfrom
fix/stack-safety
Oct 24, 2026
Merged

JuroOravec merged 1 commit into
mainfrom
fix/stack-safety

Conversation

@JuroOravec

Copy link
Copy Markdown
Member

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:

  • the parser's passes over the finished tree;
  • the compiler;
  • copying, comparing, printing and freeing the parsed tree.

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:

Step 256 KiB thread 128 KiB thread
Copy (Clone) 60 levels 30 levels
Compile <c-if> (freeing the compiler's argument tree) 391 201
Parse a template in an attribute value (freeing it) not measured 192
An invalid expression, {{ x + }}, at any depth crashed between 180 and 224 KiB inside an attribute template crashed
Free a template (Drop) 1,058 546

Past those depths the process crashed (SIGSEGV or a stack-overflow abort). Every shape in the new test aborted on main.

What changes

  • A stack guard on every recursion entry (citry_template_parser/src/stack.rs). Each entry the plan lists runs its work through stacker::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_nodes and collect_template_binding_tokens;
    • find_ignored_content_problem, _contains_only_fills_and_control_flow and validate_fill_group_content;
    • process_template_string;
    • compile_template_body_with_mode.
  • A larger guard for one embedded expression (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.
  • Copying, comparing, printing and freeing a Template go 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 == and repr(), and pytest calls repr() on a failed comparison; on main those crashed on a 128 KiB thread at 512 and 100 levels. So Template gets its own Clone, Drop, PartialEq and Debug:
    • each guards a body that holds child nodes; a body with only text and expressions can't nest, so it skips the guard;
    • Debug prints exactly what the derived one did, and a test checks this.
  • LangSpecArgument frees 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 the LangImpl trait are unchanged. The one place that moved a string out of an argument by pattern now uses std::mem::take.
  • The binding borrows the template (citry_core_py/src/template_parser.rs). compile_template and _compile_prepared_template take PyRef<'_, 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 Template or a LangSpecArgument, because both types now have a Drop. The five places in this repository that did so now use std::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.rs parses, 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:

    • nested elements;
    • <c-if>;
    • <c-for> tags that each bind a name the body reads;
    • control-flow attributes;
    • control flow mixed with elements;
    • nested components;
    • a fill under deep control flow;
    • deep content under #c-ignore;
    • a deep template in an attribute value.
  • Every shape aborted on main. The test aborts again in each of these cases:

    • the guard is disabled;
    • LangSpecArgument's drop is put back to the derived one;
    • the expression guard is removed (the new invalid-expression test).
  • 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.py runs five of the shapes on a 128 KiB Python thread, in a subprocess. Each one is parsed and compiled, == and repr() 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:

    • 1.0% to 2.1% slower in total, across rounds;
    • the 92 KB flat file 0.5% to 2.7% slower, and 4,000 <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:

    • Rust: cargo test for citry_template_parser and citry_template_formatter (647), plus clippy and fmt;
    • Python: the citry_core suite (505), and 802 citry runtime, check, format and LSP tests.

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

Differences from the plan

  • The plan follows Ruff in skipping the stack check for the first few levels of each walk. This PR checks at every guarded call. The measured cost on ordinary templates is within the plan's 5%, and a skip would mean passing a depth through each pass.
  • The plan expected derived Clone and Drop to fit at the limit and to need a change only if test 7 failed. Test 7 failed for Clone, for the attribute-template Drop, and for LangSpecArgument's drop, so all three changed. The review then found ==, repr() and the invalid-expression path crashing on small threads, so PartialEq, Debug and the expression guard were added too. The plan listed none of these.

Known limits

  • Rendering a template this deep can still raise RecursionError in 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).
  • Python code that reads a field holding a template, such as a node's body, still gets a copy. It now runs through the guard, but it is still a copy of the whole subtree.
  • On wasm32, stacker can't tell how much stack is left. Every guarded call not already on a new segment takes a 1 MiB block from the heap and frees it again. The fill check runs for each closed tag, so that is about one block per closed tag. The cost is not measured.
  • An attribute template still needs about 84 KiB of stack in the outer parse, before any guard. Threads smaller than that are not covered.
  • On Windows, CPython treats 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

…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]>
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