From 16d9cc708b7a829f99294b1d69170303c8de0554 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:49:22 -0500 Subject: [PATCH] perf(sessions): check readiness before expanding a sparse write; share one default Timestamp (SES-008, #256) --- .../Sessions/GatewaySession.cs | 5 +- .../Sessions/SparseArrayExpander.cs | 9 +++- .../Sessions/GatewayArrayWriteWiringTests.cs | 47 +++++++++++++++++++ .../Sessions/SparseArrayExpanderTests.cs | 18 +++++++ 4 files changed, 77 insertions(+), 2 deletions(-) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs index 9f8da1d5..6f7968e2 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs @@ -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); diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SparseArrayExpander.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SparseArrayExpander.cs index ec38ce7b..cbd1416b 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SparseArrayExpander.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SparseArrayExpander.cs @@ -26,6 +26,10 @@ namespace ZB.MOM.WW.MxGateway.Server.Sessions; /// 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 }; + /// /// Replaces 's with an /// equivalent full . If 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) diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewayArrayWriteWiringTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewayArrayWriteWiringTests.cs index 8236226c..5a863611 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewayArrayWriteWiringTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewayArrayWriteWiringTests.cs @@ -144,6 +144,53 @@ public sealed class GatewayArrayWriteWiringTests Assert.Equal(new[] { 0, 7, 0, 0 }, forwarded.ArrayValue.Int32Values.Values); } + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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( + () => session.InvokeAsync(command, CancellationToken.None)); + + Assert.Equal(SessionManagerErrorCode.SessionNotReady, exception.ErrorCode); + Assert.Equal(MxValue.KindOneofCase.SparseArrayValue, value.KindCase); + } + /// /// A bare array AddItem2 address is normalized to its writable array form on the wire, /// and the normalized address lands in the tracked . diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SparseArrayExpanderTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SparseArrayExpanderTests.cs index 8a658c4d..1f92e3e6 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SparseArrayExpanderTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SparseArrayExpanderTests.cs @@ -143,6 +143,24 @@ public sealed class SparseArrayExpanderTests Assert.Equal(5, value.ArrayValue.TimestampValues.Values[1].Seconds); } + /// SES-008: unspecified Time slots share one default instance instead of allocating one each. + [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 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); + } + /// Verifies that expanding a Double sparse array fills defaults and applies the given element. [Fact] public void Expand_Double_HappyPath()