Skip to content

Probe IObject::entry by the borrowed key before interning it - #30

Closed
fcostaoliveira wants to merge 2 commits into
RedisJSON:masterfrom
fcostaoliveira:pr/entry-probe-before-intern
Closed

fcostaoliveira wants to merge 2 commits into
RedisJSON:masterfrom
fcostaoliveira:pr/entry-probe-before-intern

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Nov 25, 2026 •

Copy link
Copy Markdown

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 a JSON.MERGE patch 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 entry and insert to take a small sealed trait, EntryKey. EntryKey can probe the table with the key as given and turn it into an IString only when needed. The trait is implemented for &str, &mut str, String, &String, &mut String, IString and &IString, and exported from the crate root.

  • Occupied: entry returns without interning or reserving.
  • Vacant: entry reserves one slot, interns the key, and re-probes only when the object was full (the only case where reserve rehashes).

ObjectIndex for &str :: index_or_insert (obj["k"] = v) now goes through entry(self). The &str probe uses the same DefaultHasher over the same bytes as the IString path, with a byte compare against the resident key.

In RedisJSON this is ivalue_manager::merge(), which runs map.entry(key.as_str()).unwrap().or_insert(IValue::NULL) once per patch key for JSON.MERGE. It is also the JSON.SET insert(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_safe builds (cargo-llvm-cov, unit tests). The one uncovered line is unreachable (see below).

Relation to #27

This PR is based on master and is independent of #27. Both add the same ProbeKey / find_bucket_impl / find_bucket_str code byte for byte, so that part merges cleanly. A trial merge with #27's branch has one conflict, on adjacent lines in ObjectIndex for &str :: index_or_insert: #27 keeps v.entry(IString::intern(self)), this PR has v.entry(self). The resolution is v.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 / insert change 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

Benchmark Base Candidate Δ Base spread
mutation/merge-26-into-54-occupied (RedisJSON's merge() loop, keys present) 1.90 µs 1.33 µs −29.7% 0.1%
mutation/object-insert-remove-22 (vacant inserts) 140.9 ns 133.9 ns −4.9% 0.0%
mutation/num-incrby-i64 (control) 58.5 ns 59.7 ns +2.1% 2.0%
lookup/business-22-hit (control) 56.9 ns 58.0 ns +2.0% 2.6%
lookup/wide-128-hit-long-key (control) 71.0 ns 69.2 ns −2.4% 0.3%

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_of table, 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-occupied and mutation/object-insert-remove-22:

                      merge-26-into-54      object-insert-remove-22
                      base    candidate     base    candidate
Frontend_Bound       13.3%*    29.2%        30.6%     31.9%
Bad_Speculation       3.0%      3.0%         3.2%      3.3%
Backend_Bound        53.3%     53.4%        52.1%     51.0%
  Memory_Bound       37.1%     37.0%        35.0%     33.7%
  Core_Bound         16.2%     16.3%        17.1%     17.4%
Retiring             13.5%     14.4%        14.1%     13.8%

* 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:

  • RedisJSON 9ca1c88, built unchanged against pinned ijson (379dadf) and against this change (Cargo [patch] only, same library code as this PR).
  • Pinned redis-server (x86-64, Intel Sapphire Rapids, Linux).
  • memtier, -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.

Command Workload pinned ijson ops/s this PR ops/s Δ throughput p50 ms
JSON.MERGE $.businesses[*] {"merged": <26-key object>}, 10 targets 17,557 19,295 +9.9% 1.655 → 1.551
JSON.GET $, whole 38 KB yelp document (code placement, see below; −0.5% with both modules aligned) 17,302 14,949 −13.6% 1.487 → 1.703

Unchanged (|Δ| < 3%, 12 of 14 workloads): every other workload is within ±2.0%. The largest are multi-path JSON.GET (−2.0%), $..uid over the 633 KB issue674 document (−1.9%) and the wildcard JSON.GET of reviews[*].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.

  • Static check: every function on the JSON.GET $ serialise path is instruction-for-instruction identical in the two modules (59 of 59 instances, normalised objdump). Only addresses, order and 64-byte offsets differ.
  • Aligned rebuild of this change: with both modules built with -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%.
  • Sibling change: an unrelated ijson change showed the same unaligned JSON.GET $ drop, and its aligned E2E reads +0.4%.
  • Limit: the alignment flags are a measurement setting, not a shipping recommendation (+35% module text). A server-side perf record of 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. entry and insert now take a sealed EntryKey instead of impl Into<IString>.

    • Every type IString: From<_> accepts is covered, plus &IString.
    • Every RedisJSON call site resolves: cargo check -p redis_json --no-default-features passes against this change.
    • TryExtend, TryFromIterator and TryFrom<HashMap|BTreeMap> keep their K: Into<IString> bound.
    • A downstream type that implements 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-22 came out −4.9% where I predicted ±2% before measuring. The vacant path now probes once by &str and 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 after reserve(1) rebuilt a full table. The key was absent before reserve, and reserve only 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:

    • The serialise group swung both ways (serialise/compact/yelp +34.3%, serialise/indent/yelp −17.2%).
    • lookup/small-8-hit-last read +13.5%.
    • With both sides aligned, most of these are within 3% (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% and serialise/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=1 passes: 135 tests in the default build, 130 with thread_safe, plus the doc test. The new entry_probes_borrowed_key_before_interning covers several cases:

    • Occupied entries by &str, String, &String, IString and &IString, in both no-table and table layouts.
    • Vacant entries by every EntryKey type, checking the inserted key is interned.
    • A vacant entry on a full object (rehash) and a vacant entry with slack.
    • The empty object and IndexMut<&str>.

    cargo fmt --check is clean, and cargo clippy --no-default-features reports no new warnings against master. An adversarial test pass and a fuzz run of entry/remove against a BTreeMap model (7.95 M executions) reported no finding.

The benchmark suite and the full experiment record live in the redis-performance/json-agent-workspace repository: 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 EntryKey types or .into() for custom Into<IString> wrappers.

Overview
IObject::entry and insert now take a sealed EntryKey trait (exported from the crate root) instead of impl Into<IString>. Lookups probe the hash table using the key as given—a &str is hashed and compared by bytes without touching the intern cache; IString is only created on the vacant path when the key must be stored.

The hash table gains a ProbeKey abstraction and find_bucket_str so occupied hits skip interning and (when not full) reserving. obj["k"] = v via ObjectIndex for &str routes through this path. The private HeaderMut::entry(IString) helper is removed in favor of the public entry flow, 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.

fcostaoliveira and others added 2 commits November 25, 2026 17:02
`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
fcostaoliveira marked this pull request as draft November 25, 2026 17:07
@fcostaoliveira

Copy link
Copy Markdown
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.

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.

1 participant