Skip to content

Pub/sub: overlapping subscription restores cannot register on two servers - #3353

Merged
mgravell merged 5 commits into
mainfrom
marc/pubsub-restore-race
Nov 23, 2026
Merged

mgravell merged 5 commits into
mainfrom
marc/pubsub-restore-race

Conversation

@mgravell

Copy link
Copy Markdown
Member

Fixes #3336.

During a Sentinel failover, ServerEndPoint.OnFullyEstablished (per reconnecting connection) and ConnectionMultiplexer.ReconfigureAsync both restore subscriptions fire-and-forget. A SingleNodeSubscription only records its server when the (P)SUBSCRIBE acknowledgement is processed, so between send and ack a concurrent restore saw the subscription as disconnected and subscribed again — often on a different node (sometimes a replica, depending on selectability mid-failover). The later ack overwrote the recorded endpoint while the earlier registration stayed live on its server, and since message dispatch is by channel only, every publish was delivered twice until that connection happened to drop. (Nice diagnosis by the reporter — confirmed accurate end to end, including their in-process repro test, which failed 8/8 against main.)

Two layers:

  • Claim before send: a pending-claim token (CAS) makes competing restores back off while a subscribe attempt is in flight. The subscribe message itself is no longer fire-and-forget even when the caller is (the caller just doesn't await it — "fire-and-observe"), so every completion — ack, error reply, connection failure, timeout — observably releases the claim, preserving retry liveness. Disconnected pending claims are also dropped in RemoveDisconnectedEndpoints.
  • Reconcile at ack: AddEndpoint becomes TryAdoptEndpoint, which rejects an ack when the subscription is already confirmed on a different connected server; the processor then sends a fire-and-forget unsubscribe pinned to the stray node. This mops up anything the claim cannot prevent (e.g. a timed-out attempt whose ack arrives late).

Multi-node (keyspace) subscriptions always adopt — they want every eligible node — so their behavior is unchanged.

Tests: the reporter's overlap scenario (first ack held, second restore must not subscribe elsewhere) plus the stray-ack cleanup, literal/pattern × normal/F&F × RESP2/RESP3, on the in-process test server. Full suite green locally apart from the known SortedSetScanLarge ZSCAN environment failures (fixed on the 8.12 branch).

The reporter also mentioned a separate reconfiguration-gate change for slow concurrent Sentinel discovery; that is intentionally not part of this PR.

…vers (#3336)

During a failover, OnFullyEstablished (per reconnecting connection) and
ReconfigureAsync both restore subscriptions fire-and-forget; between sending
(P)SUBSCRIBE and its acknowledgement a SingleNodeSubscription recorded no
server, so a concurrent restore would subscribe again - often on a different
node. The later ack then overwrote the recorded endpoint while the earlier
registration stayed live on its server, delivering every message twice until
that connection happened to drop.

Two layers:
- claim before send: a pending-claim token (CAS) makes competing restores back
  off while an attempt is in flight; the subscribe message is sent without
  fire-and-forget (callers that asked for F&F just don't await it) so every
  completion - ack, error reply, connection failure, timeout - observably
  releases the claim, keeping retry liveness.
- reconcile at ack: TryAdoptEndpoint rejects an ack when the subscription is
  already confirmed on a different connected server, and the processor sends a
  fire-and-forget unsubscribe pinned to the stray node - mopping up anything
  the claim cannot prevent (e.g. a timed-out attempt whose ack arrives late).

Regression tests run the reporter's overlap scenario (held first ack, second
restore must not subscribe elsewhere) plus the stray-ack cleanup, per protocol,
on the in-process test server.
Review follow-ups:
- TryAdoptEndpoint installs the adopted server *before* releasing the
  pending claim, so a competing restore that wins the next claim cannot
  observe the pre-adoption state.
- The post-claim "_currentServer = null" is now conditional (shared
  BeginSubscribeAttempt helper): a live server installed by a concurrent
  ack is left alone ("already connected") instead of being wiped, which
  orphaned a confirmed server-side registration - the #3336 symptom in a
  narrower window. Only a stale (disconnected) server is cleared, via
  CAS; RemoveIncorrectRouting's wipe gets the same treatment.
- A contended claim no longer silently no-ops a *user* subscribe: only
  internal restores defer to the in-flight attempt; user calls proceed
  unclaimed (ack-time reconciliation dedupes), preserving the
  "acknowledged or thrown" contract and honouring a caller-pinned server.
- A deferred internal restore counts as a pending change (1, not 0), so
  reconfigure logs no longer say "no subscription changes" mid-restore.
- ResubscribeToServer (sunsubscribe/smigrated) routes through
  EnsureSubscribedToServerAsync, so those restore paths participate in
  the claim handshake instead of bypassing it.
- The sync/async ensure paths share the delicate claim logic
  (BeginSubscribeAttempt / ExecuteFireAndObserve) instead of
  duplicating it.
- Fix a pre-existing inverted condition in
  MultiNodeSubscription.RemoveDisconnectedEndpoints, which removed the
  *connected* endpoints and kept the disconnected ones.
The scenarios from #3337 that apply to this design: overlapping restores
subscribe on one server only, a late acknowledgement cannot displace a newer
subscription, a reconnected subscription delivers on the new connection, the
unsubscribe task keeps the caller's async state, and repeated replacement
never calls a stopped handler.

The #3337 scenarios for unsubscribing while a subscribe is unacknowledged are
not included: that gap is not addressed here and is tracked separately.

Co-authored-by: vkyow <[email protected]>
An internal restore that backs off in favour of an in-flight subscribe had no
one to retry it if that attempt then failed: the restore paths are driven by
events (disconnect, reconfigure, connect), not a timer, so the subscription
could sit on no server at all. RetirementUnderMaintenanceTests showed it
intermittently: the subscription never moved to the surviving node.

- a claim held by an attempt aimed at a server we are no longer connected to
  can be taken over, rather than waiting for a backlog that may never drain
- an attempt that ends without a confirmed server re-drives the restore on
  behalf of whoever deferred to it
- a restore with no selectable server defers to a live in-flight attempt
  rather than racing it unclaimed
A restore that deferred to a claim was forgotten when that claim stopped
being the pending one, because only the pending claim's Release re-drives:

- on takeover, the new claim inherits the old claim's deferral
- a disconnect no longer clears a claim aimed at the lost server; takeover
  already stops such a claim obstructing anything, and clearing it orphaned
  the deferral in the same way
@mgravell
mgravell merged commit 50f1ea8 into main Nov 23, 2026
5 checks passed
@mgravell
mgravell deleted the marc/pubsub-restore-race branch November 23, 2026 16:21
mgravell added a commit that referenced this pull request Nov 23, 2026
…ptEndpoint (#3376)

#3374 added a test calling Subscription.AddEndpoint; #3353 renamed that to
TryAdoptEndpoint. Each was green alone and they merged without a textual
conflict, but main does not compile with both.
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.

Duplicate Pub/Sub messages after Redis Sentinel failover

1 participant