Repository navigation
fix(cluster): don't hang connect() or commands on an unreachable node (#3592) - #3652
Conversation
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.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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!); |
There was a problem hiding this comment.
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 👍 / 👎.
| for (const promise of promises) { | ||
| promise.catch(() => {}); |
There was a problem hiding this comment.
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 👍 / 👎.
| this.#createNodeClient(node).catch(() => {}); | ||
| } | ||
| return Promise.resolve(node.client!); |
There was a problem hiding this comment.
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 👍 / 👎.
|
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,
The alternative that sidesteps all three: keep Which would you prefer? If you'd rather keep the queue-routing, I'll need your view on the Independent of that decision:
Point 1 (detaching the node connects) and point 3 (the |
|
Thanks. Let's go with the bounded wait, kept simple:
|
…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.
fea3585 to
db459f7
Compare
|
Thanks — bounded wait it is. Pushed, rebased on the same base:
|
There was a problem hiding this comment.
💡 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; |
There was a problem hiding this comment.
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 }; |
There was a problem hiding this comment.
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 👍 / 👎.
| 'node-connect': 2, | ||
| 'node-ready': 2, |
There was a problem hiding this comment.
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'); |
There was a problem hiding this comment.
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 👍 / 👎.
nkaradzhov
left a comment
There was a problem hiding this comment.
Thanks. The shape is right. A few of the bot findings on db459f7 still need a fix:
-
timeout: 0rejects at once.0disables the command timeout (docs/command-options.md), and the command queue already skips the timer for it.#raceConnectTimeoutchecks only forundefined, so with0every command to a node that is still connecting fails withTimeoutErrorright away. Treat0likeundefined(for example,if (!timeout) return connectPromise;). -
Pub/sub listeners can still be lost.
toResubscribeis read only in#discover.#handleSmigratedandremoveAllPubSubListeners()still read only the live client's listeners. So an SMIGRATED event or a multi-db drain in the connect window still loses them. MergetoResubscribein those two places too. -
The unreachable-master test can pass the wrong way. The fixture sets
useReplicas: true, andGETis read-only. SogetSlotRandomNode()can pick the healthy replica, and thendup.get(deadKey)resolves. Use a command that goes to the master, or turn offuseReplicasondup. -
The
clusterEventstest does not wait for the nodes. It callsdestroy()right afterconnect(). The node connects now run in the background, so the 2node-connectand 2node-readyevents may not have fired yet. Wait for both nodes to be ready beforedestroy(), or assert only the events thatconnect()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.
|
All four are in 96f81af.
Left the
|
…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.
|
Bugbot flagged two more on Superseded pub/sub re-init emitted Handler accumulation on a pending Fixing it properly means attaching once per
|
There was a problem hiding this comment.
💡 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".
| if (err instanceof ClientClosedError && this.#isOpen) return; | ||
| throw err; | ||
| if (this.#isOpen) this.#emit('error', err); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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'); |
There was a problem hiding this comment.
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 👍 / 👎.
|
Thanks. Please fix the handler accumulation in this PR: attach once per |
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.
|
Done in
Two specs cover it. One counts attachments: three concurrent waiters share a single
|
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.
|
Bugbot caught a real gap on It is the same unbounded wait, on a path I had missed. Since Both waits now go through 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
|
There was a problem hiding this comment.
💡 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".
| if (!master.pubSub) return this.#raceConnectTimeout(this.#initiateShardedPubSubClient(master)); | ||
| return master.pubSub.connectPromise ? | ||
| this.#raceConnectTimeout(master.pubSub.connectPromise) : |
There was a problem hiding this comment.
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 👍 / 👎.
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.
|
Right again — fixed in
Rather than wait for the next report, I went through every
That should be the last of them. |
|
Thanks, the fan-out in
CI is approved for |
…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.
|
All four are in 1. Sharded recovery no longer times out. This was mine to own — bounding 2. Long timeouts. 3. Superseded handshake. The outer 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
|
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 7d08421. Configure here.
|
|
||
| return this.pubSubNode.connectPromise ? | ||
| this.#raceConnectTimeout(this.pubSubNode.connectPromise) : | ||
| Promise.resolve(this.pubSubNode.client); |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 7d08421. Configure here.
|
CI on The important one is the pre-existing 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 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
|
|
Bugbot's latest on Nothing clears I also need to correct something I wrote with 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 Three ways to go, and I am happy with any:
My preference is 1, since the pin only becomes permanent because
|
There was a problem hiding this comment.
💡 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".
| 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); |
There was a problem hiding this comment.
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 } } |
There was a problem hiding this comment.
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 👍 / 👎.
| const dup = cluster.duplicate({ | ||
| commandOptions: { timeout: 1000 }, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.
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.
|
Bugbot flagged two on The 60s connect timeout I added in 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 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.
|
nkaradzhov
left a comment
There was a problem hiding this comment.
Thanks, the four fixes from my last comment look right. A few more on f6a6f34:
- 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. - Codex P2: if the refresh wait times out and the resubscribe then fails, nobody hears about it and the listeners are dropped. Ignore
TimeoutErroron the bounded wait only, and report errors from the#initiatePubSubClient()promise itself. - Codex P1: this is the same problem as point 1 of my last comment, on other paths. Failover,
__MOVEDand SMIGRATED resubscribe throughRESUBSCRIBE_LISTENERS_EVENTand the publicsSubscribe(), 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. - Codex P2: the
2 ** 31test 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.
|
All four are in 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; 2. Silent drop after a timed-out refresh — the report now hangs off the 3. Internal recovery was bounded — you are right that this was point 1 again on the paths I had not followed. Failover, 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
Separately, I merged this branch against teddyteh's |


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#discoverinstalls the slot map and then lets the node and pub/sub clients keep connecting in the background instead ofawait Promise.all(...)-ing them. One unreachable master now costs only its own shard —connect()(and a topology refresh) resolve on the topology, the wayminimizeConnections: truealready behaves. The detached node connects' failures surface through each client'snode-errorevent, 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 awaitingconnectPromise,#waitForNodeClientand #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 withTimeoutErrorwhen it runs out, so an unreachable node no longer holds its commands forever. An explicitcommandOptions.timeout: undefinedkeeps the unbounded await. No per-commandtimeoutorabortSignalis threaded into it.3. A node that never became ready counts for
topologyRefreshOnReconnectionAttemptStrategyDropped the
wasReadyguard in the node client'sreconnectinghandler, 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 anddocs/clustering.mdupdated to match.4. A refresh mid-connect no longer drops pub/sub listeners
#initiatePubSubClient()assignsthis.pubSubNodesynchronously 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 astoResubscribeuntil the resubscribe lands, and a refresh merges it. A resubscribe failure that is not a superseded attempt is emitted aserrorrather than being swallowed.Tests
index.spec.tsadds two integration tests over the existing net-stub harness:connect()resolves, a command to a live shard succeeds, a command to the dead shard rejects withTimeoutError;topologyRefreshOnReconnectionAttemptStrategy, the promoted replica serves the migrated shard.clusterEvents→ "should fire events" asserted a fixed event interleaving. Point 1 detaches the node connects fromconnect(), soconnectno longer has a fixed position relative tonode-readyand that assertion became a race; it now asserts the event counts, thatdisconnectcloses the log, and that a node connects before it is ready.Notes for review
connect()now resolves on the topology without waiting for the per-node connections (likeminimizeConnections: true). Code that assumed every node was connected the momentconnect()resolved will see the connects complete slightly later.MOVEDnaming an unreachable node) is covered in substance by the failover test's "later routing still works" tail; I approximated the exactMOVED-to-unreachable wire shape rather than reproducing it precisely — happy to add a dedicated case if you'd like the exact shape.docker --network host), so I verifiedtsc,eslintandcluster-slots.spec.tslocally 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 laternode-readyandTimeoutErroron 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 vianode-errorand 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 withTimeoutErrorinstead of waiting forever;timeout: 0/ disabled keeps the wait unbounded. Connect waiters share one settlement handler perconnectPromiseto avoid listener leaks on retries.topologyRefreshOnReconnectionAttemptStrategynow 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
toResubscribethrough 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.