Repository navigation
Build the inline IString handle in a register instead of a stack buffer - #33
fcostaoliveira merged 4 commits into
Conversation
…(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>
…tring-in-register Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| lo | (hi << (8 * (len - 4))) | ||
| } else { | ||
| let mut t = bytes[0] as u64; | ||
| if len > 1 { |
There was a problem hiding this comment.
can you change it to pattern matching with match ?
There was a problem hiding this comment.
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.
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>
Summary
IString::internturns 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) throughIString::new_inline_string. Before this change, that function filled a stack[u8; 8]with one byte store and a variable-lengthcopy_from_slice, then read the buffer back as a word. For 1–7 bytes thecopy_from_sliceis an out-of-linememcpycall, and the compiler splits the reload into 1/2/4-byte loads that sit right behind the narrower stores.perf annotateof a short-key lookup put 27.6% of all samples on that reload line and about 6% in libcmemcpy.This PR builds the same word in a register:
usize::from_lekeeps the layout thatusize::from_ne_bytesgave 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_safebuilds use a differentIStringand are not affected. RedisJSON builds withoutthread_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.rsis not compiled withthread_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. Thelookup/*rows were re-run as a second, independent set of three pairs (r2).x86-64, Intel Sapphire Rapids, Linux, bench pinned to one core
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) andlookup/path-chain-yelp(r2):Every capture sums to 100.0% of slots at level 1.
* In the candidate
path-chain-yelpcapture, 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
memcpycall, no stack round trip), not a different bottleneck.parse/compact-objects/yelpwas 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):
9ca1c88, built unchanged against pinnedijson(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.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.JSON.ARRAPPENDwildcard, GeoJSONDUMP+RESTORE, yahoo2DUMP, yelpJSON.GETmulti-path, yelpJSON.GETwildcardreviews[*].user_nameJSON.GET $, whole yelpJSON.GETsingle path, yelpJSON.MERGEwildcard, 26-key patchJSON.NUMINCRBYsingle pathJSON.NUMINCRBYwildcardJSON.GET $..uid, 633 KB documentJSON.SETwildcard, 26-key objectJSON.SET $, whole yahoo2 ¹JSON.SETsingle path, yelp¹ 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.MERGEof a 26-key patch +14.8% / +16.1% and wildcardJSON.SETof 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 MEMORYof 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
parse/compact-objects/yelpandyahoo2do 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% onsmall-8-hit-last, and it came in at −11.7%. What is left ofinternthere is the length dispatch and the tag work, not the copy.business-22lookups 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 shownbusiness-22-missat +15.1%; the three-pair runs put it within spread both times.memcpyinto an 8-byte stack slot, followed by a wide reload, is the narrow-stores-then-wide-load shape that store forwarding handles worst. Thememcpywas also an out-of-line call.unsafecontract ofnew_inline_stringis unchanged (1..=7 bytes of valid UTF-8). Adebug_assert!now states the length range. All slice indexing is bounds-checked safe code.cargo test --no-default-features --lib -- --test-threads=1passes: 136 tests in the default build, 129 withthread_safe. Two tests are new:inline_handle_matches_reference_construction_for_every_lengthkeeps 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 againststr.inline_handle_round_trips_generated_strings_at_every_lengthdoes the same for 4,000 deterministic 1–7 byte strings that mix UTF-8 widths.IValue::new_ptr(data as *mut u8, …), whichmasterhas on the same line. The same library code was fuzzed withfuzz_json_de(1.36 M executions) andfuzz_object_ops(1.32 M executions): 0 crashes.cargo fmt --checkis clean, andcargo clippy --no-default-featuresreports the same findings as onmaster, 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-workspacerepository: 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_stringso short (1–7 byte) inlineIStringhandles are assembled in registers with shifts and overlappingu32loads, instead of filling an 8-byte stack buffer viacopy_from_slice/memcpyand reloading the word. The bit layout is unchanged;usize::from_lepreserves the previous native-endian layout. Adebug_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.