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
@@ -320,9 +320,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
});
// #937: a scripted condition's Part 9 method answers with THIS node's engine verdict. The pre-check (one volatile
// read) refuses while the last scripted-alarm load failed; the asker broadcasts the command to the redundant peer
// exactly as the router above does and asks the local engine (via the DriverHostActor) for its verdict. Both run
// under the SDK's Lock and only read / send; the node manager awaits the verdict off Lock.
// read) refuses while the last scripted-alarm load failed; the asker asks the local engine (via the DriverHostActor)
// for its verdict FIRST and broadcasts to the redundant peer only after an applied / unknown verdict
// (ScriptedAlarmCommandDispatch). Both run under the SDK's Lock and only read / send; the node manager awaits the
// verdict off Lock.
if (_scriptedAlarmReadiness is { } readiness)
_server.NodeManager.ScriptedAlarmCommandPreflight = readiness.Refusal;
_server.NodeManager.AlarmCommandAsker = AskScriptedAlarmCommand;
@@ -613,7 +614,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
private Task<AlarmCommandOutcome> AskScriptedAlarmCommand(AlarmCommand cmd, TimeSpan timeout)
{
Func<AlarmCommand, TimeSpan, Task<AlarmCommandOutcome>>? askLocal = _actorRegistry.TryGet<DriverHostActorKey>(out var driverHost)
? (c, t) => driverHost.Ask<AlarmCommandOutcome>(new ScriptedAlarmHostActor.ExecuteAlarmCommand(c), t)
? (c, t) => driverHost.Ask<AlarmCommandOutcome>(new ScriptedAlarmHostActor.ExecuteAlarmCommand(c, DateTime.UtcNow + t), t)
: null;
return ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(cmd, timeout, askLocal,
c => DistributedPubSub.Get(_actorSystemAccessor()).Mediator.Tell(new Publish(ScriptedAlarmHostActor.AlarmCommandsTopic, c)),
@@ -155,13 +155,26 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
// #937 review r1: one request at a time, each verdict (and any revert) settled before the next request runs, so a
// later request in the batch (e.g. Confirm after a refused Acknowledge) never runs against a node state the engine
// refused. The bound is taken per request, when its ask is sent.
// Review r2 M1: past the request deadline (less the dispatch floor) a scripted method is refused unsent in its
// handler — before the SDK applies anything — and so is every scripted method after the first one of this batch
// that got no answer (a wedged engine would otherwise cost one full bound per remaining request). Non-scripted
// requests in the batch still run.
ServiceResult? poisoned = null;
for (var i = 0; i < methodsToCall.Count; i++)
{
if (methodsToCall[i] is not { Processed: false }) continue;
var bound = ScriptedCommandBound(context.OperationDeadline);
if (CallOneAwaitingVerdict(context, methodsToCall, i, results, errors, bound) is not { } pending) continue;
var status = await SettleScriptedVerdictAsync(pending, bound).ConfigureAwait(false);
var refusal = poisoned ?? (bound is null
? new ServiceResult(StatusCodes.BadTimeout,
new LocalizedText("The request deadline leaves no time for the scripted-alarm engine; the command was not sent."))
: null);
if (CallOneAwaitingVerdict(context, methodsToCall, i, results, errors, bound ?? TimeSpan.Zero, refusal) is not { } pending)
continue;
var (status, unknown) = await SettleScriptedVerdictAsync(pending, bound ?? TimeSpan.Zero).ConfigureAwait(false);
if (!ServiceResult.IsGood(status)) errors[i] = status;
if (unknown && status.StatusCode.Code == StatusCodes.BadTimeout.Code)
poisoned = new ServiceResult(StatusCodes.BadTimeout,
new LocalizedText("An earlier scripted-alarm command in this request got no answer; this one was not sent."));
}
}
@@ -271,6 +271,14 @@ public sealed class OpcUaQuotaOptions
/// burst ceiling review 01 P6 flagged.</summary>
public int MaxQueuedRequestCount { get; set; } = 200;
/// <summary>
/// Most methods one Call request may carry (advertised as <c>OperationLimits/MaxNodesPerMethodCall</c>; a larger
/// request is refused <c>BadTooManyOperations</c> by the SDK). Default 1000 — the SDK default is 0 = unlimited, and
/// #937 settles a batch's scripted-alarm methods one at a time against the engine, so an unbounded batch is an
/// unbounded request. 0 = unlimited.
/// </summary>
public uint MaxNodesPerMethodCall { get; set; } = 1000;
/// <summary>Per-operation timeout in milliseconds; <c>null</c> keeps the SDK default.</summary>
public int? OperationTimeoutMs { get; set; }
@@ -860,6 +868,8 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
serverConfig.MinRequestThreadCount = quotas.MinRequestThreadCount;
serverConfig.MaxRequestThreadCount = quotas.MaxRequestThreadCount;
serverConfig.MaxQueuedRequestCount = quotas.MaxQueuedRequestCount;
serverConfig.OperationLimits ??= new OperationLimits();
serverConfig.OperationLimits.MaxNodesPerMethodCall = quotas.MaxNodesPerMethodCall;
}
/// <summary>
@@ -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>
@@ -1408,6 +1408,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// <returns><see langword="true"/> when the projection is a genuine change that must be reported as one event.</returns>
private bool ApplyConditionState(AlarmConditionState condition, AlarmConditionSnapshot state, DateTime sourceTimestampUtc)
{
BumpConditionMutation(condition); // #937 r2: any projection is a change a pending scripted revert must not undo
var current = ReadConditionDelta(condition);
var incoming = ToConditionDelta(state, condition);
bool fire = ShouldFireConditionEvent(current, incoming);
@@ -1585,6 +1586,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
{
// Fresh GUID-bytes EventId per event — mandatory for Part 9 ack correlation (T17 relies on it).
alarm.EventId!.Value = ByteString.From(Guid.NewGuid().ToByteArray());
BumpConditionMutation(alarm); // #937 r2
// Time/ReceiveTime were already set to sourceTimestampUtc by the WriteAlarmCondition projection
// immediately above; the assignment here is a locality repeat (same value, no behavioral change)
// so the restamp is co-located with the EventId and ClearChangeMasks in the same method.
@@ -3102,6 +3105,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
}
apply?.Invoke();
// #937 r2 L1: every accepted method is a mutation, reported or not (a Timed→Timed re-shelve by another
// session changes no delta field but must still stop an older call's revert).
BumpConditionMutation(alarm);
if (isAcknowledge && alarm.ConfirmedState is not null)
{
@@ -94,7 +94,10 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// redundant peer; this host applies whichever copy arrives first and skips the other.
/// </summary>
/// <param name="Command">The command.</param>
public sealed record ExecuteAlarmCommand(AlarmCommand Command);
/// <param name="DeadlineUtc">#937 review r2 M2: when the asker stops waiting. An ask still queued past it is answered
/// without touching the engine (the asker reported OutcomeUnknown and broadcast the command; the broadcast copy decides
/// what this host applies). Null ⇒ no deadline.</param>
public sealed record ExecuteAlarmCommand(AlarmCommand Command, DateTime? DeadlineUtc = null);
/// <summary>
/// Told to the parent from <see cref="PostRestart"/>. A supervision restart is otherwise invisible to the
@@ -822,6 +825,18 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
return;
}
// Review r2 M2: the asker already gave up (OutcomeUnknown) and broadcast the command — applying it now, minutes late
// behind a stalled store, would only grow this mailbox. Skipped without touching the engine and NOT remembered, so
// the broadcast copy of the same command (which the peer also got) still applies here.
if (msg.DeadlineUtc is { } deadline && DateTime.UtcNow >= deadline)
{
_log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} skipped on the direct path — its asker stopped waiting; the broadcast copy applies",
cmd.Operation, cmd.AlarmId);
replyTo.Tell(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
"OutcomeUnknown: the ask expired before the engine reached it.", TimedOut: true));
return;
}
var outcome = Owns(cmd.AlarmId)
? await ApplyCommandAsync(cmd)
: new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,