Skip to content

fix(native-render): leave templates nested past a depth limit to Python - #499

Merged
JuroOravec merged 1 commit into
mainfrom
fix/native-render-depth-limit
Oct 28, 2026
Merged

JuroOravec merged 1 commit into
mainfrom
fix/native-render-depth-limit

Conversation

@JuroOravec

Copy link
Copy Markdown
Member

Fixes #422 with option A of the design note: Rust leaves a simple='vue' template nested past fixed depth limits to Python's evaluator. Options B and C are parked in #496.

What happens now

The native render path builds a plan for a simple='vue' template, then evaluates it and writes each row's data, with code that calls itself once per nesting level. The PyO3 code that reads Python's description of the plan, and copies and rebuilds a row's values, does the same. That work reads Python objects, so it cannot move to a stack taken from the heap. A template nested deeply enough crashed the process on a thread with a small stack.

Rust now refuses a template past either of two limits:

  • Body depth counts the template's top level as 1, then adds one for each c-if branch or c-for body around an operation, one for the operation's expression, and one for each conditional expression inside it. {{ n }} inside six nested loops is level 8.
  • Read depth counts a path's variable plus each subscript of it and each loop over it.

The refusal is a ValueError starting with too_deep:. native_row_plan caches it as "no plan", and the first render that meets it logs one debug message on the citry logger that names the component and says how the levels count. Every row then renders through Python's evaluator, with the same output.

Build Body depth Read depth
release (uv sync, CI, the published wheels) 64 64
debug (maturin develop) 8 16

The two builds differ because debug stack frames are several times larger. citry_core._rust.NATIVE_RENDER_MAX_BODY_DEPTH and NATIVE_RENDER_MAX_READ_DEPTH report the active limits, beside BUILD_PROFILE, so tests read them instead of copying them.

How the limits were chosen

I rendered each shape on a fresh thread, with its row plan built on that thread for the first time, which is the deepest the work goes. The shapes were nested loops, nested c-ifs, nested conditional expressions and one deep read path. A throwaway script bisects for the first depth that crashes. I ran it on this branch's final code with the limits lifted, on macOS arm64 and Python 3.14:

Build, thread Loops c-if Conditional expressions Read path
release, 128 KiB 139 OK, crash at 140 139 OK, crash at 140 27 OK (the most the parser accepts) 96 OK (the most subscripts the parser accepts)
debug, 96 KiB (128 KiB with 32 KiB held back) 7 OK, crash at 8 7 OK, crash at 8 15 OK, crash at 16 18 OK, crash at 19

The reviewer also tried shapes that mix loops, c-if chains with c-elif and c-else, a root c-bind, conditional attributes and a deep path inside loops, on a debug build. None used more stack per level than plain loops or c-if.

  • Release limits are about half the crash depth. The CI probe renders at the limit on a full 128 KiB thread, so it fails only if Linux x86_64 frames are more than about twice as large.
  • Debug limits, with 32 KiB held back, are one level below the crash depth for bodies and three below for read paths.
  • A plan already built on another thread renders much deeper: a debug build reached 32 loops on a 96 KiB thread.
  • Stack per level: in a debug build, reading Python's plan description is the most expensive step, at about 11 KiB per level. In a release build it is about 1 KiB.

I tried splitting lower_ops and Builder::ops into one function per case:

  • A debug build then took about 8 KiB per level instead of 11.
  • A release build reached about 30% fewer levels (98 instead of 139).

So both stay as single functions. The error is built in a #[cold] function, so a level does not keep space for it. With that, a release build reaches 139 levels, against main's 142.

Decisions

Juro chose option A. The open questions were settled as follows:

  1. Which build sets the limits: each build profile has its own, chosen by cfg!(debug_assertions). The first plan was to take the limits from debug builds, "so CI keeps them current". It turned out CI tests a release build: uv sync builds through maturin's PEP 517 backend, which uses Cargo's release profile. So each build got its own limit. This PR also corrects the sentence in docs/codebase.md that said uv sync builds a debug extension.
  2. The regression: accepted. A template past the limit renders through Python on every thread.
  3. Visibility: one debug log message per template, naming the component. It can appear twice if two threads build the plan at the same moment.
  4. Targets CI never runs: no Alpine cell. I did not run the one-off check: no container runtime was running here, and the disk was too full to build in one. Only macOS arm64 with Python 3.14 was measured, and CI renders at the release limit on Linux x86_64 with Python 3.14. Windows, macOS x86_64, musl, aarch64 Linux, s390x, ppc64le, armv7 and x86 are unproven, and so are Python 3.11 to 3.13 and 3.15. A release limit at half the measured depth leaves room for frames up to about twice as large. arm64 kernels with 64 KiB pages, whose larger guard page leaves less usable stack, are out of scope.
  5. Drops: the note planned list-based drops for the plan, value and PyReadNode types. They stay derived. The limits bound how deep they go, and they hold far fewer locals than the walks that were measured, but their stack per level was not measured on its own.
  6. Subprocess tests: they run in one Linux CI cell (Ubuntu, Python 3.14), gated by CITRY_NATIVE_DEPTH_PROBES=1. A local run always runs them, so a maturin develop run checks the debug limits too.

Prior art

These are what I read; line numbers are from 73e94cb77:

  • Plan::new, Builder::ops, Builder::expr and plan_read_node in crates/citry_native_render/src/plan.rs. Evaluator::ops, expr and truth, and write_record/write_entry, in eval.rs. These are the pure-Rust walks; none counted depth.
  • lower_ops, lower_expr, lower_read_node, PyReadNode::new, read_value and snapshot_value in crates/citry_core_py/src/native_render/rows.rs. These are the walks that touch Python.
  • crates/citry_core_py/src/native_render/mod.rs:13-19, which records why level A has no stack guard.
  • The leaf JSON writer's own too_deep decline at depth 200 (leaf_json.rs), and how its test reads the limit from Rust. This PR follows both patterns.
  • native_row_plan in citry/_vue/leaf_program.py:2527-2558, which caches a ValueError as "no plan" and lets any other error propagate.
  • crates/citry_template_parser/src/stack.rs and packages/py/citry_core/tests/test_stack_guards.py. These are the guarded walks and the existing subprocess stack tests.
  • feat: limit templates to 512 nested tags and 256 logic levels #470, which limits templates to 512 nested tags and 256 logic levels. That is well above these limits, so the parser does not prevent the crash on its own.

Alternatives

What would show this is wrong

  • A shipped target crashes below its limit on a 128 KiB thread. Its frames would then be more than twice the macOS release build's.
  • Real templates often nest past 8 levels in a debug build, or past 64 in a release build.
  • The CI probe cell fails at the limit, which would mean Linux x86_64 frames are larger than these measurements allow.

Error modes

  • Within the limits: the native path runs, as it does for any template.
  • Past them: Python's evaluator renders every row of the template, and _NativeRun is skipped. The output is the same, with one debug log line per template.
  • A render that starts on a stack already mostly used: not covered, as before. Python's own evaluator can run out there too.
  • Compiling a template on a small thread: Python's compiler fails from about 10 nested loops on a 128 KiB thread ("Parser stack overflowed"), with or without this change.
  • Drops: the derived Drop, Clone and PartialEq of the plan and value types call themselves once per level too. The limits bound them; their stack per level was not measured on its own.

Cross-binding audit (Mechanism 4)

  • Pure Rust: citry_native_render gains MAX_BODY_DEPTH, MAX_READ_DEPTH, too_deep, BODIES and READ_PATHS, plus tests/depth_limits.rs.
  • PyO3: citry_core_py/src/native_render/rows.rs counts depth while it reads the description. citry_core_py/src/lib.rs adds two read-only module constants, NATIVE_RENDER_MAX_BODY_DEPTH and NATIVE_RENDER_MAX_READ_DEPTH. This is the only change to what Python sees; _RowPlan's arguments and behavior within the limits are unchanged.
  • _rust.pyi: declares both constants.
  • Python wrapper: citry/_vue/leaf_program.py records a depth refusal, and citry/component_render.py logs it once with the component's name.
  • src/lang/*.rs: not involved. The native render path has no per-language implementation.
  • Tests: crates/citry_native_render/tests/depth_limits.rs, packages/py/citry/tests/test_native_render_depth.py, and packages/py/citry_core/tests/test_build_profile.py.

Tests

  • Rust: each shape (loops, c-if, conditionals, path, loops with a path) plans at its limit and is refused one past it, and a plan at the limit writes its row. These pass on both the debug and the release profile.

  • Python, every cell:

    • _RowPlan accepts each shape at the limit and refuses it one past with too_deep, including loops with a subscripted path inside, where loop items and subscripts both count toward the read limit.
    • A template at the limit renders natively, and one past it renders in Python with the same output (render_both).
    • The debug message appears once over two renders and names the component.
    • The constants are ints of at least 2.
  • Python, one Linux cell (or any local run): these render on a fresh 128 KiB thread in a separate interpreter, with the plan built on that thread:

    Both outputs rebuild the Rust-read row with NativeRow.snapshot(), and the thread collects garbage afterwards. Each case takes about 0.2 to 0.5 s.

  • Run locally:

    • cargo test -p citry_native_render, in both debug and release;
    • cargo clippy --no-deps -p citry_native_render -p citry_core_py --all-targets -- -D warnings;
    • cargo fmt --check;
    • the new tests and the native render suites (rows, runs, walk, leaf JSON, build guard), on both a debug and a release build;
    • the new tests with --python-render-path;
    • ruff, and mypy (also with --platform linux) on leaf_program.py.

🤖 Generated with Claude Code

The native render path builds a plan for a simple='vue' template, then
evaluates it and writes each row's data, with code that calls itself once
per nesting level. That work reads Python objects, so it cannot move to a
stack taken from the heap. A template nested deeply enough crashed the
process on a thread with a small stack, such as musl's 128 KiB default.

Rust now refuses a template past two limits: one for the c-if and c-for
bodies around an operation plus the conditional expressions inside it,
and one for the paths it reads. The refusal is a ValueError starting with
"too_deep:", which Python caches as "no plan". The first render that meets
it logs one debug message naming the component, and every row then
renders through Python's evaluator with the same output. A debug build's
frames are several times larger, so each build profile has its own
limits (64 and 64 in a release build, 8 and 16 in a debug build), and
_rust.NATIVE_RENDER_MAX_BODY_DEPTH and _rust.NATIVE_RENDER_MAX_READ_DEPTH
report the active ones.

Tests check the refusal at each limit, the output on both sides, the log
message, and rendering at and past the limits on a fresh 128 KiB thread in
a separate interpreter. CI runs those in the Linux 3.14 cell only. The
note in docs/codebase.md now says that uv sync builds a release extension.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@JuroOravec
JuroOravec merged commit 5eb9a4c into main Oct 28, 2026
1 of 34 checks passed
@JuroOravec
JuroOravec deleted the fix/native-render-depth-limit branch October 28, 2026 16:37
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.

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

1 participant