Skip to content

fix: start each deep Rust entry point with a stack guard - #428

Merged
JuroOravec merged 1 commit into
mainfrom
fix/rust-entry-stack-guards
Oct 27, 2026
Merged

JuroOravec merged 1 commit into
mainfrom
fix/rust-entry-stack-guards

Conversation

@JuroOravec

Copy link
Copy Markdown
Member

What this fixes

Python can call into citry_core when only a little of the thread's stack is left. CPython 3.14 refuses a call into a C extension only when about 20 KiB or less is left. In a debug build, the template parser needs about 87 KiB before it reaches its first internal stack check. So a call that CPython lets through can still run off the end of the stack and kill the process.

This showed up as a crash when a component rendered a deep template from a call stack that was already deep:

  • The thread had a 512 KiB stack, the macOS default for a thread a host program starts.
  • 610 to 650 C-level frames were already in use.
  • The component had not rendered before, so Citry parsed and compiled its template inside that thread. The native render path was off.
  • The crash was inside parse_template.

What changes

  1. Each Rust entry point that does deep work starts with a stack check. It runs its Rust work through the template parser's existing with_enough_stack helper. Converting the arguments and building the Python result stay outside, because they touch Python objects. When less than 100 KiB is left, the helper runs the work on a 1 MiB stack segment taken from the heap. That work reads only Rust data, so it is safe to run off the thread's own stack. The helper is now public (citry_template_parser::stack), so the Python bindings reuse it.
  2. Entry points that run on every render skip the check on wasm32. On wasm32 (Pyodide), stacker cannot measure the stack, so every outermost guarded call takes a 1 MiB block from the heap. A small wrapper next to the helper, with_enough_stack_where_measurable, calls with_enough_stack on other targets and runs the work directly on wasm32. So on Pyodide these calls keep running on the current stack, as before. The html_transform entry points, the i18n message lookups and analyze_browser_source call the wrapper, because several of them run on every render: mark_html once per component, the output checks once per page, a message lookup once per message, and analyze_browser_source for each expression of a fill rendered outside the component that wrote it. Parsing, compiling and formatting keep the full guard on wasm32, where it now takes one block per call: the parser's own guards reuse that block, where they used to take about one block per closed tag.
  3. The formatter's tree walks check the stack at every level. After (1), format_template still crashed. Its walks over nested elements call themselves once per level, and none of them checked the stack. In a debug build, a fresh 4 MiB thread overflowed at a few hundred levels, and the 8 MiB main thread overflowed at 1,000 nested <div> elements. Now visit_node, project_node and analyze_node each go through the same helper. Comparing, printing and freeing the projection tree go through it too: the projection is the record of what a template means, which the formatter compares before and after formatting. BodyProjection gets hand-written PartialEq, Debug and Drop that give the same results as the generated ones. The parser already uses this pattern for its own Template.
  4. The native render path's gap is documented in crates/citry_core_py/src/native_render/mod.rs. Its entry points read and create Python objects as they go. CPython 3.14 checks the stack pointer against the thread's own stack, so that work cannot move to a heap segment, and the module can only keep its own stack use small.

Prior art

  • crates/citry_template_parser/src/stack.rs: with_enough_stack (100 KiB check, 1 MiB segment) and with_stack_for_expression. The parser's passes and Template's Clone, PartialEq, Debug and Drop (ast.rs) already used them, but nothing ran them before the first frames of an entry point.
  • crates/citry_template_formatter/src/python.rs: the formatter's own helper (4 MiB check, 8 MiB segment) around Ruff's formatter, for one expression at a time. It does not cover the walks over elements.
  • crates/python_safe_eval/src/stack.rs: safe_eval already starts its whole body inside this crate's guard (lib.rs), so its entry point needs nothing more.
  • crates/citry_html_transform/src/stack.rs: guards the walks in hydration_structure and static_html, but not the first frames of an entry point.
  • crates/citry_vue_compiler/src/stack.rs (fix: compile and server-render deep Vue templates on any thread #400): the Vue compiler and server renderer start their work inside their own helpers, so their entry points were already covered.
  • fix: raise SyntaxError for deeply nested expressions instead of crashing #337 made deeply nested expressions a SyntaxError, and fix: write deep data for the browser with a bounded number of frames #391 writes deep data for the browser with a bounded number of frames. Neither covered the entry points.

Entry points

Every #[pyfunction] and #[pymethods] entry in crates/citry_core_py and crates/citry_template_parser that takes nested input, and what this PR does with it:

Module Entry points Change
template_parser parse_template, compile_template, _compile_prepared_template, analyze_browser_binding_pattern, analyze_component_scope_writes, analyze_component_source Guarded
template_parser analyze_browser_source Guarded, skipped on wasm32
template_formatter format_template, prepare_embedded_format, finish_embedded_format Guarded
html_transform browser_fragment_matches_elements, browser_fragment_matches_nodes, static_html_node_count, validate_html_fragment_boundary, scan_output_html, mark_html, transform_html, check_output_html Guarded, skipped on wasm32
i18n TextCatalog(), CatalogCompiler.compile, .compile_link_unit, .analyze_source, .clear Guarded
i18n TextCatalog.format, and on the compiled catalog format, resolve_json, _resolve, resolve_rich_json, browser_artifact_json, browser_parser_artifact_json Guarded, skipped on wasm32
safe_eval safe_eval Left as is: guarded inside python_safe_eval
vue compile_vue, read_server_render_program, render_for_hydration Left as is: the Vue crate starts each of them inside its own helper (#400), and frees a program through one
native_render leaf_values_json, encode_occurrences and the methods in rows.rs, runs.rs, walk.rs, leaf_json.rs Left out: they call Python as they go (see above). Filed as #422
AST classes (ast.rs, error.rs) getters, __eq__, __repr__ Left as is: the deep part of each goes through Template's own guarded implementations

Entry points whose input does not nest do no deep work, so they are left as is. These are:

  • script_type_is_executable, classify_dependency_attribute, is_javascript_url
  • canonicalize_locale, locale_direction, python_expression_provider
  • the compiled catalog's number, percent, currency, date, time, relative-time, list and unit formatting methods, and its parse_*_json methods
  • TextCatalog.origin and .entries, and the compiled catalog's getters and artifact_json
  • CatalogCompiler(), fully_supported, the plan getters
  • the constructors of the AST classes, ForeignSpan, ParseOptions and TagRules, and the __repr__ methods in browser.rs

Recursive types

As part of the same sweep, I searched every crate for types that contain themselves, directly or through other types. The drop code Rust generates, and the derived Clone, PartialEq and Debug, call themselves once per level:

  • Formatter projections (DocumentProjection, BodyProjection, NodeProjection and the attribute types that hold a nested document): fixed in this PR. The Clone derive on them is removed because nothing clones them.
  • Parser AST (Template, Node, TemplateElement, HtmlAttr and the rest): already handled. Each level passes through Template, which has guarded implementations.
  • Vue compiler (Node, Expr, Val, JsNode and others): already handled in fix: compile and server-render deep Vue templates on any thread #400. Reading and writing stop at MAX_READ_DEPTH and MAX_DEPTH and run through guards, and a program is freed through a guard.
  • Native render (Plan, Op, Expr, ReadNode, Value, Step, WalkPlan, and PyReadNode in citry_core_py): left out, see The native render path overflows a small thread's stack on a template with 100 nested loops #422.
  • Fluent syntax trees in citry_i18n: they nest through placeables and select expressions. Compiling, resolving and clear() now run inside the guard. Freeing a whole compiled catalog when Python drops it is not guarded. That would need a hand-written Drop in citry_i18n, and I have not measured whether real catalogs nest deep enough to matter. Unproven.
  • Language specs (LangSpecArgument, LangSpecStruct): left as is. They are written in Rust code and only a few levels deep.
  • citry_html_transform's State and Answers, and python_safe_eval's SandboxTransformer: false matches. They refer to other values by index or hold flat collections.

Tests

  • packages/py/citry_core/tests/test_stack_guards.py runs each check in its own interpreter on a 512 KiB thread. It nests C-level calls until CPython refuses one, then backs off four levels at a time and calls the entry point at each depth. The test also checks that a call within 40 levels of CPython's limit returned, so at least one call really started with less stack than the guard's 100 KiB. There are three cases:

    • parse and compile a 400-level template;
    • format 400 nested elements;
    • run the output check on 400 nested elements.

    With a debug extension, which is what maturin develop and CI build, all three crash on main (exit -10) and pass with this change. With a release extension, only the format case crashes on main. The three cases take about 45 seconds together with a debug build.

  • crates/citry_template_formatter/tests/deep_elements.rs formats 1,000 nested <div> elements and a chain of 250 <c-if> tags on a 256 KiB thread. It takes about 5 seconds in a debug build. Removing the guard from visit_node, project_node or analyze_node, one at a time, makes it overflow. The comparison guard was proven by a temporary probe, which overflowed in the comparison before the guard was added. The Debug guard runs only when the two projections differ, so no test reaches it, and the Drop guard was not tested on its own.

  • Unproven: the 100 KiB check is enough for code that has no guards of its own, such as OXC (the analyze_* functions), fluent-syntax and html5ever. When the check does not fire, the whole call must fit in the stack that is left. Only _check_output_html is tested among those.

  • Not checked locally: the wasm32 build. The wrapper is a two-branch cfg, and the Pyodide wheel builds in the publish workflow.

Does the original crash still happen?

Not for the case this PR covers. With the native render path off, I reran the original crash on the 512 KiB thread with 400, 500, and 560 to 700 frames already in use, 10 to 20 frames apart. Each run now ends with a Python MemoryError or RecursionError from CPython's own limits, and none crashes.

With the native render path on, the same template still crashes even with no frames used. The cause is the native path's own stack use, which is #422. That is a separate problem with its own design choices, so this PR leaves it out.

Speed

The guard adds one stack-pointer check per call on native targets. Both sides below used release extensions and the same Python code, alternating fresh processes, with a 1-minute load of 2.2 to 2.9:

Measurement main This PR Change
lg render, native path on, minimum CPU of 15 runs 64.11 ms 64.83 ms +1.1% (median +0.5%)
lg render, native path off, minimum CPU of 15 runs 65.73 ms 65.76 ms +0.0% (median +0.2%)
benchmarks/i18n.py added median, 5 runs 0.364 to 0.377 ms 0.364 to 0.376 ms none

All of these are within the 2% budget for code that runs on every render.

Not in this PR

🤖 Generated with Claude Code

CPython lets a call into an extension through with only about 20 KiB of
the thread's stack left, which is less than the template parser needs
before its first internal guard in a debug build. Each entry point Python
calls that does deep work now runs its Rust work through the template
parser's existing `with_enough_stack`, which runs that work on a stack
segment taken from the heap when little stack is left. Entry points that
run on every render use a variant that skips the guard on wasm32, where
stacker cannot measure the stack and would allocate on every call.

The formatter's walks over nested elements also called themselves once
per level with no guard, and so did comparing and freeing its projection
trees (the record of what a template means, which it compares before and
after formatting). In a debug build they overflowed even a fresh 4 MiB
thread at a few hundred levels. They now check the stack at every level.

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