fix(alarms): #937 review r2 — deadline/poison refusals unsent, Call size quota, expired asks skip the engine, mutation-counter revert guard

M1: a scripted method whose request deadline leaves < the dispatch floor, or that
follows an unanswered scripted method in the same Call, is refused BadTimeout in
its handler (unsent, unapplied); OpcUa:Quotas:MaxNodesPerMethodCall = 1000.
M2: ExecuteAlarmCommand carries the asker's deadline; an expired ask skips the
engine and is not remembered (the broadcast copy applies).
L1: revert guarded by a per-condition mutation counter; raw severity restored.
L5 + nits: docs, stale comment. SDK check: no Part 9 handler calls our delegate
before its own validation.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-11-28 12:47:08 -05:00
parent 2d54d9d671
commit e42e666a1d
12 changed files with 249 additions and 25 deletions
@@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Server;
using System.Runtime.CompilerServices;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
@@ -48,14 +49,25 @@ public sealed partial class OtOpcUaNodeManager
/// <summary>The default node-wide cap on outstanding scripted-command asks.</summary>
internal const int DefaultMaxScriptedCommandsInFlight = 64;
/// <summary>The shortest bound a local call is given (the request deadline can be closer than this; the SDK then answers
/// the client's timeout itself).</summary>
private static readonly TimeSpan MinimumScriptedCommandBound = TimeSpan.FromMilliseconds(50);
private static readonly AsyncLocal<PendingScriptedCommand?> PendingScriptedCommandSlot = new();
private int _scriptedCommandsInFlight;
/// <summary>
/// #937 review r2 L1: a per-condition-instance mutation counter, bumped (under <c>Lock</c>) by every projection, every
/// reported condition event and every accepted method — the proof a pending revert needs that nothing changed the
/// node since its method. A field comparison missed changes that leave every compared field equal (a Timed→Timed
/// re-shelve, a ClientUserId change). Keyed by instance, so a torn-down condition takes its counter with it.
/// </summary>
private readonly System.Runtime.CompilerServices.ConditionalWeakTable<AlarmConditionState, StrongBox<long>> _conditionMutations = new();
/// <summary>Counts one mutation of <paramref name="condition"/>. Caller holds <c>Lock</c>.</summary>
private void BumpConditionMutation(AlarmConditionState condition) => _conditionMutations.GetOrCreateValue(condition).Value++;
/// <summary>The mutation count of <paramref name="condition"/>. Caller holds <c>Lock</c>.</summary>
private long ConditionMutationOf(AlarmConditionState condition) => _conditionMutations.GetOrCreateValue(condition).Value;
/// <summary>
/// #937 layer 1: returns why this node's scripted-alarm engine would reject any operator command right now (its last
/// load failed), or null to proceed. Called under <c>Lock</c>: MUST be a lock-free read, no I/O. Null ⇒ no pre-check.
@@ -84,9 +96,12 @@ public sealed partial class OtOpcUaNodeManager
/// is set the moment that call returns: an <c>AsyncLocal</c> value is captured by anything the SDK starts inside it (a
/// TimedShelve's timer), so a later callback must find the slot closed rather than park an ask nobody awaits.
/// </summary>
private sealed class PendingScriptedCommand(TimeSpan timeout)
private sealed class PendingScriptedCommand(TimeSpan timeout, ServiceResult? refusal = null)
{
public TimeSpan Timeout { get; } = timeout;
/// <summary>Set ⇒ a scripted method in this request is refused with it in the handler, unsent and unapplied
/// (review r2 M1: the request deadline is too close, or an earlier scripted method of the batch got no answer).</summary>
public ServiceResult? Refusal { get; } = refusal;
public Task<AlarmCommandOutcome>? Outcome { get; set; }
public ScriptedMethodRevert? Revert { get; set; }
public volatile bool Closed;
@@ -97,7 +112,7 @@ public sealed partial class OtOpcUaNodeManager
/// the engine refuses, and the post-call state that proves nothing else has changed the node since.
/// </summary>
private sealed record ScriptedMethodRevert(RealmKey Key, AlarmConditionState Alarm, AlarmConditionSnapshot Before,
LocalizedText? BeforeComment, string? BeforeClientUserId, AlarmConditionDelta After, LocalizedText? AfterComment);
ushort BeforeSeverity, LocalizedText? BeforeComment, string? BeforeClientUserId, long AfterMutation);
/// <summary>The slot of the request being called on this flow, when it is still open.</summary>
private static PendingScriptedCommand? OpenScriptedSlot() => PendingScriptedCommandSlot.Value is { Closed: false } slot ? slot : null;
@@ -110,6 +125,7 @@ public sealed partial class OtOpcUaNodeManager
private ServiceResult? TryStartScriptedCommandAsk(AlarmCommand cmd)
{
if (OpenScriptedSlot() is not { Outcome: null } pending || AlarmCommandAsker is not { } asker) return null;
if (pending.Refusal is { } refused) return refused;
if (Interlocked.Increment(ref _scriptedCommandsInFlight) > MaxScriptedCommandsInFlight)
{
Interlocked.Decrement(ref _scriptedCommandsInFlight);
@@ -147,7 +163,8 @@ public sealed partial class OtOpcUaNodeManager
delta.Shelving == AlarmShelvingKind.Timed && _conditionUnshelveAt.TryGetValue(key, out var unshelveAt) ? unshelveAt : null);
var comment = alarm.Comment?.Value;
var clientUserId = alarm.ClientUserId?.Value;
return () => new ScriptedMethodRevert(key, alarm, before, comment, clientUserId, ReadConditionDelta(alarm), alarm.Comment?.Value);
var severity = alarm.Severity?.Value ?? (ushort)0;
return () => new ScriptedMethodRevert(key, alarm, before, severity, comment, clientUserId, ConditionMutationOf(alarm));
}
/// <summary>From <c>ReportAfterMethod</c>, under <c>Lock</c>, after a Good method applied and reported: park the revert
@@ -168,7 +185,7 @@ public sealed partial class OtOpcUaNodeManager
lock (Lock)
{
if (!_alarmConditions.TryGetValue(revert.Key, out var live) || !ReferenceEquals(live, revert.Alarm)
|| ReadConditionDelta(live) != revert.After || !Equals(live.Comment?.Value, revert.AfterComment))
|| ConditionMutationOf(live) != revert.AfterMutation)
{
_logger.LogInformation(
"OtOpcUaNodeManager: refused scripted command on {Condition} not reverted — the condition changed since the call",
@@ -181,15 +198,20 @@ public sealed partial class OtOpcUaNodeManager
_conditionUnshelveAt[revert.Key] = unshelveAt;
else _conditionUnshelveAt.Remove(revert.Key);
ApplyConditionState(live, revert.Before, now);
// The raw captured severity: ApplyConditionState clamps to 1..1000, which would turn a 0 into 1.
if (live.Severity is not null && live.Severity.Value != revert.BeforeSeverity) live.Severity.Value = revert.BeforeSeverity;
if (live.Comment is not null) live.Comment.Value = revert.BeforeComment ?? LocalizedText.Null;
if (live.ClientUserId is not null) live.ClientUserId.Value = revert.BeforeClientUserId ?? string.Empty;
ReportConditionEvent(live, now);
}
}
/// <summary>The bound for one local request: <see cref="ScriptedCommandTimeout"/>, cut by the request deadline (less a
/// grace, so the answer still lands inside the client's TimeoutHint).</summary>
private TimeSpan ScriptedCommandBound(DateTime deadline)
/// <summary>
/// The bound for one local request: <see cref="ScriptedCommandTimeout"/>, cut by the request deadline (less a grace, so
/// the answer still lands inside the client's TimeoutHint). Null ⇒ the deadline leaves less than the dispatch floor:
/// a scripted method in this request must be refused unsent (review r2 M1 — it used to be floored and sent anyway).
/// </summary>
private TimeSpan? ScriptedCommandBound(DateTime deadline)
{
var bound = ScriptedCommandTimeout;
if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue)
@@ -197,7 +219,7 @@ public sealed partial class OtOpcUaNodeManager
var byDeadline = deadline - DateTime.UtcNow - ImportedMethodGrace;
if (byDeadline < bound) bound = byDeadline;
}
return bound < MinimumScriptedCommandBound ? MinimumScriptedCommandBound : bound;
return bound < ImportedMethodMinimumDispatchBudget ? null : bound;
}
/// <summary>
@@ -206,12 +228,12 @@ public sealed partial class OtOpcUaNodeManager
/// asker wired).
/// </summary>
private PendingScriptedCommand? CallOneAwaitingVerdict(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall, int index,
IList<CallMethodResult> results, IList<ServiceResult> errors, TimeSpan bound)
IList<CallMethodResult> results, IList<ServiceResult> errors, TimeSpan bound, ServiceResult? refusal)
{
var request = methodsToCall[index];
var singleResults = new List<CallMethodResult> { results[index] };
var singleErrors = new List<ServiceResult> { errors[index] };
var pending = new PendingScriptedCommand(bound);
var pending = new PendingScriptedCommand(bound, refusal);
PendingScriptedCommandSlot.Value = pending;
try
{
@@ -228,8 +250,9 @@ public sealed partial class OtOpcUaNodeManager
return pending.Outcome is not null && ServiceResult.IsGood(singleErrors[0]) ? pending : null;
}
/// <summary>The request's final status from its engine verdict, reverting the node on a refusal. Never throws.</summary>
private async Task<ServiceResult> SettleScriptedVerdictAsync(PendingScriptedCommand pending, TimeSpan bound)
/// <summary>The request's final status from its engine verdict (and whether it is an OutcomeUnknown), reverting the node
/// on a refusal. Never throws.</summary>
private async Task<(ServiceResult Status, bool Unknown)> SettleScriptedVerdictAsync(PendingScriptedCommand pending, TimeSpan bound)
{
var (status, unknown) = await AwaitScriptedVerdictAsync(pending.Outcome!, bound).ConfigureAwait(false);
if (!ServiceResult.IsGood(status) && !unknown && pending.Revert is { } revert)
@@ -243,7 +266,7 @@ public sealed partial class OtOpcUaNodeManager
_logger.LogError(ex, "OtOpcUaNodeManager: reverting a refused scripted command failed");
}
}
return status;
return (status, unknown);
}
/// <summary>