Repository navigation
fix: write deep data for the browser with a bounded number of frames - #391
Merged
Merged
Conversation
A component that uses Vue sends the browser data that nests about two levels for each `<c-for>` that has a `<c-empty>`. Three steps read that data with one Python frame or more per level (part of #272): - `_json_plain` in `_vue/json_data.py`, which checks the data and copies it into exact JSON types, used one Python frame per level of data (two on Python 3.11), so a chain of 256 such tags raised `RecursionError` with 200 frames already in use by the host application. - `_copy_evaluated_json` and `_secret_key_path` in the same file recurse the same way. - On Python 3.11 and PyPy, `json.dumps` in `script_json` counts each nested container against the recursion limit too. Later CPython versions stop it at a fixed limit of their own, about 10,000 levels on 3.13. Now: - `_json_plain` and `_copy_evaluated_json` copy the first 32 levels with direct calls, as before, and hand anything deeper to a stack walk that makes the same checks in the same order. They also return an exact `str`, `int`, `bool` or `None` item without a call, which makes them up to about a third faster on ordinary data. - `_secret_key_path` walks with a stack. - `script_json` catches `RecursionError` from `json.dumps` and writes the same text with a stack (`_json_text_with_stack`), which writes each scalar with `json.dumps` itself. For the exact JSON types and plain subclasses Citry passes, the text and errors are the same. Since rendering now checks `js_data()` at any depth and raises for a `Secret` or a value that is not JSON wherever it sits, `citry check` reports those however deeply they are nested: its depth cutoff and the `RecursionError` guards around the JSON check are removed. The accepted difference between Rust's and Python's conversion of deep leaf data under a low recursion limit is gone, so `native_leaf_json.py` and `docs/design/native_render.md` no longer list it. Tests: - `tests/test_deep_json_data.py` checks each step on data 2,000 levels deep with 150 frames left, that `_json_plain` raises the same error for the same value near the top, just past the switch to the stack walk, and deep down, that the stack JSON writer writes and raises what `json.dumps` does, that `script_json` writes the same text when `json.dumps` raises `RecursionError`, and that a chain of 256 `<c-for>` tags with `<c-empty>` renders with 200 host frames in use and 500 free. - `test_secret.py` checks that `citry check` reports a Secret and an object nested 5,000 deep. - `test_native_render_leaf_json.py` checks that Python and Rust both write deep data under a low recursion limit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 25, 2026
Closed
JuroOravec
added a commit
that referenced
this pull request
Oct 25, 2026
Fixes the `js_data()` part of #393. `PreparedOccurrence` copies a component's `js_data()` in `_detach_object` (`_vue/prepared.py`): `_validate_keys` called itself once per level, and the copy was `json.loads(json.dumps(...))`, which on Python 3.11 counts each level against the recursion limit. So `js_data()` nested about 1,000 levels deep raised `RecursionError`, with or without `js`. Serialization also reads the page's prepared data back with `json.loads` for a Vue fragment mount. Now: - `citry/util/deep_json.py` holds two stack-based functions. `dumps` is the writer `script_json` already used (#391), moved here; it writes, byte for byte, what `json.dumps(..., allow_nan=False, separators=(",", ":"))` writes. `loads` reads JSON text into the same value `json.loads` gives, with the same `object_pairs_hook` and `parse_constant` behavior, reading strings with the standard library's string reader and numbers by the same rules as its C scanner (ASCII digits only). - `_detach_object` and the fragment mount call the standard functions first, because they are fast, and the stack versions only after `RecursionError`: the copy becomes `deep_json.loads(deep_json.dumps(...))`, and `_validate_keys` falls back to `_validate_keys_with_stack`, which finds the same first bad key. That walk also stops at a container that holds itself, so `js_data()` with a loop and no bad key now raises the encoder's `ValueError` ("Circular reference detected") instead of `RecursionError`. A random comparison checked the stack copy against the round trip on 20,000 random values per interpreter (CPython 3.11, 3.13, 3.14 and PyPy), with str, int and float subclasses with their own repr, enums, namedtuples, dict subclasses, NaN, objects, oversized ints, shared references and loops: identical values, types and errors. `deep_json.loads` matches `json.loads` on random and damaged documents on CPython 3.11, 3.13 and 3.14, including digits from other scripts. On PyPy, where the standard string reader is the pure-Python one, `loads` accepts a `\u` escape whose characters `int(text, 16)` reads, such as ` 0e9`, which PyPy's own decoder refuses; the module says so. Tests in `test_deep_json_data.py`: `deep_json.loads` against `json.loads` on valid, invalid and seeded random documents, deep text in bounded frames, `js_data()` 2,000 levels deep rendering with and without Vue with 300 frames left (both raise `RecursionError` on `main`), a loop and a deep bad key in server data (both `RecursionError` on `main`), the copy fallback forced with subclasses, and the fragment-mount read forced. `_detach_object` runs on every render whose `js_data()` is not empty; the ordinary path only gains `try` blocks. Timed in-process at a load average over 40, it showed no slowdown (the run was too noisy for a finer claim). Not in this change: deep State. Before `_canonical_json` runs, `_reject_non_string_dict_keys` (`ext/events/tokens.py`) calls itself once per level, and `public_state_values` (`ext/events/state.py`), `_state_fingerprint` (`ext/events/dispatcher.py`), the emission and the cache code use the standard encoder, so a stack writer in `_canonical_json` alone would not let deep State mint. Reading tokens with a stack would also let an unsigned token cost far more to reject. The dependencies extension's `js_data()` JSON (`ext/dependencies/scripts.py`, which passes `default=`), the event response envelopes (`ext/events/routes.py`) and an extension's browser payload (`browser_render.py`) also still use `json` directly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #272. A component that uses Vue sends the browser data that nests about two levels for each
<c-for>that has a<c-empty>. This PR makes every step that checks, copies and writes that data use a bounded number of Python frames, so deep data no longer raisesRecursionErrorthere.What was wrong
_json_plain(_vue/json_data.py) checks the data and copies it into exact JSON types. It called itself once per level of data, which costs one Python frame per level (two on Python 3.11). A chain of 256<c-for>tags with<c-empty>raisedRecursionErrorwhen 200 frames were already in use by the host application (513_json_plainframes on the stack)._copy_evaluated_jsonand_secret_key_pathcalled themselves once per level the same way.json.dumpsinscript_jsoncounts each nested container against the recursion limit. With 300 frames free, it failed at about 300 levels on 3.11.17, and at about 1,100 on PyPy 3.11. Later CPython versions stop it at a fixed limit of their own, about 10,000 levels on 3.13. The page's data goes throughscript_jsononce per render.The change
_json_plainand_copy_evaluated_json: the first 32 levels are copied with direct calls, as before. Anything deeper goes to a stack walk, which makes the same checks in the same order, so the same value fails with the same error wherever it sits. Both functions also return an exactstr,int,boolorNoneitem without a call._secret_key_path: walks with a stack.script_json: catchesRecursionErrorfromjson.dumpsand writes the same text with a stack (_json_text_with_stack). That writer follows the standard encoder's steps and writes each scalar withjson.dumpsitself. For the exact JSON types and plain subclasses that Citry passes, it writes the same text and raises the same errors. Values that change how they are read can differ: a dict subclass whoseitems()returns lists, the notes Python 3.14 adds to an error, and on PyPy the text for a dict subclass and the error for keys that cannot be sorted. None of these reachscript_jsonfrom Citry's callers.citry check: rendering now checksjs_data()at any depth and raises for aSecretor a value that is not JSON wherever it sits. So the check now reports those however deeply they are nested. Its depth cutoff, and itsRecursionErrorguards around the JSON check, are removed.native_leaf_json.pyanddocs/design/native_render.mdlisted one accepted difference: under a low recursion limit, Rust wrote deep leaf data that Python's conversion refused. That difference no longer exists, so neither lists it.Not in this PR: plain
js_data()nested close to the recursion limit still raisesRecursionErrorone step later._detach_objectin_vue/prepared.pychecks its keys with a recursive function and copies it withjson.loads(json.dumps(...)). A deep<c-for>chain does not go through that path. I wrote it up as a separate issue._canonical_jsoninext/events/tokens.pyhas the same 3.11 limit for a deeply nestedStatevalue; it is not on this path either.Is the output the same?
_json_plain,_secret_key_pathand_copy_evaluated_jsonall had 0 mismatches. No output shares a container with its input.json.dumpson 20,000 random values in four combinations ofsort_keysandensure_ascii, it matched with 0 mismatches on CPython 3.11, 3.12, 3.13 and 3.14. On PyPy 3.11 the only differences were in the sort error above. The reviewer ran 24,000 more cases on 3.11, 3.13 and 3.14, with subclasses that overrideitems(),IntEnum, afloatsubclass with its own__repr__, and ints past the digit limit: 0 mismatches.json.dumpswrites. A 128-level chain renders the same HTML onmainand on this branch, apart from the random ids.Speed
_json_plainruns on every render of a component that uses Vue, so the minimum-CPU gate applies. Timed in-process againstmain:main_copy_evaluated_jsonof 20 rowsThe minimum-CPU gate on the large benchmark scenario, with a release build of citry-core: 15 alternating fresh processes per side, 30 renders each, load average 6 to 10.
mainTests
tests/test_deep_json_data.py(new):json.dumpsdoes;script_jsonwrites the same text whenjson.dumpsraisesRecursionError, which the test forces on every version;<c-for>/<c-empty>chain renders with 200 host frames in use and 500 free, and the server HTML holds the value.test_secret.py: a Secret and an object nested 5,000 deep are both reported bycitry check, and rendering raises for the Secret with its full path.test_native_render_leaf_json.py: Python and Rust both write 150-level data under a low recursion limit.The deep tests fail on
main. The shallow ones pass on both, which shows the behavior is unchanged. citry_core is built only for 3.14 here, so the 3.11 CI cell is the first full run on 3.11. Locally I ran the stack JSON writer on 3.11 directly.Checks
maintoo and are fixed in their own PRs:pinnedopaque-HTML record, fixed in fix: let the Vue parity check accept pinned opaque HTML records #390.--platform linux.🤖 Generated with Claude Code