Skip to content

fix: copy deeply nested js_data() on any Python - #412

Merged
JuroOravec merged 1 commit into
mainfrom
fix/js-data-deep-detach
Oct 25, 2026
Merged

JuroOravec merged 1 commit into
mainfrom
fix/js-data-deep-detach

Conversation

@JuroOravec

Copy link
Copy Markdown
Member

Fixes the js_data() part of #393. js_data() nested about 1,000 levels deep raised RecursionError while Citry copied it, with or without js. Deep State is left out; see below.

What was wrong

PreparedOccurrence copies a component's js_data() in _detach_object (_vue/prepared.py). Two steps there recursed:

  • _validate_keys called itself once per level;
  • the copy was 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.loads for a Vue fragment mount.

The change

  • citry/util/deep_json.py (new) holds two stack-based functions:
    • dumps is the writer script_json already used (fix: write deep data for the browser with a bounded number of frames #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. It reads strings with the standard library's string reader, and numbers by the same rules as its C scanner (ASCII digits only).
  • Standard functions first: _detach_object and the fragment mount call the standard functions, because they are fast, and the stack versions only after RecursionError:
    • the copy becomes deep_json.loads(deep_json.dumps(...));
    • _validate_keys falls back to _validate_keys_with_stack, which finds the same first bad key.
  • Loops: the stack 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.

Is the output the same?

  • The stack copy: a random comparison checked it against the round trip on 20,000 random values per interpreter (CPython 3.11, 3.13, 3.14 and PyPy). The values included str, int and float subclasses with their own repr, enums, namedtuples, dict subclasses, NaN, objects, oversized ints, shared references and loops. Values, types and errors were identical.
  • The reader: 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: the standard string reader there is the pure-Python one, so loads accepts a \u escape whose characters int(text, 16) reads, which PyPy's own decoder refuses. The module docstring says so.

Tests (test_deep_json_data.py)

  • deep_json.loads against json.loads on 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. On main, both raise RecursionError.
  • A loop and a deep bad key in server data. On main, both raise RecursionError.
  • The copy fallback forced with subclasses, and the fragment-mount read forced.

Speed

_detach_object runs on every render whose js_data() is not empty; the ordinary path only gains try blocks. I timed it in-process against main at 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_json runs, _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);
    • the emission and cache code.

    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. This needs its own change across those sites.

  • Other places that still call json directly: 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).

Checks

  • Tests: test_deep_json_data.py, test_events_tokens.py, test_vue_prepared.py and test_vue_hydration_regions.py pass.
  • Lint and types: ruff and mypy, including --platform linux, are clean.
  • Review: an independent review at high effort ran twice; its findings are applied.

🤖 Generated with Claude Code

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
JuroOravec force-pushed the fix/js-data-deep-detach branch from c80010c to 4bd4bbd Compare October 25, 2026 16:13
@JuroOravec
JuroOravec merged commit 3b9b964 into main Oct 25, 2026
23 of 28 checks passed
@JuroOravec
JuroOravec deleted the fix/js-data-deep-detach branch October 25, 2026 16:28
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