fix(alarms): #951 #952 #953 — late refusal reverts, never-started command is NotApplied, superseded load failure ignored

#951: the hosted-service Ask lives LateVerdictWindow (30 s) past the caller's bound
(ExecuteAlarmCommand deadline unchanged); the OutcomeUnknown it returns carries the
still-running ask as AlarmCommandOutcome.LateOutcome (process-local). The node manager
watches it (or the asker task itself when its backstop expired, following unknown
chains) and reverts the node on a late NotApplied, under the existing per-condition
mutation-counter guard. Both CallAsync and remote ExecuteConditionMethodAsync paths.

#952: ScriptedAlarmEngine throws ScriptedAlarmCommandNotStartedException (an OCE) when a
command is cancelled before it acquires _evalGate; a cancellation inside SaveAsync stays
a plain OCE (unknown). The host maps not-started to NotApplied and remembers it, except on
the direct ask once its asker's deadline passed (asker already answered unknown and
broadcast): then unknown + not remembered, so the broadcast copy decides (as review r2 M2).

#953: a faulted load pipes back AlarmsLoadFailed(cause, generation); a failure from a
generation a newer apply superseded publishes no readiness (it would refuse every command
while the newer load is in flight).

Red/green: each fix reverted individually turns its tests red (Core 1, Runtime 3,
Host 1, OpcUaServer.IntegrationTests 4).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-01 19:42:24 -05:00
parent 6b60845931
commit 068124d1ae
14 changed files with 596 additions and 33 deletions
@@ -93,4 +93,13 @@ public sealed record AlarmCommandOutcome(
string Operation,
AlarmCommandVerdict Verdict,
string? Reason = null,
bool TimedOut = false);
bool TimedOut = false)
{
/// <summary>
/// #951: for an <see cref="AlarmCommandVerdict.OutcomeUnknown"/> 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.
/// </summary>
public Task<AlarmCommandOutcome>? LateOutcome { get; init; }
}
@@ -0,0 +1,23 @@
namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
/// <summary>
/// #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
/// <see cref="ScriptedAlarmEngine.LoadAsync"/>. 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 <see cref="OperationCanceledException"/>).
/// </summary>
/// <remarks>Derives from <see cref="OperationCanceledException"/> so a caller that only knows "cancelled" is unchanged.</remarks>
public sealed class ScriptedAlarmCommandNotStartedException : OperationCanceledException
{
/// <summary>Creates the exception for <paramref name="alarmId"/>.</summary>
/// <param name="alarmId">The alarm the command was for.</param>
/// <param name="inner">The cancellation observed while waiting for the gate.</param>
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;
/// <summary>The alarm the command was for.</summary>
public string AlarmId { get; }
}
@@ -745,7 +745,16 @@ public sealed class ScriptedAlarmEngine : IDisposable
private async Task ApplyAsync(string alarmId, CancellationToken ct, Func<AlarmConditionState, TransitionResult> 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
@@ -614,7 +614,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
private Task<AlarmCommandOutcome> AskScriptedAlarmCommand(AlarmCommand cmd, TimeSpan timeout)
{
Func<AlarmCommand, TimeSpan, Task<AlarmCommandOutcome>>? askLocal = _actorRegistry.TryGet<DriverHostActorKey>(out var driverHost)
? (c, t) => driverHost.Ask<AlarmCommandOutcome>(new ScriptedAlarmHostActor.ExecuteAlarmCommand(c, 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<AlarmCommandOutcome>(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)),
@@ -24,13 +24,23 @@ namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa;
/// </remarks>
internal static class ScriptedAlarmCommandDispatch
{
/// <summary>
/// #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.
/// </summary>
internal static readonly TimeSpan LateVerdictWindow = TimeSpan.FromSeconds(30);
/// <summary>
/// Asks the local engine, then broadcasts unless it refused. Starts the ask synchronously (safe under the SDK's Lock);
/// never faults — no answer within <paramref name="timeout"/> is an OutcomeUnknown outcome.
/// </summary>
/// <param name="cmd">The command (with its <c>CommandId</c>, which de-duplicates the broadcast copy on the local host).</param>
/// <param name="timeout">The caller's bound.</param>
/// <param name="askLocal">The ask to this node's scripted-alarm host; null ⇒ none on this node.</param>
/// <param name="askLocal">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
/// <see cref="LateVerdictWindow"/> past it — and that late answer rides the timeout outcome's
/// <see cref="AlarmCommandOutcome.LateOutcome"/> (#951).</param>
/// <param name="broadcast">Publishes the command on the <c>alarm-commands</c> topic.</param>
/// <param name="logger">Logger.</param>
/// <returns>The local verdict.</returns>
@@ -44,15 +54,24 @@ internal static class ScriptedAlarmCommandDispatch
}
AlarmCommandOutcome outcome;
Task<AlarmCommandOutcome>? 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)
{
@@ -254,7 +254,7 @@ public sealed partial class OtOpcUaNodeManager
/// 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, 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);
}
/// <summary>
/// #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 — <see cref="RevertScriptedMethod"/>'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).
/// </summary>
private async Task RevertOnLateRefusalAsync(Task<AlarmCommandOutcome> 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");
}
}
/// <summary>
/// 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 <see cref="AlarmCommandVerdict.OutcomeUnknown"/>
/// 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 <see cref="AlarmCommandOutcome.LateOutcome"/>, or the pending task
/// itself when the backstop expired.
/// </summary>
private async Task<(ServiceResult Status, bool Unknown)> AwaitScriptedVerdictAsync(Task<AlarmCommandOutcome> pending, TimeSpan bound)
private async Task<(ServiceResult Status, bool Unknown, Task<AlarmCommandOutcome>? Late)> AwaitScriptedVerdictAsync(
Task<AlarmCommandOutcome> 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);
}
@@ -129,10 +129,15 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// <summary>Pipe-back marker for a <see cref="ScriptedAlarmEngine.LoadAsync"/> that was cancelled
/// because the actor is stopping (its <see cref="_cts"/> fired in <see cref="PostStop"/>). 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 <see cref="Status.Failure"/> that would log a spurious
/// pipes back a quiet message instead of an <see cref="AlarmsLoadFailed"/> that would log a spurious
/// Warning on every clean shutdown.</summary>
private sealed record AlarmsLoadCanceled;
/// <summary>Pipe-back of a faulted <see cref="ScriptedAlarmEngine.LoadAsync"/>, tagged with the load
/// <see cref="Generation"/> it ran under (#953: a failure a newer apply already superseded must not publish
/// readiness).</summary>
private sealed record AlarmsLoadFailed(Exception Cause, int Generation);
/// <summary>Default bound on one inbound alarm command's engine op (<see cref="OnAlarmCommand"/>): 10 s.</summary>
public static readonly TimeSpan DefaultCommandTimeout = TimeSpan.FromSeconds(10);
@@ -377,9 +382,12 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
ReceiveAsync<AlarmCommand>(OnAlarmCommand);
// #937: the node-local ask behind an OPC UA Part 9 method — same op, plus a reply carrying the verdict.
ReceiveAsync<ExecuteAlarmCommand>(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<Status.Failure>(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<AlarmsLoadFailed>(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<Status.Failure>(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<AlarmsLoadCanceled>(_ => { });
@@ -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);
}
/// <summary>#952: the refusal of a command that never got the engine's gate within the command bound.</summary>
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".