Skip to content

template: a chat template is held to a nesting depth, and its render to steps, stack and memory - #3072

Merged
ashhart merged 3 commits into
mainfrom
security/template-limits
Nov 13, 2026
Merged

ashhart merged 3 commits into
mainfrom
security/template-limits

Conversation

@ashhart

@ashhart ashhart commented Nov 12, 2026

Copy link
Copy Markdown
Owner

What this changes

Before: a checkpoint's chat template had no limit. 100,000 nested parentheses ran the parser off its stack, a sum of 100,000 terms built a tree that tall for the scope pass and the renderer, two nested loops over range(100000) never finished, '' * 10**18 counted to its end, and a macro that calls itself inside a filter chain overflowed the stack before the macro limit. After: the parser refuses more than 256 levels of its own recursion and any expression taller than that, a render stops by name past 50 million steps, 4 MiB of stack or 1 GiB of scratch, and an empty sequence repeated is empty at once.

  • Issue: n/a. SECURITY.md asks for private reports, so there is no public issue.
  • Stacked on: main.
  • atc overlap --json: not run.

Checks on this head

  • Head commit: d8816683591d87798ada0da36506d9d1cf22cf6f
  • Lean checker, python3 tools/zig/lean_check.py, on the base and on this head: 345 on the base, 345 on this head, 0 new.
  • Tests run, with the command and pass, fail and skip counts:
    • zig fmt --check and git diff --check: pass
    • zig test --dep sys -Mroot=zig/src/core/template/template.zig -Msys=zig/src/platform/sys.zig -lc: all 38 tests passed, and again with -OReleaseFast
    • zig build test-server-cpu: 5/5 steps succeeded; 1325/1332 tests passed (7 skipped)
    • zig build test-cuda-host: 391/391 steps succeeded; 4254/4289 tests passed (35 skipped)
    • zig build test-golden test-server-security test-pull-security: 76/76 steps succeeded
    • zig build check-native-cuda-host compile-flashnext-mtp-parity-host compile-glm-native-open: 11/11 steps succeeded
    • zig build native: 66/66 steps succeeded
  • New tests:
    • security: a template nested past the parser's depth is refused before anything recurses through it
    • security: a render stops at its steps, its recursion and its memory, and says which
  • CI: runs on this push.
  • Not run, and why: Prompt speed was not measured: each statement list and expression now counts a step and checks the stack. zig build test and every step that runs on a GPU were not run: this Mac's GPU was serving a model, and no CUDA, ROCm or Intel hardware was available.

Receipt

  • Main against branch: could not be run. It needs a served checkpoint.
  • Boxes it reaches: prompt rendering on every backend.
  • New switch? Default, accepted values, profile row: none.
  • Environment, with the TensorFold commit, Zig and backend toolchain, machine and GPU, checkpoint and revision: this head on Zig 0.17.0, on an Apple silicon Mac, CPU-only steps. No GPU and no checkpoint was used.
  • Paths and platforms the change reaches, which I ran and which I could not: the template module's tests in debug and release builds, and the server's CPU suite, on macOS.
  • Exactness: not measured. A template inside the limits renders as on main: the existing template tests and the server's suites pass unchanged.
  • Main against this branch, same machine and checkpoint: not run, for the reason above.
  • Decode speed before and after: not measured.
  • Prompt speed before and after: not measured.
  • Licence of any new weights or drafter: n/a.

Checklist

  • The title and description match the head commit, including the receipt and the stack.
  • New tests fail before the change, pass after it, and skip cleanly without their dependency. On main the same inputs were run against the unchanged engine: the nested parentheses, the long sum and the nested macro call each ended in a segmentation fault, and the nested loops and the empty repeat were still running when killed after 25 seconds.
  • Comments and docstrings are one line. No measurements or history in the source.
  • No personal data, machine names, internal hosts or local paths in the diff or its commits. No AI attribution lines.

For a change that reaches inference:

  • Every token still goes through the lane rounds. No serial path, and nothing that needs drafts off.
  • Drafted output equals "draft": false, a resumed prompt equals a fresh one, and concurrent equals solo. Not measured: no served run.
  • No precision traded for speed.
  • Decode and prompt processing are no slower than main. Not measured: no served run.

Notes for the reviewer

  • The stack is measured from where the render began, not counted in levels: frames differ too much in size between expression kinds for a count to bound it. In a debug build, where frames are large, a macro that calls itself 400 deep may stop at the stack limit with that message, where a release build reaches the macro limit first.
  • A step is one statement list or one expression. A builtin over a long sequence is one step, so the step limit bounds a render together with the memory limit, which bounds how long a sequence can be.
  • The limits are fields of the compiled template, which is how the tests lower them. The four numbers are judgment calls.
  • The 1 GiB limit refuses a template that builds its whole output by repeated concatenation on a very long conversation. None of the templates in the test suites does.

Suggested changelog line

Chat templates: a template nested too deeply is refused at load, and a render stops by name at 50 million steps, 4 MiB of stack or 1 GiB of memory.

@ashhart

ashhart commented Nov 12, 2026

Copy link
Copy Markdown
Owner Author

Review: the limits are right and far above real use. All 10,867 cases of the template parity corpus render byte-identically on main and here, and so do 16 real templates on agent requests of up to 1,000 turns with 128 tools. The most any real template used:

Limit Most used Allowed
Parser depth 17 256
Expression height 11 256
Steps 7.45M 50M
Scratch memory 302 MiB 1 GiB
Stack 48 KiB 4 MiB

One fix before landing: rendering is 3–9% slower on large requests, and templates re-render every turn, cache hits included. The cause is try c.enter() on every eval (eval.zig:449). With it kept only in exec (:130), the difference is within noise, and all 38 template tests pass. Three changes:

  1. Drop enter from eval.
  2. Count one step per item in the loop-filter path (eval.zig:177). {% for x in range(N) if … %} evaluates its filter without exec, so it would otherwise go uncounted. Add a test.
  3. Capped.resize/remap (template.zig:117, :122) count bytes even when the allocator fails. Give them back on failure.

We'll push these.

  • Synthena (Ash's Agent)

@ashhart

ashhart commented Nov 13, 2026

Copy link
Copy Markdown
Owner Author

Review fixes pushed (1ed0f31):

  • eval no longer calls enter; exec still does. Each item a loop filter tests counts as a step, so {% for x in range(N) if … %} can't run uncounted. The stack is checked once per statement list. Expressions nested 120–240 deep still stop cleanly at the stack or macro limit.
  • Capped.resize, remap and alloc give the bytes back when the underlying allocator refuses.
  • New step test-template-limits-host in the Linux and macOS fast host lists, so CI runs these tests.

Results:

  • Speed: with three versions interleaved, 15 timed runs each, the head was +4.8% over main. The fix is +0.3% and −0.2%, and within ±1.6% on small requests.

  • Parity: all 10,867 corpus cases are identical to main, in Debug and in ReleaseFast.

  • Tests: template module 40/40, test-template-limits-host 6/6, test-server-cpu 1325/1332 (7 skipped). Both new tests fail without the fixes.

  • Lean: 345 before and after.

  • Synthena (Ash's Agent)

@ashhart
ashhart marked this pull request as ready for review November 13, 2026 00:01
…to steps, stack and memory

A checkpoint's chat template had no limit at all. 100,000 nested parentheses ran the parser off its stack,
a sum of 100,000 terms built a tree that tall for the scope pass and the renderer, two nested loops over
range(100000) never finished, `'' * 10**18` counted to its end, and a macro that calls itself inside a
filter chain overflowed the stack before the macro limit. The parser now refuses more than 256 levels of
its own recursion and any expression taller than that. A render stops by name past 50 million steps,
4 MiB of stack or 1 GiB of scratch, and an empty sequence repeated is empty at once. The stack is
measured, not counted in levels, because frames differ too much in size between expression kinds.
… byte cap counts only what was given

Every expression took a step and a stack check, which slowed renders of large requests by a few percent. The
check now runs once a statement list, which every macro call and loop body passes through; an expression between
two checks is at most the parser's 256 levels tall. A loop's filter runs no statement list, so each item it tests
is now a step of its own, or a filtered loop inside another loop ran uncounted. The render arena asks to grow a
block in place before it takes a new one, and the cap kept the bytes of every refused request; it gives them back.
test-template-limits-host runs the limits tests on Linux and macOS.
@ashhart
ashhart force-pushed the security/template-limits branch from 1ed0f31 to 79062a9 Compare November 13, 2026 09:43
@ashhart
ashhart merged commit 0591c4e into main Nov 13, 2026
6 of 14 checks passed
@ashhart
ashhart deleted the security/template-limits branch November 13, 2026 09:44
ashhart added a commit that referenced this pull request Nov 13, 2026
Figures and scope corrected to the PRs (#2948, #2863, #2934, #2933, #2921, #2906, #2878, #2892, #2851, #2728, #3072,
#2915, #2864, #2854 and others), promises of later work removed (#2903, #2875, #1630, #1720), #3074 and #3047/#3046
said as their PRs scope them, the duplicate #2861, #2585, #2321 and #2719 entries and two copies of released 1.2.5
lines removed, #1953's line named for its PR, and a line for #3255. Released sections unchanged.
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