diff --git a/.claude/rules/alarms.md b/.claude/rules/alarms.md
index 5e154ff40..d86a55582 100644
--- a/.claude/rules/alarms.md
+++ b/.claude/rules/alarms.md
@@ -103,7 +103,11 @@ apply; node kept). The peer gets the broadcast only AFTER an applied/unknown loc
`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
+not remembered (its broadcast copy applies); the revert is guarded by a per-condition mutation counter, not field equality. A refusal arriving AFTER the caller got
+OutcomeUnknown still reverts (#951: the Ask lives `LateVerdictWindow` past the bound; the timeout outcome carries it as the
+process-local `AlarmCommandOutcome.LateOutcome`). A command cancelled while still waiting for the engine gate throws
+`ScriptedAlarmCommandNotStartedException` ⇒ `NotApplied` (#952; unknown + not remembered once its asker's deadline passed). A
+superseded load's failure (pipe-back carries its generation) publishes no readiness (#953). Remote gRPC-data methods ride
`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
still fire-and-forget. A plain SDK client sees only the status code (diagnostic text needs ReturnDiagnostics).
diff --git a/docs/ScriptedAlarms.md b/docs/ScriptedAlarms.md
index ee9b6d1f7..d29e60c4d 100644
--- a/docs/ScriptedAlarms.md
+++ b/docs/ScriptedAlarms.md
@@ -453,7 +453,8 @@ of which blocks under the node manager's `Lock`:
|---|---|
| applied (incl. an idempotent no-op) | `Good` |
| refused — last load failed, alarm not loaded on this node (incl. the window after a host supervision restart before its reload), malformed command, no engine on this node | `BadInvalidState` (node reverted; the peer never received it) |
-| no answer within min(5 s, request deadline − 250 ms), or the engine op timed out / failed in the store | `BadTimeout` / `BadInternalError`, diagnostic "OutcomeUnknown" — the command **may still apply**, never reported as refused |
+| no answer within min(5 s, request deadline − 250 ms), or the engine op timed out / failed in the store | `BadTimeout` / `BadInternalError`, diagnostic "OutcomeUnknown" — the command **may still apply**, never reported as refused (a refusal that arrives later still reverts the node, #951) |
+| the engine never started it — still waiting for the engine gate (e.g. behind a long load) when the host's 10 s op bound expired (#952) | `BadInvalidState` while the asker still waits (definite: nothing ran); once the asker has already answered OutcomeUnknown and broadcast it, the host answers unknown and lets the broadcast copy decide |
`BadInvalidState` is Part 4's general "object … uninitialized or in some other invalid state" code; Part 9's method result
codes (bad EventId, already acked/confirmed/shelved, disabled, shelving time out of range) do not cover "the state owner
@@ -475,9 +476,32 @@ Before #937 such a call returned Good and the broadcast let the peer apply it.
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.
+**Late refusal (#951).** The caller's bound expiring no longer drops the host's answer: the hosted service's Ask lives
+`ScriptedAlarmCommandDispatch.LateVerdictWindow` (30 s) past the bound (the `ExecuteAlarmCommand` deadline is still the
+caller's bound), and the OutcomeUnknown it returns carries the still-running ask as `AlarmCommandOutcome.LateOutcome`
+(process-local). The node manager watches it (also the asker task itself when its own backstop expired, following a chain of
+unknowns): a late `NotApplied` — e.g. a command queued behind a load that then failed — reverts the node exactly like an in-time
+refusal, under the same mutation-counter guard; a late Applied / unknown / no answer leaves the node. The caller has already
+been told `BadTimeout`, and the peer already got the broadcast; the local host remembered the refusal by `CommandId`, so the
+local broadcast copy is not applied either — the reverted node matches the local engine.
+
+**A command the engine never started (#952).** `ScriptedAlarmEngine` throws `ScriptedAlarmCommandNotStartedException` (an
+`OperationCanceledException`) when an operator command's token fires while it is still waiting for the evaluation gate —
+nothing was looked up or saved. A cancellation inside the store save stays a plain cancellation (it may have committed ⇒
+unknown). The host maps not-started to `NotApplied` and remembers it, except on the direct ask once its asker's deadline has
+passed: that asker already answered OutcomeUnknown and broadcast the command, so — like an ask that expired before it started
+— the host answers unknown and does not remember it, and the broadcast copy decides locally too.
+
+**Superseded load failure (#953).** A failed load pipes back with its load generation; a failure from a generation a newer
+apply has already superseded publishes nothing to the readiness view (the newer load is in flight and has typically cleared
+the engine's complete-generation flag, so reading it would refuse every command until that load completes — the view must
+let through while a load is pending; the engine queues a command behind it). The newer load publishes its own outcome.
+
**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
-may still apply it). A command racing the engine's first load queues behind it rather than failing.
+may still apply it) unless a late refusal arrives inside the late window (#951). A command whose direct ask gave up and whose
+broadcast copy is then refused by the local engine (no one awaits a broadcast copy) still keeps the node change until the
+next good deploy re-asserts it. A command racing the engine's first load queues behind it rather than failing.
**Not covered:** the AdminUI `/alerts` buttons are still fire-and-forget across the central→node transport (they report
"Ack sent", not "applied").
diff --git a/docs/plans/evidence/followups/937.md b/docs/plans/evidence/followups/937.md
index b6b9280cb..4284ff231 100644
--- a/docs/plans/evidence/followups/937.md
+++ b/docs/plans/evidence/followups/937.md
@@ -99,7 +99,7 @@ origin `ack` ⇒ `Acknowledge successful` (positive control).
| 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).
+Follow-ups (filed as #951 / #952 / #953, since fixed — see `docs/ScriptedAlarms.md` §"Late refusal (#951)" and the two paragraphs after it): **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
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs
index db6e2a1af..a22a0ba42 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs
@@ -93,4 +93,13 @@ public sealed record AlarmCommandOutcome(
string Operation,
AlarmCommandVerdict Verdict,
string? Reason = null,
- bool TimedOut = false);
+ bool TimedOut = false)
+{
+ ///
+ /// #951: for an produced because the caller's bound expired, the
+ /// host's eventual answer to the same command (itself bounded; it faults or completes OutcomeUnknown when no answer
+ /// comes). Lets the node manager revert the method's node change when the engine refuses after the caller was told
+ /// "unknown". Null otherwise. Process-local only: never set on an outcome that crosses a wire.
+ ///
+ public Task? LateOutcome { get; init; }
+}
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmCommandNotStartedException.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmCommandNotStartedException.cs
new file mode 100644
index 000000000..76c131b2b
--- /dev/null
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmCommandNotStartedException.cs
@@ -0,0 +1,23 @@
+namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
+
+///
+/// #952: an operator command (acknowledge, confirm, shelve, enable/disable, comment) whose cancellation token fired
+/// while it was still waiting for the engine's evaluation gate — typically queued behind a long
+/// . The command never ran: nothing was looked up, applied or persisted, so
+/// it is definitely NOT applied (unlike a cancellation inside the store save, which may have committed and stays a
+/// plain ).
+///
+/// Derives from so a caller that only knows "cancelled" is unchanged.
+public sealed class ScriptedAlarmCommandNotStartedException : OperationCanceledException
+{
+ /// Creates the exception for .
+ /// The alarm the command was for.
+ /// The cancellation observed while waiting for the gate.
+ public ScriptedAlarmCommandNotStartedException(string alarmId, OperationCanceledException inner)
+ : base($"Command for alarm {alarmId} was cancelled before the scripted-alarm engine started it; nothing was applied.",
+ inner, inner.CancellationToken)
+ => AlarmId = alarmId;
+
+ /// The alarm the command was for.
+ public string AlarmId { get; }
+}
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs
index 796e16953..557141ddc 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs
@@ -745,7 +745,16 @@ public sealed class ScriptedAlarmEngine : IDisposable
private async Task ApplyAsync(string alarmId, CancellationToken ct, Func op)
{
ScriptedAlarmEvent? pending = null;
- await _evalGate.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ await _evalGate.WaitAsync(ct).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException ex)
+ {
+ // #952: cancelled before the gate was acquired (SemaphoreSlim never acquires on a cancelled wait) — nothing
+ // was applied or saved. Distinguished from a cancellation inside SaveAsync below, which may have committed.
+ throw new ScriptedAlarmCommandNotStartedException(alarmId, ex);
+ }
try
{
// #937 review: no separate "not loaded" check before the gate any more — a command racing the FIRST load used
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs
index 4dd46ca08..f682116d1 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs
@@ -614,7 +614,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
private Task AskScriptedAlarmCommand(AlarmCommand cmd, TimeSpan timeout)
{
Func>? askLocal = _actorRegistry.TryGet(out var driverHost)
- ? (c, t) => driverHost.Ask(new ScriptedAlarmHostActor.ExecuteAlarmCommand(c, DateTime.UtcNow + t), t)
+ // The message deadline is the caller's bound; the Ask itself lives LateVerdictWindow longer so a late answer is
+ // still delivered (#951: a late refusal reverts the node).
+ ? (c, t) => driverHost.Ask(new ScriptedAlarmHostActor.ExecuteAlarmCommand(c, DateTime.UtcNow + t),
+ t + ScriptedAlarmCommandDispatch.LateVerdictWindow)
: null;
return ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(cmd, timeout, askLocal,
c => DistributedPubSub.Get(_actorSystemAccessor()).Mediator.Tell(new Publish(ScriptedAlarmHostActor.AlarmCommandsTopic, c)),
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/ScriptedAlarmCommandDispatch.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/ScriptedAlarmCommandDispatch.cs
index 8ca6f4124..ef3d66892 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/ScriptedAlarmCommandDispatch.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/ScriptedAlarmCommandDispatch.cs
@@ -24,13 +24,23 @@ namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa;
///
internal static class ScriptedAlarmCommandDispatch
{
+ ///
+ /// #951: how long past the caller's bound the local host's answer is still collected. The host bounds one engine op by
+ /// its command timeout (10 s) and skips an ask whose deadline passed before it started, so an answer that is coming at
+ /// all comes inside this window.
+ ///
+ internal static readonly TimeSpan LateVerdictWindow = TimeSpan.FromSeconds(30);
+
///
/// Asks the local engine, then broadcasts unless it refused. Starts the ask synchronously (safe under the SDK's Lock);
/// never faults — no answer within is an OutcomeUnknown outcome.
///
/// The command (with its CommandId, which de-duplicates the broadcast copy on the local host).
/// The caller's bound.
- /// The ask to this node's scripted-alarm host; null ⇒ none on this node.
+ /// The ask to this node's scripted-alarm host; null ⇒ none on this node. Its second argument is the
+ /// caller's bound (the host skips the command once it has passed); the returned task may complete later than that — up to
+ /// past it — and that late answer rides the timeout outcome's
+ /// (#951).
/// Publishes the command on the alarm-commands topic.
/// Logger.
/// The local verdict.
@@ -44,15 +54,24 @@ internal static class ScriptedAlarmCommandDispatch
}
AlarmCommandOutcome outcome;
+ Task? ask = null;
try
{
- outcome = await askLocal(cmd, timeout).ConfigureAwait(false);
+ ask = askLocal(cmd, timeout);
+ outcome = await ask.WaitAsync(timeout).ConfigureAwait(false);
}
catch (Exception ex) when (ex is AskTimeoutException or TaskCanceledException or TimeoutException)
{
+ // #951: the caller stops waiting, but the host's answer is still collected — a refusal arriving now lets the
+ // node manager put the node back. Only for the caller's bound expiring (an ask that faulted in time has no
+ // later answer); an ask completing in the same instant is still handed over, already complete.
+ var late = ex is TimeoutException ? ask : null;
+ // The late ask usually ends in an AskTimeoutException nobody may observe: observe it here.
+ late?.ContinueWith(static t => _ = t.Exception, CancellationToken.None,
+ TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
outcome = new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
$"OutcomeUnknown: the scripted-alarm engine did not answer within {timeout.TotalSeconds:0.#} s; the command may still apply.",
- TimedOut: true);
+ TimedOut: true) { LateOutcome = late };
}
catch (Exception ex)
{
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs
index a8efd90b4..ab85fcbd1 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs
@@ -254,7 +254,7 @@ public sealed partial class OtOpcUaNodeManager
/// on a refusal. Never throws.
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, late) = await AwaitScriptedVerdictAsync(pending.Outcome!, bound).ConfigureAwait(false);
if (!ServiceResult.IsGood(status) && !unknown && pending.Revert is { } revert)
{
try
@@ -266,15 +266,58 @@ public sealed partial class OtOpcUaNodeManager
_logger.LogError(ex, "OtOpcUaNodeManager: reverting a refused scripted command failed");
}
}
+ else if (unknown && late is not null && pending.Revert is { } lateRevert)
+ {
+ _ = RevertOnLateRefusalAsync(late, lateRevert);
+ }
return (status, unknown);
}
+ ///
+ /// #951: the caller was told OutcomeUnknown, but the host's answer is still coming. When it turns out to be a refusal,
+ /// put the node back exactly as an in-time refusal would — 's per-condition mutation
+ /// guard skips it if anything changed the node since the method (a projection, another method: newer truth wins). An
+ /// applied, unknown or missing late answer leaves the node as it is. Fire-and-forget; never throws. Bounded by the
+ /// late task itself (the asker's own late window).
+ ///
+ private async Task RevertOnLateRefusalAsync(Task late, ScriptedMethodRevert revert)
+ {
+ AlarmCommandOutcome outcome;
+ try
+ {
+ outcome = await late.ConfigureAwait(false);
+ // A backstop-expired asker can itself answer OutcomeUnknown later with its own late answer behind it.
+ while (outcome is { Verdict: AlarmCommandVerdict.OutcomeUnknown, LateOutcome: { } next })
+ outcome = await next.ConfigureAwait(false);
+ }
+ catch (Exception)
+ {
+ return; // no answer ever came: the outcome stays unknown
+ }
+
+ if (outcome.Verdict != AlarmCommandVerdict.NotApplied) return;
+ _logger.LogWarning(
+ "OtOpcUaNodeManager: scripted {Operation} on {Condition} was refused after its caller was told OutcomeUnknown ({Reason}); reverting the node",
+ outcome.Operation, revert.Key.Id, outcome.Reason);
+ try
+ {
+ RevertScriptedMethod(revert);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "OtOpcUaNodeManager: reverting a late-refused scripted command failed");
+ }
+ }
+
///
/// The method's final status from the engine's verdict, and whether it is an OutcomeUnknown (the command may still
/// apply). Never throws. The asker answers its own timeout as an
- /// outcome; the wait here (its bound plus a grace) is the backstop for one that never completes.
+ /// outcome; the wait here (its bound plus a grace) is the backstop for one that never completes. For an unknown, also
+ /// the answer still to come (#951): the outcome's , or the pending task
+ /// itself when the backstop expired.
///
- private async Task<(ServiceResult Status, bool Unknown)> AwaitScriptedVerdictAsync(Task pending, TimeSpan bound)
+ private async Task<(ServiceResult Status, bool Unknown, Task? Late)> AwaitScriptedVerdictAsync(
+ Task pending, TimeSpan bound)
{
AlarmCommandOutcome outcome;
try
@@ -284,21 +327,22 @@ public sealed partial class OtOpcUaNodeManager
catch (Exception ex) when (ex is TimeoutException or OperationCanceledException)
{
return (ScriptedUnknown(StatusCodes.BadTimeout,
- $"OutcomeUnknown: the scripted-alarm engine did not answer within {bound.TotalSeconds:0.#} s; the command may still apply."), true);
+ $"OutcomeUnknown: the scripted-alarm engine did not answer within {bound.TotalSeconds:0.#} s; the command may still apply."),
+ true, ex is TimeoutException ? pending : null);
}
catch (Exception ex)
{
// The command was (or may have been) sent: unknown, never "refused".
- return (ScriptedUnknown(StatusCodes.BadInternalError, "OutcomeUnknown: " + ex.GetType().Name), true);
+ return (ScriptedUnknown(StatusCodes.BadInternalError, "OutcomeUnknown: " + ex.GetType().Name), true, null);
}
return outcome.Verdict switch
{
- AlarmCommandVerdict.Applied => (ServiceResult.Good, false),
+ AlarmCommandVerdict.Applied => (ServiceResult.Good, false, null),
AlarmCommandVerdict.NotApplied => (new ServiceResult(StatusCodes.BadInvalidState,
- new LocalizedText(outcome.Reason ?? "The scripted-alarm engine did not apply the command.")), false),
+ new LocalizedText(outcome.Reason ?? "The scripted-alarm engine did not apply the command.")), false, null),
_ => (ScriptedUnknown(outcome.TimedOut ? StatusCodes.BadTimeout : StatusCodes.BadInternalError,
- outcome.Reason ?? "OutcomeUnknown: the scripted-alarm engine could not confirm the command."), true),
+ outcome.Reason ?? "OutcomeUnknown: the scripted-alarm engine could not confirm the command."), true, outcome.LateOutcome),
};
}
@@ -337,13 +381,17 @@ public sealed partial class OtOpcUaNodeManager
}
if (!decided.Applied || pending.Outcome is null) return decided;
- var (status, unknown) = await AwaitScriptedVerdictAsync(pending.Outcome, bound).ConfigureAwait(false);
+ var (status, unknown, late) = await AwaitScriptedVerdictAsync(pending.Outcome, bound).ConfigureAwait(false);
if (ServiceResult.IsGood(status)) return decided;
if (!unknown && pending.Revert is { } revert)
{
try { RevertScriptedMethod(revert); }
catch (Exception ex) { _logger.LogError(ex, "OtOpcUaNodeManager: reverting a refused remote scripted command failed"); }
}
+ else if (unknown && late is not null && pending.Revert is { } lateRevert)
+ {
+ _ = RevertOnLateRefusalAsync(late, lateRevert);
+ }
var text = status.LocalizedText.IsNullOrEmpty ? null : status.LocalizedText.Text;
return new OriginConditionMethodOutcome(false, decided.Native, status.StatusCode.Code, text, Dispatched: true, Unknown: unknown);
}
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs
index 427cac6f4..bde758d7c 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs
@@ -129,10 +129,15 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// Pipe-back marker for a that was cancelled
/// because the actor is stopping (its fired in ). It is a
/// no-op — there is nothing to register and no fault to log — and exists only so a cancelled load
- /// pipes back a quiet message instead of a that would log a spurious
+ /// pipes back a quiet message instead of an that would log a spurious
/// Warning on every clean shutdown.
private sealed record AlarmsLoadCanceled;
+ /// Pipe-back of a faulted , tagged with the load
+ /// it ran under (#953: a failure a newer apply already superseded must not publish
+ /// readiness).
+ private sealed record AlarmsLoadFailed(Exception Cause, int Generation);
+
/// Default bound on one inbound alarm command's engine op (): 10 s.
public static readonly TimeSpan DefaultCommandTimeout = TimeSpan.FromSeconds(10);
@@ -377,9 +382,12 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
ReceiveAsync(OnAlarmCommand);
// #937: the node-local ask behind an OPC UA Part 9 method — same op, plus a reply carrying the verdict.
ReceiveAsync(OnExecuteAlarmCommand);
- // A faulted LoadAsync pipes back a Status.Failure (see OnApply) — log it and stay inert so the
- // failure doesn't hit the dead-letter log.
- Receive(OnLoadFailed);
+ // A faulted LoadAsync pipes back an AlarmsLoadFailed carrying its generation (see OnApply) — log it, publish
+ // readiness if it is the latest load (#953), and stay inert.
+ Receive(OnLoadFailed);
+ // Nothing pipes a bare Status.Failure here any more (the load continuation cannot fault); kept so an unexpected
+ // one is logged rather than unhandled. It names no load generation, so it publishes no readiness.
+ Receive(f => _log.Warning(f.Cause, "ScriptedAlarmHost: unexpected failure piped to the host"));
// A LoadAsync cancelled by PostStop's _cts pipes back this marker. The actor is stopping, so
// there's nothing to do — swallow it quietly (no Warning, no dead letter).
Receive(_ => { });
@@ -420,13 +428,13 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// PipeTo marshals the completion back onto the actor thread. The continuation runs with
// CancellationToken.None so it ALWAYS executes (even after _cts fired on stop) and branches on
// the load's outcome: a clean cancel (actor stopping) pipes back a quiet AlarmsLoadCanceled; a
- // genuine fault pipes back a Status.Failure we log as Warning (the prior generation's mux
+ // genuine fault pipes back an AlarmsLoadFailed we log as Warning (the prior generation's mux
// subscription stays — a failed reload should not silently drop live values); success pipes back
// AlarmsLoaded carrying the refs + the generation it was loaded under.
_engine.LoadAsync(defs, _cts.Token)
.ContinueWith(
t => t.IsCanceled ? (object)new AlarmsLoadCanceled()
- : t.IsFaulted ? new Status.Failure(t.Exception!.GetBaseException())
+ : t.IsFaulted ? new AlarmsLoadFailed(t.Exception!.GetBaseException(), gen)
: new AlarmsLoaded(depRefs, gen),
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
@@ -437,10 +445,23 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
enabled.Count, msg.Plans.Count, depRefs.Count);
}
- private void OnLoadFailed(Status.Failure msg)
+ private void OnLoadFailed(AlarmsLoadFailed msg)
{
- // #937: loads serialize on the engine's gate, so completions arrive in start order — this is the latest completed
- // load. Publish what the ENGINE says rather than infer it from the fault (review r1 L6): a load can fault after it
+ // #953: a failure from a load a newer apply has already superseded publishes nothing. The newer load is in flight
+ // (or about to be) and has typically already taken the engine's gate and cleared its complete-generation flag, so
+ // reading the engine now would refuse every command until that load completes — the readiness view is racy by
+ // design and must LET THROUGH while a load is pending (the engine queues a command behind it). The newer load
+ // publishes its own outcome when it completes.
+ if (msg.Generation != _loadGeneration)
+ {
+ _log.Warning(msg.Cause,
+ "ScriptedAlarmHost: engine LoadAsync failed for superseded load generation {Generation} (latest {Latest}) — the newer load decides command readiness",
+ msg.Generation, _loadGeneration);
+ return;
+ }
+
+ // #937: loads serialize on the engine's gate, so completions arrive in start order — this is the latest load.
+ // Publish what the ENGINE says rather than infer it from the fault (review r1 L6): a load can fault after it
// completed its generation (e.g. subscribing), and then the engine still accepts commands.
_readiness?.SetLoadOutcome(loaded: _engine.HasCompleteGeneration);
_log.Warning(msg.Cause, "ScriptedAlarmHost: engine LoadAsync failed — alarms not (re)loaded; operator commands are refused until the next successful deploy");
@@ -842,10 +863,27 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
: new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
_readiness?.Refusal() ?? NotLoadedRefusal);
+ // #952: a command the engine never started is a refusal only while its asker is still waiting (it then neither
+ // broadcasts it nor keeps the node change). Once the asker's deadline has passed it already answered
+ // OutcomeUnknown and broadcast the command, so — exactly like the expired ask above — this copy is answered
+ // unknown and NOT remembered: the broadcast copy still decides here, so the pair can converge.
+ if (outcome is { Verdict: AlarmCommandVerdict.NotApplied, Reason: NotStartedRefusal }
+ && msg.DeadlineUtc is { } askDeadline && DateTime.UtcNow >= askDeadline)
+ {
+ replyTo.Tell(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
+ "OutcomeUnknown: the engine did not start the command before its asker stopped waiting; the broadcast copy decides.",
+ TimedOut: true));
+ return;
+ }
+
Remember(cmd, outcome);
replyTo.Tell(outcome);
}
+ /// #952: the refusal of a command that never got the engine's gate within the command bound.
+ internal const string NotStartedRefusal =
+ "The scripted-alarm engine was busy (e.g. loading a deployment) and did not start the command in time; the command was not applied.";
+
private const string NotYetLoadedRefusal =
"This server's scripted-alarm engine has not completed loading its configuration yet; the command was not applied.";
@@ -927,6 +965,15 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
}
return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied);
}
+ catch (ScriptedAlarmCommandNotStartedException)
+ {
+ // #952: cancelled while still waiting for the engine's gate (queued behind a long load, or the actor
+ // stopping) — the engine never ran it, so this is a refusal, not an unknown. OnExecuteAlarmCommand turns it
+ // back into an unknown when its asker has already given up (see there).
+ _log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} NOT applied — the engine did not start it within {Timeout} (busy, e.g. a load in progress)",
+ cmd.Operation, cmd.AlarmId, _commandTimeout);
+ return Refused(NotStartedRefusal);
+ }
catch (OperationCanceledException) when (!_cts.IsCancellationRequested)
{
// The op may have been cancelled inside SaveAsync after the store committed: unknown, never "not applied".
diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs
index 134cf901a..ae835164f 100644
--- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs
+++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs
@@ -50,11 +50,14 @@ public sealed class ScriptedAlarmEngineReloadRestatementTests
public Task> LoadAllAsync(CancellationToken ct)
=> Task.FromResult>(_rows.Values.ToArray());
- public Task SaveAsync(AlarmConditionState state, CancellationToken ct)
+ /// Optional hook run by before it writes — block it (#952).
+ public Func? OnSave { get; set; }
+
+ public async Task SaveAsync(AlarmConditionState state, CancellationToken ct)
{
+ if (OnSave is { } hook) await hook(state, ct);
Saves.Enqueue(state);
_rows[state.AlarmId] = state;
- return Task.CompletedTask;
}
public Task RemoveAsync(string alarmId, CancellationToken ct)
@@ -413,6 +416,74 @@ public sealed class ScriptedAlarmEngineReloadRestatementTests
rig.Engine.GetState("HighTemp")!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
}
+ ///
+ /// #952: a command cancelled while it still waits for the gate (here: behind a reload) never started — it throws
+ /// (still an ) and
+ /// applied nothing, so its host can answer a definite "not applied".
+ ///
+ [Fact]
+ public async Task A_command_cancelled_before_it_gets_the_gate_is_reported_not_started()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+ rig.Store.Saves.Clear();
+
+ using var loadReached = new ManualResetEventSlim();
+ using var release = new ManualResetEventSlim();
+ rig.Up.OnRead = _ => { loadReached.Set(); release.Wait(TimeSpan.FromSeconds(30)); };
+ var load = Task.Run(() => rig.Engine.LoadAsync([Alarm()], Ct), Ct);
+ loadReached.Wait(TimeSpan.FromSeconds(10), Ct).ShouldBeTrue();
+ rig.Up.OnRead = null;
+
+ using var cts = CancellationTokenSource.CreateLinkedTokenSource(Ct);
+ var comment = rig.Engine.AddCommentAsync("HighTemp", "alice", "queued", cts.Token);
+ comment.IsCompleted.ShouldBeFalse("the reload holds the gate");
+ cts.Cancel();
+ // Awaited directly, as the host does: a cancellation-derived exception leaves the task Canceled, and only a direct
+ // await rethrows the stored exception (a ContinueWith-based assertion would see a fresh TaskCanceledException).
+ var notStarted = (await CaughtAsync(comment)).ShouldBeOfType();
+ notStarted.AlarmId.ShouldBe("HighTemp");
+ notStarted.ShouldBeAssignableTo();
+
+ release.Set();
+ await load;
+ rig.Engine.GetState("HighTemp")!.Comments.Select(c => c.Text).ShouldNotContain("queued");
+ rig.Store.Saves.ShouldBeEmpty();
+ }
+
+ /// #952 counterpart: a cancellation once the command HAS the gate (inside the store save, which may already
+ /// have committed) stays a plain — its outcome is unknown, never "not started".
+ [Fact]
+ public async Task A_command_cancelled_inside_its_save_is_not_reported_not_started()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+
+ var saveReached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ rig.Store.OnSave = async (_, ct) => { saveReached.TrySetResult(); await Task.Delay(Timeout.Infinite, ct); };
+ using var cts = CancellationTokenSource.CreateLinkedTokenSource(Ct);
+ var comment = rig.Engine.AddCommentAsync("HighTemp", "alice", "saving", cts.Token);
+ await saveReached.Task.WaitAsync(TimeSpan.FromSeconds(10), Ct);
+ cts.Cancel();
+
+ var cancelled = (await CaughtAsync(comment)).ShouldBeAssignableTo();
+ cancelled.ShouldNotBeOfType();
+ rig.Store.OnSave = null;
+ }
+
+ private static async Task CaughtAsync(Task task)
+ {
+ try
+ {
+ await task;
+ return null;
+ }
+ catch (Exception ex)
+ {
+ return ex;
+ }
+ }
+
/// #935 review S1: a command that changes nothing (an uncommented re-ack) writes nothing.
[Fact]
public async Task An_idempotent_command_does_not_write_the_store()
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/OpcUa/ScriptedAlarmCommandDispatchTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/OpcUa/ScriptedAlarmCommandDispatchTests.cs
index 423b52825..21e2085e2 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/OpcUa/ScriptedAlarmCommandDispatchTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/OpcUa/ScriptedAlarmCommandDispatchTests.cs
@@ -50,4 +50,34 @@ public sealed class ScriptedAlarmCommandDispatchTests
_ => throw new InvalidOperationException("mediator down"), NullLogger.Instance);
applied.Verdict.ShouldBe(AlarmCommandVerdict.Applied);
}
+
+ ///
+ /// #951: the caller's bound expiring does not drop the host's answer — the OutcomeUnknown carries the still-running ask
+ /// as its , so a refusal that arrives later can still revert the node.
+ ///
+ [Fact]
+ public async Task An_answer_after_the_bound_rides_the_unknown_outcome_as_its_late_outcome()
+ {
+ var sent = 0;
+ var host = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ TimeSpan? askedBound = null;
+ var unknown = await ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(Cmd, TimeSpan.FromMilliseconds(50),
+ (_, bound) => { askedBound = bound; return host.Task; }, _ => sent++, NullLogger.Instance);
+
+ askedBound.ShouldBe(TimeSpan.FromMilliseconds(50), "the host's deadline is still the caller's bound");
+ unknown.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown);
+ unknown.TimedOut.ShouldBeTrue();
+ sent.ShouldBe(1);
+ var late = unknown.LateOutcome;
+ (late is not null).ShouldBeTrue("the host's answer is still collected");
+ late!.IsCompleted.ShouldBeFalse();
+
+ host.SetResult(new AlarmCommandOutcome(Cmd.AlarmId, Cmd.Operation, AlarmCommandVerdict.NotApplied, "load failed"));
+ (await late).Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
+
+ // An ask that FAILED inside the bound has no later answer.
+ var faulted = await ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(Cmd, TimeSpan.FromSeconds(1),
+ (_, _) => Task.FromException(new AskTimeoutException("no answer")), _ => sent++, NullLogger.Instance);
+ (faulted.LateOutcome is null).ShouldBeTrue();
+ }
}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs
index a6510018b..0fe921803 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs
@@ -419,4 +419,127 @@ public sealed class ScriptedCommandVerdictWireTests
}
finally { await rig.DisposeAsync(); }
}
+
+ ///
+ /// #951: the engine refuses AFTER the caller was told OutcomeUnknown (BadTimeout) — e.g. the command was queued behind a
+ /// load that then failed. The node does not keep the SDK-applied change: the late refusal reverts it with exactly one
+ /// corrective event, as an in-time refusal does. Covers both shapes of "late": the asker's own timeout outcome carrying
+ /// the host's still-running answer, and an asker that never answered inside the node manager's backstop.
+ ///
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public async Task A_refusal_arriving_after_the_timeout_reverts_the_node(bool viaLateOutcome)
+ {
+ var ct = TestContext.Current.CancellationToken;
+ var rig = await StartAsync($"Verdict951Late{viaLateOutcome}", encrypted: false, ct);
+ try
+ {
+ rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
+ rig.MaterialiseScripted();
+ rig.Nm.ScriptedCommandTimeout = TimeSpan.FromMilliseconds(500);
+ var host = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ rig.Nm.AlarmCommandAsker = (cmd, _) => viaLateOutcome
+ ? Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
+ "OutcomeUnknown: no answer in time", TimedOut: true) { LateOutcome = host.Task })
+ : host.Task;
+
+ using var session = await rig.ConnectAsync(anonymous: false, ct);
+ var events = new RecordedEvents();
+ var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
+ var item = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
+ await subscription.ApplyChangesAsync(ct);
+ rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" });
+ await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
+
+ var unknown = await Should.ThrowAsync(ConditionMethodEventTests.CallAsync(
+ session, ConditionNodeId(session, false), "Acknowledge", events.LatestEventId(item, "base"), ct));
+ unknown.StatusCode.ShouldBe(StatusCodes.BadTimeout);
+ rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value
+ .ShouldBeTrue("an unknown outcome keeps the change — the engine may still apply it");
+
+ host.SetResult(new AlarmCommandOutcome(ScriptedAlarmId, "Acknowledge", AlarmCommandVerdict.NotApplied, "load failed"));
+ await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(item, "base").Count >= 3);
+ rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "sentinel" });
+ await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
+ var baseEvents = events.ConditionEvents(item, "base");
+ baseEvents.Count.ShouldBe(3, "the base transition, the method's event, and exactly one corrective event");
+ baseEvents[2][RecordedEvents.AckedField].ClrValue().ShouldBe(baseEvents[0][RecordedEvents.AckedField].ClrValue());
+ await subscription.DeleteAsync(true, ct);
+ }
+ finally { await rig.DisposeAsync(); }
+ }
+
+ ///
+ /// #951: only a late REFUSAL reverts. A late answer already in when the verdict is settled is acted on before the call
+ /// returns, so each arm is observed deterministically: Applied / still-unknown keep the change; NotApplied (here behind
+ /// one more unknown hop, so the chain is followed) reverts it.
+ ///
+ [Theory]
+ [InlineData(AlarmCommandVerdict.Applied, false)]
+ [InlineData(AlarmCommandVerdict.OutcomeUnknown, false)]
+ [InlineData(AlarmCommandVerdict.NotApplied, true)]
+ public async Task Only_a_late_refusal_reverts(AlarmCommandVerdict lateVerdict, bool reverted)
+ {
+ var ct = TestContext.Current.CancellationToken;
+ var rig = await StartAsync($"Verdict951Only{lateVerdict}", encrypted: false, ct);
+ try
+ {
+ rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
+ rig.MaterialiseScripted();
+ rig.Nm.AlarmCommandAsker = (cmd, _) =>
+ {
+ var late = new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, lateVerdict);
+ if (lateVerdict == AlarmCommandVerdict.NotApplied)
+ {
+ late = new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown, "hop", TimedOut: true)
+ { LateOutcome = Task.FromResult(late) };
+ }
+ return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
+ "OutcomeUnknown: no answer in time", TimedOut: true) { LateOutcome = Task.FromResult(late) });
+ };
+ rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" });
+ await rig.DrainProjectionsAsync();
+
+ using var session = await rig.ConnectAsync(anonymous: false, ct);
+ var eventId = rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.EventId!.Value;
+ var result = await session.CallAsync(null, [new CallMethodRequest
+ {
+ ObjectId = ConditionNodeId(session, false), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
+ InputArguments = [new Variant(eventId), new Variant(new LocalizedText("x"))],
+ }], ct);
+ result.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code);
+ rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBe(!reverted);
+ }
+ finally { await rig.DisposeAsync(); }
+ }
+
+ /// #951 for a remote (gRPC data) condition method: a refusal arriving after the Unknown answer reverts the node too.
+ [Fact]
+ public async Task A_remote_condition_method_refused_after_its_timeout_reverts_the_node()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ var rig = await StartAsync("Verdict951Remote", encrypted: false, ct);
+ try
+ {
+ rig.MaterialiseScripted();
+ rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" });
+ await rig.DrainProjectionsAsync();
+ var host = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ rig.Nm.AlarmCommandAsker = (cmd, _) => Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation,
+ AlarmCommandVerdict.OutcomeUnknown, "OutcomeUnknown: no answer in time", TimedOut: true) { LateOutcome = host.Task });
+
+ var marker = rig.Nm.SnapshotConditions((_, id) => id == ScriptedAlarmId, 10)
+ .SelectMany(s => s.Records).Single(c => c.ConditionId == ScriptedAlarmId).Activation;
+ var call = new OriginConditionMethodCall(AddressSpaceRealm.Uns, ScriptedAlarmId, "Acknowledge", "ack", marker, "svc", null);
+
+ var unknown = await rig.Nm.ExecuteConditionMethodAsync(call, TimeSpan.FromSeconds(5));
+ unknown.Unknown.ShouldBeTrue();
+ rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeTrue("unknown keeps the change");
+
+ host.SetResult(new AlarmCommandOutcome(ScriptedAlarmId, "Acknowledge", AlarmCommandVerdict.NotApplied, "load failed"));
+ await RecordedEvents.WaitUntilAsync(() => !rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value);
+ }
+ finally { await rig.DisposeAsync(); }
+ }
}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs
index b685efb20..56fd03e7a 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs
@@ -1,3 +1,4 @@
+using System.Collections.Concurrent;
using Akka.Actor;
using Akka.TestKit;
using Serilog;
@@ -29,18 +30,53 @@ public sealed class ScriptedAlarmCommandVerdictTests : RuntimeActorTestBase
private static EquipmentScriptedAlarmPlan BadPlan(string id) => Plan(id, "return unknownIdentifier;");
- private (IActorRef Host, ScriptedAlarmEngine Engine, ScriptedAlarmCommandReadinessView Readiness, TestProbe Mux) Spawn()
+ private (IActorRef Host, ScriptedAlarmEngine Engine, ScriptedAlarmCommandReadinessView Readiness, TestProbe Mux) Spawn(
+ IAlarmStateStore? store = null, TimeSpan? commandTimeout = null)
{
var publish = CreateTestProbe();
var mux = CreateTestProbe();
var upstream = new DependencyMuxTagUpstreamSource();
var logger = new LoggerConfiguration().CreateLogger();
- var engine = new ScriptedAlarmEngine(upstream, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger);
+ var engine = new ScriptedAlarmEngine(upstream, store ?? new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger);
var readiness = new ScriptedAlarmCommandReadinessView();
- var host = Sys.ActorOf(ScriptedAlarmHostActor.Props(publish.Ref, mux.Ref, () => (upstream, engine), readiness: readiness));
+ var host = Sys.ActorOf(ScriptedAlarmHostActor.Props(publish.Ref, mux.Ref, () => (upstream, engine),
+ commandTimeout: commandTimeout, readiness: readiness));
return (host, engine, readiness, mux);
}
+ /// An in-memory store whose per-alarm row read (the engine does it under its gate, inside LoadAsync, for an alarm
+ /// it carries no state for) can be held — so a load holds the engine's gate for exactly as long as the test says.
+ private sealed class HoldableStore : IAlarmStateStore
+ {
+ private readonly InMemoryAlarmStateStore _inner = new();
+ private readonly ConcurrentDictionary Release)> _holds =
+ new(StringComparer.Ordinal);
+
+ /// Holds the next read of : Reached completes once it is held; completing
+ /// Release with null answers the read, with an exception throws it.
+ public (Task Reached, TaskCompletionSource Release) Hold(string alarmId)
+ {
+ var reached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ _holds[alarmId] = (reached, release);
+ return (reached.Task, release);
+ }
+
+ public async Task LoadAsync(string alarmId, CancellationToken ct)
+ {
+ if (_holds.TryRemove(alarmId, out var hold))
+ {
+ hold.Reached.TrySetResult();
+ if (await hold.Release.Task is { } fault) throw fault;
+ }
+ return await _inner.LoadAsync(alarmId, ct);
+ }
+
+ public Task> LoadAllAsync(CancellationToken ct) => _inner.LoadAllAsync(ct);
+ public Task SaveAsync(AlarmConditionState state, CancellationToken ct) => _inner.SaveAsync(state, ct);
+ public Task RemoveAsync(string alarmId, CancellationToken ct) => _inner.RemoveAsync(alarmId, ct);
+ }
+
private static Task Ask(IActorRef host, string alarmId, string operation, string? comment = null, string? commandId = null) =>
host.Ask(new ScriptedAlarmHostActor.ExecuteAlarmCommand(
new AlarmCommand(alarmId, operation, "alice", comment, null, commandId)), Timeout, Ct);
@@ -133,4 +169,121 @@ public sealed class ScriptedAlarmCommandVerdictTests : RuntimeActorTestBase
(await Ask(host, "alm-1", "AddComment", "other", "cmd-2")).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
engine.GetState("alm-1")!.Comments.Select(c => c.Text).ShouldBe(["note", "other"]);
}
+
+ ///
+ /// #952: a command still waiting for the engine's gate when its bound expires (queued behind a load) was never started —
+ /// a definite NotApplied, not OutcomeUnknown (which told the caller "may still apply", broadcast it to the peer and kept
+ /// the node change). Remembered, so a broadcast copy of the same id is not applied afterwards (the refusal stays true).
+ ///
+ [Fact]
+ public async Task A_command_that_never_got_the_engine_gate_is_not_applied()
+ {
+ var store = new HoldableStore();
+ var (host, engine, _, mux) = Spawn(store, commandTimeout: TimeSpan.FromMilliseconds(300));
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
+ mux.ExpectMsg(Timeout, cancellationToken: Ct);
+
+ // A deploy adding alm-2 reads its row under the engine gate — held, so the gate stays taken.
+ var (reached, release) = store.Hold("alm-2");
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1"), Plan("alm-2")]));
+ await reached.WaitAsync(Timeout, Ct);
+
+ var refused = await Ask(host, "alm-1", "AddComment", "blocked", "cmd-blocked");
+ refused.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
+ refused.Reason.ShouldBe(ScriptedAlarmHostActor.NotStartedRefusal);
+
+ release.SetResult(null);
+ mux.ExpectMsg(Timeout, cancellationToken: Ct);
+ host.Tell(new AlarmCommand("alm-1", "AddComment", "alice", "blocked", null, "cmd-blocked")); // its broadcast copy
+ // Positive control behind it in the mailbox: the engine is free again, and the copy above 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(["after"], "the refused command was never applied");
+ }
+
+ ///
+ /// #952: the same never-started command, but its asker's deadline passed while it waited — the asker already answered
+ /// OutcomeUnknown and broadcast it, so (as for an ask that expired before it started, review r2 M2) it is answered
+ /// unknown and NOT remembered: the broadcast copy decides here.
+ ///
+ [Fact]
+ public async Task A_never_started_command_past_its_asker_deadline_leaves_the_broadcast_copy_to_decide()
+ {
+ var store = new HoldableStore();
+ var (host, engine, _, mux) = Spawn(store, commandTimeout: TimeSpan.FromSeconds(3));
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
+ mux.ExpectMsg(Timeout, cancellationToken: Ct);
+
+ var (reached, release) = store.Hold("alm-2");
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1"), Plan("alm-2")]));
+ await reached.WaitAsync(Timeout, Ct);
+
+ // In time when the host takes it (2 s of slack), expired by the time the 3 s gate wait gives up.
+ var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "late", null, "cmd-late");
+ var unknown = await host.Ask(
+ new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(2)), Timeout, Ct);
+ unknown.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown);
+ unknown.Reason!.ShouldContain("did not start the command");
+
+ release.SetResult(null);
+ mux.ExpectMsg(Timeout, cancellationToken: Ct);
+ host.Tell(cmd); // the broadcast copy: not shadowed by a remembered refusal
+ (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"]);
+ }
+
+ ///
+ /// #953: a load that fails after a newer apply already started its own load is superseded — its failure must not
+ /// publish "refuse everything" while the newer load is in flight (the engine queues a command behind it; the view is
+ /// racy by design and lets through). The newer load's own outcome is what gets published.
+ ///
+ [Fact]
+ public async Task A_superseded_load_failure_does_not_refuse_commands_while_the_newer_load_runs()
+ {
+ var store = new HoldableStore();
+ var (host, engine, readiness, mux) = Spawn(store);
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
+ mux.ExpectMsg(Timeout, cancellationToken: Ct);
+ readiness.Refusal().ShouldBeNull();
+
+ // Load 2 holds the gate on alm-2's row read and will fail there; load 3 is applied behind it.
+ var (reached2, release2) = store.Hold("alm-2");
+ var (reached3, release3) = store.Hold("alm-3");
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1"), Plan("alm-2")]));
+ await reached2.WaitAsync(Timeout, Ct);
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1"), Plan("alm-3")]));
+ // Mailbox order: the answer to this ask proves load 3's apply was processed (its generation is the latest).
+ (await Ask(host, "nobody", "Acknowledge")).Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
+
+ // Load 2 fails; load 3 then takes the gate (clearing the engine's complete-generation flag) and holds it. The
+ // Warning proves the host has processed load 2's failure before the readiness assertion below.
+ await EventFilter.Warning(contains: "LoadAsync failed").ExpectOneAsync(Timeout, async () =>
+ {
+ release2.SetResult(new IOException("database is locked"));
+ await reached3.WaitAsync(Timeout, Ct);
+ }, Ct);
+ engine.HasCompleteGeneration.ShouldBeFalse("load 3 is in flight");
+ readiness.Refusal().ShouldBeNull("a superseded failure publishes nothing — a command queues behind the newer load");
+
+ release3.SetResult(null);
+ mux.ExpectMsg(Timeout, cancellationToken: Ct);
+ readiness.Refusal().ShouldBeNull();
+ (await Ask(host, "alm-3", "AddComment", "ok", "cmd-ok")).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
+ }
+
+ /// #953 positive control: the LATEST load's failure still publishes the refusal.
+ [Fact]
+ public async Task The_latest_load_failure_still_refuses_commands()
+ {
+ var store = new HoldableStore();
+ var (host, _, readiness, mux) = Spawn(store);
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
+ mux.ExpectMsg(Timeout, cancellationToken: Ct);
+
+ var (reached, release) = store.Hold("alm-2");
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1"), Plan("alm-2")]));
+ await reached.WaitAsync(Timeout, Ct);
+ release.SetResult(new IOException("database is locked"));
+ AwaitCondition(() => readiness.Refusal() is not null, Timeout, cancellationToken: Ct);
+ (await Ask(host, "alm-1", "Acknowledge")).Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
+ }
}