using System.Collections.Concurrent;
using Akka.Actor;
using Akka.TestKit;
using Serilog;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.ScriptedAlarms;
///
/// Gitea #937 — the host answers a directly-asked command with the engine's verdict, publishes its load outcome for
/// the node manager's pre-check, and applies a command reaching it twice (ask + broadcast, same CommandId) once.
///
public sealed class ScriptedAlarmCommandVerdictTests : RuntimeActorTestBase
{
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static EquipmentScriptedAlarmPlan Plan(string id, string source = "return (int)ctx.GetTag(\"M.T\").Value > 90;") =>
new(ScriptedAlarmId: id, EquipmentId: "Plant/Line1/M", Name: id, AlarmType: "AlarmCondition", Severity: 800,
MessageTemplate: "condition", PredicateScriptId: $"{id}-script", PredicateSource: source,
DependencyRefs: ["M.T"], HistorizeToAveva: false, Retain: true, Enabled: true);
private static EquipmentScriptedAlarmPlan BadPlan(string id) => Plan(id, "return unknownIdentifier;");
private (IActorRef Host, ScriptedAlarmEngine Engine, ScriptedAlarmCommandReadinessView Readiness, TestProbe Mux) Spawn(
IAlarmStateStore? store = null, TimeSpan? commandTimeout = null, TimeSpan? broadcastDecisionWindow = null)
{
var publish = CreateTestProbe();
var mux = CreateTestProbe();
var upstream = new DependencyMuxTagUpstreamSource();
var logger = new LoggerConfiguration().CreateLogger();
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),
commandTimeout: commandTimeout, readiness: readiness, broadcastDecisionWindow: broadcastDecisionWindow));
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);
[Fact]
public async Task After_a_failed_load_a_command_is_refused_and_the_readiness_view_says_so()
{
var (host, _, readiness, mux) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg(Timeout, cancellationToken: Ct);
readiness.Refusal().ShouldBeNull();
// Positive control: a good generation applies (an ack of an inactive alarm is an applied no-op).
(await Ask(host, "alm-1", "AddComment", "first")).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
// A deploy that fails to compile leaves the engine with no complete generation.
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1"), BadPlan("bad-1")]));
AwaitCondition(() => readiness.Refusal() is not null, Timeout, cancellationToken: Ct);
var refused = await Ask(host, "alm-1", "Acknowledge");
refused.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
refused.Reason.ShouldBe(ScriptedAlarmCommandReadinessView.LoadFailedRefusal);
// The alarm that broke the load is still this host's (in the plan, absent from the half-built engine set).
(await Ask(host, "bad-1", "Acknowledge")).Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
// The next good deploy clears it.
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
AwaitCondition(() => readiness.Refusal() is null, Timeout, cancellationToken: Ct);
(await Ask(host, "alm-1", "AddComment", "second")).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
}
///
/// #937 review r2 M2: an ask still queued past its asker's deadline never touches the engine (no growth of late work
/// behind a stalled store) and is NOT remembered — the broadcast copy of the same command still applies here.
///
[Fact]
public async Task An_expired_ask_skips_the_engine_and_leaves_the_broadcast_copy_to_apply()
{
var (host, engine, _, mux) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg(Timeout, cancellationToken: Ct);
var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "late", null, "cmd-late");
var expired = await host.Ask(
new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct);
expired.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown);
engine.GetState("alm-1")!.Comments.ShouldBeEmpty("the expired ask never reached the engine");
host.Tell(cmd); // the broadcast copy (same CommandId)
// Positive control behind it in the mailbox: a fresh ask (in time) applies, so the copy was processed first.
(await Ask(host, "alm-1", "AddComment", "after", "cmd-after")).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
engine.GetState("alm-1")!.Comments.Select(c => c.Text).ShouldBe(["late", "after"]);
}
[Fact]
public async Task An_alarm_this_host_does_not_own_is_answered_not_applied()
{
var (host, _, _, mux) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg(Timeout, cancellationToken: Ct);
var outcome = await Ask(host, "someone-elses", "Acknowledge");
outcome.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task A_command_arriving_as_both_ask_and_broadcast_is_applied_once(bool broadcastFirst)
{
var (host, engine, _, mux) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg(Timeout, cancellationToken: Ct);
var broadcast = new AlarmCommand("alm-1", "AddComment", "alice", "note", null, "cmd-1");
AlarmCommandOutcome outcome;
if (broadcastFirst)
{
host.Tell(broadcast);
outcome = await Ask(host, "alm-1", "AddComment", "note", "cmd-1");
}
else
{
outcome = await Ask(host, "alm-1", "AddComment", "note", "cmd-1");
host.Tell(broadcast);
}
outcome.Verdict.ShouldBe(AlarmCommandVerdict.Applied);
// Positive control: a different id IS applied — so the count below proves de-duplication, not a dropped copy.
(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
// #958: the unknown answer carries what the broadcast copy did here.
(await unknown.LateOutcome!.WaitAsync(Timeout, Ct)).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
(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"]);
}
///
/// #958: an ask answered "the broadcast copy decides" carries, as its , what
/// THIS host's engine does with that copy — so when the engine refuses the copy (here: the deploy that landed in between
/// failed) the node manager can revert the method's node change. Before #958 nobody awaited the copy and the node kept
/// the change until the next good deploy. An applied copy settles Applied (the node keeps the change).
///
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task The_broadcast_copys_local_outcome_settles_the_expired_asks_late_outcome(bool refused)
{
var (host, engine, readiness, mux) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg(Timeout, cancellationToken: Ct);
var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "late", null, "cmd-958");
var unknown = await host.Ask(
new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct);
unknown.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown);
var late = unknown.LateOutcome;
(late is not null).ShouldBeTrue("the broadcast copy's local outcome is still coming");
late!.IsCompleted.ShouldBeFalse("nothing decided the command yet");
if (refused)
{
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1"), BadPlan("bad-1")]));
AwaitCondition(() => readiness.Refusal() is not null, Timeout, cancellationToken: Ct);
}
host.Tell(cmd); // the broadcast copy (same CommandId)
var decided = await late.WaitAsync(Timeout, Ct);
decided.Verdict.ShouldBe(refused ? AlarmCommandVerdict.NotApplied : AlarmCommandVerdict.Applied);
if (refused)
{
decided.Reason.ShouldBe(ScriptedAlarmCommandReadinessView.LoadFailedRefusal);
engine.GetState("alm-1")!.Comments.ShouldBeEmpty();
}
else
{
engine.GetState("alm-1")!.Comments.Select(c => c.Text).ShouldBe(["late"]);
}
}
/// #958: the copy reaching the host BEFORE the expired ask (remembered) answers the ask with that verdict
/// directly — one terminal outcome, so the node manager reverts at most once.
[Fact]
public async Task A_broadcast_copy_refused_before_the_expired_ask_answers_it_directly()
{
var (host, _, readiness, _) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1"), BadPlan("bad-1")]));
AwaitCondition(() => readiness.Refusal() is not null, Timeout, cancellationToken: Ct);
var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "late", null, "cmd-958-first");
host.Tell(cmd);
var answer = await host.Ask(
new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct);
answer.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
(answer.LateOutcome is null).ShouldBeTrue();
}
/// #958: a broadcast copy that never arrives (the publish failed) settles the late outcome unknown after the
/// window — never left pending, never a refusal.
[Fact]
public async Task A_broadcast_copy_that_never_arrives_settles_unknown_after_the_window()
{
var (host, _, _, mux) = Spawn(broadcastDecisionWindow: TimeSpan.FromMilliseconds(200));
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg(Timeout, cancellationToken: Ct);
var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "lost", null, "cmd-958-lost");
var unknown = await host.Ask(
new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct);
var settled = await unknown.LateOutcome!.WaitAsync(Timeout, Ct);
settled.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown);
settled.AlarmId.ShouldBe("alm-1");
(settled.LateOutcome is null).ShouldBeTrue("the chain ends: nothing more is coming");
}
/// #958: a host that stops with a copy still pending settles it unknown (the late chain always ends).
[Fact]
public async Task A_stopping_host_settles_a_pending_broadcast_decision_unknown()
{
var (host, _, _, mux) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg(Timeout, cancellationToken: Ct);
var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "orphan", null, "cmd-958-stop");
var unknown = await host.Ask(
new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct);
Sys.Stop(host);
(await unknown.LateOutcome!.WaitAsync(Timeout, Ct)).Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown);
}
///
/// #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);
}
}