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