perf(workers): reuse the pre-check envelope size when framing; count pre-reply command failures (WRK-010, WRK-007, #256)

This commit is contained in:
Joseph Doherty
2026-12-03 09:51:12 -05:00
parent 16d9cc708b
commit 78bfc1b8a3
4 changed files with 172 additions and 10 deletions
@@ -24,7 +24,7 @@ public sealed class WorkerClient : IWorkerClient
private readonly ILogger<WorkerClient> _logger;
private readonly WorkerFrameReader _reader;
private readonly WorkerFrameWriter _writer;
private readonly Channel<WorkerEnvelope> _outboundEnvelopes;
private readonly Channel<OutboundEnvelope> _outboundEnvelopes;
private readonly Channel<WorkerEvent> _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<WorkerEnvelope>(
_outboundEnvelopes = Channel.CreateBounded<OutboundEnvelope>(
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
/// </summary>
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);
/// <summary>Manages writing envelopes to the worker pipe.</summary>
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
/// <summary>Enqueues an envelope for writing to the worker.</summary>
/// <param name="envelope">Envelope to enqueue.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="sizeBeforeSequence">
/// The envelope's <c>CalculateSize()</c> while its sequence was still unset, or -1 when not measured.
/// </param>
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)
{
@@ -32,14 +32,36 @@ public sealed class WorkerFrameWriter
/// <param name="envelope">Worker envelope message to write.</param>
/// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public ValueTask WriteAsync(
WorkerEnvelope envelope,
CancellationToken cancellationToken = default) =>
WriteAsync(envelope, sizeBeforeSequence: -1, cancellationToken);
/// <summary>
/// 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.
/// </summary>
/// <param name="envelope">Worker envelope message to write.</param>
/// <param name="sizeBeforeSequence">
/// <c>envelope.CalculateSize()</c> as measured while <see cref="WorkerEnvelope.Sequence"/> 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 <c>Sequence</c> changed after the
/// measurement; <c>WriteTo</c> fails loudly (it checks the buffer is filled exactly) rather than
/// emitting a wrong length prefix if that is ever violated.
/// </param>
/// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
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<byte>.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);
}
@@ -162,6 +162,83 @@ public sealed class WorkerClientTests
Assert.Equal(WorkerClientState.Ready, client.State);
}
/// <summary>
/// WRK-007: a command rejected before it reaches the worker (here <c>CommandTooLarge</c>) is counted
/// as started and as failed, so <c>commands.started</c> does not climb without a terminal counter.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<WorkerClientException>(
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);
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<WorkerCommandReply> 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);
}
}
/// <summary>Verifies that InvokeAsync ignores late replies and keeps the client ready.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
@@ -29,6 +29,34 @@ public sealed class WorkerFrameProtocolTests
Assert.Equal(original, parsed);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="sequence">The sequence stamped after the pre-stamp size was measured.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[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());
}
/// <summary>Verifies that a large payload near the message cap round-trips through the pooled write/read path.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]