Skip to content

Parse float arrays into F64 storage without boxing each element - #32

Closed
fcostaoliveira wants to merge 6 commits into
RedisJSON:masterfrom
fcostaoliveira:pr/float-arrays-no-boxing
Closed

fcostaoliveira wants to merge 6 commits into
RedisJSON:masterfrom
fcostaoliveira:pr/float-arrays-no-boxing

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Nov 25, 2026 •

Copy link
Copy Markdown

Summary

When the compact parser reads a JSON array of floats, every element goes through ValueVisitor::visit_f64. That builds a boxed F64 INumber, which IArray::push then unboxes into the array's F64 storage before freeing the box. On a 1,024-float array that is 1,023 malloc/free pairs, each used for a value that ends up stored inline in the array anyway.

This PR adds IArray::push_f64_direct(&mut self, f64) -> bool (#[inline(never)]). It writes the value straight into an array that is already F64-tagged and non-empty, and refuses in every other state. ArrayVisitor::visit_seq now branches once on fpha_config:

  • The Some arm is the existing FPHA loop, unchanged.
  • The None arm drives a new ArrayElemSeed, whose visitor arms are ValueVisitor's arms wrapped in Some. Its visit_f64 tries push_f64_direct first and returns None when that succeeds. push stays in the visit_seq loop for every element the seed returns.

Tag selection, promotion, retagging, number formatting, interning, CBOR and defrag are untouched. The direct path fires only in the state where prepare_for_item would already have found can_push_directly(F64) true, so it writes the same value into the same slot as the boxed path did.

In RedisJSON this is the JSON.SET parse path: ivalue_manager::from_str → IValueDeserSeed::deserialize_compact_objects, for any document that contains float arrays.

Code size: library +166/−8 in 2 files (src/array.rs, src/de.rs). Tests +372, in the src/array.rs and src/de.rs test modules.

Coverage of changed lines: 92/92 (100%) of the instrumented changed library lines, in both the default and thread_safe builds (cargo llvm-cov --no-default-features [--features thread_safe] --lib -- --test-threads=1, intersected with the + lines of this diff above each file's test module).

Measurements

Criterion microbenchmarks that mirror RedisJSON's call paths (default-features = false, string cache initialised as OSS RedisJSON does, system allocator, cargo bench profile, rust 1.92). Base and candidate ran interleaved, three times each. Δ is the median over the three pairs, and the spread column is the base's own run-to-run spread.

x86-64, Intel Sapphire Rapids, Linux, bench pinned to one core

Benchmark Base Candidate Δ Base spread
parse/compact-objects/floats-1024 39.90 µs 21.71 µs −45.6% 0.5%
parse/compact-objects/int-arrays 25.86 µs 23.91 µs −7.6% 0.2%
parse/compact-objects/ints-1024 28.16 µs 26.92 µs −4.4% 1.0%
parse/compact-objects/gmaps-place 291.52 µs 283.40 µs −2.8% 0.1%
parse/compact-objects/yelp 67.06 µs 66.29 µs −1.1% 0.4%
parse/compact-objects/yahoo2 35.41 µs 35.22 µs −0.5% 0.2%
parse/compact-objects/parser-0000 6.91 µs 6.87 µs −0.5% 1.0%
parse/compact-objects/pass-100 1.46 µs 1.47 µs +0.4% 0.4%
parse/fpha-f32/floats-1024 (FPHA loop, unchanged) 43.13 µs 43.32 µs +0.4% 0.4%
typed/build-f64-push-1024 19.55 µs 19.58 µs +0.1% 1.0%
typed/build-i64-try-extend-16k 3.54 µs 3.44 µs −2.7% 3.0%
typed/retag-on-string-push-1024 14.76 µs 14.52 µs −1.6% 1.0%
typed/slice-sum-f64-1024 490.5 ns 490.5 ns −0.0% 0.0%

Memory: retained bytes are identical on every fixture. Parse allocations fall on the fixtures that contain floats: floats-1024 1,033 → 10, int-arrays 367 → 315, gmaps-place 3,524 → 3,522. Peak on floats-1024 goes from 8,208 to 8,200 B.

TMA (Linux, toplev level 2, 20 s windows, CPU-pinned), parse/compact-objects/floats-1024 and parse/fpha-f32/floats-1024:

                      floats-1024           fpha-f32/floats-1024
                      base    candidate     base    candidate
Frontend_Bound       12.4%*    30.2%        30.5%     30.7%
Bad_Speculation       3.8%      3.7%         3.8%      3.5%
Backend_Bound        47.8%     47.1%        47.8%     48.9%
  Memory_Bound       29.0%     28.1%        28.7%     31.3%
  Core_Bound         18.8%     19.0%        19.1%     17.6%
Retiring             17.5%     19.1%        17.9%     16.8%

* The base floats-1024 capture sums to 81.5%. Its missing 18.5 points belong to a Frontend window that toplev dropped, so only the other three categories of that pair can be compared. They hold their shares while the time halves. That means the saving is retired work (one heap allocation and one free per element removed), not a different bottleneck. On fpha-f32 the two shapes agree within 1.1 points, which fits an unchanged time.

Things worth knowing

  • When the fast path fires. ArrayTag::from_ivalue tags a float array by the narrowest exact float type of its first element, and the array stays narrow until a value needs f64. So:

    • The first element of every float array is still boxed.
    • Arrays of "decimal" floats (0.1, 3.14159, coordinates, prices) are F64 from the start and take the fast path from their second element on.
    • Arrays of dyadic values (1.5, 2.25) stay F16/F32-tagged and take today's boxed path, as before.
  • The integer path also got faster (ints-1024 −4.4%, int-arrays −7.6%). This is a side effect of the split, not a designed property. The per-element instantiation of deserialize_any shrank from a 7,238 B function that also contains the array loop to a 1,388 B ArrayElemSeed::deserialize. A later change to de.rs could take that gain back.

  • gmaps-place came out at −2.8%, below the 3% I predicted before measuring. It is reported as measured.

  • This branch drops two #[inline] attributes (on IArray::push and push_with_fp_type) that an earlier variant carried. With them, parse/fpha-f32/floats-1024 was +1.9% / +2.4% slower in two separate runs (spread ≤ 0.1%). Without them it reads +0.4% (spread 0.4%), and the other gains are unchanged.

  • Two benchmarks that never execute this code moved in the one full-suite pair:

    • serialise/compact/* +6…+31% while serialise/indent/* moved −4…−17%.
    • clone-drop/clone/floats-1024 +20.8%.

    The benchmark record attributes these to binary layout on this host, not to this change. serialise/compact/yelp is bimodal with layout there, and the base binary itself read 83.8 ns on the clone benchmark in an earlier sweep. I'm flagging them rather than hiding them.

  • Tests: cargo test --no-default-features --lib -- --test-threads=1 passes on this branch: 139 tests in the default build, 134 with thread_safe, plus the doc test. cargo fmt --check is clean. cargo clippy --no-default-features reports one lint on the new code (len() == 0 in push_f64_direct, the same lint push already carries); the rest matches master. Some tests drive the seed's visit_string/visit_bytes/visit_none/visit_some arms through a test deserializer, because serde_json never calls them. The same library code was fuzzed with the existing fuzz_json_de target (1.31 M executions) and with a number-grammar target kept out of this PR (5.68 M executions): 0 crashes.

The benchmark suite and the full experiment record, including the rejected variants, live in the redis-performance/json-agent-workspace repository: EXP-001e. The end-to-end numbers below were measured with the same library code (the experiment branch differs from this one only by the benchmark harness).

End to end in RedisJSON

Setup:

  • RedisJSON 9ca1c88, built unchanged twice: against its pinned ijson (379dadf) and against this change, through a Cargo [patch] only.
  • redis-server and memtier on the same host (x86-64, Intel Sapphire Rapids, Linux), server and client on separate cores.
  • memtier -c 16 -t 2, 15 s per run, 16 workloads, three interleaved rounds per module, ops/s. All 96 runs finished with zero errors.

Only commands that moved by 3% or more are listed.

Command Workload pinned ijson ops/s this PR ops/s Δ throughput p50 ms
JSON.SET floats $ '<1,024-float array>' (11.7 KB, the floats-1024 fixture) 20,893 34,894 +67.0% 1.343 → 0.799
JSON.GET jsonsl-yelp $ (whole 38 KB document) 17,348 15,065 −13.2% ⚠ 1.503 → 1.695

Base spreads: 0.2% and 0.6%.

Memory: retained memory is identical. JSON.DEBUG MEMORY floats is 8,208 bytes on both modules and JSON.ARRLEN is 1,024 after every round, so the stored array is the same F64-typed array. The change only removes transient allocations (one box per float element during parse).

⚠ JSON.GET $ serialises the document and never parses a number, so this change is not on its path. Branches that do not touch serialisation either read the same −13% on this workload. It is code placement in the module binary: when both modules are built with 64-byte function and block alignment, the same workload reads +0.4% for one of those branches, and −13.9% becomes −0.5% for another. It is listed here rather than hidden.

Unchanged (|Δ| < 3%, the other 14 workloads): every one is within ±2.1% (base spreads 0.1–2.0%). That includes JSON.SET of the 18 KB yahoo2 document (782 → 782 ops/s), which contains no float arrays, and the pipelined fresh JSON.SET of the 38 KB yelp document (+0.9%).

Raw memtier output, per-round checks and the module build log: experiments/EXP-001e-no-inline-hints/e2e. The placement analysis is in experiments/GATE-2026-11-25.md.

🤖 Generated with Claude Code


Note

Medium Risk
Changes the hot JSON array parse path and uses unsafe direct writes into typed storage, though behavior is gated and heavily tested against the prior push semantics.

Overview
Adds a fast path for homogeneous F64 JSON arrays during compact parsing: after the first float establishes F64 storage, later elements can be written with IArray::push_f64_direct instead of boxing an IValue per number.

ArrayVisitor::visit_seq now branches on FPHA config. When FPHA is unset, parsing uses a new ArrayElemSeed whose visit_f64 tries the direct append and returns None on success so the loop skips push; all other value types still go through the existing boxed push path, preserving tag promotion and retagging.

Also wires in src/adversarial_tests.rs (~800 lines) under #[cfg(test)] for collision floods, malformed CBOR, nesting, and number edge cases, plus focused tests in de.rs/array.rs that equate parse output with the push path and assert far fewer allocations on large float arrays.

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

fcostaoliveira and others added 5 commits November 25, 2026 17:02
…he loop

The per-element cost EXP-001/001b/001c added on integer arrays was lost
inlining in serde_json's number dispatch (perf annotate on the Linux
referee: ParserNumber::visit became an out-of-line call with the visitor
passed by pointer, +38 instructions per integer element). ArrayElemSeed is
now ValueVisitor with one difference: visit_f64 tries
IArray::push_f64_direct (out of line, infallible) and yields None when the
float was written straight into the array's F64 storage; every other
element is returned as Some(value) and pushed by the visit_seq loop as
before. FPHA arrays keep the referee loop untouched.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Parsed arrays are compared with the same arrays built by boxing every
element and calling IArray::push (values, tags, serialisation, equality),
the direct path's allocation count is checked, the FPHA loop is checked to
keep its forced type, and push_f64_direct's refusal states are covered.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
A test Deserializer drives visit_string, visit_bytes, visit_byte_buf, visit_none, visit_some, visit_unit and visit_i128 (which reaches expecting) through ArrayElemSeed inside an F64-tagged array and compares each outcome with ValueVisitor's at top level: same value (owned strings, null for none/unit, boxed floats through visit_some, null for non-finite floats) or the same rejection (byte strings, i128). Coverage of the branch's production lines: 72/92 -> 92/92 in both feature sets. Test-only.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Add src/adversarial_tests.rs (hash-collision clusters at 8/16/128/4096 keys,
degenerate keys, duplicate-key floods, deep nesting, number edge cases, clone
and entry invariants, malformed/truncated CBOR, stream reference bounds) under
#[cfg(test)], formatted with rustfmt. Public-API only; no production code
touched.

(Cherry-picked without the two fuzz targets of the original commit,
fuzz_object_entry_remove and fuzz_json_de_numbers, to keep this branch to
src/.)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…with_fp_type

The two hints were added in EXP-001b for typed/ and parse/fpha-f32 regressions that
EXP-014 and the EXP-001d re-run attribute to code placement; EXP-001d's only
reproducible overshoot (parse/fpha-f32/floats-1024 +1.9..+2.4 %) sits on the path
whose codegen they change. No logic change.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@fcostaoliveira
fcostaoliveira marked this pull request as draft November 25, 2026 17:07
src/adversarial_tests.rs covers collisions, clone/entry invariants and CBOR
across the whole crate, not the float-array change; it belongs in its own
PR. The change keeps its own tests in src/array.rs and src/de.rs, which
still cover 92/92 of the changed library lines in both builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fcostaoliveira

Copy link
Copy Markdown
Author

Closing. A re-measurement on this exact head still shows a benchmark or end-to-end row more than 3% worse than base, which is our bar for proposing a change. I will reopen or resubmit once that row is resolved.

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