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 <noreply@anthropic.com> 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
…outing, subscribe/unsubscribe race (#3406) * Expose `HashSlot(RedisChannel)` on `IConnectionMultiplexer` (#3366) Fixes #3365. There was no public way to ask which hash slot a `RedisChannel` is routed by. The usual workaround is `HashSlot(new RedisKey(channel))`, which hashes the channel's name as a key. It gets two cases wrong: a configured `ChannelPrefix`, and single-key keyspace channels, which are routed by their key. This exposes the existing `ServerSelectionStrategy.HashSlot(in RedisChannel)`, which is what routing actually uses and handles both. - **New `IConnectionMultiplexer.HashSlot(RedisChannel)`**, implemented by `ConnectionMultiplexer` (delegating to `ServerSelectionStrategy.HashSlot(in RedisChannel)`). Also forwarded by `MultiGroupMultiplexer` and the test fixture's `NonDisposingConnection`. - **`ServerSelectionStrategy.HashSlot(in RedisChannel)` now returns `NoSlot` (`-1`) for multi-node channels** (`IsMultiNode`, e.g. `KeySpacePattern`/`KeySpacePrefix`), which are subscribed on every node rather than routed by slot. Internally, slot-based routing is unaffected: the maintenance migration check only considers sharded channels, and multi-node subscriptions never select a server by slot. - **`[OverloadResolutionPriority(1)]` on the existing `HashSlot(RedisKey)`**, on both the interface and `ConnectionMultiplexer`. `string` and `byte[]` convert implicitly to both `RedisKey` and `RedisChannel`; the channel conversions are `[Obsolete]`, but that doesn't remove them from overload resolution. Without the attribute, `HashSlot("key")` becomes ambiguous (CS0121). I checked this: removing it breaks existing calls in `ClusterTests` and `HotKeysTests`. This follows the precedent of `RedisChannel.KeySpacePrefix`, including the framework shim for older TFMs. - **`PublicAPI.Unshipped.txt`** entries. - **A new interface member.** This adds a member to `IConnectionMultiplexer`, which is a break for anyone implementing it outside the library. Happy to change the shape (e.g. an extension method) if you'd rather avoid that. - **The priority attribute on an existing member.** Adding it doesn't change any signature, so it isn't a binary break. Compilers that don't understand the attribute would still see the ambiguity for `string`/`byte[]` arguments. - **Plain literal and pattern channels.** These return the slot of the (prefixed) name: that's the slot this client routes them by, which decides the node it subscribes on, rather than a server-side slot constraint. Multi-node channels return `-1`. As with `HashSlot(RedisKey)`, it returns `-1` when not connected to a cluster. - **New `ChannelHashSlotUnitTests`**, against the in-process server in cluster mode: - a sharded channel has the same slot as the same-named key; - with a `ChannelPrefix`, its slot is the prefixed name's; - a `KeySpaceSingleKey` channel has its key's slot; - a plain literal channel on a cluster has its name's slot; - multi-node channels (`KeySpacePattern`, `KeySpacePrefix`) return `-1`; - standalone returns `-1`; - `string` and `byte[]` arguments still bind to the key overload, both through `ConnectionMultiplexer` and through the interface. - **Builds** for all of `StackExchange.Redis`'s TFMs with no warnings. - **Existing tests:** all `*UnitTests` classes pass on `net10.0`, and CI is green on Ubuntu and Windows. (cherry picked from commit f80bdd4) * A publish that demands a primary does not follow a subscription onto a replica (port of main #3380 / #3357) v4's publish used the server the channel is subscribed on whenever there was one (ResolveForChannel). After a promotion that server can be a replica, and a DemandMaster publish then failed with the new primary known. ResolveForChannel now carries the publish's flags, and the subscribed server is used only when it satisfies the primary/replica demand (GetPublishServer, as main). Main's PublishRoutingUnitTests come over unchanged: 6 of 8 fail without this change. (cherry picked from commit 97d17b7, by intent) * Pub/sub: don't orphan a subscribe that races the last unsubscribe of the same channel (port of main #3363) v4 had main's race: adding a handler and retiring the channel's last one were not atomic, so a handler could land on a subscription being removed and never fire. SubscriptionRegistrationRaceUnitTests failed on v4 before this; it passes now. The patch applied to v4's RedisSubscriber as-is. In Subscription, the multi-node UnsubscribeFromServerAsync now issues every UNSUBSCRIBE through v4's SendAsync before awaiting any of them, so all are written while the registration lock is held, as main's version does. (cherry picked from commit d278bf6, by intent) --------- Co-authored-by: Arad Alvand <aradalvand@gmail.com>
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