Unsubscribe from SMS stream fails with timeout
I'm facing an issue when calling UnsubscribeAsync on SMS provider subscription instance in OnDeactivateAsync grain method. The internal call in PubSub grain timeouts (in release mode) or hangs when debugger is attached.
[2018-03-31 16:17:39.623 GMT 22 ERROR 100516 Catalog 10.0.75.1:0] !!!!!!!!!! Error calling grain's OnDeactivateAsync() method - Grain type = Conreign.Server.Gameplay.LobbyGrain Activation = [Activation: S127.0.0.1:22222:260208985*grn/1A5E3811/00000000+natalie4@ff4a47bf #GrainType=Conreign.Server.Gameplay.LobbyGrain Placement=RandomPlacement State=Deactivating]
Exc level 0: System.TimeoutException: Response did not arrive on time in 00:00:30 for message: Request S127.0.0.1:22222:260208985*grn/1A5E3811/00000000+natalie4@ff4a47bf->S127.0.0.1:22222:260208985*grn/716E8E94/00000000+DefaultStream_conreign/rooms/natalie4@29bfe78b #565: global::Orleans.Streams.IPubSubRendezvousGrain:UnregisterConsumer(). Target History is: <S127.0.0.1:22222:260208985:*grn/716E8E94/00000000+DefaultStream_conreign/rooms/natalie4:@29bfe78b>.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Orleans.Streams.StreamConsumer`1.<UnsubscribeAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Conreign.Server.Gameplay.LobbyGrain.<OnDeactivateAsync>d__15.MoveNext() in D:\Personal\Conreign\src\Conreign.Server\Gameplay\LobbyGrain.cs:line 93
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Orleans.Runtime.Catalog.<CallGrainDeactivateAndCleanupStreams>d__88.MoveNext()
[2018-03-31 16:17:39.685 GMT 23 ERROR 103413 PubSubRendezvousGrain-S127.0.0.1:22222:260208985-*grn/716E8E94/0000000000000000000000000000000006000000716e8e94+DefaultStream_conreign/rooms/natalie4-0xF69D9439 ] !!!!!!!!!! Failed to unregister a stream consumer. Stream: conreign/rooms/natalie4-00000000-0000-0000-0000-000000000000-DefaultStream, SubscriptionId 435d4848-2050-4f3a-bfd7-54e6f460a839
Exc level 0: System.TimeoutException: Response did not arrive on time in 00:00:30 for message: IsAlwaysInterleave Request S127.0.0.1:22222:260208985*grn/716E8E94/00000000+DefaultStream_conreign/rooms/natalie4@29bfe78b->S127.0.0.1:22222:260208985*grn/E75B5B5B/00000000+natalie4@71f007aa #574: global::Orleans.Streams.IStreamProducerExtension:RemoveSubscriber(). Target History is: <S127.0.0.1:22222:260208985:*grn/E75B5B5B/00000000+natalie4:@71f007aa>.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Orleans.Streams.PubSubRendezvousGrain.<ExecuteProducerTask>d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Orleans.Streams.PubSubRendezvousGrain.<NotifyProducersOfRemovedSubscription>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Orleans.Streams.PubSubRendezvousGrain.<UnregisterConsumer>d__17.MoveNext()
[2018-03-31 16:17:39.722 GMT 22 INFO 100539 Catalog 10.0.75.1:0] Done FinishDestroyActivations #0 - Destroyed 1 Activations.
[2018-03-31 16:17:39.737 GMT 23 INFO 100540 Catalog 10.0.75.1:0] DeactivateActivationOnIdle: [Activation: S127.0.0.1:22222:260208985*grn/716E8E94/00000000+DefaultStream_conreign/rooms/natalie4@29bfe78b #GrainType=Orleans.Streams.PubSubRendezvousGrain Placement=RandomPlacement State=Deactivating] later when become idle.
[2018-03-31 16:17:39.728 GMT 21 WARNING 103402 SimpleMessageStreamProducer`1 10.0.75.1:0] Ignoring unhandled exception during PubSub.UnregisterProducer
Exc level 0: System.TimeoutException: Response did not arrive on time in 00:00:30 for message: Request S127.0.0.1:22222:260208985*grn/E75B5B5B/00000000+natalie4@71f007aa->S127.0.0.1:22222:260208985*grn/716E8E94/00000000+DefaultStream_conreign/rooms/natalie4@29bfe78b #569: global::Orleans.Streams.IPubSubRendezvousGrain:UnregisterProducer(). Target History is: <S127.0.0.1:22222:260208985:*grn/716E8E94/00000000+DefaultStream_conreign/rooms/natalie4:@29bfe78b>.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Orleans.Providers.Streams.SimpleMessageStream.SimpleMessageStreamProducer`1.<Cleanup>d__28.MoveNext()
Mentioned unsubscribe call can be seen here: https://github.com/smolyakoff/conreign/blob/feature/bots/src/Conreign.Server/Gameplay/LobbyGrain.cs#L93
I use a common helper for stream subscription which does conditional logic based on active subscription handles: https://github.com/smolyakoff/conreign/blob/feature/bots/src/Conreign.Server/Communication/StreamExtensions.cs#L14
Can You provide more details, does it always happen , or it happens in some circumstance ? If the latter, in which circumstance it happens ?
It happens always. Which other details can be helpful?
Here is the minimal code which leads to the same error reliably. I suppose it's due to Orleans concurrency model and deadlock is happening.
using System;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Host;
using Orleans.Streams;
namespace App
{
[Serializable]
public class DeactivationRequested
{
}
public interface INotifierGrain : IGrainWithStringKey
{
Task Start();
}
public class NotifierGrain : Grain, INotifierGrain
{
private StreamSubscriptionHandle<DeactivationRequested> _subscription;
private IAsyncStream<DeactivationRequested> _stream;
public override async Task OnActivateAsync()
{
await base.OnActivateAsync();
_stream = GetStreamProvider("Default").GetStream<DeactivationRequested>(Guid.Empty, "events");
_subscription = await _stream.SubscribeAsync(OnEvent);
}
public override async Task OnDeactivateAsync()
{
Console.WriteLine($"{nameof(NotifierGrain)} deactivating...");
await _subscription.UnsubscribeAsync();
Console.WriteLine($"{nameof(NotifierGrain)} unsubscribed.");
await base.OnDeactivateAsync();
}
public async Task Start()
{
await GrainFactory.GetGrain<IListenerGrain>("notifier").Listen();
await _stream.OnNextAsync(new DeactivationRequested());
Console.WriteLine("Event published.");
DeactivateOnIdle();
}
public Task OnEvent(DeactivationRequested item, StreamSequenceToken token = null)
{
Console.WriteLine($"{nameof(NotifierGrain)} event received.");
return Task.CompletedTask;
}
}
public interface IListenerGrain : IGrainWithStringKey
{
Task Listen();
}
public class ListenerGrain : Grain, IListenerGrain
{
private StreamSubscriptionHandle<DeactivationRequested> _subscription;
public override async Task OnActivateAsync()
{
await base.OnActivateAsync();
var stream = GetStreamProvider("Default").GetStream<DeactivationRequested>(Guid.Empty, "events");
_subscription = await stream.SubscribeAsync(OnEvent);
}
public override async Task OnDeactivateAsync()
{
Console.WriteLine($"{nameof(ListenerGrain)} deactivating...");
await _subscription.UnsubscribeAsync();
Console.WriteLine($"{nameof(ListenerGrain)} unsubscribed.");
await base.OnDeactivateAsync();
}
public Task Listen()
{
return Task.CompletedTask;
}
public Task OnEvent(DeactivationRequested item, StreamSequenceToken token = null)
{
Console.WriteLine($"{nameof(ListenerGrain)} event received.");
DeactivateOnIdle();
return Task.CompletedTask;
}
}
internal class Program
{
internal static void Main(string[] args)
{
Run().Wait();
}
private static async Task Run()
{
var serverConfig = ClusterConfiguration.LocalhostPrimarySilo();
serverConfig.AddSimpleMessageStreamProvider(
"Default",
fireAndForgetDelivery: true,
optimizeForImmutableData: false);
serverConfig.AddMemoryStorageProvider("PubSubStore");
serverConfig.Globals.ResponseTimeout = TimeSpan.FromSeconds(5);
var silo = new SiloHost("local", serverConfig);
silo.InitializeOrleansSilo();
silo.StartOrleansSilo();
var clientConfig = ClientConfiguration.LocalhostSilo();
var client = new ClientBuilder().UseConfiguration(clientConfig).Build();
await client.Connect();
var notifier = client.GetGrain<INotifierGrain>("listener");
await notifier.Start();
Console.WriteLine("Notifier started. Wait few seconds for error to appear.");
Console.ReadLine();
}
}
}
Actually, even more minimalistic sample reproduces the same behaviour.
using System;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Host;
using Orleans.Streams;
namespace App
{
[Serializable]
public class DeactivationRequested
{
}
public interface INotifierGrain : IGrainWithStringKey
{
Task Start();
}
public class NotifierGrain : Grain, INotifierGrain
{
private StreamSubscriptionHandle<DeactivationRequested> _subscription;
private IAsyncStream<DeactivationRequested> _stream;
public override async Task OnActivateAsync()
{
await base.OnActivateAsync();
_stream = GetStreamProvider("Default").GetStream<DeactivationRequested>(Guid.Empty, "events");
_subscription = await _stream.SubscribeAsync(OnEvent);
}
public override async Task OnDeactivateAsync()
{
Console.WriteLine($"{nameof(NotifierGrain)} deactivating...");
await _subscription.UnsubscribeAsync();
Console.WriteLine($"{nameof(NotifierGrain)} unsubscribed.");
await base.OnDeactivateAsync();
}
public async Task Start()
{
await _stream.OnNextAsync(new DeactivationRequested());
Console.WriteLine("Event published.");
DeactivateOnIdle();
}
public Task OnEvent(DeactivationRequested item, StreamSequenceToken token = null)
{
Console.WriteLine($"{nameof(NotifierGrain)} event received.");
return Task.CompletedTask;
}
}
internal class Program
{
internal static void Main(string[] args)
{
Run().Wait();
}
private static async Task Run()
{
var serverConfig = ClusterConfiguration.LocalhostPrimarySilo();
serverConfig.AddSimpleMessageStreamProvider(
"Default",
fireAndForgetDelivery: true,
optimizeForImmutableData: false);
serverConfig.AddMemoryStorageProvider("PubSubStore");
serverConfig.Globals.ResponseTimeout = TimeSpan.FromSeconds(5);
var silo = new SiloHost("local", serverConfig);
silo.InitializeOrleansSilo();
silo.StartOrleansSilo();
var clientConfig = ClientConfiguration.LocalhostSilo();
var client = new ClientBuilder().UseConfiguration(clientConfig).Build();
await client.Connect();
var notifier = client.GetGrain<INotifierGrain>("notifier");
await notifier.Start();
Console.WriteLine("Notifier started. Wait few seconds for error to appear.");
Console.ReadLine();
}
}
}
Thanks for the repro. I will donwload it and see where is the problem
I think there's a race condition between consumer trying to unsubscribe, while producer grain is in the middle of deactivating, so the unsubscribe call timed out. The call chain for unsubscribe is, consumer ->calls pubsub grain to unsubscribe , pubsub grain -> notify producers to remove this subscriber. But since producer grain is deactivating roughly at the same time, it may be in a state that it isn't deactivated yet, so the runtime won't spin up a new activation to process the remove-this-subscriber call, but it isn't in a good state to receive calls either. The logs confirmed my theory for me. In the logs, The unsubscribe call happens after producer started deactivating, but before it finished deactivating. Does this make sense?
Why do you want to deactivate your producer immediately after sending the first messge? the same with the consumer. Is it just for reproducing this bug?
Why do you want to deactivate your producer immediately after sending the first messge? the same with the consumer. Is it just for reproducing this bug?
What is not prohibited by the API, that is allowed :smile: As you can see from the last sample (not in the zip, just posted as code example), even one grain is enough to cause a deadlock. You can take an analogy with IDisposable. If you create some managed resource in your own code, you are responsible for freeing it out in Dispose(). The code in the sample does exactly this. It frees stream subscription handle on deactivation. Additionally, nothing prevents you from publishing messages on the same or another stream and then requesting deactivation.
Of course, in a real project it's much harder to understand why deadlock happens. Your explanation is helpful for sure, but developer experience is not perfect in this case as the application literally hangs. In my case there is GameEnded event published and then publisher GameGrain requests deactivation. Some other grains (BotGrain, LobbyGrain) may listen to the same stream and also request deactivation in a handler method.
What is not prohibited by the API, that is allowed
Yes, that is true, ideally. But our API is far from ideal. Streaming and Orleans are very complex system, it is hard to get it to the ideal state at once. But user feedback will help us get there. Our streaming API is still evolving. So thanks for the feedback. We will take it into account when trying to improve streaming API.
But for your case, which is trying to build an app using current Orleans streaming API, calling DeactivateOnIdle is almost always a anti-pattern for Orleans. I suggest change the design to avoid using it. Can you make GrameGrain unsubscribe, instead of deactivating, when receiving GameEnded event?
Also I think for orleans grain activation, whose lifecycle is managed by orleans runtime, analogy it with IDisposable is not right. Conceptually, grains are virtual, they are always there, application developers just need to make certain calls to it to make it do a task. Application developer shouldn't need to interfere with its specific activation lifecycle, since that is managed by Orleans runtime. A closer analogy of grains will be c# garbage collection. Just like you don't manually clean every variables you created in c#, you don't need to manually clean every grain activation, The runtime will clean that for you. Please refer to our docs see the difference between grain and its activation. DeactivateOnIdle are there to cover corner cases, if you don't have to use, don't use it.
Thanks for the tips. This is just a hobby project, so changing the design is certainly a way to go. Is there anything actionable for this issue? Maybe some documentation updates to mention edge cases are needed? If not, you may close the issue.
Glad it helped.
Yeah I will add some updates to docs explain how pubsub grain , (un)subscribe works. I will tag this as docs.