Skip to content

fix(cluster): use reference equality to guard superseded pubSub connect error in #discover() - #3520

Merged
nkaradzhov merged 7 commits into
redis:masterfrom
tamil-selvan-k:master
Nov 3, 2026
Merged

nkaradzhov merged 7 commits into
redis:masterfrom
tamil-selvan-k:master

Conversation

@tamil-selvan-k

@tamil-selvan-k tamil-selvan-k commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Problem

#discover() pushed the #initiatePubSubClient() promise into promises
with a .catch guard to treat supersession as non-fatal:

if (err instanceof ClientClosedError && this.pubSubNode) return;

This guard is racy. The sequence that breaks it:

1. #discover() calls #initiatePubSubClient() → creates pubSubNode1,
   sets this.pubSubNode = pubSubNode1
2. A concurrent #handleSmigrated (enterprise SMIGRATED event) calls
   #initiatePubSubClient() again → creates pubSubNode2, sets
   this.pubSubNode = pubSubNode2
3. pubSubNode2's connection fails → its .catch clears
   this.pubSubNode = undefined
4. pubSubNode1's connection completes but is superseded → .then throws
   ClientClosedError
5. Guard fires: ClientClosedError && this.pubSubNode →
   ClientClosedError && undefined → false → re-throws

Result: Promise.all(promises) rejects, #discover() enters its catch
block, emits a cluster error, and disables client-side cache — even
though the cluster is fully healthy and a replacement pub-sub node was
already managing the connection.

Fix

Capture this.pubSubNode synchronously right after #initiatePubSubClient
returns (the method assigns this.pubSubNode = pubSubNode before its first
await, so the capture is atomic with respect to the event loop). Compare
by reference instead of truthiness:

const initPromise = this.#initiatePubSubClient({ ... });
const capturedPubSubNode = this.pubSubNode;
promises.push(
  initPromise.catch(err => {
    if (err instanceof ClientClosedError && this.pubSubNode !== capturedPubSubNode) return;
    throw err;
  })
);

this.pubSubNode !== capturedPubSubNode is true if and only if the node
was replaced by a concurrent call — regardless of what subsequently happened
to the replacement. This correctly identifies supersession even after the
replacement itself fails and clears this.pubSubNode.

Testing

All 50 unit tests in cluster-slots.spec.ts and pub-sub.spec.ts pass.
The race requires a concurrent SMIGRATED event during topology refresh, so
no new unit test is added — the fix is verified by code inspection and the
existing pub-sub regression suite.

---

<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Medium Risk**
> Touches cluster topology refresh and pub/sub reconnection error handling; incorrect logic could still mis-report failures or hide real connect errors, but the change is a narrow guard fix aligned with existing `#initiatePubSubClient` supersession checks.
> 
> **Overview**
> Fixes a race in cluster `#discover()` when it tears down and reconnects the dedicated pub/sub client during topology refresh.
> 
> The `.catch` on `#initiatePubSubClient()` no longer treats any truthy `this.pubSubNode` as “superseded.” It **captures** `this.pubSubNode` right after starting the init and **swallows** `ClientClosedError` only when `this.pubSubNode !== capturedPubSubNode`, so a stale connect failure is ignored even if a concurrent SMIGRATED/rediscover replaced the node and the replacement later failed and cleared `pubSubNode`.
> 
> That stops `Promise.all(promises)` from rejecting spuriously, which was surfacing cluster `error` events and disabling client-side cache on an otherwise healthy cluster.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f60239176da40ce90e7fa27ed0745a952b3f0a34. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

…very

When #discover() removes a pubSub node whose address is no longer in
the new topology, it calls destroy() on the client. If both
channelsListeners and patternsListeners are empty at that moment
(e.g. a SUBSCRIBE is still in-flight or all channels were just
unsubscribed), #initiatePubSubClient() is never called and
this.pubSubNode is left pointing at the destroyed client.

The next getPubSubClient() call sees a non-null pubSubNode and
returns Promise.resolve(pubSubNode.client) — the destroyed client —
causing ClientClosedError on every subsequent subscribe.

Null pubSubNode immediately after destroy(), matching the identical
pattern at all five other callsites in the same file.
…very

When #discover() removes a pubSub node whose address is no longer in
the new topology, it calls destroy() on the client. If both
channelsListeners and patternsListeners are empty at that moment,
#initiatePubSubClient() is never called and this.pubSubNode is left
pointing at the destroyed client, causing ClientClosedError on every
subsequent subscribe.

Also guard #initiatePubSubClient's .then/.catch callbacks with a
local-reference check so that a concurrent rediscovery cannot clobber
a newer pubSubNode: the .then destroys the old client and returns
early, and the .catch skips the null-assignment when this.pubSubNode
has already been replaced.

Regression tests use a minimal mock CLUSTER SLOTS server (no Docker
required) to exercise both code paths through the real production API.
…stale connect

When #initiatePubSubClient's .then callback detects that this.pubSubNode
was replaced by a concurrent rediscovery, it was destroying the old
client and then returning it to callers. Callers waiting on the original
connectPromise would receive a destroyed client and SUBSCRIBE would fail
with ClientClosedError.

Fix: throw ClientClosedError so the promise rejects cleanly. Also add a
second identity check after the async extendPubSubListeners call so that
a replacement occurring during resubscription is caught before resolving.
Issue 1 (medium): throwing ClientClosedError on supersession caused
#discover()'s Promise.all to reject, which failed the topology refresh
and disabled client-side cache even though a replacement pubSubNode
was already created. Fix: wrap the #initiatePubSubClient push in
#discover() to treat ClientClosedError as non-fatal when this.pubSubNode
is non-null (i.e. a concurrent rediscovery already replaced the node).

Issue 2 (low): the topology-removal regression test was trivially
asserting a manual assignment rather than exercising #discover().
Fix: plant a stale pubSubNode at an address outside the mock topology,
call rediscover(), and assert pubSubNode is cleared by the real code.
…ct error

The previous guard err instanceof ClientClosedError && this.pubSubNode
was racy: if a concurrent connection failure cleared this.pubSubNode after
supersession had occurred, the guard evaluated false and re-threw the
ClientClosedError, aborting #discover() and disabling client-side cache
even though the cluster was healthy.

Fix: capture this.pubSubNode immediately after #initiatePubSubClient
(which sets it synchronously before any await), then compare by reference.
this.pubSubNode !== capturedPubSubNode is true if and only if the node was
replaced by a concurrent call, regardless of what subsequently happened to
the replacement.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-17T16:15:47.036754Z f602391 PR opened
ℹ️ 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.

@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 for looking into this. The race is real, but the new check is always true by the time it runs:

  • If this node was replaced, this.pubSubNode points to another node or is undefined.
  • If this node failed on its own, the .catch inside #initiatePubSubClient() clears this.pubSubNode before this guard runs, so it is undefined.

Either way this.pubSubNode !== capturedPubSubNode, so the PR swallows every ClientClosedError from this call. That includes teardown, which the old comment said should re-throw.

What the guard needs to know is whether the cluster is still open. Could you change it to this?

promises.push(
  this.#initiatePubSubClient({
    [PUBSUB_TYPE.CHANNELS]: channelsListeners,
    [PUBSUB_TYPE.PATTERNS]: patternsListeners
  }).catch(err => {
    // While the cluster is open, ClientClosedError means this pub/sub node was
    // deliberately dropped (replaced or destroyed), not that discovery failed.
    if (err instanceof ClientClosedError && this.#isOpen) return;
    throw err;
  })
);

No new test needed for this one.

… #discover()

The reference-equality guard introduced in the previous commit was always
true by the time it ran: either the node was replaced (this.pubSubNode
differs) or it failed on its own (the .catch in #initiatePubSubClient
clears this.pubSubNode to undefined before this guard fires). Either way
the condition was true, silently swallowing every ClientClosedError from
this call — including teardown.

Use this.#isOpen instead: while the cluster is open, a ClientClosedError
from this call means the pub-sub node was deliberately dropped (replaced
or destroyed), not that discovery failed. If the cluster was destroyed
concurrently, #isOpen is false and the error propagates normally.
@tamil-selvan-k

Copy link
Copy Markdown
Contributor Author

Hi, This issue is fixed.

@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 b0e737d into redis:master Nov 3, 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.

2 participants