You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Creating linked cancellation tokens hides which token triggered cancellation #22172
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.
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).
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.
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).
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.
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.
I thought the code sample was pretty clear. Let me tweak it a bit:
usingSystem;usingSystem.Threading;namespaceConsoleApp2{classProgram{staticasyncTaskMain(string[]args){varcts1=newCancellationTokenSource();varcts2=newCancellationTokenSource();varcts3=newCancellationTokenSource();try{cts1.Cancel();varlinkedToken=MagicSauce.CreateCombinedToken(cts1.Token,cts2.Token,cts3.Token);awaitDoSomething(linked);}catch(OperationCanceledExceptionex){Console.WriteLine(cts1.Token==ex.CancellationToken);}}}staticasyncTaskWriteHelloAsync(CancealltionTokentoken){// Throws on cancellationawaitcontext.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.
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.
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?
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.
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?
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.
@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.
@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.
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?
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...
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:
and presumably you're suggesting you'd actually want:
catch(OperationCanceledExceptionoce){if(oce.Token.IsDerivativeOf(context.RequestAborted))// with whatever method name we chose{....}
else if(oce.Token.IsDerivativeOf(_timeoutToken)){...}else{...}}
right? So my questions are:
Is that actually any better functionally?
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.
Activity
stephentoub commentedon Jun 7, 2017
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:
(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).
davidfowl commentedon Jun 7, 2017
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.stephentoub commentedon Jun 7, 2017
"no different" from Task.WhenAny would be an API like:
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:
?
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.
davidfowl commentedon Jun 7, 2017
I thought the code sample was pretty clear. Let me tweak it a bit:
I'm just trying to figure out which token caused cancellation. I renamed
CreateLinkedTokenSourcetoMagicSauce.CreateCombinedTokento 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.sharwell commentedon Jun 7, 2017
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.
stephentoub commentedon Jun 8, 2017
Consider this example:
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.
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?
davidfowl commentedon Jun 8, 2017
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.
stephentoub commentedon Jun 8, 2017
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?
davidfowl commentedon Jun 11, 2017
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.
So in the above case, if
ct1fired,oce.CancellationToken:Assert.Equal(ct1, oce.CancellationToken)- passAssert.Equal(cts.Token, oce.CancellationToken)- passAssert.NotEqual(ct2, oce.CancellationToken)- passsvick commentedon Jun 11, 2017
@davidfowl Do I understand it correctly that you want
ct1 == oce.CancellationTokenandcts.Token == oce.CancellationTokento betrue, butct1 == cts.Tokento befalse? Because that breaks the requirement that equality has to be transitive.If anything, I think this would have to be some new API.
davidfowl commentedon Jun 11, 2017
@svick good point. I'm not sure what the API would look like though.
davidfowl commentedon Jun 11, 2017
Actually, there's no reason why ct1 and cts.Token can't be equal in this scheme. I think they would be actually.
svick commentedon Jun 11, 2017
@davidfowl That still doesn't solve the transitivity issue, it just moves it around, since now
ct1 == cts.Tokenandct2 == cts.Tokenaretrue, butct1 == ct2isfalse.davidfowl commentedon Jun 11, 2017
We need another method then.
stephentoub commentedon Jun 11, 2017
If this is really important, I was going to suggest something similar:
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?
davidfowl commentedon Jun 12, 2017
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.
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...
stephentoub commentedon Jun 12, 2017
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:
and presumably you're suggesting you'd actually want:
right? So my questions are:
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.
davidfowl commentedon Aug 20, 2017
Closing this out as it's not required.