fix(grpc-data): H4 review 1 — count every projected history answer where its status is set

The consumer reads counter was fed from the gateway's outcomes, so limiter refusals, a spent
deadline, a count mismatch and refusals before the gateway were never counted, and a serve-time
fault after the gateway returned counted Good. The node manager now reports each projected node
once with the status the client sees (IProjectedHistoryAccess.RecordAnswered); a fault that
escapes to the SDK counts every projected node of the request Bad. Variant gains 'modified'.
This commit is contained in:
Joseph Doherty
2026-11-24 08:35:55 -05:00
parent ce648523ab
commit 2f11a9c609
6 changed files with 186 additions and 21 deletions
@@ -105,4 +105,13 @@ public interface IProjectedHistoryAccess
/// <returns>One outcome per node.</returns>
Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken);
/// <summary>
/// H4 diagnostics: the projected answers of one request exactly as the client sees them — every projected node once, with
/// its final status (refusals before or instead of a remote call included; a request that faults counts every projected
/// node Bad). Called by the node manager after the request, outside <c>Lock</c>. Default: nothing is counted.
/// </summary>
/// <param name="variant">raw | processed | attime | modified.</param>
/// <param name="answers">Each projected node and the status the client got for it.</param>
void RecordAnswered(string variant, IReadOnlyList<(NodeId NodeId, uint StatusCode)> answers) { }
}
@@ -9955,7 +9955,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// respected (the same benign wiring race as <see cref="MaxTieClusterOverfetch"/>).
/// </summary>
/// <returns>The shared batch limiter semaphore.</returns>
private SemaphoreSlim GetHistoryReadBatchLimiter()
internal SemaphoreSlim GetHistoryReadBatchLimiter()
{
var gate = _historyReadBatchLimiter;
if (gate is not null) return gate;
@@ -50,7 +50,11 @@ public sealed partial class OtOpcUaNodeManager
ServeProjectedHistory(context, details, nodesToRead, projected, results, errors, started);
}
/// <summary>The projected half of a variable-history request.</summary>
/// <summary>
/// The projected half of a variable-history request. H4: every projected answer is counted once, with the status the client
/// sees, at the point that status is set; a fault that escapes to the SDK (the service then fails) counts every projected
/// node of the request Bad instead.
/// </summary>
private void ServeProjectedHistory(
ServerSystemContext context,
HistoryReadDetails details,
@@ -59,15 +63,67 @@ public sealed partial class OtOpcUaNodeManager
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors,
long started)
{
var answered = new List<(NodeId NodeId, uint StatusCode)>(handles.Count);
var access = ProjectedHistoryAccess;
try
{
ServeProjectedHistoryCore(context, details, nodesToRead, handles, results, errors, started, access, answered);
}
catch
{
answered.Clear();
foreach (var handle in handles) answered.Add((handle.NodeId, StatusCodes.BadInternalError.Code));
throw;
}
finally
{
RecordProjectedAnswers(access, details, answered);
}
}
/// <summary>The <c>variant</c> label of a HistoryRead's details.</summary>
internal static string HistoryVariant(HistoryReadDetails details) => details switch
{
ReadRawModifiedDetails { IsReadModified: true } => "modified",
ReadRawModifiedDetails => "raw",
ReadProcessedDetails => "processed",
ReadAtTimeDetails => "attime",
_ => "unknown",
};
private static void RecordProjectedAnswers(IProjectedHistoryAccess? access, HistoryReadDetails details,
List<(NodeId NodeId, uint StatusCode)> answered)
{
if (access is null || answered.Count == 0) return;
try { access.RecordAnswered(HistoryVariant(details), answered); }
catch (Exception ex) when (ex is not OutOfMemoryException) { } // diagnostics never fail a read
}
private void ServeProjectedHistoryCore(
ServerSystemContext context,
HistoryReadDetails details,
ArrayOf<HistoryReadValueId> nodesToRead,
List<NodeHandle> handles,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors,
long started,
IProjectedHistoryAccess? access,
List<(NodeId NodeId, uint StatusCode)> answered)
{
var session = context.OperationContext?.Session;
var store = _historyContinuationStore;
var epoch = Volatile.Read(ref _historyContinuationEpoch);
var access = ProjectedHistoryAccess;
var identity = IdentityOf(context);
var remote = ToRemoteDetails(details);
var aggregates = details is ReadProcessedDetails processed ? processed.AggregateType : default;
void Refuse(NodeHandle handle, StatusCode status)
{
SetProjectedStatus(handle, results, errors, status);
answered.Add((handle.NodeId, status.Code));
}
var pending = new List<(NodeHandle Handle, ProjectedHistoryNode Node)>(handles.Count);
ProjectedHistoryContinuation? claimed = null;
try
@@ -87,7 +143,7 @@ public sealed partial class OtOpcUaNodeManager
|| !cursor.TryClaimForResume())
{
state?.Remote?.Release();
SetProjectedStatus(handle, results, errors, StatusCodes.BadContinuationPointInvalid);
Refuse(handle, StatusCodes.BadContinuationPointInvalid);
continue;
}
@@ -99,7 +155,7 @@ public sealed partial class OtOpcUaNodeManager
{
// No projection gateway, no session identity, or a variant a remote read never serves (a modified read).
resume?.ReleaseEvenIfClaimed();
SetProjectedStatus(handle, results, errors, StatusCodes.BadHistoryOperationUnsupported);
Refuse(handle, StatusCodes.BadHistoryOperationUnsupported);
continue;
}
@@ -110,7 +166,7 @@ public sealed partial class OtOpcUaNodeManager
var aggregate = aggregates[handle.Index];
if (AggregateFunctionMap.Map(aggregate) is null || aggregate.NamespaceIndex != 0 || !aggregate.TryGetValue(out uint numeric))
{
SetProjectedStatus(handle, results, errors, StatusCodes.BadAggregateNotSupported);
Refuse(handle, StatusCodes.BadAggregateNotSupported);
continue;
}
@@ -143,7 +199,7 @@ public sealed partial class OtOpcUaNodeManager
if (!projectedSlots.Wait(0))
{
ReleaseResumes();
foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations);
foreach (var p in pending) Refuse(p.Handle, StatusCodes.BadTooManyOperations);
return;
}
@@ -181,7 +237,7 @@ public sealed partial class OtOpcUaNodeManager
}, p =>
{
p.Node.Resume?.ReleaseEvenIfClaimed();
SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations);
Refuse(p.Handle, StatusCodes.BadTooManyOperations);
});
}
finally
@@ -194,7 +250,7 @@ public sealed partial class OtOpcUaNodeManager
{
foreach (var o in outcomes) o.Continuation?.Release();
ReleaseResumes();
foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadInternalError);
foreach (var p in pending) Refuse(p.Handle, StatusCodes.BadInternalError);
return;
}
@@ -224,7 +280,7 @@ public sealed partial class OtOpcUaNodeManager
if (StatusCode.IsBad(status))
{
outcome.Continuation?.Release();
SetProjectedStatus(handle, results, errors, status);
Refuse(handle, status);
return;
}
@@ -247,6 +303,7 @@ public sealed partial class OtOpcUaNodeManager
HistoryData = new ExtensionObject(new HistoryData { DataValues = values }),
ContinuationPoint = cp is null ? default : ByteString.From(cp),
};
answered.Add((handle.NodeId, status.Code));
}
}
@@ -151,6 +151,22 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
DataValueKind.Guid => items.Cast<Guid>().ToArray(), _ => throw new ArgumentException("Unsupported array element kind.")
};
}
/// <summary>
/// H4 diagnostics: the deployed connection a projected node's mapping uses, without authorizing or pinning anything; null
/// when the node no longer resolves. Never an access decision.
/// </summary>
internal string? ConnectionOf(NodeId nodeId)
{
try
{
return _nodes.TryResolve(nodeId, out var definition) && definition is not null
&& _catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) && proof is not null
&& proof.Metadata.View.MappingId is { } mapping && _connectionForMapping(mapping) is { Length: > 0 } connectionId
? connectionId : null;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return null; }
}
public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand)
{
demand = null;
@@ -97,6 +97,18 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
await flush.ConfigureAwait(false);
}
/// <inheritdoc />
/// <remarks>
/// H4 review: counted by the node manager at the point each status is set (limiter refusals, a spent deadline, a count
/// mismatch and a serve-time fault included), not here from the gateway's outcomes. Each node is attributed to the
/// connection its mapping is deployed on, best effort (none when the node no longer resolves: metric only).
/// </remarks>
public void RecordAnswered(string variant, IReadOnlyList<(NodeId NodeId, uint StatusCode)> answers)
{
ArgumentNullException.ThrowIfNull(answers);
foreach (var (node, status) in answers) Diagnostics.RecordConsumerRead(_access.ConnectionOf(node), variant, status);
}
/// <summary>
/// Whether a projected node is advertised as historizing: the mapping (masked by the export) grants HistoryRead AND the
/// origin's negotiated metadata (<c>HistoryInfo</c>, bit 32) says historizing.
@@ -200,7 +212,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
left -= assembled[i];
}
return Recorded(outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray());
return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -216,21 +228,13 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
outcomes[i] = Fail(timedOut ? BadTimeout : ex is OperationCanceledException && resumed ? BadContinuationPointInvalid : BadNoCommunication);
}
return Recorded(outcomes.Select(o => o!).ToArray());
return outcomes.Select(o => o!).ToArray();
}
finally
{
foreach (var demand in demands) demand?.Dispose();
}
// H4: one count per node as answered to the local client, attributed to its connection when it resolved to one.
ProjectedHistoryOutcome[] Recorded(ProjectedHistoryOutcome[] answered)
{
var variant = DataConnectionHistoryDiagnostics.Variant(details);
for (var i = 0; i < answered.Length; i++) Diagnostics.RecordConsumerRead(targets[i]?.ConnectionId, variant, answered[i].StatusCode);
return answered;
}
TimeSpan Remaining() => deadline > TimeSpan.Zero
? deadline - _clock.GetElapsedTime(started)
: TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call
@@ -214,6 +214,76 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable
access.Issued[0].Released.ShouldBe(0, "the store owns the saved cursor");
}
[Fact]
[Trait("Phase", "H4")]
public async Task Every_projected_answer_is_recorded_once_with_the_status_the_client_sees()
{
// H4 review item 1: counted where the status is set — limiter refusals, a spent deadline, a count mismatch and a
// serve-time fault included — never from the gateway's outcomes alone.
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
var a = Project(nm, f, "Speed", historizing: true);
var b = Project(nm, f, "Flow", historizing: true);
var access = new FakeAccess();
nm.ProjectedHistoryAccess = access;
(string Variant, uint[] Statuses) Delta(Action act)
{
var before = access.Answered.Count;
act();
var added = access.Answered.Skip(before).ToArray();
added.Select(x => x.Variant).Distinct().Count().ShouldBe(1);
return (added[0].Variant, added.Select(x => x.Status).ToArray());
}
// Served: Good, once per node.
var served = Delta(() => Raw(nm, f.Identity, [a, b]));
served.Variant.ShouldBe("raw");
served.Statuses.ShouldBe([StatusCodes.Good.Code, StatusCodes.Good.Code]);
// Refused unsent by the consumer: an unknown aggregate, a modified read.
var processed = new ReadProcessedDetails { StartTime = T0, EndTime = T0.AddHours(1), ProcessingInterval = 60_000,
AggregateType = [new NodeId("not-an-aggregate", 2)] };
var unknown = Delta(() => Read(nm, f.Identity, processed, [a]));
unknown.Variant.ShouldBe("processed");
unknown.Statuses.ShouldBe([StatusCodes.BadAggregateNotSupported.Code]);
var modified = new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 5, IsReadModified = true };
var refused = Delta(() => Read(nm, f.Identity, modified, [a]));
refused.Variant.ShouldBe("modified");
refused.Statuses.ShouldBe([StatusCodes.BadHistoryOperationUnsupported.Code]);
// The non-local (projected) slot limiter saturated.
var nonLocal = nm.GetNonLocalHistoryLimiter();
var taken = 0;
while (nonLocal.Wait(0, TestContext.Current.CancellationToken)) taken++;
try { Delta(() => Raw(nm, f.Identity, [a, b])).Statuses.ShouldBe([StatusCodes.BadTooManyOperations.Code, StatusCodes.BadTooManyOperations.Code]); }
finally { nonLocal.Release(taken); }
// The shared batch limiter saturated (its admission wait is capped by the request deadline).
var batch = nm.GetHistoryReadBatchLimiter();
nm.HistoryReadDeadline = TimeSpan.FromMilliseconds(100);
taken = 0;
while (batch.Wait(0, TestContext.Current.CancellationToken)) taken++;
try { Delta(() => Raw(nm, f.Identity, [a])).Statuses.ShouldBe([StatusCodes.BadTooManyOperations.Code]); }
finally { batch.Release(taken); nm.HistoryReadDeadline = TimeSpan.FromSeconds(60); }
// The request deadline spent before the remote call.
nm.HistoryReadDeadline = TimeSpan.FromTicks(1);
try { Delta(() => Raw(nm, f.Identity, [a])).Statuses.ShouldBe([StatusCodes.BadTimeout.Code]); }
finally { nm.HistoryReadDeadline = TimeSpan.FromSeconds(60); }
// The gateway answered the wrong number of outcomes.
access.DropLast = true;
Delta(() => Raw(nm, f.Identity, [a, b])).Statuses.ShouldBe([StatusCodes.BadInternalError.Code, StatusCodes.BadInternalError.Code]);
access.DropLast = false;
// A serve-time fault after the gateway returned: the service fails, so every projected node counts Bad — never Good.
var poisoned = new FakeAccess { FirstValue = new object() };
nm.ProjectedHistoryAccess = poisoned;
Should.Throw<ArgumentException>(() => Raw(nm, f.Identity, [a, b]));
poisoned.Answered.Select(x => x.Status).ShouldBe([StatusCodes.BadInternalError.Code, StatusCodes.BadInternalError.Code]);
}
[Fact]
public void Unset_bounds_travel_absent_and_AtTime_carries_its_times()
{
@@ -470,6 +540,15 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable
/// <summary>When set, every call throws it (after claiming nothing — the cursors are the caller's to release).</summary>
public Exception? Throw { get; set; }
public int Entries;
/// <summary>When set, the answer omits the last node (an outcome count mismatch).</summary>
public bool DropLast { get; set; }
/// <summary>H4: what the node manager reported as answered, in order.</summary>
public readonly List<(string Variant, NodeId Node, uint Status)> Answered = [];
public void RecordAnswered(string variant, IReadOnlyList<(NodeId NodeId, uint StatusCode)> answers)
{
lock (Answered) foreach (var (node, status) in answers) Answered.Add((variant, node, status));
}
public async Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken)
@@ -479,7 +558,7 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable
if (Interlocked.Increment(ref Entries) > 0) Entered.TrySetResult();
if (Hold is { } hold) await hold.Task.ConfigureAwait(false);
if (Throw is { } error) throw error;
return (nodes.Select(node =>
return (nodes.Take(DropLast ? nodes.Count - 1 : nodes.Count).Select(node =>
{
FakeCursor? next = null;
if (Paged)