Repository navigation
[backport] Backport sweep for 9.0 - #5073
Conversation
…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
AI backport resolution: source PR #4968Fix crash when a database's keyspace is replaced mid-stage during defrag 1 AI-edited file Claude Summary
AI-edited files requiring review
Full backport commit diff: commit 7763910e8e0e.
|
|
Important Review skippedBot user detected. To trigger a single review, invoke the
|
|
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. |
|
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 |
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
AI backport resolution: source PR #4995Fix GEOSEARCH repeated BYPOLYGON memory leak 1 AI-edited file Claude Summary
AI-edited files requiring review
Full backport commit diff: commit ce2bd0f45a5c.
|
|
Automatic follow-up on this backport's CI. The fix attempt for |
1 similar comment
|
Automatic follow-up on this backport's CI. The fix attempt for |
`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
AI backport resolution: source PR #5092Count expired but unreaped hash fields in objectComputeSize 1 AI-edited file Claude Summary
AI-edited files requiring review
Full backport commit diff: commit d6bf33e08662.
|
|
Automatic follow-up on this backport's CI. The fix attempt for |
|
Automatic follow-up on this backport's CI. The fix attempt for |
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
|
Automatic follow-up on this backport's CI. The fix attempt for |
|
Automatic follow-up on this backport's CI. The fix attempt for |
AI backport resolution: source PR #5191Clear stale cross-slot flag before computing a command's slot 1 AI-edited file Claude Summary
AI-edited files requiring review
Full backport commit diff: commit 7ce1762711e7.
|
|
Automatic follow-up on this backport's CI. No fix for What the bot checked
|
|
Automatic follow-up on this backport's CI. No fix for What the bot checked
|
|
Automatic follow-up on this backport's CI. No fix for What the bot checked
|
|
Automatic follow-up on this backport's CI. No fix for What the bot checked
|
|
Automatic follow-up on this backport's CI. No fix for What the bot checked
|
|
Automatic follow-up on this backport's CI. No fix for What the bot checked
|
`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.
12b1f25 to
23bd4e9
Compare
…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().
|
Looks mostly green! Merging it to unblock release. |
Backport sweep for 9.0
Automated cherry-picks from PRs marked "To be backported".
Applied
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)
Generated by valkey-ci-agent using Claude Code.