Skip to content

fix: write deep data for the browser with a bounded number of frames - #391

Merged
JuroOravec merged 1 commit into
mainfrom
fix/json-plain-stack
Oct 25, 2026
Merged

JuroOravec merged 1 commit into
mainfrom
fix/json-plain-stack

Conversation

@JuroOravec

Copy link
Copy Markdown
Member

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 raises RecursionError there.

What was wrong

  • The data check: _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> raised RecursionError when 200 frames were already in use by the host application (513 _json_plain frames on the stack).
  • Two more functions in the same file: _copy_evaluated_json and _secret_key_path called themselves once per level the same way.
  • Python 3.11 and PyPy: json.dumps in script_json counts 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 through script_json once per render.

The change

  • _json_plain and _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 exact str, int, bool or None item without a call.
  • _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). That writer follows the standard encoder's steps and writes each scalar with json.dumps itself. 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 whose items() 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 reach script_json from Citry's callers.
  • citry check: rendering now checks js_data() at any depth and raises for a Secret or a value that is not JSON wherever it sits. So the check now reports those however deeply they are nested. Its depth cutoff, and its RecursionError guards around the JSON check, are removed.
  • Docs: native_leaf_json.py and docs/design/native_render.md listed 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 raises RecursionError one step later. _detach_object in _vue/prepared.py checks its keys with a recursive function and copies it with json.loads(json.dumps(...)). A deep <c-for> chain does not go through that path. I wrote it up as a separate issue. _canonical_json in ext/events/tokens.py has the same 3.11 limit for a deeply nested State value; it is not on this path either.

Is the output the same?

  • Shallow data: the whole suite passes with no expected value changed, apart from the two tests that locked the old depth limit.
  • Random comparison: I compared the new functions with the recursive ones on 160,000 random values. Three quarters of them were wrapped in 25 to 45 extra levels, so the stack walk runs. The values held Consts, tuples, translated text, str-subclass keys, dict subclasses, loops, shared containers, NaN, Secrets, unknown types and non-string keys. Results and errors matched in every case: _json_plain, _secret_key_path and _copy_evaluated_json all had 0 mismatches. No output shares a container with its input.
  • The stack JSON writer: compared with json.dumps on 20,000 random values in four combinations of sort_keys and ensure_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 override items(), IntEnum, a float subclass with its own __repr__, and ints past the digit limit: 0 mismatches.
  • Deep data: for data about 600 levels deep, with 200 host frames in use, the 3.11 fallback wrote exactly the text that 3.14's json.dumps writes. A 128-level chain renders the same HTML on main and on this branch, apart from the random ids.

Speed

_json_plain runs on every render of a component that uses Vue, so the minimum-CPU gate applies. Timed in-process against main:

Data main This branch
a str 0.100 µs 0.065 µs
a dict of 3 scalars 0.86 µs 0.57 µs
20 rows of 5 fields 31.8 µs 21.2 µs
4 nested dicts 2.6 µs 2.2 µs
_copy_evaluated_json of 20 rows 7.2 µs 6.4 µs

The 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.

Native path main This branch Change
on 69.31 ms 67.99 ms -1.9%
off 71.48 ms 70.78 ms -1.0%

Tests

  • tests/test_deep_json_data.py (new):
    • each step on data 2,000 levels deep, with 150 frames left;
    • the same error for the same value at depth 3, just past the switch to the stack walk, and at 2,000;
    • the stack JSON writer writes and raises what json.dumps does;
    • script_json writes the same text when json.dumps raises RecursionError, which the test forces on every version;
    • the 256-level <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 by citry 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

🤖 Generated with Claude Code

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]>
@JuroOravec
JuroOravec merged commit 4429524 into main Oct 25, 2026
19 of 28 checks passed
@JuroOravec
JuroOravec deleted the fix/json-plain-stack branch October 25, 2026 10:31
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]>
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