Skip to content

fix(cluster): don't hang connect() or commands on an unreachable node (#3592) - #3652

Merged
nkaradzhov merged 11 commits into
redis:masterfrom
Cdineshreddy12:fix/3592-on-3628
Nov 25, 2026
Merged

nkaradzhov merged 11 commits into
redis:masterfrom
Cdineshreddy12:fix/3592-on-3628

Conversation

@Cdineshreddy12

@Cdineshreddy12 Cdineshreddy12 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Closes #3592. Built on top of #3628 (now merged), which this reuses for the role-change-mid-connect case.

Follows the three-point plan from the issue. Point 2 is the bounded wait agreed in the thread below, replacing the queue-routing approach this PR originally carried.

1. connect() no longer waits for the node/pub-sub connections

#discover installs the slot map and then lets the node and pub/sub clients keep connecting in the background instead of await Promise.all(...)-ing them. One unreachable master now costs only its own shard — connect() (and a topology refresh) resolve on the topology, the way minimizeConnections: true already behaves. The detached node connects' failures surface through each client's node-error event, and the .catch(() => {}) is scoped to those: a pub/sub resubscribe failure is emitted instead (see 4).

2. The wait for a connecting node is bounded by the command timeout

nodeClient() keeps awaiting connectPromise, #waitForNodeClient and #3628's role-change retry included. The await is raced against the cluster's command timeout — { timeout: DEFAULT_COMMAND_TIMEOUT, ...commandOptions }.timeout, 5 s by default — and rejects with TimeoutError when it runs out, so an unreachable node no longer holds its commands forever. An explicit commandOptions.timeout: undefined keeps the unbounded await. No per-command timeout or abortSignal is threaded into it.

3. A node that never became ready counts for topologyRefreshOnReconnectionAttemptStrategy

Dropped the wasReady guard in the node client's reconnecting handler, so a node that is down from the start also triggers the reconnection-attempt topology refresh — otherwise its slots could never move after a failover promotes a replica. JSDoc and docs/clustering.md updated to match.

4. A refresh mid-connect no longer drops pub/sub listeners

#initiatePubSubClient() assigns this.pubSubNode synchronously but only attaches the listeners once its connect resolves. A refresh landing in that window read an empty listener set off the new client and dropped the subscriptions, which point 1 made reachable by detaching the re-init. The pending set is now kept on the node as toResubscribe until the resubscribe lands, and a refresh merges it. A resubscribe failure that is not a superseded attempt is emitted as error rather than being swallowed.

Tests

index.spec.ts adds two integration tests over the existing net-stub harness:

  • a master on a dead port → connect() resolves, a command to a live shard succeeds, a command to the dead shard rejects with TimeoutError;
  • after a failover with topologyRefreshOnReconnectionAttemptStrategy, the promoted replica serves the migrated shard.

clusterEvents → "should fire events" asserted a fixed event interleaving. Point 1 detaches the node connects from connect(), so connect no longer has a fixed position relative to node-ready and that assertion became a race; it now asserts the event counts, that disconnect closes the log, and that a node connects before it is ready.

Notes for review

  • Behavior change worth a release note: connect() now resolves on the topology without waiting for the per-node connections (like minimizeConnections: true). Code that assumed every node was connected the moment connect() resolved will see the connects complete slightly later.
  • Scenario (c) from the issue (a MOVED naming an unreachable node) is covered in substance by the failover test's "later routing still works" tail; I approximated the exact MOVED-to-unreachable wire shape rather than reproducing it precisely — happy to add a dedicated case if you'd like the exact shape.
  • The cluster integration tests are CI-only (the harness needs docker --network host), so I verified tsc, eslint and cluster-slots.spec.ts locally and am relying on CI for the suite.

Note

Medium Risk
Changes when connect() resolves and how commands time out on dead shards—callers that assumed all nodes were connected immediately may need to handle later node-ready and TimeoutError on affected keys.

Overview
Fixes cluster hangs when a shard master is unreachable (#3592). connect() and topology refresh now install the slot map without blocking on per-node (or detached pub/sub) handshakes; unreachable nodes only affect their own shard and failures still surface via node-error and reconnect-driven refreshes.

Command and subscribe paths wait on in-flight node connects with a bounded deadline tied to cluster commandOptions.timeout (default 5s), rejecting with TimeoutError instead of waiting forever; timeout: 0 / disabled keeps the wait unbounded. Connect waiters share one settlement handler per connectPromise to avoid listener leaks on retries.

topologyRefreshOnReconnectionAttemptStrategy now counts nodes that never reached ready, so failover can refresh topology and move slots off a master that was down from the start.

Pub/sub keeps pending listeners on toResubscribe through refreshes mid-connect, merges them on rediscovery, uses bounded waits for user-facing subscribe/unsubscribe but unbounded waits for internal resubscribe after failover/MOVED/migration.

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

One unreachable master no longer hangs connect() or a topology refresh:
discover installs the slot map and lets the node and pub/sub connects
keep warming in the background, the way minimizeConnections already
behaves. Their failures surface through node-error events.

A node that never became ready now also counts for
topologyRefreshOnReconnectionAttemptStrategy, so the slots of a node
that is down from the start can move once a failover promotes a
replica. Docs and JSDoc updated accordingly.

Part of redis#3592: command routing to a not-yet-connected node (so the
command timeout applies instead of waiting on connectPromise) follows
on top of redis#3628.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T11:13:45.857361Z 91b1ce3 New commits
ℹ️ 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: fea3585ff7

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// client (flushed with the connect error) and the 'node-error' event.
this.#createNodeClient(node).catch(() => {});
}
return Promise.resolve(node.client!);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve initial connection waits when offline queuing is disabled

With minimizeConnections: true and defaults.disableOfflineQueue: true, the first command to each previously unused node now fails with ClientOfflineError, even when the node is healthy. Returning the newly created client immediately sends the command through RedisClient.sendCommand() before readiness, where the disabled-offline-queue check rejects it. Previously, nodeClient() waited for the initial connection, so this configuration worked. Preserve a bounded initial connection wait for clients that cannot accept queued commands.

Useful? React with 👍 / 👎.

Comment on lines +445 to +446
for (const promise of promises) {
promise.catch(() => {});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve listeners before detaching Pub/Sub reconnections

If successive topology refreshes replace the Pub/Sub node while the first replacement is still connecting, existing subscriptions are permanently lost. #initiatePubSubClient(toResubscribe) installs the saved listeners only after connect() resolves, so a second #discover() sees empty listener maps on that replacement, destroys it, and starts no further resubscription. The saved maps remain only in the abandoned connection's closure. Awaiting these promises previously serialized the refreshes until the listeners were installed; persist the listeners synchronously before allowing discovery to finish.

Useful? React with 👍 / 👎.

Comment on lines +911 to +913
this.#createNodeClient(node).catch(() => {});
}
return Promise.resolve(node.client!);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Settle graceful close when an initial node connection fails

If cluster.close() starts after a command has entered this new pre-connect queue but before the node's TCP connection completes, a subsequent connection failure leaves the close promise pending forever. RedisClient.close() waits for data or end while its queue is nonempty. The initial-connect failure handler then flushes that queue through client.destroy(), but RedisSocket.destroy() returns without emitting end because close already cleared isOpen and no socket was assigned. The command rejects, yet graceful shutdown never finishes. Ensure initial-connect failure also settles a draining close when enabling this queuing path.

Useful? React with 👍 / 👎.

@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 packages/client/lib/cluster/index.ts Resolved
@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

Thanks for the Codex/Bugbot pass — I went through all of it. Most of the findings are real, and taken together they point at one design question in the point-2 command routing that I'd like your call on before I push, since it shapes four of the six.

The core question: route into the connecting client's queue, or keep a (bounded) wait?

As I built point 2, nodeClient() returns the possibly-still-connecting client synchronously, so the command lands in that client's offline queue and the command deadline bounds it. That removes the unbounded connectPromise await, but it trades it for three edges the bots caught:

  • disableOfflineQueue: true: with no offline queue, the first command to a fresh node rejects with ClientOfflineError instead of waiting for connect.
  • close() mid-connect: a command sitting in that pre-connect queue plus a connect failure during close() can leave the graceful close pending.
  • Retry safety (the one I most want your read on): node removal calls client.destroy(), which flushes with DisconnectsClientError, not ClientClosedError — so my cluster-level retry misses the failover case it was meant to cover. But I don't think I can just broaden the catch to DisconnectsClientError: that same error also flushes in-flight, already-sent commands, so retrying it would double-execute a non-idempotent command. At the cluster layer I can't distinguish a never-sent queued command from a sent one, so the broaden looks unsafe to me rather than just incomplete.

The alternative that sidesteps all three: keep nodeClient() awaiting the connect, but make the wait bounded — race connectPromise against the command deadline instead of removing the await. That still meets the goal (one unreachable node can't hang a command forever) while keeping the disableOfflineQueue, close(), and ClientClosedError-only-retry behaviors intact, and it's a far smaller change to the hot path you flagged.

Which would you prefer? If you'd rather keep the queue-routing, I'll need your view on the DisconnectsClientError retry-safety question above before I can make that path correct.

Independent of that decision:

  • Pub/sub listeners lost on back-to-back refreshes and resubscribe failures swallowed: both real, both from detaching the pub/sub reconnect in point 1. I'll persist the listeners synchronously before discovery returns, and narrow the catch so the resubscribe path still surfaces — node connect failures are already on node-error, but the pub/sub resubscribe isn't, so .catch(() => {}) was too broad.
  • Existing nodeClient() tests: correct — they assume nodeClient() is the connect promise; I'll update them to whichever semantics we land on.

Point 1 (detaching the node connects) and point 3 (the wasReady drop) hold either way. Happy to push whichever routing you prefer.

@nkaradzhov

Copy link
Copy Markdown
Collaborator

Thanks. Let's go with the bounded wait, kept simple:

  • In nodeClient(), keep the await connectPromise from master, including the fix(client): retry a node connect cut short by a failover #3628 retry in #waitForNodeClient. Race it against the cluster's command timeout (commandOptions.timeout, 5 s by default) and reject with TimeoutError when it runs out. timeout: undefined keeps today's unbounded wait. No need to pass a per-command timeout or abortSignal into it.
  • Drop the queue routing and the new ClientClosedError retry in _execute.
  • Keep points 1 and 3. Please fix the pub/sub listener loss on back-to-back refreshes, and narrow the .catch(() => {}) so a failed resubscribe still surfaces.
  • Update the nodeClient() and clusterEvents tests to match.

…eout

nodeClient() keeps awaiting connectPromise, including the redis#3628 retry when
a refresh closes a client mid-connect because the node changed role. The
wait is now raced against the cluster's command timeout
(commandOptions.timeout, 5 s by default) and rejects with TimeoutError when
it runs out, so an unreachable node no longer holds its commands forever.
An explicit commandOptions.timeout: undefined keeps the unbounded wait.

A topology refresh moves the pub/sub listeners to the new client only once
its connect resolves, so a refresh landing before that read an empty
listener set and dropped them; the pending set is now kept on the pub/sub
node until the resubscribe lands. A failed resubscribe is emitted as an
'error' instead of being swallowed by the detached-connect catch, which now
covers only the node connects that report through 'node-error'.

The clusterEvents event-order assertion becomes a count and ordering-
invariant check: point 1 detaches the node connects from connect(), so
'connect' no longer has a fixed position relative to 'node-ready'.

Part of redis#3592, on top of redis#3628.
@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

Thanks — bounded wait it is. Pushed, rebased on the same base:

  • nodeClient() is back to awaiting connectPromise, #waitForNodeClient and the fix(client): retry a node connect cut short by a failover #3628 role-change retry included. The wait is raced against { timeout: DEFAULT_COMMAND_TIMEOUT, ...commandOptions }.timeout and rejects with TimeoutError; timeout: undefined falls through to the unbounded await. No per-command timeout or abortSignal is threaded in.
  • Queue routing and the ClientClosedError retry in _execute are gone — index.ts is now identical to what it was before that commit.
  • Points 1 and 3 unchanged. The pub/sub listener loss is fixed by keeping the in-flight set on the node as toResubscribe until the resubscribe lands: #initiatePubSubClient() assigns this.pubSubNode synchronously but only attaches the listeners once connect resolves, so a refresh landing in that window read an empty set off the client and dropped them. A refresh now merges the pending set. The .catch(() => {}) no longer covers the resubscribe — a failure there is emitted as 'error', and the blanket catch is left covering only the node connects that already report via 'node-error'.
  • clusterEvents "should fire events" asserted a fixed interleaving that point 1 makes racy, since connect no longer sits after node-ready. It now asserts the event counts, that disconnect closes the log, and that a node connects before it is ready. The Cluster connect() never settles while one master is unreachable #3592 dead-shard test still asserts TimeoutError — same observable result, different mechanism — so only its comment changed.

tsc and eslint are clean and cluster-slots.spec.ts is green locally; the cluster integration tests are Linux/docker-only for me, so those three scenarios will have to prove themselves in CI.

@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: db459f77fa

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

connectPromise: Promise<RedisClientType<M, F, S, RESP, TYPE_MAPPING>>
): Promise<RedisClientType<M, F, S, RESP, TYPE_MAPPING>> {
const { timeout } = { timeout: DEFAULT_COMMAND_TIMEOUT, ...this.#options?.commandOptions };
if (timeout === undefined) return connectPromise;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve zero as a disabled connection-wait timeout

When commandOptions.timeout is 0, the documented behavior is to disable command timeouts, and the command queue already treats it that way. This guard only excludes undefined, so a command targeting a connecting node instead gets a zero-delay timer and rejects with TimeoutError before a healthy connection completes. This is reproducible with minimizeConnections: true: the same command succeeds in the parent commit but fails here. Treat 0 as disabled before creating the timer.

Useful? React with 👍 / 👎.

#raceConnectTimeout(
connectPromise: Promise<RedisClientType<M, F, S, RESP, TYPE_MAPPING>>
): Promise<RedisClientType<M, F, S, RESP, TYPE_MAPPING>> {
const { timeout } = { timeout: DEFAULT_COMMAND_TIMEOUT, ...this.#options?.commandOptions };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor per-command overrides when timing out node connections

When a command uses withCommandOptions() to extend or disable the cluster's default timeout, this new connection deadline still uses the construction-time options. For example, with a 15 ms cluster timeout, a command overriding it to 200 ms now fails after 15 ms while a healthy node completes its handshake in 50 ms; overriding it to undefined also fails. Both cases succeed in the parent commit. Thread the effective command options into the connection wait so the new deadline respects these overrides.

Useful? React with 👍 / 👎.

Comment on lines +1454 to +1455
'node-connect': 2,
'node-ready': 2,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Await node readiness before asserting ready-event counts

With the newly detached connections, this test calls cluster.destroy() immediately after topology discovery returns, before the node sockets finish connecting. Consequently, the log lacks the two node-connect and node-ready events that this assertion still requires; a local socket reproduction produces only connect, two node-disconnect events, and disconnect, whereas the parent produces the expected counts. Relaxing event ordering is insufficient: wait for both nodes to become ready before destroying them, or assert only events guaranteed by topology-only startup.

Useful? React with 👍 / 👎.


// point 2: the wait for the dead node's connect is raced against the
// cluster's command timeout, instead of being unbounded
await assert.rejects(dup.get(deadKey), TimeoutError, 'the dead shard rejects on the command timeout');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Force master routing in the unreachable-node assertion

This fixture enables useReplicas and supplies one healthy replica per master, but the connection stub blocks only the master's port. Because GET is read-only, getSlotRandomNode() can select that healthy replica, causing this promise to resolve instead of rejecting and making the new test fail intermittently. The replica path was reproducible with local RESP socket stubs. Disable replica reads on dup or use a master-routed command for this assertion so it reliably exercises the unreachable connection.

Useful? React with 👍 / 👎.

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

@nkaradzhov nkaradzhov left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. The shape is right. A few of the bot findings on db459f7 still need a fix:

  1. timeout: 0 rejects at once. 0 disables the command timeout (docs/command-options.md), and the command queue already skips the timer for it. #raceConnectTimeout checks only for undefined, so with 0 every command to a node that is still connecting fails with TimeoutError right away. Treat 0 like undefined (for example, if (!timeout) return connectPromise;).

  2. Pub/sub listeners can still be lost. toResubscribe is read only in #discover. #handleSmigrated and removeAllPubSubListeners() still read only the live client's listeners. So an SMIGRATED event or a multi-db drain in the connect window still loses them. Merge toResubscribe in those two places too.

  3. The unreachable-master test can pass the wrong way. The fixture sets useReplicas: true, and GET is read-only. So getSlotRandomNode() can pick the healthy replica, and then dup.get(deadKey) resolves. Use a command that goes to the master, or turn off useReplicas on dup.

  4. The clusterEvents test does not wait for the nodes. It calls destroy() right after connect(). The node connects now run in the background, so the 2 node-connect and 2 node-ready events may not have fired yet. Wait for both nodes to be ready before destroy(), or assert only the events that connect() guarantees.

Leave the per-command override finding (withCommandOptions({ timeout })) as it is. The cluster-level timeout was the agreed scope.

I will start CI after your next push.

…d pub/sub listeners

Review follow-ups on the bounded connect wait:

- `commandOptions.timeout: 0` disables the command timeout and the command
  queue skips its timer for it, but `#raceConnectTimeout` checked only for
  `undefined`, so every command to a still-connecting node rejected with
  TimeoutError immediately. Treat 0 like undefined.
- `#handleSmigrated` and `removeAllPubSubListeners()` read only the live
  client's listeners, so an SMIGRATED event or a multi-db drain landing in
  the connect window still lost the ones parked on `toResubscribe`. Merge
  that in at both sites, as `#discover` already does.
- The unreachable-master test enabled `useReplicas` and asserted on a
  read-only GET, which `getSlotRandomNode()` could serve from the healthy
  replica and resolve. Use a write so it routes to the master.
- The clusterEvents test destroyed the cluster straight after `connect()`;
  with the node connects detached, the node-connect/node-ready pairs it
  asserts had not necessarily fired. Wait for both nodes to be ready first.
@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

All four are in 96f81af.

  1. #raceConnectTimeout returns the connect promise for any falsy timeout now, so 0 keeps the wait unbounded like undefined. Added two unit tests in cluster-slots.spec.ts: the first fails on db459f7 (settled where it wants pending) and passes here, the second pins that a real timeout still bounds the wait.

  2. #handleSmigrated and removeAllPubSubListeners() both merge pubSubNode.toResubscribe now, the same way #discover does. In removeAllPubSubListeners() I only merge and do not clear it — this.pubSubNode = undefined a few lines down already makes an in-flight #initiatePubSubClient fail its identity check and destroy its client, so the drained listeners cannot be re-applied to a node that is going away.

  3. The unreachable-master assertion is a write now (dup.set(deadKey, 'v')), so it routes to the master instead of being served by the healthy replica.

  4. The clusterEvents test waits for both nodes to report ready before destroy(), rather than asserting pairs that the detached connects may not have fired yet.

Left the withCommandOptions({ timeout }) finding as it is, per your note on the scope.

tsc --noEmit and eslint are clean and the cluster-slots unit specs pass locally; the cluster integration suites need docker, so those are on CI.

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

…as an error

A newer re-init destroys the older attempt's client, and destroy() flushes
its in-flight subscribe with DisconnectsClientError. That escaped the
resubscribe `await`, so #discover's catch, which only treats
ClientClosedError as expected, emitted `error` even though the newer
attempt already carried the merged listeners and the subscriptions had
survived. Callers that treat `error` as fatal could tear down a healthy
cluster.

Check identity on the failure path and surface the supersession, matching
the check that already follows a successful flush.
@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

Bugbot flagged two more on 96f81af. I fixed the first in d3a63e4 and want your call on the second.

Superseded pub/sub re-init emitted error — real, fixed. destroy() flushes the in-flight subscribe with DisconnectsClientError (client/index.ts), so when a newer re-init superseded an older one mid-extendPubSubListeners, that error escaped the await before reaching the identity check that turns supersession into ClientClosedError. #discover's catch only treats ClientClosedError as expected, so it emitted error even though the newer attempt already carried the merged listeners and nothing was lost. The failure path now checks identity the same way the success path right below it does.

Handler accumulation on a pending connectPromise — real, but I left it alone pending your view on scope. Every waiter attaches its own .then() to the shared connectPromise, and client.connect() only settles when the reconnect strategy gives up, so during an outage those handlers are retained. A form of this predates the PR, since await connectPromise also registered a continuation per waiter. What changes here is the churn: previously a command attached once and then hung, whereas now it rejects on the timeout and a retrying caller attaches again on each attempt, so a steady retry loop against a dead shard accumulates attachments for the life of the outage.

Fixing it properly means attaching once per connectPromise and fanning out to waiters, each keeping its own deadline — roughly 20 lines in #raceConnectTimeout, no semantic change. Happy to add it here, or leave it out if you would rather keep this PR to the agreed scope and track it separately.

tsc --noEmit, eslint and the 18 cluster-slots unit specs are green on d3a63e4.

@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: d3a63e4aad

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +437 to +438
if (err instanceof ClientClosedError && this.#isOpen) return;
throw err;
if (this.#isOpen) this.#emit('error', err);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize superseded Pub/Sub handshake failures

If a second refresh replaces the Pub/Sub node after TCP connects but before its AUTH/HELLO handshake completes, destroying that client rejects the pending handshake with DisconnectsClientError. The supersession handling in #initiatePubSubClient() only translates failures during the later resubscribe phase, so this catch emits a cluster error even though the replacement successfully preserves all listeners. A local RESP-socket reproduction confirmed this across two consecutive refreshes. Besides reporting a nonexistent subscription failure, this feeds fault evidence into the multi-db manager. Normalize superseded failures in the outer connection catch as well.

Useful? React with 👍 / 👎.

if (!timeout) return connectPromise;

return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new TimeoutError()), timeout);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle command timeouts above Node's timer-delay limit

With a valid cluster timeout such as 2 ** 31 milliseconds, this direct setTimeout() overflows Node's signed 32-bit delay limit and becomes a 1 ms timer. The command queue's CommandDeadlines explicitly supports values through 2 ** 32 - 1 by clamping and rearming its underlying timer, so this introduces inconsistent behavior: a healthy node whose connection completes after 50 ms now rejects almost immediately with TimeoutError. Apply equivalent long-delay handling to the connection timer.

Useful? React with 👍 / 👎.

}

// later commands keep routing correctly after the refresh
assert.equal(await dup.get(deadKey), 'v');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Route the failover test's final read to the reachable master

After the replica is promoted, deadMaster becomes its replica, but the connection stub continues blocking deadMaster.port until finally. Since this fixture enables useReplicas, the final GET has a 50% chance of selecting that still-unreachable replica and rejecting with TimeoutError, even though the preceding SET and topology recovery succeeded. A local post-failover RESP-socket check reproduced the failure by selecting that replica branch. Force master routing for this read or disable replica reads on the duplicate so the new test is deterministic.

Useful? React with 👍 / 👎.

@nkaradzhov

Copy link
Copy Markdown
Collaborator

Thanks. Please fix the handler accumulation in this PR: attach once per connectPromise and fan out to the waiters, each with its own deadline, as you described.

Each command waiting on a node's in-flight connect attached its own
handler to the shared connectPromise. client.connect() only settles when
the reconnect strategy gives up, so during an outage those handlers were
retained, and a caller retrying after each TimeoutError added another on
every attempt.

Keep one settlement handler per connectPromise and a set of waiters
behind it, each with its own deadline. A waiter that times out removes
itself, so traffic to an unreachable node no longer accumulates.

The new spec counts attachments: three concurrent waiters now share one,
where before they took three.
@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

Done in 50262b1.

#raceConnectTimeout now keeps one settlement handler per connectPromise with a set of waiters behind it, each holding its own timer. A waiter that times out removes itself from the set, so traffic to a node that stays unreachable no longer accumulates handlers, and a caller retrying after each TimeoutError no longer adds one per attempt. The settle path copies the set before notifying, since resolving a waiter can run a continuation that would otherwise mutate the set mid-iteration. The WeakMap is keyed on the promise and the entry is dropped as soon as it settles, which lines up with #createNodeClient clearing node.connectPromise in its finally.

Two specs cover it. One counts attachments: three concurrent waiters share a single then on the connect promise, and it fails on d3a63e4 with 3 !== 1. The other pins that a waiter which already timed out does not break the fan-out — a later command on the same connect still resolves once it lands.

tsc --noEmit, eslint and the 20 cluster-slots unit specs are green on 50262b1.

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

connect() now resolves without waiting for the node connections, so an
unreachable node can still be in the topology when the pub/sub node is
picked. getPubSubClient() and getShardedPubSubClient() awaited that
node's connectPromise raw, and the first pick pins pubSubNode (or
master.pubSub) to it, so every later subscribe() waited on the same
never-settling promise — the hang this PR removes from connect() and
nodeClient() simply moved to pub/sub.

Race those waits against the cluster's command timeout, as the command
path already does. Only the caller's wait is bounded:
#initiatePubSubClient() still returns its own unbounded promise, so a
refresh resubscribing through it keeps reporting a real failure instead
of a timeout.
@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

Bugbot caught a real gap on 50262b1 and I fixed it in 1cd7b73.

It is the same unbounded wait, on a path I had missed. Since connect() resolves without waiting for the node connections, an unreachable node can still be in the topology when the pub/sub node is picked. getPubSubClient() and getShardedPubSubClient() awaited that node's connectPromise raw, and the first pick pins pubSubNode (or master.pubSub) to it, so every later subscribe() waited on the same promise that never settles. The hang this PR removes from connect() and nodeClient() had just moved to pub/sub, which would have made the "one unreachable node costs only its own shard" claim untrue for subscribers.

Both waits now go through #raceConnectTimeout, so they fail with TimeoutError like any other command to a node that is still connecting. I deliberately bounded only the caller's wait and not #initiatePubSubClient() itself: #discover resubscribes through it and treats anything other than ClientClosedError as a real failure to report, so a timeout there would surface a spurious error during a refresh.

One thing I did not change, since it is a design call rather than a bug. The dead node stays pinned, so while it remains in CLUSTER SLOTS every subscribe() keeps timing out rather than moving to a healthy node. Re-picking on failure would fix that, but it is a behaviour change beyond bounding the wait, so I left it. Happy to add it if you want it in this PR.

tsc --noEmit, eslint and the 20 cluster-slots unit specs are green on 1cd7b73. The getters go through #assertReady(), so they need a connected cluster and are not reachable from the docker-free unit harness — this one is on CI.

@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: 1cd7b730e5

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +1661 to +1663
if (!master.pubSub) return this.#raceConnectTimeout(this.#initiateShardedPubSubClient(master));
return master.pubSub.connectPromise ?
this.#raceConnectTimeout(master.pubSub.connectPromise) :

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve sharded listeners when the connection wait times out

When an existing shard channel moves and the new owner's connection or handshake takes longer than commandOptions.timeout (5 seconds by default), this also times out automatic sharded-channel-moved recovery. That handler calls this method before attaching the saved listeners, and its catch only emits sharded-channel-moved-error; the old queue has already removed those listeners. Consequently, the replacement client later becomes ready with an empty listener map and never resubscribes. A local RESP reproduction restores the subscription in the parent but loses it here. Separate bounded public waits from background recovery, or persist the listeners before waiting.

Useful? React with 👍 / 👎.

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

getShardedPubSubClient() bounds the wait for a connecting shard pub/sub
client, but executeShardedUnsubscribeCommand() still awaited
master.pubSub.connectPromise raw. Once ssubscribe has timed out on an
unreachable master, master.pubSub is already seated, so sunsubscribe
waited on that same connect indefinitely — the hang the previous commit
removes from subscribe and from regular unsubscribe.

Race it against the command timeout like the other callers.

executeUnsubscribeCommand() needs no change: it already goes through
getPubSubClient(), which is bounded. The two #initiate* helpers keep
returning their own unbounded promises on purpose, so #discover's
resubscribe still reports a real failure rather than a timeout.
@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

Right again — fixed in debf367.

executeShardedUnsubscribeCommand() still awaited master.pubSub.connectPromise raw. Once ssubscribe has timed out on an unreachable master, master.pubSub is already seated, so sunsubscribe waited on that same connect indefinitely. It now races the command timeout like the other callers.

executeUnsubscribeCommand() needs no change — it goes through getPubSubClient(), which the previous commit bounded.

Rather than wait for the next report, I went through every connectPromise wait in the file. There are ten sites and they now fall into three groups:

  • bounded by #raceConnectTimeout: nodeClient() via #waitForNodeClient, getPubSubClient(), getShardedPubSubClient(), and now executeShardedUnsubscribeCommand()
  • producers rather than waits: #createNodeClient() returning the promise it just created, and the race helper itself, where a falsy timeout means the wait is disabled on purpose
  • deliberately unbounded: #initiatePubSubClient() and #initiateShardedPubSubClient() returning their own promises, so #discover's resubscribe keeps reporting a real failure instead of a timeout

That should be the last of them. tsc --noEmit, eslint and the 20 cluster-slots unit specs are green on debf367.

@nkaradzhov

Copy link
Copy Markdown
Collaborator

Thanks, the fan-out in 50262b1 looks right. Four bot findings are still open on debf367:

  1. Codex P1: since 1cd7b73, sharded-channel-moved recovery times out on a slow connect and drops the listeners. Keep the limit for ssubscribe/sunsubscribe, but let the recovery wait without one.
  2. Codex: #raceConnectTimeout breaks for timeouts above 2^31 − 1 ms. Re-arm the timer like command-deadlines.ts does.
  3. Codex: a handshake superseded by a newer refresh still emits error. Apply the supersession check in the outer .catch too.
  4. Codex: the failover test's final get can go to the blocked replica. Make it deterministic.

CI is approved for debf367.

…eadlines in steps

Four review follow-ups:

- sharded-channel-moved recovery must not time out. Bounding
  getShardedPubSubClient() in the previous commit also bounded the
  automatic recovery, which calls it after the old queue has handed over
  its listeners: a slow connect there left the replacement ready with an
  empty listener map and nothing to resubscribe from, losing the
  subscription for good. Recovery now waits without a limit; the
  caller-facing ssubscribe/sunsubscribe path keeps its.
- A command timeout past 2**31-1 ms collapsed to a 1ms timer, so a
  cluster configured with a long timeout rejected almost immediately.
  Arm in steps and re-arm until the deadline really passes, as
  command-deadlines.ts does.
- A pub/sub handshake cut short by a newer refresh rejects with
  DisconnectsClientError, which the outer catch reported as a failure
  even though the replacement carries the listeners. Apply the same
  supersession check the resubscribe phase already uses.
- The failover test's last read could be routed to the demoted master,
  whose port the stub still blocks, so it timed out even on a correct
  recovery. Use a write so it goes to the promoted master.
@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

All four are in 7d08421.

1. Sharded recovery no longer times out. This was mine to own — bounding getShardedPubSubClient() in 1cd7b73 also bounded the automatic sharded-channel-moved recovery, which calls it after the old queue has handed its listeners over. A slow connect there left the replacement ready with an empty listener map and nothing to resubscribe from, so the subscription was gone for good. Split into a private #shardedPubSubClient(channel, bounded): recovery passes false, and the caller-facing ssubscribe/sunsubscribe path keeps the limit, which is the split you asked for.

2. Long timeouts. #raceConnectTimeout now stores the deadline and arms Math.min(MAX_TIMER_DELAY, remaining), re-arming until the deadline really passes, same shape as command-deadlines.ts. Added a unit test at timeout: 2 ** 31; it fails on the previous code (settled where it wants pending, with Node's TimeoutOverflowWarning) and passes now.

3. Superseded handshake. The outer .catch now applies the same identity check the resubscribe phase already used, so a handshake cut short by a newer re-init reports the supersession instead of a failure that surfaced as a cluster error.

4. Failover test. The final read is a write now. The demoted master is the shard's replica by then and the stub still blocks its port, so with useReplicas the read could land there and time out on an otherwise correct recovery — the same trap as the unreachable-master assertion earlier.

tsc --noEmit, eslint and the 21 cluster-slots unit specs are green on 7d08421. Thanks for approving CI — the cluster integration suites need docker, so this is the first run that will exercise them.

@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: 7d084215b2

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

this.#assertReady();

// bounded for the same reason as getPubSubClient()
return this.#shardedPubSubClient(channel, true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep topology-driven sharded recovery off the public deadline

With useReplicas: true, a failover demoting a subscribed master takes the #discover() → RESUBSCRIBE_LISTENERS_EVENT → resubscribeAllPubSubListeners() → public sSubscribe() route, which still uses this bounded wait. If the promoted master's Pub/Sub handshake exceeds the command timeout, the wait rejects before the saved listeners are attached; the old queue has already been drained, so recovery permanently loses the subscriptions. The now-unbounded sharded-channel-moved handler does not cover this separate route: a local RESP reproduction left the replacement client ready with zero listeners, while the parent retained one. Seed the listeners synchronously or keep topology-driven recovery unbounded as well.

Useful? React with 👍 / 👎.

}, () => true);

assert.equal(
await raceSettled(slots.nodeClient(neverConnecting('127.0.0.1:5')), 50),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Settle the long-timeout connection before the test finishes

This races a never-settling connection against 50 ms but never settles the connection afterward. Consequently, #raceConnectTimeout() leaves a referenced timer armed for approximately 24.9 days. Running the test body locally confirmed that its assertion passes while the remaining Timeout keeps the process alive, preventing the documented single-file test run from exiting normally. Use a controllable connection promise and settle it in finally after checking that the wait remains pending.

AGENTS.md reference: AGENTS.md:L64-L64

Useful? React with 👍 / 👎.

CI on debf367 failed three cluster pub/sub tests.

The existing "should move listeners when PubSub node disconnects from
the cluster" broke because detaching the discovery promises (redis#3592
point 1) detached the pub/sub resubscribe along with the node connects.
A refresh that moves the pub/sub node then returned before the new
client had resubscribed, so anything published right after it was
missed. The node connects stay detached, which is the point of the
change, but the resubscribe is awaited again. It is raced against the
command timeout so an unreachable replacement still cannot hang the
refresh, and a timeout is not reported as a loss: the resubscribe is
still in flight and delivery resumes when it lands.

The two redis#3592 tests were not deterministic. Both stub a socket that
never connects, but left the default 5s socket connect timeout in
place, so on a slow runner the connect gave up before the 1s command
timeout and the command rejected with ConnectionTimeoutError instead of
the TimeoutError being asserted. Both now set a 60s connect timeout so
the bounded wait is what settles the command.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 7d08421. Configure here.


return this.pubSubNode.connectPromise ?
this.#raceConnectTimeout(this.pubSubNode.connectPromise) :
Promise.resolve(this.pubSubNode.client);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pub/sub pins to unreachable node

High Severity

connect() can now succeed while some nodes are still unreachable, and #initiatePubSubClient then pins pubSubNode to a random pick among all of them. A TimeoutError from getPubSubClient does not clear that pin, and the default reconnect strategy never settles connectPromise, so later subscribe/unsubscribe keep racing the same dead handshake. A refresh resubscribe on that node also never lands, so existing listeners stop receiving with no terminal error.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 7d08421. Configure here.

@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

CI on debf367 failed three cluster pub/sub tests. Fixed in 2597a9a.

The important one is the pre-existing test, should move listeners when PubSub node disconnects from the cluster. Detaching the discovery promises in point 1 detached the pub/sub resubscribe along with the node connects, so a refresh that moves the pub/sub node returned before the new client had resubscribed and anything published right after it was missed. waitTillBeenCalled then timed out. That is a real regression in the PR, not a flaky test.

The node connects stay detached — that is the point of #3592 — but the resubscribe is awaited again. It is raced against the command timeout so an unreachable replacement still cannot hang the refresh, and a TimeoutError there is deliberately not reported as a loss: the resubscribe is still in flight and delivery resumes when it lands.

Worth your view on one judgement call: I treated "the refresh must not hang" and "a subscriber must not silently miss messages" as both mandatory, and bounded the wait to satisfy them together. The alternative is to leave it detached and change what that test asserts, but that weakens a delivery guarantee the suite currently encodes, so I did not take it.

The two #3592 tests were my own fault and not deterministic. Both stub a socket that never connects but left the default 5s socket connect timeout in place, so on a slow runner the connect gave up before the 1s command timeout and the command rejected with ConnectionTimeoutError instead of the TimeoutError being asserted — which is exactly what the log shows. Both now set a 60s connect timeout, so the bounded wait is what settles the command. The third failure, the failover test's final read, is the routing one you flagged; that fix went in with 7d08421.

tsc --noEmit, eslint and the 21 cluster-slots unit specs are green on 2597a9a. The integration suites need docker, so this needs another CI approval when you have a moment.

@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

Bugbot's latest on 7d08421 ("Pub/sub pins to unreachable node") is right, and it is the question I raised on 1cd7b73 and left for you. I want your call before changing behaviour here, but I also think it is worse than how I described it then, so here is the accurate version.

Nothing clears pubSubNode on a timeout. The pin is only dropped when the connect rejects, and under the default reconnect strategy a dead node's connect never rejects — it retries. So once #initiatePubSubClient happens to pick an unreachable node, every later subscribe/unsubscribe races the same handshake and times out, indefinitely.

I also need to correct something I wrote with 2597a9a. I made the refresh resubscribe swallow TimeoutError on the grounds that it is "still in flight and delivery resumes when it lands". That holds for a slow connect. It does not hold for a node that is down: the resubscribe never lands, so existing listeners stop receiving and nothing is emitted. Trading a hang for silence is not obviously the better failure, and that is on me.

The fix is the re-pick I mentioned: on a timed-out wait, drop the pin and destroy that client so the next call chooses a different node, carrying the parked toResubscribe listeners to the new pick so they are not lost with it. The part I do not want to guess at is the retry shape — #initiatePubSubClient picks at random across masters and replicas, so a naive re-pick can land on the same dead node repeatedly, and a background retry loop needs a bound and a terminal error rather than retrying forever.

Three ways to go, and I am happy with any:

  1. I implement the re-pick here, bounded, with a terminal error once it gives up.
  2. I leave the pin alone and instead stop swallowing the refresh TimeoutError, so the failure is at least loud. Smaller, but subscribers still have to rebuild the client themselves.
  3. Track it separately and keep this PR to the bounded waits.

My preference is 1, since the pin only becomes permanent because connect() no longer waits — it is a consequence of this PR rather than a pre-existing gap. But it is a behaviour change on a path CI only started exercising today, so it is your call.

2597a9a is pushed and has the three CI failures fixed; that still needs a run when you get a chance.

@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: 2597a9aded

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +460 to +464
if (err instanceof ClientClosedError && this.#isOpen) return;
// The wait ran out, not the resubscribe: it is still in flight and
// delivery resumes when it lands, so do not report a loss.
if (err instanceof TimeoutError) return;
if (this.#isOpen) this.#emit('error', err);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep reporting resubscribe failures after the wait times out

If a replacement's SUBSCRIBE fails after the cluster timeout, this catch has already handled TimeoutError and cannot observe the eventual failure. #initiatePubSubClient() then clears pubSubNode, silently abandoning the saved subscriptions without emitting a cluster error. A local RESP-socket reproduction with a delayed NOPERM response confirmed this; the parent reports the error. Attach failure reporting to the underlying reinitialization promise independently of the bounded refresh wait.

Useful? React with 👍 / 👎.

topologyRefreshOnReconnectionAttemptStrategy: 100,
// same reason as the test above: the stub's socket must not give up on
// its own and turn a bounded wait into a ConnectionTimeoutError
defaults: { socket: { connectTimeout: 60_000 } }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Force socket retries before the failover test deadline

Even when discovery selects a live root, the stubbed socket neither connects nor fails before this 60-second connection timeout. RedisSocket emits reconnecting only after a failed attempt, so the 100 ms topology-refresh strategy cannot run within the test's 30-second limit. A local RESP-socket reproduction reached that limit with zero reconnection events and unchanged slot ownership; every attempted write rejected with TimeoutError. Make this test's stub fail periodically, or shorten its connection timeout, so it actually exercises reconnect-triggered discovery.

Useful? React with 👍 / 👎.

Comment on lines +1275 to +1276
const dup = cluster.duplicate({
commandOptions: { timeout: 1000 },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restrict discovery to live roots in the unreachable-node tests

Both new tests inherit the fixture's complete rootNodes list through duplicate(). Whenever randomized discovery starts with deadMaster, the connection stub also blocks the temporary discovery client, so dup.connect() waits on the 60-second socket timeout and exceeds the tests' 30-second limit before reaching any assertion. The command timeout does not bound root discovery. Give these duplicates a known-live discovery root while retaining the blocked master in the returned topology.

Useful? React with 👍 / 👎.

@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 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 2597a9a. Configure here.

…tests

The 60s connect timeout added in 2597a9a also applies to discovery, and
#discoverWithRootNodes starts at a random root, so a root attempt
against the dead master's blocked port would wait the full 60s and
outlast the 30s test timeout. Both tests now point discovery at the
live master.

The failover test also loses its 60s connect timeout. It needs the dead
node's connect to give up and start reconnecting, because that
`reconnecting` event is what drives
topologyRefreshOnReconnectionAttemptStrategy — stretching it would stop
the refresh under test from firing at all. The CI failure there was the
final read being routed to the blocked replica, which 7d08421 already
fixed by making it a write.
@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

Bugbot flagged two on 2597a9a. The first is the pub/sub pin from my comment above, so that is still waiting on your call. The second was a genuine problem with my own test fix, and I have pushed f6a6f34 for it rather than let it burn a CI approval.

The 60s connect timeout I added in 2597a9a also applies to discovery, and #discoverWithRootNodes starts at a random root — so if it picked the dead master, the topology fetch would have waited the full 60s and blown the 30s test timeout. Both tests now point discovery at the live master, which keeps the long timeout confined to the dead shard's own node client, where it is what makes the assertion deterministic.

I also took that 60s back off the failover test entirely. That test needs the dead node's connect to give up and start reconnecting, because the reconnecting event is what drives topologyRefreshOnReconnectionAttemptStrategy — stretching it would have stopped the refresh under test from firing at all. Its actual CI failure was the final read landing on the blocked replica, which 7d08421 already fixed by making it a write, so it never needed the timeout change.

Worth saying plainly: that was me fixing one source of flakiness by introducing another, and the second one would only have shown up as a 30s timeout on your next approved run.

f6a6f34 is the head now. I will hold further pushes unless something is actually broken, so you are not re-approving CI behind a moving branch.

@nkaradzhov nkaradzhov left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the four fixes from my last comment look right. A few more on f6a6f34:

  1. Pub/sub pinned to an unreachable node: let's take option 3. Master already has this pin (there subscribe() hangs on it instead of timing out), so the re-pick can go in a separate issue.
  2. Codex P2: if the refresh wait times out and the resubscribe then fails, nobody hears about it and the listeners are dropped. Ignore TimeoutError on the bounded wait only, and report errors from the #initiatePubSubClient() promise itself.
  3. Codex P1: this is the same problem as point 1 of my last comment, on other paths. Failover, __MOVED and SMIGRATED resubscribe through RESUBSCRIBE_LISTENERS_EVENT and the public sSubscribe(), which is bounded, so a slow connect loses the listeners. As a rule, only calls the user makes should be bounded. Internal recovery should wait with no limit and report its failures.
  4. Codex P2: the 2 ** 31 test leaves a ~25-day timer running. Use a connection promise you control, and settle it at the end of the test.

Review follow-ups. The rule is now explicit: a call the user made races
the command timeout, internal recovery waits as long as it takes and
reports what went wrong.

- The refresh resubscribe reported nothing if the bounded wait ran out
  and the re-init then failed, so the listeners were dropped silently.
  The TimeoutError is ignored on the bounded wait only; errors are
  reported from the #initiatePubSubClient() promise itself, so a real
  failure is heard whenever it lands.
- Failover, MOVED and SMIGRATED all resubscribe through
  RESUBSCRIBE_LISTENERS_EVENT and the public subscribe methods, which
  were bounded, so a slow connect lost the listeners the old queue had
  already given up. getPubSubClient() and getShardedPubSubClient() take
  `bounded`, the subscribe methods thread it, and
  resubscribeAllPubSubListeners() passes false.
- The 2**31 spec left a ~25 day timer running. It now settles the
  connect it controls, which clears the waiter's timer; the file runs
  clean without mocha's --exit.

The pub/sub node pinning to an unreachable node is left alone, per the
decision to track the re-pick separately: master already pins there too,
where subscribe() hangs rather than timing out.
@Cdineshreddy12

Copy link
Copy Markdown
Contributor Author

All four are in 91b1ce3.

1. Pub/sub pin — taking option 3, left alone here. Agreed it is not this PR's to fix given master pins the same way; subscribe() just hangs there instead of timing out. Happy to open the re-pick issue and write up the reproduction if you want it from me.

2. Silent drop after a timed-out refresh — the report now hangs off the #initiatePubSubClient() promise rather than the raced one, so a real failure is heard whenever it lands, including long after the bounded wait gave up. The TimeoutError is ignored on the bounded wait only, which is all that wait was ever meant to decide.

3. Internal recovery was bounded — you are right that this was point 1 again on the paths I had not followed. Failover, MOVED and SMIGRATED all resubscribe through RESUBSCRIBE_LISTENERS_EVENT → resubscribeAllPubSubListeners() → the public subscribe methods, so they inherited the limit. getPubSubClient() and getShardedPubSubClient() now take bounded, the three subscribe methods thread it through (defaulted and marked @internal), and the resubscribe passes false. The rule reads the same way in each place now: the user's call is bounded, recovery waits and reports.

4. The 25-day timer — the spec now owns the connect promise and settles it at the end, which clears the waiter's timer. I checked by running the file without mocha's --exit: it exits on its own in about a second, so nothing is left armed. The other two specs there are fine — timeout: 0 never arms a timer, and the 20ms one clears itself when it fires.

tsc --noEmit, eslint and the 21 cluster-slots specs are green on 91b1ce3.

Separately, I merged this branch against teddyteh's e4c68c7 locally to check the conflict we had both assumed. cluster-slots.ts merges cleanly — his terminated listener and the wasReady lines this PR removes sit next to each other but git resolves them. The only conflict is one import line in cluster-slots.spec.ts, where he adds SocketClosedUnexpectedlyError and I add TimeoutError. Either order works.

@nkaradzhov nkaradzhov left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, LGTM.

@nkaradzhov
nkaradzhov merged commit aa34c8f into redis:master Nov 25, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cluster connect() never settles while one master is unreachable

2 participants