Repository navigation
fix: copy deeply nested js_data() on any Python - #412
Merged
Merged
Conversation
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]>
JuroOravec
force-pushed
the
fix/js-data-deep-detach
branch
from
October 25, 2026 16:13
c80010c to
4bd4bbd
Compare
This was referenced Oct 27, 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.
Fixes the
js_data()part of #393.js_data()nested about 1,000 levels deep raisedRecursionErrorwhile Citry copied it, with or withoutjs. Deep State is left out; see below.What was wrong
PreparedOccurrencecopies a component'sjs_data()in_detach_object(_vue/prepared.py). Two steps there recursed:_validate_keyscalled itself once per level;json.loads(json.dumps(...)), which on Python 3.11 counts each level against the recursion limit.Serialization also reads the page's prepared data back with
json.loadsfor a Vue fragment mount.The change
citry/util/deep_json.py(new) holds two stack-based functions:dumpsis the writerscript_jsonalready used (fix: write deep data for the browser with a bounded number of frames #391), moved here. It writes, byte for byte, whatjson.dumps(..., allow_nan=False, separators=(",", ":"))writes.loadsreads JSON text into the same valuejson.loadsgives, with the sameobject_pairs_hookandparse_constantbehavior. It reads strings with the standard library's string reader, and numbers by the same rules as its C scanner (ASCII digits only)._detach_objectand the fragment mount call the standard functions, because they are fast, and the stack versions only afterRecursionError:deep_json.loads(deep_json.dumps(...));_validate_keysfalls back to_validate_keys_with_stack, which finds the same first bad key.js_data()with a loop and no bad key now raises the encoder'sValueError("Circular reference detected") instead ofRecursionError.Is the output the same?
deep_json.loadsmatchesjson.loadson random and damaged documents on CPython 3.11, 3.13 and 3.14, including digits from other scripts.loadsaccepts a\uescape whose charactersint(text, 16)reads, which PyPy's own decoder refuses. The module docstring says so.Tests (
test_deep_json_data.py)deep_json.loadsagainstjson.loadson valid, invalid and seeded random documents, and on deep text in bounded frames.js_data()2,000 levels deep renders with and without Vue, with 300 frames left. Onmain, both raiseRecursionError.main, both raiseRecursionError.Speed
_detach_objectruns on every render whosejs_data()is not empty; the ordinary path only gainstryblocks. I timed it in-process againstmainat a load average over 40: no slowdown showed, though the run was too noisy for a finer claim.Not in this PR
Deep State. Before
_canonical_jsonruns,_reject_non_string_dict_keys(ext/events/tokens.py) calls itself once per level, and several places use the standard encoder:public_state_values(ext/events/state.py);_state_fingerprint(ext/events/dispatcher.py);So a stack writer in
_canonical_jsonalone would not let deep State mint. Reading tokens with a stack would also let an unsigned token cost far more to reject. This needs its own change across those sites.Other places that still call
jsondirectly: the dependencies extension'sjs_data()JSON (ext/dependencies/scripts.py, which passesdefault=), the event response envelopes (ext/events/routes.py) and an extension's browser payload (browser_render.py).Checks
test_deep_json_data.py,test_events_tokens.py,test_vue_prepared.pyandtest_vue_hydration_regions.pypass.--platform linux, are clean.🤖 Generated with Claude Code