Skip to content

[backport] Backport sweep for 9.0 - #5073

Merged
sarthakaggarwal97 merged 90 commits into
9.0from
agent/backport/sweep/9.0
Nov 18, 2026
Merged

sarthakaggarwal97 merged 90 commits into
9.0from
agent/backport/sweep/9.0

Conversation

@valkeyrie-ops

@valkeyrie-ops valkeyrie-ops Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Backport sweep for 9.0

Automated cherry-picks from PRs marked "To be backported".

Applied

Source PR Title Detail
#4968 Fix crash when a database's keyspace is replaced mid-stage during defrag conflicts resolved by Claude Code
#4863 Fix module blocking of RESP3 Pub/Sub clients
#4775 Bound the time spent evicting keys from the tracking table
#4995 Fix GEOSEARCH repeated BYPOLYGON memory leak conflicts resolved by Claude Code
#5092 Count expired but unreaped hash fields in objectComputeSize conflicts resolved by Claude Code
#5133 Keep sds lengths in size_t when comparing and caching keys
#5046 Fix memory leak in GetCommandKeysWithFlags
#5210 Mark sorted-set increments and weights as doubles
#5128 Propagate PFADD elements applied before an INVALIDOBJ error
#5191 Clear stale cross-slot flag before computing a command's slot conflicts resolved by Claude Code
#5213 Represent valid expiry condition combinations in command metadata
#5118 Read Lua error table fields without invoking metamethods
#5159 Fill unmatched postponed reply lengths left by a module
#5212 Mark RESTORE IDLETIME and FREQ as mutually exclusive conflicts resolved by Claude Code
#5208 Fix SENTINEL SIMULATE-FAILURE argument metadata conflicts resolved by Claude Code
#3510 Fix TLS infinite busy loop when write/read handlers are removed
#4091 Fix crash when processing heartbeat from a node with no local role conflicts resolved by Claude Code
#4351 Fix NULL deref in usUntilEarliestTimer when all time events are deleted
#4171 Fix ping_sent getting stuck when peer traffic keeps link alive conflicts resolved by Claude Code
#4330 Reject non-migration clients for CLUSTER SYNCSLOTS FINISH
#4670 Reject repeated CLUSTER SYNCSLOTS ESTABLISH on the same connection
#4665 Check the SORT destination that is actually written
#4777 Fix geohashGetLatDistance() when latitudes are equal
#5187 Defer freeing the client that runs a replication role change
#5182 Exempt slot import SYNCSLOTS FINISH from the write pause assertion
#4785 Deflake COPY Preserves TTLs test under libc malloc cherry-picked in a prior sweep
#5178 Check XADD element size before creating the stream conflicts resolved by Claude Code
#5180 Redact HELLO, AUTH and MIGRATE credentials before validating arguments conflicts resolved by Claude Code
#5274 Free valkey-cli test hint before exiting cherry-picked in a prior sweep
#3772 Deflake diskless timeout rdb pipe test by tolerating either timeout-disconnect branch
#4251 deflake ccov: Use _exit() when a child is killed by SIGUSR1
#5126 Reject a +CONTINUE reply to PSYNC when there is no cached primary conflicts resolved by Claude Code; dropped target-missing test file(s): tests/helpers/fake_primary.tcl; ported target-missing test coverage to: tests/integration/replication.tcl
#5163 Fix integer overflow in _quicklistNodeAllowMerge size check conflicts resolved by Claude Code
#5151 Fix writevToClient stack overflow for empty bulk strings with copy avoidance conflicts resolved by Claude Code
#5137 Ignore ping extension values that nodes.conf cannot load conflicts resolved by Claude Code
#4190 Reclaim dead client IDs from the tracking table (#4143) conflicts resolved by Claude Code
#5161 Bound the bytes clusterReadHandler() reads per event conflicts resolved by Claude Code
#5120 Free repeated register_function named arguments conflicts resolved by Claude Code
#5245 Mark HEXPIREAT and HPEXPIREAT timestamps as unix-time
#5244 Mark mutually exclusive ZADD and LCS options conflicts resolved by Claude Code
#5167 Hash HRANDFIELD and SRANDMEMBER temporary tables case-sensitively conflicts resolved by Claude Code
#5184 Treat a replica with no known primary as owning no slots cherry-picked in a prior sweep
#5108 Share the Lua hook between coroutines so SCRIPT KILL reaches them all cherry-picked in a prior sweep
#5124 Reject sparse HLLs that end in a truncated XZERO opcode cherry-picked in a prior sweep
#5138 Fix hllSparseSet aborting on SDS_TYPE_5 strings when deltalen is zero cherry-picked in a prior sweep
#5146 Fix integer overflow in SORT BY/GET pattern key substitution cherry-picked in a prior sweep
#5155 Reject ValkeyModule_Calloc requests whose nmemb * size overflows cherry-picked in a prior sweep
#5157 Check for an attribute reply in RM_CallReplyAttributeElement cherry-picked in a prior sweep
#5158 Fail CONFIG REWRITE when the old config file reads short cherry-picked in a prior sweep
#5169 Dirty every client WATCHing a key that was expired at WATCH time cherry-picked in a prior sweep
#5443 Close the link on every dropped packet in the config epoch failover test cherry-picked in a prior sweep
#5440 Wait for the fork child before killing it in rdbloadsave test cherry-picked in a prior sweep
#5396 Wait for the primary to exit in the shutdown after block test cherry-picked in a prior sweep
#5315 CI: use supported macOS 15 runner cherry-picked in a prior sweep
#5211 Remove key specs from hash NUMFIELDS arguments cherry-picked in a prior sweep
#4875 Restore hex float parsing for sorted set scores cherry-picked in a prior sweep
#4805 Reset the ready-message counter after a port collision cherry-picked in a prior sweep
#3969 Avoid reusing stale test directories after PID collisions cherry-picked in a prior sweep
#4929 Guard NULL replica_primary_host in Sentinel INFO handling
#5087 Treat key specs that start past the last argument as matching no keys
#5088 Drop repeated EX/PX/EXAT when propagating HSETEX and MSETEX conflicts resolved by Claude Code
#5162 Free the ACL log object when the ACL log is disabled conflicts resolved by Claude Code
#5115 functions: key per-engine stats by registered name, not shebang text
#5164 Only resume a hash defrag scan from the hash scanner's own cursor conflicts resolved by Claude Code
#5105 Free functions ctx synchronously when its engine state is not handed over conflicts resolved by Claude Code
#5170 Rehash in proportion to scan work when sampling a shrinking hashtable conflicts resolved by Claude Code; dropped target-missing test file(s): src/unit/test_hashtable.cpp; ported target-missing test coverage to: src/unit/test_hashtable.c
#4711 Fix UAF in streams when XADD creates a new node
#5065 Cap the length of inbound cluster bus packets conflicts resolved by Claude Code
#5199 Keep the 'n' keyspace event flag when 'A' is set conflicts resolved by Claude Code
#4983 Fix for XINFO GROUPS reports too-high lag after XTRIM removes unread …
#5251 Fix CLUSTER GETSLOTMIGRATIONS reply schema
#5134 Do not adopt the MYSELF flag from a gossip entry conflicts resolved by Claude Code
#5033 Respect NOFAILOVER during shutdown failover
#5085 Disconnect default user subscribers to revoked channels on ACL LOAD conflicts resolved by Claude Code
#5349 Treat a torn annotation at the end of an AOF file as a short read conflicts resolved by Claude Code
#4313 Deflake diskless timeout replica count assertion
#5246 Allow null in SENTINEL GET-PRIMARY-ADDR-BY-NAME reply schema
#4377 Deflake qbuf fill waits in client-eviction tests
#5385 Run Daily on pull requests into agent/ branches
#5055 [deflake] Wait for valkey-server to accept connections in external server tests
#5435 Don't free the client that is executing a command when a blocked client's re-executed command evicts clients conflicts resolved by Claude Code

AI resolution details are posted as comments on this PR when available.

Needs attention

These candidates could not be applied automatically and need a maintainer to follow up.

2 candidate(s)
Source PR Title Outcome Reason
#4574 Fix script debugger uaf skipped-conflict target branch lacks conflicted file(s): src/modules/lua/debug_lua.c, src/modules/lua/engine_lua.c
#4954 Match listpack for lex range commands on mixed-score btree zsets skipped-conflict target branch lacks conflicted file(s): src/ordered_index.c

Generated by valkey-ci-agent using Claude Code.

taham0 and others added 2 commits October 28, 2026 09:09
…rag (#4968)

Clear `defrag_later` (and reset its cursor) at the start of every DbKeys defrag stage

Signed-off-by: Muhammad Taha <[email protected]>
Backport-Source-PR: 4968
moduleBlockClient() treated every subscribed client as unblockable because getClientType() returns CLIENT_TYPE_PUBSUB. A RESP3 client can still run commands while subscribed, so ValkeyModule_BlockClient and ValkeyModule_BlockClientOnAuth returned NULL with ENOTSUP and queued no reply. Allow blocking those clients again, matching the processCommand rule that only RESP2 Pub/Sub clients are restricted. Keyspace notifications still cannot block them.

Introduced by PR 1819 (8.1.1). Restores the pre-8.1.1 behavior for RESP3 subscribed clients; no change for RESP2 clients or keyspace-notification contexts.

Fixes #4862

---------

Signed-off-by: quanyeyang <[email protected]>
Signed-off-by: Rain Valentine <[email protected]>
Co-authored-by: Rain Valentine <[email protected]>
Co-authored-by: Roshan Khatri <[email protected]>
Backport-Source-PR: 4863
@valkeyrie-ops valkeyrie-ops Bot added ai-resolved-conflicts AI is used to resolve conflicts in automated backport PRs. backport Backport PR opened by valkey-ci-agent labels Oct 28, 2026
@valkeyrie-ops

valkeyrie-ops Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor Author

AI backport resolution: source PR #4968

Fix crash when a database's keyspace is replaced mid-stage during defrag

1 AI-edited file

Claude Summary

The conflict is resolved. Here's a summary of what I did:

Conflict cause: The upstream PR added a new test at the end of tests/unit/moduleapi/defrag.tcl, right after two tests ("global defrag resumes via cursor" and "global defrag is revisited on later cycles") that exist on unstable but were never backported to the 9.0 branch. The cherry-pick's context therefore didn't match, and git put the two missing tests plus the new test all on the incoming side of the conflict.

Resolution: I kept only the new test from the PR — Module defrag: FLUSHDB ASYNC while a deferred key is defragged — and dropped the two unrelated unstable-only tests, since pulling them in would have widened the backport beyond the PR's intent (they also depend on defragtest_global_resumes/defragtest_global_wrong_cursor stats that the 9.0 version of defragtest.c doesn't produce). The new test lands inside the if {[r config get activedefrag] ...} guard, directly after the existing "global defrag works" test, matching the upstream placement.

Verification:

  • No conflict markers remain in tests/unit/moduleapi/defrag.tcl.
  • Everything the new test uses exists on 9.0: wait_for_condition, getInfoProperty, fail, s, and the active_defrag_key_hits/active_defrag_key_misses INFO fields; frag.stall and the stall logic come from the auto-merged tests/modules/defragtest.c.
  • The auto-merged src/defrag.c change (clearing defrag_later and resetting defrag_later_cursor at the start of each DbKeys stage) references symbols that exist in the 9.0 file, and both C files pass a gcc -fsyntax-only check.
  • The final diff is 66 insertions across 3 files — identical in size to the upstream commit.

Per your instructions I did not run git add or git commit, so tests/unit/moduleapi/defrag.tcl still shows as unmerged (UU) in the index even though its content is fully resolved.

AI-edited files requiring review

  • tests/unit/moduleapi/defrag.tcl — view diff

Full backport commit diff: commit 7763910e8e0e.

Please review these AI resolutions for correctness before merging.

@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 99887896-446e-49af-8d1f-88df39dfa367

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@valkeyrie-ops

valkeyrie-ops Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Automatic follow-up for the current backport head.

I did not push a fix: This is a timing-dependent flake, not a deterministic failure: the identical test on the identical commit passed in ~20 sibling jobs in the same run (including io-threads-only and tls-only), and failed only in the slowest combination. No default-branch candidate commit touches this test or the offset-reporting path, and because the test passes almost always, no targeted command can deterministically reproduce the failure to verify a fix. Per the rules, flaky/timing-dependent failures are refused rather than patched.

Looked at the failure from this run.

@valkeyrie-ops

valkeyrie-ops Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Automatic follow-up for the current backport head.

I did not push a fix: the failure did not reproduce on a clean checkout; it is likely flaky or environment-specific, so refusing rather than pushing a fix

Looked at the failure from this run.

Evidence
STALL valkey-check-rdb
    INSTALL valkey-check-aof
    CC valkey-tls.so

Hint: It's a good idea to run 'make test' ;)

make[1]: Leaving directory '/tmp/ci-fix-3bids1gk/repo/src'
Cleanup: may take some time... OK
Starting test server at port 21079
[ready]: 4423
Testing integration/rdb
[ready]: 4424
[ready]: 4425
[ready]: 4429
[ready]: 4431
[ready]: 4430
[ready]: 4426
[ready]: 4427
[ready]: 4433
[ready]: 4434
[ready]: 4428
[ready]: 4438
[ready]: 4432
[ready]: 4436
[ready]: 4435
[ready]: 4437
=== () Starting server on 127.0.0.1:21111 ok
[ok]: test old version rdb file (0 ms)
=== () Starting server on 127.0.0.1:21112 ok
[ok]: RDB encoding loading test (6 ms)
=== () Starting server on 127.0.0.1:21113 
[ok]: RDB future version loading, strict version check (3 ms)
=== () Starting server on 127.0.0.1:21114 ok
[ok]: RDB future version loading, relaxed version check (9 ms)
=== () Starting server on 127.0.0.1:21115 
[ok]: RDB future version loading with unknown types, relaxed version check (2 ms)
=== () Starting server on 127.0.0.1:21116 ok
[ok]: RDB foreign version loading, relaxed version check (1 ms)
=== () Starting server on 127.0.0.1:21117 
[ok]: RDB foreign version loading with unknown types, relaxed version check (3 ms)
=== () Starting server on 127.0.0.1:21118 ok
[ok]: Server started empty with non-existing RDB file (0 ms)
=== () Starting server on 127.0.0.1:21119 ok
[ok]: Server started empty with empty RDB file (0 ms)
=== () Starting server on 127.0.0.1:21120 ok
[ok]: Test RDB stream encoding (113 ms)
Skipping umask test. Package Tclx not installed.
=== () Starting server on 127.0.0.1:21121 
[ok]: Server should not start if RDB file can't be open (3 ms)
=== () Starting server on 127.0.0.1:21122 
[ok]: Server should not start if RDB is corrupted (3 ms)
=== () Starting server on 127.0.0.1:21123 ok
[ok]: Test FLUSHALL aborts bgsave (221 ms)
[ok]: bgsave resets the change counter (104 ms)
[ok]: bgsave cancel aborts save (122 ms)
[ok]: bgsave cancel schedulled request (7 ms)
=== () Starting server on 127.0.0.1:21124 ok
[ok]: client freed during loading (1167 ms)
=== () Starting server on 127.0.0.1:21125 ok
[ok]: Test RDB load info (583 ms)
=== () Starting server on 127.0.0.1:21126 ok
Keys before bgsave start: 10000
COW info before copy-on-write: 0
current_save_keys_processed info : 0
COW info before copy-on-write: 1839104
current_save_keys_processed info : 1
[ok]: Test child sending info (1914 ms)
=== () Starting server on 127.0.0.1:21127 ok
[ok]: script won't load anymore if it's in rdb (1 ms)
=== () Starting server on 127.0.0.1:21128 ok

Waiting for background save to finish... 
Waiting for background save to finish... 
Waiting for background save to finish... 
Waiting for background save to finish... [ok]: failed bgsave prevents writes (243 ms)
[1/1 done]: integration/rdb (8 seconds)

                   The End

Execution time of different units:
  8 seconds - integration/rdb

\o/ All tests passed without errors!

Cleanup: may take some time... OK

tanmayBeginsJourney and others added 2 commits October 29, 2026 09:06
Limits time evicting from tracking table.

Signed-off-by: Tanmay <[email protected]>
Backport-Source-PR: 4775
Repeated `BYPOLYGON` options in `GEOSEARCH` and `GEOSEARCHSTORE`
overwrite the previous vertex array without freeing it. Only the final
array is released, leaking memory even when the source key does not
exist.

Free the previous vertices before allocating a replacement, preserving
the existing behavior of using the last polygon. Add
regression tests for both commands, invalid `COUNT` cleanup, and
retained memory across repeated requests.

is merged first, I'll rebase this PR and use the new name.

  Validation:
  - GEO suite: 75 passed.
- New tests with 4 I/O threads and `io-threads-always-active yes`: 2
passed.
- The leak regression fails against the parent commit and passes with
this fix.

Signed-off-by: DaeMyung Kang <[email protected]>
Backport-Source-PR: 4995
@valkeyrie-ops

valkeyrie-ops Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

AI backport resolution: source PR #4995

Fix GEOSEARCH repeated BYPOLYGON memory leak

1 AI-edited file

Claude Summary

The conflict in src/geo.c is resolved and the result matches the upstream PR exactly.

What the conflict was: The only conflict region was inside the comment block documenting GEOSEARCH syntax, just above georadiusGeneric() (src/geo.c:527). The target branch's comment line didn't mention BYPOLYGON (and had a pre-existing WITHASH typo), while the PR rewrote that line to document BYPOLYGON across two lines. I took the PR's side since it's a pure comment update that matches the surrounding GEOSEARCHSTORE documentation, which had already merged cleanly.

The actual fix — a geoPolygonPointsFree(&amp;shape) call before the vertex array is re-allocated in the BYPOLYGON parsing branch (src/geo.c:678) — had already applied cleanly and is intact. It frees any previously parsed polygon before allocating the replacement, fixing the leak when BYPOLYGON is repeated.

Verification:

  • No conflict markers remain in either file.
  • The resolved diff is identical in size to upstream: src/geo.c 5 insertions/2 deletions, tests/unit/geo.tcl 30 insertions.
  • The auto-merged test file's helpers all exist on this branch: assert_lessthan, assert_error, and assert_equal are defined in tests/support/test.tcl, and the external:skip tag is already used elsewhere in geo.tcl.
  • gcc -fsyntax-only on src/geo.c passes.

I did not run git add or git commit, and the untracked src/commands_with_reply_schema.def was already present before I started — I left it alone.

AI-edited files requiring review

Full backport commit diff: commit ce2bd0f45a5c.

Please review these AI resolutions for correctness before merging.

@valkeyrie-ops

valkeyrie-ops Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up on this backport's CI.

The fix attempt for test-sanitizer-address (clang) (run) stopped with an error: The CI-fix attempt failed: ci-fix-agent cannot reach /home/runner/work/valkey-ci-agent/valkey-ci-agent: /home/runner is not traversable.

1 similar comment
@valkeyrie-ops

valkeyrie-ops Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up on this backport's CI.

The fix attempt for test-sanitizer-address (clang) (run) stopped with an error: The CI-fix attempt failed: ci-fix-agent cannot reach /home/runner/work/valkey-ci-agent/valkey-ci-agent: /home/runner is not traversable.

sushilpaneru1 and others added 2 commits October 30, 2026 10:24
`objectComputeSize()` samples a hashtable-encoded hash with a validating
iterator, which skips fields whose TTL has passed but that have not been
reaped yet. Those fields still occupy memory, and `hashtableSize()`,
which the sampled average is multiplied by, still counts them. The
result is under-reported whenever expired fields are larger than live
ones.

**Example:** one small live field plus 99 expired 1 KB fields, with
active expiry disabled. `MEMORY USAGE` reports ~4 KB for a hash that
holds ~100 KB.

**Fix:** iterate with `HASHTABLE_ITER_SKIP_VALIDATION`. This matches the
rest of `objectComputeSize()`, where the listpack branch uses
`zmalloc_size()` and sets and sorted sets have no validator, and it
matches `rdbSaveObject()`, which already skips validation when walking
the hash. It also removes a dependency on expiry evaluation, which reads
server state a size estimate should not need.

Once expired fields are reaped the reported value is unchanged. Existing
`hashexpire.tcl` tests that check memory drops after expiry wait for
reaping first, so they are unaffected.

Adds a regression test to `tests/unit/hashexpire.tcl`.

Signed-off-by: Sushil Paneru <[email protected]>
Backport-Source-PR: 5092
dictSdsKeyCompare() and evictionPoolPopulate() stored sdslen() in an
int. At 2^31 bytes that is negative. dictSdsKeyCompare() then passes a
sign-extended length to memcmp(), which reads past the end of both
strings and can report two equal strings as different, so a set or hash
stores the same member twice, or crash. evictionPoolPopulate() takes the
short-key branch and memcpy()s a huge length into the 255 byte cached
sds, crashing the server.

dictSdsKeyCompare() became the comparator for every data hashtable in
fb655db (#3366), replacing hashtableSdsKeyCompare(), which compared
size_t lengths. The eviction pool narrowing is older.

Signed-off-by: Madelyn Olson <[email protected]>
Backport-Source-PR: 5133
@valkeyrie-ops

valkeyrie-ops Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

AI backport resolution: source PR #5092

Count expired but unreaped hash fields in objectComputeSize

1 AI-edited file

Claude Summary

Both files are resolved and verified. Summary of what I did:

Conflict resolution in tests/unit/hashexpire.tcl: The source PR added a new test, MEMORY USAGE counts expired but unreaped hash fields, immediately after an HMGET batch lookup skips expired hash fields test that exists on the unstable branch but not on 9.0. The cherry-pick conflicted because that surrounding context (including its set original_max / r config set hash-max-listpack-entries wrapper) is absent here. I resolved it by keeping only the new MEMORY USAGE test and dropping the neighboring unstable-only test and its config wrapper lines, placing the new test in the same start_server {tags {"hashexpire"}} block after the Hash Encoding Transitions with TTL - Create New Fields with TTL test — the same relative position it occupies upstream.

The test works without the hash-max-listpack-entries 0 wrapper because it stores 100 fields with 1000-byte values, which exceeds both the default hash-max-listpack-entries (128 is not exceeded, but) hash-max-listpack-value of 64 bytes, forcing hashtable encoding — and the test's own assert_encoding hashtable guards that assumption.

Verification done:

  • assert_morethan and assert_encoding helpers, HPEXPIRE/HLEN/HGET, MEMORY USAGE ... SAMPLES 0, and DEBUG SET-ACTIVE-EXPIRE all exist on the 9.0 branch; hashTypeLength uses hashtableSize so unreaped fields count toward HLEN (the test asserts 100), and hashtableFind validates expiry so HGET returns empty for the expired field — both assertions hold on 9.0.
  • src/object.c (auto-merged) uses HASHTABLE_ITER_SKIP_VALIDATION, which is defined in src/hashtable.h:103 on this branch; make object.o compiles cleanly.
  • No conflict markers remain, Tcl braces are balanced (info complete returns 1), and the resolved test-file diff is +29 lines, matching the upstream PR exactly.

I did not run git add or git commit, per instructions — the file remains unstaged for th
... summary truncated.

AI-edited files requiring review

Full backport commit diff: commit d6bf33e08662.

Please review these AI resolutions for correctness before merging.

@valkeyrie-ops

valkeyrie-ops Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up on this backport's CI.

The fix attempt for test-sanitizer-undefined (gcc) (run) stopped with an error: The CI-fix attempt failed: the fix job ended without a result (see https://github.com/valkey-io/valkey-ci-agent/actions/runs/41063016947).

@valkeyrie-ops

valkeyrie-ops Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up on this backport's CI.

The fix attempt for test-sanitizer-undefined (gcc) (run) stopped with an error: The CI-fix attempt failed: the fix job ended without a result (see https://github.com/valkey-io/valkey-ci-agent/actions/runs/41071507137).

christopherlim98 and others added 3 commits October 31, 2026 10:29
For large key lists, `ValkeyModule_GetCommandKeysWithFlags` allocates
temporary storage in `getKeysResult` and returns without freeing it.
This adds the missing cleanup after copying the positions and flags into
the returned arrays.

Fixes #5042

Signed-off-by: Christopher Lim <[email protected]>
Backport-Source-PR: 5046
The command metadata describes several sorted-set numeric arguments as
integers even though the command implementations accept floating-point
values:

- The `ZINCRBY` increment.
- `ZINTER` and `ZINTERSTORE` weights.
- `ZUNION` and `ZUNIONSTORE` weights.

This prevents metadata consumers from accurately representing valid
command arguments.

Credits to @madolson for finding this issue.

Signed-off-by: Sarthak Aggarwal <[email protected]>
Backport-Source-PR: 5210
PFADD with several elements applies them to the HLL in place, one at a
time. On a malformed sparse HLL, an early element can modify the key and
a later one can then fail with INVALIDOBJ. When that happened, PFADD
returned before `signalModifiedKey()`, the keyspace event and the
`server.dirty` update. The modified value stayed on the primary and
never reached replicas or the AOF, and it did not trip WATCH or client
tracking. This change finishes the bookkeeping for the elements that
were applied, and propagates a PFADD that carries only those elements.

Signed-off-by: Madelyn Olson <[email protected]>
Backport-Source-PR: 5128
@valkeyrie-ops

valkeyrie-ops Bot commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up on this backport's CI.

The fix attempt for test-sanitizer-address (run) stopped with an error: The CI-fix attempt failed: the fix job ended without a result (see https://github.com/valkey-io/valkey-ci-agent/actions/runs/41315820969).

@valkeyrie-ops

valkeyrie-ops Bot commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up on this backport's CI.

The fix attempt for test-sanitizer-address (run) stopped with an error: The CI-fix attempt failed: the fix job ended without a result (see https://github.com/valkey-io/valkey-ci-agent/actions/runs/41320817793).

@valkeyrie-ops

valkeyrie-ops Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

AI backport resolution: source PR #5191

Clear stale cross-slot flag before computing a command's slot

1 AI-edited file

Claude Summary

The fix is applied. Here's a summary of what I found and changed:

First real error: The build succeeded; the failure is a single test assertion in tests/unit/cluster/scripting.tcl (log lines 299–300). The test "Cross-slot command in a script does not break later script calls" expected the error pattern *non local key*, but the 9.0 branch actually returns:

ERR Command 'mget' in script attempted to access keys that don't hash to the same slot script: 1baa..., on @user_script:1.

Root cause: On 9.0, scriptVerifyClusterState (src/script.c:442-445) has a dedicated CLUSTER_REDIR_CROSS_SLOT message ("Command '%S' in script attempted to access keys that don't hash to the same slot"), whereas the source branch's test was written against a message containing "non local key" (the generic MOVED/ASK wording at src/script.c:458). This is purely an error-message difference between branches — the C fix itself (clearing stale READ_FLAGS_NO_KEYS/READ_FLAGS_CROSSSLOT in clusterSlotByCommand, src/cluster.c:987-989) compiled cleanly and is behaving correctly, as shown by the error being the cross-slot error rather than a stale-flag failure.

Fix: Updated the expected pattern in tests/unit/cluster/scripting.tcl:101 to match the target branch's actual error message, using the same prefix-plus-* style as the other assertions in that file:

assert_error "ERR Command 'mget' in script attempted to access keys that don't hash to the same slot*" {r 0 eval "return redis.call('mget', 'foo', 'bar')" 0}

The PR's intent is preserved: the test still verifies the first cross-slot call errors and, critically, that the subsequent ping script call returns PONG (the actual regression being guarded). No changes were needed in src/cluster.c, and no files outside the changed-file list were touched.

AI-edited files requiring review

  • tests/unit/cluster/scripting.tcl — view diff

Full backport commit diff: commit 7ce1762711e7.

Please review these AI resolutions for correctness before merging.

@valkeyrie-ops

valkeyrie-ops Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up on this backport's CI.

No fix for test-sanitizer-address (gcc) (run). The reported failure was not reproduced by code: no code-owned reproduction command could be established. No edit was attempted.

What the bot checked

@valkeyrie-ops

valkeyrie-ops Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up on this backport's CI.

No fix for test-sanitizer-force-defrag (run). The reported failure was not reproduced by code: no code-owned reproduction command could be established. No edit was attempted.

What the bot checked

@valkeyrie-ops

valkeyrie-ops Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up on this backport's CI.

No fix for test-sanitizer-undefined (gcc) (run). The reported failure was not reproduced by code: every reproduction probe passed without reproducing the failure. No edit was attempted.

What the bot checked

@valkeyrie-ops

valkeyrie-ops Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up on this backport's CI.

No fix for test-ubuntu-libc-malloc (run). The reported failure was not reproduced by code: every reproduction probe passed without reproducing the failure. No edit was attempted.

What the bot checked

@valkeyrie-ops

valkeyrie-ops Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up on this backport's CI.

No fix for test-sanitizer-address (clang) (run). The reported failure was not reproduced by code: the reproduction stopped without reproducing the failure. No edit was attempted.

What the bot checked

@valkeyrie-ops

valkeyrie-ops Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up on this backport's CI.

No fix for test-sanitizer-force-defrag (run). The reported failure was not reproduced by code: no code-owned reproduction command could be established. No edit was attempted.

What the bot checked

smkher and others added 23 commits November 17, 2026 20:56
`sentinelRefreshInstanceInfo()` passes `ri->replica_primary_host` into
`sentinelAddrEqualsHostname()` without a NULL check. If a monitored
replica's INFO reply has `role:slave` and a matching `master_port` but
no `master_host`, the host stays NULL and the comparison falls through
to `strcasecmp()` on NULL, crashing Sentinel.

Added a fix to guard the comparison with a NULL check, mirroring the
sibling branch below that already requires `replica_primary_host`.

Signed-off-by: Saurabh Kher <[email protected]>
Backport-Source-PR: 4929
…#5087)

`PFMERGE destkey` with no source keys is valid, but its source key spec
starts past the end of argv, and key-spec extraction treats that as a
syntax error that drops every key, destkey included. PFMERGE has no
getkeys_proc to fall back on, so ACL sees no keys: a user limited to
`~allowed*` or `%R~*` can create an empty HyperLogLog under any key
name, and `COMMAND GETKEYS PFMERGE k1` returns an error. An index spec
that starts past the last argument now matches nothing, like a keyword
spec whose keyword is absent, which also fixes module commands with
optional trailing keys and a module keynum spec in that position that
crashed the server.

Signed-off-by: Madelyn Olson <[email protected]>
Backport-Source-PR: 5087
HSETEX and MSETEX accept a repeated EX, PX or EXAT and apply the last
one, but when propagating they rewrite only that last pair to PXAT and
keep the earlier ones. Replicas and AOF loading get `HSETEX h EX 100
PXAT <ms> FIELDS 1 f v`, reject it as a syntax error, and the write is
missing on the replica and lost after an AOF reload. This drops the
earlier pairs, so only the expiry that was applied is propagated, the
same as SET, GETEX and HGETEX.

Release-branch adaptations contributed by Sarthak Aggarwal <[email protected]>.

Signed-off-by: Madelyn Olson <[email protected]>
Backport-Source-PR: 5088
Backport-Source-Commit: 7035f41
Backport-Adaptation: Preserve the native parser while exposing the source fix's expiry argument index. Select the last expiry by argument position, including when a module aliases expiry argument objects. Cover aliased EX, PX and EXAT in the native module hash regression.
With `acllog-max-len 0`, every script command refused by ACL leaks a
copy of the refused key or command name. `addACLLogEntry()` takes
ownership of its `object` argument, but its early return for a disabled
log never frees it. Since Lua runs as a module,
`server.call`/`server.pcall` reach the ACL check through `VM_Call`,
which hands over a fresh copy on each refusal, so one `EVAL` looping
`pcall` over a large denied key name grows `used_memory` without bound
until restart. The fix frees `object` on that return.

Signed-off-by: Madelyn Olson <[email protected]>
Backport-Source-PR: 5162
Backport-Adaptation: Use the native CONFIG SET command in the ACL-log regression.
…5115)

`functionsCreateWithLibraryCtx()` stores the per-engine stats entry
under the raw shebang engine name (`md.engine`). `libraryLink()` looks
it up under the registered engine name
(`scriptingEngineGetName(engine)`). When `sdsnsplitargs()` decodes an
escape sequence in a quoted shebang — e.g. `#!"lua\x00zz" name=mylib`
delivers a 6-byte sds with a NUL at position 3 — the two keys hash to
different buckets in `engineStatsDictType` (which hashes on `sdslen()`).
The lookup returns NULL and `serverAssert(stats)` fires at
`src/functions.c:370`.

The fix is one line: pass `scriptingEngineGetName(engine)` instead of
`md.engine` to `functionsAddEngineStats()`.

Signed-off-by: Madelyn Olson <[email protected]>
Backport-Source-PR: 5115
)

With active defrag on, replacing a large set, sorted set or list with a
hashtable-encoded hash while defrag is partway through it (RENAME, or
DEL then HSET) crashes the server with SIGSEGV. Defrag resumes large
keys with one cursor shared by every type, and `hashTypeScanDefrag()`
treats any non-zero cursor as the address of its own static iterator, so
it dereferences the previous collection's bucket index or rank. The fix
resumes only from that iterator's address and otherwise starts a fresh
scan of the hash.

Signed-off-by: Madelyn Olson <[email protected]>
Backport-Source-PR: 5164
…over (#5105)

When FUNCTION RESTORE replaces or refuses more than 64 functions, the
old ctx is lazy freed, but its functions are still registered in the
live Lua state. If FUNCTION FLUSH SYNC runs before that job, it closes
the Lua state and opens a new one, which libc usually puts at the same
address. The job then passes the `lua == script->lua` check and unrefs
registry slots that now belong to newly loaded functions, so FCALL on
them fails with `attempt to call a number value` or aborts on
`ValkeyModule_Assert(!lua_isnil(lua, -1))`. This patch frees such a ctx
synchronously and keeps lazy free only for FUNCTION FLUSH ASYNC, where
the job also owns closing the old Lua state.

Signed-off-by: Madelyn Olson <[email protected]>
Backport-Source-PR: 5105
Backport-Adaptation: Save, set and restore lazyfree-lazy-user-flush explicitly in the native test harness.
…#5170)

While a hashtable shrinks, every random pick (ZRANDMEMBER, SRANDMEMBER,
SPOP, HRANDFIELD) scans all the old-table buckets that map to one bucket
of the new table, but advances the shrink by only one rehash step of at
most 10 empty buckets. A small key left over from a large one therefore
pays the whole old table on every pick until about B/10 picks have gone
by: `ZRANDMEMBER z -1000` on a 6-member zset trimmed from 1M members
blocks for 3.7 s. This makes sampling rehash at least as many old
buckets as its scans visited, so the shrink finishes after linear total
work.

Signed-off-by: Madelyn Olson <[email protected]>
Backport-Source-PR: 5170
Fixes #4705.

### Summary

`XADD` can leave a stream's radix tree holding a **dangling pointer to a
freed
listpack**. When the entry is later read (`XRANGE`, `XREVRANGE`,
`XINFO STREAM ... FULL`), we hit UB.

### Root cause

In `streamAppendItem()`, when a `XADD` cannot append to the current tail
node, the tail node is shrunk to fit,
that in turn might relocate it to a different location in memory, while
`ri.data` is kept pointing to the old dangling pointer.

```
if (new_node) {
    lp = lpShrinkToFit(lp); <------ lp is moved to a new location in memory
    if (ri.data != lp) raxInsert(s->rax, ri.key, ri.key_len, lp, NULL);
    lp = NULL;
    <----- ri.data is still pointing to the old dangling pointer
}
```

After which a new node is created & is inserted.

```
    lp = lpNew(prealloc);
    ....
    raxInsert(s->rax, (unsigned char *)&rax_key, sizeof(rax_key), lp, NULL);
    <---- lp is now pointing to a new location different from ri.data (will later dangle)
```

Following that multiple appends happen on that node, that operation
might reallocate it & it's possible that the final
allocation might just happen to reallocate to the same location as the
original node `ri.data`, I.E. `ri.data == lp`

Due to this unfortunate allocation, the radix tree will never be updated
with the latest values leaving it with a dangling pointer

```
if (ri.data != lp) raxInsert(s->rax, (unsigned char *)&rax_key, sizeof(rax_key), lp, NULL);
<---- This check fails as ri.data == lp
```

### Fix

- A new `rax_lp` variable is now used track the need to update the radix
tree along side the origin `lp`
- remove `raxInsert` when a new node is created to avoid sending a
pointer to the radix tree that might later get invalidated

### Testing

Added an integration test in `tests/unit/type/stream.tcl` that reliably
fails with jemalloc without the fix

---------

Signed-off-by: Bara' Hasheesh <[email protected]>
Co-authored-by: Ran Shidlansik <[email protected]>
Backport-Source-PR: 4711
A cluster bus peer can send a header claiming a packet of up to 4GB, and
the node keeps the link open and grows its receive buffer until the
whole body arrives, because the header's length is only checked against
a minimum. This rejects packets over 16MB as soon as the header is read,
on both the main-thread and IO-thread read paths, for every type except
PUBLISH, PUBLISHSHARD and MODULE, whose client-supplied payloads can
legitimately be larger. Reported by Petr Khartskhaev.

Signed-off-by: Madelyn Olson <[email protected]>
Backport-Source-PR: 5065
`n` (new key events) is not part of `A`, but
`keyspaceEventsFlagsToString()` only prints `n` when `A` is not set. So:

```
CONFIG SET notify-keyspace-events KEAn
CONFIG GET notify-keyspace-events   -> "AKE"
```

New key events still fire at runtime, but `CONFIG REWRITE` saves
`"AKE"`, so after a restart they silently stop.

The fix prints `n` outside the `A` branch, the same way `m` is handled.
`KEAn` now reads back as `AnKE`. Added the case to the existing CONFIG
GET/SET flags test.

Signed-off-by: Aman Kumar <[email protected]>
Backport-Source-PR: 5199
#4983)

Fixes [#4979 ](#4979)

`XINFO GROUPS` / `XINFO STREAM ... FULL` reported a `lag` that was too
high after `XTRIM` (or `XADD` with a trimming option) removed entries
the group had not read yet.

`streamReplyWithCGLag` trusts the group's `entries-read` counter when no
tombstone sits after the group's last ID. `XTRIM` does not update
`max_deleted_entry_id`, so after a trim Valkey believed nothing was
deleted and computed `entries_added - entries_read`, which counts the
trimmed entries as still pending.

If the group's last ID is before the stream's first entry and no
tombstone follows it, everything left in the stream is unread, so the
lag is now the stream length.

Example (6 entries, group has read 0-1, then `XTRIM s MAXLEN 2`):

| | Before | After |
|---|---|---|
| `lag` | 5 | 2 |

Tests:
- Added "Consumer group lag after XTRIM removes unread entries" to
`tests/unit/type/stream-cgroups.tcl`.
- Corrected the expected lag in "Consumer group lag with XTRIM" (2 to 1)
and "Consumer group lag with XADD trimming" (3 to 2). Both trim an
unread entry and asserted the old, incorrect value.

---------

Signed-off-by: Sasidharan Gopal <[email protected]>
Backport-Source-PR: 4983
Rename link_name to name in the CLUSTER GETSLOTMIGRATIONS reply
schema to match clusterCommandGetSlotMigrations(). The native 9.0
command does not emit remaining_repl_size, so that newer field is
excluded from this backport.

Release-branch adaptations contributed by Sarthak Aggarwal <[email protected]>.

Signed-off-by: SHUVA JYOTI KAR <[email protected]>
Backport-Source-PR: 5251
Backport-Source-Commit: eda518a
Backport-Adaptation: Describe only fields emitted by the native 9.0 command.
When a gossip entry names a node we don't know,
`clusterProcessGossipSection()` creates it with the entry's wire flags
unchanged, including `CLUSTER_NODE_MYSELF`. One such packet on the
cluster bus leaves the receiver with two nodes flagged myself. Nothing
visible happens until the next start, which fails on
`serverAssert(server.cluster->myself == NULL)` in `clusterLoadConfig()`,
and keeps failing until `nodes.conf` is edited by hand. The fix clears
MYSELF before creating the node.

Signed-off-by: Madelyn Olson <[email protected]>
Backport-Source-PR: 5134
Resolves #5031.

Shutdown-triggered failover can promote a `NOFAILOVER` replica,
bypassing `cluster-replica-no-failover yes`.

This PR excludes `NOFAILOVER` replicas from shutdown failover. If no
fully synchronized, eligible replica is available, shutdown proceeds
without proactive promotion. Explicit manual failovers remain unchanged.

---------

Signed-off-by: Simonas Rupsys <[email protected]>
Backport-Source-PR: 5033
…5085)

When `ACL LOAD` narrows the default user's channel permissions, existing
default user connections subscribed to a now-denied channel are not
disconnected and keep receiving every message published there.
Subscribers of every other user are disconnected correctly.
`ACLLoadFromFile()` copies the new default rules into `DefaultUser` in
place before it checks subscribers, so for a default user client the old
and new user are the same object and nothing looks revoked. The fix runs
`ACLKillPubsubClientsIfNeeded()` for the default user before the copy,
which is what `ACL SETUSER` already does.

Signed-off-by: Madelyn Olson <[email protected]>
Backport-Source-PR: 5085
)

An annotation line without a newline at the end of an AOF file, such as
a #TS line cut short by a crash, was skipped when loading. The next
write was then appended to that line, so the next load skipped the start
of that command and failed with a format error.

The loader now treats such a line as a short read: with
aof-load-truncated yes, the file is truncated before it, and otherwise
the load fails with the usual unexpected end of file error.
valkey-check-aof reports it the same way, so --fix truncates it.

Signed-off-by: sumitk163 <[email protected]>
Backport-Source-PR: 5349
## What changed

Correlate the diskless timeout branch with the exact pipe-completion
count: `(full sync)` requires one replica still up, while `(streaming
sync)` requires two. Keep the exact-one timeout guard and use
`wait_for_log_messages` directly so its native diagnostic is preserved.

Fixes #4209.

## Why

The two timeout branches are both legitimate, but their pipe counts are
not interchangeable. Accepting either count unconditionally could hide
incorrect pipe bookkeeping for the branch that actually fired.

## Verification

On Linux, an intentionally inverted mapping failed at the derived
pipe-log assertion. The corrected focused test passed, followed by
100/100 sequential repetitions; all local repetitions observed `(full
sync)` with one replica still up. The macOS Daily test remains pending.

---------

Signed-off-by: Taeknology <[email protected]>
Backport-Source-PR: 4313
### Problem

SENTINEL GET-PRIMARY-ADDR-BY-NAME and its deprecated alias SENTINEL
GET-MASTER-ADDR-BY-NAME reply with a null when no monitored primary has
the given name ("*-1" in RESP2, "_" in RESP3), but the reply schema in
src/commands/sentinel-get-primary-addr-by-name.json and
sentinel-get-master-addr-by-name.json described only the two-element
address array. The reply schema validator,
utils/req-res-log-validator.py, checks the replies logged by a
LOG_REQ_RES build against these schemas and rejects the null with "None
is not of type 'array'". This change adds a null branch to both schemas
and a sentinel test that queries an unknown name. The server reply does
not change.

The gap has not shown up in the daily reply-schemas-validator job so
far, because every existing sentinel test queries a monitored name. Any
test that asks for an unknown name makes the job fail.

### Fix

Each schema becomes a oneOf of the existing address array and null, the
form commands such as GET use for a missing key. Both JSON files change
because the alias has its own schema and the validator looks the schema
up by the command name the client sent.

The reply schema exists only in LOG_REQ_RES builds, so a normal build is
not affected.

### Testing

The Tcl test passes on the base too, because the server already sends
the null; the check that fails without the fix is the validator on the
logged traffic.

Under --force-resp3, the mode the daily job uses, the test checks only
the RESP3 reply: the validator reads a logged RESP2 "*-1" as an empty
array, which has fewer than two items and is not null, so it matches
neither branch. That validator limitation is not changed here.

### Related change

#5209 adds the same null branch
form for other commands; the two PRs touch disjoint files and can merge
in any order.

Signed-off-by: Rain Valentine <[email protected]>
Backport-Source-PR: 5246
The two exact-fill qbuf waits in tests/unit/client-eviction.tcl timed out on a loaded CI runner: in a test-fedorarawhide-tls-module run, each CLIENT LIST poll took about 120 ms, so the 200 x 10 ms budget of two seconds was spent after about 28 seconds of wall time while the fill itself was fine. This change moves both waits into a shared helper, wait_for_qbuf_size, that polls 500 x 100 ms (50 seconds). These waits target an exact value that then stays stable: the test parks an incomplete multibulk payload, so the command never completes and qbuf remains at the expected size. A larger budget therefore cannot hide a wrong value or a stalled fill; those cases still time out. The coarser interval also reduces the polling load on the server.

The smaller >= waits in the same file are unchanged because they have slack and were not involved in the failure.

Test-only change. No server behavior or compatibility impact.

Fixes #4324

---------

Signed-off-by: Tarik Ermis <[email protected]>
Co-authored-by: Rain Valentine <[email protected]>
Backport-Source-PR: 4377
Extra tests for pulls into the agent/ branches (backports)

---------

Signed-off-by: Sarthak Aggarwal <[email protected]>
Backport-Source-PR: 5385
…rver tests (#5055)

`valkey-server --daemonize yes` returns before the listener is bound, so
the next step sometimes runs first and fails with `Could not connect to
Valkey at 127.0.0.1:6379: Connection refused` before any test executes.
Seen on unstable in
https://github.com/valkey-io/valkey/actions/runs/40357362301/job/121693295920
and on PR 5049 in
https://github.com/valkey-io/valkey/actions/runs/40457332228/job/122033601627;
44 of the last 300 failed runs of this workflow (2026-08-24 to
2026-10-27) died in this step, including on unstable, 9.2 and 8.0
pushes. Poll PING until it answers PONG, bounded at 30 seconds.

Signed-off-by: Rain Valentine <[email protected]>
Backport-Source-PR: 5055
…nt's re-executed command evicts clients (#5435)

Fixes #5422

---------

Release-branch adaptations contributed by Sarthak Aggarwal <[email protected]>.

Signed-off-by: nadav-levanoni <[email protected]>
Signed-off-by: Ran Shidlansik <[email protected]>
Co-authored-by: Ran Shidlansik <[email protected]>
Backport-Source-PR: 5435
Backport-Source-Commit: 339d861
Backport-Adaptation: Include upstream's existing two-word client-flag storage prerequisite so normal, AOF and recycled module-client initialization covers all 65 native active flags after adding processing_command. The prerequisite comes from dcf8191; CallArgv and other newer features are not imported.
Baraa-Hasheesh and others added 3 commits November 18, 2026 07:56
…ow runners (#5456)

The test added in #5435 failed in CI

Signed-off-by: Bara' Hasheesh <[email protected]>
Backport-Source-PR: 5456
Backport-Source-Commit: 3fc96b1
…5467)

The BLMPOP + maxmemory-clients test failed in both `--tls-module` EL9
jobs of a Daily run
([almalinux9](https://github.com/valkey-io/valkey/actions/runs/44253401795/job/134629245183),
[centosstream9](https://github.com/valkey-io/valkey/actions/runs/44253401795/job/134629245235))
with `I/O error reading reply`.

### Cause

The test sets `maxmemory-clients` to the measured total plus 1MB. The
two BLMPOP replies together are about 4.35MB. When the kernel socket
buffers absorb little of them, the waiters' replies alone stay over the
limit after the executing client is evicted, so `waiter_a` is evicted
too and its read fails. The server log shows both evictions in the same
millisecond.

### Fix

Raise the margin to 1.5MB. The margin has two bounds:
- **Lower:** the waiters must stay under the limit once the executing
client is gone. With 1.5MB they sit 520-750KB under. With 1MB they would
land between 4KB under and 226KB over.
- **Upper:** it must stay below one served reply (~2.17MB), so the
executing client is still over the limit mid-command. That is the path
from #5422. With the `processing_command` skip removed, the test still
crashes at 1.5MB. At 2.5MB it passes, so it would no longer cover the
bug.

### Testing

| Setup | Before | After |
|---|---|---|
| TLS, one CPU shared with two CPU hogs | 4/50 failed | 0/50 |

Signed-off-by: Bara' Hasheesh <[email protected]>
Backport-Source-PR: 5467
Backport-Source-Commit: 448950e
…3719)

## Summary

This PR addresses 2 race conditions where deferred `freeClient`
(introduced by #3324) clobbers replication state set by `REPLICAOF`
commands.

Found while triaging the recurring `test-ubuntu-tls-io-threads` daily CI
failure in `tests/unit/wait.tcl`.

## Root Cause

Since PR #3324 ("Redesign IO threading communication model"),
`freeClient()` on a primary client with pending IO is deferred via
`freeClientAsync` (gated on `clientHasPendingIO`). When the deferred
free eventually executes, it chains through `replicationCachePrimary()`
-> `replicationHandlePrimaryDisconnection()`, which unconditionally sets
`server.repl_state = REPL_STATE_CONNECT`.

This causes two bugs:

### Bug 1: REPLICAOF NO ONE (SIGSEGV)

`replicationUnsetPrimary()` sets `primary_host = NULL` before calling
`freeClient`. The deferred free runs later, sets `repl_state =
REPL_STATE_CONNECT` while `primary_host` is still NULL.
`replicationCron` then calls `connectWithPrimary()` which passes NULL to
`connTLSConnect()` -> `inet_pton(AF_INET, NULL, ...)` -> SIGSEGV.

### Bug 2: REPLICAOF newhost newport (connection leak)

`replicationSetPrimary()` calls `freeClient(old_primary)` (deferred),
then sets `primary_host` to the new IP and progresses `repl_state` to
`REPL_STATE_CONNECTING` with a new connection handle in
`server.repl_transfer_s`. The deferred free runs later, clobbers
`repl_state` back to `REPL_STATE_CONNECT`. `replicationCron` then calls
`connectWithPrimary()` again, overwriting `server.repl_transfer_s`
without closing the previous connection -- an FD leak.

## Fix

Make `replicationHandlePrimaryDisconnection()` only transition to
`REPL_STATE_CONNECT` when `repl_state` is still `REPL_STATE_CONNECTED`
and `primary_host` is set. This means the disconnection is genuine and
no other state transition has already occurred. If `repl_state` has
already moved on (CONNECT, CONNECTING, NONE, etc.), the deferred free is
stale and the function leaves the state untouched.

Additionally:
- `connTLSConnect()`: Return `C_ERR` if `addr` is NULL (defense in
depth).
- `tests/unit/wait.tcl`: Add 10s timeout to the blocking WAITAOF test,
and add dedicated tests for the repoint scenario.

## Reproduction

Reproduced locally by establishing TLS replication and executing
`REPLICAOF NO ONE`:
- Without fix: server crashes with signal 11, accessing address 0x0
- With fix: server continues operating normally

## Testing

- Full `unit/wait` test suite passes (51/51) with IO threads enabled
- New tests "Repoint replica between primaries does not leak connections
or crash" and "Rapid repoint does not crash or leak" pass
- Crash reproduced locally over TLS (SIGSEGV without fix, graceful
handling with fix)

---------

Signed-off-by: Yaron Sananes <[email protected]>
Signed-off-by: Ran Shidlansik <[email protected]>
Co-authored-by: Ran Shidlansik <[email protected]>
Backport-Source-PR: 3719
Backport-Source-Commit: 0321a69
Backport-Adaptation: Needed by the #5187 backport on 9.0. Its deferred free of the primary client otherwise resets repl_state to CONNECT after REPLICAOF NO ONE, so replicationCron reconnects to a NULL primary host and full-syncs away writes. The DEBUG force-free-primary-async hook is adapted to this branch's argv accessor and void freeClient().
@sarthakaggarwal97
sarthakaggarwal97 merged commit e185016 into 9.0 Nov 18, 2026
92 of 94 checks passed
@sarthakaggarwal97

Copy link
Copy Markdown
Contributor

Looks mostly green! Merging it to unblock release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai-resolved-conflicts AI is used to resolve conflicts in automated backport PRs. backport Backport PR opened by valkey-ci-agent

Projects

None yet

Development

Successfully merging this pull request may close these issues.