Repository navigation
Description
What happens
A component whose template nests 100 <div c-for> loops, each looping over the list the loop around it gives, crashes the Python process. The crash happens when the component renders on a thread with a 512 KiB stack, with no other work using that stack first. It happens in Citry's native render path, the Rust code that renders the rows of a component's loops without calling the generated Python code for each one.
With CITRY_NATIVE_RENDER=0, Citry renders the same component through its Python path, and it works. So the native path needs more stack than a 512 KiB thread holds.
512 KiB is the default stack for a thread that a C library or a host program starts on macOS. musl Linux, for example Alpine, gives threads 128 KiB by default, including Python's own threads.
Part of #272. The nesting limits that #272 plans in stage C2 are 512 nested tags, 256 of them control flow. 100 loops is well inside those limits, so this crash happens at a depth the parser will accept.
Reproduction
import threading
from citry import Citry, Component
depth = 100
app = Citry(autodiscover=False)
names = ["rows"] + [f"r{i}" for i in range(depth)]
deep_template = "".join(
f'<div c-for="{names[i + 1]} in {names[i]}">'
for i in range(depth)
) + "{{ n }}" + "</div>" * depth
data = [1]
for _ in range(depth - 1):
data = [data]
class Deep(Component):
citry = app
template = deep_template
js = "$component({});"
def template_data(self, kwargs, slots):
return {"n": 7, "rows": data}
Deep().render().serialize() # compile on the main thread first
threading.stack_size(512 * 1024)
thread = threading.Thread(
target=lambda: Deep().render().serialize()
)
thread.start()
thread.join()Measurements
These runs used a debug build of citry_core on macOS arm64 with Python 3.14.
| Loop depth | Thread stack | Native path | Python path |
|---|---|---|---|
| 20 | 512 KiB | works | works |
| 50 | 512 KiB | works | works |
| 100 | 512 KiB | crashes (SIGBUS or SIGILL) | works |
| 100 | 8 MiB | works | works |
Unproven: whether a release build crashes at the same depth. A release build uses smaller stack frames, so its limit is likely deeper. The cost per level still grows with the depth, so a 128 KiB thread is likely to reach it within the planned limits. I have not measured this.
Why it happens
The native path's data nests once per loop level. Its compiled plan (Plan, Op, Expr, ReadNode in crates/citry_native_render/src/plan.rs) and the values it copies out of Python (Value in value.rs, PyReadNode in crates/citry_core_py/src/native_render/rows.rs) all do. The code that walks, copies, compares and frees them calls itself once per level. None of it checks how much stack is left.
The other deep Rust entry points that Python calls start with a stack check (with_enough_stack), which moves the work to a stack segment taken from the heap when the thread's own stack runs low. The native path cannot do that everywhere. Part of its work reads and creates Python objects, and CPython 3.14 checks the stack pointer against the thread's own stack, so that work must stay on the thread's stack.
Two possible fixes
- Fall back above a depth limit. When the template's loops nest deeper than a limit, use the Python path for that component, the same way the native path already declines templates it does not support. This is the smallest change. The limit needs measuring on a 128 KiB thread in a release build.
- Split the pure-Rust work from the Python reads. Run the evaluation, which is pure Rust, through the stack check, and give the plan and value types guarded
Drop,CloneandPartialEqimplementations, like the template parser'sTemplate. Then make the step that reads from Python keep its own list of levels still to visit, in place of one call per level, so it needs only a fixed amount of the thread's stack. This keeps deep templates on the fast path, but it is a larger change.
Activity
JuroOravec commentedon Oct 25, 2026
The data does not have to nest for this to happen. A template with 256 nested loops over the same one-item list crashes the same way:
That component crashes in a debug build on a fresh 512 KiB thread, with no other stack in use, when the native path is on. With
CITRY_NATIVE_RENDER=0it renders. So the plan's own nesting is enough to cause the crash, and the values copied out of Python do not have to nest at all.JuroOravec commentedon Oct 28, 2026
This is the design note for this issue, written against
4ec0dd175. Juro chose option A, and its PR follows from this note. Options B and C are parked for after 0.7.0 in a separatev1.1issue, with the questions about them.The open questions for option A at the end of the note were settled as follows:
Read against origin/main
4ec0dd175. The native path is the Rust code thatreads a
simple='vue'row's values and writes its data as JSON, withoutrunning the generated Python evaluator. It declines a template or row by
handing it back to that evaluator. A stack guard (
with_enough_stack) moveswork to a 1 MiB heap stack when the thread's own stack runs low. PyPy, Pyodide
and free-threaded CPython never use the native path (
native_render.py:110).What goes wrong
A row that nests 100
c-forloops, or 256 over a flat list, crashes theprocess on a new 512 KiB thread in a debug build. The native path calls itself
once per nesting level, and nothing checks how much stack is left. Plain
<div>nesting adds no recursion, because an element's operation holds nonested operations (
plan.rs:395-411). Three things nest:c-forandc-ifbodies, the paths a template reads (
a['b']['c']), and conditionalexpressions.
check_nestingalready caps expressions at about 40 to 50conditional levels (
python_safe_eval/src/nesting.rs:48, 200 countedoperators); read paths have no cap.
Prior art
the values it reads (the read set), as nested tuples. Rust builds a plan
from them once per template.
native_row_plancaches aValueErroras "noplan"; any other error propagates, on purpose, and is not cached
(
leaf_program.py:2522-2552, comment at2537-2539). Every row asks for theplan (
:2564). Per-row declines use theDeclineenum, whose reason Pythonnever sees (
rows.rs:57-90,762-773).citry_native_render/src):plan_read_node(
plan.rs:282),Builder::expr(:337),Builder::ops(:378),assign_ranks(:495);Evaluator::truth/expr(eval.rs:83,94),Evaluator::ops(:108, intoc-ifbranches at:166andc-foremptybodies at
:193), andwrite_entry/write_record, which call each other(
:274,:339). Also the derived drop,Clone,PartialEqandDebugofthe plan types (
plan.rs:46-212),Value(value.rs:9) andRecord/Entry(
eval.rs:34-44). Only tests clone or compare them. The run, JSON, digest andloop-walk modules do not recurse.
citry_core_py/src/native_render/rows.rs):lower_expr(:114),lower_ops(:149),lower_read_node(:202),PyReadNode::new(:238),read_value(:438),snapshot_value(:789),and dropping
PyReadNode. The cyclic garbage collector can free a plan on anythread (
rows.rs:746-756).CPython 3.14 checks the stack pointer against the thread's own stack
(
citry_template_parser/src/stack.rs:45-46).native_render/mod.rs:13-19records the native path as unguarded.
itself for 8 levels, then keeps open containers on a list
(
leaf_json.rs:109-147,340-391). It declinestoo_deepat depth 200 andabove (
:56,220), and its test finds that limit by asking Rust(
test_native_render_leaf_json.py:976-1004).Template(ast.rs:1023-1105) andLangSpecArgument's list-based drop (lang.rs:201-228). 50 nested<c-if>blocks fail with "too many nested parentheses", and about 1,000 crash the process #272 plans 512 nestedtags, 256 control flow (not landed), tested on 128 KiB threads in both
tests/deep_nesting.rs.Cargo.toml:71, unused bythis crate) has
remaining_stack(). It reads the stack pointer againstbounds it caches per thread on first use. On Linux those bounds come from
pthread_getattr_np(backends/unix.rs). On musl's main thread, that callreports only the part of the stack mapped so far.
ceval.c).It raises
RecursionErrorbelow a soft limit (base + 2 ×_PyOS_STACK_MARGIN_BYTES: 32 KiB, or 64 KiB on aPy_DEBUGbuild). Itaborts with
Py_FatalErrorbelow base + 16 KiB (32 KiB onPy_DEBUG). Onnon-glibc Linux it assumes a 4 MB stack, so it never fires on a small musl
thread. Its base and stacker's bottom differ by a guard page on glibc (4 KiB,
or 64 KiB on arm64 kernels with 64 KiB pages) and by 8 to 12 KiB on Windows.
[profile.release-wheel], with LTO andcodegen-units = 1(Cargo.toml:187-191). CI tests a debug build(
uv sync) on Ubuntu x86_64 and Windows, Python 3.11 to 3.15, plus a macOSpair (
py--tests.yml:149-156). No CI cell runs musl, aarch64 Linux, s390x,ppc64le, armv7 or x86, all of which ship wheels. The Ubuntu 3.11 cell runs
with
--python-render-path, which also setsCITRY_NATIVE_RENDER=0forsubprocesses (
py--tests.yml:204,tests/conftest.py:41-47).Option A: decline above a fixed depth limit
Rust checks two counts while it builds the plan, and refuses with
PlanError("too_deep: ..."), which Python caches as "no plan":(each
c-forbody and empty body, eachc-ifbranch) plus that operation'sexpression nesting;
key.
lower_*,Builder::ops,Builder::exprandplan_read_nodecarry the countand stop at the limit, so even the reads of Python's tuples stay bounded.
Copied values nest no deeper than the read set, and output records nest once per
c-for. The plan, value andPyReadNodedrops free children from a list, so agarbage-collector run on a small thread stays shallow.
Choosing the limits. A throwaway script bisects for the first crashing depth
of each shape on fresh threads of 128 KiB and 256 KiB. The shapes are nested
c-for, nestedc-if, a deep read path, the deepest expressioncheck_nestingaccepts in the innermost loop, and the plan build itself. The two crash depths
give the bytes per level and the fixed cost. Each limit is the result of
dividing (128 KiB minus the fixed cost minus a stated 32 KiB margin) by the
bytes per level, taking the smallest result across shapes. It runs on debug and
on the shipped
release-wheelprofile, on macOS arm64, Linux x86_64 andWindows, with Python 3.11 and 3.14. A 128 KiB thread on glibc stands in for a
new musl thread, which has that size by default.
Error modes.
also skip
_NativeRun, the object that records a whole loop of Rust-readrows in one go. The output is the same, only slower, with no warning.
covered. The native path can still overflow there, as it can today.
__eq__that recurses deeply insideread_value, under every option:on 3.14 with glibc, macOS or Windows it raises
RecursionError, and the rowdeclines, or the process aborts with
Py_FatalErrorin the last 16 KiB.On musl, and on 3.11 to 3.13, a crash stays possible.
them on small threads.
RUST_BACKTRACEset, needs muchmore stack and can overflow. Accepted.
Cost. About 80-120 Rust lines, including the list-based drops, and no PyO3
change. The regression: templates deeper than the limit lose the native path on
every thread, including an 8 MiB main thread, though they work natively there
today. A debug-based limit could be as low as 8 to 25. There is no data on how
often real templates go that deep. Whatever the limit, it depends on frame sizes
and can go stale on targets CI never runs. A debug-based limit is checked on
every CI run by the test at the limit (below), because debug frames are larger.
Option B: check the remaining stack at run time
Before each step that goes one level deeper, Rust calls
remaining_stack(). Itis pure Rust and calls no Python; the call itself is a thread-local read plus a
psm assembly call, a few nanoseconds. The reserve is the least stack Rust
must leave free. When less than that is left, a row declines with a new
Decline::StackLow. A plan build raisesRecursionError, which Python does notcache, so the next row tries to build it again. Snapshot and the drops become
loops over a list. The second review shows that B needs three things before it
is safe:
uvicorn's event loop) the reading is far too low, so every row would decline
silently. Citry needs its own reading there, or must treat it as unknown.
CI has no musl cell to catch a mistake. The existing guards probably misread
the same way: they would move to a heap stack on every call, which is slower
but cannot crash.
stack Rust uses between two checks, measured once for each recursive
function on a debug build. On top of that it adds 2 ×
_PyOS_STACK_MARGIN_BYTES,the guard size from
pthread_attr_getguardsize, room for a panic, and amargin. Shipped targets, toolchains and LTO change frame sizes, so it needs a
CI check to stay current, or an accepted risk.
None, for example on glibc's mainthread without
/proc). It should use option A's conservative limit.So B includes option A, plus platform-specific readings on top. What it adds
is native rendering above A's limit when enough stack is left. It still does
not protect a render that starts low on stack: after a decline, the Python path
runs on the same low stack and may raise
RecursionError, and on 3.11 to 3.13nothing checks at all. A failed plan build costs one retry per row unless it is
recorded, for example with the stack reading at that moment. Catching
RecursionErrorinnative_row_planwidens the errors Citry swallows, whichleaf_program.py:2537-2539avoids on purpose.Option C: split the pure-Rust work from the Python reads
As in the issue: guard the pure-Rust work and rewrite the four Python-reading
recursions as loops in exactly the current order. Deep templates stay native on
small threads, but stack already in use is not covered, read depth still needs a
limit, and the guards inherit the musl reading problem. About 400-600 lines,
medium-to-high risk.
Recommendation
Option A first, with conservative limits. It is deterministic: it reads no
platform-specific stack values, so musl, unknown readings and CPython's margins
cannot make it decline every row or crash. It removes the crash for the
templates in the issue on a fresh 128 KiB thread. Its cost is that templates
deeper than the limit become slower everywhere.
Later, add option B only above A's limit, and only where the reading is
trusted. A wrong reading can then cost only templates past the limit, never the
shallow ones. Do this when someone reports a deep template that lost the native
path, and after the musl and reserve questions below are settled. Option C
stays the last resort.
These results would show the recommendation is wrong:
native path.
moves the failure rather than removing it.
crashes at the limit in a one-off check. Its frames would then be larger than
the debug build's.
regression the bigger problem.
Tests
Cases that could crash run in a subprocess, as
packages/py/citry_core/tests/test_stack_guards.pydoes. Each subprocess setsCITRY_NATIVE_RENDER=1and skips when the native path is unsupported, so the--python-render-pathcell still passes. The tests find the limits by probing_RowPlan, as the leaf-JSON test does, so no constant is copied. The expectedoutput comes from the Python path on the main thread. Cases, on a 128 KiB
thread:
render_bothcounts)and one past it (Rust reads none);
check_nestingaccepts, at the body limit;NativeRow.snapshot()there, anddropping rows and plans with
gc.collect()inside the thread.Rust unit tests of the refusal and drops take milliseconds. Each Python
subprocess costs an interpreter start plus a debug compile: guessed at 1-2 s, or
10-20 s per CI cell in the ordinary pytest phase, with cases that share a
template sharing a subprocess. The limit measurement is one-off.
Open questions for Juro
are lower, so more templates regress.
release-wheel: higher limits, butchecked only by a one-off run or a new release-build CI job.
path on every thread until option B lands?
64 KiB pages) enough, or should CI gain an Alpine cell? And is arm64 with
64 KiB pages in scope?
reading as unknown?
enough?
RecursionErrorfrom_RowPlanacceptable, given that itwidens what Citry swallows?