Skip to content

Drop an IString's cache entry with one probe, matched by address - #31

Merged
fcostaoliveira merged 3 commits into
RedisJSON:masterfrom
fcostaoliveira:pr/istring-drop-single-probe
Nov 29, 2026
Merged

fcostaoliveira merged 3 commits into
RedisJSON:masterfrom
fcostaoliveira:pr/istring-drop-single-probe

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Nov 25, 2026 •

Copy link
Copy Markdown

Summary

When the last reference to a heap IString is dropped, drop_impl_with_deallocator unregisters 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 two memcmps.

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 the WeakIString entries. Its hashbrown::Equivalent<WeakIString> matches only the entry whose pointer is this copy. HashSet::remove(&ThisCopy) then:

  • removes this copy's entry in one probe, comparing addresses instead of bytes;
  • walks past an entry for the same text that belongs to another copy, and leaves it alone. That is the active-defrag case the existing code guards against with its pointer check: after reinit_shared_string_cache the 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 Hash and Equivalent agree. CacheGuard::remove_val is replaced by remove_copy, and get_val becomes #[cfg(test)] because nothing else calls it. Both are private. Interning semantics, the defrag guard, the public API and src/string.rs (the thread_safe feature'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.SET overwriting a document or subtree whose strings the new value does not share, JSON.ARRPOP and JSON.ARRTRIM;
  • active defrag: defrag_start calls ijson::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_safe the file is not compiled (lib.rs uses src/string.rs there), 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

For reviewers: the benchmarks that reach this path are not yet in the open benchmark PR #29. They come from two later harness revisions on my fork:

  • clone-drop/drop-last-ref/<fixture> (harness r6, 3b2d3db) times the drop of the only reference to a freshly parsed document. The existing clone-drop/drop/* drops one value out of a batch while the benchmark's own doc stays alive, so no refcount reaches zero and this code never runs.
  • mem-defrag/defrag-reinit-yelp (harness r7, d4ec325) runs a defrag after the cache reinit that RedisJSON's defrag_start does.

Both sit on the fork branch exp/021r7-istring-drop-single-probe, directly below the two commits of this PR. This PR contains only the library change and its tests.

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

Benchmark Base Candidate Δ Base spread
clone-drop/drop-last-ref/yelp 18.55 µs 13.59 µs −26.8% 0.6%
clone-drop/drop-last-ref/gmaps-place 77.99 µs 71.28 µs −8.6% 0.3%
mem-defrag/defrag-reinit-yelp 55.90 µs 54.36 µs −2.8% 0.6%
mem-defrag/defrag-copy-yelp (cache kept, path not reached) 34.22 µs 34.77 µs +1.6% 0.6%
lookup/small-8-miss 61.0 ns 52.3 ns −14.2% 0.0%
lookup/business-22-miss 70.5 ns 63.4 ns −10.0% 0.1%
lookup/business-22-hit 56.1 ns 56.8 ns +1.1% 0.0%
lookup/path-chain-yelp 56.4 ns 56.5 ns +0.2% 0.2%
lookup/small-8-hit-last 18.8 ns 17.7 ns −6.0% ⚠ 0.3%
clone-drop/drop/yelp (strings shared, path not reached) 9.33 µs 9.31 µs −0.2% 1.8%
clone-drop/drop/gmaps-place (same) 53.66 µs 54.62 µs +1.8% 0.9%
clone-drop/drop-last-ref/floats-1024 (no strings) 27.0 ns 25.9 ns −4.0% ⚠ 0.6%
parse/compact-objects/yelp 67.21 µs 67.45 µs +0.4% 3.2%
parse/compact-objects/gmaps-place 286.29 µs 278.99 µs −2.5% 0.2%
mem-defrag/mem_allocated-yelp 2.29 µs 2.37 µs +3.6% ⚠ 0.3%

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-yelp is a tree walk that never touches the cache, and small-8-hit-last and floats-1024 do 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):

Benchmark Base Candidate Δ aligned Base spread Δ unaligned
mem-defrag/mem_allocated-yelp 2.27 µs 2.28 µs +0.4% 0.0% +3.6%
clone-drop/drop-last-ref/yelp 18.57 µs 13.33 µs −28.2% 0.7% −26.8%
lookup/small-8-miss 61.0 ns 53.0 ns −13.2% 0.5% −14.2%
lookup/small-8-hit-last 15.9 ns 15.9 ns +0.1% 0.3% −6.0%

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 remove frees 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/yelp and mem-defrag/defrag-reinit-yelp:

                      drop-last-ref/yelp      defrag-reinit-yelp
                      base    candidate       base    candidate
Frontend_Bound       32.1%     31.0%          30.6%     31.1%
  Fetch_Latency      28.2%     27.2%          26.5%     27.1%
  Fetch_Bandwidth     3.9%      3.8%           4.1%      4.0%
Bad_Speculation       3.0%      2.9%           3.2%      3.3%
  Branch_Mispredicts  2.9%      2.8%           3.1%      3.1%
  Machine_Clears      0.0%      0.0%           0.1%      0.1%
Backend_Bound        51.8%     52.9%          51.9%     52.1%
  Memory_Bound       35.7%     37.0%          35.4%     35.7%
  Core_Bound         16.1%     16.0%          16.4%     16.4%
Retiring             13.2%     13.2%          14.3%     13.5%
  Light_Operations   10.4%     10.4%          11.5%     10.8%
  Heavy_Operations    2.7%      2.7%           2.8%      2.7%

On drop-last-ref/yelp the 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-yelp keeps its profile too: every L1 category is within 0.8 points.

End to end in RedisJSON

Setup:

  • RedisJSON 9ca1c88, built unchanged against pinned ijson (379dadf) and against this change (Cargo [patch] only).
  • Pinned redis-server (x86-64, Intel Sapphire Rapids, Linux), started empty.
  • memtier, one connection (-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> and JSON.DEL churn, so every JSON.DEL frees a document whose strings no other key holds. The control overwrite_yelp sets the same document over itself. The new value shares every string with the old one, so no last-reference drop happens. All 18 runs had errorstats 0, and INFO commandstats shows equal json.set and json.del call counts in every churn run.

Workload pinned ijson ops/s this PR ops/s Δ throughput Base spread Server µs per JSON.DEL Server µs per JSON.SET
JSON.SET+JSON.DEL churn, yelp (38 KB) 16,770 17,952 +7.0% 1.0% 21.0–21.3 → 16.3–16.4 (−23%) 83.6–84.3 → 80.3–80.8
JSON.SET+JSON.DEL churn, yahoo2 (18 KB) 34,127 35,534 +4.1% 1.2% 9.9–10.2 → 7.9 (−21%) 42.7–43.2 → 42.7–42.9
JSON.SET overwrite, yelp (control) 10,207 10,377 +1.7% (in spread) 3.0% — 82.4–84.5 → 81.2–82.5

Server time per JSON.DEL falls 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 in JSON.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):

  • 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,140 −1.7% 47,244 46,618 −1.3%
DUMP+RESTORE, yahoo2 31,897 32,139 +0.8% 33,090 33,145 +0.2%
DUMP, yelp 12,978 13,049 +0.6% 13,414 13,506 +0.7%
JSON.GET multi-path, yelp 52,435 51,857 −1.1% 53,127 53,145 +0.0%
JSON.GET wildcard reviews[*].user_name 84,952 84,283 −0.8% 84,482 85,084 +0.7%
JSON.GET $, whole yelp 17,458 17,324 −0.8% 17,301 17,261 −0.2%
JSON.GET single path, yelp 153,009 152,120 −0.6% 152,533 154,095 +1.0%
JSON.MERGE wildcard, 26-key patch 17,595 17,572 −0.1% 17,559 17,658 +0.6%
JSON.NUMINCRBY single path 156,504 155,440 −0.7% 156,834 157,772 +0.6%
JSON.NUMINCRBY wildcard 97,650 94,356 −3.4% ² 97,177 97,800 +0.6%
JSON.GET $..uid, 633 KB document 1,345 1,332 −0.9% 1,322 1,328 +0.5%
JSON.SET wildcard, 26-key object 24,631 24,559 −0.3% 24,916 24,790 −0.5%
JSON.SET $, whole yahoo2 ¹ 782 782 +0.0% 782 782 +0.0%
JSON.SET single path, yelp 144,688 143,500 −0.8% 144,642 144,888 +0.2%

¹ 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_wild read −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

  • The first version of this change was slower on defrag. It used HashSet::take and put the entry back when it belonged to another copy. Harness r7 showed that this case is not rare: after defrag_start empties the cache, it happens for every heap string of every defragged key, once per cycle. That version cost +9% on defrag-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.
  • The thread_safe feature is not touched. It uses src/string.rs, and this change is in src/unsafe_string.rs. RedisJSON builds default-features = false. Both cache modes of the default build (the ThreadUnsafe set and the Mutex set used when init_shared_string_cache(true)) go through the same remove_copy.
  • Tests: cargo test --no-default-features --lib -- --test-threads=1 passes 137 tests (3 new), --features thread_safe passes 129 (the new tests live in unsafe_string's test module, so they are not compiled there), and the doc test passes. Miri on the three new tests passes. cargo fmt --check is clean, and cargo clippy --no-default-features reports the same warnings and errors as on master, none new.

The benchmark suite and the full experiment record, including the rejected first version, live in the redis-performance/json-agent-workspace repository: 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 IString is dropped, cache unregistering is collapsed from two hash-set operations into one. A private ThisCopy lookup key hashes like the string text (same probe chain as WeakIString) but matches entries only when the header pointer equals the copy being freed, via hashbrown::Equivalent.

CacheGuard::remove_val is replaced by remove_copy; production code no longer uses get_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.

fcostaoliveira and others added 2 commits November 25, 2026 17:02
…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
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>

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

LGTM

@fcostaoliveira
fcostaoliveira marked this pull request as ready for review November 29, 2026 22:11
@fcostaoliveira
fcostaoliveira merged commit aaa007a into RedisJSON:master Nov 29, 2026
7 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