Repository navigation
Description
Continuing the theme #844 at the request of @gabikliot, I give feedback.
For starters, I would like to say I could be wrong in my statements because I may not know some of the nuances in the script and the principles of implementation or maybe I do not fully understand the work scenario.
Scenario example: lets says you subscribed at offset X, then produced event with sequence X, X was delivered to consumer, now it maybe be deleted from the cache, now you subscribe again to X from a different consumer, then you will get cache miss exception, rightfully, for the 2nd subscription.
Overall I completely agree with this scenario, but there are a number of issues.
During testing I noticed that if you receive an error QueueCacheMissException I lose data flow (queue), based on the described scenario it is logical, because there is a false consumer that does not process messages, and all messages go nowhere
But is it right? How can I recover this data? Why not leave in the stream and in the queue until the consumer who will be able to handle them? As the message can be considered processed if it has not been processed?
About the subscription:
Of course one the consumer needs to sign only once.
But I faced a problem, what if multiple consumers subscribed to the stream, or rather how to understand what the current consumer I don't have a subscription again?
While I always work with only one consumer because to me it is important to follow FIFO
So I want to show my subscription option with one consumer within the solution of the problem which I described #844
Would welcome comments on the code and the answer to the question how to track the subscription of current consumer if you know what subscriptionHandles.Count > 1 ?
Consumer
public async override Task OnActivateAsync()
{
var streamProvider = GetStreamProvider(PROVIDER_NAME);
_stream = streamProvider.GetStream<string>(Guid.Parse(GUID_STREAM), this.GetPrimaryKeyString());
var subscriptionHandles = await _stream.GetAllSubscriptionHandles();
if (!subscriptionHandles.IsNullOrEmpty())
subscriptionHandles.ForEach(async x => await x.ResumeAsync(OnNextAsync));
}
public async Task SubscribeAsync()
{
var subscriptionHandles = await _stream.GetAllSubscriptionHandles();
if (subscriptionHandles.IsNullOrEmpty())
await _stream.SubscribeAsync(OnNextAsync);
}Producer
private async Task<IAsyncStream<string>> GetStream(string consumerName)
{
var streamConsumerGrain = GrainFactory.GetGrain<IConsumerGrain>(consumerName);
await streamConsumerGrain.SubscribeAsync();
var streamProvider = GetStreamProvider(PROVIDER_NAME);
return streamProvider.GetStream<string>(Guid.Parse(GUID_STREAM), consumerName);
}
Activity
gabikliot commentedon Sep 28, 2015
you are missing
awaitinsubscriptionHandles.ForEach(x => x.ResumeAsync(OnNextAsync));Merroy commentedon Sep 28, 2015
of course, I forgot to copy, corrected
jason-bragg commentedon Oct 1, 2015
"if you receive an error QueueCacheMissException I lose data flow"
This was a bug which was also addressed in #849, though I admit we should have more testing around this to verify that. The intended behavior is as follows:
t.tis in cache, start delivering events fromt.tis newer than items in cache, no data is sent untiltis added to the cache, then deliver fromt.tis older than the items in the cache, send the consumer will get a cache miss exception on theOnErrorAsynccall, then continue delivering from the most recent data in the cache.This means if the consumer does nothing with the
OnErrornotification of the cache miss, the consumer may loose data, but the consumer has the opportunity to decide what to do: Unsubscribe? Re-subscribe at the next interesting token? Just continue processing?Merroy commentedon Oct 5, 2015
Do I understand correctly that I can't subscribe again? I definitely need to re-subscribe (ResumeAsync)?
If Yes, then how can I among all subscribers (.GetAllSubscriptionHandles()) select (current) to re-subscribe it (ResumeAsync)?
jason-bragg commentedon Oct 5, 2015
"Do I understand correctly that I can't subscribe again?"
Subscribing again will create a new subscription. This is probably not the behavior you want.
"I definitely need to re-subscribe (ResumeAsync)?"
It's not clear to me if you mean resume after grain deactivation, or after a cache miss exception. I'll assume you mean after cache miss.
To be clear, you "shouldn't" need to re-subscribe (resume) just because a cache miss occurs. You "can" but should not have to. If you don't re-subscribe on the error, you will miss all of the events from the point in the stream the consumer was at, to the most recent data. If you do re-subscribe, you may avoid losing some data, but you'll need to know where to resume from, which can be non-trivial.
It sound like you may also be struggling with matching an onError call to the subscription handle that you would use for any unsubscribe call. For this I would suggest writing your own implementation of IAsyncObserver that contains subscription details and subscription state. The SubscribeAsync extension functions you are using are utilities to handle simple cases. They are not likely to be sufficient to handle more complex scenarios, such as multiple subscriptions. They 'can' be used for this if you really want to avoid implementing your own observers though by doing something like this.
subscriptionHandles.ForEach(async x => await x.ResumeAsync(OnNextAsync, ex => OnErrorAsync(x,ex)));private Task OnErrorAsync(StreamSubscriptionHandle handle, Exception ex)
{
...
}
This provides the error handler the subscription handle the error came from.
Merroy commentedon Oct 5, 2015
"It's not clear to me if you mean resume after grain deactivation, or after a cache miss exception. I'll assume you mean after cache miss."
I meant both options
jason-bragg commentedon Oct 6, 2015
As I touched on in my previous post. If there is some sort of state associated with a subscription (aggregates, routes, ..?) you'll need to persist this state associated with the subscription to re-associate it when rehydrating the grain and resuming the subscription. Serializable implementations of IAsyncObservable would be the method I'd suggest, but there are other options.
When storing stream state, I'd avoid serializing the IAsyncStream or the subscription handle, even though they are both serializable and intended to be used that way. The reason I discourage this is that these objects are still in flux and we don't have backwards compatibility built in yet. Instead, I'd suggest storing the stream guid and namespace, then matching those with the related data in the handle to associate the correct handle during grain activation.
When it comes to passing a sequence token to a resume, at grain activation or on cache miss, I would also avoid this if you can. The issue here is that there are two types of PersistenStreamProviders.
From the above description of persistent stream providers, what you've been building more resembles a non-rewindable stream provider. These stream providers allow for producers to place data in the queue and for processers to process it, but do not have a strong recoverability story. Applications using this type of stream provider tend to focus on fast best effort stream processing, identifying when data loss occurs to successfully processing the data that is not lost.
Some things that would be helpful for us to understand when advising:
How important is the data you're processing? Mission critical, or is some data loss acceptable?
How important is it that these data be processed in real time? On failures can backend, recovery batch process be used for eventual consistency or is the data of no value if it's not served in real time?
Merroy commentedon Oct 6, 2015
data is important, loss is not acceptable (better way one pack will be processed again than get lost completely)
I have a tree structure from multiple streams. the first three levels I important processing in real time, all subsequent I admit or a long data processing or deferred (but to keep all data for me in the first place).
there is one exception:
throughout the tree there is one branch which needs to be served in real time, but data integrity after the third level I priority (I can assure you that data processing it will be fast)
can draw a diagram if this scenario is not the end understandable
Merroy commentedon Oct 6, 2015
Why not initially considered an option of saving the key grain of the consumer as subscription handle?
"Instead, I'd suggest storing the stream guid and namespace, then matching those with the related data in the handle to associate the correct handle during grain activation."
Do I understand correctly that you propose to do cosumer state and to store basic information about the stream to which it relates, including subscription handle?
jason-bragg commentedon Oct 6, 2015
"Do I understand correctly that you propose to do cosumer state and to store basic information about the stream to which it relates, including subscription handle?"
Yes, but I don't advise actually persisting the subscription handle. Instead, persist the guid and namespace, and get the actual handle from GetAllSubscriptionHandles. This is because serializing the handle will likely cause issues if/when we change the subscription handle. The persistent stream provider (and its subscription handles) is still very much in flux.
Merroy commentedon Oct 6, 2015
I got confused a little. Let's consider the following scenario:
I have a stream and two grain of consumer who have subscribed (C1 and C2, with keys guid1 and guid2, respectively).
therefore GetAllSubscriptionHandles().Count == 2 and we know what belongs HandleId1 C1 and C2 HandleId2
now I restart silo
C1 is activated, but it is not subscribed on the stream, but I know that GetAllSubscriptionHandles().Count == 2, but I don't know what HandleId belongs (belonged) to C1, so I don't know to what Handle I need to call ResumeAsync in the current consumer C1
jason-bragg commentedon Oct 6, 2015
Thanks for the scenario.
I was under the impression you were talking about multiple consumers in a single grain, so I think clarifying the scenario will help.
I'll restate what I think you're saying:
-two stream consumer grains C1, C2.
-one stream S1
-C1 is subscribed to S1 using handle H1.
-C2 is subscribed to S1 using handle H2.
-restart
-How does C1 know which handle to resume?
-How does C2 know which handle to resume?
Is the above correct?
"therefore GetAllSubscriptionHandles().Count == 2"
This should not be the case. GetAllSubscriptionHandles called on an IAsyncStream from a grain should only return the subscriptions that grain has on that stream.
So when C1 calls S1.GetAllSubscriptionHandles() it should only find H1.
When C2 calls S1.GetAllSubscriptionHandles() it should only find H2.
To verify this you can log the handles during the subscribe/GetAllSubscriptionHandles/resume calls. The handle's ToString has been overridden to aid in this kind of debugging.
If there are multiple handles, the this means the grain must have, at some point, subscribed multiple times. In this case, you can resume any of the previous handles, and should unsubscribe from the rest.
If this is not the behavior you are seeing, then please let me know.
Merroy commentedon Oct 6, 2015
Yes that's right, you understood correctly my scenario, and all correctly explained and described, I am convinced of this in practice
I immediately raises a number of "provocative questions" :)
1)is it correct that the same consumer can subscribe to a stream multiple times and appropriately handle several times the same message? (if I remember correctly, in this scenario, the error occurred the second subscription (before the fix))
2)is it correct that two different consumer can process one and the same "message"?
2.1)how to implement scenario when the first consumer will get the first message from the stream, and the second will take next?
3)how the consumer may inquire about other consumer the same steam?
4) can a single consumer to be subscribed to 2 different stream? (came to mind when I wrote these questions :))
jason-bragg commentedon Oct 6, 2015
I'm going to assume, as before, when you say consumer you are referring to a consumer grain.
Yes. However, this will come at the cost of the stream infrastructure actually delivering the event to each subscription the consumer creates. That is, each subscription is independent, so the stream infrastructure will send each event on a stream to every subscription. Since grains are usually not reentrant, this can lead to timeouts if there are large numbers of subscriptions or long event processing time. Rather than doing this, it would be more efficient to have one subscription per consumer and perform all the related processing on the events from the single subscription.
Each event (message) is delivered per subscription, not per consumer.
For instance.
Consumers C1, C2.
Stream S1.
Consumer C1 subscribes to S1 twice, H11, and H12.
Consumer C2 subscribes to S1 once on H2.
An event E is produced on S1.
E is sent to C1 on H11
E is sent to C1 on H12
E is sent to C2 on H2.
2.1) No native support for this. One possible solution is to write a consumer grain that 'dispatches' work to other grains in a round-robin fashion.
No native support for this. If consumers need to know about each other, you'll need to create some sort of consumer registry.
The pubsub system knows about subscribers, but it does not expose this data natively, nor does the stream infrastructure allow one to provide one's own pubsub system. If this is an extensibility point you need for this capability, it is probably significant enough for it's own issue.
Yes. A consumer grain can subscribe to multiple streams, the same stream multiple times, and even the same handler (onNext) can be used with multiple subscriptions. In general it's better to think of stream delivery in terms of subscriptions rather than consumer grains. We often mix this terminology because a single subscription per grain is the most common (and tested) usage pattern.
35 remaining items
alan-geller commentedon Oct 14, 2015
@Merroy @jason-bragg I used to own the Amazon SQS service, and spent a lot of time looking into guaranteeing exactly-once delivery. The short answer is that it requires a unicorn (more precisely, a perfect distributed consensus algorithm that works in the face of arbitrary Byzantine failures). This is particularly true in a system like Orleans where a component on a failed node will be automatically recreated.
Idempotency is generally the best approach, but it does require that all instances of the receiver agree on whether or not a specific message has been processed. Even if there's never more than one receiver active at a time, this is hard because it requires persisting a unique message ID as part of processing the message -- and doing it transactionally along with any other outputs of the message processing.
All you can really do is reduce the likelihood of duplicate delivery. Since you can't be perfect, this then becomes a question of trade-offs: generally, the more work the platform does to minimize duplicates, the higher the performance impact. If your application just can't handle duplicates, then you need to code for duplicate delivery regardless of what the platform is doing for you, so it's a question of perf cost in the platform versus perf cost in the application. If your application can handle a low likelihood of duplicates, then it's good if the platform can meet your threshold because then the application code doesn't have to deal with it at all.
One nice thing about the Orleans model is that you could build different providers that have different likelihoods of duplicate delivery, with different costs, and let the application developer pick the appropriate one for each message stream.
jason-bragg commentedon Oct 16, 2015
@alan-geller +1
So when I said it was 'non-trivial', yeah, umm. I was understating the point :)
"One nice thing about the Orleans model is that you could build different providers that have different likelihoods of duplicate delivery."
This is very true, though developing a stream provider from scratch can be daunting. The IQueueAdapterFactory pattern used by the PersistentStreamProvider was intended to help mitigate this. Unfortunately, the event delivery logic is not yet customizable through the adapter pattern.
"Since you can't be perfect, this then becomes a question of trade-offs"
Regarding the limiting of duplicates, one approach would be to make your custom version of the azure queue receiver not delete the message in the MessagesDeliveredAsync, but instead generated IAsyncDisposable events that deleted themselves from the queue upon being disposed. Once the OnNextAsync completed processing the event, it could dispose of it. This would allow the application control of the queue cleanup, rather than relying on the streaming infrastructure. This would be best implemented with consumer grains that were locally placed (located on the same silo as the queue they came from).
gabikliot commentedon Oct 16, 2015
The last suggestion means you are breaking location transparency, a big no no in Orleans world (this is a comment only on Jason last suggestion about async disposable and local grains, not about Alan's point).
Merroy commentedon Oct 17, 2015
@jason-bragg you are right, option 1
I studied the code, and if I'm not mistaken,the change needs to be made in PersistentStreamPullingAgent (major changes in RunConsumerCursor) and/or add a new agent.
PS in the course of examining the code, I had the idea to extend the functionality, namely to add a subscription to the consumer on OnNextBatchAsync
One can consider to integrate in the subscription of the consumer to ObserverSubscriptionManager (), i.e. to realize the quick transfer of the responsibility for the message stream (the consumer), for example in state grain, without waiting
although the existing functionality already allows you to implement this script, if I'm not mistaken
jason-bragg commentedon Oct 19, 2015
"to be made in PersistentStreamPullingAgent (major changes in RunConsumerCursor) and/or add a new agent."
My previous (brief) investigation into this left me with the impression that PersistentStreamPullingAgent performs three different behaviors.
A) Queue processor - It is managed by the PersistentStreamPullingManager and IStreamQueueBalancer to determine what queue it processes, and starts/stops processing of that queue.
B) Stream Producer - It inherits from IStreamProducerExtension and interacts with the stream pub/sub system (IStreamPubSub) to publish streams.
C) Event dispatcher - it reads from the queue and dispatches events to consumers (IStreamProducerExtension).
The behavior you seem to want to modify is C.
If you want to keep the same queue management infrastructure but swap out behaviors, you'll likely also need to address A.
If you're addressing A, and C, B will almost automatically be isolated as well.
What are your thoughts on the following:
jason-bragg commentedon Oct 19, 2015
Note that 3.b from previous post not only allows you to add the delivery behavior you want, but allows anyone using Orleans streams to introduce their own custom stream delivery logic without needing to change Orleans.
3.a, and any similar change, requires changes to Orleans because the pubsub system and related interfaces are all internal. By separating the stream publishing and event delivery, we can allow customization of the delivery logic without updates to Orleans.