Repository navigation
Pub/Sub: don't orphan a subscribe that races the last unsubscribe of the same channel - #3363
Conversation
…the same channel Subscribing (looking up the channel's subscription, then adding the handler) and unsubscribing the last handler (removing it, removing the now-empty subscription from the multiplexer, then unsubscribing from the server) were not atomic with respect to each other. Interleaved, the handler could be added to a subscription that was being removed: nothing routes messages to it anymore, and the server is told to stop sending them; yet the subscribe completes successfully, so the handler silently never fires. A per-subscription registration lock now makes adding a handler and retiring the subscription mutually exclusive; a subscribe that finds the subscription retired looks up a fresh one instead. The retiring side also issues the unsubscribe command to the server (and only then removes the subscription from the multiplexer) while holding the lock, so that the racing subscribe's command is issued after it, rather than being able to overtake it and leave the server unsubscribed while the client considers itself subscribed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XUNs4qcAQaGCRpkwmr8LnY
|
Some additional evidence, in case it helps the review: I hit both variants through a higher-level usage pattern, not just the minimal repro in #3362, and measured the effect of this branch. Setup
Results
Every miss had one of two fingerprints. They match the two variants described in this PR:
The second variant reproduces on the released 3.4.20 and comes in bursts. Across three 1,500-iteration runs, it accounted for 41 of 42 misses in one run, none in another, and the bulk of a third. In the 1,800 iterations against Two more observations:
|
mgravell
left a comment
There was a problem hiding this comment.
Thanks for this, and for the measurements - the two fingerprints match what I'd expect from the code, and the approach (retire under a per-subscription lock, remove from the map only after the unsubscribe is issued) looks right to me.
One thing I'd like addressed before merging: because a retiring subscription now stays in the map until its unsubscribe has been issued, the restore paths (EnsureSubscriptions, UpdateSubscriptions) can still see it, and they don't check IsRetired. A reconnect in that window would re-issue the subscribe after the unsubscribe, leaving the server subscribed with nothing on the client. On main the subscription is removed first, so this window is new, and it is widest on the synchronous path where the lock is held across the round trip. Could the restore paths skip retired subscriptions (taking the lock, or making the flag safely readable without it), with a test?
Minor: a synchronous Unsubscribe now blocks a concurrent SubscribeAsync to the same channel for the duration of its round trip. I think that's acceptable, but a comment at TryAdd saying so would help.
This also needs a rebase: #3353 (the fix for #3336) and #3374 have just merged and touch the same files. The only conflict is trivial - two adjacent using lines at the top of Subscription.cs - but please re-check the restore path against the pending-claim logic that #3353 added to SingleNodeSubscription when you do.
The wider picture for this area is tracked in #3375.
# Conflicts: # src/StackExchange.Redis/Subscription.cs
Fixes #3362.
Subscribing a handler, and unsubscribing a channel's last handler, each take several steps that weren't atomic with respect to each other. When they interleave on the same channel, the new handler can be added to a
Subscriptionthat is concurrently being removed. Nothing routes messages to it anymore, and the server has been told to stop sending them.SubscribeAsyncstill completes successfully, so the handler silently never fires.Changes
Registration lock.
Subscriptiongets a registration lock and a "retired" flag.TryAdd) and retiring the subscription after its last handler is removed (RetireIfEmpty) are now mutually exclusive.ConnectionMultiplexer.AddToSubscription).Ordering on the wire. While still holding that lock, the retiring side first issues the unsubscribe command to the server, and only then removes the subscription from the multiplexer.
Multi-node unsubscribe.
MultiNodeSubscription.UnsubscribeFromServerAsyncnow issues the command to every server before awaiting any of them, so that all of them are issued while the lock is held.Unsubscribe-all.
UnsubscribeAll/UnsubscribeAllAsyncgo through the same retire-then-remove path.Things worth a reviewer's eye
Unsubscribeholds the registration lock while it waits for the server's reply. The lock is per subscription, so this only holds up concurrent subscribe/unsubscribe calls on the same channel. None of the reply-processing paths (TrackSubscriptionsProcessor, message dispatch,EnsureSubscriptions,ResubscribeToServer) take that lock, so it can't deadlock. The async paths only issue the command under the lock; they don't await it there.Subscription.cs,RedisSubscriber.cs), but the two address different races and should compose. Fix duplicate Pub/Sub subscription restoration after Sentinel failover #3337's restoration logic lives insideEnsureSubscribedToServer*, while this change is about whichSubscriptiona handler is added to, and the order of unsubscribe versus subscribe.Testing
SubscriptionRegistrationRaceUnitTests. It uses the in-process test server: 300 attempts at unsubscribing a channel's last handler while another handler subscribes to the same channel, then publishing and checking that it arrives.main, it consistently misses some messages.*UnitTestsclasses pass (1221), and all*PubSub*classes pass against a local primary/replica (91 passed, 93 skipped, needing cluster or sentinel). Both onnet10.0.Checklist