From 78bfc1b8a3b93a6301c64c3ec2a28a73adb9eb98 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:51:12 -0500 Subject: [PATCH] perf(workers): reuse the pre-check envelope size when framing; count pre-reply command failures (WRK-010, WRK-007, #256) --- .../Workers/WorkerClient.cs | 45 ++++++++--- .../Workers/WorkerFrameWriter.cs | 32 +++++++- .../Gateway/Workers/WorkerClientTests.cs | 77 +++++++++++++++++++ .../Workers/WorkerFrameProtocolTests.cs | 28 +++++++ 4 files changed, 172 insertions(+), 10 deletions(-) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs index 0f05317c..32680b81 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs @@ -24,7 +24,7 @@ public sealed class WorkerClient : IWorkerClient private readonly ILogger _logger; private readonly WorkerFrameReader _reader; private readonly WorkerFrameWriter _writer; - private readonly Channel _outboundEnvelopes; + private readonly Channel _outboundEnvelopes; private readonly Channel _events; // Staging hand-off between the read loop and the dedicated event writer. The read loop writes @@ -88,7 +88,7 @@ public sealed class WorkerClient : IWorkerClient _reader = new WorkerFrameReader(connection.Stream, connection.FrameOptions); _writer = new WorkerFrameWriter(connection.Stream, connection.FrameOptions); _pendingCommandSlots = new SemaphoreSlim(_options.MaxPendingCommands, _options.MaxPendingCommands); - _outboundEnvelopes = Channel.CreateBounded( + _outboundEnvelopes = Channel.CreateBounded( new BoundedChannelOptions(_options.MaxPendingCommands + 4) { SingleReader = true, @@ -287,7 +287,9 @@ public sealed class WorkerClient : IWorkerClient + $"{MaxSequenceEncodingBytes}-byte sequence-stamp allowance."); } - await EnqueueAsync(commandEnvelope, cancellationToken).ConfigureAwait(false); + // envelopeSize rides along so the write loop does not walk the whole command graph again + // to size the frame (it adds the exact sequence-stamp bytes instead). + await EnqueueAsync(commandEnvelope, cancellationToken, envelopeSize).ConfigureAwait(false); // one pooled timer instead of a linked CTS + Task.Delay + WhenAny per command. // Task.WaitAsync arms a TimerQueueTimer on the shared timer queue and cancels it when the @@ -352,11 +354,26 @@ public sealed class WorkerClient : IWorkerClient throw; } } - catch + catch (Exception exception) { + // Reached with the entry still present only for exits that never got a reply: the + // CommandTooLarge rejection, a failed enqueue, or cancellation during the enqueue. Every + // other exit (reply, timeout, wait cancellation, worker fault) already removed the entry + // and recorded its own terminal metric, so the removal below is what keeps this from + // double-counting. Without it commands.started climbed with no matching terminal counter. if (_pendingCommands.TryRemove(correlationId, out _)) { ReleasePendingCommandSlot(); + string category = exception switch + { + WorkerClientException workerException => workerException.ErrorCode.ToString(), + OperationCanceledException => WorkerClientErrorCode.CallerCancelled.ToString(), + _ => exception.GetType().Name, + }; + _metrics?.CommandFailed( + pendingCommand.Method, + category, + _timeProvider.GetElapsedTime(pendingCommand.StartTimestamp)); } throw; @@ -543,13 +560,19 @@ public sealed class WorkerClient : IWorkerClient /// private const int MaxSequenceEncodingBytes = 11; + // An envelope queued for the write loop, with the size measured by the CommandTooLarge pre-check + // (-1 when the envelope was not measured). Carrying it spares the writer a second walk of the + // whole message graph per command. + private readonly record struct OutboundEnvelope(WorkerEnvelope Envelope, int SizeBeforeSequence); + /// Manages writing envelopes to the worker pipe. private async Task WriteLoopAsync() { try { - await foreach (WorkerEnvelope envelope in _outboundEnvelopes.Reader.ReadAllAsync(_stopCts.Token).ConfigureAwait(false)) + await foreach (OutboundEnvelope outbound in _outboundEnvelopes.Reader.ReadAllAsync(_stopCts.Token).ConfigureAwait(false)) { + WorkerEnvelope envelope = outbound.Envelope; // stamp the sequence at the point of writing, not when the envelope is built. // Stamping at construction let two concurrent InvokeAsync callers take 1 and 2 and then // enqueue in the order 2, 1 — non-monotonic on the wire, breaking gateway.md's @@ -557,7 +580,7 @@ public sealed class WorkerClient : IWorkerClient // (SingleReader = true), so wire order and stamp order are the same thing here and // _nextSequence needs no interlocking. Mirrors the worker's equivalent fix. envelope.Sequence = unchecked(++_nextSequence); - await _writer.WriteAsync(envelope, _stopCts.Token).ConfigureAwait(false); + await _writer.WriteAsync(envelope, outbound.SizeBeforeSequence, _stopCts.Token).ConfigureAwait(false); } } catch (OperationCanceledException) when (_stopCts.IsCancellationRequested || IsTerminalState()) @@ -980,7 +1003,7 @@ public sealed class WorkerClient : IWorkerClient Reason = reason, }); - if (_outboundEnvelopes.Writer.TryWrite(cancelEnvelope)) + if (_outboundEnvelopes.Writer.TryWrite(new OutboundEnvelope(cancelEnvelope, -1))) { return; } @@ -1364,13 +1387,17 @@ public sealed class WorkerClient : IWorkerClient /// Enqueues an envelope for writing to the worker. /// Envelope to enqueue. /// Cancellation token. + /// + /// The envelope's CalculateSize() while its sequence was still unset, or -1 when not measured. + /// private async Task EnqueueAsync( WorkerEnvelope envelope, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + int sizeBeforeSequence = -1) { try { - await _outboundEnvelopes.Writer.WriteAsync(envelope, cancellationToken).ConfigureAwait(false); + await _outboundEnvelopes.Writer.WriteAsync(new OutboundEnvelope(envelope, sizeBeforeSequence), cancellationToken).ConfigureAwait(false); } catch (ChannelClosedException exception) { diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameWriter.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameWriter.cs index a7f1cf43..ad71dd93 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameWriter.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameWriter.cs @@ -32,14 +32,36 @@ public sealed class WorkerFrameWriter /// Worker envelope message to write. /// Token to cancel the asynchronous operation. /// A task that represents the asynchronous operation. + public ValueTask WriteAsync( + WorkerEnvelope envelope, + CancellationToken cancellationToken = default) => + WriteAsync(envelope, sizeBeforeSequence: -1, cancellationToken); + + /// + /// Writes a WorkerEnvelope as a length-prefixed message, reusing a size the caller already + /// computed so the writer does not walk the whole message graph a second time. + /// + /// Worker envelope message to write. + /// + /// envelope.CalculateSize() as measured while was still + /// 0, or a negative value when no size is known. The writer adds the exact encoded size of the + /// sequence stamp applied since. Only valid when nothing but Sequence changed after the + /// measurement; WriteTo fails loudly (it checks the buffer is filled exactly) rather than + /// emitting a wrong length prefix if that is ever violated. + /// + /// Token to cancel the asynchronous operation. + /// A task that represents the asynchronous operation. public async ValueTask WriteAsync( WorkerEnvelope envelope, + int sizeBeforeSequence, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(envelope); WorkerEnvelopeValidator.Validate(envelope, _options); - int payloadLength = envelope.CalculateSize(); + int payloadLength = sizeBeforeSequence >= 0 + ? sizeBeforeSequence + SequenceStampSize(envelope.Sequence) + : envelope.CalculateSize(); if (payloadLength == 0) { throw new WorkerFrameProtocolException( @@ -75,4 +97,12 @@ public sealed class WorkerFrameWriter ArrayPool.Shared.Return(frame); } } + + // Bytes the sequence field adds to an envelope that was measured with Sequence == 0 (an unset + // proto3 scalar is not encoded): its tag plus the varint of the stamped value. + private static int SequenceStampSize(ulong sequence) => + sequence == 0 + ? 0 + : CodedOutputStream.ComputeTagSize(WorkerEnvelope.SequenceFieldNumber) + + CodedOutputStream.ComputeUInt64Size(sequence); } 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 789cb5c3..baeebfdc 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs @@ -162,6 +162,83 @@ public sealed class WorkerClientTests Assert.Equal(WorkerClientState.Ready, client.State); } + /// + /// WRK-007: a command rejected before it reaches the worker (here CommandTooLarge) is counted + /// as started and as failed, so commands.started does not climb without a terminal counter. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task InvokeAsync_WhenCommandExceedsFrameMax_RecordsOneFailedCommand() + { + await using PipePair pipePair = await PipePair.CreateAsync(); + using GatewayMetrics metrics = new(); + await using WorkerClient client = CreateClient(pipePair, metrics: metrics, maxMessageBytes: 4096); + await CompleteHandshakeAsync(client, pipePair); + + WorkerCommand oversized = new() + { + Command = new MxCommand + { + Kind = MxCommandKind.Write, + Write = new WriteCommand + { + ServerHandle = 1, + ItemHandle = 2, + Value = new MxValue { StringValue = new string('x', 8192) }, + }, + }, + }; + + await Assert.ThrowsAsync( + async () => await client.InvokeAsync(oversized, TestTimeout, CancellationToken.None)); + + GatewayMetricsSnapshot snapshot = metrics.GetSnapshot(); + Assert.Equal(1, snapshot.CommandsStarted); + Assert.Equal(1, snapshot.CommandsFailed); + Assert.Equal(0, snapshot.CommandsSucceeded); + } + + /// + /// WRK-010: the write loop sizes a command frame from the pre-check's measurement plus the exact + /// sequence-stamp bytes, and the frame on the wire still parses to the stamped envelope. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task InvokeAsync_LargeCommand_FramesCorrectlyAfterSequenceStamp() + { + await using PipePair pipePair = await PipePair.CreateAsync(); + await using WorkerClient client = CreateClient(pipePair); + await CompleteHandshakeAsync(client, pipePair); + + string payload = new('y', 70_000); + for (int attempt = 0; attempt < 3; attempt++) + { + Task invoke = client.InvokeAsync( + new WorkerCommand + { + Command = new MxCommand + { + Kind = MxCommandKind.Write, + Write = new WriteCommand + { + ServerHandle = 1, + ItemHandle = 2, + Value = new MxValue { StringValue = payload }, + }, + }, + }, + TestTimeout, + CancellationToken.None); + + WorkerEnvelope onWire = await pipePair.WorkerReader.ReadAsync().AsTask().WaitAsync(TestTimeout); + Assert.Equal(payload, onWire.WorkerCommand.Command.Write.Value.StringValue); + Assert.True(onWire.Sequence > 0); + + await pipePair.WriteAsync(CreateCommandReplyEnvelope(onWire.CorrelationId, MxCommandKind.Write)); + await invoke.WaitAsync(TestTimeout); + } + } + /// Verifies that InvokeAsync ignores late replies and keeps the client ready. /// A task that represents the asynchronous operation. [Fact] diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerFrameProtocolTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerFrameProtocolTests.cs index ea92ded0..c8da5a59 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerFrameProtocolTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerFrameProtocolTests.cs @@ -29,6 +29,34 @@ public sealed class WorkerFrameProtocolTests Assert.Equal(original, parsed); } + /// + /// WRK-010: writing with a size measured before the sequence stamp produces byte-identical frames + /// to the writer's own measurement, across sequence values whose varints differ in length. + /// + /// The sequence stamped after the pre-stamp size was measured. + /// A task that represents the asynchronous operation. + [Theory] + [InlineData(1UL)] + [InlineData(127UL)] + [InlineData(128UL)] + [InlineData(16384UL)] + [InlineData(ulong.MaxValue)] + public async Task WriteAsync_WithSizeMeasuredBeforeTheSequenceStamp_MatchesTheWritersOwnFrame(ulong sequence) + { + WorkerFrameProtocolOptions options = new(SessionId); + WorkerEnvelope envelope = CreateEnvelope(); + envelope.Sequence = 0; + int sizeBeforeSequence = envelope.CalculateSize(); + envelope.Sequence = sequence; + + await using MemoryStream known = new(); + await new WorkerFrameWriter(known, options).WriteAsync(envelope, sizeBeforeSequence); + await using MemoryStream measured = new(); + await new WorkerFrameWriter(measured, options).WriteAsync(envelope); + + Assert.Equal(measured.ToArray(), known.ToArray()); + } + /// Verifies that a large payload near the message cap round-trips through the pooled write/read path. /// A task that represents the asynchronous operation. [Fact]