Repository navigation
add orjson - #6116
add orjson#6116benedikt-bartscher wants to merge 83 commits into
Conversation
Merging this PR will degrade performance by 9.12%3 warnings
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting Comparing Footnotes
|
[Medium impact] The PR affects several JSON paths used by Reflex apps and generated frontend projects. The custom-codec string issue still needs a complete fix before merging. Findings
SummaryAdds optional
Reviews (48) · Last reviewed commit: "Reuse one encoder for bare strings witho..." · Reviewed by Greptile |
|
the issue with orjson is that we lose NaN handling which is relevant for numpy, which is why we were using JSON5 as well |
|
Yeah, that's why i did not update it in all places |
…llback Happy path uses native JSON.parse; the catch rewrites Python"s bare Infinity/-Infinity/NaN tokens outside string literals before retrying, so only payloads that actually contain specials pay the extra cost. NaN has no JSON literal and becomes null (matches JSON.stringify).
…o null Swap bare NaN for a sentinel string before JSON.parse and revive it back to a real NaN so Python-side float(nan) round-trips to the frontend.
|
related #6339 |
Apply orjson_dumps/orjson_loads helpers to the new reflex_base package locations after upstream's restructuring.
bed6d7b to
7555e7b
Compare
Route main's new stateful-pages marker reader/writer through the orjson helpers and keep both new event-processing benchmarks.
# Conflicts: # reflex/app.py # reflex/utils/frontend_skeleton.py # tests/benchmarks/test_event_processing.py # tests/units/test_prerequisites.py # tests/units/utils/test_exec.py
Upstream's new JSON emitters in the compile path now go through orjson_dumps like the PR's other call sites: the stateSchema export in app_root_template (templates.py no longer imports json) and the useStateContext hook in VarData.from_state. The stateful pages marker read keeps orjson_loads with upstream's ValueError comment. The orjson test's datetime.timezone.utc becomes datetime.UTC, which ruff now requires after upstream raised the minimum Python to 3.11.
|
#7448 seems like a better approach |
orjson emits an Enum's value without consulting default, so a serializer registered for a non-Enum base of an Enum was bypassed only when the extra was installed. Registration now also checks existing subclasses, and resolving an Enum or UUID to a non-native serializer disables the orjson paths for Enums created later.
The real socket path decodes with the stdlib, so decoding with orjson_loads overstated the gain.
| if (v === NAN_SENTINEL) return NaN; | ||
| if (v === INF_SENTINEL) return Infinity; | ||
| if (v === NEG_INF_SENTINEL) return -Infinity; | ||
| if (v.startsWith(SENTINEL_ESCAPE_PREFIX)) | ||
| return v.slice(SENTINEL_ESCAPE_PREFIX.length); |
There was a problem hiding this comment.
Reflex keeps an explicitly supplied Socket.IO JSON codec, but parseJson now assumes that every sender escapes reserved strings. If a custom codec sends {"v":"__reflex_nan__"}, the browser receives NaN instead of the string. Strings starting with __reflex_esc__ lose that prefix. Custom codecs did not previously need Reflex-specific escaping. Preserve these strings unless the sender explicitly uses the new encoding.
orjson writes None, NaN and infinities all as null, so a delta with a null takes a different socket codec path than one without. The wire benchmark had no null at all and measured only the best case. Put a None (small and large delta) or a NaN (large delta) in the first row's balance; locally the large None delta takes 2.23 ms against 1.29 ms without it.
The socket codec escaped user strings starting with __reflex_ and, when
one appeared, re-serialized the payload with NaN and infinities turned
into sentinel strings that a new reviver in parseJson restored. Main's
parseJson already decodes the bare NaN/Infinity tokens the stdlib emits,
deriving a placeholder no string in the payload can collide with, so the
sentinels only added cost: a byte scan of every orjson payload, a str
scan of every stdlib one, and includes("__reflex_") on every message in
the browser (11 us on an 18 KB table delta in node, next to a 53 us
JSON.parse). Restore main's json.js and stop installing the codec on a
custom socket.io server, whose only reason was the escaping.
100-row table delta with orjson: 26.1 -> 22.7 us; small delta: 0.85 ->
0.76 us. A test now runs the codec's output through parseJson and pins
that it decodes to what the stdlib encoding decodes to.
OPT_NON_STR_KEYS doubled orjson's own time on every payload (5.8 -> 10.7 us on a 100-row table delta). Without it orjson raises TypeError on a non-str key and the existing stdlib fallback writes what main writes; it also stops orjson from accepting Enum, date and UUID keys that the stdlib, and so the default install, rejects. 100-row table delta: 22.7 -> 14.1 us; small delta: 0.76 -> 0.67 us.
orjson writes None, NaN and infinities all as null, so every payload with a None (an unset Optional var) or a string containing "null" was serialized a second time by the stdlib, which made it slower than main. Now a null only triggers a walk for non-finite floats over the payload and over what default returned for orjson (a StateUpdate, dataclasses, models), so no custom object is serialized twice; only a payload that really holds a NaN or an infinity goes to the stdlib, which keeps the bare tokens main sends. default is a functools.partial rather than a closure, whose annotations would be rebuilt on every call, and the null scan uses a compiled regex, a third faster than `in` on bytes. Per message, before -> after (main): small delta + None 2.02 -> 1.25 us (1.33) 100-row table + None 65.5 -> 25.7 us (57.7) 100-row table + NaN 65.3 -> 64.9 us (57.3) 100-row table 14.1 -> 11.3 us (57.9) small delta 0.67 -> 0.75 us (1.35)
Without the orjson extra, the bare-string fast path called
json.dumps(obj, ensure_ascii=False), which builds a new encoder because
it is given an option. A module-level encoder produces the same output:
LiteralStringVar.create("hello") 930 -> 555 ns (main 570 ns).
State updates over the websocket and generated frontend files are serialized with orjson when the new
reflex[orjson]extra is installed; without it Reflex falls back to the stdlibjsonmodule. Output is byte-compatible between the two backends, and inbound socket integers beyond 64 bits still reach event handlers exactly.Benchmarks
Event wire path — decode 3 incoming events, process them, serialize 3 deltas — measured with each revision's own socket codec (
_sio_dumps/_sio_loads). Python 3.14.7, 500 rounds, 3 interleaved repetitions; medians, ±1–2% run to run.mainOutgoing encode in isolation (95.7 KB payload):
mainWithout the extra, the fallback adds two scans of the serialized string on top of the stdlib dump — the sentinel-collision check and the
isascii()UTF-8 guard — about +29 µs on 95.7 KB.