feat(grpc-data): A1 MarkConditionsKnown in OpcUaPublishActor — deferred beside alarm states, replayed after them (F2), discarded on a source's dropped/skipped projection (G3)

This commit is contained in:
Joseph Doherty
2026-11-24 09:27:53 -05:00
parent f49e4e100b
commit d64578b1c5
4 changed files with 336 additions and 7 deletions
@@ -2338,7 +2338,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
var nodeId = n.NodeId;
var snapshot = _nativeAlarmProjector.Project(nodeId, msg.Args, out IReadOnlyList<AlarmTransitionKind> historyKinds);
_opcUaPublishActor.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.AlarmStateUpdate(
nodeId, snapshot, msg.Args.SourceTimestampUtc, n.Realm));
nodeId, snapshot, msg.Args.SourceTimestampUtc, n.Realm, Source: msg.DriverInstanceId));
// Only the Primary publishes the cluster-wide alerts transition (see the gate above). The projector
// decides WHICH rows the transition warrants: none for a re-statement (a Raise on an
@@ -76,7 +76,28 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// <param name="TimestampUtc">The source timestamp of the transition in UTC.</param>
/// <param name="Realm">The namespace realm the condition lives in — <see cref="AddressSpaceRealm.Uns"/> for
/// scripted alarms (default), <see cref="AddressSpaceRealm.Raw"/> for v3 native raw conditions.</param>
public sealed record AlarmStateUpdate(string AlarmNodeId, AlarmConditionSnapshot State, DateTime TimestampUtc, AddressSpaceRealm Realm);
/// <param name="Source">A1 (plan §5.1 G3): the emitting source — the driver instance id for a native projection,
/// <see cref="ScriptedSource"/> for the scripted host, null when unattributed. Only used to discard a source's
/// deferred <see cref="MarkConditionsKnown"/> when one of its deferred projections is dropped or skipped.</param>
public sealed record AlarmStateUpdate(string AlarmNodeId, AlarmConditionSnapshot State, DateTime TimestampUtc, AddressSpaceRealm Realm,
string? Source = null);
/// <summary>The <see cref="AlarmStateUpdate.Source"/> / <see cref="MarkConditionsKnown.Source"/> of the scripted host.</summary>
public const string ScriptedSource = "scripted-alarms";
/// <summary>
/// A1 (plan §5.1 T1/F2/G3): the state of <paramref name="ConditionIds"/> has been established by
/// <paramref name="Source"/> (or, with <paramref name="Known"/> false, can no longer be vouched for). Treated as an
/// alarm message: applied after every <see cref="AlarmStateUpdate"/> the same sender sent before it (Akka per-pair
/// order), deferred beside them while a plan is in flight and replayed AFTER the deferred alarms — or discarded
/// when one of the same source's deferred projections was dropped (overflow) or skipped (out of scope), so a
/// condition is never made known over a projection that did not land.
/// </summary>
/// <param name="Source">The driver instance id, or <see cref="ScriptedSource"/>.</param>
/// <param name="ConditionIds">The condition node ids (RawPath for native, ScriptedAlarmId for scripted).</param>
/// <param name="Realm">Their realm.</param>
/// <param name="Known">True = mark known; false = withdraw (a scripted input reverted to never-pushed).</param>
public sealed record MarkConditionsKnown(string Source, IReadOnlyList<string> ConditionIds, AddressSpaceRealm Realm, bool Known = true);
/// <summary>Annotate a materialised condition's source-data Quality out of band from any alarm
/// transition (the driver-connectivity path: comms lost → <see cref="OpcUaStatus.BadNoCommunication"/>,
/// restored → <see cref="OpcUaStatus.Good"/>). Routed to <see cref="IOpcUaAddressSpaceSink.WriteAlarmQuality"/>,
@@ -562,6 +583,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
Receive<AttributeStatusBatchUpdate>(HandleAttributeStatusBatchUpdate);
Receive<AlarmStateUpdate>(HandleAlarmUpdate);
Receive<AlarmQualityUpdate>(HandleAlarmQualityUpdate);
Receive<MarkConditionsKnown>(HandleMarkConditionsKnown);
Receive<RebuildAddressSpace>(HandleRebuild);
Receive<PlanReady>(HandlePlanReady);
Receive<PlanFailed>(HandlePlanFailed);
@@ -775,6 +797,25 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
}
}
private void HandleMarkConditionsKnown(MarkConditionsKnown msg)
{
if (PlanPipelineBusy) _deferred.Mark(msg);
ApplyMark(msg);
}
private void ApplyMark(MarkConditionsKnown msg)
{
try
{
if (msg.Known) _sink.MarkConditionsKnown(msg.Source, msg.ConditionIds, msg.Realm);
else _sink.MarkConditionsUnknown(msg.Source, msg.ConditionIds, msg.Realm);
}
catch (Exception ex)
{
_log.Warning(ex, "OpcUaPublish: sink.MarkConditions{Kind} threw for {Source}", msg.Known ? "Known" : "Unknown", msg.Source);
}
}
private void HandleAlarmQualityUpdate(AlarmQualityUpdate msg)
{
if (PlanPipelineBusy) DeferAlarmQuality(msg);
@@ -1047,7 +1088,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
private void DeferAlarm(AlarmStateUpdate msg)
{
if (!_deferred.Alarm(msg)) WarnDeferredOverflow();
if (_deferred.Alarm(msg)) return;
// G3: this source's projection will not be replayed, so its deferred "known" marks must not be either.
_deferred.NoteAlarmLoss(msg.Source);
WarnDeferredOverflow();
}
private void DeferAlarmQuality(AlarmQualityUpdate msg)
@@ -1105,7 +1149,12 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
var alarms = 0;
foreach (var alarm in _deferred.Alarms)
{
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) continue;
if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId)))
{
_deferred.NoteAlarmLoss(alarm.Source); // G3: a skipped projection — the source's marks go too
continue;
}
alarms++;
try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm); }
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); }
@@ -1120,6 +1169,31 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); }
}
// A1 F2/G3: the deferred "known" marks replay LAST, after every deferred alarm — and only for a source none of
// whose deferred projections was dropped or skipped. A discarded mark leaves its conditions unknown (Uncertain)
// until the source's next signal.
var marks = 0;
var discarded = 0;
foreach (var mark in _deferred.Marks)
{
if (_deferred.SourceLost(mark.Source))
{
discarded++;
continue;
}
marks++;
ApplyMark(mark);
}
if (discarded > 0)
{
OtOpcUaTelemetry.DataConnConditionMarksDiscarded.Add(discarded);
_log.Info(
"OpcUaPublish: discarded {Count} deferred condition-known mark(s) whose source lost a deferred alarm projection; those conditions stay unknown until the source signals again",
discarded);
}
_log.Debug(
"OpcUaPublish: replayed {Values} value, {Statuses} status, {Alarms} alarm-state and {Qualities} alarm-quality writes (of {Held} held; {Unfit} not fitting a re-shaped node) deferred during a rebuild plan",
values.Count, statuses.Count, alarms, qualities, _deferred.Count, unfit);
@@ -1146,13 +1220,34 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
private readonly Dictionary<(AddressSpaceRealm, string), VariableEntry> _variables = new();
private readonly Dictionary<(AddressSpaceRealm, string), AlarmStateUpdate> _alarms = new();
private readonly Dictionary<(AddressSpaceRealm, string), AlarmQualityUpdate> _qualities = new();
// A1: condition-known marks in arrival order (bounded by Capacity — a dropped mark only keeps conditions
// unknown, which is always safe), and the sources that lost a deferred alarm projection (G3).
private readonly List<MarkConditionsKnown> _marks = new();
private readonly HashSet<string> _lossySources = new(StringComparer.Ordinal);
private bool _unattributedLoss;
public int Capacity { get; } = capacity;
public long Dropped { get; private set; }
public int Count => _variables.Count + _alarms.Count + _qualities.Count;
public bool IsEmpty => Count == 0;
public bool IsEmpty => Count == 0 && _marks.Count == 0;
public IEnumerable<AlarmStateUpdate> Alarms => _alarms.Values;
public IEnumerable<AlarmQualityUpdate> AlarmQualities => _qualities.Values;
public IReadOnlyList<MarkConditionsKnown> Marks => _marks;
public void Mark(MarkConditionsKnown msg)
{
if (_marks.Count < Capacity) _marks.Add(msg);
}
/// <summary>G3: a deferred projection of <paramref name="source"/> was dropped or skipped. An unattributed
/// loss (null source) discards every source's marks.</summary>
public void NoteAlarmLoss(string? source)
{
if (source is null) _unattributedLoss = true;
else _lossySources.Add(source);
}
public bool SourceLost(string source) => _unattributedLoss || _lossySources.Contains(source);
public bool Value(in ValueWrite write)
{
@@ -1218,6 +1313,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
_variables.Clear();
_alarms.Clear();
_qualities.Clear();
_marks.Clear();
_lossySources.Clear();
_unattributedLoss = false;
Dropped = 0;
}
@@ -482,7 +482,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// A client reading Time/ReceiveTime after a rebuild should still see when the alarm went
// active, not when the address space happened to be rebuilt.
TimestampUtc: projection.Condition.LastTransitionUtc,
Realm: AddressSpaceRealm.Uns));
Realm: AddressSpaceRealm.Uns,
Source: OpcUaPublishActor.ScriptedSource));
reasserted++;
}
@@ -582,7 +583,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
AlarmNodeId: e.AlarmId,
State: ToSnapshot(e),
TimestampUtc: e.TimestampUtc,
Realm: AddressSpaceRealm.Uns));
Realm: AddressSpaceRealm.Uns,
Source: OpcUaPublishActor.ScriptedSource));
// Publish the transition to the cluster `alerts` topic — the single historization + live
// fan-out path. The mediator was cached on the ACTOR thread in PreStart; we only Tell it here.
@@ -0,0 +1,229 @@
using System.Text.Json;
using Akka.Actor;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.OpcUa;
/// <summary>
/// A1 (plan §5.1 F2/G3): <see cref="OpcUaPublishActor.MarkConditionsKnown"/> is an alarm message. Live it applies in
/// arrival order; while a plan is in flight it is deferred beside the alarm states and replayed AFTER them — and a
/// source that lost a deferred projection (overflow or out-of-scope skip) has its deferred marks discarded.
/// </summary>
[Trait("Feature", "GrpcData")]
[Trait("Phase", "A1")]
[Trait("Category", "Unit")]
public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase
{
private static readonly TimeSpan PlanBudget = TimeSpan.FromSeconds(30);
private const string Src = OpcUaPublishActor.ScriptedSource;
private static readonly AlarmConditionSnapshot Active =
new(Active: true, Acknowledged: false, Confirmed: true, Enabled: true, AlarmShelvingKind.Unshelved, 500, "high");
[Fact]
public void Live_a_mark_applies_after_the_alarm_state_sent_before_it()
{
var sink = new OrderSink("al-1");
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), new OpcUaPublishActor.TestHooks()));
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns));
AwaitAssert(() => sink.IsKnown("al-1").ShouldBeTrue(), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.Log.ShouldBe(["alarm:al-1:True", "known:al-1"]);
}
/// <summary>T2 (iv) at the publish actor: the apply is artificially delayed (the plan is held open); the alarm and
/// the mark both arrive during it; on replay the mark still lands after the Active projection.</summary>
[Fact]
public void During_a_plan_the_deferred_mark_replays_after_the_deferred_alarm()
{
var sink = new OrderSink();
using var gate = new ManualResetEventSlim(false);
var actor = Spawn(sink, gate);
actor.Tell(Rebuild());
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns));
AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.IsKnown("al-1").ShouldBeFalse(); // the condition does not exist yet
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.IsKnown("al-1").ShouldBeTrue();
sink.Log.IndexOf("known:al-1").ShouldBeGreaterThan(sink.Log.IndexOf("alarm:al-1:True"));
}
/// <summary>T2 (x) G3 — overflow: the deferred alarm does not fit, so the same source's deferred mark is discarded
/// and the condition stays unknown until the next signal.</summary>
[Fact]
public void A_deferred_alarm_overflow_discards_the_sources_deferred_mark()
{
var sink = new OrderSink();
using var gate = new ManualResetEventSlim(false);
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
new OpcUaPublishActor.TestHooks { BeforePlan = () => gate.Wait() }, deferredWriteCapacity: 1));
actor.Tell(Rebuild());
// Fill the one-key buffer, so the alarm state is dropped.
actor.Tell(new OpcUaPublishActor.AttributeValueBatchUpdate([new ValueWrite("Plant/x", 1, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw)]));
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns));
AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.ConditionExists("al-1").ShouldBeTrue();
sink.IsKnown("al-1").ShouldBeFalse("never known over a projection that did not land");
// The next signal (after its projection) makes it known.
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns));
AwaitAssert(() => sink.IsKnown("al-1").ShouldBeTrue(), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>T2 (x) G3 — out-of-scope skip: a deferred projection of the source is skipped on replay (its condition is
/// not in the applied scope), so the source's mark is discarded even for a condition that does exist.</summary>
[Fact]
public void An_out_of_scope_skip_discards_the_sources_deferred_mark_but_not_another_sources()
{
var sink = new OrderSink();
using var gate = new ManualResetEventSlim(false);
var actor = Spawn(sink, gate);
actor.Tell(Rebuild());
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-ghost", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns));
AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-ghost"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.Marks.ShouldBe(["drv-1"]); // the scripted source's mark was discarded; the unrelated source's applied
}
[Fact]
public void A_withdrawal_reaches_MarkConditionsUnknown()
{
var sink = new OrderSink("al-1");
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), new OpcUaPublishActor.TestHooks()));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns));
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns, Known: false));
AwaitAssert(() => sink.Log.ShouldBe(["known:al-1", "unknown:al-1"]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
}
private IActorRef Spawn(OrderSink sink, ManualResetEventSlim gate) =>
Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
new OpcUaPublishActor.TestHooks { BeforePlan = () => gate.Wait() }));
private static OpcUaPublishActor.RebuildAddressSpace Rebuild() =>
new(CorrelationId.NewId(), DeploymentId.NewId(), ScriptedAlarmArtifact(), ReportOutcome: true);
private static byte[] ScriptedAlarmArtifact() =>
JsonSerializer.SerializeToUtf8Bytes(new
{
UnsAreas = new[] { new { UnsAreaId = "area-1", ClusterId = "c1", Name = "Area" } },
UnsLines = new[] { new { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "Line" } },
Equipment = new[] { new { EquipmentId = "eq-1", DriverInstanceId = (string?)null, UnsLineId = "line-1", Name = "Eq", MachineCode = "EQ-1" } },
RawFolders = Array.Empty<object>(),
DriverInstances = Array.Empty<object>(),
Devices = Array.Empty<object>(),
TagGroups = Array.Empty<object>(),
Tags = Array.Empty<object>(),
ScriptedAlarms = new[]
{
new
{
ScriptedAlarmId = "al-1", EquipmentId = "eq-1", Name = "High", AlarmType = "AlarmCondition",
Severity = 500, MessageTemplate = "high", PredicateScriptId = "s-1", HistorizeToAveva = false,
Retain = true, Enabled = true,
},
},
Scripts = new[] { new { ScriptId = "s-1", SourceCode = "return false;" } },
});
/// <summary>Records the order alarm states and marks land in; like the node manager, both are no-ops for a
/// condition that does not exist.</summary>
private sealed class OrderSink : IOpcUaAddressSpaceSink
{
private readonly object _gate = new();
private readonly HashSet<string> _conditions = new();
private readonly HashSet<string> _known = new();
private readonly List<string> _log = new();
private readonly List<string> _skipped = new();
private readonly List<string> _marks = new();
public OrderSink(params string[] existing) => _conditions.UnionWith(existing);
public List<string> Log { get { lock (_gate) return [.. _log]; } }
public List<string> Skipped { get { lock (_gate) return [.. _skipped]; } }
public List<string> Marks { get { lock (_gate) return [.. _marks]; } }
public bool IsKnown(string id) { lock (_gate) return _known.Contains(id); }
public bool ConditionExists(string id) { lock (_gate) return _conditions.Contains(id); }
public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime ts, AddressSpaceRealm realm)
{
lock (_gate)
{
if (!_conditions.Contains(alarmNodeId)) { _skipped.Add("alarm:" + alarmNodeId); return; }
_log.Add($"alarm:{alarmNodeId}:{state.Active}");
_known.Add(alarmNodeId);
}
}
public void MarkConditionsKnown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
{
lock (_gate)
{
foreach (var id in conditionIds.Where(_conditions.Contains))
{
_log.Add("known:" + id);
_marks.Add(source);
_known.Add(id);
}
}
}
public void MarkConditionsUnknown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
{
lock (_gate)
{
foreach (var id in conditionIds.Where(_conditions.Contains))
{
_log.Add("unknown:" + id);
_known.Remove(id);
}
}
}
public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false)
{
lock (_gate) _conditions.Add(alarmNodeId);
}
public void RebuildAddressSpace()
{
lock (_gate) { _conditions.Clear(); _known.Clear(); }
}
public void WriteValue(string nodeId, object? value, uint statusCode, DateTime ts, AddressSpaceRealm realm) { }
public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime ts, AddressSpaceRealm realm) { }
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm) { }
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) { }
public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) { }
public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { }
public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { }
}
}