From 3469095c80524d3dbaf08eb38d0658775c2b40fc Mon Sep 17 00:00:00 2001 From: Roman Ettlinger Date: Fri, 13 Nov 2026 17:02:54 +0100 Subject: [PATCH 1/5] Run client response continuations on the receive loop thread once it waits A request waits for its response on a value task source that runs its continuation asynchronously: the receive loop completes it under the channel gate. The source queues the continuation with preferLocal, so the loop's thread runs it once the next receive goes pending, or a worker that the enqueue woke takes it. When the loop's thread runs it, the woken worker found no work, and on .NET 11 such a worker spins up to 1024 backoff units. The receive loop now defers the completions of the responses in a chunk and completes them on its thread when one of its waits goes pending, after it registered its continuation on that wait. The loop then no longer depends on the thread, so a continuation that blocks, for example a synchronous call on the same channel, cannot stall it. At most 16 completions are deferred; a loop that ends completes them on the pool. Client work items per request drop from 2 to 1. Client CPU per request on .NET 11 -5 to -24 %, on .NET 10 -3 to -11 %; throughput -2 to +8 % (within the noise of the encrypted scenario, +1 to +2 % in the confirming run). Starting the server writer at the request worker's park point instead of queueing it was measured as well and dropped: server work items per request fell by a third to a half, but CPU per request did not fall consistently and single-value Read lost 2-5 % throughput. Co-Authored-By: Claude Opus 5.5 --- docs/ServerScalability.md | 2 +- .../Stack/Tcp/ChannelAsyncOperation.cs | 14 +- .../Stack/Tcp/ResponseContinuationDeferral.cs | 250 ++++++++++++++++++ .../Stack/Tcp/UaSCBinaryChannel.cs | 38 ++- .../ResponseContinuationDeferralTests.cs | 225 ++++++++++++++++ 5 files changed, 523 insertions(+), 6 deletions(-) create mode 100644 src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs create mode 100644 tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs diff --git a/docs/ServerScalability.md b/docs/ServerScalability.md index f0d7587d95..50477156db 100644 --- a/docs/ServerScalability.md +++ b/docs/ServerScalability.md @@ -187,7 +187,7 @@ Two runtime settings bring CPU per request back to the .NET 10 level (medians of | `System.Threading.ThreadPool.SpuriousDispatchNoSpinThreshold` = 0 (`DOTNET_ThreadPool_SpuriousDispatchNoSpinThreshold=0`) | −14 % (Read), −40 % (Write), ±0 (Browse) | −23 %, −58 %, −54 % | +9 %, +6 %, +7 % | | `System.Threading.ThreadPool.UnfairSemaphoreSpinLimit` = 70 (`DOTNET_ThreadPool_UnfairSemaphoreSpinLimit=46`, hexadecimal) | −13 %, −40 %, −1 % | −18 %, −55 %, −51 % | −1 %, +2 %, +1 % | -The changes are relative to .NET 11 with default settings. `SpuriousDispatchNoSpinThreshold=0` stops the spinning only after a wake-up that found no work, so it also kept the throughput gains of .NET 11. Neither setting is among the documented [threading settings](https://learn.microsoft.com/dotnet/core/runtime-config/threading), and both can change between releases; measure before and after with the [server load harness](../perf/README.md) (`SERVER_DOTNET_ThreadPool_…` for the server child, `DOTNET_ThreadPool_…` for the client). The client channel starts its writer on the requesting thread instead of queuing a work item for it, which removes one of these wake-ups per request on every runtime. +The changes are relative to .NET 11 with default settings. `SpuriousDispatchNoSpinThreshold=0` stops the spinning only after a wake-up that found no work, so it also kept the throughput gains of .NET 11. Neither setting is among the documented [threading settings](https://learn.microsoft.com/dotnet/core/runtime-config/threading), and both can change between releases; measure before and after with the [server load harness](../perf/README.md) (`SERVER_DOTNET_ThreadPool_…` for the server child, `DOTNET_ThreadPool_…` for the client). The client channel starts its writer on the requesting thread instead of queuing a work item for it, and its receive loop runs the continuations of the requests it answered on its own thread once the next receive is pending, which removes two of these wake-ups per request on every runtime (client CPU per request on .NET 11 −8 to −23 % for the second). ### JIT warm-up diff --git a/src/Opc.Ua.Core/Stack/Tcp/ChannelAsyncOperation.cs b/src/Opc.Ua.Core/Stack/Tcp/ChannelAsyncOperation.cs index af3ab0d4e4..c2f75dbede 100644 --- a/src/Opc.Ua.Core/Stack/Tcp/ChannelAsyncOperation.cs +++ b/src/Opc.Ua.Core/Stack/Tcp/ChannelAsyncOperation.cs @@ -40,7 +40,7 @@ namespace Opc.Ua.Bindings /// Stores the results of an asynchronous operation. /// /// - public class ChannelAsyncOperation : IAsyncResult, IDisposable, IValueTaskSource + public class ChannelAsyncOperation : IAsyncResult, IDisposable, IValueTaskSource, IDeferredWaitCompletion { /// /// Initializes the object with a callback @@ -435,12 +435,22 @@ internal ValueTask WaitForCompletionAsync(CancellationToken ct) /// private void TrySetWaitResult(bool completed) { - if (Interlocked.Exchange(ref m_waitResultSet, 1) == 0) + if (Interlocked.Exchange(ref m_waitResultSet, 1) == 0 && + !(completed && ResponseContinuationDeferral.TryDefer(this))) { m_waitCore.SetResult(completed); } } + /// + void IDeferredWaitCompletion.CompleteDeferredWait(bool inline) + { + // the receive loop that deferred the completion holds no lock now and no + // longer depends on its thread (see ResponseContinuationDeferral) + m_waitCore.RunContinuationsAsynchronously = !inline; + m_waitCore.SetResult(true); + } + /// void IValueTaskSource.GetResult(short token) { diff --git a/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs b/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs new file mode 100644 index 0000000000..81532e0288 --- /dev/null +++ b/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs @@ -0,0 +1,250 @@ +/* ======================================================================== + * Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved. + * + * OPC Foundation MIT License 1.00 + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * The complete license agreement can be found here: + * http://opcfoundation.org/License/MIT/1.00/ + * ======================================================================*/ + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Opc.Ua.Bindings +{ + /// + /// A wait for a channel operation whose completion the receive loop deferred. + /// + internal interface IDeferredWaitCompletion + { + /// + /// Ends the deferred wait. + /// + /// Whether the continuation of the wait may run on the + /// calling thread. + void CompleteDeferredWait(bool inline); + } + + /// + /// Lets a receive loop run the continuations of the requests its responses completed + /// on its own thread once it has nothing more to receive, instead of queueing a pool + /// work item for each. + /// + /// + /// + /// A request waits for its response on a value task source that runs its + /// continuation asynchronously: the receive loop holds the channel gate when it + /// completes the request, and must not run the caller's code. The source queues the + /// continuation with preferLocal, so the receive loop's thread runs it once + /// the next receive goes pending and the thread returns to the pool, or a worker + /// the enqueue woke takes it. When the loop's thread runs it, the woken worker found + /// no work, and since .NET 11 such a worker spins much longer before it blocks again + /// (UnfairSemaphoreSpinLimit 70 to 1024 backoff units). + /// + /// + /// The receive loop defers the completions instead and runs them where its thread + /// would have run the queued items: after the loop registered its continuation on a + /// receive (or another wait) that went pending. The loop then no longer depends on + /// the thread, so a caller's continuation that blocks it cannot stall the receive + /// loop, as with a pool thread today. A completion that would exceed + /// deferred ones is not deferred. + /// + /// + internal static class ResponseContinuationDeferral + { + /// + /// The most completions one receive loop defers; later ones complete at once. + /// + private const int kMaxPending = 16; + + /// + /// Opens a scope in which completed waits are deferred. + /// + public static void Enter() + { + t_depth++; + } + + /// + /// Closes the scope opened by . + /// + public static void Exit() + { + t_depth--; + } + + /// + /// Defers the completion of a wait, when the calling thread is in a scope. + /// + /// if the caller must complete the wait. + public static bool TryDefer(IDeferredWaitCompletion wait) + { + if (t_depth <= 0) + { + return false; + } + List pending = t_pending ??= []; + if (pending.Count >= kMaxPending) + { + return false; + } + pending.Add(wait); + return true; + } + + /// + /// Completes the deferred waits of this thread. + /// + /// Whether their continuations run on this thread; only + /// when the thread holds no lock and nothing waits for it to return. + public static void CompletePending(bool inline) + { + List? pending = t_pending; + if (pending == null || pending.Count == 0) + { + return; + } + int depth = t_depth; + t_depth = 0; + try + { + // in the order the responses arrived + for (int ii = 0; ii < pending.Count; ii++) + { + IDeferredWaitCompletion wait = pending[ii]; + pending[ii] = null!; + wait.CompleteDeferredWait(inline); + } + } + finally + { + pending.Clear(); + t_depth = depth; + } + } + + /// + /// Awaits and, if it goes pending, completes the deferred + /// waits on this thread once the continuation is registered. + /// + public static CompleteOnSuspend AwaitAndComplete(ValueTask task) + { + return new CompleteOnSuspend(task); + } + + /// + /// Awaits and, if it goes pending, completes the deferred + /// waits on this thread once the continuation is registered. + /// + /// The result type. + public static CompleteOnSuspend AwaitAndComplete(ValueTask task) + { + return new CompleteOnSuspend(task); + } + + /// + /// Awaits a value task; when the awaiting method suspends, its continuation is + /// registered first, then the deferred waits complete inline. + /// + internal readonly struct CompleteOnSuspend : ICriticalNotifyCompletion + { + private readonly ValueTask m_task; + + public CompleteOnSuspend(ValueTask task) + { + m_task = task; + } + + public CompleteOnSuspend GetAwaiter() + { + return this; + } + + public bool IsCompleted => m_task.IsCompleted; + + public void GetResult() + { + m_task.GetAwaiter().GetResult(); + } + + public void OnCompleted(Action continuation) + { + m_task.ConfigureAwait(false).GetAwaiter().OnCompleted(continuation); + CompletePending(inline: true); + } + + public void UnsafeOnCompleted(Action continuation) + { + m_task.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(continuation); + CompletePending(inline: true); + } + } + + /// + /// Awaits a value task; when the awaiting method suspends, its continuation is + /// registered first, then the deferred waits complete inline. + /// + /// The result type. + internal readonly struct CompleteOnSuspend : ICriticalNotifyCompletion + { + private readonly ValueTask m_task; + + public CompleteOnSuspend(ValueTask task) + { + m_task = task; + } + + public CompleteOnSuspend GetAwaiter() + { + return this; + } + + public bool IsCompleted => m_task.IsCompleted; + + public T GetResult() + { + return m_task.GetAwaiter().GetResult(); + } + + public void OnCompleted(Action continuation) + { + m_task.ConfigureAwait(false).GetAwaiter().OnCompleted(continuation); + CompletePending(inline: true); + } + + public void UnsafeOnCompleted(Action continuation) + { + m_task.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(continuation); + CompletePending(inline: true); + } + } + + [ThreadStatic] + private static List? t_pending; + + [ThreadStatic] + private static int t_depth; + } +} diff --git a/src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs b/src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs index 8a56fd5af3..06d7507875 100644 --- a/src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs +++ b/src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs @@ -1418,7 +1418,28 @@ protected void StartReceiveLoopWithBody( /// /// Receives and dispatches chunks while the transport remains current, reporting receive and dispatch failures. /// + /// + /// The requests that the received responses complete continue once the loop waits: + /// every wait of the loop that goes pending runs them on the loop's thread (see + /// ). + /// private async Task RunReceiveLoopAsync(IUaSCByteTransport transport, CancellationToken ct) + { + try + { + await RunReceiveLoopCoreAsync(transport, ct).ConfigureAwait(false); + } + finally + { + // the loop ended with completions it deferred + ResponseContinuationDeferral.CompletePending(inline: false); + } + } + + /// + /// The loop of . + /// + private async Task RunReceiveLoopCoreAsync(IUaSCByteTransport transport, CancellationToken ct) { while (!ct.IsCancellationRequested && ReferenceEquals(Transport, transport)) { @@ -1427,8 +1448,8 @@ private async Task RunReceiveLoopAsync(IUaSCByteTransport transport, Cancellatio { // backpressure: do not read more requests while their responses // cannot be written; the peer's sends block in TCP flow control. - await WaitForWriteCapacityAsync(ct).ConfigureAwait(false); - chunk = await transport.ReceiveChunkAsync(ct).ConfigureAwait(false); + await ResponseContinuationDeferral.AwaitAndComplete(WaitForWriteCapacityAsync(ct)); + chunk = await ResponseContinuationDeferral.AwaitAndComplete(transport.ReceiveChunkAsync(ct)); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { @@ -1456,7 +1477,18 @@ private async Task RunReceiveLoopAsync(IUaSCByteTransport transport, Cancellatio try { - await OnChunkReceivedAsync(chunk, ct).ConfigureAwait(false); + // the responses in the chunk defer the continuations of their requests + ValueTask dispatch; + ResponseContinuationDeferral.Enter(); + try + { + dispatch = OnChunkReceivedAsync(chunk, ct); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + await ResponseContinuationDeferral.AwaitAndComplete(dispatch); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { diff --git a/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs b/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs new file mode 100644 index 0000000000..2acc0123fa --- /dev/null +++ b/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs @@ -0,0 +1,225 @@ +/* ======================================================================== + * Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved. + * + * OPC Foundation MIT License 1.00 + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * The complete license agreement can be found here: + * http://opcfoundation.org/License/MIT/1.00/ + * ======================================================================*/ + +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using NUnit.Framework; +using Opc.Ua.Bindings; +using Opc.Ua.Tests; + +namespace Opc.Ua.Core.Tests.Stack.Transport +{ + /// + /// The receive loop runs the continuations of the requests it completed once it + /// waits for the next chunk (see ). + /// + [TestFixture] + [Category("TcpTransport")] + [Parallelizable] + public sealed class ResponseContinuationDeferralTests + { + private readonly ILogger m_logger = + NUnitTelemetryContext.Create().CreateLogger(); + + [Test] + [CancelAfter(10000)] + public async Task CompletionOutsideAScopeIsNotDeferredAsync() + { + using var operation = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + ValueTask wait = operation.WaitForCompletionAsync(CancellationToken.None); + + Assert.That(operation.Complete(true, 7), Is.True); + + Assert.That(wait.IsCompleted, Is.True); + await wait.ConfigureAwait(false); + Assert.That(operation.End(0), Is.EqualTo(7)); + } + + [Test] + [CancelAfter(10000)] + public async Task CompletionInAScopeRunsItsContinuationWhenPendingCompletesInlineAsync() + { + using var operation = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + Task waiter = ContinuationThreadAsync(operation.WaitForCompletionAsync(CancellationToken.None)); + + ResponseContinuationDeferral.Enter(); + try + { + Assert.That(operation.Complete(true, 7), Is.True); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + Assert.That(waiter.IsCompleted, Is.False, "the completion is deferred"); + + ResponseContinuationDeferral.CompletePending(inline: true); + + Assert.That(waiter.IsCompleted, Is.True, "the continuation ran inline"); + Assert.That(await waiter.ConfigureAwait(false), Is.EqualTo(Environment.CurrentManagedThreadId)); + Assert.That(operation.End(0), Is.EqualTo(7)); + } + + [Test] + [CancelAfter(10000)] + public async Task CompletionsDeferredOnLoopExitRunOnThePoolAsync() + { + using var operation = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + Task waiter = ContinuationThreadAsync(operation.WaitForCompletionAsync(CancellationToken.None)); + + ResponseContinuationDeferral.Enter(); + try + { + operation.Complete(true, 7); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + ResponseContinuationDeferral.CompletePending(inline: false); + + await waiter.ConfigureAwait(false); + Assert.That(operation.End(0), Is.EqualTo(7)); + } + + [Test] + [CancelAfter(10000)] + public async Task ScopeDefersAtMostSixteenCompletionsAsync() + { + var operations = new ChannelAsyncOperation[17]; + var waits = new ValueTask[operations.Length]; + for (int ii = 0; ii < operations.Length; ii++) + { + operations[ii] = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + // each wait is awaited once, below +#pragma warning disable CA2012 + waits[ii] = operations[ii].WaitForCompletionAsync(CancellationToken.None); +#pragma warning restore CA2012 + } + try + { + ResponseContinuationDeferral.Enter(); + try + { + foreach (ChannelAsyncOperation operation in operations) + { + operation.Complete(true, 1); + } + } + finally + { + ResponseContinuationDeferral.Exit(); + } + + for (int ii = 0; ii < 16; ii++) + { + Assert.That(waits[ii].IsCompleted, Is.False, $"wait {ii} is deferred"); + } + Assert.That(waits[16].IsCompleted, Is.True, "the 17th completion is not deferred"); + + ResponseContinuationDeferral.CompletePending(inline: true); + foreach (ValueTask wait in waits) + { + Assert.That(wait.IsCompleted, Is.True); + await wait.ConfigureAwait(false); + } + } + finally + { + foreach (ChannelAsyncOperation operation in operations) + { + operation.Dispose(); + } + } + } + + /// + /// A continuation that blocks until the receive loop resumes does not stall the + /// loop: the loop registers its continuation on the pending receive before it + /// runs the deferred continuations on its thread. + /// + [Test] + [CancelAfter(20000)] + public async Task BlockingContinuationDoesNotStallTheLoopAsync() + { + using var operation = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + var receive = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var loopResumed = new ManualResetEventSlim(); + + // the caller of the request: completes the next receive, then blocks until + // the loop has processed it, as a synchronous call on the channel would + Task caller = CallerAsync( + operation.WaitForCompletionAsync(CancellationToken.None), + receive, + loopResumed); + + Task loop = Task.Run(() => LoopAsync(operation, receive, loopResumed)); + + Assert.That(await loop.ConfigureAwait(false), Is.EqualTo(1)); + Assert.That(await caller.ConfigureAwait(false), Is.True, "the loop resumed while the caller blocked"); + } + + private static async Task LoopAsync( + ChannelAsyncOperation operation, + TaskCompletionSource receive, + ManualResetEventSlim loopResumed) + { + ResponseContinuationDeferral.Enter(); + try + { + operation.Complete(true, 7); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + int received = await ResponseContinuationDeferral.AwaitAndComplete(new ValueTask(receive.Task)); + loopResumed.Set(); + return received; + } + + private static async Task CallerAsync( + ValueTask wait, + TaskCompletionSource receive, + ManualResetEventSlim loopResumed) + { + await wait.ConfigureAwait(false); + receive.SetResult(1); + return loopResumed.Wait(TimeSpan.FromSeconds(5)); + } + + private static async Task ContinuationThreadAsync(ValueTask wait) + { + await wait.ConfigureAwait(false); + return Environment.CurrentManagedThreadId; + } + } +} From c6735e4ecd8d18e6194546243b1ff0ec804134d6 Mon Sep 17 00:00:00 2001 From: Roman Ettlinger Date: Fri, 13 Nov 2026 19:02:33 +0100 Subject: [PATCH 2/5] Wait for the server to close the channel before completing the dropped response ResponseAfterChannelClosedIsDroppedQuietlyAsync completed the pending response as soon as the client's CloseAsync returned. The client does not wait for the server to process the close, so on a slow runner the server channel was still open, the response was queued normally and the expected "channel closed by the client" log never came (seen on linux net11.0 CI). The test now waits for the listener to log the closed channel first. Co-Authored-By: Claude Opus 5.5 --- .../Transport/TcpTransportListenerRequestCompletionTests.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/Opc.Ua.Core.Tests/Stack/Transport/TcpTransportListenerRequestCompletionTests.cs b/tests/Opc.Ua.Core.Tests/Stack/Transport/TcpTransportListenerRequestCompletionTests.cs index 21a2f7725c..5e479a09d6 100644 --- a/tests/Opc.Ua.Core.Tests/Stack/Transport/TcpTransportListenerRequestCompletionTests.cs +++ b/tests/Opc.Ua.Core.Tests/Stack/Transport/TcpTransportListenerRequestCompletionTests.cs @@ -282,6 +282,12 @@ public async Task ResponseAfterChannelClosedIsDroppedQuietlyAsync() closing.Dispose(); await Assert.CatchAsync(async () => await abandoned.ConfigureAwait(false)); + // the client does not wait for the server to process the close: the response + // is dropped only once the listener has closed its side of the channel + Assert.That(await WaitForAsync(() => loopback.Logs.Any(l => + l.EventId == CoreEventIds.TcpTransportListener + 4)) + .ConfigureAwait(false), Is.True, "The server did not close the channel."); + source.SetResult(Respond(CreateReadRequest(1))); Assert.That(await WaitForAsync(() => loopback.Logs.Any(l => From f0a7990d3ed98c6dfce21143f317709dd1ceb65d Mon Sep 17 00:00:00 2001 From: Roman Ettlinger Date: Sat, 14 Nov 2026 10:09:35 +0100 Subject: [PATCH 3/5] Hold at most one deferred response completion per receive loop thread Review fixes for the response continuation deferral: - A thread holds one deferred completion. A later response completes the held one on the pool: two completions drained inline in turn deadlocked when the first continuation blocked until the second request completed. - A held completion goes to the pool after the loop dispatched four more chunks without its receive going pending, so a busy channel whose receives keep completing synchronously does not hold a response back. This replaces the cap of 16, past which the held ones stayed unsignalled. - The loop completes a held completion in a finally of the loop method itself, on the thread that dispatched the last chunk, not in a wrapper that could resume on another thread. - A loop that resumed inside another loop's dispatch leaves the inline completion to the outer loop, which may hold locks. Client work items per request stay at 1; client CPU per request on .NET 11 -1 to -28 %, throughput 0 to +2 %. Co-Authored-By: Claude Opus 5.5 --- .../Stack/Tcp/ResponseContinuationDeferral.cs | 101 ++++++++----- .../Stack/Tcp/UaSCBinaryChannel.cs | 133 +++++++++--------- .../ResponseContinuationDeferralTests.cs | 115 ++++++++++----- 3 files changed, 210 insertions(+), 139 deletions(-) diff --git a/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs b/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs index 81532e0288..c63a333f4f 100644 --- a/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs +++ b/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs @@ -28,7 +28,6 @@ * ======================================================================*/ using System; -using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading.Tasks; @@ -64,26 +63,41 @@ internal interface IDeferredWaitCompletion /// (UnfairSemaphoreSpinLimit 70 to 1024 backoff units). /// /// - /// The receive loop defers the completions instead and runs them where its thread - /// would have run the queued items: after the loop registered its continuation on a + /// The receive loop defers the completion instead and runs it where its thread + /// would have run the queued item: after the loop registered its continuation on a /// receive (or another wait) that went pending. The loop then no longer depends on /// the thread, so a caller's continuation that blocks it cannot stall the receive - /// loop, as with a pool thread today. A completion that would exceed - /// deferred ones is not deferred. + /// loop, as with a pool thread today. + /// + /// + /// A thread holds at most one deferred completion. A later response completes the + /// one held before it on the pool, as without deferral: a continuation run inline + /// may block until another of its requests completes, and that one must not wait + /// for the blocked thread. The held completion also goes to the pool once the loop + /// dispatched more chunks without its receive going + /// pending, so a busy channel does not hold a response back. /// /// internal static class ResponseContinuationDeferral { /// - /// The most completions one receive loop defers; later ones complete at once. + /// How many more chunks a receive loop dispatches while it holds a completion + /// before it completes it on the pool. /// - private const int kMaxPending = 16; + private const int kMaxDeferredChunks = 4; /// - /// Opens a scope in which completed waits are deferred. + /// Opens a scope in which a completed wait is deferred. /// + /// + /// Called by the receive loop before it dispatches a chunk, while it holds no lock. + /// public static void Enter() { + if (t_pending != null && ++t_deferredChunks > kMaxDeferredChunks) + { + CompletePending(inline: false); + } t_depth++; } @@ -96,8 +110,13 @@ public static void Exit() } /// - /// Defers the completion of a wait, when the calling thread is in a scope. + /// Defers the completion of a wait, when the calling thread is in a scope. A + /// completion deferred before completes on the pool. /// + /// + /// The caller may hold locks: a completion on the pool only queues the + /// continuation. + /// /// if the caller must complete the wait. public static bool TryDefer(IDeferredWaitCompletion wait) { @@ -105,49 +124,54 @@ public static bool TryDefer(IDeferredWaitCompletion wait) { return false; } - List pending = t_pending ??= []; - if (pending.Count >= kMaxPending) - { - return false; - } - pending.Add(wait); + IDeferredWaitCompletion? previous = t_pending; + t_pending = wait; + t_deferredChunks = 0; + previous?.CompleteDeferredWait(inline: false); return true; } /// - /// Completes the deferred waits of this thread. + /// Completes the wait deferred on this thread, if any. /// - /// Whether their continuations run on this thread; only - /// when the thread holds no lock and nothing waits for it to return. + /// Whether its continuation runs on this thread; only when + /// the thread holds no lock and nothing waits for it to return. public static void CompletePending(bool inline) { - List? pending = t_pending; - if (pending == null || pending.Count == 0) + IDeferredWaitCompletion? pending = t_pending; + if (pending == null) { return; } + t_pending = null; int depth = t_depth; t_depth = 0; try { - // in the order the responses arrived - for (int ii = 0; ii < pending.Count; ii++) - { - IDeferredWaitCompletion wait = pending[ii]; - pending[ii] = null!; - wait.CompleteDeferredWait(inline); - } + pending.CompleteDeferredWait(inline); } finally { - pending.Clear(); t_depth = depth; } } + /// + /// Completes the deferred wait inline once the awaiting receive loop suspended, + /// unless the loop ran inside the dispatch of another loop on this thread, which + /// may hold locks: that loop completes it when it suspends. + /// + private static void CompleteOnSuspended() + { + if (t_depth == 0) + { + CompletePending(inline: true); + } + } + /// /// Awaits and, if it goes pending, completes the deferred - /// waits on this thread once the continuation is registered. + /// wait on this thread once the continuation is registered. /// public static CompleteOnSuspend AwaitAndComplete(ValueTask task) { @@ -156,7 +180,7 @@ public static CompleteOnSuspend AwaitAndComplete(ValueTask task) /// /// Awaits and, if it goes pending, completes the deferred - /// waits on this thread once the continuation is registered. + /// wait on this thread once the continuation is registered. /// /// The result type. public static CompleteOnSuspend AwaitAndComplete(ValueTask task) @@ -166,7 +190,7 @@ public static CompleteOnSuspend AwaitAndComplete(ValueTask task) /// /// Awaits a value task; when the awaiting method suspends, its continuation is - /// registered first, then the deferred waits complete inline. + /// registered first, then the deferred wait completes inline. /// internal readonly struct CompleteOnSuspend : ICriticalNotifyCompletion { @@ -192,19 +216,19 @@ public void GetResult() public void OnCompleted(Action continuation) { m_task.ConfigureAwait(false).GetAwaiter().OnCompleted(continuation); - CompletePending(inline: true); + CompleteOnSuspended(); } public void UnsafeOnCompleted(Action continuation) { m_task.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(continuation); - CompletePending(inline: true); + CompleteOnSuspended(); } } /// /// Awaits a value task; when the awaiting method suspends, its continuation is - /// registered first, then the deferred waits complete inline. + /// registered first, then the deferred wait completes inline. /// /// The result type. internal readonly struct CompleteOnSuspend : ICriticalNotifyCompletion @@ -231,18 +255,21 @@ public T GetResult() public void OnCompleted(Action continuation) { m_task.ConfigureAwait(false).GetAwaiter().OnCompleted(continuation); - CompletePending(inline: true); + CompleteOnSuspended(); } public void UnsafeOnCompleted(Action continuation) { m_task.ConfigureAwait(false).GetAwaiter().UnsafeOnCompleted(continuation); - CompletePending(inline: true); + CompleteOnSuspended(); } } [ThreadStatic] - private static List? t_pending; + private static IDeferredWaitCompletion? t_pending; + + [ThreadStatic] + private static int t_deferredChunks; [ThreadStatic] private static int t_depth; diff --git a/src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs b/src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs index 06d7507875..9772d9546c 100644 --- a/src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs +++ b/src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs @@ -1427,86 +1427,79 @@ private async Task RunReceiveLoopAsync(IUaSCByteTransport transport, Cancellatio { try { - await RunReceiveLoopCoreAsync(transport, ct).ConfigureAwait(false); - } - finally - { - // the loop ended with completions it deferred - ResponseContinuationDeferral.CompletePending(inline: false); - } - } - - /// - /// The loop of . - /// - private async Task RunReceiveLoopCoreAsync(IUaSCByteTransport transport, CancellationToken ct) - { - while (!ct.IsCancellationRequested && ReferenceEquals(Transport, transport)) - { - ArraySegment chunk; - try - { - // backpressure: do not read more requests while their responses - // cannot be written; the peer's sends block in TCP flow control. - await ResponseContinuationDeferral.AwaitAndComplete(WaitForWriteCapacityAsync(ct)); - chunk = await ResponseContinuationDeferral.AwaitAndComplete(transport.ReceiveChunkAsync(ct)); - } - catch (OperationCanceledException) when (ct.IsCancellationRequested) - { - return; - } - catch (ServiceResultException sre) - { - OnTransportError(transport, sre.Result, ct); - return; - } - catch (Exception ex) + while (!ct.IsCancellationRequested && ReferenceEquals(Transport, transport)) { - OnTransportError(transport, ServiceResult.Create( - ex, - StatusCodes.BadTcpInternalError, - ex.Message), ct); - return; - } + ArraySegment chunk; + try + { + // backpressure: do not read more requests while their responses + // cannot be written; the peer's sends block in TCP flow control. + await ResponseContinuationDeferral.AwaitAndComplete(WaitForWriteCapacityAsync(ct)); + chunk = await ResponseContinuationDeferral.AwaitAndComplete(transport.ReceiveChunkAsync(ct)); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return; + } + catch (ServiceResultException sre) + { + OnTransportError(transport, sre.Result, ct); + return; + } + catch (Exception ex) + { + OnTransportError(transport, ServiceResult.Create( + ex, + StatusCodes.BadTcpInternalError, + ex.Message), ct); + return; + } - if (ct.IsCancellationRequested || !ReferenceEquals(Transport, transport)) - { - BufferManager.ReturnBuffer(chunk.Array, nameof(RunReceiveLoopAsync)); - return; - } + if (ct.IsCancellationRequested || !ReferenceEquals(Transport, transport)) + { + BufferManager.ReturnBuffer(chunk.Array, nameof(RunReceiveLoopAsync)); + return; + } - try - { - // the responses in the chunk defer the continuations of their requests - ValueTask dispatch; - ResponseContinuationDeferral.Enter(); try { - dispatch = OnChunkReceivedAsync(chunk, ct); + // the responses in the chunk defer the continuations of their requests + ValueTask dispatch; + ResponseContinuationDeferral.Enter(); + try + { + dispatch = OnChunkReceivedAsync(chunk, ct); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + await ResponseContinuationDeferral.AwaitAndComplete(dispatch); } - finally + catch (OperationCanceledException) when (ct.IsCancellationRequested) { - ResponseContinuationDeferral.Exit(); + return; + } + catch (Exception ex) + { + // Dispatching a chunk must never end the loop silently. The + // task this runs on is fire-and-forget, so an escaping + // exception would otherwise stop the channel receiving with no + // report at all, and the peer would simply time out. + OnTransportError(transport, ServiceResult.Create( + ex, + StatusCodes.BadTcpInternalError, + "An error occurred dispatching a received message."), ct); + return; } - await ResponseContinuationDeferral.AwaitAndComplete(dispatch); - } - catch (OperationCanceledException) when (ct.IsCancellationRequested) - { - return; - } - catch (Exception ex) - { - // Dispatching a chunk must never end the loop silently. The - // task this runs on is fire-and-forget, so an escaping - // exception would otherwise stop the channel receiving with no - // report at all, and the peer would simply time out. - OnTransportError(transport, ServiceResult.Create( - ex, - StatusCodes.BadTcpInternalError, - "An error occurred dispatching a received message."), ct); - return; } } + finally + { + // A completion deferred by the last chunk goes to the pool. The loop ends + // on the thread that dispatched that chunk, which holds the completion. + ResponseContinuationDeferral.CompletePending(inline: false); + } } /// diff --git a/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs b/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs index 2acc0123fa..7bbcdb98ae 100644 --- a/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs +++ b/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs @@ -112,53 +112,104 @@ public async Task CompletionsDeferredOnLoopExitRunOnThePoolAsync() [Test] [CancelAfter(10000)] - public async Task ScopeDefersAtMostSixteenCompletionsAsync() + public async Task LaterCompletionCompletesTheHeldOneOnThePoolAsync() { - var operations = new ChannelAsyncOperation[17]; - var waits = new ValueTask[operations.Length]; - for (int ii = 0; ii < operations.Length; ii++) + using var first = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + using var second = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + Task firstWaiter = ContinuationThreadAsync(first.WaitForCompletionAsync(CancellationToken.None)); + Task secondWaiter = ContinuationThreadAsync(second.WaitForCompletionAsync(CancellationToken.None)); + + ResponseContinuationDeferral.Enter(); + try + { + first.Complete(true, 1); + second.Complete(true, 2); + } + finally { - operations[ii] = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); - // each wait is awaited once, below -#pragma warning disable CA2012 - waits[ii] = operations[ii].WaitForCompletionAsync(CancellationToken.None); -#pragma warning restore CA2012 + ResponseContinuationDeferral.Exit(); } + + // the first completes on the pool without the loop suspending; waited for on + // this thread, which holds the second + Assert.That(firstWaiter.Wait(TimeSpan.FromSeconds(5)), Is.True); + Assert.That(secondWaiter.IsCompleted, Is.False, "the latest completion is held"); + + ResponseContinuationDeferral.CompletePending(inline: true); + Assert.That(secondWaiter.IsCompleted, Is.True); + Assert.That(await secondWaiter.ConfigureAwait(false), Is.EqualTo(Environment.CurrentManagedThreadId)); + } + + [Test] + [CancelAfter(10000)] + public async Task HeldCompletionGoesToThePoolAfterFourMoreChunksAsync() + { + using var operation = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + Task waiter = ContinuationThreadAsync(operation.WaitForCompletionAsync(CancellationToken.None)); + + ResponseContinuationDeferral.Enter(); try + { + operation.Complete(true, 7); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + + // chunks without responses, received without the loop suspending + for (int ii = 0; ii < 4; ii++) + { + ResponseContinuationDeferral.Enter(); + ResponseContinuationDeferral.Exit(); + } + Assert.That(waiter.IsCompleted, Is.False, "held while the loop dispatches four more chunks"); + + ResponseContinuationDeferral.Enter(); + ResponseContinuationDeferral.Exit(); + await waiter.ConfigureAwait(false); + Assert.That(operation.End(0), Is.EqualTo(7)); + ResponseContinuationDeferral.CompletePending(inline: true); + } + + /// + /// Two responses in a row: the continuation of the first blocks until the second + /// request completes, which must not wait for the blocked thread. + /// + [Test] + [CancelAfter(20000)] + public async Task ContinuationBlockingOnTheNextResponseDoesNotDeadlockAsync() + { + using var first = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + using var second = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + var receive = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Task secondWaiter = ContinuationThreadAsync(second.WaitForCompletionAsync(CancellationToken.None)); + Task firstCaller = BlockOnAsync(first.WaitForCompletionAsync(CancellationToken.None), secondWaiter); + + Task loop = Task.Run(async () => { ResponseContinuationDeferral.Enter(); try { - foreach (ChannelAsyncOperation operation in operations) - { - operation.Complete(true, 1); - } + first.Complete(true, 1); + second.Complete(true, 2); } finally { ResponseContinuationDeferral.Exit(); } + return await ResponseContinuationDeferral.AwaitAndComplete(new ValueTask(receive.Task)); + }); - for (int ii = 0; ii < 16; ii++) - { - Assert.That(waits[ii].IsCompleted, Is.False, $"wait {ii} is deferred"); - } - Assert.That(waits[16].IsCompleted, Is.True, "the 17th completion is not deferred"); + Assert.That(await firstCaller.ConfigureAwait(false), Is.True, "the second response completed"); + receive.SetResult(1); + Assert.That(await loop.ConfigureAwait(false), Is.EqualTo(1)); + } - ResponseContinuationDeferral.CompletePending(inline: true); - foreach (ValueTask wait in waits) - { - Assert.That(wait.IsCompleted, Is.True); - await wait.ConfigureAwait(false); - } - } - finally - { - foreach (ChannelAsyncOperation operation in operations) - { - operation.Dispose(); - } - } + private static async Task BlockOnAsync(ValueTask wait, Task other) + { + await wait.ConfigureAwait(false); + return other.Wait(TimeSpan.FromSeconds(5)); } /// From 2fc346cc8c582f71610670133b8a7f7c0a800196 Mon Sep 17 00:00:00 2001 From: Roman Ettlinger Date: Sat, 14 Nov 2026 11:26:47 +0100 Subject: [PATCH 4/5] Complete a held response before a receive blocks for buffer budget The next receive can rent its buffer synchronously from the process buffer budget, which blocks while the budget is exhausted. A response the receive loop thread held stayed unsignalled meanwhile, and its caller may be the one that returns the budget. The limiter now completes the response held on the calling thread on the pool before it waits for capacity. Co-Authored-By: Claude Opus 5.5 --- .../Bindings/BufferManagerMemoryLimiter.cs | 3 ++ .../ResponseContinuationDeferralTests.cs | 41 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/Opc.Ua.Core/Stack/Bindings/BufferManagerMemoryLimiter.cs b/src/Opc.Ua.Core/Stack/Bindings/BufferManagerMemoryLimiter.cs index 995e2d6a61..ca765f5ff7 100644 --- a/src/Opc.Ua.Core/Stack/Bindings/BufferManagerMemoryLimiter.cs +++ b/src/Opc.Ua.Core/Stack/Bindings/BufferManagerMemoryLimiter.cs @@ -156,6 +156,9 @@ internal long Reserve( using CapacityWaiter waiter = registration.Value; try { + // A receive loop that blocks here completes the response it holds on the + // pool first: that request's caller may be the one to return the budget. + Bindings.ResponseContinuationDeferral.CompletePending(inline: false); BeforeCapacityWaitForTesting?.Invoke(); waiter.Wait(ct); } diff --git a/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs b/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs index 7bbcdb98ae..cbb5d0cdac 100644 --- a/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs +++ b/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs @@ -206,6 +206,47 @@ public async Task ContinuationBlockingOnTheNextResponseDoesNotDeadlockAsync() Assert.That(await loop.ConfigureAwait(false), Is.EqualTo(1)); } + /// + /// A receive loop that blocks for buffer budget completes the response it holds on + /// the pool: that request's caller returns the budget the loop waits for. + /// + [Test] + [CancelAfter(20000)] + public async Task LoopBlockedOnBufferBudgetCompletesTheHeldResponseAsync() + { + using var limiter = new BufferManagerMemoryLimiter(100); + long held = limiter.Reserve(100, CancellationToken.None); + using var operation = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + Task caller = ReturnBudgetAsync(operation.WaitForCompletionAsync(CancellationToken.None), limiter, held); + + Task loop = Task.Run(() => + { + ResponseContinuationDeferral.Enter(); + try + { + operation.Complete(true, 7); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + // the next receive rents a buffer from the exhausted budget + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + long next = limiter.Reserve(50, timeout.Token); + limiter.Cancel(next); + }); + + await loop.ConfigureAwait(false); + await caller.ConfigureAwait(false); + Assert.That(operation.End(0), Is.EqualTo(7)); + } + + private static async Task ReturnBudgetAsync(ValueTask wait, BufferManagerMemoryLimiter limiter, long reservation) + { + await wait.ConfigureAwait(false); + limiter.Cancel(reservation); + } + private static async Task BlockOnAsync(ValueTask wait, Task other) { await wait.ConfigureAwait(false); From 47321b237babe57e79f27a6116c040cf80e3005a Mon Sep 17 00:00:00 2001 From: Roman Ettlinger Date: Sat, 14 Nov 2026 14:13:50 +0100 Subject: [PATCH 5/5] Complete a response deferred inside an inline continuation on the pool A continuation the receive loop's thread runs inline can complete the loop's receive synchronously (a source without asynchronous continuations, as with an in-process peer). The loop then resumes on that stack, defers the next response and, when it suspends, ran that one inline too, nested in the first: a second continuation that waited for the first never returned. The thread now counts its inline completions, and a loop that suspends inside one completes its response on the pool. Co-Authored-By: Claude Opus 5.5 --- .../Stack/Tcp/ResponseContinuationDeferral.cs | 19 ++++- .../ResponseContinuationDeferralTests.cs | 69 +++++++++++++++++++ 2 files changed, 87 insertions(+), 1 deletion(-) diff --git a/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs b/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs index c63a333f4f..2f1feba097 100644 --- a/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs +++ b/src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs @@ -146,6 +146,10 @@ public static void CompletePending(bool inline) t_pending = null; int depth = t_depth; t_depth = 0; + if (inline) + { + t_inline++; + } try { pending.CompleteDeferredWait(inline); @@ -153,6 +157,10 @@ public static void CompletePending(bool inline) finally { t_depth = depth; + if (inline) + { + t_inline--; + } } } @@ -161,11 +169,17 @@ public static void CompletePending(bool inline) /// unless the loop ran inside the dispatch of another loop on this thread, which /// may hold locks: that loop completes it when it suspends. /// + /// + /// A loop can also resume inside a continuation this thread runs inline, when that + /// continuation completes the loop's receive synchronously. The wait it deferred + /// then completes on the pool: run inline as well, its continuation would be + /// nested in the first and could wait for it forever. + /// private static void CompleteOnSuspended() { if (t_depth == 0) { - CompletePending(inline: true); + CompletePending(inline: t_inline == 0); } } @@ -273,5 +287,8 @@ public void UnsafeOnCompleted(Action continuation) [ThreadStatic] private static int t_depth; + + [ThreadStatic] + private static int t_inline; } } diff --git a/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs b/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs index cbb5d0cdac..672c91a2eb 100644 --- a/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs +++ b/tests/Opc.Ua.Core.Tests/Stack/Transport/ResponseContinuationDeferralTests.cs @@ -241,6 +241,75 @@ public async Task LoopBlockedOnBufferBudgetCompletesTheHeldResponseAsync() Assert.That(operation.End(0), Is.EqualTo(7)); } + /// + /// An inline continuation completes the loop's receive synchronously, so the loop + /// resumes on its stack and defers the next response. That one completes on the + /// pool: run nested inline, it would wait for the first continuation forever. + /// + [Test] + [CancelAfter(20000)] + public async Task LoopResumedInsideAnInlineContinuationDoesNotNestTheNextAsync() + { + using var first = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + using var second = new ChannelAsyncOperation(int.MaxValue, null, null, m_logger); + // continuations of a default source run synchronously, as with an in-process peer + var firstReceive = new TaskCompletionSource(); + var secondReceive = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var firstDone = new ManualResetEventSlim(); + + Task firstCaller = CompleteReceiveAsync( + first.WaitForCompletionAsync(CancellationToken.None), firstReceive, firstDone); + Task secondCaller = WaitForEventAsync( + second.WaitForCompletionAsync(CancellationToken.None), firstDone); + + Task loop = Task.Run(async () => + { + ResponseContinuationDeferral.Enter(); + try + { + first.Complete(true, 1); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + await ResponseContinuationDeferral.AwaitAndComplete(new ValueTask(firstReceive.Task)); + + // resumed inside the first caller's continuation + ResponseContinuationDeferral.Enter(); + try + { + second.Complete(true, 2); + } + finally + { + ResponseContinuationDeferral.Exit(); + } + return await ResponseContinuationDeferral.AwaitAndComplete(new ValueTask(secondReceive.Task)); + }); + + await firstCaller.ConfigureAwait(false); + Assert.That(await secondCaller.ConfigureAwait(false), Is.True, "the first caller finished"); + secondReceive.SetResult(3); + Assert.That(await loop.ConfigureAwait(false), Is.EqualTo(3)); + } + + private static async Task CompleteReceiveAsync( + ValueTask wait, + TaskCompletionSource receive, + ManualResetEventSlim done) + { + await wait.ConfigureAwait(false); + receive.SetResult(1); + done.Set(); + } + + private static async Task WaitForEventAsync(ValueTask wait, ManualResetEventSlim done) + { + await wait.ConfigureAwait(false); + return done.Wait(TimeSpan.FromSeconds(5)); + } + private static async Task ReturnBudgetAsync(ValueTask wait, BufferManagerMemoryLimiter limiter, long reservation) { await wait.ConfigureAwait(false);