Skip to content

perf: write the JSON of ordinary components' leaf data in Rust (native render, level B2) - #269

Merged
JuroOravec merged 4 commits into
mainfrom
perf/native-render-leaf-json
Oct 23, 2026
Merged

JuroOravec merged 4 commits into
mainfrom
perf/native-render-leaf-json

Conversation

@JuroOravec

@JuroOravec JuroOravec commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

What this changes

An ordinary component (not simple = "vue") whose template calls no other components and has no slots compiles into one leaf program, and its render records the values that program sends to the browser (its leaf data). A simple = "vue" row that level A did not read records such a leaf too. Today assembly copies each of those values into the occurrence's prepared data, value by value, and the manifest writer later turns the copy into JSON.

With this PR, on the precompile path (when no browser hook can read or change prepared data) and on the Rust path:

  1. Rust writes the JSON. At the two places where assembly attaches an occurrence's own single leaf, attach_leaf_data asks native_leaf_json.take. Rust (_leaf_values_json) writes each value's JSON, byte for byte what _script_json(_json_plain(value)) writes, and returns a _LeafJson. No Python code runs while it writes.
  2. Assembly stores a placeholder. It puts one shared placeholder object under each leaf key instead of a copy, keeps the duplicate-key check, and maps the occurrence id to the _LeafJson in the dict that already carries level A's rows to the manifest writer.
  3. The encoder writes it in. _encode_occurrences writes that occurrence's item with its keys in sorted order and each placeholder's JSON in its place. Other values are written as _script_json writes them.

Rust writes only exact plain data: None, bool, an int within 64 bits, a finite float, a str with a UTF-8 form, and exact dict (with exact str keys), list and tuple, nested at most 200 deep, with no container inside itself. For anything else it returns a reason, and assembly copies the leaf in Python as before, so every error is Python's own, including the citry.Secret refusal and its message. Leaf programs have already turned their data into text, ints and bools, so the declines a page reaches are a lone surrogate in text and an int past Python's digit limit in an attribute; both then fail or succeed exactly as without Rust.

Output bytes, errors and the order of user callbacks are unchanged on both paths; the callback-order tests from #263 pass unchanged. This level runs only on the Rust path.

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
#268 -> this PR (10 pairs) 1,400 58.5 ms 54.8 ms -6.3% 10 of 10
#268 -> this PR (10 pairs) 140 10.7 ms 10.3 ms -3.6% 10 of 10

The bar was at least 1.5 ms at 1,400 rows; it measured 3.6 ms on the mean (2.6 ms on the collection-free median).

The whole stack against main

The same method, origin/main 736071308 against this branch (all five levels), 5 pairs:

Page Rows main Stack Change
Hydrated (default) 1,400 99.3 ms 54.5 ms -45.1%
Hydrated 140 14.1 ms 10.2 ms -27.2%
Fragment (rows rebuilt in Python) 1,400 108.0 ms 80.3 ms -25.7%
Fragment 140 15.1 ms 12.6 ms -16.2%
Strict CSP with a nonce 1,400 850.7 ms 818.2 ms -3.8%
Strict CSP with a nonce 140 68.7 ms 66.8 ms -2.7%

First and second page load through the real server (Server-Timing prepare, median of 10 fresh servers per side): at 1,400 rows first load 155.3 -> 111.4 ms (0.72 of main) and second load 103.1 -> 54.7 ms (0.53); at 140 rows 60.0 -> 56.3 ms (0.94) and 14.1 -> 10.6 ms (0.75). Every side sent the same bytes.

Notable implementation choices

  • The placeholder is an object, not a string. No user value can take its place: assembly copies every other value into plain JSON types, which never include it, and the encoder recognizes it by identity. JSON encoding refuses it, so a writer that skipped Rust's JSON would raise instead of sending the browser a wrong value. Copying and pickling give back the same object. This keeps perf: read simple="vue" rows and hash call-run ids in Rust (native render, level A) #265's rule that the manifest writer replaces no placeholder strings.
  • take returns the reason. It returns the _LeafJson or the decline reason as a string, as level C2's walk does, so the tests can see which case declined. Nothing in the shipped code counts declines.
  • _LeafJson is not tracked by the garbage collector. It holds only Rust strings and the placeholder, so it can be in no reference cycle, as with level B1's classes. The plan had proposed __traverse__; a test checks that a _LeafJson is untracked and holds no reference to the values it wrote.
  • The encoder writes simple values itself. For a leaf occurrence's item, Rust writes None, an exact str with a UTF-8 form and an empty dict, and calls _script_json only for the rest (a non-empty serverData, an Events eventContext). The research called _script_json for 8 to 10 values per item.
  • The manifest's entries are written in sorted order. _manifest_json now writes the entries before occurrences, then the occurrences, then the rest, the order _script_json(manifest) writes them in. A page with such leaves and no Rust rows now takes this writer, so a value that cannot be written raises the error that call would raise first.
  • The encoder checks the leaf is complete. It raises ValueError when a placeholder has no JSON, when a value Rust wrote has no placeholder in the item (which would drop data silently), and when an item key is not a str. Assembly never makes such an item.
  • Owners are checked. Both places that attach Rust's JSON finish the occurrence without building a body, so it never owns data, calls or a slot selection whose values assembly reads or merges. owner_values raises AssertionError if one ever did.
  • Development mode keeps this level. A development page checks every element id in its HTML; leaf JSON changes no HTML, so this level stays on there.
  • Not shipped from the research: the CITRY_RESEARCH_RUST_LEAF_JSON switch, the leaf counters and count_leaf_json_decline, and _LeafJson.value_json.

Accepted differences

None changes output.

  • With a very low recursion limit, Rust writes data up to 200 levels deep that Python's conversion would refuse with RecursionError. A test shows it.
  • PreparedOccurrence equality includes prepared_data, and every placeholder is the same object, so two such occurrences whose leaf values differ would compare equal. Nothing compares them on this path.

Tests

  • tests/test_native_render_leaf_json.py (88 cases, about 0.4 s on one worker):
    • B2 really runs: on a 140-row board shaped like the benchmark page (a project information panel and three note tabs beside five phases of rows), a spy on take shows all 4 ordinary leaves written and no decline, with 140 rows read and none rebuilt;
    • page cases through render_both, each checking that its pages are pages and not errors: awkward text (quotes, </script>, control characters, U+2028, an astral character), three calls sharing one definition so both attach places run, the two reachable declines (a lone surrogate beside two leaves Rust writes, and an int past the digit limit in an attribute), a simple = "vue" row Rust did not read, whose leaf Rust then writes, the flag switched off after assembly, a leaf beside a run of Rust rows, js_data, a Secret in js_data (Python's refusal and message), a Secret in text, an attribute and a spread (masked before Rust sees it), Markup, an Events component, development mode, and a browser hook (no leaf written);
    • Rust's JSON against Python's, through the manifest encoder as a page writes it: 31 hand-written values (hard floats, the 64-bit bounds, every control character, keys whose UTF-16 and code point orders differ, shared references, tuples), data nested 200 deep, and 300 seeded random values;
    • each decline reason called directly (24 values), the leaf-data shapes Rust refuses, both guarded keys, each encoder refusal (including a value with no placeholder and a non-str key), the placeholder refused by json.dumps and kept by copy, deepcopy and pickle, and a _LeafJson untracked by the collector with no leaked references.
  • render_both now also counts the leaves Rust wrote and records each decline reason, and checks the Python path writes none.
  • The SUPPORTED/ACTIVE decision test gains a module with level C2's names but not level B2's.

Gates

  • Fast profile (scripts/check.py --profile fast --reporter agent, on the final tree): "status": "PASSED", all 20 phases passed. An earlier run failed only in the Vue render parity phase, on this PR's own test pages: a DEL character (U+007F) in hydrated page text fails that phase's parse check on both paths. DEL now appears only in the direct byte checks (see "For the maintainer" below).
  • mypy: clean, also with --platform linux (254 source files).
  • Python-path run (pytest -m "not e2e" -n 4 --python-render-path): 13,038 passed, 145 skipped, 1 xfailed. It ran before the last review fixes, which add tests and an encoder check on the Rust path only.
  • Coverage (the full profile's pytest command with --cov, run locally on Python 3.14): 89.56%, against a ratchet of 88.5 (89.56% on perf: walk a loop of simple="vue" rows in Rust when it reads only plain paths (native render, level C2) #268). native_leaf_json.py is fully covered. The coverage settings leave out assemble_typed_render, so B2's assembly code is not counted; its two defensive AssertionErrors are reachable from no page.
  • cargo: fmt --check and clippy -D warnings clean.

Cross-binding list

  • Rust: crates/citry_core_py/src/native_render/leaf_json.rs (new, PyO3 only; the pure crate is unchanged), registered in native_render/mod.rs; rows.rs's _encode_occurrences gains the leaf branch and shares python_float_repr.
  • Stub: _LeafJson, _leaf_values_json and the encoder's natives type in _rust.pyi; both names added to native_render._REQUIRED_NAMES.
  • Python: citry/_vue/native_leaf_json.py (new), citry/_vue/direct_capture.py (attach_leaf_data, owner_values), citry/_vue/serialization.py (_manifest_json), comments in events.py, prepared.py and native_render.py.
  • No grammar, AST, compiler output or LangImpl change.
  • Docs: docs/design/native_render.md (new section 5, the B2 error modes and accepted differences, code map, tests), a ledger row in performance_architecture_experiments.md (with the measured figures), one paragraph on the performance page, docs/agent/INDEX.md, and the AGENTS.md files of citry_core_py and citry_core.
  • No changelog entry and no version bump, as for the rest of the stack.

Review

An independent reviewer (high effort) compared Rust's JSON with Python's on 35 hand-picked values and 20,000 fuzzed items, probed the item writer, every reader of prepared data between assembly and the manifest writer, citry.Secret, the flag, Events, development mode and the collector. It found no blocker and no byte or error difference. Its findings and what was done:

  • Minor: a page can reach a second decline, big_int, through an attribute holding an int past Python's digit limit. Fixed the claim everywhere and added a page case.
  • Minor: B2 also writes the leaf of a simple = "vue" row that level A declined. Fixed the wording and added a page case (leaves=(3, ())).
  • Minor: the encoder did not check that every value Rust wrote reached the item, so a missing placeholder would have dropped data silently. It now raises ValueError; tested.
  • Nits, applied: an item key that is not a str now raises instead of being written without quotes; the "item changes while fallback runs" error is described as a lost key; the depth comment counts two frames per level on Python 3.10 and 3.11; every success case checks it got pages, not errors; a test switches the flag off after assembly; take checks the two guarded keys with two lookups; the placeholder's no-cycle requirement is stated on _leaf_values_json.
  • Not changed: the performance page does not say that an extension with a browser hook keeps a page off this path; the paragraph for simple = "vue" rows does not say it either. leaf_json.rs has no Rust unit tests or fixtures (the cross-binding table planned none for B2): it lives in the PyO3 layer, and the Python byte comparisons cover it; the JSON string and float writers it uses are level A's, which have fixtures.

A separate prose pass checked every changed comment, docstring, the stub, the docs, the commit message and this draft. It found three misleading statements (the performance paragraph sat under a list of cases that do not apply to it, a test comment gave the wrong reason for its outputs, a frame count) and about 30 wording items. All were applied, including the paragraph's own limits (it applies in development mode and with js_data()).

For the maintainer

  • DEL in page text. A hydrated page whose text holds DEL (U+007F) fails the Vue render parity phase's full parse check, on both paths, so it is older than this stack. Whether the hydration writer or the check is wrong is not investigated here.
  • The bar's statistic. The research measured 2.04 ms on the mean, about half of it from fewer garbage-collector pauses, so a collection-free median may show only about half the gain.

Base

Rebased onto main after the rest of the stack (#263, #265-#268) and the research record (#275) merged. Two small commits on top: the wheel-size note in scripts/verify_citry_distribution.py now gives the size with B2 (1,396,226 bytes, about 12.8 KB under the 1,376 KiB cap), and one accepted-difference bullet in native_render.md now says correctly that Rust-read rows are still checked against the registry for every row.

🤖 Generated with Claude Code

JuroOravec and others added 4 commits October 23, 2026 13:26
…e render level B2)

When assembly attaches the leaf data of an ordinary (not simple='vue')
component's occurrence on the precompile path, native_render._leaf_values_json writes each value's
JSON as _script_json(_json_plain(value)) would, and assembly stores one
shared placeholder object under each key instead of a copy.
_encode_occurrences then writes the occurrence's item with Rust's JSON in
place of each placeholder. Anything Rust cannot write exactly returns a
reason, and Python copies the leaf as before, so every error, the
citry.Secret refusal included, stays Python's. _manifest_json now writes
the manifest's entries in sorted key order, so a value that cannot be
written raises the error _script_json(manifest) would raise first. Rust
path only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@JuroOravec
JuroOravec force-pushed the perf/native-render-leaf-json branch from dd4ca71 to 46c45d3 Compare October 23, 2026 11:27
@JuroOravec
JuroOravec merged commit 801477f into main Oct 23, 2026
15 of 29 checks passed
@JuroOravec
JuroOravec deleted the perf/native-render-leaf-json branch October 23, 2026 11:43
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