Skip to content

Build the inline IString handle in a register instead of a stack buffer - #33

Merged
fcostaoliveira merged 4 commits into
RedisJSON:masterfrom
fcostaoliveira:pr/inline-string-in-register
Nov 30, 2026
Merged

fcostaoliveira merged 4 commits into
RedisJSON:masterfrom
fcostaoliveira:pr/inline-string-in-register

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Nov 25, 2026 •

Copy link
Copy Markdown

Summary

IString::intern turns every non-empty string of 7 bytes or fewer into an inline handle (the length goes in the tag byte, the text in the other 7 bytes) through IString::new_inline_string. Before this change, that function filled a stack [u8; 8] with one byte store and a variable-length copy_from_slice, then read the buffer back as a word. For 1–7 bytes the copy_from_slice is an out-of-line memcpy call, and the compiler splits the reload into 1/2/4-byte loads that sit right behind the narrower stores. perf annotate of a short-key lookup put 27.6% of all samples on that reload line and about 6% in libc memcpy.

This PR builds the same word in a register:

  • 4–7 bytes: two overlapping little-endian 4-byte loads (the overlap holds identical bytes), shifted and ORed.
  • 1–3 bytes: byte loads, shifts and ORs.
  • usize::from_le keeps the layout that usize::from_ne_bytes gave before on every endianness. On little-endian targets it compiles to nothing.

The representation does not change. Equality, hashing, ordering, the string cache, CBOR and defrag are untouched. The tests check that the new code produces bit-identical handles to the previous construction for every length.

In RedisJSON this is the key intern on every path step (JSON.GET, JSON.SET, JSON.MERGE, JSON.NUMINCRBY, ...), where short query keys become inline handles, and the parse path, which interns every short object key. thread_safe builds use a different IString and are not affected. RedisJSON builds without thread_safe.

Code size: +30/−6 library lines in 1 file (src/unsafe_string.rs), plus 118 test lines.
Coverage of changed lines: 16/16 (100%) of the instrumented changed library lines in the default build. src/unsafe_string.rs is not compiled with thread_safe, so that build has no changed lines.

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. The lookup/* rows were re-run as a second, independent set of three pairs (r2).

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

Benchmark Base Candidate Δ Base spread Δ (r2)
lookup/wide-128-hit-short-key 55.6 ns 39.7 ns −28.6% 0.5% −28.7%
lookup/path-chain-yelp 56.4 ns 42.1 ns −25.3% 0.1% −26.0%
lookup/small-8-hit-last 15.9 ns 14.1 ns −11.7% 1.7% −11.4%
lookup/wide-128-hit-long-key 72.9 ns 70.9 ns −2.8% 0.0% −0.3%
lookup/small-8-miss 57.5 ns 57.5 ns +0.0% 0.0% +0.3%
lookup/wide-128-miss-long-key 158.6 ns 158.6 ns +0.0% 0.0% +0.1%
lookup/typed-array-slice-index-f64-x64 21.6 ns 21.6 ns +0.0% 0.1% +0.0%
lookup/business-22-hit 56.4 ns 57.9 ns +2.6% 0.7% −0.4%
lookup/business-22-miss 69.8 ns 71.3 ns +2.1% 0.1% +0.3%
mutation/merge-26-into-54-occupied 1.90 µs 1.36 µs −28.2% 0.2%
mutation/object-insert-remove-22 146.2 ns 135.7 ns −7.2% 2.6%
parse/compact-objects/pass-100 1.47 µs 1.39 µs −4.8% 30.3%
parse/compact-objects/yahoo2 35.49 µs 34.93 µs −1.6% 3.5%
parse/compact-objects/yelp 67.40 µs 66.49 µs −1.3% 2.8%

Memory: identical. Every retained, peak and allocation count in the memory benchmark is unchanged. An inline handle is a tagged word, so no allocation was involved before or after.

TMA (Linux, toplev level 2, 20 s windows, CPU-pinned), lookup/small-8-hit-last (first run) and lookup/path-chain-yelp (r2):

                      small-8-hit-last      path-chain-yelp
                      base    candidate     base    candidate
Frontend_Bound       32.0%     31.0%        31.4%     29.0%*
  Fetch_Latency      27.8%     26.8%        27.4%      8.9%*
  Fetch_Bandwidth     4.2%      4.2%         4.1%      4.4%
Bad_Speculation       3.1%      3.4%         3.1%      3.2%
Backend_Bound        51.4%     51.4%        51.2%     51.8%
  Memory_Bound       33.6%     35.2%        34.4%     34.5%
  Core_Bound         17.7%     16.2%        16.9%     17.2%
Retiring             13.5%     14.2%        14.2%     16.0%

Every capture sums to 100.0% of slots at level 1.

* In the candidate path-chain-yelp capture, the Frontend_Bound children add up to 13.3%, not 29.0%. One level-2 Frontend window was not recorded, so only that capture's level-1 Frontend_Bound value can be compared.

The bottleneck shape stays the same while the time falls by 12% and 26%. Retiring gains 0.7 and 1.8 points. That fits fewer µops on the critical path (no memcpy call, no stack round trip), not a different bottleneck. parse/compact-objects/yelp was also captured: every category stays within 0.5 points, which matches its unchanged time.

End to end in RedisJSON

Setup (re-measured on this PR's head, 2026-11-25):

  • RedisJSON 9ca1c88, built unchanged against pinned ijson (379dadf) and against this head (Cargo [patch] only), each built twice: the normal build, and with 64-byte function and block alignment (-C llvm-args=-align-all-functions=6 -C llvm-args=-align-all-nofallthru-blocks=6) so that code placement in the module cannot move a result.
  • Pinned redis-server (x86-64, Intel Sapphire Rapids, Linux), memtier -c 16 -t 2, 15 s runs, three interleaved rounds per cell, the 14 standard workloads. An A/A check (pinned ijson against an identical rebuild, and against itself) stays within ±1.2% unaligned and ±1% aligned.
Workload unaligned: pinned ijson ops/s unaligned: this PR Δ aligned: pinned ijson ops/s aligned: this PR Δ
JSON.ARRAPPEND wildcard, GeoJSON 46,960 46,720 −0.5% 47,244 47,903 +1.4%
DUMP+RESTORE, yahoo2 31,897 32,326 +1.3% 33,090 32,862 −0.7%
DUMP, yelp 12,978 13,088 +0.8% 13,414 13,383 −0.2%
JSON.GET multi-path, yelp 52,435 53,124 +1.3% 53,127 53,586 +0.9%
JSON.GET wildcard reviews[*].user_name 84,952 85,025 +0.1% 84,482 86,357 +2.2%
JSON.GET $, whole yelp 17,458 17,436 −0.1% 17,301 17,234 −0.4%
JSON.GET single path, yelp 153,009 152,608 −0.3% 152,533 153,762 +0.8%
JSON.MERGE wildcard, 26-key patch 17,595 20,204 +14.8% 17,559 20,381 +16.1%
JSON.NUMINCRBY single path 156,504 157,317 +0.5% 156,834 155,302 −1.0%
JSON.NUMINCRBY wildcard 97,650 97,762 +0.1% 97,177 97,721 +0.6%
JSON.GET $..uid, 633 KB document 1,345 1,386 +3.1% 1,322 1,381 +4.5%
JSON.SET wildcard, 26-key object 24,631 27,051 +9.8% 24,916 27,231 +9.3%
JSON.SET $, whole yahoo2 ¹ 782 782 +0.0% 782 782 −0.0%
JSON.SET single path, yelp 144,688 144,627 −0.0% 144,642 145,009 +0.3%

¹ Client-bound: memtier writes this 18 KB request in two parts and the second waits for the server's delayed ACK (~41 ms p50), so this row measures the client, not JSON.SET. Without the stall (a 14.6 KB document) no build is worse than −1.9%.

No workload is worse than 0.5% in the normal build or 1.0% in the aligned build. The gains are the commands that intern many short keys: wildcard JSON.MERGE of a 26-key patch +14.8% / +16.1% and wildcard JSON.SET of a 26-key object +9.8% / +9.3% (normal / aligned build). The 26 one-letter keys become inline handles once per key per target. Memory is identical: JSON.DEBUG MEMORY of a fresh yelp document is 16,234 bytes on both modules.

Microbenchmark re-run on this head (3 interleaved pairs, both builds): serialise/compact/yahoo2 −0.6% / +1.1%.

Raw data: https://github.com/redis-performance/json-agent-workspace/tree/night/2026-11-24/experiments/REMEASURE-2026-11-25-pr-heads

Things worth knowing

  • Where it pays. The gain shows up on operations that intern a short key and then do little else, such as a path step or merge's per-key lookup, where the constructor is a big share of a 15–60 ns operation. In parse it is one call per key among allocation, hashing and table inserts, so parse/compact-objects/yelp and yahoo2 do not move (−1.3% / −1.6%, inside their spread). I predicted ≥ 3% on those two before measuring, and that prediction was wrong. I also predicted ≥ 20% on small-8-hit-last, and it came in at −11.7%. What is left of intern there is the length dispatch and the tag work, not the copy.
  • Keys of 8 bytes or more are not affected. The business-22 lookups use keys like "review_count" and "business_id", which are heap strings. Their first-run +2.6% / +2.1% did not reproduce in r2 (−0.4% / +0.3%, spreads 0.2% / 0.1%). A one-run full sweep had shown business-22-miss at +15.1%; the three-pair runs put it within spread both times.
  • Why the old construction was slow is my reading, not a sourced claim: a byte store plus a 1–7 byte memcpy into an 8-byte stack slot, followed by a wide reload, is the narrow-stores-then-wide-load shape that store forwarding handles worst. The memcpy was also an out-of-line call.
  • Safety. The unsafe contract of new_inline_string is unchanged (1..=7 bytes of valid UTF-8). A debug_assert! now states the length range. All slice indexing is bounds-checked safe code.
  • Tests: cargo test --no-default-features --lib -- --test-threads=1 passes: 136 tests in the default build, 129 with thread_safe. Two tests are new:
    • inline_handle_matches_reference_construction_for_every_length keeps the replaced byte-buffer algorithm as a reference. For 18 samples (NUL bytes, 2-, 3- and 4-byte UTF-8, \u{7f}, the 7/8-byte boundary against a heap string) it checks the handle bits, as_str, len, equality, hashing and ordering against str.
    • inline_handle_round_trips_generated_strings_at_every_length does the same for 4,000 deterministic 1–7 byte strings that mix UTF-8 widths.
  • Other checks: Miri (nightly) passes on both new tests. Its one warning is the integer-to-pointer cast in IValue::new_ptr(data as *mut u8, …), which master has on the same line. The same library code was fuzzed with fuzz_json_de (1.36 M executions) and fuzz_object_ops (1.32 M executions): 0 crashes. cargo fmt --check is clean, and cargo clippy --no-default-features reports the same findings as on master, with none new.

The benchmark suite and the full experiment record, including raw criterion output, TMA captures and the memtier runs, live in the redis-performance/json-agent-workspace repository: EXP-020. Those numbers were measured on the experiment branch, which carries the same two commits on top of the benchmark harness.

🤖 Generated with Claude Code


Note

Low Risk
Representation and intern paths are unchanged except construction of ≤7-byte inline handles; new tests assert bit-identical behavior to the prior algorithm.

Overview
Rewrites new_inline_string so short (1–7 byte) inline IString handles are assembled in registers with shifts and overlapping u32 loads, instead of filling an 8-byte stack buffer via copy_from_slice / memcpy and reloading the word. The bit layout is unchanged; usize::from_le preserves the previous native-endian layout. A debug_assert! enforces the length range.

Adds tests that keep the old byte-buffer algorithm as inline_handle_reference, then verify bit-identical handles, as_str, and equality/hash/cmp behavior for sampled and 4,000 generated strings, including the 7 vs 8 byte inline/heap boundary.

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

fcostaoliveira and others added 2 commits November 25, 2026 17:02
…(EXP-020)

The inline handle (len in the tag byte, up to 7 text bytes) was built in a
stack [u8; 8]: a byte store, a variable-length copy_from_slice (a memcpy
call for 1..=7 bytes) and a reload of the whole word, which the compiler
split into 1/2/4-byte loads that cannot be forwarded from the narrower
stores. perf annotate of lookup/small-8-hit-last put 27.6% of all samples
on that reload line and ~6% in libc memcpy.

Build the word from two overlapping 4-byte little-endian loads (4..=7
bytes) or 1..=3 byte loads, shifts and ORs; usize::from_le keeps the
previous usize::from_ne_bytes layout on every endianness. Representation
unchanged, so equality, hashing, ordering and the string cache are
untouched; tests pin bit-identity with the previous construction for
every length and compare inline/inline, inline/heap and the 7/8-byte
boundary against str.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@fcostaoliveira
fcostaoliveira marked this pull request as draft November 25, 2026 17:07
@fcostaoliveira
fcostaoliveira marked this pull request as ready for review November 26, 2026 02:50
…tring-in-register

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread src/unsafe_string.rs Outdated
lo | (hi << (8 * (len - 4)))
} else {
let mut t = bytes[0] as u64;
if len > 1 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

can you change it to pattern matching with match ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done in abfee65: text is now chosen by match len { 4..=INLINE_STRING_MAX_LEN => …, 1..=3 => …, _ => unreachable!() }.

I kept the 1..=3 arm byte by byte, not one arm per length, for this reason. With separate 1/2/3 arms the compiler emits a different short-string path: a 2-byte load per arm, with more branches. That is the path the 3-byte-key lookups in this PR's numbers go through, so the measurements would no longer describe the code.

As written, the emitted x86-64 code of IString::intern matches the previous head instruction for instruction (release, --no-default-features, codegen-units=1). The only difference is a panic location's line number. The unit tests pass single-threaded in both the default and thread_safe builds.

If you'd prefer one arm per length, I can do that and re-measure.

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

One small comment.

The 4..=7 and 1..=3 byte cases are now match arms. The 1..=3 arm keeps its byte-by-byte
assembly: a separate arm per length made the compiler emit a different 1..=3 byte path
(a 2-byte load per arm), which is the path the 3-byte-key lookups measure. As written, the
emitted x86-64 code of IString::intern is unchanged (release, --no-default-features,
codegen-units=1); only a panic location's line number differs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fcostaoliveira
fcostaoliveira merged commit 8be55fa into RedisJSON:master Nov 30, 2026
8 checks passed
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