Skip to content

Clone an exact-sized IObject by copying its bucket table - #28

Closed
fcostaoliveira wants to merge 2 commits into
RedisJSON:masterfrom
fcostaoliveira:pr/clone-copy-table
Closed

fcostaoliveira wants to merge 2 commits into
RedisJSON:masterfrom
fcostaoliveira:pr/clone-copy-table

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Nov 24, 2026 •

Copy link
Copy Markdown

Summary

IObject::clone_impl built the clone by re-inserting every key into a fresh table, hashing each key again although the keys are the same interned strings and the clone has the same capacity as the source would need. When the source is exact-sized (capacity() == len, which is what compact parsing produces for every object RedisJSON loads), the clone has the same capacity and therefore the same hash_capacity, so this PR clones the items index-for-index and copies the bucket table verbatim. Sources with spare capacity (after mutations) keep the existing rebuild path.

Nothing observable about the clone changes: same capacity (with_capacity(len), as before), same item order, same table contents, same bytes. Only the hashing is gone. Pre-checks done in the source: DefaultHasher::new() has fixed keys (no per-table seed), the table has no tombstones (remove_bucket shifts the Robin Hood run back), and the clone's capacity was already len.

In RedisJSON this is the .clone() behind JSON.SET overwrite paths, JSON.GET of subtrees and JSON.MSET.

Measurements

Criterion microbenchmarks mirroring RedisJSON's call paths (default-features = false, string cache initialised as OSS RedisJSON does, system allocator, release profile), base and candidate interleaved three times, median over the pairs, spread = the base's own run-to-run spread.

x86-64, Intel Sapphire Rapids (Xeon Platinum 8488C), Linux, bench pinned to one core, host idle

Benchmark Base Candidate Δ Base spread
clone/yelp (38 KB document, 64 objects) 33.62 µs 14.96 µs −55.5% 0.8%
clone/gmaps-place (77 KB, arrays only, no objects) 127.14 µs 127.04 µs −0.1% 0.5%
drop/yelp (of a parsed value) 9.29 µs 9.28 µs −0.2% 0.7%
object-insert-remove-22 144.1 ns 143.9 ns −0.1% 0.0%
lookup/wide-128-hit-long-key 70.0 ns 69.9 ns −0.1% 0.0%
str-append 57.8 ns 58.0 ns +0.3% 0.1%

arm64, Apple M-series, macOS (same protocol, no pinning): clone/yelp −58%, memory identical.

Memory: retained and peak bytes, mem_allocated(), clone/serialise/CBOR sizes identical to the baseline on every fixture.

TMA (Linux, toplev level 2, CPU-pinned), clone/yelp:

                      base    candidate
Frontend_Bound        8.0%     11.3%
Bad_Speculation       5.1%      4.6%
Backend_Bound        21.5%     36.8%
  Core_Bound         18.0%     30.1%
Retiring             65.3%     47.4%

The removed work (SipHash and probing, ~46% of the baseline clone's samples) was retiring-heavy; what remains per item (a refcount increment and two dependent stores) is a core-bound chain, so the tree shifts toward Backend/Core while the clone gets 2.2× faster.

Things worth knowing

  • One benchmark that does not execute any changed code moved +2.6% (1.6 ns on a 58 ns get_mut + number replace loop) across three interleaved pairs on the Linux host; nm placement and TMA (Frontend_Bound 14.6% → 18.4% on the sibling f64 variant) point at code layout. Flagging rather than hiding it.
  • Earlier measurements of this change showed apparent regressions on mutation benchmarks whose iter_batched setup cloned an object; those were the setup's cache state, confirmed by perf record (the timed routine was under 2% of the process samples) and gone once the benchmarks mutate in place.
  • Tests: cargo test --lib -- --test-threads=1 passes in both the default and thread_safe configurations.

Benchmark suite and the full experiment record (including the superseded verdicts) live in redis-performance/json-agent-workspace, branch fcostaoliveira/add-optimize-overnight-skill, under experiments/EXP-003-clone-copy-table/.


Note

Medium Risk
Unsafe pointer/table copying on a core data structure; correctness depends on exact-capacity invariants and valid source tables, though behavior is meant to be unchanged.

Overview
Optimizes IObject::clone_impl when the source is exact-sized (capacity() == len, typical after compact parsing): instead of re-inserting every entry and re-hashing keys, the clone writes key/value pairs index-for-index, bumps len after each item (so a panicking nested clone does not leak partial state), and memcopies the Robin Hood bucket table when one exists.

Objects that still have spare capacity after mutations keep the previous rebuild-via-insert path. Observable clone semantics (capacity, order, lookup behavior) are intended to stay the same; the win is avoiding SipHash and probing on the hot RedisJSON clone paths.

Reviewed by Cursor Bugbot for commit 505321b. Bugbot is set up for automated code reviews on this repo. Configure here.

RedisJSON impact by command

RedisJSON 9ca1c88 built unchanged against pinned ijson (379dadf) and against this change (Cargo [patch] only), on a pinned redis-server (x86-64, Intel Sapphire Rapids, Linux); memtier -c 16 -t 2 15 s runs (-c 1 -t 1 for the 633 KB issue674 document; the yelp filter and $..name rows with redis-benchmark -c 16 --threads 2 -n 300000), three interleaved rounds per cell, base run-to-run spreads 0.3–5.1%. Only commands that moved by 3% or more are listed; everything else is within noise. Full record, raw memtier output and server TMA: MODULE-001 in json-agent-workspace.

Command Workload #27 ops/s #27 + this PR ops/s Δ from this PR Δ vs pinned ijson p50 ms (#27 → +this PR)
JSON.SET $.businesses[*].extra <26-key object>, 10 targets 27,515 35,830 +30.2% +44.5% 1.071 → 0.823
JSON.MERGE $.businesses[*] {"merged": <26-key object>}, 10 targets 18,845 22,578 +19.8% +28.1% 1.583 → 1.327
JSON.SET $.businesses[*].reviews[*].geo <GeoJSON feature>, 28 targets 21,683 23,851 +10.0% +24.1% 1.351 → 1.247
JSON.ARRAPPEND $.businesses[*].categories <GeoJSON feature>, 10 targets 50,772 55,260 +8.8% +20.6% 0.575 → 0.519

Unchanged (|Δ| < 3%, 14 of 18 workloads): JSON.GET: $.message.code on the 38 KB yelp doc, $.ResultSet.totalResultsAvailable yahoo2, $.[8].zero jsonsl-1, $ whole 38 KB yelp document, $.ResultSet.totalResultsAvailable yahoo2 at pipeline 16, five wildcard paths over 10 businesses, $.businesses[*].reviews[*].user_name, $..uid over the 633 KB issue674 document, $..[?(@.uid==1198)].MD5ModelUID issue674, $.businesses[?(@.avg_rating>=4.5)].name yelp, $..name yelp; JSON.SET: $.message.code 1 yelp; JSON.NUMINCRBY: num $ 1, $.businesses[*].review_count 1. No clone runs on those paths.

Every mover clones its argument once per matched target (value.clone() / val.clone() / args.clone() in commands.rs): a 26-key object with a bucket table gains the most (table copied instead of 26 re-inserts); the small nested GeoJSON objects gain the index-for-index copy alone. Memory: same capacity and retained bytes as before.

🤖 Generated with Claude Code

IObject::clone_impl rebuilt the table of the clone by re-inserting every
key, hashing each one again although the keys are the same interned
strings. When the source is exact-sized (capacity == len, which is what
compact parsing produces) the clone has the same capacity and therefore the
same hash_capacity, so the items are cloned index-for-index and the bucket
table is copied verbatim. Sources with spare capacity keep the rebuild.
Capacity, item order, table contents and memory of the clone are unchanged;
only the hashing is gone.

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit bccd2cb. Configure here.

Comment thread src/object.rs Resolved
… leak them

Review finding on the table-copy clone: set_len was called once after the
loop, so a panic inside a nested key/value clone left len at 0 and
drop_impl would deallocate the written slots without dropping them. Set
len after each item instead.
@fcostaoliveira

Copy link
Copy Markdown
Author

RedisJSON end-to-end results for this change (stacked on #27, as in the exp/012 branch) are in: RedisJSON 9ca1c88 built unchanged against pinned ijson, #27, and #27 + this PR, on a pinned redis-server (x86-64 Sapphire Rapids), memtier, three interleaved rounds per cell, with server-side TMA.

Where RedisJSON clones the argument once per target, versus #27 alone:

  • JSON.SET $.businesses[*].extra <26-key object> (10 targets): 27.5k → 35.8k ops/s (+30%), +44.5% over the pinned build; p50 1.07 → 0.82 ms.
  • JSON.MERGE $.businesses[*] {...26 keys}: 18.8k → 22.6k ops/s (+20%), +28.1% over pinned.
  • JSON.ARRAPPEND $.businesses[*].categories <GeoJSON>: 50.8k → 55.3k (+9%), +20.6% over pinned.
  • JSON.SET $.businesses[*].reviews[*].geo <GeoJSON> (28 small objects, no bucket tables): 21.7k → 23.9k (+10%), +24.1% over pinned.

GET workloads and single-path commands: unchanged (no clone on those paths). Memory: clone capacity and retained bytes unchanged.

Full record, raw memtier output and TMA trees: https://github.com/redis-performance/json-agent-workspace/blob/main/experiments/MODULE-001-redisjson-end-to-end/README.md

🤖 Generated with Claude Code

@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