Repository navigation
Probe IObject::entry by the borrowed key before interning it - #30
Closed
fcostaoliveira wants to merge 2 commits into
Closed
fcostaoliveira wants to merge 2 commits into
fcostaoliveira wants to merge 2 commits into
Conversation
`IObject::entry` and `IObject::insert` take an `EntryKey` (sealed; implemented for &str, &mut str, String, &String, &mut String, IString, &IString) instead of `impl Into<IString>`. The table is probed with the key as given: a `&str` is hashed with the same `DefaultHasher` and compared by bytes against the resident key, so an occupied entry costs no intern-cache round trip (shard write lock, cache probe, refcount up and down). Only a vacant entry interns the key, exactly as before, and only a full object re-probes after `reserve` rehashes the table. RedisJSON's JSON.MERGE (`merge()`: `map.entry(key.as_str())` per patch key) and the JSON.SET `insert(&str / String)` sites hit this path with no RedisJSON change. `ObjectIndex for &str::index_or_insert` goes through the same `entry`. Generic collection conversions (`TryExtend`, `TryFromIterator`, `TryFrom<HashMap/BTreeMap>`) keep their `Into<IString>` bounds and intern up front. The `ProbeKey` / `find_bucket_str` machinery is identical to EXP-002 so the two branches stack. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Covers the &mut str, &mut String, &String and &IString entry/insert paths so the inserted key is shown to be interned for each key type. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
fcostaoliveira
marked this pull request as draft
November 25, 2026 17:07
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
IObject::entry(impl Into<IString>)interns the key before it probes the table. When the key is already present, which is every key of aJSON.MERGEpatch the target already holds, that intern trip finds an occupied bucket and then throws the temporary away. It costs a shard lock, a hash and probe in the global string cache, and an atomic refcount up and down.This PR changes
entryandinsertto take a small sealed trait,EntryKey.EntryKeycan probe the table with the key as given and turn it into anIStringonly when needed. The trait is implemented for&str,&mut str,String,&String,&mut String,IStringand&IString, and exported from the crate root.entryreturns without interning or reserving.entryreserves one slot, interns the key, and re-probes only when the object was full (the only case wherereserverehashes).ObjectIndex for &str :: index_or_insert(obj["k"] = v) now goes throughentry(self). The&strprobe uses the sameDefaultHasherover the same bytes as theIStringpath, with a byte compare against the resident key.In RedisJSON this is
ivalue_manager::merge(), which runsmap.entry(key.as_str()).unwrap().or_insert(IValue::NULL)once per patch key for JSON.MERGE. It is also the JSON.SETinsert(key.as_str(), …)/insert(key.to_string(), …)sites.Code size: +277/−41 in 2 files (
src/object.rs,src/lib.rs): +179/−41 library, +98 tests.Coverage of changed lines: 94/95 (98.9%) of the instrumented changed library lines, in both the default and
thread_safebuilds (cargo-llvm-cov, unit tests). The one uncovered line is unreachable (see below).Relation to #27
This PR is based on
masterand is independent of #27. Both add the sameProbeKey/find_bucket_impl/find_bucket_strcode byte for byte, so that part merges cleanly. A trial merge with #27's branch has one conflict, on adjacent lines inObjectIndex for &str :: index_or_insert: #27 keepsv.entry(IString::intern(self)), this PR hasv.entry(self). The resolution isv.entry(self). With that resolution, the merged tree passes the unit tests in both builds.If #27 lands first, I will rebase this PR on it. The shared probe code then drops out of this diff, and only the
entry/insertchange and its test remain.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
merge()loop, keys present)The merge loop went from 1.90 µs to 1.33 µs for 26 keys, about 22 ns saved per key. That is the measured cost of the intern round trip on this core. The two targets reproduce with both sides built with 64-byte function and block alignment (see below): merge −31.5%, insert-remove −4.8%.
Memory: retained and peak bytes, and the
size_oftable, are byte-identical on every fixture. No field, allocation or table is added.TMA (Linux, toplev level 2, 20 s windows, CPU-pinned),
mutation/merge-26-into-54-occupiedandmutation/object-insert-remove-22:* The base merge capture sums to 83.1%. Its Frontend window is under-reported, so its residual is in Frontend_Bound, and its other three categories match the candidate within 1 point. The slot mix is unchanged while the time falls 30%. The removed work (lock, cache probe, two atomic read-modify-writes) had the same stall profile as the work that remains, so this is a cut in instruction count, not a change of bottleneck.
End to end in RedisJSON
Setup:
9ca1c88, built unchanged against pinnedijson(379dadf) and against this change (Cargo[patch]only, same library code as this PR).redis-server(x86-64, Intel Sapphire Rapids, Linux).-c 16 -t 2, pipeline 1, 15 s runs, three interleaved rounds per cell against the same base module, base spreads 0.0–2.3%.Only commands that moved by 3% or more are listed.
$.businesses[*] {"merged": <26-key object>}, 10 targets$, whole 38 KB yelp document (code placement, see below; −0.5% with both modules aligned)Unchanged (|Δ| < 3%, 12 of 14 workloads): every other workload is within ±2.0%. The largest are multi-path
JSON.GET(−2.0%),$..uidover the 633 KB issue674 document (−1.9%) and the wildcardJSON.GETofreviews[*].user_name(−1.2%).The MERGE gain was consistent in all three rounds: 19,311 / 19,097 / 19,295 ops/s against 17,565 / 17,552 / 17,557.
With #27 and #28. On the same base module, #27 + #28 alone give MERGE +27.6%. A stack of six branches that includes #27, #28 and this change gives MERGE +47.8%. The other three branches in that stack change parsing and CBOR decoding, not
entry. The split inside the stack was not measured per member.JSON.GET $−13.6% is code placement, not this change. That path runs none of the code this PR touches.JSON.GET $serialise path is instruction-for-instruction identical in the two modules (59 of 59 instances, normalisedobjdump). Only addresses, order and 64-byte offsets differ.-C llvm-args=-align-all-functions=6 -C llvm-args=-align-all-nofallthru-blocks=6, the same comparison reads −0.5% (17,214 → 17,126 ops/s, spread 0.9%), and MERGE keeps +8.5%. In the same session, the unaligned pair reproduced −13.9%.JSON.GET $drop, and its aligned E2E reads +0.4%.perf recordof the two unaligned modules was not captured, so the aligned rebuild is the evidence.Memory: identical. No field, allocation or table is added.
Things worth knowing
API change.
entryandinsertnow take a sealedEntryKeyinstead ofimpl Into<IString>.IString: From<_>accepts is covered, plus&IString.cargo check -p redis_json --no-default-featurespasses against this change.TryExtend,TryFromIteratorandTryFrom<HashMap|BTreeMap>keep theirK: Into<IString>bound.Into<IString>itself would need an explicit.into()at the call site. There are none in RedisJSON or ijson.Interning semantics are unchanged for inserted keys. The vacant path interns exactly as before. An occupied lookup no longer creates and then drops a cache entry, which is observable only as fewer cache lock acquisitions.
Removed private method. The private
unsafe fn HeaderMut::entry(IString)has no caller left after this change, so this PR deletes it. A later change that needs it can bring it back.object-insert-remove-22came out −4.9% where I predicted ±2% before measuring. The vacant path now probes once by&strand reuses that bucket after interning, instead of interning first and then probing.The one uncovered line,
src/object.rs:867, is the "found after all" arm of the second probe afterreserve(1)rebuilt a full table. The key was absent beforereserve, andreserveonly reinserts existing keys with the same hasher, so this arm cannot be reached. It is kept as a defensive arm rather than a panic.Unaligned microbenchmark full suite, one pair:
serialise/compact/yelp+34.3%,serialise/indent/yelp−17.2%).lookup/small-8-hit-lastread +13.5%.serialise/compact/yelp+1.2%,small-8-hit-last+0.9%).Three serialise benchmarks remain layout-sensitive after alignment:
serialise/compact/yahoo2+8.0%,serialise/indent/parser-0000+5.8% andserialise/indent/yelp+3.1%. No line of this PR runs in them. I'm flagging rather than hiding them.Tests:
cargo test --no-default-features --lib -- --test-threads=1passes: 135 tests in the default build, 130 withthread_safe, plus the doc test. The newentry_probes_borrowed_key_before_interningcovers several cases:&str,String,&String,IStringand&IString, in both no-table and table layouts.EntryKeytype, checking the inserted key is interned.IndexMut<&str>.cargo fmt --checkis clean, andcargo clippy --no-default-featuresreports no new warnings againstmaster. An adversarial test pass and a fuzz run ofentry/removeagainst aBTreeMapmodel (7.95 M executions) reported no finding.The benchmark suite and the full experiment record live in the
redis-performance/json-agent-workspacerepository: EXP-015. The aligned rebuild is EXP-014.🤖 Generated with Claude Code
Note
Medium Risk
Changes core object lookup/insert semantics and a public API bound, but behavior for stored keys is preserved and covered by new tests; downstream must use
EntryKeytypes or.into()for customInto<IString>wrappers.Overview
IObject::entryandinsertnow take a sealedEntryKeytrait (exported from the crate root) instead ofimpl Into<IString>. Lookups probe the hash table using the key as given—a&stris hashed and compared by bytes without touching the intern cache;IStringis only created on the vacant path when the key must be stored.The hash table gains a
ProbeKeyabstraction andfind_bucket_strso occupied hits skip interning and (when not full) reserving.obj["k"] = vviaObjectIndex for &strroutes through this path. The privateHeaderMut::entry(IString)helper is removed in favor of the publicentryflow, with a new unit test covering occupied/vacant paths across table layouts.Reviewed by Cursor Bugbot for commit d50de19. Bugbot is set up for automated code reviews on this repo. Configure here.