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
@@ -0,0 +1,219 @@
using System.Collections.Concurrent;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.ServerEventRig;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// Gitea #937 over the wire — a scripted condition's Part 9 method returns the scripted-alarm engine's verdict. Before
/// #937 the command was a fire-and-forget topic publish and every allowed call returned Good, including one the engine
/// then rejected because its last load had failed.
/// </summary>
public sealed class ScriptedCommandVerdictWireTests
{
private const NodePermissions All =
NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead
| NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.AlarmShelve
| NodePermissions.MethodCall;
/// <summary>The engine refuses (no complete generation): the client's Acknowledge fails BadInvalidState with its reason.</summary>
[Theory]
[InlineData("Acknowledge")]
[InlineData("AddComment")]
[InlineData("OneShotShelve")]
[InlineData("Disable")]
public async Task A_command_the_engine_refuses_returns_BadInvalidState(string method)
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync($"Verdict937Refused{method}", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
var asked = new ConcurrentQueue<AlarmCommand>();
rig.Nm.AlarmCommandAsker = (cmd, _) =>
{
asked.Enqueue(cmd);
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "engine blind"));
};
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(method, native: false) with { Message = "base" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
var refused = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
session, ConditionNodeId(session, false), method, events.LatestEventId(item, "base"), ct));
refused.StatusCode.ShouldBe(StatusCodes.BadInvalidState);
asked.Count.ShouldBe(1, "the command reached the engine exactly once");
asked.Single().CommandId.ShouldNotBeNullOrEmpty("the local host de-duplicates the broadcast copy by it");
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>Positive control: an applied verdict is Good, and the method still reports exactly one event.</summary>
[Fact]
public async Task A_command_the_engine_applies_returns_Good_with_one_event()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Applied", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
var current = ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" };
var routed = new ConcurrentQueue<AlarmCommand>();
rig.Nm.AlarmCommandRouter = routed.Enqueue;
rig.Nm.AlarmCommandAsker = (cmd, _) =>
{
// What the engine does: apply, then re-project (the method's own event already covered it).
current = current with { Acknowledged = true };
rig.ProjectLater(native: false, current);
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied));
};
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, current);
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
await ConditionMethodEventTests.CallAsync(session, ConditionNodeId(session, false), "Acknowledge",
events.LatestEventId(item, "base"), ct);
await rig.DrainProjectionsAsync();
rig.Project(false, current = current with { Message = "sentinel" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
events.ConditionEvents(item, "base").Count.ShouldBe(2, "the base transition plus exactly one Acknowledge event");
routed.ShouldBeEmpty("the asker replaces the fire-and-forget router inside a Call");
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>No answer inside the bound: BadTimeout with OutcomeUnknown — never reported as refused.</summary>
[Fact]
public async Task An_unanswered_command_returns_BadTimeout_outcome_unknown()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Timeout", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
rig.Nm.ScriptedCommandTimeout = TimeSpan.FromMilliseconds(500);
var never = new TaskCompletionSource<AlarmCommandOutcome>();
rig.Nm.AlarmCommandAsker = (_, _) => never.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 started = DateTime.UtcNow;
var unknown = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
session, ConditionNodeId(session, false), "Acknowledge", events.LatestEventId(item, "base"), ct));
unknown.StatusCode.ShouldBe(StatusCodes.BadTimeout);
(DateTime.UtcNow - started).ShouldBeLessThan(TimeSpan.FromSeconds(10), "bounded");
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// The synchronous pre-check: while the last load failed, the call is refused BadInvalidState BEFORE the SDK applies
/// anything — nothing is asked or routed, and no condition event is reported (sentinel-checked).
/// </summary>
[Fact]
public async Task The_preflight_refuses_before_any_state_change()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Preflight", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
var asked = 0;
var routed = 0;
rig.Nm.AlarmCommandAsker = (cmd, _) =>
{
Interlocked.Increment(ref asked);
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied));
};
rig.Nm.AlarmCommandRouter = _ => Interlocked.Increment(ref routed);
string? refusal = "the last scripted-alarm deploy failed";
rig.Nm.ScriptedAlarmCommandPreflight = () => refusal;
var current = ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" };
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, current);
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
var refused = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
session, ConditionNodeId(session, false), "Acknowledge", events.LatestEventId(item, "base"), ct));
refused.StatusCode.ShouldBe(StatusCodes.BadInvalidState);
rig.Project(false, current with { Message = "sentinel" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
events.ConditionEvents(item, "base").Count.ShouldBe(1, "no Acknowledge event was reported");
events.ConditionEvents(item, "sentinel")[0][RecordedEvents.AckedField].ClrValue()!.ShouldBe(false, "the node was not acknowledged");
Volatile.Read(ref asked).ShouldBe(0);
Volatile.Read(ref routed).ShouldBe(0);
// Positive control: once a load succeeds the same call goes through.
refusal = null;
await ConditionMethodEventTests.CallAsync(session, ConditionNodeId(session, false), "Acknowledge",
events.LatestEventId(item, "sentinel"), ct);
Volatile.Read(ref asked).ShouldBe(1);
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>A2b: a remote (gRPC data) condition method on a scripted condition carries the same verdict.</summary>
[Fact]
public async Task A_remote_condition_method_reports_the_engine_refusal_as_dispatched()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Remote", encrypted: false, ct);
try
{
rig.MaterialiseScripted();
rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" });
await rig.DrainProjectionsAsync();
rig.Nm.AlarmCommandAsker = (cmd, _) =>
Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "engine blind"));
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 refused = await rig.Nm.ExecuteConditionMethodAsync(call, TimeSpan.FromSeconds(5));
refused.Applied.ShouldBeFalse();
refused.Dispatched.ShouldBeTrue();
refused.Unknown.ShouldBeFalse();
refused.StatusCode.ShouldBe(StatusCodes.BadInvalidState.Code);
refused.Diagnostic.ShouldBe("engine blind");
}
finally { await rig.DisposeAsync(); }
}
}
@@ -61,6 +61,24 @@ public sealed class GrpcDataConditionMethodTests
"Acknowledge", "ack", new ConditionActivationMarker("inc", 1), "peer", "peer-key"));
}
/// <summary>#937: a scripted engine's refusal after dispatch is a definite failure; no answer is OutcomeUnknown.</summary>
[Fact]
public async Task A_scripted_engine_verdict_after_dispatch_maps_to_confirmed_failure_or_outcome_unknown()
{
using var refusedFixture = new ConditionFixture(2, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
refusedFixture.Source.Execute = _ => new(false, false, BadInvalidState, "engine blind", Dispatched: true);
var refused = await CallAsync(refusedFixture, Request(RawPlacement(1)));
refused.State.ShouldBe(DataWriteState.DriverConfirmedFailure);
refused.StatusCode.ShouldBe(BadInvalidState);
refused.Diagnostic.ShouldBe("engine blind");
using var unknownFixture = new ConditionFixture(2, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
unknownFixture.Source.Execute = _ => new(false, false, BadTimeout, "OutcomeUnknown: no answer", Dispatched: true, Unknown: true);
var unknown = await CallAsync(unknownFixture, Request(RawPlacement(1)));
unknown.State.ShouldBe(DataWriteState.OutcomeUnknown);
unknown.StatusCode.ShouldBe(BadTimeout);
}
[Fact]
public async Task Capabilities_carry_the_method_bits_and_mask_only_on_the_Primary()
{
@@ -0,0 +1,113 @@
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;
/// <summary>
/// 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.
/// </summary>
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()
{
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 readiness = new ScriptedAlarmCommandReadinessView();
var host = Sys.ActorOf(ScriptedAlarmHostActor.Props(publish.Ref, mux.Ref, () => (upstream, engine), readiness: readiness));
return (host, engine, readiness, mux);
}
private static Task<AlarmCommandOutcome> Ask(IActorRef host, string alarmId, string operation, string? comment = null, string? commandId = null) =>
host.Ask<AlarmCommandOutcome>(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<DependencyMuxActor.RegisterInterest>(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);
}
[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<DependencyMuxActor.RegisterInterest>(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<DependencyMuxActor.RegisterInterest>(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"]);
}
}