Skip to content

perf: walk a loop of simple="vue" rows in Rust when it reads only plain paths (native render, level C2) - #268

Merged
JuroOravec merged 3 commits into
mainfrom
perf/native-render-walk
Oct 23, 2026
Merged

JuroOravec merged 3 commits into
mainfrom
perf/native-render-walk

Conversation

@JuroOravec

@JuroOravec JuroOravec commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

What this changes

Level C1 (#267) records a <c-for> loop's simple = "vue" rows in one _DeferredRun, which one render-queue task renders. The loop itself still runs in Python: for each row, Python's walk (ForNode._render_call_run) copies the template's variables, evaluates each input with the sandboxed evaluator, looks the class up with the registry's get, evaluates the key and builds the call metadata.

With this PR, when the loop's iterable, the call's inputs and its #c-key are plain paths (a name and constant subscripts, as in <c-Row c-for="row in phase['outputs']" #c-key="row['id']" c-row="row" />), Rust does that walk:

  1. The plan, once per loop node. ForNode._build_walk_plan turns the loop clause, the key and each input into paths (citry/_vue/native_walk.py) and builds a _CallRunWalkPlan. Each expression is turned into a path twice, from Python's own parse of the text and from the Python code the expression sandbox generated for it, and the loop gets no plan unless both agree. The sandbox reads a lone surrogate escape such as '\ud800' as U+FFFD while Python's parser keeps it, so the two evaluators would otherwise read different keys.
  2. Checks before Rust runs. ForNode._walk_call_run leaves the loop to Python when tracing is on or when the variables are not exactly Citry's _ConstMapping. It then checks, as Python's walk does, that the loop variable's name is not already in scope, and leaves the loop to Python when an input reads a scope name marked constant or when the engine's get is not Citry.get.
  3. Pass 1, the reads. Rust reads the iterable, then each row's inputs in attribute order and its key, checking exact types at every step (an exact dict, list or tuple; a key that is an exact str or an int within i64). It follows a list's current length before every item, as Python's list iterator does, and keeps the objects it read, never copies.
  4. Pass 2, the rows. Only when every read succeeded, Rust calls get for each row, checks it returned the run's class, and builds the row's kwargs dict and _PreparedCallMetadata.
  5. The records. Rust returns a list of kwargs dicts and a list of call metadata. Python puts them in one _DeferredRun with one _DeferredRunRow per row position, exactly what Python's walk records, and level C1's run task renders the rows as before.

Anything Rust cannot read exactly as Python does makes it return a reason, and Python's walk runs the loop from the start, so every error is Python's own, with its template position. Output bytes and the order of every user callback and extension hook are unchanged on both paths: the callback-order tests from #263 (tests/test_call_run_order.py) pass unchanged. This level runs only on the Rust path; the Python path keeps C1's walk.

Measured

Release wheels, Python 3.12, alternating fresh-process pairs of 11 renders of the benchmark board; mean per process.

Comparison Rows Before After Change Pairs faster
#267 -> this PR (10 pairs) 1,400 62.3 ms 58.3 ms -6.3% 10 of 10
#267 -> this PR (10 pairs) 140 11.1 ms 10.8 ms -3.2% 10 of 10
main -> this PR, whole stack so far (5 pairs) 1,400 98.8 ms 58.0 ms -41.3% 5 of 5
main -> this PR, whole stack so far (5 pairs) 140 14.0 ms 10.6 ms -24.3% 5 of 5

The bar was at least 3 ms on the collection-free median at 1,400 rows; it measured 4.2 ms (4.1 ms on the mean).

Notable implementation choices

  • Two readings of each expression. The research branch (research/rust-render-stage0) refused only surrogate escapes. Comparing Python's parse with the sandbox's generated code catches any literal the two read differently, and refuses generated code of a shape native_walk.py does not know. The board's five loops all get a plan, which a test checks.
  • The list is followed as Python follows it. The research declined when the list changed length during the reads (a colliding key's __eq__ can change it). Rust now re-reads the length before every item, so such a loop gives what Python's walk gives without a decline.
  • The scope must be exactly _ConstMapping. The research also walked a plain dict scope. Python's walk copies a plain dict scope for each row by inserting every key again, which runs a non-str key's __hash__ once per row; Rust would not. Citry always builds _ConstMapping; only an extension that replaces context.variables with a plain dict reaches this decline.
  • An overridden get keeps Python's walk. A Citry subclass's get is user code, which Python's walk calls between each row's reads and Rust would call only after all of them; such a loop declines (custom_get).
  • A failing row build declines. An exception while Rust builds a row's dict or metadata (such as MemoryError or RecursionError) makes the walk decline, so Python's walk raises it with the row's template position.
  • Panics decline. A Rust panic inside walk returns the reason panic, because the walk keeps nothing it built. A panic in the plan's constructor raises RuntimeError, which _build_walk_plan turns into "no plan".
  • The plan follows SUPPORTED. A loop's plan, or the reason it has none, is kept on the node; it is never built or used on the Python path, so a Python-path render cannot leave "no plan" cached for a later Rust-path render.
  • Not shipped from the research: the CITRY_RESEARCH_RUST_WALK switch, the walk counters and count_walk_decline, and the changed decline.

Accepted differences

None changes output unless the named user code has side effects.

  • A hash-colliding key's __eq__ runs again after a decline, because Python's walk reads the rows again. On a walked loop, a key among the template's variables that collides with the loop variable's name or a constant name is compared fewer times; one inside a row, or colliding with another scope name, is compared as often as in Python's walk (tests count both). A colliding __eq__ that rebinds a template variable is seen by the same row in Rust and only by the next row in Python's walk.
  • When get raises or returns another class at row k, the get calls of rows 0 to k-1 run twice (a test counts them). This is the one change in how many times get runs, and only another thread's registry change can reach it.
  • The bound component.citry.get and the execution frame are read once per walk, and the class's simple and dynamic-selector flags once before the loop, not once per row.
  • Another thread can run while get is called. If it changes a row in place, the walk does not see the change: the rows hold the values Rust read just before.
  • With the sandbox off, Python's evaluator writes and removes __builtins__ in the variables while it evaluates the iterable; Rust writes nothing.

Tests

  • tests/test_native_render_walk.py (127 cases, about 1.8 s on four workers):
    • C2 really runs: on the 140-row board a spy shows 5 loops walked in Rust and no decline, and each walk is compared with Python's walk of the same loop on the same context: the same rows, kwargs holding the very objects Python reads, and equal call metadata;
    • 37 page cases through render_both, one for each decline reason a page can reach (no_plan_loop, no_plan_key, no_plan_input, tracing, scope, const_input, custom_get, iterable, missing, not_plain, marker, key_type, read_raised, get_raised, class_changed) and for each kind of value the walk reads (tuples, int and extreme int keys, list and mixed rows, a dict keyed True read by row[1], a deeper iterable path, a scope input, a Const marker inside a row, an empty loop, the sandbox off);
    • order cases from test_call_run_order.py through the walk, including a row that changes the next row's dict before it renders, and two threads rendering together;
    • the lowering, and the plan called directly for what no page reaches: colliding row and scope keys compared as often as Python's reads compare them, a list that grows or shrinks during the reads, a compare or get that raises or is interrupted, a failing row build, a PanicException, the constructor's refusals, the collector seeing every held object and collecting a cycle through the plan, and no leaked references.
  • render_both now also records the loops Rust walked and each decline reason, and checks the Python path never walks in Rust.
  • Rust: crates/citry_native_render/tests/walk_rows.rs against walk_rows.json (24 loops over JSON data, values from Python's sandboxed evaluator), written by scripts/native_render_fixtures.py, whose --check a Python test runs.

Surrogate keys read differently by the sandbox

A related bug is real, older than this stack, and wider than simple = "vue": the sandbox reads '\ud800' as U+FFFD while the fast leaf evaluator and the unsandboxed path keep U+D800, so even an ordinary component reads a different key depending on its template's shape and its data. The fix belongs in the sandbox's code generator, outside this PR; an issue draft with reproductions is ready to file. Level A refuses such a key already (the comment and test now say why), and level C2 refuses any path whose two readings differ.

Review

An independent reviewer (high effort) attacked the equivalence of the reads (exact types, colliding __eq__, lists changed during the walk, threads, generators, Const markers, constness, tracing, the sandbox on and off), the panic and decline paths, reference counts and the collector, with throwaway probes comparing both paths. It found no blocker and no case where a page without side-effecting user code renders differently. Its findings and what was done:

  • Major: the surrogate sibling bug the plan asked this PR to investigate is real (see above). Recorded in an issue draft with the reproductions and a suggested fix in the sandbox; not fixed here, because the fix changes what existing pages render.
  • Minor: an overridden Citry.get is user code, and Rust would call it after all the reads instead of between them. Fixed: such a loop now declines (custom_get), with a page case whose get adds a row.
  • Minor: a colliding __eq__ that rebinds a template variable is seen one row earlier in Rust. Added to the accepted differences.
  • Minor: the stated reason for fewer __eq__ compares was wrong (copying a _ConstMapping compares nothing; the extra compares come from adding the loop variable and looking up constant names). Corrected in the doc and a test comment.
  • Nits, all applied: a decline also repeats the binding and constant checks; a row build can also fail with RecursionError; the doc's "every value's exact type" (only containers on a path and the key are checked); a PanicException also runs sys.excepthook; the collector test now checks every held object and collects a cycle through the plan; the fixture generator records a None key as Python's walk does; step keys are interned.

A separate prose pass checked every changed doc, comment, docstring, the stub, the commit message and both drafts, and found three wrong claims (the order of the checks before Rust runs, the fixture count, "the one call-count change"), one missing accepted difference, and about 35 wording items. All were applied.

Gates

  • Fast profile (scripts/check.py --profile fast --reporter agent, on the commit): "status": "PASSED", every phase passed.
  • mypy: clean, also with --platform linux (251 source files).
  • Python-path run (pytest -m "not e2e" -n 4 --python-render-path): 12,951 passed, 145 skipped, 1 xfailed. It ran before the review fixes, which change only code the Rust path runs.
  • Coverage (the full profile's pytest command with --cov, run locally on Python 3.14): 89.56%, against a ratchet of 88.5 (89.53% on perf: render a loop's simple="vue" rows in one render-queue task (native render, level C1) #267). The one new line no test reaches is a guard in native_walk.py for generated code whose loop element is not the loop variable, which the lowering's own wrapping rules out.

Cross-binding list

  • Rust: crates/citry_native_render/src/walk.rs (pure), crates/citry_core_py/src/native_render/walk.rs (PyO3, _CallRunWalkPlan), registered in native_render/mod.rs; the _rust.pyi stub; _CallRunWalkPlan added to native_render._REQUIRED_NAMES and to the SUPPORTED/ACTIVE decision test in test_native_render_rows.py.
  • Python: citry/_vue/native_walk.py (new), citry/nodes/__init__.py (ForNode), one comment in citry/_vue/leaf_program.py.
  • No grammar, AST, compiler output or LangImpl change; the template parser is not involved.
  • Docs: docs/design/native_render.md (new section 4, the C2 error modes and accepted differences, code map, tests), a ledger row in performance_architecture_experiments.md with the measured figures, docs/agent/INDEX.md, and the crate AGENTS.md files.
  • No changelog entry and no version bump, as for the rest of the stack.

Base

Rebased onto main after #263, #265, #266 and #267 merged.

Wheel size cap

This level takes the citry wheel 354 bytes past its 1,360 KiB release cap (1,392,994 bytes). The last commit raises the cap to 1,376 KiB in scripts/verify_citry_distribution.py, as agreed; level B2 (#269) adds about 3 KB more and still leaves about 12.8 KB of headroom.

🤖 Generated with Claude Code

JuroOravec and others added 3 commits October 23, 2026 13:22
…in paths (native render level C2)

When a c-for call run's iterable, call inputs and #c-key are plain paths
(a name and constant subscripts), Rust walks the loop through
native_render._CallRunWalkPlan: it reads every row with exact-type
checks, then calls the registry's get and builds each row's kwargs dict
and call metadata. Python puts them in the _DeferredRun and
_DeferredRunRow objects level C1's run task renders. Anything Rust cannot
read exactly as Python does declines with a reason, and Python's walk
runs the loop from the start. citry/_vue/native_walk.py turns each
expression into a path from both Python's parse and the sandbox's
generated code, and refuses the loop when the two differ. A loop whose
engine overrides Citry.get keeps Python's walk. Rust path only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…evels

The loop walk (level C2) takes the wheel 354 bytes past the 1,360 KiB cap,
and level B2 adds about 3 KB more. The new cap leaves about 12.8 KB of
headroom with every level in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@JuroOravec
JuroOravec force-pushed the perf/native-render-walk branch from de743a1 to b001252 Compare October 23, 2026 11:23
@JuroOravec
JuroOravec merged commit 0305dfb into main Oct 23, 2026
21 of 29 checks passed
@JuroOravec
JuroOravec deleted the perf/native-render-walk branch October 23, 2026 11:24
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