Skip to content

Add atomic sorted-set moves with batching and destination conditions - #16135

Merged
sundb merged 40 commits into
redis:unstablefrom
fcenedes:zmove-commands-refresh
Nov 11, 2026
Merged

sundb merged 40 commits into
redis:unstablefrom
fcenedes:zmove-commands-refresh

Conversation

@fcenedes

@fcenedes fcenedes commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Adds atomic sorted-set moves for end-of-set batches, score ranges and named members. Continues #10430 by @vikeychen. Related: #9989. Docs: redis/docs#4522.

ZMOVE        source destination <MIN | MAX | BYSCORE score-min score-max> [COUNT count]
BZMOVE       source destination <MIN | MAX> timeout [COUNT count]
ZMOVEMEMBER  source destination [NX | XX] MEMBERS num-members member [member ...]

Reply

  • When members are moved, the reply is an array of [member, score] pairs, nested even for one member. Scores are bulk strings in RESP2 and doubles in RESP3.
  • When nothing is moved, the reply is nil (RESP2 *-1, RESP3 _). That covers a missing source, no matching or eligible member, source == destination, and a BZMOVE timeout. It also covers BZMOVE inside MULTI or a script when the source is empty.
  • Reply order:
    • MIN and BYSCORE: ascending (score, then member);
    • MAX: descending;
    • ZMOVEMEMBER: argument order, with duplicates once and missing members skipped.

Semantics

  • COUNT must be positive. Zero, negative or malformed values return ERR count should be greater than 0 before anything moves or blocks, as ZMPOP does. The default count is 1 for MIN/MAX. BYSCORE moves the whole matching range by default.
  • BYSCORE takes ZRANGEBYSCORE-style bounds ((, -inf, +inf). It has no LIMIT offset.
  • BZMOVE blocks on the source only. It wakes as soon as the source has a member and moves up to COUNT; it doesn't wait for a full batch. When members are moved, it is propagated as ZMOVE source destination MIN|MAX [COUNT count].
  • ZMOVEMEMBER:
    • The counted MEMBERS block keeps member data apart from options, like HSETEX FIELDS. NX/XX may appear before or after the block, so a member named NX or MEMBERS is unambiguous.
    • With NX, only members absent from the destination move; with XX, only members already present there move. Members that aren't moved stay in the source.
    • With no condition, the source score overwrites the destination score.
  • Source == destination returns nil right after the type check, without reading any member. BZMOVE does not block in that case.
  • An emptied source is deleted. An existing destination keeps its TTL; a new destination has none. In cluster mode both keys must hash to the same slot.

Keyspace notifications

These fire only when at least one member moved:

  • Source:
    • zpopmin / zpopmax for MIN/MAX;
    • zrem for BYSCORE and ZMOVEMEMBER;
    • del when the source is emptied.
  • Destination: zadd, but only if the destination actually changed. Moving a member that already has the same score doesn't count as a change. A newly created destination also gets new.

Co-authored-by: vikeychen [email protected]

@CLAassistant

CLAassistant commented Oct 31, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-31T19:19:38.405751Z ae8b07b PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ae8b07b629

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/commands/zmove.json Resolved
@fcenedes fcenedes changed the title Add ZMOVE, BZMOVE, and ZMOVEMEMBER sorted-set commands Add atomic sorted-set moves with BYSCORE batch limits Oct 31, 2026
@fcenedes

fcenedes commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

@sundb

Comment thread src/commands/bzmove.json Resolved
Comment thread src/commands/bzmove.json Resolved
Comment thread src/commands/zmove.json Resolved
Comment thread tests/unit/type/zset-move.tcl Resolved
Comment thread src/t_zset.c Resolved
Comment thread src/t_zset.c Resolved
Comment thread src/t_zset.c Resolved
@sundb

sundb commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

@sundb sundb added this to Redis 8.12 Nov 5, 2026
@sundb sundb added release-notes indication that this issue needs to be mentioned in the release notes state:needs-doc-pr requires a PR to redis-doc repository labels Nov 5, 2026

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

Stale Bugbot comment from a previous run.

Comment thread tests/unit/type/zset-move.tcl Resolved
@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.26087% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.33%. Comparing base (d866f80) to head (f656d73).

Files with missing lines Patch % Lines
src/t_zset.c 98.25% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           unstable   #16135    +/-   ##
==========================================
  Coverage     78.32%   78.33%            
==========================================
  Files           156      156            
  Lines         95478    95704   +226     
==========================================
+ Hits          74781    74966   +185     
- Misses        20697    20738    +41     
Files with missing lines Coverage Δ
src/commands.def 100.00% <ø> (ø)
src/server.c 90.01% <100.00%> (+<0.01%) ⬆️
src/server.h 100.00% <ø> (ø)
src/t_zset.c 81.02% <98.25%> (+0.93%) ⬆️

... and 17 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment thread src/t_zset.c Resolved
Comment thread src/t_zset.c Resolved
Comment thread src/t_zset.c Resolved
Comment thread tests/unit/type/zset.tcl Resolved
sundb and others added 2 commits November 9, 2026 19:53
Comment thread src/commands/bzmove.json Resolved
sundb and others added 3 commits November 10, 2026 13:06
ZMOVEMEMBER source destination member [member ...] now moves every given
member that exists in the source and replies with nested [member, score]
pairs in request order, or nil when nothing moved. Missing members are
skipped and duplicates are moved once. Keyspace events, KEYSIZES and
memory tracking are updated once per command.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sundb and others added 3 commits November 11, 2026 11:52
The rewrite depends on BZMOVE's argument layout, so do it in the
command itself instead of having zmoveGenericCommand check the
caller's proc.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The three commands each repeated the key validation, lazy destination
creation, reply and bookkeeping. Move that into zmoveBegin(),
zmoveAdd() and zmoveEnd() around a shared zmoveCtx.

ZMOVE MIN, MAX and BYSCORE now all resolve to a range of consecutive
ranks that is read in place and deleted as a whole, instead of popping
members one by one or going through the ZRANGEBYSCORE result handler.
A new destination is created with a size hint and, for ascending
moves, filled with the B+tree append batch.

No behavior change. Moving 500k members is 20-55% faster; single
member moves are unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Replace zmoveParseCount() with zmoveParseCountOrReply(), placed right
above ZMOVE and BZMOVE instead of among the score range parsers. The
default count is now set by the caller.

A malformed COUNT tail is reported as a syntax error, as ZMPOP does,
rather than as a wrong number of arguments.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

@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

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 482d121. Configure here.

Comment thread src/t_zset.c Resolved
sundb and others added 10 commits November 11, 2026 13:43
The append batch requires members that are ascending and distinct. A
listpack source may be a restored payload that is unsorted or, without
deep sanitization, repeats a member, so moving it into a new B+tree
destination could store members out of order.

Take the append path only for a B+tree source, as ZRANGESTORE does;
a listpack source goes through zsetAdd().

Co-Authored-By: Claude Fable 5.2 <[email protected]>
zmoveBegin() and zmoveGenericCommand() took the keys from argv[1] and
argv[2] themselves. Have the callers pass them in, so the shared code
doesn't depend on the commands' argument layout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The MIN/MAX and BYSCORE branches now only parse their own arguments
and set the default count; COUNT is parsed and the move is run once
after them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
zmoveGenericCommand() now returns the number of members moved, and
BZMOVE skips the rewrite when it is zero, e.g. for equal keys or a
destination of the wrong type. Nothing is propagated in that case, so
the rewrite was harmless but unnecessary.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The append path relies on the destination having been created by this
move. NX would let every such member through anyway, and XX never
creates a destination, so the flags check guarded nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/t_zset.c Resolved
Comment thread src/t_zset.c Resolved
Comment thread src/t_zset.c Resolved
@sundb
sundb merged commit 0cfe837 into redis:unstable Nov 11, 2026
20 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in Redis 8.12 Nov 11, 2026
PavelPashov added a commit to ioredis/commands that referenced this pull request Nov 12, 2026
Add BZMOVE, ZMOVE and ZMOVEMEMBER from redis/redis#16135.

Co-authored-by: Claude Opus 5.5 <[email protected]>
ndyakov added a commit to redis/go-redis that referenced this pull request Nov 13, 2026
* chore(cmd): regenerate command info for 8.12-rc3

Adds the ZMOVE, BZMOVE and ZMOVEMEMBER records. All three are writes,
so the CSC eligible set is unchanged; only the table fingerprint moves.

* feat(command): add ZMOVE, BZMOVE and ZMOVEMEMBER

Atomic moves between sorted sets (Redis 8.12): ZMove/ZMoveCount,
ZMoveByScore/ZMoveByScoreCount, BZMove/BZMoveCount and
ZMoveMember/ZMoveMemberWithArgs (NX/XX). COUNT is sent only by the
Count variants, the BZMOVE timeout keeps its fraction of a second, and
a move of nothing returns redis.Nil. BZMOVE is a blocking command, so
autopipelining never queues it on a shared connection.

Refs redis/redis#16135
mgravell added a commit to seredis/StackExchange.Redis that referenced this pull request Nov 13, 2026
…3351)

redis/redis#16135 (8.12-rc3) adds ZMOVE, BZMOVE and ZMOVEMEMBER:

- SortedSetMove (ZMOVE MIN|MAX [COUNT]) - from the low or high end
- SortedSetMoveByScore (ZMOVE BYSCORE min max [COUNT]) - a score range
- SortedSetMoveMembers (ZMOVEMEMBER [NX|XX] MEMBERS n ...) - named members,
  with When as the per-member condition on the destination

Each returns SortedSetEntry[]?, null when nothing moved (the server's null
reply is never folded into an empty array). COUNT is sent if and only if the
caller gives one: for BYSCORE, no COUNT means the whole range, so the
SortedSetPop habit of eliding COUNT 1 is not copied.

The reply is nested [member, score] pairs in RESP2 as well as RESP3, unlike
ZPOPMIN, so SortedSetWithScores does not fit; NullableSortedSetEntryArray
is a strict nested-pair processor.

BZMOVE is not exposed (blocking; policy row in CommandCoverage.md).

Gated [Experimental] behind SER011 and the new RedisFeatures.v8_12_0_rc3
(8.11.242: rc2 does not have the commands); the test docker image moves to
client-libs-test:8.12-rc3.
mgravell added a commit to seredis/StackExchange.Redis that referenced this pull request Nov 23, 2026
…011) (#3343)

* Redis 8.12 BITRANGEINTARRAY (bit enumeration): IDatabase.StringBitPositions (#3315)

* Plan: StringBitPositions (BITRANGEINTARRAY, Redis 8.12)

* Plan: record the behaviour observed against a local unstable build

* Redis 8.12 BITRANGEINTARRAY: IDatabase.StringBitPositions

Enumerates the set (or, with bit: false, the clear) bit positions in a
byte or bit range of a string or native bitmap, ascending, with an
optional LIMIT; the sibling of StringBitPosition (BITPOS). Reuses
ResultProcessor.Int64Array; the argument tail fits Message.Create, with
the default BYTE omitted as BITCOUNT/BITPOS do. Negative limit throws
client-side.

Gated [Experimental(Experiments.Server_8_12)] (SER011), with
RedisFeatures.v8_12_0 and RedisFeatures.StringBitPositions, matching the
BLESS branch so the two merge textually.

Tests: exact wire bytes for every option combination (BitPositionsRoundTrip),
and live tests in BitTests gated on v8_12_0, observed green against a
local build of unstable (6a5fee67) on RESP2 and RESP3.

Removes the BITRANGEINTARRAY row from the command coverage ledger.

* 8.12 RC2: pin the real pre-release version and run CI against the RC2 image

- RedisFeatures.v8_12_0 is now 8.11.241, which is what 8.12 RC2 reports
  (the earlier 8.12.0 placeholder made the gated tests skip on RC2)
- the test topology image defaults to redislabs/client-libs-test:8.12-rc2
- the cluster configs opt out of the new cluster-bus-port-protected-mode
  check, which otherwise refuses to start a plaintext cluster node on RC2

Validated locally against the RC2 topology: StringBitPositions live tests
and BitPositionsRoundTrip all pass, and the cluster forms cleanly.

* SortedSetScanLarge: count distinct members, tolerating ZSCAN duplicates

The 8.12 btree zset encoding can return duplicate members even for an
unmodified key (redis/redis#16158; the SCAN contract allows it), so the
test now asserts the distinct member count instead of the raw count.
All 8 cases pass against the RC2 topology.

* Set-member expiration (Redis 8.12): SADDEX / SEXPIRE / SPTTL / SPERSIST on IDatabase (#3340)

* Initial support for Redis 8.12 set-member expiration

The hash-field-TTL idea (7.4's HEXPIRE) brought to sets (redis/redis#15938,
8.12-rc2), mirroring the HashField* family:

- SetAddAndSetExpiry (SADDEX): add members and/or (re)set their expiration in
  one atomic call; When.NotExists/Exists map to MNX/MXX, which are
  all-or-nothing across the batch, exactly as HSETEX's FNX/FXX; the bare form
  discards an existing TTL, KEEPTTL keeps it
- SetMemberExpire (SEXPIRE/SPEXPIRE/SEXPIREAT/SPEXPIREAT by precision) ->
  ExpireResult[], per member
- SetMemberGetTimeToLive (SPTTL) and SetMemberGetExpireDateTime (SPEXPIRETIME)
  -> long[]
- SetMemberPersist (SPERSIST) -> PersistResult[]
- KeyNotificationType.SExpired ('sexpired', side-effect block), so the 8.12
  notification - including on the subkey channels, whose payload names the
  lapsed member - parses as a known type; GetSubKeys() already handles the
  payload

Gated [Experimental] behind SER011/Experiments.Server_8_12 and
RedisFeatures.v8_12_0 (8.11.241), both shared with #3261/#3315; the test
docker image moves to client-libs-test:8.12-rc2 as in those PRs.

Round-trip tests pin the exact wire bytes; the live tests (HashFieldTests
mirror) pass against the 8.12-rc2 topology on both protocols. Plan document
in notes/set-member-expiry/.

* SADDEX rides SetAdd: two Expiration overloads replace the four-per-arity SetAddAndSetExpiry surface

Review feedback (see the PR): Expiration already encodes EX/PX/EXAT/PXAT/KEEPTTL - exactly SADDEX's
expiration block - so the TimeSpan?/DateTime/keepTtl splits collapse and the surface is
SetAdd(key, value, Expiration, When, flags) and SetAdd(key, values, Expiration, When, flags), both
bool (+async): 8 members become 4, with no new method name. A required Expiration keeps overload
resolution away from the existing SetAdd members.

- Expiration.Persist is rejected (SADDEX has no PERSIST; SetMemberPersist is the way to remove
  member expirations) - previously it would have been sent as a bogus token.
- The overloads always send SADDEX: plain SADD is not an equivalent fallback for the no-expiry
  form, because bare SADDEX discards an existing member's TTL where SADD leaves existing members
  untouched; the XML docs call this out, and that the multi-value form reports only whether
  anything changed, not a count.
- The SetMemberExpire/GetTimeToLive/GetExpireDateTime/Persist family is unchanged (ExpireWhen's
  GT/LT cannot ride Expiration, and it mirrors the HashField shape).
- plan.md carries a revision note; SER011.md updated; all 50 SetMemberExpiry tests pass live
  against 8.12-rc2, 525 KeyPrefixed tests pass.

* Each set-member-expiry test deletes its key up front: SADDEX's changed-anything reply and the MNX/NX conditions make residue from a previous run (or the other protocol) look like a failure

* Redis 8.12 BLESS (eviction protection) support (#3261)

Adds KeyBless/KeyUnbless/KeyBlessFlags (+async) on IDatabase and
IServer.BlessedKeys (+async) over BLESS SCAN, with the BlessFlags enum,
gated behind SER011 (Server_8_12). SET/CLEAR are raised to primary-only;
GET stays replica-eligible. Adds bless/unbless keyspace notification types.

* CommandCoverage: the BLESS rows retire with #3261 (the ledger lists only unexposed commands)

* Redis 8.12 atomic sorted-set moves: ZMOVE / ZMOVEMEMBER on IDatabase (#3351)

redis/redis#16135 (8.12-rc3) adds ZMOVE, BZMOVE and ZMOVEMEMBER:

- SortedSetMove (ZMOVE MIN|MAX [COUNT]) - from the low or high end
- SortedSetMoveByScore (ZMOVE BYSCORE min max [COUNT]) - a score range
- SortedSetMoveMembers (ZMOVEMEMBER [NX|XX] MEMBERS n ...) - named members,
  with When as the per-member condition on the destination

Each returns SortedSetEntry[]?, null when nothing moved (the server's null
reply is never folded into an empty array). COUNT is sent if and only if the
caller gives one: for BYSCORE, no COUNT means the whole range, so the
SortedSetPop habit of eliding COUNT 1 is not copied.

The reply is nested [member, score] pairs in RESP2 as well as RESP3, unlike
ZPOPMIN, so SortedSetWithScores does not fit; NullableSortedSetEntryArray
is a strict nested-pair processor.

BZMOVE is not exposed (blocking; policy row in CommandCoverage.md).

Gated [Experimental] behind SER011 and the new RedisFeatures.v8_12_0_rc3
(8.11.242: rc2 does not have the commands); the test docker image moves to
client-libs-test:8.12-rc3.

* SLOWLOG GET: surface the 8.12 estimated-CPU-time field as CommandTrace.CpuTime

The 8th entry field (redis/redis#15907, 8.12 RC3) is the duration minus
the provable off-CPU time, distinguishing a command that ran slowly from
one starved of CPU. Parsed positionally past the client address/name and
argument count, so every historical entry length still parses: null when
the server did not send the field, zero (per the server) when it was not
measured. Gated SER011 with the rest of the 8.12 surface.

* Redis 8.12 GA: test against client-libs-test:8.12.0; SER011 stays while the library API settles

8.12.0 went GA on 2026-11-22. The docker test image moves from 8.12-rc3 to 8.12.0, and docs/exp/SER011.md now says the server is generally available while the library API remains experimental.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-notes indication that this issue needs to be mentioned in the release notes state:needs-doc-pr requires a PR to redis-doc repository

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

7 participants