From 0967fe07309c52943522f3f8f1db5e2a051855a1 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 13:08:29 -0500 Subject: [PATCH] perf(sessions): bound a sparse array write by the worker command limit before expanding it (SES-008, #258) IWorkerClient gains MaxCommandBytes (the negotiated frame maximum less the sequence-stamp allowance, the bound its CommandTooLarge pre-check uses). GatewaySession passes it as a byte budget into SparseArrayExpander, which charges a lower bound of each expanded array's encoding (default-valued slots) before allocating, so an oversized sparse write - or a bulk command whose sparse values together overrun the frame - is rejected with InvalidArgument without the million-slot allocation. --- docs/GatewayConfiguration.md | 2 +- gateway.md | 6 ++ .../Sessions/GatewaySession.cs | 34 ++++++----- .../Sessions/SparseArrayExpander.cs | 51 ++++++++++++++++ .../Workers/IWorkerClient.cs | 9 +++ .../Workers/WorkerClient.cs | 3 + .../Sessions/GatewayArrayWriteWiringTests.cs | 38 ++++++++++++ .../Sessions/SparseArrayExpanderTests.cs | 59 +++++++++++++++++++ 8 files changed, 187 insertions(+), 15 deletions(-) diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md index 900d62fa..494da662 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -205,7 +205,7 @@ All numeric session options must be greater than zero. | `MxGateway:Events:ReplayBufferCapacity` | `1024` | Maximum number of events retained per session in the replay ring buffer, used to re-deliver events a returning subscriber missed (reconnect/reattach). The oldest retained event is evicted once this count is exceeded. `0` disables replay retention. | | `MxGateway:Events:ReplayRetentionSeconds` | `300` | Maximum age, in seconds, of an event retained in the replay ring buffer. Entries older than this are evicted regardless of capacity. `0` disables age-based eviction. | | `MxGateway:Events:ReplayBufferMaxBytes` | `67108864` (64 MiB) | Maximum summed serialized size, in bytes, of the events retained per session in the replay ring buffer. The count cap alone does not bound memory: one large-array event can approach the worker frame size, so 1024 of them could pin gigabytes per session. When the retained total exceeds this cap the oldest events are evicted first, and an event larger than the whole cap is not retained at all; a resuming subscriber then sees the ordinary `ReplayGap`. The default never binds for scalar traffic and only trims bursts of large events. `0` disables the byte cap. | -| `MxGateway:Events:MaxSparseArrayLength` | `1000000` | Maximum `total_length` a sparse-array write (`MxSparseArray`) may declare. A write above this cap is rejected with `InvalidArgument` before the full array is materialized, guarding against a single write forcing a multi-GB allocation. Must be between `1` and `Array.MaxLength`. | +| `MxGateway:Events:MaxSparseArrayLength` | `1000000` | Maximum `total_length` a sparse-array write (`MxSparseArray`) may declare. A write above this cap is rejected with `InvalidArgument` before the full array is materialized, guarding against a single write forcing a multi-GB allocation. Must be between `1` and `Array.MaxLength`. Independently, a sparse write whose expanded array cannot fit the worker frame (`MxGateway:Worker:MaxMessageBytes`) is rejected with `InvalidArgument` before allocation. | `QueueCapacity` must be greater than zero and no greater than `int.MaxValue / 2` (the validator rejects a larger value so the derived `2 ×` staging bound cannot diff --git a/gateway.md b/gateway.md index 6fe1a62b..ecbf4dd4 100644 --- a/gateway.md +++ b/gateway.md @@ -775,6 +775,12 @@ read, all of which contradict MXAccess semantics. - an element `value` whose kind does not match `element_data_type` - `total_length` exceeds the gateway-configured maximum array length (`MxGateway:Events:MaxSparseArrayLength`, default 1,000,000) +- the expanded array cannot fit the worker command frame: every slot encodes to + at least its default value's size (1 byte for bool/integer, 4 for float, 8 for + double, 2 for string/time), and when `total_length` times that exceeds the + negotiated worker frame limit (`MxGateway:Worker:MaxMessageBytes`, less an + 11-byte sequence allowance) the write is refused before the array is allocated. + The sparse values of one bulk command share that budget. An empty `elements` list with a non-zero `total_length` is valid — it writes an all-defaults array of length `total_length` (explicit reset). A `sparse_array_value` diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs index d6b5d8f1..8e28cda5 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs @@ -1533,7 +1533,11 @@ public sealed class GatewaySession : IAsyncDisposable IWorkerClient workerClient = await GetReadyWorkerClientAsync(cancellationToken).ConfigureAwait(false); if (command.Command is not null) { - NormalizeOutboundCommand(command.Command); + // The client's own CommandTooLarge pre-check is exact but runs after expansion; this + // budget is the same limit, charged with a lower bound of each expanded array's encoding + // so an oversized sparse write is refused before the array is allocated (SES-008). + long expansionBudget = workerClient.MaxCommandBytes ?? long.MaxValue; + NormalizeOutboundCommand(command.Command, ref expansionBudget); } TouchClientActivity(_eventStreaming.TimeProvider.GetUtcNow()); @@ -1549,8 +1553,9 @@ public sealed class GatewaySession : IAsyncDisposable // partial-array write primitive — the worker only ever sees a full MxArray. // SparseArrayExpander.Expand throws SparseArrayException for an invalid sparse payload; that // propagates out of InvokeAsync and the gRPC layer maps it to InvalidArgument. It is - // deliberately not caught here. - private void NormalizeOutboundCommand(MxCommand command) + // deliberately not caught here. expansionBudget is the worker command byte limit, shared by + // every sparse value in the command so a bulk write of many sparse arrays is bounded as a whole. + private void NormalizeOutboundCommand(MxCommand command, ref long expansionBudget) { switch (command.PayloadCase) { @@ -1574,42 +1579,42 @@ public sealed class GatewaySession : IAsyncDisposable break; case MxCommand.PayloadOneofCase.Write: - ExpandValue(command.Write.Value); + ExpandValue(command.Write.Value, ref expansionBudget); break; case MxCommand.PayloadOneofCase.WriteSecured: - ExpandValue(command.WriteSecured.Value); + ExpandValue(command.WriteSecured.Value, ref expansionBudget); break; case MxCommand.PayloadOneofCase.Write2: - ExpandValue(command.Write2.Value); + ExpandValue(command.Write2.Value, ref expansionBudget); break; case MxCommand.PayloadOneofCase.WriteSecured2: - ExpandValue(command.WriteSecured2.Value); + ExpandValue(command.WriteSecured2.Value, ref expansionBudget); break; case MxCommand.PayloadOneofCase.WriteBulk: foreach (WriteBulkEntry entry in command.WriteBulk.Entries) { - ExpandValue(entry.Value); + ExpandValue(entry.Value, ref expansionBudget); } break; case MxCommand.PayloadOneofCase.Write2Bulk: foreach (Write2BulkEntry entry in command.Write2Bulk.Entries) { - ExpandValue(entry.Value); + ExpandValue(entry.Value, ref expansionBudget); } break; case MxCommand.PayloadOneofCase.WriteSecuredBulk: foreach (WriteSecuredBulkEntry entry in command.WriteSecuredBulk.Entries) { - ExpandValue(entry.Value); + ExpandValue(entry.Value, ref expansionBudget); } break; case MxCommand.PayloadOneofCase.WriteSecured2Bulk: foreach (WriteSecured2BulkEntry entry in command.WriteSecured2Bulk.Entries) { - ExpandValue(entry.Value); + ExpandValue(entry.Value, ref expansionBudget); } break; @@ -1623,12 +1628,13 @@ public sealed class GatewaySession : IAsyncDisposable // MXAccess writes replace the whole array; expand a sparse value in place so the worker only // ever receives a whole-array MxValue. No-op for null or non-sparse values. The configured - // MxGateway:Events:MaxSparseArrayLength cap is enforced before the full array is allocated. - private void ExpandValue(MxValue? value) + // MxGateway:Events:MaxSparseArrayLength cap and the worker command size budget are both + // enforced before the full array is allocated. + private void ExpandValue(MxValue? value, ref long expansionBudget) { if (value is not null) { - SparseArrayExpander.Expand(value, _eventStreaming.EventOptions.MaxSparseArrayLength); + SparseArrayExpander.Expand(value, _eventStreaming.EventOptions.MaxSparseArrayLength, ref expansionBudget); } } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SparseArrayExpander.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SparseArrayExpander.cs index cbd1416b..220ab3a5 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SparseArrayExpander.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SparseArrayExpander.cs @@ -50,6 +50,30 @@ internal static class SparseArrayExpander /// element value whose kind does not match the declared element type. /// public static void Expand(MxValue value, int maxSparseArrayLength = int.MaxValue) + { + long unbounded = long.MaxValue; + Expand(value, maxSparseArrayLength, ref unbounded); + } + + /// + /// Expands as does, first charging a + /// lower bound of the expanded array's encoded size against . + /// + /// The value to expand in place. + /// The maximum total_length the sparse array may declare. + /// + /// Bytes of the worker command size limit still available to expanded arrays in this command. + /// A sparse value whose expansion needs at least more than this is rejected before the array is + /// allocated; otherwise the lower bound is deducted, so several sparse values in one bulk + /// command share the budget. The bound is the encoding of every slot at its default value, so it + /// never rejects a write that would have fit; the worker client's exact size check still runs + /// on the expanded command. + /// + /// + /// Thrown for the same invalid payloads as , and when the + /// expansion cannot fit . + /// + public static void Expand(MxValue value, int maxSparseArrayLength, ref long remainingCommandBytes) { ArgumentNullException.ThrowIfNull(value); @@ -84,6 +108,19 @@ internal static class SparseArrayExpander $"Sparse array total_length {totalLength} exceeds the maximum supported array length {Array.MaxLength}."); } + // Every slot encodes to at least its default value's size, so this is a lower bound on the + // expanded array. Checked before anything is allocated: a request of a few dozen bytes can + // otherwise declare a million-slot array that the worker frame could never carry (SES-008). + long minimumEncodedBytes = (long)totalLength * MinimumEncodedBytesPerSlot(elementType); + if (minimumEncodedBytes > remainingCommandBytes) + { + throw Invalid( + $"Sparse array total_length {totalLength} of element_data_type '{elementType}' expands to at least " + + $"{minimumEncodedBytes} bytes, exceeding the {remainingCommandBytes} bytes left in the worker command size limit."); + } + + remainingCommandBytes -= minimumEncodedBytes; + int length = (int)totalLength; HashSet seenIndices = new(); @@ -260,6 +297,20 @@ internal static class SparseArrayExpander return array; } + // Encoded size of one default-valued slot in the expanded array: packed bool and varint 0 are one + // byte, packed float/double are fixed width, and each empty string or empty Timestamp message + // costs at least a tag byte and a zero length byte. + private static int MinimumEncodedBytesPerSlot(MxDataType elementType) => elementType switch + { + MxDataType.Boolean => 1, + MxDataType.Integer => 1, + MxDataType.Float => sizeof(float), + MxDataType.Double => sizeof(double), + MxDataType.String => 2, + MxDataType.Time => 2, + _ => 1, + }; + private static bool IsSupportedElementType(MxDataType elementType) => elementType switch { MxDataType.Boolean => true, diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/IWorkerClient.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/IWorkerClient.cs index 88b9fcf1..1026a4b7 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/IWorkerClient.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/IWorkerClient.cs @@ -35,6 +35,15 @@ public interface IWorkerClient : IAsyncDisposable /// string? RecordInfoPinStatus => null; + /// + /// Largest command envelope, in bytes, this client will accept for sending — the negotiated + /// worker-frame maximum less the sequence-stamp allowance, i.e. the bound its own + /// CommandTooLarge pre-check enforces. The session uses it to reject a sparse array + /// write whose expansion cannot fit before allocating the expanded array (SES-008). The + /// default implementation returns (no bound known). + /// + int? MaxCommandBytes => null; + /// UTC timestamp of the most recent heartbeat from the worker. DateTimeOffset LastHeartbeatAt { get; } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs index 17ba7ec0..d9813e47 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs @@ -188,6 +188,9 @@ public sealed class WorkerClient : IWorkerClient /// public string? RecordInfoPinStatus => Volatile.Read(ref _recordInfoPinStatus); + /// + public int? MaxCommandBytes => _connection.FrameOptions.MaxMessageBytes - MaxSequenceEncodingBytes; + /// public DateTimeOffset LastHeartbeatAt { 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 5a863611..d951575c 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,41 @@ public sealed class GatewayArrayWriteWiringTests Assert.Equal(new[] { 0, 7, 0, 0 }, forwarded.ArrayValue.Int32Values.Values); } + /// + /// SES-008: a bulk write whose sparse values together cannot fit the worker's command size + /// limit is rejected before the overrunning value is expanded, and nothing reaches the worker. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task WriteBulk_SparseValuesOverWorkerCommandLimit_RejectedBeforeExpanding() + { + CapturingWorkerClient worker = new() { MaxCommandBytes = 3_000 }; + GatewaySession session = CreateReadySession(worker); + MxValue first = new() { SparseArrayValue = new MxSparseArray { ElementDataType = MxDataType.Time, TotalLength = 1_000 } }; + MxValue second = new() { SparseArrayValue = new MxSparseArray { ElementDataType = MxDataType.Time, TotalLength = 1_000 } }; + WorkerCommand command = new() + { + Command = new MxCommand + { + Kind = MxCommandKind.WriteBulk, + WriteBulk = new WriteBulkCommand + { + ServerHandle = 1, + Entries = + { + new WriteBulkEntry { ItemHandle = 42, Value = first }, + new WriteBulkEntry { ItemHandle = 43, Value = second }, + }, + }, + }, + }; + + await Assert.ThrowsAsync(() => session.InvokeAsync(command, CancellationToken.None)); + + Assert.Null(worker.LastCommand); + Assert.Equal(MxValue.KindOneofCase.SparseArrayValue, second.KindCase); + } + /// /// 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. @@ -824,6 +859,9 @@ public sealed class GatewayArrayWriteWiringTests /// Gets or sets the reply returned by the next invocation. public WorkerCommandReply NextReply { get; set; } = new(); + /// + public int? MaxCommandBytes { get; set; } + /// public string SessionId { get; } = "session-array-write-wiring"; 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 1f92e3e6..5140c3ac 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SparseArrayExpanderTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SparseArrayExpanderTests.cs @@ -161,6 +161,65 @@ public sealed class SparseArrayExpanderTests Assert.Equal(0, slots[0].Seconds); } + /// + /// SES-008: a sparse write whose expansion cannot fit the worker command limit is rejected + /// before the array is allocated, and the budget is left untouched. + /// + [Fact] + public void Expand_WhenMinimumEncodingExceedsBudget_ThrowsBeforeExpanding() + { + MxValue value = SparseValue(MxDataType.Time, 1_000_000); + long budget = 1_000_000; + + SparseArrayException ex = Assert.Throws( + () => SparseArrayExpander.Expand(value, int.MaxValue, ref budget)); + + Assert.Contains("at least 2000000 bytes", ex.Message, StringComparison.Ordinal); + Assert.Equal(MxValue.KindOneofCase.SparseArrayValue, value.KindCase); + Assert.Equal(1_000_000, budget); + } + + /// SES-008: several sparse values in one command share the budget. + [Fact] + public void Expand_SharedBudget_RejectsTheValueThatOverrunsIt() + { + MxValue first = SparseValue(MxDataType.Double, 100); + MxValue second = SparseValue(MxDataType.Double, 100); + long budget = 1_500; + + SparseArrayExpander.Expand(first, int.MaxValue, ref budget); + Assert.Equal(700, budget); + + Assert.Throws(() => SparseArrayExpander.Expand(second, int.MaxValue, ref budget)); + Assert.Equal(MxValue.KindOneofCase.SparseArrayValue, second.KindCase); + } + + /// + /// SES-008: the charged size is a true lower bound on the expanded encoding for every element + /// type, so the budget never refuses a write the worker frame could have carried. + /// + /// The sparse element type. + [Theory] + [InlineData(MxDataType.Boolean)] + [InlineData(MxDataType.Integer)] + [InlineData(MxDataType.Float)] + [InlineData(MxDataType.Double)] + [InlineData(MxDataType.String)] + [InlineData(MxDataType.Time)] + public void Expand_ChargedBytes_DoNotExceedExpandedEncoding(MxDataType elementType) + { + MxValue value = SparseValue(elementType, 1_000); + long budget = long.MaxValue; + + SparseArrayExpander.Expand(value, int.MaxValue, ref budget); + + long charged = long.MaxValue - budget; + Assert.True(charged > 0); + Assert.True( + charged <= value.ArrayValue.CalculateSize(), + $"charged {charged} > encoded {value.ArrayValue.CalculateSize()}"); + } + /// Verifies that expanding a Double sparse array fills defaults and applies the given element. [Fact] public void Expand_Double_HappyPath()