fix(grpc-data): A1 review S2 + F5 re-arm + nits — native known is withdrawn on comms loss

- The Bad connectivity edge (and a Good edge with no Bad edge since the last Good one, or from a new child
  incarnation) sends MarkConditionsKnown(Known: false) for the driver's condition nodes, ahead of the quality
  annotation, so an alarm raised during an outage never reads known-inactive, Good after the reconnect. Stopping a
  child (a respawn) withdraws too.
- DriverInstanceActor stamps a connection epoch (bumped on every Connected entry) on the initial-state signal and
  on ConnectivityChanged(Connected); a signal raised under an earlier connection is dropped by the child and the host.
- G3 never discards a deferred withdrawal.
- F5 'still unknown' follows the node manager: a native transition takes its ref out of Pending.
- Re-arm F5 at the alarm-ref reindex for refs a deploy adds while connected (defensive: today such a deploy
  respawns the driver because its RawTags are folded into its config).
- Nits: signals/edges from a retired or non-current child never (re)create a tracker; the injected clock replaces
  DateTime.UtcNow.
- Primary demote/re-promote: checked, not a stale-known window — drivers and their condition writes run ungated on
  both pair members.
This commit is contained in:
Joseph Doherty
2026-11-24 10:37:02 -05:00
parent 6ba5185f10
commit f08ca7d9e3
7 changed files with 337 additions and 40 deletions
@@ -20,12 +20,16 @@ public sealed partial class DriverHostActor
private sealed record ConditionSignalTimedOut(string DriverInstanceId, long Epoch);
private sealed record ConditionBackstopElapsed(string DriverInstanceId, long Epoch);
/// <summary>Per driver instance: the current connectivity epoch, when its quality went Good, the conditions not
/// yet signalled since then, and the conditions the driver reported unsignalable.</summary>
/// <summary>Per driver instance: the current connectivity epoch, the child that sent the last edge, its connection
/// epoch at the last Good edge, when its quality went Good, when the current F5 window started, the conditions not
/// yet established since then, and the conditions the driver reported unsignalable.</summary>
private sealed class ConditionSignalTracker
{
public long Epoch;
public IActorRef? Owner;
public long? ConnectionEpoch;
public DateTime? GoodSinceUtc;
public DateTime? PendingSinceUtc;
public readonly HashSet<string> Pending = new(StringComparer.Ordinal);
public readonly HashSet<string> Unsignalable = new(StringComparer.Ordinal);
public bool DiagnosticRaised;
@@ -37,6 +41,9 @@ public sealed partial class DriverHostActor
private static string SignalTimeoutKey(string driverInstanceId) => "cond-signal-timeout:" + driverInstanceId;
private static string BackstopKey(string driverInstanceId) => "cond-backstop:" + driverInstanceId;
/// <summary>The injected clock (review nit: never <see cref="DateTime.UtcNow"/> here).</summary>
private DateTime ConditionClockUtc => _writeClock.GetUtcNow().UtcDateTime;
private void ReceiveConditionSignals()
{
Receive<DriverInstanceActor.AlarmInitialStatePublished>(OnAlarmInitialState);
@@ -62,35 +69,117 @@ public sealed partial class DriverHostActor
private string? DriverTypeOf(string driverInstanceId) =>
_children.TryGetValue(driverInstanceId, out var child) ? child.DriverType : null;
/// <summary>A connectivity edge restarts the F5 window (from quality Good) and the backstop; a Bad edge cancels both.</summary>
private void OnConditionSignalConnectivity(string driverInstanceId, bool connected)
/// <summary>Whether <paramref name="sender"/> is the CURRENT child for <paramref name="driverInstanceId"/> — not a
/// stopped (retired) incarnation whose late message must not recreate a tracker after
/// <see cref="ForgetConditionSignals"/>, nor anything else.</summary>
private bool IsCurrentChild(string driverInstanceId, IActorRef sender) =>
!_retiredChildren.Contains(sender)
&& _children.TryGetValue(driverInstanceId, out var child) && Equals(child.Actor, sender);
/// <summary>
/// A connectivity edge restarts the F5 window (from quality Good) and the backstop; a Bad edge cancels both.
/// Review S2: the Bad edge withdraws "known" from the driver's conditions — the source can no longer vouch for
/// their state, and an alarm raised during the outage would otherwise read known-inactive, Good after the
/// reconnect until the replay. A Good edge withdraws too (ahead of the Good quality annotation) when no Bad edge
/// was seen since the previous Good one, or it comes from a new child incarnation. They become known again only
/// on the reconnected source's next signal (or transition).
/// </summary>
private void OnConditionSignalConnectivity(string driverInstanceId, bool connected, IActorRef sender, long? connectionEpoch)
{
if (!IsCurrentChild(driverInstanceId, sender))
{
// A stopped incarnation (or a stray sender): never recreate or reset the tracker. Its Bad edge still
// withdraws known unless the CURRENT child of the same id is connected (its state is the live one).
var currentConnected = _conditionSignalTrackers.TryGetValue(driverInstanceId, out var live) && live.GoodSinceUtc is not null
&& _children.TryGetValue(driverInstanceId, out var current) && Equals(live.Owner, current.Actor);
if (!connected && !currentConnected) WithdrawDriverConditionsKnown(driverInstanceId);
return;
}
var t = Tracker(driverInstanceId);
// A Good edge with no Bad edge since the previous Good one (or from a new incarnation) — withdraw here instead.
var missedBadEdge = connected && (t.GoodSinceUtc is not null || (t.Owner is not null && !Equals(t.Owner, sender)));
t.Owner = sender;
t.Epoch++;
Timers.Cancel(SignalTimeoutKey(driverInstanceId));
Timers.Cancel(BackstopKey(driverInstanceId));
t.Pending.Clear();
t.PendingSinceUtc = null;
if (!connected || missedBadEdge) WithdrawDriverConditionsKnown(driverInstanceId);
if (!connected)
{
t.GoodSinceUtc = null;
t.ConnectionEpoch = null;
return;
}
t.GoodSinceUtc = DateTime.UtcNow;
t.GoodSinceUtc = ConditionClockUtc;
t.ConnectionEpoch = connectionEpoch;
if (_alarmRefsByDriver.TryGetValue(driverInstanceId, out var refs))
foreach (var (rawPath, _) in refs) t.Pending.Add(rawPath);
if (t.Pending.Count > 0 && DriverTypeOf(driverInstanceId) is { } type)
{
Timers.StartSingleTimer(SignalTimeoutKey(driverInstanceId), new ConditionSignalTimedOut(driverInstanceId, t.Epoch),
_conditionSignals.SignalTimeoutFor(type));
}
ArmSignalTimeout(driverInstanceId, t);
if (t.Unsignalable.Count > 0) ScheduleBackstop(driverInstanceId, t);
}
/// <summary>(Re)start the F5 window for the tracker's pending conditions, from now.</summary>
private void ArmSignalTimeout(string driverInstanceId, ConditionSignalTracker t)
{
if (t.Pending.Count == 0 || DriverTypeOf(driverInstanceId) is not { } type) return;
t.PendingSinceUtc = ConditionClockUtc;
Timers.StartSingleTimer(SignalTimeoutKey(driverInstanceId), new ConditionSignalTimedOut(driverInstanceId, t.Epoch),
_conditionSignals.SignalTimeoutFor(type));
}
/// <summary>
/// Open-question answer (re-arm F5): after a deploy re-indexed the alarm refs, a CONNECTED driver's newly added
/// refs join <c>Pending</c> and the F5 window restarts now; refs the deploy removed leave it. (Today a deploy that
/// adds alarm refs also changes the driver's config — its RawTags are folded in — so the driver is respawned and
/// the new incarnation's Good edge re-arms F5 anyway; this covers an in-place deploy.)
/// </summary>
/// <param name="previousRefs">Each driver's alarm RawPaths before the reindex.</param>
private void RearmConditionSignalsAfterReindex(IReadOnlyDictionary<string, HashSet<string>> previousRefs)
{
foreach (var (driverInstanceId, t) in _conditionSignalTrackers)
{
if (t.GoodSinceUtc is null) continue; // armed on the next Good edge
var current = _alarmRefsByDriver.TryGetValue(driverInstanceId, out var refs)
? refs.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal)
: new HashSet<string>(StringComparer.Ordinal);
previousRefs.TryGetValue(driverInstanceId, out var before);
var added = current.Where(r => before is null || !before.Contains(r)).ToList();
t.Pending.IntersectWith(current);
t.Unsignalable.IntersectWith(current);
if (added.Count > 0)
{
t.Pending.UnionWith(added);
ArmSignalTimeout(driverInstanceId, t);
}
else if (t.Pending.Count == 0)
{
ClearPendingWindow(driverInstanceId, t);
}
}
}
private void OnAlarmInitialState(DriverInstanceActor.AlarmInitialStatePublished msg)
{
if (!IsCurrentChild(msg.DriverInstanceId, Sender))
{
_log.Debug("DriverHost {Node}: dropping an initial alarm-state signal for {Id} from a sender that is not its current child",
_localNode, msg.DriverInstanceId);
return;
}
var t = Tracker(msg.DriverInstanceId);
// Review S2: a signal from an earlier connection (queued across a Connected→Reconnecting→Connected bounce)
// covers state the reconnect withdrew; it must not mark anything known.
if (msg.ConnectionEpoch is { } epoch && t.ConnectionEpoch != epoch)
{
_log.Debug("DriverHost {Node}: dropping a stale initial alarm-state signal from {Id} (connection {Epoch}, current {Current})",
_localNode, msg.DriverInstanceId, epoch, t.ConnectionEpoch);
return;
}
if (msg.Args.Unsignalable)
{
// InitialStateUnsignalable: no real signal will come. Only a driver type with a backstop (OpcUaClient) marks
@@ -101,23 +190,61 @@ public sealed partial class DriverHostActor
}
var marked = MarkDriverConditionsKnown(msg.DriverInstanceId, msg.Args.ConditionIds);
t.Pending.ExceptWith(msg.Args.ConditionIds);
t.Unsignalable.ExceptWith(msg.Args.ConditionIds);
if (t.Pending.Count == 0)
NoteConditionsEstablished(msg.DriverInstanceId, t, msg.Args.ConditionIds);
_log.Debug("DriverHost {Node}: driver {Driver} established {Count} condition(s) ({Marked} routed)",
_localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, marked);
}
/// <summary>
/// Keep F5's "still unknown" set consistent with the node manager: a condition leaves <c>Pending</c> when the
/// node manager marks it known — on its driver's signal, and on a native transition (a native projection is an
/// established state there). An emptied set ends the F5 window and clears the diagnostic.
/// </summary>
private void NoteConditionsEstablished(string driverInstanceId, ConditionSignalTracker t, IEnumerable<string> rawPaths)
{
if (t.Pending.Count == 0) return;
t.Pending.ExceptWith(rawPaths);
if (t.Pending.Count == 0) ClearPendingWindow(driverInstanceId, t);
}
/// <summary>A forwarded native transition established <paramref name="rawPath"/> (see <see cref="NoteConditionsEstablished"/>).</summary>
private void NoteNativeTransitionEstablished(string driverInstanceId, string rawPath)
{
if (_conditionSignalTrackers.TryGetValue(driverInstanceId, out var t) && t.GoodSinceUtc is not null)
NoteConditionsEstablished(driverInstanceId, t, [rawPath]);
}
private void ClearPendingWindow(string driverInstanceId, ConditionSignalTracker t)
{
Timers.Cancel(SignalTimeoutKey(driverInstanceId));
t.PendingSinceUtc = null;
// F5: a late signal clears the "not signalled" diagnostic.
if (!t.DiagnosticRaised) return;
t.DiagnosticRaised = false;
_conditionSignals.Hub?.ClearUnsignalled(driverInstanceId);
_log.Info("DriverHost {Node}: driver {Driver} signalled its initial alarm state late — diagnostic cleared",
_localNode, driverInstanceId);
}
/// <summary>Review S2: withdraw "known" from every condition node of <paramref name="driverInstanceId"/> (one
/// <see cref="PublishActor.MarkConditionsKnown"/> with <c>Known: false</c> per realm), on the same chain as its
/// alarm projections and quality annotations.</summary>
private void WithdrawDriverConditionsKnown(string driverInstanceId)
{
if (_opcUaPublishActor is null || !_alarmRefsByDriver.TryGetValue(driverInstanceId, out var refs)) return;
var byRealm = new Dictionary<AddressSpaceRealm, List<string>>();
foreach (var (_, nodes) in refs)
{
Timers.Cancel(SignalTimeoutKey(msg.DriverInstanceId));
// F5: a late signal clears the "not signalled" diagnostic.
if (t.DiagnosticRaised)
foreach (var n in nodes)
{
t.DiagnosticRaised = false;
_conditionSignals.Hub?.ClearUnsignalled(msg.DriverInstanceId);
_log.Info("DriverHost {Node}: driver {Driver} signalled its initial alarm state late — diagnostic cleared",
_localNode, msg.DriverInstanceId);
if (!byRealm.TryGetValue(n.Realm, out var list)) byRealm[n.Realm] = list = new List<string>();
list.Add(n.NodeId);
}
}
_log.Debug("DriverHost {Node}: driver {Driver} established {Count} condition(s) ({Marked} routed)",
_localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, marked);
foreach (var (realm, ids) in byRealm)
_opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm, Known: false));
}
private void ScheduleBackstop(string driverInstanceId, ConditionSignalTracker t)
@@ -130,7 +257,7 @@ public sealed partial class DriverHostActor
return;
}
var remaining = goodSince + settle - DateTime.UtcNow;
var remaining = goodSince + settle - ConditionClockUtc;
Timers.StartSingleTimer(BackstopKey(driverInstanceId), new ConditionBackstopElapsed(driverInstanceId, t.Epoch),
remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero);
}
@@ -141,9 +268,8 @@ public sealed partial class DriverHostActor
return;
var ids = t.Unsignalable.ToList();
t.Unsignalable.Clear();
t.Pending.ExceptWith(ids);
if (t.Pending.Count == 0) Timers.Cancel(SignalTimeoutKey(msg.DriverInstanceId));
var marked = MarkDriverConditionsKnown(msg.DriverInstanceId, ids);
NoteConditionsEstablished(msg.DriverInstanceId, t, ids);
_log.Info("DriverHost {Node}: backstop settled — {Count} unsignalable condition(s) of {Driver} marked known (residual: an upstream alarm active and never re-transitioned reads inactive)",
_localNode, marked, msg.DriverInstanceId);
}
@@ -153,7 +279,7 @@ public sealed partial class DriverHostActor
if (!_conditionSignalTrackers.TryGetValue(msg.DriverInstanceId, out var t) || t.Epoch != msg.Epoch || t.Pending.Count == 0)
return;
// F5: the conditions STAY unknown (Uncertain on a consumer) — never known-inactive.
var elapsed = t.GoodSinceUtc is { } since ? DateTime.UtcNow - since : TimeSpan.Zero;
var elapsed = (t.PendingSinceUtc ?? t.GoodSinceUtc) is { } since ? ConditionClockUtc - since : TimeSpan.Zero;
t.DiagnosticRaised = true;
if (_conditionSignals.Hub is { } hub) hub.ReportUnsignalled(msg.DriverInstanceId, elapsed, t.Pending.Count);
else OtOpcUaTelemetry.DataConnConditionsUnsignalled.Add(t.Pending.Count,
@@ -2016,7 +2016,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// The mux fan-out is independent of the OPC UA sink — a node with scripted alarms but no
// publish actor (the mux-only test/dev path) must still see comms loss. Done before the early
// return for exactly that reason.
OnConditionSignalConnectivity(msg.DriverInstanceId, msg.Connected);
OnConditionSignalConnectivity(msg.DriverInstanceId, msg.Connected, Sender, msg.ConnectionEpoch);
if (!msg.Connected)
{
if (!_retiredChildren.Contains(Sender) &&
@@ -2340,6 +2340,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_localNode, msg.DriverInstanceId, msg.Args.ConditionId);
}
// A1 review S2: the node manager marks a native condition known on this projection, so F5 stops counting it.
NoteNativeTransitionEstablished(msg.DriverInstanceId, msg.Args.ConditionId);
foreach (var n in nodeIds)
{
var nodeId = n.NodeId;
@@ -4058,6 +4060,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// The per-driver secondary indexes are rebuilt WHOLE alongside their primaries below — same pass,
// same clear — so no incremental maintenance exists to get out of step with them.
_valueRefsByDriver.Clear();
// A1 review (re-arm F5): each driver's alarm refs before this reindex, so a deploy's added refs can be found.
var previousAlarmRefs = _alarmRefsByDriver.ToDictionary(
kv => kv.Key, kv => kv.Value.Select(e => e.RawPath).ToHashSet(StringComparer.Ordinal), StringComparer.Ordinal);
_alarmRefsByDriver.Clear();
foreach (var t in composition.RawTags)
{
@@ -4139,6 +4144,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// so the two stay in step. Keyed by the bare condition NodeId, exactly as ForwardNativeAlarm projects.
_nativeAlarmProjector.RetainOnly(_driverRefByAlarmNodeId.Keys.ToHashSet(StringComparer.Ordinal));
PublishAckPreflight();
RearmConditionSignalsAfterReindex(previousAlarmRefs);
// Cache the per-driver payload as THE authority, in the same clear-and-repopulate pass as the routing
// maps above so a rename/removal can never leave a stale entry behind. Keyed over the UNION of the two
@@ -4680,6 +4686,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_dataWriteRuntime?.BeforeDriverStopForTests?.Invoke(driverInstanceId);
Context.Stop(entry.Actor);
_children.Remove(driverInstanceId);
// A1 review S2: the stopped incarnation can no longer vouch for its conditions (a respawn's carried-over
// known state would otherwise stand until the new incarnation signals). No-op when the deploy removed them.
WithdrawDriverConditionsKnown(driverInstanceId);
ForgetConditionSignals(driverInstanceId);
PublishAckPreflight();
EvictRetainedValues(driverInstanceId);
@@ -108,7 +108,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// annotates this driver's native alarm conditions' source-data Quality from it (comms lost → Bad,
/// restored → Good) — independently of alarm transitions, since a comms-lost driver emits no alarm
/// events. Fire-and-forget.</summary>
public sealed record ConnectivityChanged(string DriverInstanceId, bool Connected, long? ProducerIncarnation = null);
public sealed record ConnectivityChanged(string DriverInstanceId, bool Connected, long? ProducerIncarnation = null,
long? ConnectionEpoch = null);
/// <summary>
/// Sent to the parent from <see cref="PostRestart"/> so the host re-provisions THIS incarnation.
@@ -236,8 +237,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <see cref="IAlarmInitialStateSignal.InitialAlarmStateDelivered"/>. It travels the SAME self-Tell → parent path as
/// <see cref="AttributeAlarmPublished"/>, so it reaches <see cref="DriverHostActor"/> after every alarm event the
/// driver raised before it.</summary>
public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args);
private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args);
/// <remarks>A1 review S2: <paramref name="ConnectionEpoch"/> is the connection (Connected entry) the driver raised
/// it under, matching <see cref="ConnectivityChanged.ConnectionEpoch"/> of that Good edge.</remarks>
public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args,
long? ConnectionEpoch = null);
private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args, long Epoch);
/// <summary>Self-sent on Connected entry / when alarm refs are (re)pushed, to establish the native-alarm
/// subscription that un-gates an <see cref="IAlarmSource"/> driver's feed. Handled async so the
/// <see cref="IAlarmSource.SubscribeAlarmsAsync"/> call is bounded + off the synchronous handlers.</summary>
@@ -505,6 +509,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// A1 (plan §5.1 G5): attached and detached WITH the alarm handler, so the signal obeys exactly the gate
// OnAlarmEvent obeys.
private EventHandler<AlarmInitialStateEventArgs>? _alarmInitialStateHandler;
// A1 review S2: bumped on every Connected entry; read on the driver's thread when it raises its signal.
private long _connectionEpoch;
private EventHandler<RediscoveryEventArgs>? _rediscoveryHandler;
private EventHandler<HostStatusChangedEventArgs>? _hostStatusHandler;
private EventHandler<DriverConnectionLossEventArgs>? _connectionLossHandler;
@@ -898,7 +904,10 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// Announce connectivity to the host so it can clear any comms-lost Quality annotation on this
// driver's native alarm conditions (Bad → Good). Fire-and-forget; the host defaults conditions to a
// non-Good "waiting for initial data" quality at materialise, and this is what confirms them Good.
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: true, ProducerIncarnation: _sourceIncarnation));
// A1 review S2: a new connection epoch — a signal the driver raised under an earlier one is dropped below.
var epoch = Interlocked.Increment(ref _connectionEpoch);
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: true, ProducerIncarnation: _sourceIncarnation,
ConnectionEpoch: epoch));
// Baseline for the comms-loss watchdog. Re-stamped on every Connected entry so a driver that
// reconnects but never manages a read is measured from THIS connect, not from a stale earlier one.
@@ -1000,7 +1009,18 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// project it to the parent the same way DataChangeForward projects AttributeValueBatchPublished.
Receive<NativeAlarmRaised>(m => Context.Parent.Tell(new AttributeAlarmPublished(_driverInstanceId, m.Args)));
// A1 F2: the same mailbox and the same forward, so the signal follows every alarm event raised before it.
Receive<NativeAlarmInitialState>(m => Context.Parent.Tell(new AlarmInitialStatePublished(_driverInstanceId, m.Args)));
// Review S2: a signal raised under an earlier connection (queued across a Connected→Reconnecting→Connected
// bounce, e.g. while an async reconnect held the mailbox) covers events of a feed that no longer exists — drop it.
Receive<NativeAlarmInitialState>(m =>
{
if (m.Epoch != Interlocked.Read(ref _connectionEpoch))
{
_log.Debug("DriverInstance {Id}: initial alarm-state signal from an earlier connection — dropped", _driverInstanceId);
return;
}
Context.Parent.Tell(new AlarmInitialStatePublished(_driverInstanceId, m.Args, m.Epoch));
});
// ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the
// sender, which on the self-resubscribe path is Self. Swallow it (trace only) so it doesn't dead-letter.
Receive<SubscriptionEstablished>(msg =>
@@ -2557,7 +2577,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
src.OnAlarmEvent += _alarmEventHandler;
if (_driver is IAlarmInitialStateSignal signal)
{
_alarmInitialStateHandler = (_, e) => self.Tell(new NativeAlarmInitialState(e));
_alarmInitialStateHandler = (_, e) => self.Tell(new NativeAlarmInitialState(e, Interlocked.Read(ref _connectionEpoch)));
signal.InitialAlarmStateDelivered += _alarmInitialStateHandler;
}
}
@@ -1176,7 +1176,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
var discarded = 0;
foreach (var mark in _deferred.Marks)
{
if (_deferred.SourceLost(mark.Source))
// A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe.
if (mark.Known && _deferred.SourceLost(mark.Source))
{
discarded++;
continue;
@@ -1,7 +1,9 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
@@ -112,4 +114,92 @@ public sealed class NativeAlarmInitialStateSignalTests : NativeAlarmSignalTestBa
rig.Driver.Signal([A, B]).ShouldBeFalse();
AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300));
}
// ---------------------------------------------------------------- review S2 / re-arm F5 / nits
/// <summary>
/// Review S2 — comms loss and a Connected→Reconnecting→Connected bounce: the Bad edge withdraws "known"; the
/// reconnect's Good quality annotation arrives with nothing marked known (an alarm raised during the outage must
/// not read known-inactive, Good); a signal queued under the earlier connection is dropped; the reconnected
/// driver's own signal marks them known again.
/// </summary>
[Fact]
public void Comms_loss_withdraws_known_and_a_signal_from_before_the_bounce_is_dropped()
{
var rig = StartRig(DriverTypeNames.Galaxy, ["hi", "lo"]);
rig.Driver.Signal([A, B]).ShouldBeTrue();
rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct);
var child = ChildOf(rig);
rig.Host.Tell(new ReconnectDriver("c1", DriverId, "test", Guid.NewGuid()), TestActor);
var withdrawal = rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(m => !m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct);
withdrawal.Source.ShouldBe(DriverId);
withdrawal.ConditionIds.ShouldBe([A, B], ignoreOrder: true);
// The child retries the connection on its reconnect interval; until its Good edge nothing is marked known.
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (true)
{
var m = rig.Publish.ReceiveOne(deadline - DateTime.UtcNow, Ct);
m.ShouldNotBeNull("the reconnect's Good quality annotation never arrived");
if (m is OpcUaPublishActor.MarkConditionsKnown { Known: true } mark)
throw new ShouldAssertException($"marked known before the reconnected driver signalled: {string.Join(",", mark.ConditionIds)}");
if (m is OpcUaPublishActor.AlarmQualityUpdate { StatusCode: OpcUaStatus.Good }) break;
}
// A signal raised under the first connection, delivered after the bounce: dropped.
rig.Host.Tell(new DriverInstanceActor.AlarmInitialStatePublished(DriverId, new AlarmInitialStateEventArgs([A, B]), ConnectionEpoch: 1), child);
AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(400));
// Positive control: the reconnected driver's own signal marks them known.
AwaitCondition(() => rig.Driver.Signal([A, B]), TimeSpan.FromSeconds(10), Ct);
rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct)
.ConditionIds.ShouldBe([A, B], ignoreOrder: true);
}
/// <summary>Open question answered — re-arm F5 for refs a deploy adds while the driver is connected. Today every such
/// deploy changes the driver's config (its authored RawTags are folded into it), so the driver is respawned: the
/// stopped incarnation's conditions are withdrawn, and the new incarnation's Good edge puts EVERY ref — the added one
/// included — in the F5 window, so a driver that never signals raises the diagnostic for all of them. (The reindex
/// re-arm covers a future in-place deploy.)</summary>
[Fact]
public void A_deploy_that_adds_alarm_refs_while_connected_covers_them_with_F5()
{
var rig = StartRig(DriverTypeNames.Galaxy, ["hi"], o => o.WithSignalTimeout(DriverTypeNames.Galaxy, TimeSpan.FromMilliseconds(400)));
rig.Driver.Signal([A]).ShouldBeTrue();
rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct);
rig.Hub.Unsignalled.ShouldBeEmpty();
Redeploy(rig, ["hi", "lo"]);
rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(m => !m.Known && m.ConditionIds.Contains(A),
TimeSpan.FromSeconds(5), cancellationToken: Ct);
AwaitCondition(() => rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct);
rig.Hub.Unsignalled[DriverId].Conditions.ShouldBe(2);
AwaitCondition(() => rig.Driver.Signal([A, B]), TimeSpan.FromSeconds(5), Ct);
AwaitCondition(() => !rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct);
}
/// <summary>Review S2 — F5's "still unknown" set follows the node manager: a native transition (which the node
/// manager treats as an established state) takes its condition out of the F5 count.</summary>
[Fact]
public void A_native_transition_leaves_the_F5_pending_set_like_the_node_manager()
{
var rig = StartRig(DriverTypeNames.Galaxy, ["hi", "lo"], o => o.WithSignalTimeout(DriverTypeNames.Galaxy, TimeSpan.FromMilliseconds(600)));
rig.Driver.Raise(A).ShouldBeTrue();
rig.Publish.FishForMessage<OpcUaPublishActor.AlarmStateUpdate>(u => u.AlarmNodeId == A, TimeSpan.FromSeconds(5), cancellationToken: Ct);
AwaitCondition(() => rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct);
rig.Hub.Unsignalled[DriverId].Conditions.ShouldBe(1); // only B is still unknown
}
/// <summary>Review nit — a signal from anything but the current child (a stopped incarnation, a stray sender) is
/// dropped and never (re)creates a tracker.</summary>
[Fact]
public void A_signal_from_a_sender_that_is_not_the_current_child_is_dropped()
{
var rig = StartRig(DriverTypeNames.Galaxy, ["hi"]);
rig.Host.Tell(new DriverInstanceActor.AlarmInitialStatePublished(DriverId, new AlarmInitialStateEventArgs([A])), TestActor);
AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(400));
}
}
@@ -33,6 +33,10 @@ public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase
protected const string DriverId = "drv-sig";
private static readonly NodeId RigNode = NodeId.Parse("a1-signal-rig");
private static readonly RevisionHash Rev = RevisionHash.Parse(new string('c', 64));
private IDbContextFactory<OtOpcUaConfigDbContext>? _rigDb;
private TestProbe? _rigCoordinator;
private string? _rigDriverType;
private int _redeploys;
/// <summary>The RawPath of alarm tag <paramref name="tag"/> under the rig's folder/driver/device.</summary>
/// <param name="tag">The tag name.</param>
@@ -57,13 +61,15 @@ public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase
Func<ConditionSignalOptions, ConditionSignalOptions>? configure = null, FakeSignallingAlarmDriver? driver = null)
{
var db = NewInMemoryDbFactory();
var deploymentId = Seed(db, driverType, alarmTags);
var deploymentId = Seed(db, driverType, alarmTags, Rev);
_rigDb = db;
_rigDriverType = driverType;
driver ??= new FakeSignallingAlarmDriver(DriverId, driverType);
var hub = new ConditionStateHub();
var options = new ConditionSignalOptions { Hub = hub };
options = configure?.Invoke(options) ?? options;
var coordinator = CreateTestProbe();
var coordinator = _rigCoordinator = CreateTestProbe();
var publish = this.CreateCleanOutcomePublishProbe();
var host = Sys.ActorOf(DriverHostActor.Props(
db, RigNode, coordinator.Ref,
@@ -81,8 +87,27 @@ public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase
return new Rig(host, publish, driver, hub);
}
/// <summary>Re-deploys the last started rig with <paramref name="alarmTags"/> (a new revision) and waits for the apply.</summary>
/// <param name="rig">The rig.</param>
/// <param name="alarmTags">The alarm tag names the new revision carries.</param>
protected void Redeploy(Rig rig, IReadOnlyList<string> alarmTags)
{
var rev = RevisionHash.Parse(new string((char)('d' + _redeploys++ % 3), 64));
var deploymentId = Seed(_rigDb!, _rigDriverType!, alarmTags, rev);
rig.Host.Tell(new DispatchDeployment(deploymentId, rev, CorrelationId.NewId()));
_rigCoordinator!.FishForMessage<ApplyAck>(a => a.DeploymentId == deploymentId, TimeSpan.FromSeconds(10),
cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied);
}
/// <summary>The rig's current driver child (the <c>DriverInstanceActor</c> the host spawned).</summary>
/// <param name="rig">The rig.</param>
/// <returns>Its actor ref.</returns>
protected IActorRef ChildOf(Rig rig) =>
Sys.ActorSelection(rig.Host.Path + "/drv-*").ResolveOne(TimeSpan.FromSeconds(5)).GetAwaiter().GetResult();
/// <summary>Negative control: for <paramref name="duration"/>, the probe receives no
/// <see cref="OpcUaPublishActor.MarkConditionsKnown"/> (other traffic — quality annotations — is ignored).</summary>
/// <see cref="OpcUaPublishActor.MarkConditionsKnown"/> that marks known (other traffic — quality annotations,
/// withdrawals — is ignored).</summary>
/// <param name="publish">The probe.</param>
/// <param name="duration">How long to watch.</param>
protected static void AssertNoMark(TestProbe publish, TimeSpan duration)
@@ -91,7 +116,7 @@ public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase
while (DateTime.UtcNow < deadline)
{
var m = publish.ReceiveOne(deadline - DateTime.UtcNow);
if (m is OpcUaPublishActor.MarkConditionsKnown mark)
if (m is OpcUaPublishActor.MarkConditionsKnown { Known: true } mark)
throw new ShouldAssertException($"unexpected MarkConditionsKnown({string.Join(",", mark.ConditionIds)})");
}
}
@@ -118,7 +143,8 @@ public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase
throw new ShouldAssertException($"stop condition not met; saw {seen.Count} alarm message(s)");
}
private static DeploymentId Seed(IDbContextFactory<OtOpcUaConfigDbContext> db, string driverType, IReadOnlyList<string> alarmTags)
private static DeploymentId Seed(IDbContextFactory<OtOpcUaConfigDbContext> db, string driverType, IReadOnlyList<string> alarmTags,
RevisionHash rev)
{
var artifact = JsonSerializer.SerializeToUtf8Bytes(new
{
@@ -140,7 +166,7 @@ public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase
using var ctx = db.CreateDbContext();
ctx.Deployments.Add(new Deployment
{
DeploymentId = id.Value, RevisionHash = Rev.Value, Status = DeploymentStatus.Sealed, CreatedBy = "test",
DeploymentId = id.Value, RevisionHash = rev.Value, Status = DeploymentStatus.Sealed, CreatedBy = "test",
SealedAtUtc = DateTime.UtcNow, ArtifactBlob = artifact,
});
ctx.SaveChanges();
@@ -123,6 +123,31 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase
AwaitAssert(() => sink.Log.ShouldBe(["known:al-1", "unknown:al-1"]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>Review S2: a deferred WITHDRAWAL (<c>Known: false</c>) is never discarded by G3 — it only makes conditions
/// unknown, which is always safe — so it replays after the plan even for a source that lost a deferred projection.</summary>
[Fact]
public void A_deferred_withdrawal_is_replayed_even_for_a_source_that_lost_a_projection()
{
var sink = new OrderSink("al-1");
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());
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, Known: false));
// Applied live (to the pre-plan node) as well as deferred.
AwaitAssert(() => sink.Log.ShouldContain("unknown:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
var unknownBeforeReplay = sink.Log.Count(l => l == "unknown:al-1");
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(unknownBeforeReplay + 1), PlanBudget,
cancellationToken: TestContext.Current.CancellationToken);
}
private IActorRef Spawn(OrderSink sink, ManualResetEventSlim gate) =>
Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),