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
+4 -1
View File
@@ -100,7 +100,10 @@ once) and returns Good; the Call then settles the verdict — one request at a t
changed since); no answer (min 5 s / deadline − 250 ms) ⇒ `BadTimeout` "OutcomeUnknown" (never "refused" — it may still changed since); no answer (min 5 s / deadline − 250 ms) ⇒ `BadTimeout` "OutcomeUnknown" (never "refused" — it may still
apply; node kept). The peer gets the broadcast only AFTER an applied/unknown local verdict (`ScriptedAlarmCommandDispatch`) apply; node kept). The peer gets the broadcast only AFTER an applied/unknown local verdict (`ScriptedAlarmCommandDispatch`)
— broadcasting first let the peer apply a command the caller was told failed. ≤ 64 asks in flight node-wide, else — broadcasting first let the peer apply a command the caller was told failed. ≤ 64 asks in flight node-wide, else
`BadTooManyOperations` before anything applies. A native AddComment skips all of this (no engine owns it). Remote gRPC-data methods ride `BadTooManyOperations` before anything applies. A native AddComment skips all of this (no engine owns it). Review r2: a
deadline leaving < 250 ms, or an earlier unanswered scripted method in the same Call, refuses the method `BadTimeout`
unsent; `OpcUa:Quotas:MaxNodesPerMethodCall` (1000) bounds a Call; an ask expired in the host mailbox skips the engine and is
not remembered (its broadcast copy applies); the revert is guarded by a per-condition mutation counter, not field equality. Remote gRPC-data methods ride
`ExecuteConditionMethodAsync` (⇒ `DriverConfirmedFailure` / `OutcomeUnknown`). Never await the verdict inside the handler `ExecuteConditionMethodAsync` (⇒ `DriverConfirmedFailure` / `OutcomeUnknown`). Never await the verdict inside the handler
(it runs under `Lock`). The sync `base.Call` path (no asker) keeps the old fire-and-forget router. The AdminUI `/alerts` path is (it runs under `Lock`). The sync `base.Call` path (no asker) keeps the old fire-and-forget router. The AdminUI `/alerts` path is
still fire-and-forget. A plain SDK client sees only the status code (diagnostic text needs ReturnDiagnostics). still fire-and-forget. A plain SDK client sees only the status code (diagnostic text needs ReturnDiagnostics).
+17 -1
View File
@@ -438,7 +438,14 @@ of which blocks under the node manager's `Lock`:
revert. Cheap refusals the engine would make (a blank scripted AddComment ⇒ `BadInvalidArgument`) happen in the revert. Cheap refusals the engine would make (a blank scripted AddComment ⇒ `BadInvalidArgument`) happen in the
handler, before the SDK applies anything. handler, before the SDK applies anything.
3. **Load bound** — at most 64 asks outstanding node-wide (`MaxScriptedCommandsInFlight`); past it the call is refused 3. **Load bound** — at most 64 asks outstanding node-wide (`MaxScriptedCommandsInFlight`); past it the call is refused
`BadTooManyOperations` before anything is applied or sent. Each request's 5 s bound starts when its own ask is sent. `BadTooManyOperations` before anything is applied or sent. Each request's 5 s bound starts when its own ask is sent and
is cut by the request deadline; a scripted method whose deadline leaves less than 250 ms (after a 250 ms grace) is
refused `BadTimeout` unsent, and after the FIRST scripted method of a batch that got no answer every later scripted
method of that batch is refused `BadTimeout` unsent (non-scripted methods in the batch still run) — so a wedged engine
costs one bound per Call, not one per method. A Call carries at most `OpcUa:Quotas:MaxNodesPerMethodCall` methods
(default 1000; the SDK default 0 was unlimited; 0 restores it). The host answers an ask still queued past its asker's
deadline without touching the engine and without remembering it, so its broadcast copy (which the peer also received —
the asker had reported OutcomeUnknown) is what applies; late work cannot pile up behind a stalled store.
Measured through one host with the production LocalDb store (`ScriptedAlarmCommandThroughputTests`): 300 sequential Measured through one host with the production LocalDb store (`ScriptedAlarmCommandThroughputTests`): 300 sequential
acks in 59 ms (max 11 ms each); 300 AddComments with 64 outstanding at once in 49 ms (max 24 ms each). acks in 59 ms (max 11 ms each); 300 AddComments with 64 outstanding at once in 49 ms (max 24 ms each).
@@ -459,6 +466,15 @@ broadcast, so no engine anywhere applied it and the revert plus the definite fai
gRPC-data `CallConditionMethod` on a scripted condition carries the same verdict (`ExecuteConditionMethodAsync`): applied ⇒ gRPC-data `CallConditionMethod` on a scripted condition carries the same verdict (`ExecuteConditionMethodAsync`): applied ⇒
`DriverConfirmedSuccess`, refused after dispatch ⇒ `DriverConfirmedFailure`, no answer ⇒ `OutcomeUnknown`. `DriverConfirmedSuccess`, refused after dispatch ⇒ `DriverConfirmedFailure`, no answer ⇒ `OutcomeUnknown`.
**Behaviour change (review r2 L5).** A scripted method is now REFUSED (`BadInvalidState`), reverted, and NOT broadcast to
the redundant peer when this node has no scripted-alarm host (no condition-state store, or the host not yet spawned) or the
host does not own the alarm — including the window after a host supervision restart before its configuration is re-sent.
Before #937 such a call returned Good and the broadcast let the peer apply it.
**Revert guard.** A refusal reverts the node only when its per-condition mutation counter (bumped by every projection,
every reported condition event and every accepted method) is unchanged since the method — a field comparison missed a
Timed→Timed re-shelve or a ClientUserId change. The captured raw severity is restored as captured.
**Residual.** Only the pre-check stops the SDK from applying the node change, so a refusal that arrives through the ask **Residual.** Only the pre-check stops the SDK from applying the node change, so a refusal that arrives through the ask
shows subscribers two events: the method's, then the corrective one. An OutcomeUnknown leaves the node changed (the engine shows subscribers two events: the method's, then the corrective one. An OutcomeUnknown leaves the node changed (the engine
may still apply it). A command racing the engine's first load queues behind it rather than failing. may still apply it). A command racing the engine's first load queues behind it rather than failing.
+17
View File
@@ -87,3 +87,20 @@ origin `ack` ⇒ `Acknowledge successful` (positive control).
| Host.Tests (incl. `GrpcDataV1CompatibilityTests`) | 503 passed | | Host.Tests (incl. `GrpcDataV1CompatibilityTests`) | 503 passed |
| Commons.Tests / Core.ScriptedAlarms.Tests | 513 / 147 passed | | Commons.Tests / Core.ScriptedAlarms.Tests | 513 / 147 passed |
| Live `fu937-3` (`6004a5a56`) | F937 + A01 + A02 3/3 PASS; rig down | | Live `fu937-3` (`6004a5a56`) | F937 + A01 + A02 3/3 PASS; rig down |
## Review round 2
| # | Finding | Outcome | Red on revert |
|---|---|---|---|
| M1 | Each request floored at 50 ms ⇒ past the deadline every remaining request still applied/asked; TimeoutHint 0 × wedged engine ≈ 5 s per method | **Fixed.** Deadline (− 250 ms grace) leaving < the 250 ms dispatch floor ⇒ the scripted handler refuses `BadTimeout` unsent (the SDK applies nothing); after the first timed-out OutcomeUnknown in a batch the rest of its scripted methods are refused the same way (non-scripted still run). New quota `OpcUa:Quotas:MaxNodesPerMethodCall` = 1000 (SDK default 0 = unlimited; 0 restores it). | `A_too_close_deadline_or_an_earlier_unanswered_command_refuses_scripted_methods_unsent` red with the floor/poison removed; quota pinned in `OpcUaApplicationHostQuotaTests` |
| M2 | Cap released on Ask timeout while the command stays queued in the host ⇒ unbounded late work | **Fixed.** `ExecuteAlarmCommand.DeadlineUtc`; an expired ask is answered without touching the engine and NOT remembered, so its broadcast copy (already sent on Unknown) applies. Answered OutcomeUnknown rather than NotApplied: the broadcast copy may still apply here, so "not applied" would be untrue (nobody is waiting for it anyway). | `An_expired_ask_skips_the_engine_and_leaves_the_broadcast_copy_to_apply` red with the check removed |
| L1 | Revert guard compared delta + comment | **Fixed.** Per-instance mutation counter (`ConditionalWeakTable`), bumped in `ApplyConditionState`, `ReportConditionEvent` and on every accepted method in `ReportAfterMethod`. | `A_refusal_does_not_revert_a_node_changed_since_the_method` (identical re-projection) red with the guard removed |
| L5 | Behaviour change undocumented | `docs/ScriptedAlarms.md`: no local host / not owned (incl. the post-supervision-restart window) ⇒ refused + reverted + no peer broadcast. | docs |
| nits | stale hosted-service comment; severity 0 ⇒ 1 on revert | Fixed (comment says ask-then-broadcast; the raw captured severity is restored). | — |
| SDK check | Does any Part 9 handler call our delegate before its own validation? | **No** (decompiled SDK 2.0.1): Acknowledge/Confirm/AddComment run the delegate at the END of `ProcessBefore*` (after EventId/Enabled/already-acked/IsLive); the three shelve methods after Enabled + `IsCausePermitted` (+ shelving-time range); Enable/Disable after the already-enabled checks. Nothing after a Good delegate can turn the call Bad, so a started ask is always awaited. (Branch acks would recurse into a branch's own delegate — this server creates no branches.) | — |
Follow-ups (not fixed): **L2** a late refusal that arrives after the ask's timeout (the caller got OutcomeUnknown) is never reverted; **L3** a command cancelled while waiting on `_evalGate` (nothing applied) is reported OutcomeUnknown, not NotApplied; **L4** `OnLoadFailed` reads `HasCompleteGeneration` while a newer load may already be running (transiently refuses during that load).
Gates (round 2): build 0 warnings / 0 errors; OpcUaServer.Tests 1460 passed / 2 skipped; OpcUaServer.IntegrationTests 441 / 39 skipped;
Runtime.Tests 2122 / 3 skipped; Host.Tests 503; Commons.Tests 513; Core.ScriptedAlarms.Tests 147. No live re-run (the dispatch
order is unchanged; the new refusals are pre-dispatch and the expiry skip is host-local).
@@ -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 // #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 // read) refuses while the last scripted-alarm load failed; the asker asks the local engine (via the DriverHostActor)
// exactly as the router above does and asks the local engine (via the DriverHostActor) for its verdict. Both run // for its verdict FIRST and broadcasts to the redundant peer only after an applied / unknown verdict
// under the SDK's Lock and only read / send; the node manager awaits the verdict off Lock. // (ScriptedAlarmCommandDispatch). Both run under the SDK's Lock and only read / send; the node manager awaits the
// verdict off Lock.
if (_scriptedAlarmReadiness is { } readiness) if (_scriptedAlarmReadiness is { } readiness)
_server.NodeManager.ScriptedAlarmCommandPreflight = readiness.Refusal; _server.NodeManager.ScriptedAlarmCommandPreflight = readiness.Refusal;
_server.NodeManager.AlarmCommandAsker = AskScriptedAlarmCommand; _server.NodeManager.AlarmCommandAsker = AskScriptedAlarmCommand;
@@ -613,7 +614,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
private Task<AlarmCommandOutcome> AskScriptedAlarmCommand(AlarmCommand cmd, TimeSpan timeout) private Task<AlarmCommandOutcome> AskScriptedAlarmCommand(AlarmCommand cmd, TimeSpan timeout)
{ {
Func<AlarmCommand, TimeSpan, Task<AlarmCommandOutcome>>? askLocal = _actorRegistry.TryGet<DriverHostActorKey>(out var driverHost) 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; : null;
return ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(cmd, timeout, askLocal, return ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(cmd, timeout, askLocal,
c => DistributedPubSub.Get(_actorSystemAccessor()).Mediator.Tell(new Publish(ScriptedAlarmHostActor.AlarmCommandsTopic, c)), 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 // #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 // 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. // 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++) for (var i = 0; i < methodsToCall.Count; i++)
{ {
if (methodsToCall[i] is not { Processed: false }) continue; if (methodsToCall[i] is not { Processed: false }) continue;
var bound = ScriptedCommandBound(context.OperationDeadline); var bound = ScriptedCommandBound(context.OperationDeadline);
if (CallOneAwaitingVerdict(context, methodsToCall, i, results, errors, bound) is not { } pending) continue; var refusal = poisoned ?? (bound is null
var status = await SettleScriptedVerdictAsync(pending, bound).ConfigureAwait(false); ? 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 (!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> /// burst ceiling review 01 P6 flagged.</summary>
public int MaxQueuedRequestCount { get; set; } = 200; 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> /// <summary>Per-operation timeout in milliseconds; <c>null</c> keeps the SDK default.</summary>
public int? OperationTimeoutMs { get; set; } public int? OperationTimeoutMs { get; set; }
@@ -860,6 +868,8 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable
serverConfig.MinRequestThreadCount = quotas.MinRequestThreadCount; serverConfig.MinRequestThreadCount = quotas.MinRequestThreadCount;
serverConfig.MaxRequestThreadCount = quotas.MaxRequestThreadCount; serverConfig.MaxRequestThreadCount = quotas.MaxRequestThreadCount;
serverConfig.MaxQueuedRequestCount = quotas.MaxQueuedRequestCount; serverConfig.MaxQueuedRequestCount = quotas.MaxQueuedRequestCount;
serverConfig.OperationLimits ??= new OperationLimits();
serverConfig.OperationLimits.MaxNodesPerMethodCall = quotas.MaxNodesPerMethodCall;
} }
/// <summary> /// <summary>
@@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Opc.Ua; using Opc.Ua;
using Opc.Ua.Server; using Opc.Ua.Server;
using System.Runtime.CompilerServices;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; 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> /// <summary>The default node-wide cap on outstanding scripted-command asks.</summary>
internal const int DefaultMaxScriptedCommandsInFlight = 64; 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 static readonly AsyncLocal<PendingScriptedCommand?> PendingScriptedCommandSlot = new();
private int _scriptedCommandsInFlight; 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> /// <summary>
/// #937 layer 1: returns why this node's scripted-alarm engine would reject any operator command right now (its last /// #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. /// 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 /// 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. /// TimedShelve's timer), so a later callback must find the slot closed rather than park an ask nobody awaits.
/// </summary> /// </summary>
private sealed class PendingScriptedCommand(TimeSpan timeout) private sealed class PendingScriptedCommand(TimeSpan timeout, ServiceResult? refusal = null)
{ {
public TimeSpan Timeout { get; } = timeout; 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 Task<AlarmCommandOutcome>? Outcome { get; set; }
public ScriptedMethodRevert? Revert { get; set; } public ScriptedMethodRevert? Revert { get; set; }
public volatile bool Closed; 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. /// the engine refuses, and the post-call state that proves nothing else has changed the node since.
/// </summary> /// </summary>
private sealed record ScriptedMethodRevert(RealmKey Key, AlarmConditionState Alarm, AlarmConditionSnapshot Before, 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> /// <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; 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) private ServiceResult? TryStartScriptedCommandAsk(AlarmCommand cmd)
{ {
if (OpenScriptedSlot() is not { Outcome: null } pending || AlarmCommandAsker is not { } asker) return null; 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) if (Interlocked.Increment(ref _scriptedCommandsInFlight) > MaxScriptedCommandsInFlight)
{ {
Interlocked.Decrement(ref _scriptedCommandsInFlight); 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); delta.Shelving == AlarmShelvingKind.Timed && _conditionUnshelveAt.TryGetValue(key, out var unshelveAt) ? unshelveAt : null);
var comment = alarm.Comment?.Value; var comment = alarm.Comment?.Value;
var clientUserId = alarm.ClientUserId?.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 /// <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) lock (Lock)
{ {
if (!_alarmConditions.TryGetValue(revert.Key, out var live) || !ReferenceEquals(live, revert.Alarm) 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( _logger.LogInformation(
"OtOpcUaNodeManager: refused scripted command on {Condition} not reverted — the condition changed since the call", "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; _conditionUnshelveAt[revert.Key] = unshelveAt;
else _conditionUnshelveAt.Remove(revert.Key); else _conditionUnshelveAt.Remove(revert.Key);
ApplyConditionState(live, revert.Before, now); 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.Comment is not null) live.Comment.Value = revert.BeforeComment ?? LocalizedText.Null;
if (live.ClientUserId is not null) live.ClientUserId.Value = revert.BeforeClientUserId ?? string.Empty; if (live.ClientUserId is not null) live.ClientUserId.Value = revert.BeforeClientUserId ?? string.Empty;
ReportConditionEvent(live, now); ReportConditionEvent(live, now);
} }
} }
/// <summary>The bound for one local request: <see cref="ScriptedCommandTimeout"/>, cut by the request deadline (less a /// <summary>
/// grace, so the answer still lands inside the client's TimeoutHint).</summary> /// The bound for one local request: <see cref="ScriptedCommandTimeout"/>, cut by the request deadline (less a grace, so
private TimeSpan ScriptedCommandBound(DateTime deadline) /// 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; var bound = ScriptedCommandTimeout;
if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue) if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue)
@@ -197,7 +219,7 @@ public sealed partial class OtOpcUaNodeManager
var byDeadline = deadline - DateTime.UtcNow - ImportedMethodGrace; var byDeadline = deadline - DateTime.UtcNow - ImportedMethodGrace;
if (byDeadline < bound) bound = byDeadline; if (byDeadline < bound) bound = byDeadline;
} }
return bound < MinimumScriptedCommandBound ? MinimumScriptedCommandBound : bound; return bound < ImportedMethodMinimumDispatchBudget ? null : bound;
} }
/// <summary> /// <summary>
@@ -206,12 +228,12 @@ public sealed partial class OtOpcUaNodeManager
/// asker wired). /// asker wired).
/// </summary> /// </summary>
private PendingScriptedCommand? CallOneAwaitingVerdict(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall, int index, 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 request = methodsToCall[index];
var singleResults = new List<CallMethodResult> { results[index] }; var singleResults = new List<CallMethodResult> { results[index] };
var singleErrors = new List<ServiceResult> { errors[index] }; var singleErrors = new List<ServiceResult> { errors[index] };
var pending = new PendingScriptedCommand(bound); var pending = new PendingScriptedCommand(bound, refusal);
PendingScriptedCommandSlot.Value = pending; PendingScriptedCommandSlot.Value = pending;
try try
{ {
@@ -228,8 +250,9 @@ public sealed partial class OtOpcUaNodeManager
return pending.Outcome is not null && ServiceResult.IsGood(singleErrors[0]) ? pending : null; 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> /// <summary>The request's final status from its engine verdict (and whether it is an OutcomeUnknown), reverting the node
private async Task<ServiceResult> SettleScriptedVerdictAsync(PendingScriptedCommand pending, TimeSpan bound) /// 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); var (status, unknown) = await AwaitScriptedVerdictAsync(pending.Outcome!, bound).ConfigureAwait(false);
if (!ServiceResult.IsGood(status) && !unknown && pending.Revert is { } revert) 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"); _logger.LogError(ex, "OtOpcUaNodeManager: reverting a refused scripted command failed");
} }
} }
return status; return (status, unknown);
} }
/// <summary> /// <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> /// <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) 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 current = ReadConditionDelta(condition);
var incoming = ToConditionDelta(state, condition); var incoming = ToConditionDelta(state, condition);
bool fire = ShouldFireConditionEvent(current, incoming); 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). // Fresh GUID-bytes EventId per event — mandatory for Part 9 ack correlation (T17 relies on it).
alarm.EventId!.Value = ByteString.From(Guid.NewGuid().ToByteArray()); alarm.EventId!.Value = ByteString.From(Guid.NewGuid().ToByteArray());
BumpConditionMutation(alarm); // #937 r2
// Time/ReceiveTime were already set to sourceTimestampUtc by the WriteAlarmCondition projection // 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) // 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. // 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(); 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) 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. /// redundant peer; this host applies whichever copy arrives first and skips the other.
/// </summary> /// </summary>
/// <param name="Command">The command.</param> /// <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> /// <summary>
/// Told to the parent from <see cref="PostRestart"/>. A supervision restart is otherwise invisible to the /// 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; 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) var outcome = Owns(cmd.AlarmId)
? await ApplyCommandAsync(cmd) ? await ApplyCommandAsync(cmd)
: new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, : new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
@@ -296,6 +296,102 @@ public sealed class ScriptedCommandVerdictWireTests
finally { await rig.DisposeAsync(); } finally { await rig.DisposeAsync(); }
} }
/// <summary>
/// #937 review r2 M1: a scripted method whose request deadline leaves less than the dispatch floor is refused
/// BadTimeout unsent (nothing asked, nothing applied); after the first unanswered scripted method of a batch the rest
/// of that batch's scripted methods are refused unsent — while a native method in the same batch still runs.
/// </summary>
[Fact]
public async Task A_too_close_deadline_or_an_earlier_unanswered_command_refuses_scripted_methods_unsent()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Deadline", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
rig.MaterialiseNative();
rig.Nm.NativeAlarmAckRouter = _ => { };
rig.Nm.ScriptedCommandTimeout = TimeSpan.FromMilliseconds(400);
var asked = new ConcurrentQueue<string>();
var never = new TaskCompletionSource<AlarmCommandOutcome>();
rig.Nm.AlarmCommandAsker = (cmd, _) => { asked.Enqueue(cmd.Operation); return never.Task; };
var pre = new AlarmConditionSnapshot(Active: true, Acknowledged: false, Confirmed: true, Enabled: true,
Shelving: AlarmShelvingKind.Unshelved, Severity: 700, Message: "pre");
rig.Project(false, pre);
rig.Project(true, pre);
await rig.DrainProjectionsAsync();
using var session = await rig.ConnectAsync(anonymous: false, ct);
ByteString EventIdOf(bool native) => rig.Nm.TryGetAlarmCondition(native ? RawAlarmPath : ScriptedAlarmId,
native ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns)!.EventId!.Value;
CallMethodRequest Request(bool native, NodeId method, string text) => new()
{
ObjectId = ConditionNodeId(session, native), MethodId = method,
InputArguments = [new Variant(EventIdOf(native)), new Variant(new LocalizedText(text))],
};
// (a) TimeoutHint 200 ms < grace + dispatch floor: refused unsent.
var tight = await session.CallAsync(new RequestHeader { TimeoutHint = 200 },
[Request(false, MethodIds.AcknowledgeableConditionType_Acknowledge, "tight")], ct);
tight.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code);
asked.ShouldBeEmpty("nothing was sent");
rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeFalse("nothing was applied");
// (b) one unanswered scripted method poisons the rest of its batch (scripted only).
var started = DateTime.UtcNow;
var batch = await session.CallAsync(null,
[
Request(false, MethodIds.AcknowledgeableConditionType_Acknowledge, "first"),
Request(false, MethodIds.ConditionType_AddComment, "second"),
Request(true, MethodIds.AcknowledgeableConditionType_Acknowledge, "native"),
Request(false, MethodIds.ConditionType_AddComment, "third"),
], ct);
batch.Results.ToArray()!.Select(r => r.StatusCode.Code).ToArray().ShouldBe(
[StatusCodes.BadTimeout.Code, StatusCodes.BadTimeout.Code, StatusCodes.Good.Code, StatusCodes.BadTimeout.Code]);
asked.ToArray().ShouldBe(["Acknowledge"], "only the first scripted method was sent");
(DateTime.UtcNow - started).ShouldBeLessThan(TimeSpan.FromSeconds(3), "one bound for the batch, not one per request");
}
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// #937 review r2 L1: a refusal does not revert a node something else changed since the method — even a change that
/// leaves every compared field equal (here an identical re-projection, the shape of a Timed→Timed re-shelve).
/// </summary>
[Fact]
public async Task A_refusal_does_not_revert_a_node_changed_since_the_method()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937NoRevert", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
var acked = ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Acknowledged = true, Message = "base" };
rig.Nm.AlarmCommandAsker = (cmd, _) => Task.Run(() =>
{
// Another writer touches the node after the method (off Lock — the handler runs under it), leaving every
// field as the method left it.
rig.Project(false, acked);
return new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "refused");
});
rig.Project(false, acked with { Acknowledged = false });
await rig.DrainProjectionsAsync();
using var session = await rig.ConnectAsync(anonymous: false, ct);
var eventId = rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.EventId!.Value;
var refused = await session.CallAsync(null, [new CallMethodRequest
{
ObjectId = ConditionNodeId(session, false), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(eventId), new Variant(new LocalizedText("x"))],
}], ct);
refused.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadInvalidState.Code);
rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeTrue("the newer write wins over the revert");
}
finally { await rig.DisposeAsync(); }
}
/// <summary>A2b: a remote (gRPC data) condition method on a scripted condition carries the same verdict.</summary> /// <summary>A2b: a remote (gRPC data) condition method on a scripted condition carries the same verdict.</summary>
[Fact] [Fact]
public async Task A_remote_condition_method_reports_the_engine_refusal_as_dispatched() public async Task A_remote_condition_method_reports_the_engine_refusal_as_dispatched()
@@ -17,6 +17,7 @@ public sealed class OpcUaApplicationHostQuotaTests
config.MinRequestThreadCount.ShouldBe(5); config.MinRequestThreadCount.ShouldBe(5);
config.MaxRequestThreadCount.ShouldBe(100); config.MaxRequestThreadCount.ShouldBe(100);
config.MaxQueuedRequestCount.ShouldBe(200); config.MaxQueuedRequestCount.ShouldBe(200);
config.OperationLimits.MaxNodesPerMethodCall.ShouldBe(1000u, "#937: a Call is bounded (the SDK default 0 is unlimited)");
} }
[Fact] [Fact]
@@ -72,6 +72,29 @@ public sealed class ScriptedAlarmCommandVerdictTests : RuntimeActorTestBase
(await Ask(host, "alm-1", "AddComment", "second")).Verdict.ShouldBe(AlarmCommandVerdict.Applied); (await Ask(host, "alm-1", "AddComment", "second")).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
} }
/// <summary>
/// #937 review r2 M2: an ask still queued past its asker's deadline never touches the engine (no growth of late work
/// behind a stalled store) and is NOT remembered — the broadcast copy of the same command still applies here.
/// </summary>
[Fact]
public async Task An_expired_ask_skips_the_engine_and_leaves_the_broadcast_copy_to_apply()
{
var (host, engine, _, mux) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(Timeout, cancellationToken: Ct);
var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "late", null, "cmd-late");
var expired = await host.Ask<AlarmCommandOutcome>(
new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct);
expired.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown);
engine.GetState("alm-1")!.Comments.ShouldBeEmpty("the expired ask never reached the engine");
host.Tell(cmd); // the broadcast copy (same CommandId)
// Positive control behind it in the mailbox: a fresh ask (in time) applies, so the copy was processed first.
(await Ask(host, "alm-1", "AddComment", "after", "cmd-after")).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
engine.GetState("alm-1")!.Comments.Select(c => c.Text).ShouldBe(["late", "after"]);
}
[Fact] [Fact]
public async Task An_alarm_this_host_does_not_own_is_answered_not_applied() public async Task An_alarm_this_host_does_not_own_is_answered_not_applied()
{ {