Repository navigation
fix: start each deep Rust entry point with a stack guard - #428
Merged
Merged
Conversation
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]>
This was referenced Oct 27, 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.
What this fixes
Python can call into
citry_corewhen 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:
parse_template.What changes
with_enough_stackhelper. 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.stackercannot 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, callswith_enough_stackon other targets and runs the work directly on wasm32. So on Pyodide these calls keep running on the current stack, as before. Thehtml_transformentry points, the i18n message lookups andanalyze_browser_sourcecall the wrapper, because several of them run on every render:mark_htmlonce per component, the output checks once per page, a message lookup once per message, andanalyze_browser_sourcefor 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.format_templatestill 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. Nowvisit_node,project_nodeandanalyze_nodeeach 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.BodyProjectiongets hand-writtenPartialEq,DebugandDropthat give the same results as the generated ones. The parser already uses this pattern for its ownTemplate.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) andwith_stack_for_expression. The parser's passes andTemplate'sClone,PartialEq,DebugandDrop(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_evalalready 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 inhydration_structureandstatic_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.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 incrates/citry_core_pyandcrates/citry_template_parserthat takes nested input, and what this PR does with it:template_parserparse_template,compile_template,_compile_prepared_template,analyze_browser_binding_pattern,analyze_component_scope_writes,analyze_component_sourcetemplate_parseranalyze_browser_sourcetemplate_formatterformat_template,prepare_embedded_format,finish_embedded_formathtml_transformbrowser_fragment_matches_elements,browser_fragment_matches_nodes,static_html_node_count,validate_html_fragment_boundary,scan_output_html,mark_html,transform_html,check_output_htmli18nTextCatalog(),CatalogCompiler.compile,.compile_link_unit,.analyze_source,.cleari18nTextCatalog.format, and on the compiled catalogformat,resolve_json,_resolve,resolve_rich_json,browser_artifact_json,browser_parser_artifact_jsonsafe_evalsafe_evalpython_safe_evalvuecompile_vue,read_server_render_program,render_for_hydrationnative_renderleaf_values_json,encode_occurrencesand the methods inrows.rs,runs.rs,walk.rs,leaf_json.rsast.rs,error.rs)__eq__,__repr__Template's own guarded implementationsEntry 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_urlcanonicalize_locale,locale_direction,python_expression_providerparse_*_jsonmethodsTextCatalog.originand.entries, and the compiled catalog's getters andartifact_jsonCatalogCompiler(),fully_supported, the plan gettersForeignSpan,ParseOptionsandTagRules, and the__repr__methods inbrowser.rsRecursive 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,PartialEqandDebug, call themselves once per level:DocumentProjection,BodyProjection,NodeProjectionand the attribute types that hold a nested document): fixed in this PR. TheClonederive on them is removed because nothing clones them.Template,Node,TemplateElement,HtmlAttrand the rest): already handled. Each level passes throughTemplate, which has guarded implementations.Node,Expr,Val,JsNodeand others): already handled in fix: compile and server-render deep Vue templates on any thread #400. Reading and writing stop atMAX_READ_DEPTHandMAX_DEPTHand run through guards, and a program is freed through a guard.Plan,Op,Expr,ReadNode,Value,Step,WalkPlan, andPyReadNodeincitry_core_py): left out, see The native render path overflows a small thread's stack on a template with 100 nested loops #422.citry_i18n: they nest through placeables and select expressions. Compiling, resolving andclear()now run inside the guard. Freeing a whole compiled catalog when Python drops it is not guarded. That would need a hand-writtenDropincitry_i18n, and I have not measured whether real catalogs nest deep enough to matter. Unproven.LangSpecArgument,LangSpecStruct): left as is. They are written in Rust code and only a few levels deep.citry_html_transform'sStateandAnswers, andpython_safe_eval'sSandboxTransformer: false matches. They refer to other values by index or hold flat collections.Tests
packages/py/citry_core/tests/test_stack_guards.pyruns 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:With a debug extension, which is what
maturin developand CI build, all three crash onmain(exit -10) and pass with this change. With a release extension, only the format case crashes onmain. The three cases take about 45 seconds together with a debug build.crates/citry_template_formatter/tests/deep_elements.rsformats 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 fromvisit_node,project_nodeoranalyze_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. TheDebugguard runs only when the two projections differ, so no test reaches it, and theDropguard 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_htmlis 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
MemoryErrororRecursionErrorfrom 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:
mainlgrender, native path on, minimum CPU of 15 runslgrender, native path off, minimum CPU of 15 runsbenchmarks/i18n.pyadded median, 5 runsAll of these are within the 2% budget for code that runs on every render.
Not in this PR
🤖 Generated with Claude Code