Repository navigation
Drop an IString's cache entry with one probe, matched by address - #31
Merged
fcostaoliveira merged 3 commits intoNov 29, 2026
Merged
fcostaoliveira merged 3 commits into
fcostaoliveira merged 3 commits into
Conversation
…nd-put-back After reinit_shared_string_cache (RedisJSON's defrag_start) the entry for a string's text belongs to its re-interned copy when the old copy is dropped. take() removed that entry and insert() put it back: a second hash and probe per string on every defrag cycle (+9% on mem-defrag/defrag-reinit-yelp, Mac smoke). A key hashed like the text but equivalent only to the entry pointing at this copy removes our entry in one probe, leaves another copy's entry alone, and compares addresses instead of bytes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fcostaoliveira
marked this pull request as draft
November 25, 2026 17:20
…drop-single-probe Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fcostaoliveira
marked this pull request as ready for review
November 29, 2026 22:11
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
When the last reference to a heap
IStringis dropped,drop_impl_with_deallocatorunregisters it from the global string cache. Today it does that in two steps.cache.get_val(s)finds the entry. If the entry points at this copy,cache.remove_val(s)removes it. Each step hashes the full string and probes the set with a full-length compare against the resident. So every freed heap string pays two hashes, two probes and twomemcmps.This PR does it with one hash and one probe. A private key type
ThisCopy { text, ptr }hashes like the text, so it probes the same slots as theWeakIStringentries. Itshashbrown::Equivalent<WeakIString>matches only the entry whose pointer is this copy.HashSet::remove(&ThisCopy)then:reinit_shared_string_cachethe string is re-interned into a new copy, and the old copy is freed later.The set holds at most one entry per text, and an entry that points at this copy has this copy's text, so
HashandEquivalentagree.CacheGuard::remove_valis replaced byremove_copy, andget_valbecomes#[cfg(test)]because nothing else calls it. Both are private. Interning semantics, the defrag guard, the public API andsrc/string.rs(thethread_safefeature's implementation) are unchanged.In RedisJSON this runs whenever a document's strings lose their last reference:
JSON.DEL,UNLINK, key expiry and eviction of a document whose strings no other key holds;JSON.SEToverwriting a document or subtree whose strings the new value does not share,JSON.ARRPOPandJSON.ARRTRIM;defrag_startcallsijson::reinit_shared_string_cache(), so every string of every defragged key is re-interned, and the old copy's drop must not remove the new copy's entry. That is the case this change handles in one probe instead of two.Code size: library +29/−12 in 1 file (
src/unsafe_string.rs), plus +54 lines of tests.Coverage of changed lines: 13/13 (100%) of the instrumented changed library lines in the default build. With
--features thread_safethe file is not compiled (lib.rsusessrc/string.rsthere), so that build has no changed lines.Three new tests pin the cases: the last-reference drop removes the entry; dropping a stale copy after a cache reinit keeps the live copy's entry; dropping a copy that has no entry leaves the cache alone.
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). The base is harness r7 (d4ec325) and the candidate is the same tree plus this change. They 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
The miss lookups are on the path. Without #27, a lookup by a key that is not present interns the key and then drops it as the last reference.
⚠
mem_allocated-yelpis a tree walk that never touches the cache, andsmall-8-hit-lastandfloats-1024do not reach this code either. I re-ran the A/B with both sides built with 64-byte function and block alignment (-C llvm-args=-align-all-functions=6 -C llvm-args=-align-all-nofallthru-blocks=6, same commits and host):With placement controlled, the off-path movers disappear, and the on-path gains stay where they were. I attribute the unaligned
mem_allocated+3.6% to code placement, not to this change.Memory: the memory referee's output is byte-identical between base and candidate. The change allocates nothing, and
removefrees the same slot as before.TMA (Linux, topdown-profiler with the toplev collector, level 2, 20 s windows, bench pinned to one core; every capture sums to 100.0% at L1, MUX 100%),
clone-drop/drop-last-ref/yelpandmem-defrag/defrag-reinit-yelp:On
drop-last-ref/yelpthe time falls by 27% with almost the same slot mix. The removed work (the second hash, probe and compare) was the same kind of work as what remains (hashing, probing, freeing), so the change removes a proportional slice and does not move the bottleneck.defrag-reinit-yelpkeeps its profile too: every L1 category is within 0.8 points.End to end in RedisJSON
Setup:
9ca1c88, built unchanged against pinnedijson(379dadf) and against this change (Cargo[patch]only).redis-server(x86-64, Intel Sapphire Rapids, Linux), started empty.-c 1 -t 1), pipeline 10, 15 s runs, three interleaved rounds per cell.The standard workloads cannot reach this path: they preload the fixtures, so every string a command frees is still held by another key. The churn workload alternates
JSON.SET churn $ <doc>andJSON.DEL churn, so everyJSON.DELfrees a document whose strings no other key holds. The controloverwrite_yelpsets the same document over itself. The new value shares every string with the old one, so no last-reference drop happens. All 18 runs haderrorstats0, andINFO commandstatsshows equaljson.setandjson.delcall counts in every churn run.JSON.DELJSON.SETJSON.SET+JSON.DELchurn, yelp (38 KB)JSON.SET+JSON.DELchurn, yahoo2 (18 KB)JSON.SEToverwrite, yelp (control)Server time per
JSON.DELfalls by a fifth. That is the microbenchmark's −27% diluted by the command's own work (key lookup, keyspace delete, reply). Throughput gains less because each pair also pays a full parse inJSON.SET. The control stays within its spread: with the strings shared, the changed code does not run. Active defrag (−2.8% in the microbenchmark) was not measured end to end.Standard workloads
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%.²
numincrby_wildread −3.4% in this session (base spread 2.2%) and −2.1% in an independent re-run; aligned it reads +0.6%. No other workload is worse than 1.7% in either build. These workloads preload their documents, so they do not reach the changed drop path; they are here as a regression check.Microbenchmark re-run on this head (3 interleaved pairs, normal / aligned build):
cbor/encode-yelp+1.5% / +0.3%,clone-drop/clone/floats-1024−1.9% / +0.0%,mem-defrag/mem_allocated-yelp−3.0% / +0.2%,mutation/str-append−0.0% / +0.4%,serialise/indent/int-arrays+1.6% / −1.2%.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
HashSet::takeand put the entry back when it belonged to another copy. Harness r7 showed that this case is not rare: afterdefrag_startempties the cache, it happens for every heap string of every defragged key, once per cycle. That version cost +9% ondefrag-reinit-yelp(arm64, Apple M-series smoke run). Matching by address removes the put-back, and the same benchmark is now −2.8% on x86-64.clone-drop/drop/*from Add criterion microbenchmarks for the RedisJSON call paths, a memory referee, and benchmark docs #29 does not measure this. That is why the r6 benchmark exists; see the note at the top of Measurements.thread_safefeature is not touched. It usessrc/string.rs, and this change is insrc/unsafe_string.rs. RedisJSON buildsdefault-features = false. Both cache modes of the default build (theThreadUnsafeset and theMutexset used wheninit_shared_string_cache(true)) go through the sameremove_copy.cargo test --no-default-features --lib -- --test-threads=1passes 137 tests (3 new),--features thread_safepasses 129 (the new tests live inunsafe_string's test module, so they are not compiled there), and the doc test passes. Miri on the three new tests passes.cargo fmt --checkis clean, andcargo clippy --no-default-featuresreports the same warnings and errors as onmaster, none new.The benchmark suite and the full experiment record, including the rejected first version, live in the
redis-performance/json-agent-workspacerepository: EXP-021.🤖 Generated with Claude Code
Note
Medium Risk
Changes the hot path when heap string refcounts hit zero; incorrect equivalence logic could corrupt the intern cache after defrag or on last drop.
Overview
When the last reference to a heap
IStringis dropped, cache unregistering is collapsed from two hash-set operations into one. A privateThisCopylookup key hashes like the string text (same probe chain asWeakIString) but matches entries only when the header pointer equals the copy being freed, viahashbrown::Equivalent.CacheGuard::remove_valis replaced byremove_copy; production code no longer usesget_val(test-only). The active-defrag case—cache rebuilt and the same text re-interned to a new allocation while an older copy is still alive—is handled by skipping removal when the slot points at a different pointer, without a separate get-then-compare step.Three tests lock in last-ref removal, stale-copy drop after
reinit_shared_string_cache, and drop when no cache entry exists.Reviewed by Cursor Bugbot for commit 5a08649. Bugbot is set up for automated code reviews on this repo. Configure here.