Repository navigation
Description
Description
I'm looking into all the threadpool dispatches in the hot loop of a project and I'm noticing many dispatches done because awaiters raced against completion, sometimes even causing a dispatch cascade, for instance during socket read completions. The latter seems to happen when the ASAEA (AwaitableSocketAsyncEventArgs) read is finished so fast, but not quite fast enough to be seen as completed before the caller tries to add its continuation. Note: the continuation here is going to do not much more than take the result and complete its ValueTaskSource (StreamPipeReader.ReadAtLeastAsyncCore.Core to be precise, which is a PoolingAsyncValueTaskMethodBuilder method).
That particular race then results in the IValueTaskSource.OnCompleted (on the ASAEA) taking the race branch where it does a dispatch to prevent any, supposed?, stack dive potential.
More problematically however is that after this dispatch is done the original stack unwinds to the next await which will now see IsCompleted false on the task returned (from the StreamPipeReader in this instance). This method will then also try to add its continuation while it's racing against the extremely simple SetResult continuation from the previously dispatched continuation. It can then fall into the same race branch (this time on the ManualResetValueTaskCore of the pooling method builder) and dispatch again as well. So on and so forth until we're at code that can't quite create a race so easily anymore. Adding about 2 to 3 superfluous dispatches to a logical operation fairly consistenly.
This turns into quite a substantial perf hit (at least 25%) and needs to be prevented.
Is there any way, outside of idiotic approaches like spinning for a short while on the returned tasks before awaiting, to prevent these races?
Additional Analysis
The stack dive concern in this race branch shared by ManualResetValueTaskSourceCore, Task{<TResult>} and others? doesn't make a lot of sense to me.
I can imagine that at IO boundaries you want a dispatch just to be sure stacks get reset every so often, so for ASAEA I can see the dispatch having a place. Though for unix there is already a dispatch from the socket async engine anyway, controlled via DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS. For any other kind of non-IO task it just seems it is a drag on perf?
I would really like to learn more about the reasoning here.
As a hypothetical case, just for async await: in which specific way is it worse to try to attach a continuation that ends up failing to do so, which is then run inline. As compared to the non race case, where observing IsCompleted is already true and its similarly running inline as part of the standard async await codegen? Is it purely because of api contract expectations of Awaiter.{Unsafe}OnCompleted that it will always hop threads?
The main issue with the way this works today is that it is anti-compositional, the more async methods as part of a well designed app, protocol or networked service you would like to layer the more of these racing dispatches you'll likely hit. Even if you are able to pool all the statemachines as we are, an alloc pales in comparison to an additional dispatch.
Our async stack is a bit deeper than I'd like but it looks like this on completion:
- SAEA.ReceiveAsync
- NetworkStream.ReadAsync (this isn't actually an async method, just here for clarity)
- StreamPipeReader.ReadAtLeastAsyncCore.Core
-- start of our code -- - ProtocolPipeReader.ReadAtLeastAsync.Core
- Protocol.ReadMessageAsync
- a few other async frames further upwards that also show themselves from time to time.
I would 100% argue this is not excessive and it should be possible from a runtime standpoint to support this without incurring more than one dispatch.
I can easily hit the racing dispatches with the debugger attached to a benchmark project, pouring out endless breakpoint logs:
(scroll to the end to see the file and line numbers corresponding to the racing branch dispatch)
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/a765d25c84d42923eab89de4e99896d19f2f6acd58af26cd8b6cb569f27bba/Socket.Tasks.cs:1316,25
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/a765d25c84d42923eab89de4e99896d19f2f6acd58af26cd8b6cb569f27bba/Socket.Tasks.cs:1316,25
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/a765d25c84d42923eab89de4e99896d19f2f6acd58af26cd8b6cb569f27bba/Socket.Tasks.cs:1316,25
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/a765d25c84d42923eab89de4e99896d19f2f6acd58af26cd8b6cb569f27bba/Socket.Tasks.cs:1316,25
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Breakpoint reached: /Users/nfloris/Library/Application Support/JetBrains/Rider2022.3/resharper-host/SourcesCache/d99725fcc1cadbd0ddce081df2c5c66b92b894658742333774b719bd8a9844/ManualResetValueTaskSourceCore.cs:178,29
Randomly pausing on the ManualResetValueTaskSourceCore breakpoint shows a variety of TStateMachine types in the continuation state, all corresponding to async methods along the hot loop.
Activity
stephentoub commentedon Nov 4, 2022
Why doesn't it make sense? The consuming code ends up doing a structure like:
You don't want that OnCompleted calling back into this code, in large part because it'll be doing so several frames deeper on the stack. If your argument is "that would never get deep enough to cause a problem", this was all added because we observed it did. Maybe it wouldn't in your use, but this needs to be general purpose.
If you have suggestions for something better, please share.
davidfowl commentedon Nov 5, 2022
The only thing I could think of doing here would be some sort of heuristic to avoid the dispatch if there was "enough space". Something like this
runtime/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs
Lines 3399 to 3401 in 3b0ef30
stephentoub commentedon Nov 5, 2022
Right. That might address some aspects, although it'd be adding extra checks. But there are others that are more subtle. For example, none of the locals in the first stack frame would be cleared and would remain rooted until the stack eventually unwound.
NinoFloris commentedon Nov 8, 2022
Apologies for the delayed reply.
What gave you that impression? Regardless, let me say that pragmatically I'm not at all against the occasional dispatch even just for the purpose of clean stacks. What's important is that it shouldn't be excessive and it should mostly be configurable by app/library code.
#77896 (comment)
I had little doubt it wasn't already considered but like @davidfowl I did immediately think in the direction of a stack depth check as well.
Ideally you 'just' want a way to get back to the stack frame of the state machine or a clean stack that is faster than a dispatch. Thinking in the wild directions of delimited continuations, split stacks, or some kind of faster trampoline than the TP queue. If exceptions were cheap enough that could be another approach as well (even though it I don't like the sound of it).
Unrealistically you could say awaiting should have had a different api that could signal to the caller that it failed to attach (even though that would leak an undesirable amount of implementation details into those apis).
I did experiment a bit with a local build of the runtime to get some low overhead telemetry on the completion races and the TP enqueues in general and I was happy to see the bulk of the dispatches go the normal route. The remaining portion I might just have to live with, trim the stacks a bit and move on.
As a library author 'I know best' when I should dispatch but it does come with a serious perf penalty to do so. The one promise style IVTS involved in the mentioned project is activated as a result of the completion of the previous logical operation. These operations can be entirely separate flows of user code. Practically it'll be problematic to make the IVTS run continuations inline. It may significantly delay the original operation from - for instance - completing the web request it was a part of.
Related to all of this, are there still plans (and opportunities?) to improve local TP queue perf @stephentoub? Is unwinding to get back to the TP worker a large part of the cost at this point? I know it entirely depends on the stack depth but async stacks are fairly EH heavy, need to create state machine boxes and tasks during unwind etc, maybe you have some insights into this?
Beyond any improvements, it seems that what I can realistically do is to accept the continuations will run inline and try to estimate when it should be about time to get off the original stack, dispatching more judiciously than once per operation. When the next continuation starts with a nice amount of synchronous compute any heuristics will be thwarted regardless, but it should be ok to assume this is not the general case.
Doing cooperative quantums, what could go wrong... 😁
If either of you has any valuable insights to share I would very much appreciate it.
stephentoub commentedon Jan 20, 2023
Nothing, I was just speculating as to what the argument might have been... hence the "if" 😄. As noted, though, it's one of multiple real concerns.
We would love to improve ThreadPool perf, and #77665 tracks some of the experiments being done / areas of focus. I'm not aware of any plans specifically around improving the actual queue data structure utilized... for the global queue (now queues on large enough machines), that's just
ConcurrentQueue<T>, which was already optimized a few releases back. If someone has a different queue implementation that meets all the necessary criteria and has demonstrably better perf, we'd of course consider it; I'm just not aware of such an implementation or anyone working on it.While I'd love to say "here's the answer", I don't really have one for you. If you have a concrete suggestion for what we could do to improve the situation for you, it'd be great to hear; otherwise, I'm not sure there's much we can really do about this particular construction at this point.
NinoFloris commentedon Jan 31, 2023
Particularly I/O reads seem to have one or two more dispatches than they would have in C++ or rust (after investigating some of the implementations) for instance. These effects can be seen in TE results as well. I know TE scenarios are still quite synthetic and heavily influenced by these smaller overheads but it's something to keep in mind. I've written a reply going into this direction in the threadpool issue you linked to. Given any of this is off topic from the original issue I'll close this now.