Skip to content

Add a native JSON writer for IValue (byte-identical to serde_json) - #34

Merged
fcostaoliveira merged 3 commits into
RedisJSON:masterfrom
fcostaoliveira:native-json-writer
Dec 3, 2026
Merged

fcostaoliveira merged 3 commits into
RedisJSON:masterfrom
fcostaoliveira:native-json-writer

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Dec 1, 2026 •

Copy link
Copy Markdown

What

A writer that serialises an IValue to JSON text by walking it directly, instead of going through Serialize:

ijson::to_writer(&mut w, &value)?;          // compact
ijson::to_vec(&value)?;                       // Vec<u8>
ijson::to_string(&value)?;                    // String
ijson::write_json(&mut w, &mut fmt, &value)?; // any serde_json Formatter (indent, newline, space)

The output is byte-identical to serde_json::to_writer / Serializer::with_formatter on the same value. Every token goes through the same serde_json::ser::Formatter method serde_json would call, in the same order and with the same arguments, so:

  • numbers are still formatted by ryu/itoa, including the shortest-round-trip handling of f32/f16/bf16 typed-array elements in ser.rs;
  • a custom formatter sees the same calls, such as RedisJSON's RedisJsonFormatter for INDENT/NEWLINE/SPACE.

What changes is how the work is done:

  • Escaping: strings are scanned for bytes that need escaping (", \, bytes below 0x20) eight bytes at a time. A clean run is written with one write_string_fragment call, and escapes are mapped through serde_json's own escape table.
  • Typed arrays: they are written straight from their slices, with no IValue built per element.
  • No Serialize/Serializer indirection per value.

Memory: nothing changes per value or per document; the writer only reads.

Why

Whole-document JSON.GET ($, or legacy GET with no path) serialises the full document. On RedisJSON 8.12.0, serde_json::ser::format_escaped_str, which scans one byte at a time, is about 35 % of server CPU samples for JSON.GET key $ on a 38 KB document.

Benchmarks

benches/callpaths.rs gains serialise/native-compact and serialise/native-indent rows next to the existing serde_json compact/indent rows. The two rows for a document produce the same bytes.

cargo bench --bench callpaths --no-default-features -- serialise/, AWS Graviton4 (Neoverse-V2), pinned to one core, rustc 1.92, one run, criterion median, µs:

Fixture compact (serde_json) native-compact Δ indent (serde_json) native-indent Δ
yelp 26.29 13.07 −50.3 % 32.55 21.07 −35.3 %
yahoo2 13.11 6.98 −46.7 % 17.32 10.82 −37.6 %
gmaps-place 110.36 50.85 −53.9 % 222.61 163.13 −26.7 %
refsnp-400 (NDJSON) 276.62 190.49 −31.1 % 416.41 346.36 −16.8 %
floats-1024 48.77 16.63 −65.9 % 53.67 19.85 −63.0 %
ints-1024 14.84 7.57 −49.0 % 18.02 9.90 −45.1 %
int-arrays 12.39 6.25 −49.5 % 16.13 9.39 −41.7 %
parser-0000 2.32 1.48 −35.9 % 3.45 2.48 −28.0 %
pass-100 0.53 0.37 −30.6 % 1.19 1.04 −13.1 %

A separate harness ran 3 interleaved rounds over 52 serialise cases on the same CPU, and every case was faster. The worst case was a synthetic string dense with escapes, at −6.3 %.

RedisJSON server (for context; it needs the follow-up call-site change below). RedisJSON 8.12.0 at this ijson base, with vs without the writer on the JSON.GET path. Server CPU per request, one pinned core, median of 3 interleaved runs:

Workload Before µs/req After µs/req Δ
whole-document GET, 38 KB (yelp) 47.8 37.5 −21.7 %
whole-document GET (yahoo2) 28.4 23.0 −18.9 %
whole-document GET (ncbi-refsnp) 14.4 13.0 −9.5 %
session-caching mix (90 % GET / 10 % SET) 10.0 9.6 −4.7 %
multipath GET / recursive descent (not on this path) within noise

Server replies were byte-identical across 120 commands, and used_memory was unchanged.

Other operations (guard). The writer touches no other code path, so I also A/B'd the parse, lookup, mutate, typed-array, clone/drop and CBOR benchmark groups, with the thread-safe string cache that RedisJSON uses (2 rounds, same CPU).

  • No row changed significantly; the smallest p was 0.057.
  • The ijson rows drifted less than the serde_json control rows, whose code is identical in both builds: 29 vs 52 rows moved by more than 3 %, with medians of +0.04 % and −0.08 %.
  • Three small clusters read +3…6 % (typed sum i8/i16, typed parse i32/i64) and one lookup iterate row +20 %. Their code is unchanged, so I read this as code-layout noise, but that is not proven; they are worth a re-run if anyone sees a change there.

Correctness

  • tests/json_writer_diff.rs:
    • a seeded differential test against serde_json on random documents, covering objects, arrays, every number kind, typed arrays and escape-heavy strings, in compact and pretty modes;
    • a test that every ASCII byte (below 0x80), at every offset of strings around the 8-byte word size, escapes exactly as serde_json does;
    • typed float arrays (f16, bf16, f32, f64) against serde_json.
  • fuzz/fuzz_targets/fuzz_json_writer.rs: fuzzes the writer against serde_json, and is added to the CI fuzz matrix.
  • cargo test -- --test-threads=1 passes in both the default and thread_safe builds, as in CI.
    • The new integration test shares the global string cache, so like the existing tests it needs --test-threads=1 in the default build.
  • Benchmarks build in both configurations.

Not in this PR

  • RedisJSON call site. Calling ijson::write_json from the JSON.GET serialise path is a separate RedisJSON change, made after this lands and the pin is bumped.
  • Other platforms. Only Neoverse-V2 (arm64) was measured; x86-64 is not.

🤖 Generated with Claude Code


Note

Medium Risk
New serialization path must match serde_json on all value shapes (numbers, escapes, typed arrays); extensive differential/fuzz coverage mitigates but regressions would affect JSON.GET-style outputs once wired.

Overview
Adds a native JSON writer (ijson::to_vec, to_writer, to_string, write_json) that walks IValue directly instead of Serialize, while driving the same serde_json::ser::Formatter calls so output stays byte-identical to serde_json. Optimizations include 8-byte SIMD-style escape scanning, typed-array slice serialization without per-element IValues, and reuse of find_shortest_roundtrip_f64 (now pub(crate)) for f16/bf16 arrays.

Testing & CI: differential integration tests (tests/json_writer_diff.rs), a shared recording_formatter that compares formatter call sequences, unit tests in json_writer.rs, a new fuzz_json_writer target in the fuzz matrix, and serialise benchmark rows native-compact / native-indent beside the existing serde_json paths.

Reviewed by Cursor Bugbot for commit fde4ec8. Bugbot is set up for automated code reviews on this repo. Configure here.

fcostaoliveira and others added 2 commits December 1, 2026 22:05
`ijson::{to_writer, to_vec, to_string, write_json}` write an `IValue` as JSON text
by walking it directly instead of going through `Serialize`. The output is
byte-identical to serde_json's: every token is written through the same
`serde_json::ser::Formatter` call, in the same order, so numbers still go through
ryu/itoa and a custom formatter (indent, newline, space) sees the same calls.

- Strings are scanned for bytes to escape eight bytes at a time; a clean run is
  written with one `write_string_fragment` call. Escapes use serde_json's table.
- Typed (homogeneous numeric) arrays are written from their slices.
- No per-value memory change: the writer only reads the value.

Tests: a seeded differential test against serde_json (both builds), an
every-byte escape test, and a `fuzz_json_writer` target. Benchmarks:
`serialise/native-compact` and `serialise/native-indent` rows next to the
existing serde_json rows in `benches/callpaths.rs`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fcostaoliveira
fcostaoliveira marked this pull request as ready for review December 2, 2026 00:56
Comment thread src/json_writer.rs Resolved

@AvivDavid23 AvivDavid23 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! one small comment, and two extras:

1:
The PR promises that every Formatter call matches serde_json's, but the diff tests and the fuzzer only compare output bytes with CompactFormatter/PrettyFormatter. A write_i64 vs write_u64 mix-up, or a different split of write_string_fragment calls, would produce the same bytes and pass. Could we add a small recording Formatter that logs (method, args) and assert the native and serde logs are equal, reusing it in fuzz_json_writer?

2:
The integer typed-array arms (I8..U64) don't seem to be tested directly. random_value almost never produces I16/U16/U32 storage, the unit tests have no U16 ([40000]), U32 ([3000000000]) or I8 ([-1, 2]) cases, and the ints literal mixes i64::MIN with u64::MAX, so I think it may be stored as a heterogeneous array — is that right? Could we add an explicit differential check over IArray::from(Vec<iN/uN>) for each width, including the edges (u64::MAX, i64::MAX as u64 + 1, i64::MIN)?

@fcostaoliveira

Copy link
Copy Markdown
Author

Addressed all three requests in fde4ec8.

  • to_vec, to_string, and to_vec_with_formatter now return io::Result. An injected formatter error propagates to the caller, including when the destination is a vector.
  • The differential suite and fuzz_json_writer share a recording formatter that compares callback names, order, and arguments. We checked it in two scratch builds. Changing an in-range U64 element from write_i64 to write_u64, or splitting one ASCII string fragment into two, preserved the JSON bytes. Each change failed both the new differential assertion and a fixed-input fuzz replay.
  • The deterministic test constructs all eight integer widths with IArray::try_from(Vec<T>), asserts the actual storage tag, and exercises the signed/unsigned boundary and extrema. Your reading of the original mixed literal was correct. It becomes heterogeneous when the final u64::MAX is appended.

Independent CI ran the pristine unit and integration suites in both feature modes with serde_json 1.0.146 and 1.0.154. The writer fuzzer also completed 20,000 executions per mode with 1.0.146.

Upstream build, bench compilation and all six fuzz jobs passed. The first memory gate observed 1,280 → 1,368 bytes on three thread_safe parse/decode metrics for pass-100. The unmodified gate passed on repeat at the same head. In a separate local check, 31 alternating runs of each fixed binary gave the same median (1,348 bytes) and range (1,260–1,392 bytes) on all three metrics. These are parse/decode measurements. First CI attempt · Repeat

@fcostaoliveira
fcostaoliveira merged commit 8489133 into RedisJSON:master Dec 3, 2026
16 of 17 checks passed
@fcostaoliveira
fcostaoliveira deleted the native-json-writer branch December 3, 2026 14:49
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.

2 participants