From 3d73f4d7d5868764120304cd40ee49359f0ff4cc Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 15:20:00 -0500 Subject: [PATCH] fix(grpc-data): #1057 origin snapshot admission is per stream, so one principal's cohorts no longer starve each other The origin admitted MaxStreamsPerPrincipal (8) concurrent snapshots per PRINCIPAL, shared by every stream that principal held. A consumer opens one stream per (connection, identity, publishing interval) and each cohort keeps up to 4 commands or snapshots outstanding, so a third cohort's add was refused and its whole stream reset ('Snapshot admission exhausted'). SubscriptionTransportCapacity.ForDataPlane (used by LocalDataRuntimeComposition) now gives each stream 8 slots (SnapshotSlotsPerStream) and sizes the principal and node caps so every admitted stream can hold all of them; the snapshot byte budgets still bound memory. A session's background waiting-item recoveries may take at most half its slots, so the peer's outstanding commands always find theirs. Capacities built without a per-session cap (tests) keep the old per-principal behaviour. --- .../DataSubscriptionSession.cs | 9 +- .../LocalDataRuntimeComposition.cs | 2 +- .../DataConnections/ProjectedDataAccess.cs | 3 +- .../SnapshotAdmissionScheduler.cs | 57 ++++++-- .../SubscriptionTransportCapacity.cs | 27 +++- .../GrpcData1057SnapshotAdmissionTests.cs | 131 ++++++++++++++++++ 6 files changed, 212 insertions(+), 17 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1057SnapshotAdmissionTests.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs index c5654f335..c79d143c1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs @@ -538,7 +538,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo if (tickets.Length == 0) { await EnqueueAsync(ControlAck(commandId, acks, () => admitted.All(item => item.View.CanPublish()))).ConfigureAwait(false); return; } var budget = snapshotBudget ?? new DataBudget(timeout, Math.Max(tickets.Length, 1), _limits.MaxPendingBytes); - if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission)) { CloseWithReset("Snapshot admission exhausted; retry later."); return; } + if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, this, background: false, 1, out var rawAdmission)) { CloseWithReset("Snapshot admission exhausted; retry later."); return; } var permit = (SnapshotAdmissionScheduler.Permit)rawAdmission!; if (!permit.TryRetain(out var snapshotHold)) { permit.Dispose(); CloseWithReset("Snapshot admission expired."); return; } var admission = new SnapshotOwnership(permit, snapshotHold!); @@ -598,7 +598,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo } } var tickets = items.Select(x => x.Ticket!.Value).Distinct().ToArray(); - if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission)) + if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, this, background: false, 1, out var rawAdmission)) { CloseWithReset("Freshness snapshot admission exhausted; retry later."); return; } var permit = (SnapshotAdmissionScheduler.Permit)rawAdmission!; if (!permit.TryRetain(out var hold)) { permit.Dispose(); Stop(); return; } @@ -691,7 +691,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo result.Status == DataItemStatus.Good ? DataItemStatus.WaitingForInitialData : result.Status, null, null, null)); continue; } var budget = new DataBudget(remaining, 1, _limits.MaxPendingBytes); - if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission)) + if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, this, background: false, 1, out var rawAdmission)) { result.Lease.Dispose(); acks.Add(new(request.ClientItemId, DataItemStatus.ResourceExhausted, null, null, null)); continue; @@ -957,7 +957,8 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo private async Task RecoverWaitingAsync(Item item, SourceTicket ticket) { var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, _limits.MaxPendingBytes); - if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission)) return false; + // #1057: a background acquisition — at most half this stream's snapshot slots, so the peer's commands always find theirs. + if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, this, background: true, 1, out var rawAdmission)) return false; var permit = (SnapshotAdmissionScheduler.Permit)rawAdmission!; if (!permit.TryRetain(out var snapshotHold)) { permit.Dispose(); return false; } var admission = new SnapshotOwnership(permit, snapshotHold!); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs index d3389428d..2d880f12c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs @@ -37,7 +37,7 @@ public sealed class LocalDataRuntimeComposition : IDisposable var sessionLimits = new SubscriptionSessionLimits(limits.MaxCommands, limits.MaxPendingFrames, limits.MaxPendingBytes, limits.MaxSessionLifetime); sessionLimits.Validate(); var registry = new UpstreamDemandRegistry(limits.MaxInterests, limits.MaxInterests); - var capacity = new SubscriptionTransportCapacity(limits.MaxOperations, limits.MaxOperationsPerPrincipal, limits.MaxTransportBytes, clock); + var capacity = SubscriptionTransportCapacity.ForDataPlane(limits.MaxOperations, limits.MaxOperationsPerPrincipal, limits.MaxTransportBytes, clock); _demand = new DriverHostSubscriptionDemandSource(host, registry, limits.MaxDrivers, limits.MaxInterests, limits.DriverAskTimeout, acquisitionCapacity); AcquisitionCapacity = acquisitionCapacity; LocalDataServices? services = null; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs index 7e83e18ec..f67ba3955 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs @@ -1690,7 +1690,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable } } // Commands not yet acknowledged AND snapshots not yet finished: the origin holds a snapshot admission per add and per - // challenge until its SnapshotEnd is delivered (MaxStreamsPerPrincipal per principal), and refusing one resets the stream. + // challenge until its SnapshotEnd is delivered (#1057: SnapshotSlotsPerStream = 8 per stream, half of them always left for + // commands), and refusing one resets the stream. int Outstanding() => pendingCommands.Count + _removing.Count + (challengeId is null ? 0 : 1) + snapshotQueue.Count + (inSnapshot ? 1 : 0); bool TryTakeCommandSlot() { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotAdmissionScheduler.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotAdmissionScheduler.cs index 52a5319c7..2fc9d5700 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotAdmissionScheduler.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotAdmissionScheduler.cs @@ -5,10 +5,13 @@ internal sealed class SnapshotAdmissionScheduler { private readonly object _gate = new(); private readonly int _maxConcurrent, _maxPerPrincipal, _maxPrincipals; + private readonly int? _maxPerSession; private readonly long _maxBytes, _maxPrincipalBytes, _globalRate, _principalRate; private readonly TimeSpan _lifetime; private readonly TimeProvider _clock; private readonly Dictionary _principals = new(StringComparer.OrdinalIgnoreCase); + // #1057: permits held per session (stream), when a per-session cap is configured. + private readonly Dictionary _sessions = new(ReferenceEqualityComparer.Instance); private int _count; private long _bytes, _windowStart, _windowBytes; private sealed class Principal(long now) @@ -21,6 +24,7 @@ internal sealed class SnapshotAdmissionScheduler private readonly SnapshotAdmissionScheduler _owner; private readonly object _state = new(); internal readonly string Principal; + internal readonly object? Session; internal long Bytes; private ITimer? _timer; private int _references = 1, _expired; @@ -29,9 +33,9 @@ internal sealed class SnapshotAdmissionScheduler private Permit? _permit = permit; public void Dispose() => Interlocked.Exchange(ref _permit, null)?.ReleaseHold(); } - internal Permit(SnapshotAdmissionScheduler owner, string principal, long bytes, TimeSpan lifetime) + internal Permit(SnapshotAdmissionScheduler owner, string principal, object? session, long bytes, TimeSpan lifetime) { - _owner = owner; Principal = principal; Bytes = bytes; + _owner = owner; Principal = principal; Session = session; Bytes = bytes; _timer = owner._clock.CreateTimer(static state => ((Permit)state!).Dispose(), this, lifetime, Timeout.InfiniteTimeSpan); } internal bool IsValid => Volatile.Read(ref _expired) == 0; @@ -71,38 +75,72 @@ internal sealed class SnapshotAdmissionScheduler } internal SnapshotAdmissionScheduler(int maxConcurrent, int maxPerPrincipal, long maxBytes, long? maxPrincipalBytes = null, long globalBytesPerSecond = long.MaxValue, - long principalBytesPerSecond = long.MaxValue, TimeSpan? maxLifetime = null, TimeProvider? clock = null) + long principalBytesPerSecond = long.MaxValue, TimeSpan? maxLifetime = null, TimeProvider? clock = null, + int? maxPerSession = null) { if (maxConcurrent <= 0 || maxPerPrincipal <= 0 || maxBytes <= 0 || maxPrincipalBytes is <= 0 || - globalBytesPerSecond <= 0 || principalBytesPerSecond <= 0 || maxLifetime is { } lifetime && lifetime <= TimeSpan.Zero) + globalBytesPerSecond <= 0 || principalBytesPerSecond <= 0 || maxLifetime is { } lifetime && lifetime <= TimeSpan.Zero || + maxPerSession is <= 0) throw new ArgumentOutOfRangeException(nameof(maxConcurrent)); - _maxConcurrent = maxConcurrent; _maxPerPrincipal = maxPerPrincipal; _maxBytes = maxBytes; + _maxConcurrent = maxConcurrent; _maxPerPrincipal = maxPerPrincipal; _maxBytes = maxBytes; _maxPerSession = maxPerSession; _maxPrincipalBytes = maxPrincipalBytes ?? maxBytes; _globalRate = globalBytesPerSecond; _principalRate = principalBytesPerSecond; _lifetime = maxLifetime ?? TimeSpan.FromSeconds(30); _clock = clock ?? TimeProvider.System; _maxPrincipals = checked(maxConcurrent * 16); _windowStart = _clock.GetTimestamp(); } internal bool TryAcquire(string principal, long bytes, out IDisposable? lease) => TryAcquire(principal, bytes, out lease, out _); - internal bool TryAcquire(string principal, long bytes, out IDisposable? lease, out TimeSpan retryAfter) + internal bool TryAcquire(string principal, long bytes, out IDisposable? lease, out TimeSpan retryAfter) => + TryAcquire(principal, null, false, bytes, out lease, out retryAfter); + + /// The per-session permit cap, when one is configured (). + internal int? MaxPerSession => _maxPerSession; + + /// + /// #1057: acquires a permit charged to as well as its principal. With a per-session cap + /// configured, a acquisition (a waiting item's recovery, which the peer did not ask for + /// and which is simply retried) may use only half the session's slots, so the commands the peer has outstanding always + /// find theirs — refusing one of those resets the stream. Without a cap the session is not counted. + /// + internal bool TryAcquire(string principal, object? session, bool background, long bytes, out IDisposable? lease) => + TryAcquire(principal, session, background, bytes, out lease, out _); + + private bool TryAcquire(string principal, object? session, bool background, long bytes, out IDisposable? lease, out TimeSpan retryAfter) { ArgumentException.ThrowIfNullOrWhiteSpace(principal); if (bytes <= 0) throw new ArgumentOutOfRangeException(nameof(bytes)); lease = null; retryAfter = Jitter(principal); + if (_maxPerSession is null) session = null; lock (_gate) { var now = _clock.GetTimestamp(); if (!TryPrincipal(principal, now, out var state)) return false; - if (_count >= _maxConcurrent || state.Count >= _maxPerPrincipal || bytes > _maxBytes - _bytes || + var sessionCount = 0; + if (session is not null) _sessions.TryGetValue(session, out sessionCount); + var sessionLimit = _maxPerSession is { } perSession ? (background ? Math.Max(1, perSession / 2) : perSession) : int.MaxValue; + if (_count >= _maxConcurrent || state.Count >= _maxPerPrincipal || sessionCount >= sessionLimit || bytes > _maxBytes - _bytes || bytes > _maxPrincipalBytes - state.Bytes) { if (state.Count == 0 && state.WindowBytes == 0) _principals.Remove(principal); return false; } state.Count++; state.Bytes += bytes; _count++; _bytes += bytes; - try { lease = new Permit(this, principal, bytes, _lifetime); return true; } - catch { state.Count--; state.Bytes -= bytes; _count--; _bytes -= bytes; throw; } + if (session is not null) _sessions[session] = sessionCount + 1; + try { lease = new Permit(this, principal, session, bytes, _lifetime); return true; } + catch + { + state.Count--; state.Bytes -= bytes; _count--; _bytes -= bytes; + if (session is not null) ReleaseSessionLocked(session); + throw; + } } } + private void ReleaseSessionLocked(object session) + { + var count = _sessions[session] - 1; + if (count == 0) _sessions.Remove(session); else _sessions[session] = count; + } + internal int ActiveForTests { get { lock (_gate) return _count; } } + internal int SessionCountForTests(object session) { lock (_gate) return _sessions.TryGetValue(session, out var count) ? count : 0; } /// Charges actual snapshot bytes immediately before the delivery handoff; no waiting queue. internal bool TryConsume(string principal, long bytes, out TimeSpan retryAfter) { @@ -156,6 +194,7 @@ internal sealed class SnapshotAdmissionScheduler lock (_gate) { var state = _principals[permit.Principal]; state.Count--; state.Bytes -= permit.Bytes; _count--; _bytes -= permit.Bytes; + if (permit.Session is not null) ReleaseSessionLocked(permit.Session); if (state.Count == 0 && (_principalRate == long.MaxValue || state.WindowBytes == 0)) _principals.Remove(permit.Principal); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionTransportCapacity.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionTransportCapacity.cs index 46a1015fc..c76ebd277 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionTransportCapacity.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionTransportCapacity.cs @@ -56,15 +56,38 @@ internal sealed class SubscriptionTransportCapacity internal SubscriptionTransportCapacity(int maximum, int perPrincipal, long maximumBytes, TimeProvider? clock = null, int? maxSnapshots = null, int? maxSnapshotsPerPrincipal = null, long? maxSnapshotBytes = null, long? maxPrincipalSnapshotBytes = null, long? globalSnapshotBytesPerSecond = null, - long? principalSnapshotBytesPerSecond = null, TimeSpan? maxSnapshotLifetime = null, int maxCommandsPerSecond = 128) + long? principalSnapshotBytesPerSecond = null, TimeSpan? maxSnapshotLifetime = null, int maxCommandsPerSecond = 128, + int? maxSnapshotsPerSession = null) { if (maximum <= 0 || perPrincipal <= 0 || maximumBytes <= 0 || maxCommandsPerSecond <= 0) throw new ArgumentOutOfRangeException(nameof(maximum)); _maximum = maximum; _perPrincipal = perPrincipal; _maximumBytes = maximumBytes; _clock = clock ?? TimeProvider.System; _maxCommandsPerSecond = maxCommandsPerSecond; _maxRatePrincipals = checked(maximum * 16); Snapshots = new(maxSnapshots ?? maximum, maxSnapshotsPerPrincipal ?? perPrincipal, maxSnapshotBytes ?? maximumBytes, maxPrincipalBytes: maxPrincipalSnapshotBytes, globalBytesPerSecond: globalSnapshotBytesPerSecond ?? maximumBytes, - principalBytesPerSecond: principalSnapshotBytesPerSecond ?? maximumBytes, maxLifetime: maxSnapshotLifetime, clock: clock); + principalBytesPerSecond: principalSnapshotBytesPerSecond ?? maximumBytes, maxLifetime: maxSnapshotLifetime, clock: clock, + maxPerSession: maxSnapshotsPerSession); } + + /// + /// #1057: snapshot permits each stream may hold at once. A projected cohort keeps at most 4 commands or snapshots + /// outstanding (ProjectedDataAccess MaxOutstandingCommands); the other half is room for the session's own + /// background recoveries, which may never take more than half (). + /// + internal const int SnapshotSlotsPerStream = 8; + + /// + /// #1057: the data plane's capacity. Snapshot admission used to be capped at + /// permits per PRINCIPAL (8 by default), shared by every stream that principal holds — so one consumer's cohorts (one + /// stream per connection, identity and publishing interval, each with up to 4 snapshots outstanding) starved each other, + /// and the refused add reset its whole stream. Now each stream has its own slots, and + /// the principal and node caps are sized so every admitted stream can hold all of them; the snapshot BYTE budgets + /// (node-wide and per principal) still bound the memory. + /// + internal static SubscriptionTransportCapacity ForDataPlane(int streams, int streamsPerPrincipal, long maximumBytes, TimeProvider? clock = null) => + new(streams, streamsPerPrincipal, maximumBytes, clock, + maxSnapshots: checked(streams * SnapshotSlotsPerStream), + maxSnapshotsPerPrincipal: checked(streamsPerPrincipal * SnapshotSlotsPerStream), + maxSnapshotsPerSession: SnapshotSlotsPerStream); internal int ActiveOperations { get { lock (_gate) return _active; } } internal bool TryAdmitCommand(string principal) { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1057SnapshotAdmissionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1057SnapshotAdmissionTests.cs new file mode 100644 index 000000000..6f839cf83 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1057SnapshotAdmissionTests.cs @@ -0,0 +1,131 @@ +using System.Collections.Concurrent; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// #1057: the origin admitted MaxStreamsPerPrincipal (8) snapshots per PRINCIPAL, shared by all of that principal's streams. +/// A consumer holds one stream per (connection, identity, publishing interval) — a cohort — and each keeps up to 4 commands +/// or snapshots outstanding, so a third cohort's add was refused and its whole stream reset ("Snapshot admission exhausted"). +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Issue", "1057")] +public sealed class GrpcData1057SnapshotAdmissionTests +{ + [Fact(Timeout = 60000)] + public async Task Three_streams_of_one_principal_each_holding_four_snapshots_are_all_admitted() + { + var ct = TestContext.Current.CancellationToken; + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + // The production composition (LocalDataRuntimeComposition) with the default options: 256 streams, 8 per principal. + var capacity = SubscriptionTransportCapacity.ForDataPlane(256, 8, 64L * 1024 * 1024); + var limits = new SubscriptionSessionLimits(128, 64, 100_000, TimeSpan.FromMinutes(5)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(additionalRawNodes: 12, hubBytes: 64L * 1024 * 1024, targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + fixture.Publish(10); + var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var streams = new List<(IDataSubscription Subscription, HoldingSink Sink, Task Writer)>(); + await using var connection = fixture.Connection(); + try + { + for (var s = 0; s < 3; s++) + { + var subscription = await connection.SubscribeAsync(ct); + var sink = new HoldingSink(held.Task); + streams.Add((subscription, sink, subscription.ShouldBeAssignableTo().RunDeliveryAsync(sink, ct))); + await subscription.SendAsync(new OpenSubscription("s" + s, 1, "open", TimeSpan.FromSeconds(30), + [new("i0", GrpcData1057FollowUpTests.Extra(fixture, s * 4), GrpcData1057FollowUpTests.Settings)], false, + TimeSpan.FromSeconds(60), LocalDataFixture.Budget), ct); + for (var c = 1; c < 4; c++) + await subscription.SendAsync(new AddSubscriptionItems("s" + s, 1, "add" + c, TimeSpan.FromSeconds(30), + [new("i" + c, GrpcData1057FollowUpTests.Extra(fixture, s * 4 + c), GrpcData1057FollowUpTests.Settings)]), ct); + } + // Every stream's first SnapshotEnd is held by its sink, so each keeps all four snapshot permits it acquired. + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); + while (capacity.Snapshots.ActiveForTests < 12 && DateTime.UtcNow < deadline) await Task.Delay(10, ct); + capacity.Snapshots.ActiveForTests.ShouldBe(12, "every stream holds its four outstanding snapshots at once"); + held.TrySetResult(); + foreach (var (_, sink, writer) in streams) + { + await sink.WaitForAcks(4, ct); + sink.Resets.ShouldBe(0, sink.Describe()); + writer.IsCompleted.ShouldBeFalse(); + } + } + finally + { + held.TrySetResult(); + foreach (var (subscription, _, _) in streams) await subscription.DisposeAsync(); + } + } + } + + [Fact] + public void A_streams_background_recoveries_never_take_the_slots_its_commands_need() + { + var scheduler = SubscriptionTransportCapacity.ForDataPlane(4, 2, 1_000_000).Snapshots; + var session = new object(); + var held = new List(); + for (var i = 0; i < SubscriptionTransportCapacity.SnapshotSlotsPerStream; i++) + { + if (!scheduler.TryAcquire("peer", session, background: true, 1, out var recovery)) break; + held.Add(recovery!); + } + held.Count.ShouldBe(SubscriptionTransportCapacity.SnapshotSlotsPerStream / 2, "recoveries stop at half the stream's slots"); + for (var i = 0; i < SubscriptionTransportCapacity.SnapshotSlotsPerStream / 2; i++) + { + scheduler.TryAcquire("peer", session, background: false, 1, out var command).ShouldBeTrue("a command still finds its slot"); + held.Add(command!); + } + scheduler.TryAcquire("peer", session, background: false, 1, out _).ShouldBeFalse("the stream's own cap"); + // A second stream of the same principal is not starved by the first. + var sibling = new object(); + scheduler.TryAcquire("peer", sibling, background: false, 1, out var other).ShouldBeTrue(); + other!.Dispose(); + foreach (var permit in held) permit.Dispose(); + scheduler.SessionCountForTests(session).ShouldBe(0); + scheduler.ActiveForTests.ShouldBe(0); + } + + internal sealed class HoldingSink(Task release) : IDataSubscriptionDeliverySink + { + private readonly ConcurrentQueue _frames = new(); + private int _acks, _resets; + internal int Resets => Volatile.Read(ref _resets); + internal async Task WaitForAcks(int count, CancellationToken ct) + { + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(20); + while (Volatile.Read(ref _acks) < count) + { + if (DateTime.UtcNow > deadline) throw new ShouldAssertException("acks: " + Describe()); + await Task.Delay(10, ct); + } + } + internal string Describe() => string.Join(" | ", _frames.Select(frame => frame switch + { + DataSubscriptionAck ack => "ack:" + ack.CommandId + "[" + string.Join(",", ack.Items.Select(i => i.ClientItemId + "=" + i.Status)) + "]", + DataSubscriptionControl control => control.Kind + (control.Diagnostic is { } d ? ":" + d : ""), + _ => frame.GetType().Name + })); + public ValueTask PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, + CancellationToken cancellationToken) => ValueTask.FromResult(new Prepared(frame)); + public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken) + { + var frame = ((Prepared)prepared).Frame; + _frames.Enqueue(frame); + if (frame is DataSubscriptionAck) Interlocked.Increment(ref _acks); + if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset }) Interlocked.Increment(ref _resets); + if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) await release.WaitAsync(cancellationToken); + } + private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery + { + internal DataSubscriptionFrame Frame { get; } = frame; + public long RetainedBytes => 1; + public void Dispose() { } + } + } +}