diff --git a/docs/GatewayProcessDesign.md b/docs/GatewayProcessDesign.md index 2c73c2ad..e9c5aefa 100644 --- a/docs/GatewayProcessDesign.md +++ b/docs/GatewayProcessDesign.md @@ -566,6 +566,43 @@ The worker event queue-depth gauge (`mxgateway.events.worker_queue.depth`) is incremented at staging and decremented at consumer read, so it reports total undelivered events across both channels rather than only the inbound channel. +### Event path threading + +The staging channel and the inbound event channel are both created with +`AllowSynchronousContinuations = true` (mxaccessgw#235). The read loop's staging +`TryWrite` resumes the event write loop inline, whose `TryWrite` into the +inbound channel resumes the session's distributor pump inline. In the steady +state an event therefore travels from the pipe read to the per-subscriber +channels on one thread, instead of costing two thread-pool work items. At +~240 events/s each of those work items ended in a thread-pool spin-wait, which +was most of the gateway's context-switch rate. + +This is safe because everything that can run inline is bounded and +non-blocking: + +- The event write loop either moves the event into the inbound channel or, when + that channel is full, parks in its timed `WriteAsync`. The park is an await, so + control returns to the read loop at once and staging absorbs further events + exactly as before. The two overflow faults are unchanged. +- The pump maps the event, appends it to the replay ring under a short lock, and + fans out with `TryWrite`. Subscriber channels keep + `AllowSynchronousContinuations = false`, so no gRPC write, dashboard publish, + alarm reconcile or other consumer code ever runs on the read loop; each + consumer still resumes on the pool. A subscriber overflow runs the overflow + handler (a metric, at most a session state flip, and a log line) inline. +- Channel completion also runs inline. `MarkClosed`, `SetFaulted` and + `DisposeAsync` complete the channels after releasing `_syncRoot`, and no caller + holds a session or distributor lock, so the pump's final sweep and + `ObserveWorkerTerminalState` run on the completing thread without lock + inversion. Previously that work ran on the pool at an unspecified later point. +- The reverse direction is bounded too: when the pump frees space in a full + inbound channel, the parked event writer resumes on the pump's thread, drains + what staging holds into the inbound channel, and awaits again. + +The constraint this imposes is that the sole `WorkerClient.ReadEventsAsync` +consumer must not block synchronously inside its loop body. The distributor +pump is the only production consumer and the channel is single-reader. + ### Write loop The write loop serializes all writes to the pipe. No other code should write to diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/IWorkerClient.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/IWorkerClient.cs index 26facf4e..88b9fcf1 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/IWorkerClient.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/IWorkerClient.cs @@ -54,6 +54,14 @@ public interface IWorkerClient : IAsyncDisposable CancellationToken cancellationToken); /// Reads events from the worker as they arrive. + /// + /// The production client resumes this enumeration inline on the thread that received the + /// event — normally the pipe read loop — to avoid a thread-pool hop per event. The consumer + /// must therefore never block synchronously inside its loop body; awaiting genuinely + /// asynchronous work is fine, because the await hands the thread back. The only production + /// consumer is the session's event distributor pump, which maps, retains and fans out with + /// non-blocking writes. + /// /// Token to cancel the asynchronous operation. /// An asynchronous stream of worker events. IAsyncEnumerable ReadEventsAsync(CancellationToken cancellationToken); diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs index 71d3aebc..0f05317c 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs @@ -108,7 +108,17 @@ public sealed class WorkerClient : IWorkerClient SingleReader = true, SingleWriter = true, FullMode = BoundedChannelFullMode.Wait, - AllowSynchronousContinuations = false, + // Synchronous continuations remove a thread-pool hop per event (mxaccessgw#235): + // the event writer's TryWrite resumes the distributor pump inline, so mapping, + // replay append and fan-out run on the thread that staged the event — normally the + // pipe read loop. That is safe only because everything the pump does inline is + // bounded and non-blocking: it maps the event, appends to the replay ring under a + // short lock, and fans out with TryWrite into subscriber channels that keep + // AllowSynchronousContinuations = false. No gRPC write, SignalR send, alarm + // reconcile or other consumer code can therefore run on the read loop; each + // consumer still resumes on the pool. docs/GatewayProcessDesign.md ("Event path threading") + // has the full argument, including what runs inline on channel completion. + AllowSynchronousContinuations = true, }); _eventStagingCapacity = checked(2 * _options.EventChannelCapacity); _eventStaging = Channel.CreateBounded( @@ -121,7 +131,11 @@ public sealed class WorkerClient : IWorkerClient // when the bound is reached — the same Wait+TryWrite overflow-detection idiom the // session event distributor uses. The read loop never awaits this channel. FullMode = BoundedChannelFullMode.Wait, - AllowSynchronousContinuations = false, + // The read loop's TryWrite resumes EventWriteLoopAsync inline, which moves the + // event straight into _events (and, through that channel, runs the pump inline). + // When _events is full the writer parks in its timed WriteAsync and control + // returns to the read loop at once, so the read loop still never waits on events. + AllowSynchronousContinuations = true, }); _eventQueueDepthRegistration = _metrics?.RegisterWorkerEventQueueDepthSource( () => Volatile.Read(ref _eventQueueDepth)); @@ -726,14 +740,18 @@ public sealed class WorkerClient : IWorkerClient _metrics?.EventReceived(SessionId, MxEventFamilyNames.Get(workerEvent.Event.Family)); } + // Counted here rather than at the _events write so the single gauge reports total + // undelivered events (staged + queued). ReadEventsCoreAsync decrements on consumer read. + // The increment comes BEFORE the TryWrite because the write runs the consumer inline + // (synchronous continuations), so the decrement can happen inside TryWrite; counting + // afterwards would let a scrape observe -1. + Interlocked.Increment(ref _eventQueueDepth); if (_eventStaging.Writer.TryWrite(workerEvent)) { - // Counted here rather than at the _events write so the single gauge reports total - // undelivered events (staged + queued). ReadEventsCoreAsync decrements on consumer read. - Interlocked.Increment(ref _eventQueueDepth); return; } + Interlocked.Decrement(ref _eventQueueDepth); if (IsTerminalState()) { // Shutdown completed the staging channel; dropping the event is the documented behavior. diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs index 40682d17..789cb5c3 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs @@ -555,6 +555,68 @@ public sealed class WorkerClientTests Assert.Equal(WorkerClientState.Ready, client.State); } + /// + /// The worker event channels use synchronous continuations (mxaccessgw#235), so the + /// consumer resumes inline on the read loop. A + /// consumer whose loop body awaits real asynchronous work must hand the thread back at that + /// await, so command replies arriving behind the event still dispatch promptly and later + /// events keep their pipe order. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ReadLoop_WhenEventConsumerAwaitsSlowWork_DispatchesCommandReplyWithoutBlocking() + { + await using PipePair pipePair = await PipePair.CreateAsync(); + await using WorkerClient client = CreateClient(pipePair); + await CompleteHandshakeAsync(client, pipePair); + using CancellationTokenSource cancellationTokenSource = new(TestTimeout); + + TaskCompletionSource releaseConsumer = new(TaskCreationOptions.RunContinuationsAsynchronously); + TaskCompletionSource firstEventSeen = new(TaskCreationOptions.RunContinuationsAsynchronously); + List sequences = []; + Task consumer = Task.Run(async () => + { + await foreach (WorkerEvent workerEvent in client.ReadEventsAsync(cancellationTokenSource.Token)) + { + sequences.Add(workerEvent.Event.WorkerSequence); + if (sequences.Count == 1) + { + firstEventSeen.TrySetResult(); + + // Parks the consumer mid-loop on genuinely asynchronous work. + await releaseConsumer.Task; + } + + if (sequences.Count == 3) + { + return; + } + } + }); + + await pipePair.WriteAsync(CreateEventEnvelope(sequence: 11, MxEventFamily.OnDataChange)); + await firstEventSeen.Task.WaitAsync(TestTimeout); + await pipePair.WriteAsync(CreateEventEnvelope(sequence: 12, MxEventFamily.OnDataChange)); + + Task invokeTask = client.InvokeAsync( + CreateCommand(MxCommandKind.Ping), + TestTimeout, + CancellationToken.None); + WorkerEnvelope commandEnvelope = await pipePair.WorkerReader.ReadAsync().AsTask().WaitAsync(TestTimeout); + await pipePair.WriteAsync( + CreateCommandReplyEnvelope(commandEnvelope.CorrelationId, MxCommandKind.Ping)); + + WorkerCommandReply reply = await invokeTask.WaitAsync(TestTimeout); + Assert.Equal(MxCommandKind.Ping, reply.Reply.Kind); + + await pipePair.WriteAsync(CreateEventEnvelope(sequence: 13, MxEventFamily.OnDataChange)); + releaseConsumer.TrySetResult(); + await consumer.WaitAsync(TestTimeout); + + Assert.Equal([11UL, 12UL, 13UL], sequences); + Assert.Equal(WorkerClientState.Ready, client.State); + } + /// /// Verifies that when the client faults it kills the owned worker process. /// The assertion waits on , which