fix(grpc-data): A1 review B1 — a scripted projection never marks its condition known

WriteAlarmCondition set _conditionStateKnown for every projection. Scripted Active is not persisted, so the
post-restart re-assert of a restored unacked/shelved/disabled alarm (or the re-projection of an operator ack
before the inputs arrived) produced a known=true, Active=false record no predicate decided (T2 case i).
Only native transitions are established states now; scripted known-ness comes only from MarkConditionsKnown.
This commit is contained in:
Joseph Doherty
2026-11-24 10:17:34 -05:00
parent eb688a4ee0
commit e9d82a6a5a
3 changed files with 130 additions and 6 deletions
@@ -1419,10 +1419,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// WireMethodTransitionReporting) equals the node's current state → no delta → suppress, so
// the transition is reported exactly once. ReportConditionEvent
// stamps a fresh EventId, ClearChangeMasks, and ReportEvent — all still under this lock.
// A1 (§5.1): a projected snapshot IS an established state. The record is raised by
// ReportConditionEvent when the gate fires, otherwise here as a state-only record (ConditionClass and
// the other silent fields).
_conditionStateKnown.Add(key);
// A1 (§5.1): a NATIVE driver transition IS an established state. A SCRIPTED projection is not: the
// engine's Active is not persisted, so a post-load re-assert (or a projection after an operator
// ack/shelve/disable before the inputs arrived) can carry Active=false that no predicate decided —
// scripted known-ness comes ONLY from MarkConditionsKnown (the engine's inputs-established flip).
// The record is raised by ReportConditionEvent when the gate fires, otherwise here as a state-only
// record (ConditionClass and the other silent fields).
if (_nativeAlarmNodeIds.Contains(key)) _conditionStateKnown.Add(key);
if (fire)
{
ReportConditionEvent(condition, sourceTimestampUtc);
@@ -208,6 +208,28 @@ public sealed class ConditionStateNodeManagerTests : IDisposable
await host.DisposeAsync();
}
/// <summary>Review B1: a scripted projection (a post-restart re-assert of a restored unacked alarm, or the
/// re-projection of an early operator ack) is not an established state — only <c>MarkConditionsKnown</c> makes a
/// scripted condition known. A native transition still is one.</summary>
[Fact]
public async Task B1_A_scripted_projection_never_marks_known_a_native_one_does()
{
var (host, nm, sink) = await BootAsync();
MaterialiseAll(nm);
nm.CompleteAddressSpaceApply();
nm.WriteAlarmCondition(Scripted, State(false, false), DateTime.UtcNow, AddressSpaceRealm.Uns); // restored unacked
nm.WriteAlarmCondition(Scripted, State(false, true), DateTime.UtcNow, AddressSpaceRealm.Uns); // early ack
nm.IsConditionStateKnown(Scripted, AddressSpaceRealm.Uns).ShouldBeFalse();
sink.Records.ShouldNotContain(r => r.ConditionId == Scripted && r.StateKnown);
nm.MarkConditionsKnown("scripted", [Scripted], AddressSpaceRealm.Uns).ShouldBe(1);
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
nm.IsConditionStateKnown(Native, AddressSpaceRealm.Raw).ShouldBeTrue();
AssertParity(nm, sink);
await host.DisposeAsync();
}
[Fact]
public async Task T3_The_marker_moves_only_on_a_new_occurrence()
{
@@ -25,6 +25,8 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.ScriptedAlarms;
[Trait("Category", "Unit")]
public sealed class ScriptedAlarmHostInputsEstablishedTests : RuntimeActorTestBase
{
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-a1host-{Guid.NewGuid():N}");
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
@@ -34,14 +36,111 @@ public sealed class ScriptedAlarmHostInputsEstablishedTests : RuntimeActorTestBa
PredicateSource: "return (int)ctx.GetTag(\"M.T\").Value > 90;", DependencyRefs: ["M.T"],
HistorizeToAveva: false, Retain: true, Enabled: true);
private IActorRef Spawn(TestProbe publish, TestProbe mux)
private IActorRef Spawn(TestProbe publish, TestProbe mux) => Spawn(publish, mux, new InMemoryAlarmStateStore(), out _);
private IActorRef Spawn(TestProbe publish, TestProbe mux, IAlarmStateStore store, out ScriptedAlarmEngine engine)
{
var upstream = new DependencyMuxTagUpstreamSource();
var logger = new LoggerConfiguration().CreateLogger();
var engine = new ScriptedAlarmEngine(upstream, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger);
engine = new ScriptedAlarmEngine(upstream, store, new ScriptLoggerFactory(logger), logger);
return Sys.ActorOf(ScriptedAlarmHostActor.Props(publish.Ref, mux.Ref, upstream, engine, null));
}
/// <summary>
/// Review B1 (T2 case i): a restart restores a persisted UNACKED alarm (Active is not persisted). The post-load
/// re-assert projects it Active=false while its input is still never-pushed, and an operator ack before the input
/// arrives projects it again. Neither projection may make the condition known — that would be a
/// <c>known=true, Active=false</c> record no predicate decided. Known comes only from the engine's flip after the
/// first real evaluation. The host's publish-probe traffic is applied to a real node manager + hub.
/// </summary>
[Fact]
public async Task A_restored_unacked_alarm_is_not_known_through_its_reassert_or_an_early_ack()
{
var store = new InMemoryAlarmStateStore();
await store.SaveAsync(AlarmConditionState.Fresh("alm-1", DateTime.UtcNow) with { Acked = AlarmAckedState.Unacknowledged }, Ct);
var (opcHost, nm) = await BootNodeManagerAsync();
var hub = new ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionStateHub();
nm.ConditionStateSink = hub;
nm.EnsureFolder("Plant/Line1/M", null, "M", AddressSpaceRealm.Uns);
nm.MaterialiseAlarmCondition("alm-1", "Plant/Line1/M", "HighTemp", "AlarmCondition", 800, AddressSpaceRealm.Uns);
nm.CompleteAddressSpaceApply();
var publish = CreateTestProbe();
var mux = CreateTestProbe();
var host = Spawn(publish, mux, store, out var engine);
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan()]));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(Timeout, cancellationToken: Ct);
// The post-load re-assert of the restored unacked state, input still never-pushed.
var reassert = publish.ExpectMsg<OpcUaPublishActor.AlarmStateUpdate>(Timeout, cancellationToken: Ct);
reassert.State.Active.ShouldBeFalse();
reassert.State.Acknowledged.ShouldBeFalse();
Apply(nm, reassert);
nm.IsConditionStateKnown("alm-1", AddressSpaceRealm.Uns).ShouldBeFalse();
// An operator ack before the input arrives.
await engine.AcknowledgeAsync("alm-1", "op", null, Ct);
var ack = publish.ExpectMsg<OpcUaPublishActor.AlarmStateUpdate>(Timeout, cancellationToken: Ct);
ack.State.Acknowledged.ShouldBeTrue();
Apply(nm, ack);
nm.IsConditionStateKnown("alm-1", AddressSpaceRealm.Uns).ShouldBeFalse();
publish.ExpectNoMsg(TimeSpan.FromMilliseconds(300), Ct);
hub.ReadAll(0)!.ShouldNotContain(r => r.ConditionId == "alm-1" && r.StateKnown);
// The late input: the first real evaluation marks it known.
host.Tell(new VirtualTagActor.DependencyValueChanged("M.T", 50, DateTime.UtcNow));
var mark = publish.FishForMessage(m => m is OpcUaPublishActor.MarkConditionsKnown, Timeout, cancellationToken: Ct);
Apply(nm, mark);
nm.IsConditionStateKnown("alm-1", AddressSpaceRealm.Uns).ShouldBeTrue();
hub.ReadAll(0)!.Last(r => r.ConditionId == "alm-1").ShouldSatisfyAllConditions(
r => r.StateKnown.ShouldBeTrue(), r => r.Active.ShouldBeFalse());
await opcHost.DisposeAsync();
}
private static void Apply(OtOpcUaNodeManager nm, object message)
{
switch (message)
{
case OpcUaPublishActor.AlarmStateUpdate u:
nm.WriteAlarmCondition(u.AlarmNodeId, u.State, u.TimestampUtc, u.Realm);
break;
case OpcUaPublishActor.MarkConditionsKnown m when m.Known:
nm.MarkConditionsKnown(m.Source, m.ConditionIds, m.Realm);
break;
case OpcUaPublishActor.MarkConditionsKnown m:
nm.MarkConditionsUnknown(m.Source, m.ConditionIds, m.Realm);
break;
}
}
private async Task<(OpcUaApplicationHost Host, OtOpcUaNodeManager Nm)> BootNodeManagerAsync()
{
var started = await OpcUaHostStart.StartAsync(
port => new OpcUaApplicationHost(
new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.A1HostTest",
ApplicationUri = $"urn:OtOpcUa.A1HostTest:{Guid.NewGuid():N}",
OpcUaPort = port,
PublicHostname = "localhost",
PkiStoreRoot = _pkiRoot,
},
Microsoft.Extensions.Logging.Abstractions.NullLogger<OpcUaApplicationHost>.Instance),
() => new OtOpcUaSdkServer(), Ct);
return (started.Host, started.Server.NodeManager!);
}
/// <summary>Cleans up the PKI root directory.</summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && Directory.Exists(_pkiRoot))
{
try { Directory.Delete(_pkiRoot, recursive: true); }
catch { /* best-effort cleanup */ }
}
}
/// <summary>T2 (i) at the host: the input arrives late ⇒ no mark before the first real evaluation; then the Active
/// projection, then the mark.</summary>
[Fact]