Skip to content

Creating linked cancellation tokens hides which token triggered cancellation  #22172

Closed

Description

@davidfowl

In the following scenario, I would expect the code to print true instead of false. The problem is that once you have a linked cancellation token, it will always be the reported token in any OperationCanceledException instead of the actual token that fired.

using System;
using System.Threading;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            var cts1 = new CancellationTokenSource();
            var cts2 = new CancellationTokenSource();
            var cts3 = new CancellationTokenSource();

            try
            {
                cts1.Cancel();

                CancellationTokenSource.CreateLinkedTokenSource(cts1.Token, cts2.Token, cts3.Token).Token.ThrowIfCancellationRequested();
            }
            catch (OperationCanceledException ex)
            {
                Console.WriteLine(cts1.Token == ex.CancellationToken);
            }
        }
    }
}

I know it's a breaking change but it's super annoying. The work around is to check each of the tokens manually in the catch (which isn't even correct since it may have been triggered elsewhere).

/cc @stephentoub

Activity

  1. stephentoub commented on Jun 7, 2017

    @stephentoub
    Member

    It's not just a breaking change, it doesn't make sense to me. You have a CancellationToken, and you call ThrowIfCancellationRequested on it. If it's canceled, why would the OperationCanceledException that's thrown not contain that CancellationToken but instead contain another? CreateLinkedTokenSource isn't magic; it's really just doing the work of creating a new CancellationTokenSource and registering with each of the input tokens to propagate the cancellation request / signal to the new uber CancellationTokenSource. Its CancellationToken is a real CancellationToken, tied to a real CancellationTokenSource.

    In other words, I'd expect this to be true:

    using System;
    using System.Threading;
    
    namespace ConsoleApp2
    {
        class Program
        {
            static void Main(string[] args)
            {
                var cts1 = new CancellationTokenSource();
                var cts2 = new CancellationTokenSource();
                var cts3 = new CancellationTokenSource();
    
                CancellationTokenSource linked = null;
                try
                {
                    cts1.Cancel();
    
                    linked = CancellationTokenSource.CreateLinkedTokenSource(cts1.Token, cts2.Token, cts3.Token);
                    linked.Token.ThrowIfCancellationRequested();
                }
                catch (OperationCanceledException ex)
                {
                    Console.WriteLine(linked.Token == ex.CancellationToken);
                }
            }
        }
    }

    (which it is).

    Note, too, that the CancellationToken that's passed in to some API might actually have been from a linked token source. If you called ThrowIfCancellationRequested on that, you'd expect the OperationCanceledException that emerges to contain that CancellationToken (or, at least, I would, otherwise things break down).

  2. davidfowl commented on Jun 7, 2017

    @davidfowl
    MemberAuthor

    It may not be magic but it's the only way to use it an it's really hard to achieve the scenario I want to achieve which IMO should be the default. It's no different to Task.WhenAny. At a high level, I'm calling a thing that takes a token and I have several tokens, I want to pass a combined token and I want to know which one triggered.

  3. stephentoub commented on Jun 7, 2017

    @stephentoub
    Member

    It's no different to Task.WhenAny

    "no different" from Task.WhenAny would be an API like:

    public Task<CancellationToken> WhenAny(params CancellationToken[] cancellationTokens);

    I'm unclear what you're actually asking for. Is it an API like the above? Or just a helper you can call after the fact like:

    public bool AnyCancellationRequest(CancellationToken[] cancellationTokens, out CancellationToken cancellationRequestedToken);

    ?

    I disagree that the current semantics are wrong; it really depends what you're trying to do with it, but the semantics as they are make sense in a variety of scenarios and are self-consistent. It may be that those semantics don't meet the needs of what you're trying to do, so let's better understand that and try to find a good solution. Actually changing ThrowIfCancellationRequested to produce an OperationCanceledException that contained one of those input tokens would not only be a fairly substantial breaking change, I don't even know how it would be implemented without overhauling CancellationToken/CancellationTokenSource or adding non-trivial overheads to existing functionality, e.g. making CancellationToken and ThrowIfCancellationRequested virtual and probably some others.

  4. davidfowl commented on Jun 7, 2017

    @davidfowl
    MemberAuthor

    I'm unclear what you're actually asking for.

    I thought the code sample was pretty clear. Let me tweak it a bit:

    using System;
    using System.Threading;
    
    namespace ConsoleApp2
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var cts1 = new CancellationTokenSource();
                var cts2 = new CancellationTokenSource();
                var cts3 = new CancellationTokenSource();
    
                try
                {
                   
                    cts1.Cancel();
    
                    var linkedToken = MagicSauce.CreateCombinedToken(cts1.Token, cts2.Token, cts3.Token);
                    await DoSomething(linked);
                }
                catch (OperationCanceledException ex)
                {
                    Console.WriteLine(cts1.Token == ex.CancellationToken);
                }
            }
        }
        static async Task WriteHelloAsync(CancealltionToken token)
        {
              // Throws on cancellation
              await context.Response.WriteAsync("Hello World", token);
        }
    }

    I'm just trying to figure out which token caused cancellation. I renamed CreateLinkedTokenSource to MagicSauce.CreateCombinedToken to create combined token so you can see what I want.

    When I say it's like WhenAny, I'm making a comparison that I want similar functionality to what task has. I can pass a bunch of different tasks to an API and get a result that tells me which one completed. When a cancellation token fires, it reports which token fired via the OperationCanceledException. This works well if you don't use linked tokens and have different function calls with different tokens but not if you combined tokens.

  5. sharwell commented on Jun 7, 2017

    @sharwell
    Contributor

    I totally understand where @davidfowl is coming from here, and have hit similar frustrating situations. For example, code like this becomes dependent on code not wrapping an operation in a timeout handler without incurring a substantial performance penalty to re-wrap the cancellation in a new exception that propagates the original cancellation source.

  6. stephentoub commented on Jun 8, 2017

    @stephentoub
    Member

    Consider this example:

    static void Foo(CancellationToken ct1, CancellationToken ct2)
    {
        CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct1, ct2);
        try
        {
            Bar(cts.Token);
        }
        catch (OperationCanceledException oce)
        {
            CancellationToken canceledCt = oce.CancellationToken;
            ...
        }
    }

    Under your desired semantics, let's say ct1 is canceled, ct2 isn't. Bar throws the OperationCanceledException as a result of ct1 being canceled. There is no guarantee that canceledCt == ct1... for example, ct1 could itself be a linked token, and it could have been one of its constituent tokens that was canceled. This is one of the places the semantics you're saying are desirable breaks down.

    I thought the code sample was pretty clear

    It was clear. I didn't mean to say it wasn't. I meant I was unclear what you wanted to see happen... what you're asking for is a big breaking change. I can think of several APIs off the top of my head that would break if it changed. And you acknowledged it's a breaking change. So, what is it you're asking for?

  7. davidfowl commented on Jun 8, 2017

    @davidfowl
    MemberAuthor

    A new API with the semantics I expressed above. An aggregate cancellation token that just delegates. The problem is we have all of these concrete classes/structs and no abstractions. A composite/aggregate token would have been perfect here. It could preserve all semantics while having all of the relevant data. In the above case, c1 would be an aggregate and you could unwrap it to get al the token that actually triggered.

  8. stephentoub commented on Jun 8, 2017

    @stephentoub
    Member

    A new API with the semantics I expressed above.

    I'm trying to understand exactly what you're proposing. Can you be specific, with a sketch of the API you have in mind? Or are you suggesting creating an entirely new replacement for CancellationTokenSource/CancellationToken?

  9. davidfowl commented on Jun 11, 2017

    @davidfowl
    MemberAuthor

    I hadn't thought about it past what I filed (like the inner workings of cancellation tokens and sources).

    What if we started from the premise that the combined token was just an aggregate token? In the scenario you describe, equality of both the combined token and individual tokens would work because Equals on the aggregate was really just a check to see if any of the tokens backing it were equal.

    static void Foo(CancellationToken ct1, CancellationToken ct2)
    {
        CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct1, ct2);
        try
        {
            Bar(cts.Token);
        }
        catch (OperationCanceledException oce)
        {
            CancellationToken canceledCt = oce.CancellationToken;
            ...
        }
    }
    

    So in the above case, if ct1 fired, oce.CancellationToken:

    • Assert.Equal(ct1, oce.CancellationToken) - pass
    • Assert.Equal(cts.Token, oce.CancellationToken) - pass
    • Assert.NotEqual(ct2, oce.CancellationToken) - pass
  10. svick commented on Jun 11, 2017

    @svick
    Member

    @davidfowl Do I understand it correctly that you want ct1 == oce.CancellationToken and cts.Token == oce.CancellationToken to be true, but ct1 == cts.Token to be false? Because that breaks the requirement that equality has to be transitive.

    If anything, I think this would have to be some new API.

  11. davidfowl commented on Jun 11, 2017

    @davidfowl
    MemberAuthor

    @svick good point. I'm not sure what the API would look like though.

  12. davidfowl commented on Jun 11, 2017

    @davidfowl
    MemberAuthor

    Actually, there's no reason why ct1 and cts.Token can't be equal in this scheme. I think they would be actually.

  13. svick commented on Jun 11, 2017

    @svick
    Member

    @davidfowl That still doesn't solve the transitivity issue, it just moves it around, since now ct1 == cts.Token and ct2 == cts.Token are true, but ct1 == ct2 is false.

  14. davidfowl commented on Jun 11, 2017

    @davidfowl
    MemberAuthor

    We need another method then.

    oce.CancellationToken.TriggeredBy(ct1);
    oce.CancellationToken.TriggeredBy(ct2);
    oce.CancellationToken.TriggeredBy(cts.Token);
    
  15. stephentoub commented on Jun 11, 2017

    @stephentoub
    Member

    We need another method then

    If this is really important, I was going to suggest something similar:

    public struct CancellationToken
    {
        public bool IsDerivativeOf(CancellationToken);
        ...
    }

    I'd have to double-check, but if we had that call a virtual method on CancellationTokenSource that simply returned Equals, I expect we could override it on the Linked_CancellationTokenSource-derived types and have them consult the registrations they store, fishing out of the registrations the associated CTS and thus CT, and working through it recursively, or if there were stack-dive concerns, some kind of iterative logic. Seems reasonable.

    That said, I am curious about the cases where this really matters. Can you share examples? From what I've seen, most of the time one cares about this is where you've received one or more CancellationTokens and you then call to some other method with one or more of those, that one throws, you catch the OperatinCanceledException, and you decide whether you want to do something based on the cancellation. But in such situations, at least from the ones I've seen, you can simply check whether the constituent tokens you care about have been canceled. If they haven't been, then you know that the cancellation didn't result from them. And if they have, then what does it matter whether the cancellation was caused by them or not? There's a race condition, but generally a benign one, as if it was canceled, even if it wasn't the exact check that caused the exception, it's still canceled, and no one needs to be the wiser. I'm sure one could construct a situation where the caller really, really cared which of two canceled tokens actually caused the operation to stop, but it seems super niche. Am I wrong?

  16. davidfowl commented on Jun 12, 2017

    @davidfowl
    MemberAuthor

    This is the piece of code that caused me to file this issue:

    https://github.com/aspnet/SignalR/blob/12917ef0e99f26939e2226ea8968b71020f0cba3/src/Microsoft.AspNetCore.Sockets.Http/Transports/LongPollingTransport.cs#L62-L87

    I originally just tried comparing tokens but it didn't work so ended up with this.

    https://github.com/aspnet/SignalR/blob/12917ef0e99f26939e2226ea8968b71020f0cba3/src/Microsoft.AspNetCore.Sockets.Http/HttpConnectionDispatcher.cs#L178-L185

    Here's where the linked token is created. In this scenario, nobody ever the linked token source is merely a proxy, nobody ever has a handle to the cts. It's just used to aggregate the input tokens.

    There's a race condition, but generally a benign one, as if it was canceled, even if it wasn't the exact check that caused the exception, it's still canceled, and no one needs to be the wiser. I'm sure one could construct a situation where the caller really, really cared which of two canceled tokens actually caused the operation to stop, but it seems super niche. Am I wrong?

    Like I said, I worked around it, but I personally thing it needs to be addressed (otherwise I wouldn't have filed the bug). If the cost of adding such an API seems like it doesn't meet the bar to address this scenario then fine. I'm sure I won't be the last one to be bitten by this. Especially since it's the only way to make aggregate tokens...

  17. stephentoub commented on Jun 12, 2017

    @stephentoub
    Member

    Thanks for the context, @davidfowl.

    To be clear, I'm not against adding APIs like this, but I want to make sure they're actually going to be valuable enough before we collectively do so. Hence the discussion and my questions.

    Looking at your example, would it actually be better with the proposed API? Right now you have:

    catch (OperationCanceledException)
    {
        if (context.RequestAborted.IsCancellationRequested)
        {
            ....
        }
        else if (_timeoutToken.IsCancellationRequested)
        {
            ...
        }
        else
        {
            ...
        }
    }

    and presumably you're suggesting you'd actually want:

    catch (OperationCanceledException oce)
    {
        if (oce.Token.IsDerivativeOf(context.RequestAborted)) // with whatever method name we chose
        {
            ....
        }
        else if (oce.Token.IsDerivativeOf(_timeoutToken))
        {
            ...
        }
        else
        {
            ...
        }
    }

    right? So my questions are:

    1. Is that actually any better functionally?
    2. Would you actually switch to this, given that it's almost certainly going to be slower? IsCancellationRequested is basically just return source != null && source.m_state == COMPLETE;, whereas this new method as I mentioned would need to follow a trail of objects, invoke one or more virtual methods, potentially do recursion or maintain its own stack of objects to follow, etc.

    And of course even if we could make Equals work the way you wanted, it would still have similar complexity to this new proposed method, and it would be a breaking change, and it wouldn't behave the same across implementations, and it would lack some of the behaviors that Equals is supposed to across the framework, so that doesn't seem like a good option either.

    That all leaves me wondering whether adding such a method or changing such functionality would help or would actually be a step backwards.

  18. davidfowl commented on Aug 20, 2017

    @davidfowl
    MemberAuthor

    Closing this out as it's not required.

  19. transferred this issue fromdotnet/corefxon Jan 31, 2020
  20. added this to the 2.1.0 milestone on Jan 31, 2020
  21. ghost locked as resolved and limited conversation to collaborators on Dec 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions