Repository navigation
fix(client): retry a node connect cut short by a failover - #3628
nkaradzhov merged 1 commit into
Conversation
A command that reaches a node before the slot map learns of a failover opens that node's client lazily. If the refresh then demotes the node, it closes the client before it connects, and the command failed with "The client is closed". nodeClient() now moves on to the node's new client when a role change closed the one it waited on. The role change also clears the closed client's connectPromise, and a connect only clears connectPromise when it still owns it.
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. |
Cdineshreddy12
left a comment
There was a problem hiding this comment.
Traced this against the cluster-slots.ts connect paths — the fix looks correct to me, and the test reproduces the race precisely. A couple of notes:
The connectPromise ownership invariant holds. The retry in #waitForNodeClient depends on node.client and node.connectPromise always being a matched pair (so passing node.client alongside node.connectPromise from nodeClient() identifies the right client). They do stay in sync: #createNodeClient sets both synchronously, the demotion path at :786 now clears both together, and the .finally only nulls connectPromise when it still equals the one it created — so a newer client B's promise survives the old client A's rejection. That's what lets the retry pick up B. Nice.
One thing worth connecting to #3592: the retry awaits the new client's connectPromise with no timeout, same as the original path. For the brief-failover race this PR targets that's fine (it resolves in milliseconds), but it's the same unbounded-wait shape @nkaradzhov called out in #3592 ("it waits on the node's connectPromise in nodeClient(), where no timeout applies"). If a node's new client is itself slow/unreachable, a command can sit here past its command timeout. Not a regression — this PR doesn't make it worse — but the #3592 direction (let the command go into the node client's queue so the command timeout applies, rather than awaiting connectPromise) would also cover this retry path. Might be worth a cross-reference so the two don't drift.
Minor: the retry recurses through nodeClient() on each ClientClosedError. It's async so there's no stack concern, and it's bounded by actual topology transitions, so I don't think it needs a guard — just flagging that the recursion depth is "number of role changes during the connect" rather than a fixed bound, in case that's worth a comment in the code.
Builds clean locally. Couldn't run the cluster spec on my machine (the docker harness uses --network host, which doesn't expose ports on Docker for Mac), but the test reads correctly for the scenario.
Cdineshreddy12
left a comment
There was a problem hiding this comment.
Approving — traced the fix when I reviewed it earlier: the connectPromise ownership invariant the retry depends on holds at every site (set together, cleared together on demotion, and the .finally only clears its own promise), and the test pins the race deterministically. My earlier notes were advisory (the unbounded connectPromise wait predates this PR and is in scope for #3592, which I'll base on this once it merges).
…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.
…#3592) (#3652) * fix(cluster): resolve connect() without waiting for unreachable nodes 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 #3592: command routing to a not-yet-connected node (so the command timeout applies instead of waiting on connectPromise) follows on top of #3628. * fix(cluster): bound the wait for a connecting node by the command timeout nodeClient() keeps awaiting connectPromise, including the #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 #3592, on top of #3628. * fix(cluster): treat a zero command timeout as disabled and keep parked 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. * fix(cluster): report a superseded pub/sub re-init as superseded, not 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. * fix(cluster): attach once per connect and fan out to the waiters 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. * fix(cluster): bound the pub/sub wait for a connecting node too 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. * fix(cluster): bound the sharded unsubscribe wait too 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. * fix(cluster): keep sharded recovery unbounded, and arm long connect deadlines 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. * fix(cluster): keep the pub/sub resubscribe awaited during a refresh 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 (#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 #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. * test(cluster): keep discovery off the blocked port in the #3592 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. * fix(cluster): bound only the pub/sub waits the user asked for 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.
This pull request fixes a race in cluster mode: a command sent during a failover could fail with
The client is closed. The testcloses the sharded pub/sub client of a master demoted by a failoverfailed intermittently in CI because of this race.With
minimizeConnections, the cluster opens a node's client on first use. Here is how the race happens:#initiateSlotNodecloses the node's client.ClientClosedError. The command fails instead of following the topology change.Changes:
nodeClient()now retries with the node's current client when the client it waited on was closed by a role change. It retries only if the node is still in the cluster and the cluster is open. The command then reaches the demoted node, getsMOVED, and is redirected as usual.connectPromise, so new callers do not wait on the closed connect.connectPromiseonly if it still owns it, so it no longer clears a newer client's pending connect.A new test reproduces the race every time. It holds the TCP connect to the old master open across a slot-map refresh.
Note
Medium Risk
Changes cluster node connection and failover timing in
cluster-slots.ts; behavior is constrained toClientClosedErrorretries when topology refresh swaps clients, with a focused regression test.Overview
Fixes a cluster failover race where a command opened a lazy node connection to a stale master, topology refresh closed that client mid-connect, and the waiter surfaced "The client is closed" instead of continuing on the demoted node's new client.
nodeClient()now routes through#waitForNodeClient: onClientClosedError, if the cluster is still open, the node remains innodeByAddress, and a newer client replaced the one that was waited on, it recursively retriesnodeClient(node)so the command can follow normal MOVED redirection.connectPromiselifecycle is tightened: demoting a master to replica and closing its client clears the staleconnectPromise; a finished connect only clearsconnectPromisewhen it still owns that promise, avoiding clobbering a newer in-flight connect.Adds an integration test that gates TCP connect to the old master, triggers rediscover during connect, and asserts the command still completes with OK.
Reviewed by Cursor Bugbot for commit 7728995. Bugbot is set up for automated code reviews on this repo. Configure here.