Skip to content

Pub/Sub: track retiring subscriptions and drive cleanup via ack, restore, and heartbeat - #3368

Open
aradalvand wants to merge 3 commits into
seredis:mainfrom
aradalvand:fix/failed-unsubscribe-leaves-server-subscribed
Open

aradalvand wants to merge 3 commits into
seredis:mainfrom
aradalvand:fix/failed-unsubscribe-leaves-server-subscribed

Conversation

@aradalvand

@aradalvand aradalvand commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #3367. Addresses items 1, 2, and 3 of #3375.

Unsubscribing a channel's last handler retires its subscription on the client whether or not the server-side unsubscribe succeeds (or even sends, if a SUBSCRIBE is still in flight). Previously, if the server declined the unsubscribe (e.g. BUSY, LOADING, MASTERDOWN), if the unsubscribe timed out, if a SUBSCRIBE was unacknowledged when unsubscribed, or if a stray cleanup unsubscribe for a live subscription was declined, the server remained subscribed with nothing left on the client to clean it up until the connection was replaced.

Changes

  • Explicit retiring state on Subscription:
    • Subscription.IsRetired is safely readable without RegistrationLock (Interlocked.Exchange / Volatile.Read).
    • Restore paths (EnsureSubscriptions, EnsureSubscribedToServer[Async], deferred PendingClaim release, ResubscribeToServer, and ResubscribeStrandedShardedChannels) skip retired subscriptions.
    • TryAdoptEndpoint records the acked server and returns false when retired (re-checking IsRetired after publishing _currentServer so an ack racing UnsubscribeFromServer cannot be missed).
  • Heartbeat- and restore-driven retirement:
    • Retired subscriptions that observe a failure, timeout, write failure, or deferral are marked retry-needed and tracked in ConnectionMultiplexer._retiringSubscriptions, then driven by OnHeartbeat() and EnsureSubscriptions() (with disconnected endpoints cleaned up in UpdateSubscriptions()).
    • The retry-needed flag is consumed before re-issuing so slow servers do not receive duplicate unsubscribes on every heartbeat while merely waiting for a reply.
    • Both send branches in TryUnsubscribeRetiringServer issue the fire-and-forget unsubscribe under lock (subscriptions) to order against new GetOrAddSubscription calls; if a newer active subscription already owns the server, the server is dropped from the retired record without unsubscribing.
  • Self-correcting unsubscribe replies & stray cleanup retries:
    • In TrackSubscriptionsProcessor.SetResultCore, when an UNSUBSCRIBE/PUNSUBSCRIBE/SUNSUBSCRIBE reply arrives on a server and the current active subscription for that channel is a different, non-retired object that believes it is on that server, the endpoint is cleared and the active subscription is immediately re-subscribed — preventing silent message loss if a retired unsubscribe overtakes a lock-free restore.
    • When a stray SUBSCRIBE ack arrives on another server for a live subscription (Duplicate Pub/Sub messages after Redis Sentinel failover #3336 / Pub/sub: client and server subscription state can disagree #3375 item 3), the stray registration is tracked as a retired SingleNodeSubscription so declined stray cleanups are also retried via the heartbeat/restore path (and benefit from the same self-correction).
  • In-flight subscribe/unsubscribe:
    • Both SingleNodeSubscription.UnsubscribeFromServerAsync and UnsubscribeFromServer queue an unsubscribe behind an in-flight _pending subscribe on that server (fire-and-forget on the sync path so sync callers like UnsubscribeAll do not block or time out, while still closing the gap if the in-flight subscribe times out and its late ack is dropped by Message.ComputeResult).
    • TryConsumePendingUnsubscribe lets the ack path skip sending a second UNSUBSCRIBE when one was already queued behind the pending subscribe.

Testing

  • FailedUnsubscribeUnitTests (RESP2 & RESP3, 18 tests): declined async/sync/fire-and-forget/multi-node unsubscribes, timed-out-then-declined, slow unsubscribe not re-sent by heartbeat, newer subscription not undone, retired unsubscribe overtaking an active subscription self-correcting, and restore skipping a retired subscription.
  • SubscriptionRestorationTests (RESP2 & RESP3, 44 tests): the four in-flight subscribe/unsubscribe scenarios from Fix duplicate Pub/Sub subscription restoration after Sentinel failover #3337/Pub/sub: client and server subscription state can disagree #3375 (asserting single UNSUBSCRIBE on the wire and server-side PUBLISH == 0), sync unsubscribe during a subscribe that times out, and DeclinedStrayCleanupIsRetried.
  • All *UnitTests pass (1,242 on net10.0); Release multi-TFM build passes with 0 warnings across all 5 TFMs.

Checklist

  • I fully and freely contribute this code in accordance with the project license (and am legally able to do so)
  • I take responsibility for this contribution's quality and correctness, including any portions produced with AI assistance (see CONTRIBUTING.md)

@aradalvand
aradalvand force-pushed the fix/failed-unsubscribe-leaves-server-subscribed branch from 903d730 to ebe2190 Compare November 20, 2026 19:37
@mgravell

Copy link
Copy Markdown
Member

Thanks - the diagnosis in #3367 is accepted, and the BUSY-replying test server is a good way to pin it.

I don't want to merge the retry loop as it stands: it gives up after 30 attempts, so the leak is bounded but not closed; each failure starts its own background task with no tie to multiplexer shutdown; and there is the timed-out-then-declined hole you already called out. I'd prefer the client to remember "retire pending" as state and let the existing heartbeat and restore path drive it, which also covers a related gap (unsubscribe while a subscribe is unacknowledged). That work is tracked in #3375, and I'd like to use your FailedUnsubscribeUnitTests as acceptance tests there.

I'll leave this open until that lands, in case it is useful as a reference. #3363, which this builds on, has a separate review.

Unrelated to your change: the earlier Ubuntu failure here was a flake in the in-process test server.

…ore, and heartbeat

Replaces the per-failure background retry loop with an explicit retiring state on Subscription driven by the existing ack, restore, and heartbeat paths (addressing seredis#3367 and items 1-2 of seredis#3375):

- Make Subscription.IsRetired safely readable without RegistrationLock (Interlocked.Exchange / Volatile.Read) and skip retired subscriptions in EnsureSubscriptions, EnsureSubscribedToServer[Async], Release, ResubscribeToServer, and ResubscribeStrandedShardedChannels.
- Track retiring subscriptions that still have server endpoints in ConnectionMultiplexer._retiringSubscriptions and drive them from OnHeartbeat() and EnsureSubscriptions(), cleaning up disconnected endpoints in UpdateSubscriptions().
- Honour IsRetired in TryAdoptEndpoint and TrackSubscriptionsProcessor.SetResultCore so late SUBSCRIBE acks on retired subscriptions (e.g. unsubscribed while a subscribe was in flight) are cleaned up without disturbing a newer active subscription on the same or another server.
- Queue async unsubscribes behind an in-flight SingleNodeSubscription subscribe on the pending server so async callers wait for the unsubscribe.
- Keep FailedUnsubscribeUnitTests (plus timed-out-then-declined and restore-skips-retired cases) and add the four in-flight subscribe/unsubscribe acceptance tests from seredis#3337/seredis#3375 in SubscriptionRestorationTests.
@aradalvand
aradalvand force-pushed the fix/failed-unsubscribe-leaves-server-subscribed branch from ebe2190 to e22fafa Compare November 24, 2026 21:33
@aradalvand

Copy link
Copy Markdown
Contributor Author

Thanks for the feedback — I've rebased onto main (post-#3363, #3353, #3374) and reworked this in e22fafa around the explicit retiring-state design described here and in #3375:

  • No background retry tasks / no attempt cap: retiring subscriptions that still have unconfirmed server endpoints are tracked in ConnectionMultiplexer._retiringSubscriptions and driven by OnHeartbeat() and EnsureSubscriptions() (with disconnected endpoints cleared in UpdateSubscriptions()), so cleanup stays tied to the multiplexer lifecycle and closes the timed-out-then-declined gap too.
  • Honoured by ack and restore paths: Subscription.IsRetired is now safely readable without RegistrationLock; restore paths (EnsureSubscriptions, EnsureSubscribedToServer[Async], deferred PendingClaim release, ResubscribeToServer, and ResubscribeStrandedShardedChannels) skip retired subscriptions, and TryAdoptEndpoint + TrackSubscriptionsProcessor.SetResultCore clean up late SUBSCRIBE acks on retired subscriptions without disturbing a newer active subscription on the same or another server.
  • In-flight subscribe/unsubscribe: SingleNodeSubscription.UnsubscribeFromServerAsync queues behind an in-flight _pending subscribe on that server, while sync Unsubscribe/UnsubscribeAll detaches immediately and lets the late ack trigger cleanup.
  • Acceptance tests: kept FailedUnsubscribeUnitTests (adding TimedOutThenDeclinedLastUnsubscribeIsRetried and RestoreSkipsRetiredSubscription) and added the four in-flight scenarios from Fix duplicate Pub/Sub subscription restoration after Sentinel failover #3337/Pub/sub: client and server subscription state can disagree #3375 to SubscriptionRestorationTests. All pass under both RESP2 and RESP3.

@mgravell

Copy link
Copy Markdown
Member

Thanks for this rework. It's the design I had in mind in #3375: a retired subscription keeps its server until the server confirms the unsubscribe, and the ack, restore and heartbeat paths drive it. There are no background tasks and no attempt cap. The cases where an ack races the retire hold up: at least one side always sees the other, so the worst case is a duplicate unsubscribe. The restore paths all skip a retired subscription. The fire-and-forget case and the timed-out-then-declined case are both closed now. The tests pass for me locally, repeatedly.

A few things need sorting before this merges, in rough order of severity:

  1. This can now cause silent message loss. In TryUnsubscribeRetiringServer, the "newer subscription is confirmed elsewhere" branch decides under lock (subscriptions) but sends outside it. Holding the lock wouldn't help anyway, because restores never take it. The sequence:

    • The retired subscription is still recorded on server S, and the newer one is live on T.
    • T drops, and the restore moves the newer subscription to S.
    • The heartbeat's UNSUBSCRIBE to S is written after the new SUBSCRIBE.

    Now the server has dropped the channel, but the newer subscription still believes it's on S, and nothing repairs that until a reconnect. That's worse than the leak we started with, because it's silent. The heartbeat re-sending (point 2) widens the window. I think the robust fix is to make the unsubscribe reply self-correcting: when an UNSUBSCRIBE reply for a channel arrives on S, and the current subscription for that channel is a different object that believes it's on S, clear its endpoint and re-subscribe it. Then any ordering mistake recovers by itself instead of failing quietly. A test that forces the sequence above would pin it.

  2. The heartbeat re-sends unsubscribes that are merely waiting for their reply. A subscription is tracked from the moment its unsubscribe is issued, and ProcessRetiringSubscriptions re-sends a fire-and-forget UNSUBSCRIBE for every tracked entry with a connected server. Against a slow server, that's one extra UNSUBSCRIBE per channel per heartbeat until the first reply lands. It should re-issue only after a failure or timeout has actually been observed.

  3. The sync path still has a gap. Message.ComputeResult drops the late reply of a command whose result box has already faulted. While a subscribe is in flight, the sync unsubscribe sends nothing and relies on that subscribe's ack. If the subscribe has already timed out, the ack is never processed and the server stays subscribed. The async path mostly avoids this by queueing an UNSUBSCRIBE behind the pending SUBSCRIBE. Doing the same on the sync path would close it.

  4. The PR description still describes the first design: OnUnsubscribeNotApplied, the backoff, the 30-attempt cap, TryIssueWhileUnsubscribed and ObserveUnsubscribe. None of those exist any more, and this text becomes the squash commit message. Could you update it to match what's here now?

Smaller points:

  • The in-flight tests mostly assert that an UNSUBSCRIBE arrived. Asserting that the server ended up unsubscribed (PUBLISH reaching 0 clients, as the FailedUnsubscribeUnitTests already do) would be stronger.
  • The failed-unsubscribe tests only cover literal channels. A multi-node case would be worth having.
  • AsyncTimeout = 200 and SyncTimeout = 100 are fine locally, but we already have a Windows CI flake from a 200ms timeout in this test class (LateAcknowledgementCannotReplaceANewerSubscription). Something more generous would save us chasing it later.
  • In TryUnsubscribeRetiringServer, one branch sends under the lock and the other outside it. Whichever rule we keep (see point 1), it should be the same rule in both places, with a comment saying why.

Given how much of this is now in place, I'm treating this PR as the route for items 1 and 2 of #3375, and I'll close my draft #3377 in its favour.

You've left maintainer edits enabled. If you'd rather not take on the remaining items, or would like a hand with any of them, just say so, and I'm happy to push them to this branch myself. Your call entirely.

@aradalvand aradalvand changed the title Pub/Sub: retry a last unsubscribe the server declined, rather than leaving it subscribed Pub/Sub: track retiring subscriptions and drive cleanup via ack, restore, and heartbeat Nov 26, 2026
@aradalvand

aradalvand commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Just addressed all of these in d8526e8 and updated the PR title and description:

  1. Self-correcting unsubscribe reply: TrackSubscriptionsProcessor.SetResultCore now checks whether an UNSUBSCRIBE/PUNSUBSCRIBE/SUNSUBSCRIBE reply landed on an endpoint owned by a different, active subscription for the same channel; if so, it clears that endpoint and immediately re-subscribes the active subscription (fire-and-forget). Pinned with RetiredUnsubscribeOvertakingActiveSubscriptionSelfCorrects.
  2. Retry only after failure/timeout/deferral: added a retry-needed flag on Subscription set only on error replies (TrackSubscriptionsProcessor.SetResult), sync/async failures/timeouts, write failures, or deferrals, and consumed via TryTakeUnsubscribeRetryNeeded() before re-sending on heartbeat. Pinned with SlowUnsubscribeIsNotResentByHeartbeat.
  3. Sync path with timed-out in-flight subscribe: SingleNodeSubscription.UnsubscribeFromServer now queues a fire-and-forget UNSUBSCRIBE behind _pending.Server (without blocking sync callers like UnsubscribeAll), and SetResult / fault observation records the endpoint if that unsubscribe fails. Pinned with SyncUnsubscribeDuringInFlightSubscribeThatTimesOutStillUnsubscribes.
  4. PR description & smaller points: updated the PR description to match the current design, unified both send branches in TryUnsubscribeRetiringServer under lock (subscriptions) with a comment, added DeclinedMultiNodeLastUnsubscribeIsRetried, strengthened the in-flight tests to assert PUBLISH reaches 0 clients, and bumped the test timeouts from 100–200ms to 500ms.

mgravell added a commit that referenced this pull request Nov 27, 2026
Unsubscribing a channel's last handler retires the subscription on the client
whether or not the server ran the unsubscribe. If the server declined it (BUSY,
LOADING, TRYAGAIN, CLUSTERDOWN) it stayed subscribed, with nothing left on the
client that would ever unsubscribe it (#3367). The same applied to the removal
of a stray registration (#3375).

The reply processing now notices the refusal, including for fire-and-forget,
and records it; the heartbeat issues the unsubscribe again, once per beat, until
the server runs it or the connection it was subscribed on is replaced. The
caller still sees the original failure. The retry goes through the same guard
as other stray removals, so it never unsubscribes a channel that has been
subscribed again.

Fixes #3367. Tests from #3368.

Co-authored-by: aradalvand <26527405+aradalvand@users.noreply.github.com>

@mgravell mgravell left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the quick turnaround on d8526e8. As an independent check I ran the tests from my closed draft (#3377) against this branch. They were written against a different implementation, so they needed adjusting for two design differences here, neither of which is a problem:

  • UnsubscribeAsync does not complete until the in-flight subscribe is acknowledged, because the unsubscribe is queued behind it.
  • A retired subscription keeps its server until the unsubscribe reply arrives, so state settles on the reply and not on the send.

With those adjustments the outcomes hold: restores skip a retired subscription, an unsubscribe during an in-flight subscribe leaves the server unsubscribed (literal, pattern and multi-node; sync and async), declined unsubscribes are retried, and a replacement subscription is not disturbed. I looked at the same-server replacement case in particular: the old subscription's ack defers, and the next heartbeat drops the server from the retired record without sending anything. One unsubscribe reaches the server, ahead of the replacement's subscribe, and the replacement is never re-subscribed.

Two things came out of it. Neither blocks merging, hence the approval.

  1. An unsubscribe during an in-flight subscribe is sent twice. One is queued behind the pending subscribe when the unsubscribe is called, and the ack path (TryAdoptEndpoint returning false, then TryUnsubscribeRetiringServer) sends another. I see two UNSUBSCRIBEs on the wire when there is no replacement, or when the replacement is confirmed on another server. It is harmless, since the second is a no-op on the server. If the ack path can tell that one is already queued, it could skip the send and rely on the retry-needed flag should the queued one fail.

  2. A declined cleanup of a stray is not retried when the subscription is live. This is the #3336 case: a late ack arrives for a subscription that is already confirmed on another server, and the stray registration is removed with a fire-and-forget unsubscribe. If the server declines that one (BUSY etc.), nothing issues it again, because the error handling in TrackSubscriptionsProcessor.SetResult is gated on IsRetired. The stray then delivers duplicates until the connection is replaced. This is item 3 of #3375, which this PR does not claim to address. There is a test for it on the #3377 branch (DeclinedStrayCleanupIsRetried in SubscriptionRestorationTests).

Do you particularly want to take those two yourself in this PR? If not, I'm happy to merge this as it stands and pick them up myself afterwards. Your call; let me know which you prefer.

@aradalvand

aradalvand commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the approval and the verification. Both of those turned out to fit very cleanly on top of the existing retiring machinery, so I went ahead and added them in 97cf584 (and updated the PR description to include item 3 of #3375):

  1. Single UNSUBSCRIBE during an in-flight subscribe: SingleNodeSubscription now records _pendingUnsubscribeServer when queueing an unsubscribe behind _pending; the ack path consumes it via TryConsumePendingUnsubscribe(ep) and skips sending a duplicate, still relying on SetResult / ObserveUnsubscribeFault if the queued one fails. Added UnsubscribeCount == 1 assertions to the in-flight tests.
  2. Retrying declined stray cleanups on live subscriptions (Pub/sub: client and server subscription state can disagree #3375 item 3): when a stray subscribe ack arrives on ep for a live subscription confirmed elsewhere, SetResultCore now tracks ep on a retired SingleNodeSubscription and routes it through TryUnsubscribeRetiringServer, so declined stray cleanups are retried on heartbeat/restore (and get the same active-subscription check and self-correcting reply handling for free). Pinned with DeclinedStrayCleanupIsRetried (literal & pattern, RESP2 & RESP3).

This branch has not been deployed

No deployments
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.

Pub/Sub: a failed unsubscribe of the last handler leaves the server subscribed while the client forgets it

2 participants