fix(grpc-data): maxAge=0 projected reads served from an awaited origin read; origin refusals are access denials; Write/CreateMonitoredItems renew lapsed leases (#938, #939, #940)

#938: OtOpcUaNodeManager implements IReadAsyncNodeManager. A projected Value read whose maxAge the
cache cannot satisfy (0 always: Part 4 "read the source"; ScadaBridge's DCL and the Client CLI send
0) is served from IProjectedDataAccess.ReadNowAsync in the same request — same unary admission,
authenticated freshness-checked read and cache publication as ScheduleRead, pumped through the
unary budget, at most 5 s / request deadline − 250 ms, no Lock, no blocked thread. A lapsed lease
is renewed first and read in the same request. Previously every maxAge=0 read answered
BadWaitingForInitialData forever.

#939: RemoteNamespaceResolver.RenewExactOutcomeAsync reports Renewed/Refused/Failed. Refused only
for the origin's verdict (PERMISSION_DENIED call, Denied item, Metadata not granted, operation not
granted / not writable) ⇒ BadUserAccessDenied, held 5 s per node+operation unsent; transport and
other failures stay retryable. HistoryRead follows it.

#940: RenewLapsed accepts Write (gated on the local write role) and Subscribe. WriteAsync awaits the
renewal (≤ 4 s, ≤ half the timeout hint) then dispatches, BadResourceUnavailable unsent otherwise.
CreateMonitoredItems awaits renewals once per request (ICreateMonitoredItemsAsyncNodeManager) and
classifies each projected item PER ITEM outside Lock (lapse ⇒ BadResourceUnavailable, refusal ⇒
BadUserAccessDenied) — a refusal thrown from the item manager used to fault the whole request.

Red/green: 15 wire tests in GrpcDataProjectedOriginAccessWireTests (12 red on the pre-fix source,
controls green both ways); 4 existing tests updated where the first read is now Good. Evidence:
docs/plans/evidence/grpc-data-ext/938-939-940-948.md.
This commit is contained in:
Joseph Doherty
2026-12-01 19:55:49 -05:00
parent 4fcabdf24a
commit 62d9504868
15 changed files with 1151 additions and 131 deletions
@@ -208,11 +208,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
// 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 readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), Task<ProjectedRenewalResult>> _lapseRenewals = new();
// #939: a failed renewal backs off briefly (Refused = false ⇒ retryable); a definitive ORIGIN refusal is held longer and
// answered Denied (BadUserAccessDenied) without another origin call until it expires.
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), (long Until, bool Refused)> _lapseRenewalBackoff = new();
private const int MaxLapseRenewalBackoffEntries = 4096;
internal const int MaxQueuedLapseRenewals = 64;
internal static readonly TimeSpan LapseRenewalBackoff = TimeSpan.FromMilliseconds(250);
/// <summary>#939: how long a definitive origin refusal of a lapsed node's renewal is answered <c>BadUserAccessDenied</c> unsent.</summary>
internal static readonly TimeSpan LapseRefusalHold = 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>
@@ -221,11 +225,12 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
private int _lapseRenewalsStarted;
/// <inheritdoc />
public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task<bool>? renewal)
public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation,
out Task<ProjectedRenewalResult>? renewal)
{
renewal = null;
if (caller is null || operation is not (DataOperations.Read or DataOperations.HistoryRead) || _renewalSink is not { } sink ||
_catalog is not RemoteNamespaceResolver resolver) return ProjectedLapseOutcome.Denied;
if (caller is null || operation is not (DataOperations.Read or DataOperations.HistoryRead or DataOperations.Write or DataOperations.Subscribe) ||
_renewalSink is not { } sink || _catalog is not RemoteNamespaceResolver resolver) return ProjectedLapseOutcome.Denied;
try
{
// The SDK node must still be live, and either it or its catalog proof must have lapsed — a refusal of a node whose
@@ -235,9 +240,13 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
definition.AuthorityIsCurrent() && _catalog.IsUsableProof(proof) ||
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) ||
proof.Metadata.View.MappingId is not { } mapping || _connectionForMapping(mapping) is not { Length: > 0 } ||
(operation == DataOperations.Read && proof.MaximumSampleAge <= TimeSpan.Zero) ||
(operation is DataOperations.Read or DataOperations.Subscribe && proof.MaximumSampleAge <= TimeSpan.Zero) ||
(operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))))
return ProjectedLapseOutcome.Denied;
// #940: a write is also gated on this node's local write role — a node that may not write refuses whatever the lease
// says, exactly as TryAcquire does.
if (operation == DataOperations.Write && _localWriteRole() is not { Allowed: true, Generation: > 0 })
return ProjectedLapseOutcome.Denied;
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
// The same grant the served operation needs, judged on everything but the lapsed lease: a caller without it is
// refused exactly as before, and never causes an origin call.
@@ -245,24 +254,25 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
return ProjectedLapseOutcome.Denied;
var key = (definition.Realm, definition.LocalIdentifier, operation);
var budget = new DataBudget(LapseRenewalTimeout, 1, Math.Min(LapseRenewalBytes, _limits.MaxUnaryBytes));
TaskCompletionSource<bool> started;
TaskCompletionSource<ProjectedRenewalResult> started;
lock (_sync)
{
if (_disposed) return ProjectedLapseOutcome.Unavailable;
if (_lapseRenewals.TryGetValue(key, out var running)) { renewal = running; return ProjectedLapseOutcome.Renewing; }
var now = Clock.GetTimestamp();
if (_lapseRenewalBackoff.TryGetValue(key, out var until))
if (_lapseRenewalBackoff.TryGetValue(key, out var held))
{
if (now < until) return ProjectedLapseOutcome.Unavailable;
// #939: a recent definitive origin refusal is an access denial, answered without another origin call.
if (now < held.Until) return held.Refused ? ProjectedLapseOutcome.Denied : ProjectedLapseOutcome.Unavailable;
_lapseRenewalBackoff.Remove(key);
}
if (_lapseRenewals.Count >= MaxQueuedLapseRenewals) return ProjectedLapseOutcome.Unavailable;
started = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
started = new TaskCompletionSource<ProjectedRenewalResult>(TaskCreationOptions.RunContinuationsAsynchronously);
_lapseRenewals.Add(key, started.Task);
}
Interlocked.Increment(ref _lapseRenewalsStarted);
// Never on the caller's thread: the renewal awaits the origin and commits through the SDK sink (node-manager Lock).
_ = Task.Run(() => RunLapseRenewalAsync(resolver, sink, key, proof, definition, nodeId, caller, identity, operation, budget, started));
_ = Task.Run(() => RunLapseRenewalAsync(resolver, sink, key, proof, definition, nodeId, identity, operation, budget, started));
renewal = started.Task;
return ProjectedLapseOutcome.Renewing;
}
@@ -271,52 +281,42 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
private async Task RunLapseRenewalAsync(RemoteNamespaceResolver resolver, IProjectedNamespacePageSink sink,
(DataRealm Realm, string LocalIdentifier, DataOperations Operation) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
RoleCarryingUserIdentity caller, DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource<bool> completion)
DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource<ProjectedRenewalResult> completion)
{
var renewed = false;
var result = ProjectedRenewalResult.Failed;
try
{
renewed = await resolver.RenewExactAsync(proof, definition, nodeId, identity, null, sink, budget,
result = await resolver.RenewExactOutcomeAsync(proof, definition, nodeId, identity, null, sink, budget,
() => { lock (_sync) return !_disposed; }, CancellationToken.None, overlap: false,
authorizeAs: Operation(operation), required: operation, onDemand: true).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException) { renewed = false; }
catch (Exception ex) when (ex is not OutOfMemoryException) { result = ProjectedRenewalResult.Failed; }
finally
{
lock (_sync)
{
_lapseRenewals.Remove(key);
if (!renewed && !_disposed)
if (result != ProjectedRenewalResult.Renewed && !_disposed)
{
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) EvictLapseBackoffLocked();
var delay = (long)(LapseRenewalBackoff.TotalSeconds * Clock.TimestampFrequency);
_lapseRenewalBackoff[key] = Clock.GetTimestamp() + Math.Max(1, delay);
var refused = result == ProjectedRenewalResult.Refused;
var delay = (long)((refused ? LapseRefusalHold : LapseRenewalBackoff).TotalSeconds * Clock.TimestampFrequency);
_lapseRenewalBackoff[key] = (Clock.GetTimestamp() + Math.Max(1, delay), refused);
}
}
}
// A Read answered retryable while the lease renewed: fetch the value now, through the ordinary authorized path, so the
// client's retry is served from the fresh sample instead of starting another cold read.
if (renewed && operation == DataOperations.Read)
{
IProjectedDemandLease? demand = null;
try
{
if (TryAcquire(nodeId, caller, DataOperations.Read, out demand) && demand is not null &&
ScheduleRead(demand, new DataBudget(LapseRenewalTimeout, 1, ProjectedReadBytes), Clock.GetTimestamp())) demand = null;
}
catch (Exception ex) when (ex is not OutOfMemoryException) { }
finally { demand?.Dispose(); }
}
completion.TrySetResult(renewed);
// #938: the Read that started this renewal reads the origin itself, within its own request, once it commits — so the
// renewal no longer schedules a separate cache-warming read.
completion.TrySetResult(result);
}
// 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();
var expired = _lapseRenewalBackoff.Where(entry => entry.Value.Until <= 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);
if (expired.Length == 0) _lapseRenewalBackoff.Remove(_lapseRenewalBackoff.MinBy(entry => entry.Value.Until).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;
@@ -860,21 +860,46 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
}
public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp)
{
if (demand is not Demand item || item.RequestedOperation != DataOperations.Read || !item.IsValid || budget is null) return false;
if (!TryAdmitRead(demand, budget, requestStartedTimestamp, out var item, out var boundedBudget)) return false;
_ = Task.Run(() => ReadCoreAsync(item!, boundedBudget!, requestStartedTimestamp, CancellationToken.None, ownsDemand: true)); return true;
}
/// <inheritdoc />
public Task<ProjectedOriginRead> ReadNowAsync(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp,
CancellationToken cancellationToken)
{
// #938: the same admission (unary count + bytes) and the same authenticated, freshness-checked, cache-publishing read as
// ScheduleRead — but the caller awaits it and is served what it read. The caller keeps the demand. Admission is decided
// here, synchronously, so NotAdmitted is an already-completed task.
if (cancellationToken.IsCancellationRequested) return Task.FromResult(ProjectedOriginRead.NoValue);
if (!TryAdmitRead(demand, budget, requestStartedTimestamp, out var item, out var boundedBudget))
return Task.FromResult(demand is Demand { IsValid: true } ? ProjectedOriginRead.NotAdmitted : ProjectedOriginRead.NoValue);
return Task.Run(async () =>
{
var value = await ReadCoreAsync(item!, boundedBudget!, requestStartedTimestamp, cancellationToken, ownsDemand: false).ConfigureAwait(false);
return value is null ? ProjectedOriginRead.NoValue : new ProjectedOriginRead(ProjectedOriginReadStatus.Served, value);
}, CancellationToken.None);
}
private bool TryAdmitRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp, out Demand? item, out DataBudget? boundedBudget)
{
item = null; boundedBudget = null;
if (demand is not Demand candidate || candidate.RequestedOperation != DataOperations.Read || !candidate.IsValid || budget is null) return false;
try { budget.Validate(); } catch (ArgumentException) { return false; }
var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false;
// The request's byte budget is an upper bound. Narrow it to this adapter's
// configured physical limit before admission and before remote dispatch.
var boundedBudget = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) };
var bounded = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) };
lock (_sync)
{
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || boundedBudget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) return false;
_unaryCount++; _unaryBytes += boundedBudget.MaxBytes;
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || bounded.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !candidate.TryHold()) return false;
_unaryCount++; _unaryBytes += bounded.MaxBytes;
}
_ = Task.Run(() => ReadCoreAsync(item, boundedBudget, requestStartedTimestamp)); return true;
item = candidate; boundedBudget = bounded;
return true;
}
private async Task ReadCoreAsync(Demand demand, DataBudget budget, long started)
// Returns the read sample when it is servable to the demand's caller: authenticated by the demand's current binding, fresh
// within the mapping's stale timeout, and published to (or already superseded in) the projection cache. Null otherwise.
private async Task<DataValueSnapshot?> ReadCoreAsync(Demand demand, DataBudget budget, long started, CancellationToken callerStop, bool ownsDemand)
{
IGrpcDataAdapterConnectionLease? connection = null;
try
@@ -882,14 +907,14 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
var original = demand.CurrentBinding;
var originalProof = original.Proof;
var remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (remaining <= TimeSpan.Zero || !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return;
if (remaining <= TimeSpan.Zero || !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return null;
var connectionId = _connectionForMapping(originalProof.Metadata.View.MappingId!);
if (string.IsNullOrWhiteSpace(connectionId)) return;
if (string.IsNullOrWhiteSpace(connectionId)) return null;
using var timeout = new CancellationTokenSource(remaining, Clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, demand.CancellationToken);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, demand.CancellationToken, callerStop);
connection = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false);
if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || connection.CancellationToken.IsCancellationRequested ||
!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return;
!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return null;
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
var readStarted = Clock.GetTimestamp();
var result = await connection.Connection.ReadAsync(new DataReadRequest([new ReadItem("0", originalProof.OriginMetadata.View, null)], budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
@@ -897,32 +922,36 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{
if (result.Count != 1 || result[0].CorrelationId != "0" || result[0].Status != DataItemStatus.Good || result[0].Readiness != DataReadiness.Ready ||
result[0].Sample is not { } sample || sample.Serving != originalProof.Lease.Serving || sample.Version <= 0 || !demand.IsValid ||
!ReferenceEquals(demand.CurrentBinding, original) || route.IsCancellationRequested) return;
!ReferenceEquals(demand.CurrentBinding, original) || route.IsCancellationRequested) return null;
result[0].AgeBounds.Validate();
// An unstamped implementation is conservatively anchored before the read call.
var received = result[0].FreshnessObservedTimestamp ?? readStarted;
if (!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return;
if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return;
if (!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return null;
if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return null;
var payload = DecodeValue(sample.Value, originalProof.OriginMetadata);
var snapshot = new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime);
var source = GetSource(demand, connectionId);
if (source is null) return;
if (source is null) return null;
lock (source.Gate)
{
if (!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original) || !source.IsValid || sample.Version <= source.LastVersion || route.IsCancellationRequested ||
!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return;
if (!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original) || !source.IsValid || route.IsCancellationRequested ||
!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return null;
// The cache already holds this acquisition or a newer one: nothing to publish, but what was read is still an
// authenticated, fresh origin sample of this request (#938 serves it).
if (sample.Version <= source.LastVersion) return snapshot;
var update = new ProjectedValueUpdate(source.Route, snapshot, result[0].AgeBounds, received, source.CaptureReadProof(originalProof), true, originalProof.MaximumSampleAge, sample.Version);
if (_publisher.TryPublish([update])) { source.LastVersion = sample.Version; source.CacheLocked(update, sample.Version); }
else if (!ProjectedEvidenceRetirement.CanDrop(update.SourceProof)) source.Invalidate();
if (_publisher.TryPublish([update])) { source.LastVersion = sample.Version; source.CacheLocked(update, sample.Version); return snapshot; }
if (!ProjectedEvidenceRetirement.CanDrop(update.SourceProof)) source.Invalidate();
return null;
}
}
finally { foreach (var item in result) item.Dispose(); }
}
catch (Exception) { }
catch (Exception) { return null; }
finally
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
finally { demand.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
finally { if (ownsDemand) demand.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
}
}
public async Task<DataWriteOutcome> WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget,