Skip to content

Pub/Sub: retry a last unsubscribe the server declined, rather than leaving it subscribed - #3368

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

aradalvand wants to merge 1 commit 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.

Builds on #3363. This branch includes its commit (bb0d88f), since it restructured the unsubscribe path this change hooks into. The change itself is the second commit, ebe2190. I'll rebase once #3363 is merged.

Unsubscribing a channel's last handler retires its subscription on the client whether or not the server-side unsubscribe succeeds. When the server declined to run it, for example with a BUSY reply while a script runs, it stays subscribed. It keeps pushing messages that nothing receives, and nothing is left on the client to unsubscribe, until the connection is replaced. This happens for awaited, synchronous and FireAndForget unsubscribes alike.

Changes

  • A new ConnectionMultiplexer.OnUnsubscribeNotApplied re-issues the retired subscription's unsubscribe, with backoff from 100ms up to 5s, at most 30 attempts, unless the channel has been subscribed to again by then, at which point client and server agree once more. It's called once per failure, including failures of the re-issued unsubscribes, from wherever that failure is observed:
    • TrackSubscriptionsProcessor.SetResult (now overridden) handles error replies. It checks whether an error reply to an UNSUBSCRIBE/SUNSUBSCRIBE/PUNSUBSCRIBE of a retired subscription is one where the server never ran the command (FaultContext.IsKnownNotApplied: BUSY, LOADING, MASTERDOWN, …). Reply processing sees every reply, so this works whether or not anyone awaits the command; FireAndForget included.
    • ObserveUnsubscribe (on the returned task) and the sync path's catch handle failures with no reply at all, where the command was never written (FaultContext.NotApplied). Server errors are left to the processor, so nothing is retried twice.
  • The caller still observes the original failure. Only the consequence is repaired.

Things worth a reviewer's eye

  • Ordering against a newer subscription. A re-issued unsubscribe must never undo a subscription made after the failed one; that's the same class of race as Pub/Sub: don't orphan a subscribe that races the last unsubscribe of the same channel #3363. So each re-issue goes through the new TryIssueWhileUnsubscribed. It holds the same lock as GetOrAddSubscription, and only issues the command if the channel still has no subscription. A subscription added afterwards therefore has its subscribe command issued after the unsubscribe. Like Pub/Sub: don't orphan a subscribe that races the last unsubscribe of the same channel #3363, this relies on commands to the same bridge being written in the order they're issued.
  • Reading IsRetired in the processor without RegistrationLock. A subscription is retired before its unsubscribe command is issued, so before that command's reply can be read. The flag also never goes back from true.
  • Which server it's re-issued to: the retired Subscription's own server(s), where the server-side subscription actually lives. An error reply doesn't clear _currentServer.
  • Timeouts. SE.Redis keeps a timed-out command queued so later replies still line up (OnBridgeHeartbeat), but Message.ComputeResult skips processing the late reply of a command whose result box has already faulted. So:
    • a FireAndForget unsubscribe's late error reply is handled (it has no box);
    • an unsubscribe that timed out before being written is handled by ObserveUnsubscribe (NotApplied, by its status);
    • one gap remains: an awaited unsubscribe that's written, times out, and then gets a "declined" error reply. That seems unlikely, since such errors are typically immediate. Closing it would mean letting processors observe late replies, which felt too broad for this PR.
  • A dropped connection isn't retried: the server forgets the subscription anyway. A retry that's pending when the connection is replaced is a harmless no-op on the new connection.
  • A background task for each scheduled retry. I didn't see an existing scheduler for this kind of deferred work; happy to move it if there's a better place.

Testing

  • New FailedUnsubscribeUnitTests, run for both protocols, against an in-process server that replies BUSY to UNSUBSCRIBE a given number of times:
    • DeclinedLastUnsubscribeIsRetried (async), DeclinedSyncLastUnsubscribeIsRetried and DeclinedFireAndForgetLastUnsubscribeIsRetried: the server ends up unsubscribed (PUBLISH reaches 0 clients). Without the fix, all three fail on both protocols.
    • RetriedUnsubscribeDoesNotUndoNewerSubscription: subscribing again right after the failure isn't undone by the retries.
  • All *UnitTests classes pass (1229, on net10.0).
  • Against a real Redis 8.10.2, with the repro from Pub/Sub: a failed unsubscribe of the last handler leaves the server subscribed while the client forgets it #3367, both awaited and FireAndForget:
    • 3.4.20: server-side subscribers stay at 1.
    • With this change: they drop to 0 within the backoff window.

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).

🤖 Generated with Claude Code

https://claude.ai/code/session_01XUNs4qcAQaGCRpkwmr8LnY

@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.

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