runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Possible CancellationTokenRegistration leak in AsyncOperation<T>

Open invidious9000 opened this issue 6 years ago • 26 comments

Under profiling it appears as if BoundedChannel may leak cancellation callbacks when used in this manner:

var channel = Channel.CreateBounded<bool>(1);
while (true)
{
    using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
    try
    {
        await channel.Reader.ReadAsync(cts.Token);
    }
    catch (OperationCanceledException)
    {
    }
}

Firstly, is this an intended use case? We have a long-running Channel that multiple readers may attempt to read from (these readers may timeout and cancel their CancellationToken as they disconnect, the 100ms timeout with CTS is to simulate this faster).

If this is an intended use case it looks like _registration in AsyncOperation ctor is not disposed when cancellation path is taken? I see that TrySetResult() and TrySetException() both call UnregisterCancellation() but not TrySetCanceled(), though I am unsure if my understanding of this is correct.

In addition to this (or perhaps as a result of it) it seems like OperationCanceledExceptions are accumulated via ExceptionDispatchInfo and a reference back to Deque.

image

invidious9000 avatar Dec 11 '19 08:12 invidious9000

Thanks. Are you actually observing the effects of a leak, i.e. memory grows unbounded, or is this based on code review only?

stephentoub avatar Dec 11 '19 13:12 stephentoub

Ah, I took a look at your repro and understand now why you're seeing what you're seeing.

It's not actually about unregistering from the CancellationToken. We don't need to unregister when cancellation occurs because unregistering at that point would be a nop: cancellation already occurred, effectively automatically unregistering everything at that point.

The issue you're seeing is by-design in the bounded channel, though we might be able to improve things... you can see reference to it in the comment here, and it's why this is a loop: https://github.com/dotnet/runtime/blob/5d4304e04d6a8b0ff34d4f4ef9c97b8d483f3bb8/src/libraries/System.Threading.Channels/src/System/Threading/Channels/BoundedChannel.cs#L339-L342 The bounded channel maintains a collection of the AsyncOperation instances that have been created, and when one of them is canceled, it marks the instance as such but doesn't actually remove it from the collection (for performance / simplicity). In this case, you're creating AsyncOperations for reads; when a write then comes along and can satisfy a read, it'll pull the next item from the collection to complete it, but if it sees at that point it's already been canceled, it'll just discard it and get the next one.

In other words, in your repro, I expect you'll find that the moment you write to the bounded channel, you'll see all of those objects become unrooted and become available to the GC, because the write will end up pulling out all of the canceled objects from the queue.

So, while this behavior is by-design, it's possible we could improve things further here.

stephentoub avatar Dec 11 '19 14:12 stephentoub

Thank you for looking at this so quickly. This came about as a result of profiling an actual application vs code review. We have also observed that if the Channel is permitted to fall out of scope or once a write occurs and queued waiters are drained then these objects are eligible for GC.

Is there any way to mitigate this behavior with a long-running Channel where there may be many reader cancellations before the next write? Perhaps something like a poison pill to drain waiters?

invidious9000 avatar Dec 11 '19 17:12 invidious9000

.... As a side question, why do you have so many cancelled readers between writes?

Clockwork-Muse avatar Dec 11 '19 19:12 Clockwork-Muse

@Clockwork-Muse We're using a Channel to aggregate writes against a transport stream (gRPC) that experiences frequent transient network issues.

The transport stream itself throws when writing from more than one thread so we have a long-running Channel that aggregates response writes for a single reader that is "attached" when transport connects. When transport connects a Task runs and attempts to ReadAsync() from the Channel and drain responses and the issue emerges when the transport connection dies (cancels) before any response writes are performed.

We're a bit uncertain if this is an acceptable use case but it seems to work well under normal conditions, it's only during long periods of transient reconnects where the cancelled-waiter nuance becomes an issue.

invidious9000 avatar Dec 11 '19 20:12 invidious9000

Is there any way to mitigate this behavior with a long-running Channel where there may be many reader cancellations before the next write?

With the shipped bits, I can't think of any, other than doing a write.

We / I didn't think this would be an issue, so we explicitly don't make any effort to remove AsyncOperations from the deques when they're canceled, and just let them get purged naturally.

The right fix for the next release is probably to make these into doubly-linked lists, and change how cancellation callbacks are handled to also remove the nodes from the relevant list.

stephentoub avatar Dec 12 '19 21:12 stephentoub

I have just written-up another issue (which I shall now not file), which turns out to be exactly this problem. This was based on analysing a memory dump of a real, leaking, production application which had leaked about 70000 of each of the 6-or-so objects which gets leaked for every cancellation (the relationship between the objects is complex, but it's 10s of MB leaked)

As it stands, it's clear that the BoundedChannel is not very suitable for the kind of application where there are many many timeouts for each use of the queue - clearly there are several work-arounds we could adopt (push some kind of 'null object' through the queue every so often, for example), but it's a bit sad because we had high hopes for Channel to cleanly replace a previous very complex (but working) TCS+CTS arrangement which, ironically, had taken some effort to get the leaks out of. If we have to build an additional time-based system to flush the queue somehow the cleanliness is marred.

I accept that this design decision was deliberate, but it looks very like a bug when one stumbles over it in a memory dump. Can I put in a +1 for future improvement here, please?

willdean avatar Mar 21 '20 23:03 willdean

I'm randomly losing items while using a BoundedChannel (with FullMode=Wait). I most likely tracked it down to cancellation happening during channel.Reader.ReadAsync(token) -- and the very same code is running happily for days and weeks when using an UnboundedChannel instead.

Is this known/expected behavior?

springy76 avatar Jun 08 '20 10:06 springy76

Is this known/expected behavior?

Without a repro, it's hard to say. Doesn't sound related to the issue you commented on, though.

stephentoub avatar Jun 08 '20 10:06 stephentoub

@stephentoub I'll create a new issue for that, this issue just looked most related (Reader.ReadAsync + CancellationToken) at first place.

My repro script currently is a LINQPad script: Would you accept this or do you need a console app (which would take some time rewriting all the nice and easy LINQPad.Dump()'s)?

springy76 avatar Jun 08 '20 11:06 springy76

Would you accept this or do you need a console app (which would take some time rewriting all the nice and easy LINQPad.Dump()'s)?

A console app would be helpful, thanks!

stephentoub avatar Jun 08 '20 11:06 stephentoub

@stephentoub done: https://github.com/dotnet/runtime/issues/37671

springy76 avatar Jun 09 '20 20:06 springy76

I had a similar issue. My scenario is:

  • I want to wait at most x millis to get as much as items as I can
  • I have a main token (application's token)
  • I create a timeout token to wait at most x seconds

I had the same "leak" issue and resolved by:

  • First read uses main token (If I have no items to handle, just wait until one arrives)
  • All the remaining items must be read in x milliseconds This way I will never get an empty read due to timeout cancellation token (ok, maybe one empty read when application is being shutdown) and I get correct behaviour when items arrives from channel's writer.

tkrafael avatar Mar 16 '21 19:03 tkrafael

This issue is due to

var reader = new AsyncOperation<T>(parent._runContinuationsAsynchronously | cancellationToken.CanBeCanceled, cancellationToken);
parent._blockedReaders.EnqueueTail(reader);
return reader.ValueTaskOfT;

and really bothers me. I have to regularly write dummy message to this channel to recycle the readers.

hooyao avatar May 18 '21 07:05 hooyao

I have also observed a bizarre behavior, not sure if I'm misunderstanding anything here. So when a channel contains these cancelled AsyncOperation, setting it to null or making it go out-of-scope doesn't seem to free up memory. Below is the test program.

class Program
    {
        static void Main(string[] args)
        {
            var cts = new CancellationTokenSource();

            var task1 = RunLoop(cts.Token);
            Console.WriteLine("Loop started, Press Enter to stop loop");
            Console.ReadLine();

            cts.Cancel();
            task1.Wait();
            task1 = null;
            GC.Collect();

            Console.WriteLine("Press Enter to exit");
            Console.ReadLine();
        }

        static async Task RunLoop(CancellationToken stopToken)
        {
            var channel = Channel.CreateBounded<bool>(1);
            while (!stopToken.IsCancellationRequested)
            {
                using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(10));
                try
                {
                    await channel.Reader.ReadAsync(cts.Token);
                }
                catch (OperationCanceledException)
                {
                }
            }
        }
    }

Steps: start the program, watch memory usage in Task Manager. The program starts at ~5MB, and after about 5 minutes it goes up to ~29MB (which is expected due to all the queued up AsyncOperation, examining GC dump confirmed this).
However when I stop the loop (which makes the channel go out of scope and hence GC-collected), the process memory usage does NOT reduce (as we should expect it to), but instead stays at ~29MB.

I collected GC dump after the loop has been stopped and it seems like all the AsyncOperation has been GC-collected.
However the process memory usage remains high.

GC dump while loop is running image

GC dump after loop is stopped image

dhhoang avatar Jul 29 '21 19:07 dhhoang

I have also recently encountered this issue for low-volume channels.

https://github.com/couchbase/couchbase-net-client/blob/3.2.3/src/Couchbase/Core/Diagnostics/Tracing/OrphanResponseReporting/OrphanReporter.cs#L106

I certainly understand the logic involved in not clearing the linked list of AsyncOperation<T> when a wait is canceled, for most use cases this would go unnoticed and it would add a lot of complexity. However, there are some simple improvements that could help the quality of life for everyone.

  1. When the token is canceled, setting _registration = default within AsyncOperation<T>.TrySetCanceled would at least reduce the size of the memory leak. It would allow GC to collect the CancellationTokenSource, CallbackNode, etc.
  2. Some similar cleanup of the ExceptionDispatchInfo and continuation delegate after the continuation delegate completes could help further.
  3. Some documentation that this isn't an intended/supported use case for Channels may help reduce headaches. The API surface itself makes it appear that WaitToReadAsync(CancellationToken) is safe and easy to use.

brantburnett avatar Nov 04 '21 03:11 brantburnett

Are there any plans about documenting the current behavior of the ChannelReader<T>.ReadAsync method? It's quite likely that some developers will assume that awaiting and canceling the ReadAsync repeatedly in a loop is a safe operation. Apparently this is not the case, and this usage pattern is not supported. It seems that the cancellation functionality is intended to be used only a few times during the life-time of this component.

If there is any interest at documenting the current behavior, I am willing to contribute. I would suggest to add something like this in the docs, with a blue background color:

Important

Canceling ReadAsync operations repeatedly in a loop, using a timer-based CancellationTokenSource, is not a supported usage pattern for this API. Doing so might result in non-trivial increase in the memory used by the associated Channel<T>.

A similar warning could be added in the docs of the ChannelWriter<T>.WriteAsync method too, because according to my experiments it has a similar behavior.

theodorzoulias avatar May 19 '22 11:05 theodorzoulias

Are there any plans about documenting the current behavior of the ChannelReader.ReadAsync?

That would mean guaranteeing this behavior. We're not going to do that if we might change it. It's an implementation detail, and this issue is still open.

It seems that the cancellation functionality is intended to be used only a few times during the life-time of this component.

No. It's fine to cancel a lot. The implementation just assumes that you'll also be consuming data from the channel, as the moment a canceled item gets to the front it'll be discarded, and all canceled items at the head of the queue will be purged.

stephentoub avatar May 19 '22 11:05 stephentoub

@stephentoub

No. It's fine to cancel a lot. The implementation just assumes that you'll also be consuming data from the channel, as the moment a canceled item gets to the front it'll be discarded, and all canceled items at the head of the queue will be purged.

See this use case: https://github.com/dotnet/runtime/issues/761#issuecomment-800558836 Maybe ChannelReader needs a healing mechanism to dispose those cancelled tokens independent of new items arriving.

tkrafael avatar May 19 '22 16:05 tkrafael

@tkrafael that's a clever technique. It solves the problem of reading a Channel<T> in batches, enforcing a maximum latency between consuming an item from the channel and processing a batch, and without triggering the memory leak issue. But it doesn't help at handling a different scenario, where you just want to wake up every X seconds and do periodically something unrelated to the channel, like emitting a heartbeat signal to indicate that your service is still alive. If the channel's producer has become idle for a prolonged duration, and the consumer wakes up frequently with a timer-based CancellationTokenSource in order to emit heartbeats, you'll get a memory leak.

I've heard of one dev who implemented a healing mechanism manually like this:

I actually came out a nasty solution, sending a dummy message to the channel when timeout cancel, it has minimal impact.

I guess that they filtered out these dummy messages when they consumed them later. It sounds like an effective solution that is easy to implement.

That would mean guaranteeing this behavior. We're not going to do that if we might change it. It's an implementation detail, and this issue is still open.

@stephentoub deciding about whether the implementation should be changed or should stay as is, might take a long time though. Let's say that the final decision is that the current implementation is best for the majority of scenarios, would it be OK to document the behavior then?

theodorzoulias avatar May 19 '22 23:05 theodorzoulias