fix(grpc-data): #922 review r1 — own renewal pool + queue, bounded HistoryRead wait, two-authority denial, per-op keys

This commit is contained in:
Joseph Doherty
2026-11-28 10:54:10 -05:00
parent b569d5c5dd
commit 7e924deda9
6 changed files with 351 additions and 24 deletions
@@ -201,13 +201,20 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireException); return false; }
}
// #922: at most one on-demand renewal per projected node; a failed one is not retried for a short back-off so a client
// polling a node whose origin is unreachable cannot turn every Read into a metadata call.
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier), Task<bool>> _lapseRenewals = new();
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier), long> _lapseRenewalBackoff = new();
// #922: at most one on-demand renewal per projected node AND operation (each requests its own bit at the origin); a failed
// one is not retried for a short back-off so a client polling a node whose origin is unreachable cannot turn every Read into
// a metadata call. Renewals never use the unary budget (that would starve cold reads, writes and subscription renewals):
// they queue — at most MaxQueuedLapseRenewals — for the resolver's own on-demand pool, so a batch of N lapsed nodes renews
// them all, a few at a time.
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), Task<bool>> _lapseRenewals = new();
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), long> _lapseRenewalBackoff = new();
private const int MaxLapseRenewalBackoffEntries = 4096;
internal const int MaxQueuedLapseRenewals = 64;
internal static readonly TimeSpan LapseRenewalBackoff = TimeSpan.FromMilliseconds(250);
internal static readonly TimeSpan LapseRenewalTimeout = TimeSpan.FromSeconds(5);
/// <summary>The whole on-demand renewal, pool wait included; clearly shorter than the longest a HistoryRead waits for it.</summary>
internal static readonly TimeSpan LapseRenewalTimeout = TimeSpan.FromSeconds(3);
/// <summary>One metadata item and its capability probe: never a multi-MiB unary reservation.</summary>
internal const long LapseRenewalBytes = 256 * 1024;
internal int LapseRenewalsStartedForTests => Volatile.Read(ref _lapseRenewalsStarted);
private int _lapseRenewalsStarted;
@@ -234,8 +241,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
// refused exactly as before, and never causes an origin call.
if (!_policy.AuthorizeMappedSubject(identity, Operation(operation), proof.Metadata.View, proof.Lease.Serving, proof.Subject, proof.Resolver))
return ProjectedLapseOutcome.Denied;
var key = (definition.Realm, definition.LocalIdentifier);
var budget = new DataBudget(LapseRenewalTimeout, 1, _limits.MaxUnaryBytes);
var key = (definition.Realm, definition.LocalIdentifier, operation);
var budget = new DataBudget(LapseRenewalTimeout, 1, Math.Min(LapseRenewalBytes, _limits.MaxUnaryBytes));
TaskCompletionSource<bool> started;
lock (_sync)
{
@@ -247,9 +254,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (now < until) return ProjectedLapseOutcome.Unavailable;
_lapseRenewalBackoff.Remove(key);
}
if (_unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes)
return ProjectedLapseOutcome.Unavailable;
_unaryCount++; _unaryBytes += budget.MaxBytes;
if (_lapseRenewals.Count >= MaxQueuedLapseRenewals) return ProjectedLapseOutcome.Unavailable;
started = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_lapseRenewals.Add(key, started.Task);
}
@@ -263,7 +268,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
}
private async Task RunLapseRenewalAsync(RemoteNamespaceResolver resolver, IProjectedNamespacePageSink sink,
(DataRealm Realm, string LocalIdentifier) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
(DataRealm Realm, string LocalIdentifier, DataOperations Operation) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
RoleCarryingUserIdentity caller, DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource<bool> completion)
{
var renewed = false;
@@ -271,18 +276,17 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{
renewed = await resolver.RenewExactAsync(proof, definition, nodeId, identity, null, sink, budget,
() => { lock (_sync) return !_disposed; }, CancellationToken.None, overlap: false,
authorizeAs: Operation(operation), required: operation).ConfigureAwait(false);
authorizeAs: Operation(operation), required: operation, onDemand: true).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException) { renewed = false; }
finally
{
lock (_sync)
{
_unaryCount--; _unaryBytes -= budget.MaxBytes;
_lapseRenewals.Remove(key);
if (!renewed && !_disposed)
{
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) _lapseRenewalBackoff.Clear();
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) EvictLapseBackoffLocked();
var delay = (long)(LapseRenewalBackoff.TotalSeconds * Clock.TimestampFrequency);
_lapseRenewalBackoff[key] = Clock.GetTimestamp() + Math.Max(1, delay);
}
@@ -303,6 +307,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
}
completion.TrySetResult(renewed);
}
// Full map (rare): drop the expired entries; if none expired, the one that expires first — never the whole map, which would
// let every node's back-off lapse at once.
private void EvictLapseBackoffLocked()
{
var now = Clock.GetTimestamp();
var expired = _lapseRenewalBackoff.Where(entry => entry.Value <= now).Select(entry => entry.Key).ToArray();
foreach (var key in expired) _lapseRenewalBackoff.Remove(key);
if (expired.Length == 0) _lapseRenewalBackoff.Remove(_lapseRenewalBackoff.MinBy(entry => entry.Value).Key);
}
/// <summary>The per-read byte budget the SDK Read path schedules a cold projected read with.</summary>
internal const long ProjectedReadBytes = 4 * 1024 * 1024;
internal bool TryAcquireConfigured(NodeId nodeId, ConfiguredProjectionCapability capability, out IProjectedDemandLease? demand)