fix(grpc-data): A3b review r1 — per-item results after base.Call (S1), mapping timeout honoured + transport-known BadTimeout (S2), unsent vs OutcomeUnknown + origin failure status (S3), per-connection sub-limit + dispatch floor (S4), N1/N2/N3/N7/N8; tests: real-path L3, worst-case L2 harness, RefreshRequired over the wire, Confirm guards isolated, gate placements/realm, slots, standby, faults, principals

This commit is contained in:
Joseph Doherty
2026-11-24 19:59:21 -05:00
parent 01a4e8db9d
commit 72dece7f45
9 changed files with 787 additions and 76 deletions
@@ -62,10 +62,25 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
/// <summary>Most remote condition methods in flight on this node (§5.6: bounds upstream load, not threads).</summary>
internal const int DefaultImportedMethodConcurrency = 8;
/// <summary>
/// A3b review S4: most remote condition methods in flight to ONE connection — a sub-limit inside the node-wide
/// <see cref="DefaultImportedMethodConcurrency"/>, so a stalled origin holds at most half the node's slots and acks to
/// healthy origins still dispatch.
/// </summary>
internal const int DefaultImportedMethodConcurrencyPerConnection = 4;
/// <summary>How long past the call's own budget the node manager waits for the port before answering <c>BadTimeout</c>.</summary>
internal static readonly TimeSpan ImportedMethodGrace = TimeSpan.FromMilliseconds(250);
/// <summary>
/// A3b review S4: a call whose remaining budget at dispatch is below this is refused <c>BadTimeout</c> UNSENT — the origin
/// could apply it while the consumer had already answered <c>BadTimeout</c>.
/// </summary>
internal static readonly TimeSpan ImportedMethodMinimumDispatchBudget = TimeSpan.FromMilliseconds(250);
private readonly SemaphoreSlim _importedMethodSlots = new(DefaultImportedMethodConcurrency, DefaultImportedMethodConcurrency);
// One per connection that ever dispatched (connections are few and long-lived; never removed — a SemaphoreSlim is small).
private readonly ConcurrentDictionary<string, SemaphoreSlim> _importedMethodConnectionSlots = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, Task<ServiceResult>> _importedMethodsInFlight = new(StringComparer.Ordinal);
private long _importedMethodsDispatched, _importedMethodsJoined, _importedMethodsRefused;
@@ -85,7 +100,8 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
/// §5.6 step 1: (a) claim every unprocessed request whose ObjectId is in <c>mapped/conditions</c> — a namespace-index
/// test, no lock; (b) the unchanged synchronous <c>base.Call</c> for everything else (it skips claimed requests), run
/// and completed before any remote await; (c) the claimed calls concurrently, bounded by the per-node semaphore.
/// No <c>Lock</c> is held by this method at any point.
/// No <c>Lock</c> is held by this method at any point. Review S1: nothing after <c>base.Call</c> throws — local items are
/// already applied by then, so a fault there must become a per-item status, never a ServiceFault for the batch.
/// </summary>
public override async ValueTask CallAsync(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall,
IList<CallMethodResult> results, IList<ServiceResult> errors, CancellationToken cancellationToken = default)
@@ -109,10 +125,26 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
for (var k = 0; k < claimed.Count; k++)
{
results[claimed[k]] = new CallMethodResult();
calls[k] = CallImportedAsync(caller, methodsToCall[claimed[k]], deadline, linked.Token);
calls[k] = CallImportedGuardedAsync(caller, methodsToCall[claimed[k]], deadline, linked.Token);
}
// Each task is guarded (never faults), so WhenAll never throws; results are collected per item regardless.
await Task.WhenAll(calls).ConfigureAwait(false);
for (var k = 0; k < claimed.Count; k++) errors[claimed[k]] = calls[k].Result;
}
/// <summary>Review S1: <see cref="CallImportedAsync"/> as a task that cannot fault (a synchronous throw included).</summary>
private async Task<ServiceResult> CallImportedGuardedAsync(RoleCarryingUserIdentity? caller, CallMethodRequest request, DateTime deadline,
CancellationToken cancellationToken)
{
try
{
return await CallImportedAsync(caller, request, deadline, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "OtOpcUaNodeManager: imported condition method failed before dispatch");
return Refuse(StatusCodes.BadInternalError);
}
var outcomes = await Task.WhenAll(calls).ConfigureAwait(false);
for (var k = 0; k < claimed.Count; k++) errors[claimed[k]] = outcomes[k];
}
/// <summary>
@@ -133,7 +165,8 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
if (method == DataConditionMethods.None) return Refuse(StatusCodes.BadNotSupported); // shelve, enable/disable, …
if (ProjectedConditionMethods is not { } port) return Refuse(StatusCodes.BadNotSupported);
// Step 2 local checks (no I/O, no Lock). The mapping gate first: an unauthorized caller learns nothing else.
// Step 2 local checks (no I/O, no Lock). The mapping gate first: an unauthorized caller learns nothing else
// (review N5: the two answers above are the SDK pre-validation's own — the node and its method exist publicly).
var placements = condition.Placements;
var route = port.AuthorizeMethod(caller, placements, method);
if (route is null || caller is null) return Refuse(StatusCodes.BadUserAccessDenied);
@@ -157,6 +190,8 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
if (expected is null) return Refuse(StatusCodes.BadEventIdUnknown);
// An identical call already in flight (same caller, condition, EventId, method, comment) joins it: one dispatch.
// Review N4: a joiner shares the first caller's outcome — its cancellation and budget included (it asked for the
// same thing at the same moment; a joiner never dispatches a second time).
var key = string.Join('\n', caller.Principal, condition.Alarm.NodeId.ToString(), Convert.ToHexString(eventId.Span),
((uint)method).ToString(System.Globalization.CultureInfo.InvariantCulture), comment ?? "\u0001");
var mine = new TaskCompletionSource<ServiceResult>(TaskCreationOptions.RunContinuationsAsynchronously);
@@ -168,17 +203,22 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
}
try
{
var result = await DispatchImportedAsync(port, condition, route, method, expected, comment, caller, deadline, started,
cancellationToken).ConfigureAwait(false);
ServiceResult result;
try
{
result = await DispatchImportedAsync(port, condition, route, method, expected, comment, caller, deadline, started,
cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
// DispatchImportedAsync answers every post-dispatch failure itself: anything escaping it was thrown before
// the port was called — nothing was sent (review S1/S3).
_logger.LogError(ex, "OtOpcUaNodeManager: imported condition method failed before dispatch");
result = Refuse(StatusCodes.BadInternalError);
}
mine.TrySetResult(result);
return result;
}
catch (Exception ex)
{
var unknown = new ServiceResult(StatusCodes.BadCommunicationError, new LocalizedText("OutcomeUnknown: " + ex.GetType().Name));
mine.TrySetResult(unknown);
return unknown;
}
finally
{
_importedMethodsInFlight.TryRemove(new KeyValuePair<string, Task<ServiceResult>>(key, mine.Task));
@@ -194,22 +234,40 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
ImportedConditionMethodRoute route, DataConditionMethods method, DataActivationMarker expected, string? comment,
RoleCarryingUserIdentity caller, DateTime deadline, long started, CancellationToken cancellationToken)
{
// Step 4: timeout = min(request deadline, ConditionMethodTimeout).
var budget = route.Timeout;
// Step 4: timeout = min(request deadline, ConditionMethodTimeout), as ONE end instant (review N7: elapsed time was
// subtracted from the request-deadline leg twice). When the request deadline binds, the grace the node manager waits
// past the budget is taken out of it, so the answer still lands inside the client's TimeoutHint.
var end = started + (long)(route.Timeout.TotalSeconds * Stopwatch.Frequency);
if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue)
{
var left = deadline - DateTime.UtcNow;
if (left < budget) budget = left;
var byDeadline = Stopwatch.GetTimestamp() + (long)((deadline - DateTime.UtcNow - ImportedMethodGrace).TotalSeconds * Stopwatch.Frequency);
if (byDeadline < end) end = byDeadline;
}
budget -= Stopwatch.GetElapsedTime(started);
if (budget <= TimeSpan.Zero) return Refuse(StatusCodes.BadTimeout);
TimeSpan Remaining() => Stopwatch.GetElapsedTime(Stopwatch.GetTimestamp(), end);
if (Remaining() < ImportedMethodMinimumDispatchBudget) return Refuse(StatusCodes.BadTimeout);
if (!await _importedMethodSlots.WaitAsync(budget, cancellationToken).ConfigureAwait(false))
return Refuse(StatusCodes.BadTooManyOperations);
// Review S4: the connection's sub-limit first, then the node-wide slots. Review S3: a cancel while WAITING is unsent.
var perConnection = _importedMethodConnectionSlots.GetOrAdd(condition.ConnectionId,
static _ => new SemaphoreSlim(DefaultImportedMethodConcurrencyPerConnection, DefaultImportedMethodConcurrencyPerConnection));
bool connectionSlot = false, nodeSlot = false;
try
{
var remaining = budget - Stopwatch.GetElapsedTime(started);
if (remaining <= TimeSpan.Zero) return Refuse(StatusCodes.BadTimeout);
try
{
connectionSlot = await perConnection.WaitAsync(Remaining() is var w && w > TimeSpan.Zero ? w : TimeSpan.Zero, cancellationToken)
.ConfigureAwait(false);
if (!connectionSlot) return Refuse(StatusCodes.BadTooManyOperations);
nodeSlot = await _importedMethodSlots.WaitAsync(Remaining() is var n && n > TimeSpan.Zero ? n : TimeSpan.Zero, cancellationToken)
.ConfigureAwait(false);
if (!nodeSlot) return Refuse(StatusCodes.BadTooManyOperations);
}
catch (OperationCanceledException)
{
return Refuse(StatusCodes.BadRequestCancelledByClient); // nothing sent
}
var remaining = Remaining();
if (remaining < ImportedMethodMinimumDispatchBudget) return Refuse(StatusCodes.BadTimeout); // review S4 floor: unsent
var call = new ImportedConditionMethodCall(condition.ConnectionId, condition.ConditionKey, route.Placement, method, expected,
comment, "a3-" + Guid.NewGuid().ToString("N"), remaining, caller.Principal);
using var bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
@@ -224,6 +282,8 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
catch (TimeoutException)
{
// The port did not answer inside the budget: it may have reached the origin — OutcomeUnknown, never retried.
// Review N1: WaitAsync and CancelAfter share a due time; cancel explicitly so the port's call ends with it.
bounded.Cancel();
return Unknown(StatusCodes.BadTimeout, "OutcomeUnknown: no answer within the condition method timeout.");
}
catch (OperationCanceledException) when (bounded.IsCancellationRequested)
@@ -231,21 +291,29 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
return Unknown(cancellationToken.IsCancellationRequested ? StatusCodes.BadCommunicationError : StatusCodes.BadTimeout,
"OutcomeUnknown: the call was cancelled after dispatch.");
}
return MapOutcome(result, Stopwatch.GetElapsedTime(started) >= budget);
catch (Exception ex)
{
// The port is contracted not to throw for a remote failure; one that does may have sent the request.
return Unknown(StatusCodes.BadCommunicationError, "OutcomeUnknown: " + ex.GetType().Name);
}
return MapOutcome(result);
}
finally
{
_importedMethodSlots.Release();
if (nodeSlot) _importedMethodSlots.Release();
if (connectionSlot) perConnection.Release();
}
}
/// <summary>
/// §5.6 step 5 outcome mapping. Applied (scripted <c>DriverConfirmedSuccess</c>) and accepted (native
/// <c>AcceptedUnconfirmed</c>) ⇒ Good — the confirming record arrives on the stream; <c>RejectedBeforeDispatch</c> ⇒ the
/// origin's status; <c>OutcomeUnknown</c> ⇒ <c>BadTimeout</c> when the budget ran out, else <c>BadCommunicationError</c>
/// — always Bad (the client must not read it as done), with "OutcomeUnknown" in the diagnostic.
/// <c>AcceptedUnconfirmed</c>) ⇒ Good — the confirming record arrives on the stream; <c>RejectedBeforeDispatch</c> and
/// <c>DriverConfirmedFailure</c> ⇒ the origin's status (review S3: a definite failure is not "unknown");
/// <c>OutcomeUnknown</c> ⇒ the status the transport KNEW (review S2: <c>BadTimeout</c> on a deadline, else
/// <c>BadCommunicationError</c>) — always Bad (the client must not read it as done), with "OutcomeUnknown" in the
/// diagnostic.
/// </summary>
internal ServiceResult MapOutcome(DataConditionMethodResult result, bool budgetElapsed)
internal ServiceResult MapOutcome(DataConditionMethodResult result)
{
switch (result.State)
{
@@ -253,11 +321,13 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
case DataWriteState.AcceptedUnconfirmed:
return StatusCode.IsBad(new StatusCode(result.StatusCode)) ? new ServiceResult(new StatusCode(result.StatusCode)) : ServiceResult.Good;
case DataWriteState.RejectedBeforeDispatch:
case DataWriteState.DriverConfirmedFailure:
var refused = new StatusCode(result.StatusCode);
if (!StatusCode.IsBad(refused)) refused = StatusCodes.BadInternalError;
return result.Diagnostic is { Length: > 0 } text ? new ServiceResult(refused, new LocalizedText(text)) : new ServiceResult(refused);
default:
return Unknown(budgetElapsed ? StatusCodes.BadTimeout : StatusCodes.BadCommunicationError,
var known = new StatusCode(result.StatusCode);
return Unknown(StatusCode.IsBad(known) && known.Code == StatusCodes.BadTimeout.Code ? StatusCodes.BadTimeout : StatusCodes.BadCommunicationError,
"OutcomeUnknown: " + (result.Diagnostic ?? "the origin's outcome is unknown."));
}
}
@@ -324,8 +394,13 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
MintImportedEventId(condition, current);
return false;
}
if (previous is null || current is null || previous == current) return false;
if (state.TimeUtc is { } time && previousTime == time)
if (previous == current) return false;
// Review N3: a marker appearing or disappearing is a marker change too — mint and refresh, never leave the current
// EventId bound to a marker no record carries. Review N2: re-binding (F6) is for an origin RESTART only — a new
// incarnation re-announcing the same state at the same time; a same-incarnation sequence bump is, by the origin's
// definition, a new occurrence.
if (previous is not null && current is not null && previous.Incarnation != current.Incarnation
&& state.TimeUtc is { } time && previousTime == time)
{
var node = condition.RecentEvents.First;
while (node is not null)
@@ -19,7 +19,15 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec
public AlarmConditionState Alarm { get; } = alarm;
public string ConnectionId { get; } = connectionId;
public string ConditionKey { get; } = conditionKey;
public IReadOnlyList<ImportedConditionPlacement> Placements { get; set; } = [];
private IReadOnlyList<ImportedConditionPlacement> _placements = [];
private long _supportedMethods = -1;
/// <summary>Written under <c>Lock</c>; read without it by A3b methods (review N8: a volatile publication of an immutable list).</summary>
public IReadOnlyList<ImportedConditionPlacement> Placements
{
get => Volatile.Read(ref _placements);
set => Volatile.Write(ref _placements, value);
}
public HashSet<FolderState> Folders { get; } = new(ReferenceEqualityComparer.Instance);
/// <summary>NIT (review r1): an immutable copy of <see cref="Folders"/> for the delivery paths that read off <c>Lock</c>.</summary>
public FolderState[] WiredFolders { get; set; } = [];
@@ -34,7 +42,12 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec
/// marker under it, never under the node manager's <c>Lock</c>.</summary>
public object MethodGate { get; } = new();
/// <summary>The origin's <c>supported_methods</c> for the service principal (null until a listing carried it).</summary>
public uint? SupportedMethods { get; set; }
/// <remarks>Review N8: read without <c>Lock</c> by A3b methods — stored as one atomic 64-bit word (-1 = not listed yet).</remarks>
public uint? SupportedMethods
{
get => Interlocked.Read(ref _supportedMethods) is var v && v >= 0 ? (uint)v : null;
set => Interlocked.Exchange(ref _supportedMethods, value is { } m ? m : -1);
}
/// <summary>The <c>time</c> of the latest applied record (N6/F6: re-binding requires it unchanged).</summary>
public DateTimeOffset? LastTime { get; set; }
/// <summary>Bumped on every placement change (verdict caches key on it).</summary>
@@ -155,6 +168,13 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
/// <summary>Imported condition events reported (one per genuine origin transition).</summary>
internal long ImportedEventsReported => Interlocked.Read(ref _importedEventsReported);
/// <summary>How many N6 EventId slots a condition holds (test/diagnostic observation, the L2 harness).</summary>
internal int FindImportedConditionRecentEventCount(string connectionId, string conditionKey)
{
if (_importedConditions.Find(ImportedConditionNodeId(connectionId, conditionKey)) is not { } c) return 0;
lock (c.MethodGate) return c.RecentEvents.Count;
}
/// <summary>RefreshRequired events queued for imported conditions.</summary>
internal long ImportedRefreshRequiredQueued => Interlocked.Read(ref _importedRefreshRequired);
@@ -16,9 +16,17 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
public sealed partial class GrpcDataConnection : IDataConditionMethodService
{
internal const uint BadCommunicationError = 0x80050000u;
private TimeSpan _conditionMethodTimeout = TimeSpan.FromSeconds(5);
/// <summary>
/// The validator's ceiling for a mapping's <c>ConditionMethodTimeoutMilliseconds</c> (3,600,000 ms) — the client's default
/// backstop. A3b review S2: the per-MAPPING ceiling arrives in <see cref="DataConditionMethodRequest.RemainingBudget"/>
/// (the consumer node manager computes min(request deadline, mapping timeout) − elapsed); a connection-wide 5 s default
/// here silently capped a 30 s mapping at 5 s.
/// </summary>
public static readonly TimeSpan MaxConditionMethodTimeout = TimeSpan.FromMilliseconds(3_600_000);
/// <summary>The per-call method ceiling (the mapping's <c>ConditionMethodTimeoutMilliseconds</c>; A3 binds it per mapping).</summary>
private TimeSpan _conditionMethodTimeout = MaxConditionMethodTimeout;
/// <summary>An optional connection-wide backstop over the per-call budget (default <see cref="MaxConditionMethodTimeout"/>).</summary>
public TimeSpan ConditionMethodTimeout
{
get => _conditionMethodTimeout;
@@ -29,7 +37,9 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService
public async Task<DataConditionMethodResult> CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
request.Validate();
// A3b review S3: an invalid request is refused unsent, never thrown into a caller that would read it as "unknown".
try { request.Validate(); }
catch (ArgumentException ex) { return new(DataWriteState.RejectedBeforeDispatch, BadInvalidArgument, "Invalid request: " + ex.Message); }
var start = Clock.GetTimestamp();
var deadline = request.RemainingBudget < ConditionMethodTimeout ? request.RemainingBudget : ConditionMethodTimeout;
if (deadline <= TimeSpan.Zero) return new(DataWriteState.RejectedBeforeDispatch, BadTimeout, "Budget expired before dispatch.");
@@ -82,6 +92,12 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService
ex.StatusCode is StatusCode.PermissionDenied or StatusCode.Unauthenticated ? 0x801F0000u : BadNotSupportedMethod,
"Refused by the origin transport: " + ex.StatusCode);
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.DeadlineExceeded && !cancellationToken.IsCancellationRequested)
{
// A3b review S2: the deadline is a KNOWN timeout — say BadTimeout here instead of letting the caller infer it
// from its own clock. Still OutcomeUnknown: the origin may have applied it.
return new(DataWriteState.OutcomeUnknown, BadTimeout, "OutcomeUnknown: no answer before the method deadline.");
}
catch (Exception ex) when (ex is RpcException or HttpRequestException or OperationCanceledException or InvalidOperationException
or ArgumentException or IOException)
{
@@ -99,4 +115,5 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService
}
private const uint BadNotSupportedMethod = 0x803D0000u;
private const uint BadInvalidArgument = 0x80AB0000u;
}
@@ -18,6 +18,7 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionMethod
private const uint BadNoCommunication = 0x80310000u;
private const uint BadNotSupported = 0x803D0000u;
private const uint BadUserAccessDenied = 0x801F0000u;
private const uint BadInvalidArgument = 0x80AB0000u;
/// <inheritdoc />
public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements,
@@ -57,6 +58,12 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionMethod
if (serving is null)
return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "No condition stream is open on the connection.");
var request = new DataConditionMethodRequest(call.OperationId, call.Placement.Placement, call.Method, call.ExpectedActivation,
call.Comment, serving.Incarnation, call.RemainingBudget, call.OnBehalfOf);
// A3b review S3: validated before the lease — an invalid request is refused unsent, never an "unknown" outcome.
try { request.Validate(); }
catch (ArgumentException ex) { return new(DataWriteState.RejectedBeforeDispatch, BadInvalidArgument, "Invalid request: " + ex.Message); }
IGrpcDataAdapterConnectionLease? lease;
try { lease = await _connections.AcquireAsync(call.ConnectionId, cancellationToken).ConfigureAwait(false); }
catch (Exception ex) when (ex is InvalidOperationException or OperationCanceledException or TimeoutException)
@@ -66,8 +73,6 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionMethod
{
if (lease.Connection is not IDataConditionMethodService methods)
return new(DataWriteState.RejectedBeforeDispatch, BadNotSupported, "The connection does not serve condition methods.");
var request = new DataConditionMethodRequest(call.OperationId, call.Placement.Placement, call.Method, call.ExpectedActivation,
call.Comment, serving.Incarnation, call.RemainingBudget, call.OnBehalfOf);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lease.CancellationToken);
try
{