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.
This commit is contained in:
@@ -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<bool> 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!);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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<string, Principal> _principals = new(StringComparer.OrdinalIgnoreCase);
|
||||
// #1057: permits held per session (stream), when a per-session cap is configured.
|
||||
private readonly Dictionary<object, int> _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);
|
||||
|
||||
/// <summary>The per-session permit cap, when one is configured (<see cref="SubscriptionTransportCapacity.ForDataPlane"/>).</summary>
|
||||
internal int? MaxPerSession => _maxPerSession;
|
||||
|
||||
/// <summary>
|
||||
/// #1057: acquires a permit charged to <paramref name="session"/> as well as its principal. With a per-session cap
|
||||
/// configured, a <paramref name="background"/> 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.
|
||||
/// </summary>
|
||||
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; }
|
||||
/// <summary>Charges actual snapshot bytes immediately before the delivery handoff; no waiting queue.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
+25
-2
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1057: snapshot permits each stream may hold at once. A projected cohort keeps at most 4 commands or snapshots
|
||||
/// outstanding (<c>ProjectedDataAccess</c> <c>MaxOutstandingCommands</c>); the other half is room for the session's own
|
||||
/// background recoveries, which may never take more than half (<see cref="SnapshotAdmissionScheduler.TryAcquire(string, object?, bool, long, out IDisposable?)"/>).
|
||||
/// </summary>
|
||||
internal const int SnapshotSlotsPerStream = 8;
|
||||
|
||||
/// <summary>
|
||||
/// #1057: the data plane's capacity. Snapshot admission used to be capped at <paramref name="streamsPerPrincipal"/>
|
||||
/// 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 <see cref="SnapshotSlotsPerStream"/> 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.
|
||||
/// </summary>
|
||||
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)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user