From a606407fc4fe670b3ce4c9458f3c0d1fc9215e42 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 13:04:28 -0500 Subject: [PATCH 1/3] perf(dashboard): NativeDialog sends update() only on busy/generation change or a reported submit (DSH-008, #258) JS now reports when a submit raises its in-flight pending flag, and a cancel request marks the same, so the next render clears pending through update() without update() running on every snapshot tick. Escape still works after a rejected submit. --- docs/ui-validation/technical-light-dialogs.md | 7 + .../Components/Shared/NativeDialog.razor | 42 ++++- .../wwwroot/js/dashboard-dialog.js | 6 +- .../Dashboard/NativeDialogInteropTests.cs | 172 ++++++++++++++++++ 4 files changed, 222 insertions(+), 5 deletions(-) diff --git a/docs/ui-validation/technical-light-dialogs.md b/docs/ui-validation/technical-light-dialogs.md index 0d88903a..790657d9 100644 --- a/docs/ui-validation/technical-light-dialogs.md +++ b/docs/ui-validation/technical-light-dialogs.md @@ -26,6 +26,13 @@ returns to a usable connected trigger; otherwise the page heading gets temporary programmatic focus, with tabindex removed on blur. A newly claimed outside focus is respected. Native backdrop is the only dimming layer. +Interop is sent only on state changes, because the host pages re-render every +snapshot tick (DSH-008, #258): close() once per generation, update() only when the +generation or busy flag changes or JS has reported a submit. A submit or Escape +raises a client-side pending flag that blocks a second cancel; JS reports the +submit (NotifyPendingAsync) and the next render sends update(), which clears it, so +Escape works again after a rejected submit. + ## Observed checks - Baseline 341 dashboard tests passed. Two semantic tests failed on the old overlay, diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Shared/NativeDialog.razor b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Shared/NativeDialog.razor index 78610fa4..337174bc 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Shared/NativeDialog.razor +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Shared/NativeDialog.razor @@ -26,6 +26,15 @@ // no-op there, and the host pages re-render every snapshot tick, so without this a dismissed // dialog cost one interop round trip per tick for the life of the tab (DSH-008). private long _closedGeneration = -1; + // Last generation/busy pair sent to JS through open() or update(). update() runs only when + // that pair changes or JS reported its in-flight "pending" flag set, so an open dialog no + // longer costs one interop round trip per snapshot tick (DSH-008). + private long _updatedGeneration = -1; + private bool _updatedBusy; + // Set when JS reports a submit/cancel that raised its "pending" flag. The next render + // (normally the parent's re-render after handling that submit) sends update() to clear it, so + // a rejected submit (validation error, guarded handler) re-enables Escape-to-cancel. + private bool _pendingClearRequested; private Task? _disposeTask; /// Whether the parent requests an interactive native modal. @@ -54,6 +63,7 @@ ++_generation; _needsOpen = IsOpen; _cancelPending = false; + _pendingClearRequested = false; } /// @@ -86,15 +96,24 @@ { _needsOpen = false; _self ??= DotNetObjectReference.Create(this); + // open() reads busy from the rendered data-busy attribute and starts with pending + // cleared, so it counts as an update for this generation. + _updatedGeneration = generation; + _updatedBusy = IsBusy; bool opened = await _module.InvokeAsync("open", _element, _self, generation); openedNow = opened; if (!opened) rejectedGeneration = generation; } - // update() is deliberately not de-duplicated: the JS side clears its in-flight "pending" - // flag there, and a re-render with unchanged parameters is how a rejected submit - // (validation error, guarded handler) re-enables Escape-to-cancel. - if (!openedNow && !_disposed && generation == _generation && IsOpen) + if (!openedNow && !_disposed && generation == _generation && IsOpen + && (_pendingClearRequested || _updatedGeneration != generation || _updatedBusy != IsBusy)) + { + // Record before the await: a pending report that arrives while update() is in + // flight must survive to the next render. + _pendingClearRequested = false; + _updatedGeneration = generation; + _updatedBusy = IsBusy; await _module.InvokeVoidAsync("update", _element, generation, IsBusy); + } } catch (JSDisconnectedException) { } finally { _lifecycle.Release(); } @@ -105,12 +124,27 @@ [JSInvokable] public Task RequestCancelAsync(long generation) => InvokeAsync(async () => { + // JS raised its pending flag before calling here; a rejected cancel must still clear it. + if (generation == _generation) _pendingClearRequested = true; if (_disposed || !IsOpen || IsBusy || _cancelPending || generation != _generation) return; _cancelPending = true; try { await OnCancel.InvokeAsync(); } finally { if (generation == _generation) _cancelPending = false; } }); + /// + /// Invoked by JS when a submit raised its in-flight pending flag. No render is requested: the + /// parent's re-render after handling the submit (or the next snapshot tick) sends update(), + /// which clears the flag, so Escape works again after a rejected submit. + /// + /// Presentation generation the submit belongs to. + /// A task that completes once the report is recorded. + [JSInvokable] + public Task NotifyPendingAsync(long generation) => InvokeAsync(() => + { + if (!_disposed && generation == _generation) _pendingClearRequested = true; + }); + /// public ValueTask DisposeAsync() => new(_disposeTask ??= DisposeCoreAsync()); diff --git a/src/ZB.MOM.WW.MxGateway.Server/wwwroot/js/dashboard-dialog.js b/src/ZB.MOM.WW.MxGateway.Server/wwwroot/js/dashboard-dialog.js index e2aecf3e..c6c43050 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/wwwroot/js/dashboard-dialog.js +++ b/src/ZB.MOM.WW.MxGateway.Server/wwwroot/js/dashboard-dialog.js @@ -21,7 +21,11 @@ export function open(dialog, dotnet, generation) { dotnet.invokeMethodAsync('RequestCancelAsync', generation).catch(() => {}); }; state.operation = event => { - if (event.type === 'submit' || event.target.closest('[data-dialog-submit]')) state.pending = true; + if (event.type !== 'submit' && !event.target.closest('[data-dialog-submit]')) return; + state.pending = true; + // The server sends update() (which clears pending) only after this report, not on every + // render, so a rejected submit must say it happened. + dotnet.invokeMethodAsync('NotifyPendingAsync', generation).catch(() => {}); }; states.set(dialog, state); dialog.addEventListener('cancel', state.cancel); diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/NativeDialogInteropTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/NativeDialogInteropTests.cs index b345baa4..f8b9a7f6 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/NativeDialogInteropTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/NativeDialogInteropTests.cs @@ -42,6 +42,139 @@ public sealed class NativeDialogInteropTests Assert.Equal(1, js.ModuleCalls.Count(call => call == "close")); } + /// An open, idle dialog sends no update() while the parent re-renders unchanged. + /// A task that represents the asynchronous operation. + [Fact] + public async Task OpenDialog_WhenParentRerendersUnchanged_DoesNotCallUpdate() + { + (RecordingJsRuntime js, ServiceProvider provider, TestRenderer renderer, HostHandle handle) = await MountAsync(); + await using ServiceProvider providerScope = provider; + await using TestRenderer rendererScope = renderer; + + await SetOpenAsync(renderer, handle, true); + await RerenderAsync(renderer, handle, 10); + + Assert.Equal(1, js.ModuleCalls.Count(call => call == "open")); + Assert.Equal(0, js.ModuleCalls.Count(call => call == "update")); + } + + /// A busy transition reaches JS once per change, not once per render. + /// A task that represents the asynchronous operation. + [Fact] + public async Task OpenDialog_WhenBusyChanges_CallsUpdateOncePerChange() + { + (RecordingJsRuntime js, ServiceProvider provider, TestRenderer renderer, HostHandle handle) = await MountAsync(); + await using ServiceProvider providerScope = provider; + await using TestRenderer rendererScope = renderer; + + await SetOpenAsync(renderer, handle, true); + await SetBusyAsync(renderer, handle, true); + await RerenderAsync(renderer, handle, 5); + Assert.Equal([true], js.UpdateBusyArguments); + + await SetBusyAsync(renderer, handle, false); + await RerenderAsync(renderer, handle, 5); + Assert.Equal([true, false], js.UpdateBusyArguments); + } + + /// + /// A rejected submit (JS raised pending, the parent re-rendered without going busy or closing) + /// sends exactly one update(), which is what clears JS pending, and Escape then cancels. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RejectedSubmit_SendsOneUpdate_ThenEscapeCancels() + { + (RecordingJsRuntime js, ServiceProvider provider, TestRenderer renderer, HostHandle handle) = await MountAsync(); + await using ServiceProvider providerScope = provider; + await using TestRenderer rendererScope = renderer; + + await SetOpenAsync(renderer, handle, true); + await RerenderAsync(renderer, handle, 3); + Assert.Equal(0, js.ModuleCalls.Count(call => call == "update")); + long generation = js.OpenGeneration; + + // JS: submit clicked -> pending raised and reported; the handler rejects and the parent + // re-renders with nothing changed. + await handle.Host!.Dialog!.NotifyPendingAsync(generation); + await RerenderAsync(renderer, handle, 1); + Assert.Equal([generation], js.UpdateGenerations); + + // Further ticks do not repeat it. + await RerenderAsync(renderer, handle, 5); + Assert.Equal([generation], js.UpdateGenerations); + + // JS: Escape with pending cleared -> RequestCancelAsync -> parent cancel. + await handle.Host.Dialog.RequestCancelAsync(generation); + Assert.Equal(1, handle.Host.CancelCount); + } + + /// An Escape the parent ignores still gets JS pending cleared on the next render. + /// A task that represents the asynchronous operation. + [Fact] + public async Task IgnoredCancel_SendsUpdateOnNextRender() + { + (RecordingJsRuntime js, ServiceProvider provider, TestRenderer renderer, HostHandle handle) = await MountAsync(); + await using ServiceProvider providerScope = provider; + await using TestRenderer rendererScope = renderer; + + await SetOpenAsync(renderer, handle, true); + long generation = js.OpenGeneration; + await handle.Host!.Dialog!.RequestCancelAsync(generation); + await RerenderAsync(renderer, handle, 3); + + Assert.Equal(1, handle.Host.CancelCount); + Assert.Equal([generation], js.UpdateGenerations); + } + + /// A pending report for a superseded generation is ignored. + /// A task that represents the asynchronous operation. + [Fact] + public async Task NotifyPending_ForStaleGeneration_DoesNotCallUpdate() + { + (RecordingJsRuntime js, ServiceProvider provider, TestRenderer renderer, HostHandle handle) = await MountAsync(); + await using ServiceProvider providerScope = provider; + await using TestRenderer rendererScope = renderer; + + await SetOpenAsync(renderer, handle, true); + await handle.Host!.Dialog!.NotifyPendingAsync(js.OpenGeneration - 1); + await RerenderAsync(renderer, handle, 3); + + Assert.Equal(0, js.ModuleCalls.Count(call => call == "update")); + } + + private static async Task<(RecordingJsRuntime Js, ServiceProvider Provider, TestRenderer Renderer, HostHandle Handle)> MountAsync() + { + RecordingJsRuntime js = new(); + ServiceCollection services = new(); + services.AddLogging(); + services.AddSingleton(js); + ServiceProvider provider = services.BuildServiceProvider(); + TestRenderer renderer = new(provider, provider.GetRequiredService()); + HostHandle handle = new(); + await renderer.MountAsync(handle); + return (js, provider, renderer, handle); + } + + private static async Task RerenderAsync(TestRenderer renderer, HostHandle handle, int count) + { + for (int i = 0; i < count; i++) + { + await renderer.Dispatcher.InvokeAsync(() => handle.Host!.Rerender()); + await Task.Delay(10); + } + } + + private static async Task SetBusyAsync(TestRenderer renderer, HostHandle handle, bool busy) + { + await renderer.Dispatcher.InvokeAsync(() => + { + handle.Host!.Busy = busy; + handle.Host.Rerender(); + }); + await Task.Delay(50); + } + private static async Task SetOpenAsync(TestRenderer renderer, HostHandle handle, bool open) { await renderer.Dispatcher.InvokeAsync(() => @@ -94,6 +227,15 @@ public sealed class NativeDialogInteropTests /// Gets or sets a value indicating whether the dialog is open. public bool Open { get; set; } + /// Gets or sets a value indicating whether the parent reports in-flight work. + public bool Busy { get; set; } + + /// Gets the number of cancel callbacks; the parent ignores them (stays open). + public int CancelCount { get; private set; } + + /// Gets the rendered dialog instance. + public NativeDialog? Dialog { get; private set; } + /// Requests a render, as a snapshot tick does for the host pages. public void Rerender() => StateHasChanged(); @@ -110,6 +252,9 @@ public sealed class NativeDialogInteropTests // A RenderFragment is not a change-detectable parameter, so the dialog re-renders with // its host exactly as it does on the real pages. builder.AddAttribute(3, nameof(NativeDialog.ChildContent), (RenderFragment)(content => { })); + builder.AddAttribute(4, nameof(NativeDialog.IsBusy), Busy); + builder.AddAttribute(5, nameof(NativeDialog.OnCancel), EventCallback.Factory.Create(this, () => CancelCount++)); + builder.AddComponentReferenceCapture(6, dialog => Dialog = (NativeDialog)dialog); builder.CloseComponent(); } } @@ -121,6 +266,15 @@ public sealed class NativeDialogInteropTests /// Gets the module-level calls made, in order. public List ModuleCalls => _module.Calls; + /// Gets the generation passed to the most recent open() call. + public long OpenGeneration => _module.OpenGeneration; + + /// Gets the generation argument of each update() call, in order. + public List UpdateGenerations => _module.UpdateGenerations; + + /// Gets the busy argument of each update() call, in order. + public List UpdateBusyArguments => _module.UpdateBusyArguments; + /// public ValueTask InvokeAsync(string identifier, object?[]? args) => new((TValue)(object)_module); @@ -135,12 +289,30 @@ public sealed class NativeDialogInteropTests /// Gets the calls made, in order. public List Calls { get; } = []; + /// Gets the generation passed to the most recent open() call. + public long OpenGeneration { get; private set; } + + /// Gets the generation argument of each update() call, in order. + public List UpdateGenerations { get; } = []; + + /// Gets the busy argument of each update() call, in order. + public List UpdateBusyArguments { get; } = []; + /// public ValueTask InvokeAsync(string identifier, object?[]? args) { lock (Calls) { Calls.Add(identifier); + if (identifier == "open") + { + OpenGeneration = (long)args![2]!; + } + else if (identifier == "update") + { + UpdateGenerations.Add((long)args![1]!); + UpdateBusyArguments.Add((bool)args[2]!); + } } return new(typeof(TValue) == typeof(bool) ? (TValue)(object)true : default!); From d526b69b0bd54452bee06acc7fc196177ef66a06 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 13:06:25 -0500 Subject: [PATCH 2/3] perf(auth): skip the limiter's composite resolve and reset work when nothing is tracked; ValueTask auth path (SEC-012, #258) The cached-success path already bypasses the limiter (SEC-002); this trims the cache-miss success path and the per-call Task. Check no longer builds the (peer, key id) string when no peer partition exists, Reset skips the partition clear in that case and reuses the check's composite for the verified mark, and a disabled limiter's Reset does nothing. SEC-001/002/003 tests unchanged and green. --- .../Authorization/ApiKeyFailureLimiter.cs | 74 ++++++++++++++----- .../GatewayGrpcAuthorizationInterceptor.cs | 4 +- .../ApiKeyFailureLimiterTests.cs | 60 +++++++++++++++ 3 files changed, 118 insertions(+), 20 deletions(-) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs index 684dc0f4..5a72d481 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs @@ -166,10 +166,23 @@ public sealed class ApiKeyFailureLimiter } long now = _clock.GetUtcNow().UtcTicks; - (string partitionKey, string? effectiveKeyId) = ResolvePartitionKey(peer, partition.KeyId, mint: false); - resolution = new PartitionResolution(partitionKey, effectiveKeyId); - WindowState? peerState = _partitions.TryGetValue(partitionKey, out WindowState? tracked) ? tracked : null; + // The common case on a quiet limiter is that no peer partition exists at all. Skipping the + // resolve then avoids building the composite (peer, key id) string only to miss the lookup + // with it (SEC-012). A failure that a concurrent request records after this read is not one + // this request's later success clears; it decays by window like any other. + WindowState? peerState = null; + if (_partitions.IsEmpty) + { + resolution = PartitionResolution.NoTrackedState; + } + else + { + (string partitionKey, string? effectiveKeyId) = ResolvePartitionKey(peer, partition.KeyId, mint: false); + resolution = new PartitionResolution(partitionKey, effectiveKeyId); + peerState = _partitions.TryGetValue(partitionKey, out WindowState? tracked) ? tracked : null; + } + WindowState? aggregateState = null; if (partition.KeyId is not null && _aggregateLimit > 0 @@ -275,34 +288,50 @@ public sealed class ApiKeyFailureLimiter internal void Reset(ApiKeyThrottlePartition partition, PartitionResolution resolution) { string peer = RequirePeer(partition); - (string partitionKey, string? effectiveKeyId) = resolution.IsResolved - ? (resolution.PartitionKey!, resolution.EffectiveKeyId) - : ResolvePartitionKey(peer, partition.KeyId, mint: false); - // Clear only a partition this caller actually owns. When its key id was squeezed into the - // address's shared fallback bucket by the per-peer cap, that bucket also holds failures - // contributed by other key ids — and by junk-shaped tokens — from the same address, so - // removing it would let one successful authentication wipe an in-progress spray. The shared - // bucket decays by window expiry instead; the caller still recovers through probe admission. - if (effectiveKeyId is not null - && string.Equals(effectiveKeyId, partition.KeyId, StringComparison.Ordinal)) + // A disabled limiter never records a partition or consults a verified mark. + if (_limit <= 0) { - RemovePartition(partitionKey); + return; + } + + // The composite (peer, key id) string the check built, when it built one this caller owns; + // the verified mark below reuses it rather than building it again. + string? ownComposite = null; + + // A check that saw no tracked partition has nothing for this success to clear (SEC-012). + if (!resolution.Untracked) + { + (string partitionKey, string? effectiveKeyId) = resolution.IsResolved + ? (resolution.PartitionKey!, resolution.EffectiveKeyId) + : ResolvePartitionKey(peer, partition.KeyId, mint: false); + + // Clear only a partition this caller actually owns. When its key id was squeezed into the + // address's shared fallback bucket by the per-peer cap, that bucket also holds failures + // contributed by other key ids — and by junk-shaped tokens — from the same address, so + // removing it would let one successful authentication wipe an in-progress spray. The shared + // bucket decays by window expiry instead; the caller still recovers through probe admission. + if (effectiveKeyId is not null + && string.Equals(effectiveKeyId, partition.KeyId, StringComparison.Ordinal)) + { + RemovePartition(partitionKey); + ownComposite = partitionKey; + } } // The aggregate is deliberately NOT cleared (SEC-003). A key in steady use succeeds many // times a second, so clearing it on success meant it never accumulated and a sprayer guessing // the same key id from other addresses was bounded by neither layer. It decays by window. // Instead the verifying address is marked, so the aggregate cannot lock the holder out. - if (partition.KeyId is not null && _aggregateLimit > 0 && _limit > 0) + if (partition.KeyId is not null && _aggregateLimit > 0) { - MarkVerified(peer, partition.KeyId, _clock.GetUtcNow().UtcTicks); + MarkVerified(ownComposite ?? Composite(peer, partition.KeyId), _clock.GetUtcNow().UtcTicks); } } - private void MarkVerified(string peer, string keyId, long now) + private void MarkVerified(string composite, long now) { - _verified[Composite(peer, keyId)] = now; + _verified[composite] = now; if (_verified.Count <= _maxPartitions) { return; @@ -633,11 +662,18 @@ public sealed class ApiKeyFailureLimiter /// The key id that actually earned a partition, or when the token carried /// none or the per-peer cap collapsed it onto the transport-peer fallback. /// - internal readonly record struct PartitionResolution(string? PartitionKey, string? EffectiveKeyId) + /// + /// when the check found no peer partition tracked at all and so skipped + /// resolving a storage key; the reset then has no partition to clear. + /// + internal readonly record struct PartitionResolution(string? PartitionKey, string? EffectiveKeyId, bool Untracked = false) { /// Gets the sentinel for "not resolved yet"; the receiving call resolves it itself. internal static PartitionResolution Unresolved => default; + /// Gets the sentinel for "the check saw no tracked peer partition". + internal static PartitionResolution NoTrackedState => new(null, null, Untracked: true); + /// Gets a value indicating whether this carries a resolved storage key. internal bool IsResolved => PartitionKey is not null; } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs index 5bb2a2e6..236a6170 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs @@ -154,7 +154,9 @@ public sealed class GatewayGrpcAuthorizationInterceptor( /// The scope the call requires, resolved by the caller. /// RPC server call context. /// Authenticated API key identity, or null if authentication is disabled. - private async Task AuthenticateAndAuthorizeAsync( + // ValueTask: a cache hit completes synchronously, and a Task would be one more allocation on + // every authenticated RPC (SEC-012). + private async ValueTask AuthenticateAndAuthorizeAsync( string requiredScope, ServerCallContext context) { diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs index d9d66524..e95a6a44 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs @@ -557,6 +557,66 @@ public sealed class ApiKeyFailureLimiterTests Assert.Equal(ApiKeyThrottleDecision.ThrottledByPeer, limiter.Check(arriving)); } + /// + /// SEC-012: on a quiet limiter the check resolves no composite key and allocates nothing, and + /// the matching reset still writes the verified mark that keeps the aggregate from locking the + /// holder out (SEC-002). + /// + [Fact] + public void Check_WithNoTrackedPartition_AllocatesNothing_AndResetStillMarksVerified() + { + ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch); + ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 3, aggregateLimit: 5); + ApiKeyThrottlePartition holder = new("ipv4:10.0.0.1", "victim"); + + // Warm up JIT and any lazy statics before measuring. + limiter.Check(holder, out _); + + long before = GC.GetAllocatedBytesForCurrentThread(); + ApiKeyThrottleDecision decision = limiter.Check(holder, out ApiKeyFailureLimiter.PartitionResolution resolution); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.Equal(ApiKeyThrottleDecision.Allowed, decision); + Assert.Equal(0, allocated); + Assert.True(resolution.Untracked); + + limiter.Reset(holder, resolution); + Assert.Equal(1, limiter.VerifiedMarkCount); + + // The mark still bypasses an aggregate a sprayer then drives over its limit. + for (int i = 0; i < 5; i++) + { + limiter.RecordFailure(new ApiKeyThrottlePartition($"ipv4:10.0.1.{i}", "victim")); + } + + Assert.Equal(ApiKeyThrottleDecision.Allowed, limiter.Check(holder)); + Assert.Equal( + ApiKeyThrottleDecision.ThrottledByAggregate, + limiter.Check(new ApiKeyThrottlePartition("ipv4:10.0.2.1", "victim"))); + } + + /// + /// SEC-012: once any partition is tracked the check resolves again, and a success still clears + /// the caller's own partition through the resolution it handed back. + /// + [Fact] + public void Check_WithTrackedPartition_ResolvesAndResetClearsOwnPartition() + { + ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch); + ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 3, aggregateLimit: 5); + ApiKeyThrottlePartition holder = new("ipv4:10.0.0.1", "victim"); + RecordFailures(limiter, holder, 2); + + limiter.Check(holder, out ApiKeyFailureLimiter.PartitionResolution resolution); + Assert.False(resolution.Untracked); + Assert.True(resolution.IsResolved); + + limiter.Reset(holder, resolution); + + Assert.False(limiter.IsTracked(holder)); + Assert.Equal(1, limiter.VerifiedMarkCount); + } + private static void RecordFailures(ApiKeyFailureLimiter limiter, ApiKeyThrottlePartition partition, int count) { for (int i = 0; i < count; i++) From 0967fe07309c52943522f3f8f1db5e2a051855a1 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 13:08:29 -0500 Subject: [PATCH 3/3] 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()