Skip to content

The native render path overflows a small thread's stack on a template with 100 nested loops #422

Closed

Description

@JuroOravec

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

  1. 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.
  2. 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, Clone and PartialEq implementations, like the template parser's Template. 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

  1. JuroOravec commented on Oct 25, 2026

    @JuroOravec
    MemberAuthor

    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:

    template = "".join(
        f'<div c-for="row{i} in rows">' for i in range(256)
    ) + "<div>" * 144 + "{{ n }}" + "</div>" * 144 + "</div>" * 256
    # template_data returns {"n": 7, "rows": [1]}

    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=0 it 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.

  2. JuroOravec commented on Oct 28, 2026

    @JuroOravec
    MemberAuthor

    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 separate v1.1 issue, with the questions about them.

    The open questions for option A at the end of the note were settled as follows:

    • Limits come from measuring each build profile; each build gets its own value.
    • Templates past the limit lose the native path; that regression is accepted.
    • A depth refusal is logged once per template at debug level.
    • No Alpine CI cell is added.
    • The tests that start a separate interpreter run in one Linux CI cell.

    Read against origin/main 4ec0dd175. The native path is the Rust code that
    reads a simple='vue' row's values and writes its data as JSON, without
    running the generated Python evaluator. It declines a template or row by
    handing it back to that evaluator. A stack guard (with_enough_stack) moves
    work 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-for loops, or 256 over a flat list, crashes the
    process 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 no
    nested operations (plan.rs:395-411). Three things nest: c-for and c-if
    bodies, the paths a template reads (a['b']['c']), and conditional
    expressions. check_nesting already caps expressions at about 40 to 50
    conditional levels (python_safe_eval/src/nesting.rs:48, 200 counted
    operators); read paths have no cap.

    Prior art

    • Plan once, read per row. Python describes the template's operations, and
      the values it reads (the read set), as nested tuples. Rust builds a plan
      from them once per template. native_row_plan caches a ValueError as "no
      plan"; any other error propagates, on purpose, and is not cached
      (leaf_program.py:2522-2552, comment at 2537-2539). Every row asks for the
      plan (:2564). Per-row declines use the Decline enum, whose reason Python
      never sees (rows.rs:57-90, 762-773).
    • Pure-Rust recursion (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, into c-if branches at :166 and c-for empty
      bodies at :193), and write_entry/write_record, which call each other
      (:274, :339). Also the derived drop, Clone, PartialEq and Debug of
      the plan types (plan.rs:46-212), Value (value.rs:9) and Record/Entry
      (eval.rs:34-44). Only tests clone or compare them. The run, JSON, digest and
      loop-walk modules do not recurse.
    • Recursion that touches Python (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 any
      thread (rows.rs:746-756).
    • Why no guard wraps it. Guarded work must not call Python, because
      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-19
      records the native path as unguarded.
    • Leaf JSON already avoids deep recursion. The leaf-data JSON writer calls
      itself for 8 levels, then keeps open containers on a list
      (leaf_json.rs:109-147, 340-391). It declines too_deep at depth 200 and
      above (:56, 220), and its test finds that limit by asking Rust
      (test_native_render_leaf_json.py:976-1004).
    • Other guarded recursion. Template (ast.rs:1023-1105) and
      LangSpecArgument'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 nested
      tags, 256 control flow (not landed), tested on 128 KiB threads in both
      tests/deep_nesting.rs.
    • Reading the remaining stack. stacker 0.1.25 (Cargo.toml:71, unused by
      this crate) has remaining_stack(). It reads the stack pointer against
      bounds 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 call
      reports only the part of the stack mapped so far.
    • CPython 3.14's own check (per the second review's reading of ceval.c).
      It raises RecursionError below a soft limit (base + 2 ×
      _PyOS_STACK_MARGIN_BYTES: 32 KiB, or 64 KiB on a Py_DEBUG build). It
      aborts with Py_FatalError below base + 16 KiB (32 KiB on Py_DEBUG). On
      non-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.
    • Builds and CI. Wheels use [profile.release-wheel], with LTO and
      codegen-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 macOS
      pair (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 sets CITRY_NATIVE_RENDER=0 for
      subprocesses (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":

    • body depth: the maximum, over every operation, of the bodies around it
      (each c-for body and empty body, each c-if branch) plus that operation's
      expression nesting;
    • read depth: the depth of the read set, which grows with every loop and path
      key.

    lower_*, Builder::ops, Builder::expr and plan_read_node carry the count
    and 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 and PyReadNode drops free children from a list, so a
    garbage-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, nested c-if, a deep read path, the deepest expression check_nesting
    accepts 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-wheel profile, on macOS arm64, Linux x86_64 and
    Windows, 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.

    • Within the limits: the native path runs, as today.
    • Above them: every row of the template uses the Python evaluator. Those rows
      also skip _NativeRun, the object that records a whole loop of Rust-read
      rows in one go. The output is the same, only slower, with no warning.
    • Stack already in use before the render starts, and Python's last few KiB: not
      covered. The native path can still overflow there, as it can today.
    • A user __eq__ that recurses deeply inside read_value, under every option:
      on 3.14 with glibc, macOS or Windows it raises RecursionError, and the row
      declines, or the process aborts with Py_FatalError in the last 16 KiB.
      On musl, and on 3.11 to 3.13, a crash stays possible.
    • If the limits come from release builds, debug builds can still crash within
      them on small threads.
    • A panic near the edge of the stack, with RUST_BACKTRACE set, needs much
      more 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(). It
    is 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 raises RecursionError, which Python does not
    cache, 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:

    1. musl handling. On a musl main thread (Alpine, gunicorn sync workers,
      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.
    2. A reserve defined against CPython's soft limit. The reserve is the most
      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 a
      margin. Shipped targets, toolchains and LTO change frame sizes, so it needs a
      CI check to stay current, or an accepted risk.
    3. A policy for an unknown reading (None, for example on glibc's main
      thread 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.13
    nothing 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
    RecursionError in native_row_plan widens the errors Citry swallows, which
    leaf_program.py:2537-2539 avoids 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:

    • The limit comes out so low (below about 8) that ordinary templates lose the
      native path.
    • The Python path itself fails on a 128 KiB thread above the limit, so option A
      moves the failure rather than removing it.
    • A shipped target that CI never runs (musl aarch64, s390x, ppc64le, armv7, x86)
      crashes at the limit in a one-off check. Its frames would then be larger than
      the debug build's.
    • Users report many real templates past the limit, which makes the
      regression the bigger problem.

    Tests

    Cases that could crash run in a subprocess, as
    packages/py/citry_core/tests/test_stack_guards.py does. Each subprocess sets
    CITRY_NATIVE_RENDER=1 and skips when the native path is unsupported, so the
    --python-render-path cell still passes. The tests find the limits by probing
    _RowPlan, as the leaf-JSON test does, so no constant is copied. The expected
    output comes from the Python path on the main thread. Cases, on a 128 KiB
    thread:

    • both issue reproductions, with no crash and equal output;
    • body depth at the limit (Rust reads every row, by the render_both counts)
      and one past it (Rust reads none);
    • read depth at the limit and one past it;
    • the deepest expression check_nesting accepts, at the body limit;
    • a shallow template, which must still render natively;
    • a plan first built on the small thread, NativeRow.snapshot() there, and
      dropping 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

    1. Which build sets the limits? Debug: the CI test keeps them current, but they
      are lower, so more templates regress. release-wheel: higher limits, but
      checked only by a one-off run or a new release-build CI job.
    2. Is the regression acceptable, where templates past the limit lose the native
      path on every thread until option B lands?
    3. Should depth and stack declines be visible, for example as a debug counter?
    4. Is a one-off check on targets CI never runs (Alpine/musl, aarch64 with
      64 KiB pages) enough, or should CI gain an Alpine cell? And is arm64 with
      64 KiB pages in scope?
    5. Is the subprocess test cost acceptable, at an estimated 10-20 s per CI cell?
    6. If option B goes ahead later:
      • On a musl main thread, should Citry take its own reading, or treat the
        reading as unknown?
      • Should a CI check keep the reserve current, or is a one-off measurement
        enough?
      • Should a plan build that runs short retry, or be recorded?
      • Is catching RecursionError from _RowPlan acceptable, given that it
        widens what Citry swallows?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions