fix(alarms): a scripted condition's Part 9 method returns the engine's verdict (#937)

Before: the alarm-commands topic is fire-and-forget, so an OPC UA method (and a
remote gRPC-data condition method) returned Good even when the engine rejected
the command because its last load failed.

- ScriptedAlarmCommandReadinessView: the host's latest load outcome; the node
  manager's handler refuses BadInvalidState before the SDK applies anything
  while the last load failed (lock-free read).
- Bounded ask: inside CallAsync (off Lock) each local request runs base.Call
  alone; the handler only STARTS AlarmCommandAsker (broadcast for the peer +
  DriverHostActor -> ScriptedAlarmHostActor.ExecuteAlarmCommand on the local
  engine, CommandId-deduplicated) and the Call awaits the verdict: refused =>
  BadInvalidState, no answer => BadTimeout OutcomeUnknown.
- Remote CallConditionMethod: ExecuteConditionMethodAsync => DriverConfirmedFailure
  / OutcomeUnknown on the origin.
- Host ownership uses the latest plan set (stable across a load in flight and a
  failed load's half-built set).
- Docs: ScriptedAlarms.md (verdicts, residual, duplicate-activation trade-off),
  DataConnections.md, rules/alarms.md. Live leg scenario F937 + seeder
  scripted_predicate mutation.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-11-28 09:40:35 -05:00
parent 05f431f5d8
commit d6f2a1b5e2
21 changed files with 1074 additions and 38 deletions
@@ -86,6 +86,16 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// <param name="Plans">The desired Equipment-namespace scripted-alarm plans.</param>
public sealed record ApplyScriptedAlarms(IReadOnlyList<EquipmentScriptedAlarmPlan> Plans);
/// <summary>
/// #937: a NODE-LOCAL ask (never published, never serialized) — apply <paramref name="Command"/> to this host's
/// engine and reply an <see cref="AlarmCommandOutcome"/> to the sender, so the OPC UA Part 9 method that issued it
/// can return the engine's verdict instead of the Good a fire-and-forget topic publish implied. The same command
/// (same <see cref="AlarmCommand.CommandId"/>) is also broadcast on <see cref="AlarmCommandsTopic"/> for the
/// redundant peer; this host applies whichever copy arrives first and skips the other.
/// </summary>
/// <param name="Command">The command.</param>
public sealed record ExecuteAlarmCommand(AlarmCommand Command);
/// <summary>
/// Told to the parent from <see cref="PostRestart"/>. A supervision restart is otherwise invisible to the
/// parent, and the new incarnation has an EMPTY engine (factory Props) and no mux interest, so until the
@@ -175,6 +185,19 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// <see cref="OnAlarmsLoaded"/> so out-of-order loads never register superseded dep refs.</summary>
private int _loadGeneration;
/// <summary>#937: the published outcome of the latest completed load (null in tests).</summary>
private readonly ScriptedAlarmCommandReadinessView? _readiness;
/// <summary>#937: the enabled alarm ids of the latest <see cref="ApplyScriptedAlarms"/> — this host's alarms even while
/// the engine's own set is mid-load or (a failed load) half-built.</summary>
private HashSet<string> _plannedAlarmIds = new(StringComparer.Ordinal);
/// <summary>#937: the outcome of each recent command that carried a <see cref="AlarmCommand.CommandId"/>, so the
/// broadcast copy of a directly-asked command (or the other way round) is applied once. Bounded FIFO.</summary>
private readonly Dictionary<string, AlarmCommandOutcome> _recentCommands = new(StringComparer.Ordinal);
private readonly Queue<string> _recentCommandOrder = new();
internal const int RecentCommandCapacity = 1024;
/// <summary>Cached cluster DistributedPubSub mediator, resolved once in <see cref="PreStart"/> (on the
/// actor thread) and reused for every emission instead of re-resolving it per-publish.</summary>
private IActorRef _mediator = null!;
@@ -230,8 +253,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
NodeId? localNode = null,
Func<int>? driverMemberCountProvider = null,
ITelemetryLocalHub? telemetryHub = null,
TimeSpan? commandTimeout = null) =>
Akka.Actor.Props.Create(() => new ScriptedAlarmHostActor(publishActor, mux, engineFactory, localNode, driverMemberCountProvider, telemetryHub, commandTimeout));
TimeSpan? commandTimeout = null,
ScriptedAlarmCommandReadinessView? readiness = null) =>
Akka.Actor.Props.Create(() => new ScriptedAlarmHostActor(publishActor, mux, engineFactory, localNode, driverMemberCountProvider, telemetryHub, commandTimeout, readiness));
/// <summary>Factory-built incarnation: owns (and on every stop disposes) the engine it builds.</summary>
/// <param name="publishActor">The OPC UA publish actor emissions are bridged to.</param>
@@ -241,6 +265,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// <param name="driverMemberCountProvider">Test seam for the alerts-emit gate's driver-member count.</param>
/// <param name="telemetryHub">Optional node-local live-telemetry hub.</param>
/// <param name="commandTimeout">Bound on one inbound alarm command's engine op.</param>
/// <param name="readiness">#937: where the outcome of every completed load is published for the node manager's
/// synchronous pre-check. Null ⇒ none (tests).</param>
public ScriptedAlarmHostActor(
IActorRef publishActor,
IActorRef? mux,
@@ -248,8 +274,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
NodeId? localNode = null,
Func<int>? driverMemberCountProvider = null,
ITelemetryLocalHub? telemetryHub = null,
TimeSpan? commandTimeout = null)
: this(publishActor, mux, Build(engineFactory), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: true, commandTimeout)
TimeSpan? commandTimeout = null,
ScriptedAlarmCommandReadinessView? readiness = null)
: this(publishActor, mux, Build(engineFactory), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: true, commandTimeout, readiness)
{
}
@@ -284,7 +311,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
NodeId? localNode = null,
Func<int>? driverMemberCountProvider = null,
ITelemetryLocalHub? telemetryHub = null)
: this(publishActor, mux, (upstream, engine), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: false, commandTimeout: null)
: this(publishActor, mux, (upstream, engine), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: false, commandTimeout: null, readiness: null)
{
}
@@ -296,8 +323,12 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
Func<int>? driverMemberCountProvider,
ITelemetryLocalHub? telemetryHub,
bool ownsEngine,
TimeSpan? commandTimeout)
TimeSpan? commandTimeout,
ScriptedAlarmCommandReadinessView? readiness)
{
_readiness = readiness;
// A new incarnation has not loaded yet: whatever the previous one published no longer describes this engine.
_readiness?.Reset();
ArgumentNullException.ThrowIfNull(publishActor);
ArgumentNullException.ThrowIfNull(pair.Upstream);
ArgumentNullException.ThrowIfNull(pair.Engine);
@@ -341,6 +372,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// the handler is a Task-returning ReceiveAsync: Akka suspends the mailbox until the op completes
// (ordered, awaited on the actor thread) and routes any escaped fault through supervision.
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);
@@ -369,6 +402,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// Skip disabled plans entirely — the engine has no Enabled flag, so a disabled alarm is simply
// not loaded (no predicate, no upstream subscription, no events).
var enabled = msg.Plans.Where(p => p.Enabled).ToList();
_plannedAlarmIds = new HashSet<string>(enabled.Select(p => p.ScriptedAlarmId), StringComparer.Ordinal);
var defs = enabled.Select(ToDefinition).ToList();
@@ -401,10 +435,19 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
}
private void OnLoadFailed(Status.Failure msg)
=> _log.Warning(msg.Cause, "ScriptedAlarmHost: engine LoadAsync failed — alarms not (re)loaded");
{
// #937: loads serialize on the engine's gate, so completions arrive in start order — this is the latest
// completed load, and the engine now holds no complete generation (it rejects every operator command).
_readiness?.SetLoadOutcome(loaded: false);
_log.Warning(msg.Cause, "ScriptedAlarmHost: engine LoadAsync failed — alarms not (re)loaded; operator commands are refused until the next successful deploy");
}
private void OnAlarmsLoaded(AlarmsLoaded msg)
{
// #937: ANY completed load — even one a newer apply superseded — left the engine holding a complete generation
// until that newer load finishes (which then publishes its own outcome).
_readiness?.SetLoadOutcome(loaded: true);
// Discard a stale completion: if a newer apply has since bumped the generation, this load's
// dep refs are superseded and registering them would re-introduce the old set. The latest
// generation's continuation will (or already did) register the current interest set.
@@ -741,17 +784,74 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// <param name="cmd">The inbound alarm command.</param>
private async Task OnAlarmCommand(AlarmCommand cmd)
{
// #937: the broadcast copy of a command this host already took through ExecuteAlarmCommand (or the other way
// round) is applied once.
if (cmd.CommandId is { } id && _recentCommands.ContainsKey(id))
{
_log.Debug("ScriptedAlarmHost: skipping duplicate AlarmCommand {Op} for {AlarmId} (command {CommandId})",
cmd.Operation, cmd.AlarmId, id);
return;
}
// Ownership filter FIRST: ignore commands for alarms this engine doesn't own. The topic is a
// cluster-wide broadcast, so the same command lands on every host — only the owner acts.
// Note: a concurrent LoadAsync can momentarily clear the loaded set, so a racing command may
// surface a spurious ArgumentException from the engine below — the outer catch absorbs it (benign).
if (!_engine.LoadedAlarmIds.Contains(cmd.AlarmId))
if (!Owns(cmd.AlarmId))
{
_log.Debug("ScriptedAlarmHost: ignoring AlarmCommand {Op} for unowned alarm {AlarmId}",
cmd.Operation, cmd.AlarmId);
return;
}
Remember(cmd, await ApplyCommandAsync(cmd));
}
/// <summary>
/// #937: the node-local ask behind an OPC UA Part 9 method. Applies the command exactly as
/// <see cref="OnAlarmCommand"/> does (once — a broadcast copy that already arrived is not re-applied; its recorded
/// outcome is the answer) and replies the verdict to the sender. Unlike the broadcast, an alarm this host does not
/// own is answered (<see cref="AlarmCommandVerdict.NotApplied"/>): the caller's condition node is on this node.
/// </summary>
private async Task OnExecuteAlarmCommand(ExecuteAlarmCommand msg)
{
var replyTo = Sender;
var cmd = msg.Command;
if (cmd.CommandId is { } id && _recentCommands.TryGetValue(id, out var known))
{
replyTo.Tell(known);
return;
}
var outcome = Owns(cmd.AlarmId)
? await ApplyCommandAsync(cmd)
: new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
_readiness?.Refusal() ?? NotLoadedRefusal);
Remember(cmd, outcome);
replyTo.Tell(outcome);
}
private const string NotLoadedRefusal =
"The alarm is not loaded by this server's scripted-alarm engine; the command was not applied.";
/// <summary>Whether this host owns <paramref name="alarmId"/>: in the latest plan (stable across a load in flight and
/// a failed load's half-built set) or loaded by the engine (a legacy, externally loaded engine).</summary>
private bool Owns(string alarmId) => _plannedAlarmIds.Contains(alarmId) || _engine.LoadedAlarmIds.Contains(alarmId);
private void Remember(AlarmCommand cmd, AlarmCommandOutcome outcome)
{
if (cmd.CommandId is not { } id || !_recentCommands.TryAdd(id, outcome)) return;
_recentCommandOrder.Enqueue(id);
while (_recentCommandOrder.Count > RecentCommandCapacity) _recentCommands.Remove(_recentCommandOrder.Dequeue());
}
/// <summary>
/// Runs one owned command against the engine and classifies the result (#937). Never throws: every failure is
/// logged like <see cref="OnLoadFailed"/> and becomes a verdict.
/// </summary>
private async Task<AlarmCommandOutcome> ApplyCommandAsync(AlarmCommand cmd)
{
AlarmCommandOutcome Refused(string reason) => new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, reason);
// Bounded (R02:H3): every op ends in IAlarmStateStore.SaveAsync (LocalDb/SQLite), and this is a
// ReceiveAsync — the mailbox is suspended until the op returns, so an unbounded await on a hung
// file lock stalled dependency-value ingestion for the duration. Linked to the actor's lifetime
@@ -780,7 +880,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
{
_log.Warning("ScriptedAlarmHost: rejecting TimedShelve for {AlarmId} — missing UnshelveAtUtc",
cmd.AlarmId);
return;
return Refused("TimedShelve requires an unshelve time; the command was not applied.");
}
await _engine.TimedShelveAsync(cmd.AlarmId, cmd.User, unshelveAt, ct);
break;
@@ -797,35 +897,50 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
if (string.IsNullOrWhiteSpace(cmd.Comment))
{
_log.Warning("ScriptedAlarmHost: rejecting AddComment for {AlarmId} — empty comment text", cmd.AlarmId);
return;
return Refused("AddComment requires comment text; the command was not applied.");
}
await _engine.AddCommentAsync(cmd.AlarmId, cmd.User, cmd.Comment, ct);
break;
default:
_log.Warning("ScriptedAlarmHost: ignoring AlarmCommand with unknown operation {Op} for {AlarmId}",
cmd.Operation, cmd.AlarmId);
break;
return Refused($"Unknown alarm operation '{cmd.Operation}'; the command was not applied.");
}
return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied);
}
catch (OperationCanceledException) when (!_cts.IsCancellationRequested)
{
// The op may have been cancelled inside SaveAsync after the store committed: unknown, never "not applied".
_log.Warning("ScriptedAlarmHost: engine op {Op} for alarm {AlarmId} timed out after {Timeout} — the condition-state store is stalled",
cmd.Operation, cmd.AlarmId, _commandTimeout);
return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
$"OutcomeUnknown: the alarm engine did not finish the command within {_commandTimeout.TotalSeconds:0.#} s.", TimedOut: true);
}
catch (ScriptedAlarmCommandRejectedException ex)
{
// #935 review S3: the last LoadAsync failed, so the engine holds no trusted state and refuses the
// command rather than persist one derived from a Fresh seed. The command is a fire-and-forget topic
// broadcast (the OPC UA method / AdminUI already returned), so this Warning is the operator-visible
// record; the next successful deploy re-asserts the condition node from the store.
// command (thrown before anything is saved) rather than persist one derived from a Fresh seed. #937: a
// directly-asked command reports this to its OPC UA caller; a broadcast-only copy (the AdminUI, the
// redundant peer's copy) has only this Warning. The next successful deploy re-asserts the node from the store.
_log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} NOT applied — {Reason}",
cmd.Operation, cmd.AlarmId, ex.Message);
return Refused(ScriptedAlarmCommandReadinessView.LoadFailedRefusal);
}
catch (ArgumentException ex)
{
// The engine's lookup (under its gate, before any save): the alarm is not in the generation the command
// ran against — e.g. the deploy queued ahead of it removed the alarm.
_log.Warning(ex, "ScriptedAlarmHost: engine op {Op} refused for alarm {AlarmId}", cmd.Operation, cmd.AlarmId);
return Refused(NotLoadedRefusal);
}
catch (Exception ex)
{
// A failing engine op must not crash the actor — mirror OnLoadFailed's log-and-stay-inert style.
// A failing engine op must not crash the actor — mirror OnLoadFailed's log-and-stay-inert style. A store
// fault may have left the row written, so this is unknown, not a refusal.
_log.Warning(ex, "ScriptedAlarmHost: engine op {Op} failed for alarm {AlarmId}",
cmd.Operation, cmd.AlarmId);
return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
"OutcomeUnknown: the alarm engine failed while applying the command.");
}
}
@@ -887,6 +1002,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
_engine.OnInputsEstablished -= _onInputsEstablished;
if (_ownsEngine || !_restarting) _engine.Dispose();
_cts.Dispose();
// #937: this engine's load outcome describes nothing once it is gone (the ask path answers for a missing host).
_readiness?.Reset();
base.PostStop();
}