perf(sessions): check readiness before expanding a sparse write; share one default Timestamp (SES-008, #256)

This commit is contained in:
Joseph Doherty
2026-12-03 09:49:22 -05:00
parent 09da8063a9
commit 16d9cc708b
4 changed files with 77 additions and 2 deletions
@@ -1527,12 +1527,15 @@ public sealed class GatewaySession : IAsyncDisposable
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(command);
// Readiness first: expanding a sparse array write allocates a whole array, so a session that
// cannot take the command must fail before that cost is paid (SES-008).
IWorkerClient workerClient = await GetReadyWorkerClientAsync(cancellationToken).ConfigureAwait(false);
if (command.Command is not null)
{
NormalizeOutboundCommand(command.Command);
}
IWorkerClient workerClient = await GetReadyWorkerClientAsync(cancellationToken).ConfigureAwait(false);
TouchClientActivity(_eventStreaming.TimeProvider.GetUtcNow());
return await workerClient.InvokeAsync(command, CommandTimeout, cancellationToken).ConfigureAwait(false);
@@ -26,6 +26,10 @@ namespace ZB.MOM.WW.MxGateway.Server.Sessions;
/// </remarks>
internal static class SparseArrayExpander
{
// Shared filler for unspecified Time slots. Timestamp is a mutable protobuf type, so this must
// never be handed to code that edits array elements in place; the expanded value is serialized only.
private static readonly Timestamp DefaultTimestamp = new() { Seconds = 0, Nanos = 0 };
/// <summary>
/// Replaces <paramref name="value"/>'s <see cref="MxValue.SparseArrayValue"/> with an
/// equivalent full <see cref="MxValue.ArrayValue"/>. If <paramref name="value"/> is not
@@ -231,9 +235,12 @@ internal static class SparseArrayExpander
{
TimestampArray values = new();
values.Values.Capacity = length;
// One shared default instance for every unspecified slot: the expanded array is only
// serialized, never mutated in place, and a distinct Timestamp per slot cost a million
// objects for a request of a few dozen bytes (SES-008).
for (int i = 0; i < length; i++)
{
values.Values.Add(new Timestamp { Seconds = 0, Nanos = 0 });
values.Values.Add(DefaultTimestamp);
}
foreach (MxSparseElement element in elements)
@@ -144,6 +144,53 @@ public sealed class GatewayArrayWriteWiringTests
Assert.Equal(new[] { 0, 7, 0, 0 }, forwarded.ArrayValue.Int32Values.Values);
}
/// <summary>
/// SES-008: a sparse write to a session that cannot take commands fails on readiness before the
/// sparse value is expanded, so a not-ready session never pays for the whole-array allocation.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Write_SparseArrayValue_ToNotReadySession_FailsWithoutExpanding()
{
GatewaySession session = new(
sessionId: "session-not-ready",
backendName: "mxaccess",
pipeName: "mxaccess-gateway-1-session-not-ready",
nonce: "nonce",
clientIdentity: "client-1",
ownerKeyId: null,
clientSessionName: "test-session",
clientCorrelationId: "client-correlation-1",
commandTimeout: TimeSpan.FromSeconds(5),
startupTimeout: TimeSpan.FromSeconds(5),
shutdownTimeout: TimeSpan.FromSeconds(5),
leaseDuration: TimeSpan.FromMinutes(30),
openedAt: DateTimeOffset.UtcNow,
addressNormalizer: CreateNormalizer());
MxValue value = new()
{
SparseArrayValue = new MxSparseArray
{
ElementDataType = MxDataType.Time,
TotalLength = 1_000_000,
},
};
WorkerCommand command = new()
{
Command = new MxCommand
{
Kind = MxCommandKind.Write,
Write = new WriteCommand { ServerHandle = 1, ItemHandle = 42, Value = value },
},
};
SessionManagerException exception = await Assert.ThrowsAsync<SessionManagerException>(
() => session.InvokeAsync(command, CancellationToken.None));
Assert.Equal(SessionManagerErrorCode.SessionNotReady, exception.ErrorCode);
Assert.Equal(MxValue.KindOneofCase.SparseArrayValue, value.KindCase);
}
/// <summary>
/// A bare array <c>AddItem2</c> address is normalized to its writable array form on the wire,
/// and the normalized address lands in the tracked <see cref="SessionItemRegistration"/>.
@@ -143,6 +143,24 @@ public sealed class SparseArrayExpanderTests
Assert.Equal(5, value.ArrayValue.TimestampValues.Values[1].Seconds);
}
/// <summary>SES-008: unspecified Time slots share one default instance instead of allocating one each.</summary>
[Fact]
public void Expand_Time_UnspecifiedSlotsShareOneDefaultInstance()
{
MxValue value = SparseValue(
MxDataType.Time,
100_000,
(3, new MxValue { TimestampValue = new Timestamp { Seconds = 9 } }));
SparseArrayExpander.Expand(value);
IList<Timestamp> slots = value.ArrayValue.TimestampValues.Values;
Assert.Equal(100_000, slots.Count);
Assert.Equal(9, slots[3].Seconds);
Assert.Same(slots[0], slots[99_999]);
Assert.Equal(0, slots[0].Seconds);
}
/// <summary>Verifies that expanding a Double sparse array fills defaults and applies the given element.</summary>
[Fact]
public void Expand_Double_HappyPath()