Merge #1112 (owner decision: brief Bad on restart): on a driver config-change respawn or operator Restart the raw + UNS value nodes go BadWaitingForInitialData until the new driver's first value; the retired child's late disconnect no longer stamps/latches value nodes while a replacement exists

This commit is contained in:
Joseph Doherty
2026-12-05 00:49:27 -05:00
6 changed files with 521 additions and 41 deletions
+8 -2
View File
@@ -146,8 +146,14 @@ non-`Healthy` state **and** its `LastSuccessfulRead` has been frozen for 90 s. T
edge still covers the gap. `DriverHostStaleConnectivityTests`. ⚠️ So that Bad edge can NOT be what tells
**mux dependents** (VTs, scripted alarms, Calculation) the old object ended — it raced the replacement and was
dropped, leaving them on the stopped object's last Good (#1109). The host itself fans `BadNoCommunication` to the
mux at the stop (`TellDependentsDriverObjectEnded`, before `SourceRemoved`); value nodes keep the #1070 rule.
`DriverHostRespawnDependentGapTests`.
mux at the stop (`TellDependentsDriverObjectEnded`, before `SourceRemoved`). `DriverHostRespawnDependentGapTests`.
- ⚠️ **Contract (#1112, owner decision "Brief Bad on restart"): on a driver-object change, dependents and OPC UA
nodes go non-Good until the new driver's first value.** A config-change respawn (`StopChild(respawning: true)`) or
an operator Restart stamps `BadWaitingForInitialData` on raw + every UNS mirror at the stop
(`StampValueNodesAwaitingNewDriver`, host→publish pair ⇒ ordered before the new Good). NOT latched (a respawn is not
an outage: no audit, no counter), and the retired child's late Bad no longer stamps value nodes while a replacement
exists — so a Restart now cancels the old audit itself (#1053 keeps the latch). Supervision restarts and deploy
removals/disables are unchanged. ScadaBridge sees the brief Bad. `DriverHostRespawnValueNodeGapTests`.
- **Every dedup on the recovery path is keyed on (value, status), not value.** A device that comes back
usually comes back holding the same reading, so a value-only dedup swallows the recovery and the node
stays Bad forever — the v3-gate trap, now closed in the Calculation driver, the virtual-tag actor and
+25 -6
View File
@@ -398,6 +398,7 @@ a fifth (archreview round 3, theme "the stale-Good family"). The seams that impl
| Calculation driver | holds on Bad, propagates the worst input status | [`docs/drivers/Calculation.md`](drivers/Calculation.md#input-quality) |
| Virtual tags | holds on Bad, inherits the worst input status, reassert carries it | [`docs/ScriptEditor.md`](ScriptEditor.md#input-quality-what-a-script-sees-and-when-it-runs-at-all) |
| Scripted alarms | worst-of-input quality annotated out of band; Bad inputs hold the condition | [`docs/ScriptedAlarms.md`](ScriptedAlarms.md) |
| Driver **object replaced** — config-change respawn / operator Restart (#1109, #1112) | **On a driver-object change, dependents and OPC UA nodes go non-Good until the new driver's first value.** At the stop the host fans `BadNoCommunication` to the mux (`TellDependentsDriverObjectEnded`) and stamps `BadWaitingForInitialData` on the raw NodeIds and every referencing UNS NodeId (`StampValueNodesAwaitingNewDriver`, status-only, **not latched** — no recovery audit, no `comms_latched_refs`, no driver status). Not on a supervision restart (same object) nor a deploy removal / disable (row below) | `DriverHostActor.StopChild(respawning: true)` / `HandleRestartDriver` |
| Input **removed** by a deploy (#979) | a raw value ref that leaves the composition (tag deleted/renamed, driver removed) or a VirtualTag output that leaves the deployed set reaches every dependent still naming it (VirtualTags, the Calculation adapter, the scripted-alarm upstream — replay-opting mux subscribers only; the historization recorder is not told) as `BadWaitingForInitialData` — the status it reads after a restart with the same config. Late bursts for a removed ref are withheld from the mux until the next apply | `DriverHostActor.ApplyDesiredSubscriptions` → `DependencyMuxActor.ValueRefsRemoved` / `VirtualTagOutputsRemoved` |
⚠️ **Consumer-visible:** value nodes of a comms-lost driver now go **Bad**, where they used to serve
@@ -600,8 +601,9 @@ holds the id in the `ChildHealthLedger` (`Forget` then `Readmit` on the next spa
publish cannot resurrect its diagnostics entry.
An operator **Restart** deliberately KEEPS the latch (#1053): the nodes stay in the address space, still Bad, and the
respawned incarnation is what must re-publish them. The stopped incarnation's `PostStop` comms-loss announcement re-latches
the current ref set and cancels the audit the old incarnation armed; the new incarnation's `Connected` re-arms it.
respawned incarnation is what must re-publish them. `HandleRestartDriver` keeps the latch and cancels the audit the old
incarnation armed; the new incarnation's `Connected` re-arms it. (Before #1112 that cancel rode the stopped incarnation's
`PostStop` comms-loss announcement re-latching — which also latched a Restart of a perfectly healthy driver.)
⚠️ **A stopped incarnation's connectivity can arrive late, and is then dropped (#1070).** `Context.Stop` is asynchronous and
messages from two children are not ordered, so the old child's `PostStop` `ConnectivityChanged(false)` can reach the host
@@ -610,8 +612,9 @@ running returns (a synchronous driver call such as a health publish). Applied th
`BadNoCommunication` with nothing left to re-publish them, re-latched them and cancelled the new incarnation's audit: nodes
stuck Bad with the tripwire disarmed. `DriverHostActor.IsStaleRetiredConnectivity` now drops, whole, any `Connected=true` from a
retired child and its `Connected=false` once the current child of the same id has announced Connected (`ChildEntry.Connected`).
A retired child's Bad edge is still applied while the replacement has not connected (or there is none) — that is the gap
cover above. Same rule the condition-signal tracker already applied. Pinned by `DriverHostStaleConnectivityTests` (the race
Before that, a retired child's Bad edge still annotates conditions and the mux, but since #1112 it stamps **value nodes**
only when there is no replacement (the host already stamped them at the stop — below — and a comms-loss stamp would latch
them for the audit). Same rule the condition-signal tracker already applied. Pinned by `DriverHostStaleConnectivityTests` (the race
made deterministic by wedging the old child in `GetHostStatuses`).
⚠️ **…so mux dependents are told by the HOST, not by that edge (#1109).** #1041 relied on the old child's `PostStop` Bad to
@@ -620,8 +623,24 @@ publishes. With the rule above that edge is dropped whenever the replacement con
from the stopped object's last Good — indefinitely for an on-change source that does not republish an unchanged value (the
#1109 flake: 15 of 30 stressed runs). `StopChild` and an operator Restart now fan `BadNoCommunication` for the driver's value
refs to the mux themselves (`TellDependentsDriverObjectEnded`), on the host→mux pair the new incarnation's values travel and
before `SourceRemoved`, so it is ordered ahead of the new driver's first value and is never retained. Value nodes are
unchanged (they keep the #1070 rule). Pinned by `DriverHostRespawnDependentGapTests` (same wedge).
before `SourceRemoved`, so it is ordered ahead of the new driver's first value and is never retained. Pinned by
`DriverHostRespawnDependentGapTests` (same wedge).
⚠️ **…and so are the OPC UA value nodes (#1112, owner decision "Brief Bad on restart").** The contract: **on a driver-object
change (config-change respawn, operator Restart), dependents and OPC UA nodes go non-Good until the new driver's first
value.** `StopChild(respawning: true)` (an id the planner both stops and spawns) and `HandleRestartDriver` stamp
`BadWaitingForInitialData` — what a freshly materialised node shows — on the driver's raw NodeIds **and every referencing
UNS NodeId**, status-only (value kept server-side; clients see null + the Bad status), before the replacement is spawned,
on the host→publish-actor pair the replacement's values travel — so the new Good always lands after it, and the stopped
child cannot overwrite it (its bursts are dropped once retired; its late Bad stamps no value nodes while a replacement
exists). It is **not a comms loss**: nothing is latched, no recovery audit / `otopcua.driver.comms_latched_refs`, no driver
status published, native condition state and quality untouched by it (the old child's own `PostStop` edge still annotates
conditions as before). Historization is unchanged: it records what the mux sees, i.e. #1109's `BadNoCommunication` outage
marker; the node stamp is an address-space write only. A write in flight loses revert ownership exactly as under the
comms-loss stamp (the status write invalidates it), so its later failure cannot revert over the stamp. **Not** done on a
supervision restart (same driver object — unchanged, still covered by that child's own connectivity) nor a deploy removal /
disable (`RemovedInputStatus` + node removal). ScadaBridge sees a brief Bad per respawn/Restart — accepted.
Pinned by `DriverHostRespawnValueNodeGapTests` (both seams, both interleavings, no-latch with a positive control).
### The connect path feeds the circuit breaker (R2-10 T10 closure)
@@ -2030,9 +2030,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
private void ForwardBatchToMux(DriverInstanceActor.AttributeValueBatchPublished msg)
{
// A burst from an incarnation this host already stopped: forwarding it would undo the SourceRemoved
// eviction (see _retiredChildren). Its ConnectivityChanged is filtered only once the replacement has
// connected (#1070, IsStaleRetiredConnectivity) — until then the respawn path relies on that Bad fan to
// cover the gap.
// eviction (see _retiredChildren). The respawn gap is covered by the host's own stop-time stamps (#1109 mux,
// #1112 value nodes), not by this child's late ConnectivityChanged (#1070, IsStaleRetiredConnectivity).
if (_retiredChildren.Contains(Sender))
{
_log.Debug("DriverHost {Node}: dropped a {Count}-item value burst from a stopped incarnation of {Id}",
@@ -2174,8 +2173,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
(msg.ProducerIncarnation is null || _sourcePublisher?.IsDriverIncarnationActive(msg.DriverInstanceId, msg.ProducerIncarnation.Value) == true))
_sourcePublisher?.PublishDriverStatus(msg.DriverInstanceId, OpcUaStatus.BadNoCommunication);
FanCommsLossToDependencyMux(msg.DriverInstanceId);
// And the EXTERNAL data plane, which the dependency-mux fan-out stopped one seam short of.
FanCommsLossToValueNodes(msg.DriverInstanceId);
// And the EXTERNAL data plane, which the dependency-mux fan-out stopped one seam short of — except for a
// stopped incarnation that has a replacement (#1112): the host stamped those nodes awaiting-first-value at
// the stop, and this late edge would turn that into a comms-loss latch (and a recovery audit) for what is
// not an outage.
if (!(_retiredChildren.Contains(Sender) && _children.ContainsKey(msg.DriverInstanceId)))
FanCommsLossToValueNodes(msg.DriverInstanceId);
}
else
{
@@ -2231,10 +2234,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// Stale, and dropped whole: any <c>Connected=true</c> from a retired child (it vouches for a connection
/// that has been torn down — applied, it would arm an audit and annotate conditions Good for a driver
/// that may not be connected yet), and its <c>Connected=false</c> once the current child of the same id
/// has announced it is connected. A retired child's Bad edge is still APPLIED while the replacement has
/// not connected (or there is none): that is the 03/S15 gap cover an operator Restart and a respawn rely
/// on, and the replacement's own push clears it. Same rule the condition-signal tracker already applies
/// (<c>OnConditionSignalConnectivity</c>). A sender that was never a child of this host is not filtered.
/// has announced it is connected. Before that a retired child's Bad edge still annotates conditions and
/// the mux; its VALUE-NODE stamp is skipped whenever a replacement exists (#1112 — the host already
/// stamped those nodes <c>BadWaitingForInitialData</c> at the stop, and a comms-loss stamp would latch
/// them for the recovery audit), and applied only when there is none. Same rule the condition-signal
/// tracker already applies (<c>OnConditionSignalConnectivity</c>). A sender that was never a child of
/// this host is not filtered.
/// </para>
/// </remarks>
/// <param name="msg">The connectivity announcement; <c>Sender</c> is its producer.</param>
@@ -4006,7 +4011,14 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
StringComparer.Ordinal);
var plan = DriverSpawnPlanner.Compute(snapshots, specs);
foreach (var id in plan.ToStop) StopChild(id);
// #1112: an id both stopped and spawned is a config-change RESPAWN (a new driver object for the same tags), so
// its value nodes are stamped awaiting-first-value at the stop. A stop with no spawn is a removal / disable,
// which keeps its own path (the apply's RemovedInputStatus / node removal).
HashSet<string>? respawning = null;
foreach (var spec in plan.ToSpawn)
if (plan.ToStop.Contains(spec.DriverInstanceId))
(respawning ??= new HashSet<string>(StringComparer.Ordinal)).Add(spec.DriverInstanceId);
foreach (var id in plan.ToStop) StopChild(id, respawning?.Contains(id) == true);
foreach (var spec in plan.ToSpawn) SpawnChild(spec, deferSubscriptions: _sourcePublisher is not null);
// v3: a dependency-consumer driver's declared dependency refs change when its tags/scripts are
@@ -5131,7 +5143,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
if (incarnation is not null) routes!.RetireDriver(driverInstanceId, incarnation);
}
private void StopChild(string driverInstanceId)
/// <summary>Stops a driver child that left the plan or is about to be respawned with a new config.</summary>
/// <param name="driverInstanceId">The driver instance to stop.</param>
/// <param name="respawning"><see langword="true"/> when the same apply spawns a replacement (a config-change
/// respawn): the driver's value nodes are then stamped <see cref="OpcUaStatus.BadWaitingForInitialData"/> until the
/// new driver object's first value (#1112, <see cref="StampValueNodesAwaitingNewDriver"/>).</param>
private void StopChild(string driverInstanceId, bool respawning = false)
{
if (!_children.TryGetValue(driverInstanceId, out var entry)) return;
StopDependencyAdapter(driverInstanceId);
@@ -5148,6 +5165,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
ForgetConditionSignals(driverInstanceId);
PublishAckPreflight();
TellDependentsDriverObjectEnded(driverInstanceId);
if (respawning) StampValueNodesAwaitingNewDriver(driverInstanceId);
EvictRetainedValues(driverInstanceId);
// The instance left the plan (StopChild is only reached via plan.ToStop), so its cached
// Health/Resilience snapshots must not replay to new telemetry subscribers. Release the shared
@@ -5210,9 +5228,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// host→mux pair the new incarnation's values also travel, it is ordered ahead of every one of them.
/// </para>
/// <para>
/// Mux only, deliberately: the external value nodes keep the #1070 rule (the retired child's Bad edge is
/// applied only while the replacement has not connected) — stamping them here would also latch them for
/// the comms-recovery audit. Sent BEFORE <see cref="EvictRetainedValues"/> so the Bad it retains is
/// Mux only: the external value nodes get their own, un-latched stamp on a respawn / Restart
/// (<see cref="StampValueNodesAwaitingNewDriver"/>, #1112) — routing them through the comms-loss fan here
/// would latch them for the comms-recovery audit. Sent BEFORE <see cref="EvictRetainedValues"/> so the Bad it retains is
/// evicted with the old object's values and never replayed. Not sent on a supervision restart (same
/// driver object). For a deploy removal it precedes the apply's <c>RemovedInputStatus</c>; a duplicate
/// Bad from the old child's <c>PostStop</c> is absorbed by the (value, status) dedup downstream.
@@ -5221,6 +5239,54 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// <param name="driverInstanceId">The driver instance whose object ended.</param>
private void TellDependentsDriverObjectEnded(string driverInstanceId) => FanCommsLossToDependencyMux(driverInstanceId);
/// <summary>
/// Gitea #1112 (owner decision "Brief Bad on restart") — stamps
/// <see cref="OpcUaStatus.BadWaitingForInitialData"/> on every raw NodeId <b>and</b> every referencing UNS NodeId
/// of <paramref name="driverInstanceId"/>'s value refs when the host replaces the driver OBJECT (config-change
/// respawn, operator Restart), so no OPC UA client keeps reading the stopped object's last Good until the
/// replacement publishes.
/// </summary>
/// <remarks>
/// <para>
/// <b>Ordering.</b> Sent from the host's own stop handler, before the replacement is spawned, on the
/// host→publish-actor pair every one of the replacement's values also travels (the host forwards them), so
/// the new driver's first Good always lands after it. The stopped child cannot overwrite it either: its
/// bursts are dropped once it is retired (<see cref="ForwardBatchToMux"/>), and its late
/// <c>PostStop</c> <c>ConnectivityChanged(false)</c> no longer stamps value nodes while a replacement exists
/// (<see cref="OnDriverConnectivityChanged"/>) — #1070 still drops it whole once the replacement connected.
/// </para>
/// <para>
/// <b>Not a comms loss.</b> <c>BadWaitingForInitialData</c> — what a freshly materialised node shows — rather
/// than <c>BadNoCommunication</c>, and deliberately NOT latched (<see cref="TrackCommsLatchSet"/>): a
/// respawn is not an outage, so it arms no recovery audit, increments no
/// <c>otopcua.driver.comms_latched_refs</c>, and publishes no driver status. Status-only (the node keeps
/// its value server-side; the SDK serves <c>null</c> under a Bad status), through the same
/// <see cref="OpcUa.OpcUaPublishActor.AttributeStatusBatchUpdate"/> the comms-loss stamp uses, so a write
/// in flight loses its revert ownership exactly as it does there. Address-space only: historization
/// records what the mux sees, which is #1109's <see cref="TellDependentsDriverObjectEnded"/> outage marker.
/// Native alarm conditions are not touched. Not sent on a supervision restart (same driver object) nor
/// on a deploy removal / disable (the apply's own removal path).
/// </para>
/// </remarks>
/// <param name="driverInstanceId">The driver instance whose object is being replaced.</param>
private void StampValueNodesAwaitingNewDriver(string driverInstanceId)
{
if (_opcUaPublishActor is null) return;
if (!_valueRefsByDriver.TryGetValue(driverInstanceId, out var entries) || entries.Count == 0) return;
var ts = DateTime.UtcNow;
var writes = new List<StatusWrite>(entries.Count);
foreach (var (_, nodes) in entries)
foreach (var n in nodes)
writes.Add(new StatusWrite(n.NodeId, OpcUaStatus.BadWaitingForInitialData, ts, n.Realm));
if (writes.Count == 0) return;
_opcUaPublishActor.Tell(new OpcUa.OpcUaPublishActor.AttributeStatusBatchUpdate(writes));
_log.Info(
"DriverHost {Node}: driver {Driver} object replaced — {Count} value node(s) marked BadWaitingForInitialData until its first value",
_localNode, driverInstanceId, writes.Count);
}
/// <summary>Marks a child this host is about to stop as retired and watches it until it terminates.</summary>
/// <param name="child">The child being stopped.</param>
private void RetireChild(IActorRef child)
@@ -5324,6 +5390,13 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// An operator Restart builds a NEW driver object, so the old one's retained values are evicted like a
// removal's; the respawned driver republishes its own. Dependents are told first (#1109).
TellDependentsDriverObjectEnded(msg.DriverInstanceId);
// ...and so are the OPC UA value nodes (#1112): awaiting the new object's first value.
StampValueNodesAwaitingNewDriver(msg.DriverInstanceId);
// #1053 (kept): a Restart keeps an outstanding comms latch for the new incarnation to clear, and only the new
// incarnation's Connected may arm its audit. The old incarnation's armed audit is cancelled HERE — this used
// to ride the stopped child's PostStop Bad re-latching, which #1112 no longer applies to value nodes while a
// replacement exists (a respawn must not latch).
Timers.Cancel(CommsAuditTimerKey(msg.DriverInstanceId));
EvictRetainedValues(msg.DriverInstanceId);
// The old incarnation's health must not read as the new one's until it publishes its own.
_healthPublisher.Forget(msg.DriverInstanceId);
@@ -160,9 +160,10 @@ public sealed class DriverHostCommsLossRecoveryTests : RuntimeActorTestBase
/// <summary>
/// #1053 (decided: KEEP). Unlike a removal (R-16, <see cref="Removing_a_comms_lost_driver_cancels_its_audit_and_leaves_no_false_warning_or_metric"/>),
/// an operator RESTART must not clear the comms latch: the nodes stay in the address space, still Bad, and the
/// respawned incarnation is what has to re-publish them — exactly what the audit checks. No host change is needed
/// for that: the stopped incarnation's <c>PostStop</c> comms-loss announcement re-latches the CURRENT ref set and
/// cancels the audit the old incarnation armed, and the new incarnation's <c>Connected</c> re-arms it. Pinned
/// respawned incarnation is what has to re-publish them — exactly what the audit checks. The Restart handler keeps
/// the latch and cancels the audit the old incarnation armed (since #1112 — this used to ride the stopped
/// incarnation's <c>PostStop</c> comms-loss announcement re-latching, which no longer stamps value nodes while a
/// replacement exists), and the new incarnation's <c>Connected</c> re-arms it. Pinned
/// here: no audit fires while the new incarnation is still connecting (well past the old window), and once it
/// connects and stays silent its OWN audit reports the kept ref.
/// </summary>
@@ -0,0 +1,369 @@
using System.Diagnostics.Metrics;
using Akka.Actor;
using Akka.TestKit;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using static ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness.V3ArtifactSeeder;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// <b>#1112 — "Brief Bad on restart" (owner decision).</b> When the host replaces a driver OBJECT (a config-change
/// respawn or an operator Restart), the driver's OPC UA value nodes — the raw NodeId AND every referencing UNS
/// mirror — go <c>BadWaitingForInitialData</c> at the stop and stay there until the NEW driver's first value.
/// <para>
/// Before this, only the dependency mux was told (#1109); the value nodes kept the stopped object's last Good
/// whenever the stopped child's own <c>PostStop</c> Bad edge reached the host after its replacement connected
/// (and #1070 dropped it). And when that edge DID land first, it stamped <c>BadNoCommunication</c> and latched
/// the refs for the comms-recovery audit, as if a respawn were an outage.
/// </para>
/// <para>
/// Every test drives both seams (config change and Restart). The race is made deterministic the way
/// <see cref="DriverHostStaleConnectivityTests"/> does it: either the old driver's
/// <see cref="IHostConnectivityProbe.GetHostStatuses"/> wedges the old child's mailbox (its stop lands late) or
/// the new driver's initialise is held (the stop lands first).
/// </para>
/// </summary>
public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase
{
private static readonly NodeId TestNode = NodeId.Parse("driver-respawn-value-gap");
private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64));
private static readonly RevisionHash RevB = RevisionHash.Parse(new string('b', 64));
/// <summary>The child's reconnect retry runs on <c>DriverInstanceActor.DefaultReconnectInterval</c> (10 s).</summary>
private static readonly TimeSpan ReconnectBudget = TimeSpan.FromSeconds(25);
private static readonly TimeSpan AuditDelay = TimeSpan.FromSeconds(1);
private const string DriverId = "drv-gap";
private const string SpeedRef = "Plant/Modbus/dev1/speed";
private const string FlowRef = "Plant/Modbus/dev1/flow";
private const string TempRef = "Plant/Modbus/dev1/temp";
private const string UnsSpeedNode = "filling/line1/station1/speed";
private const string UnsFlowNode = "filling/line1/station1/flow";
private static readonly string[] AllOldNodes = [SpeedRef, UnsSpeedNode, FlowRef, UnsFlowNode];
/// <summary>
/// The old child stops LATE (after the replacement connected and subscribed). The host's own stamp still puts
/// raw + UNS non-Good at the stop, the stopped child's late Bad never lands on top of the new Good, and the new
/// driver's first value — the IDENTICAL value, so only a status edge can show the gap — makes them Good again.
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public void A_late_stopping_old_child_value_nodes_go_awaiting_first_value_then_Good(bool configChange)
{
var oldDriver = new GatedDriver(DriverId);
var newDriver = new GatedDriver(DriverId);
var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver);
SeedGoodFromOldDriver(oldDriver, publish);
oldDriver.BlockHostStatuses();
oldDriver.RaiseHostStatusChanged();
oldDriver.HostStatusesEntered.Wait(PresenceBudget, TestContext.Current.CancellationToken)
.ShouldBeTrue("the old child must be parked inside GetHostStatuses before the respawn");
Replace(configChange, host, coordinator, db);
// The stamp is the host's, sent at the stop: it arrives although the old child cannot stop yet.
var stamp = ExpectStampBeforeAnyValue(publish);
stamp.Items.Select(i => i.NodeId).ShouldBe(AllOldNodes, ignoreOrder: true);
stamp.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadWaitingForInitialData);
AwaitFinalSubscribe(newDriver, configChange);
// Release the old child: PostStop announces comms loss THEN shuts the driver down, so once ShutdownAsync ran
// the stale Bad is already in the host's mailbox, ahead of the value fired next.
oldDriver.ReleaseHostStatuses();
AwaitCondition(() => oldDriver.ShutdownCalled, PresenceBudget, TestContext.Current.CancellationToken);
newDriver.Fire(SpeedRef, 11.0);
var (statusBatches, recovered) = DrainUntilValueBatch(publish, PresenceBudget);
statusBatches.ShouldBeEmpty("the stopped incarnation's late Bad must not be stamped once its replacement exists");
recovered.Items.Select(i => i.NodeId).ShouldBe(new[] { SpeedRef, UnsSpeedNode }, ignoreOrder: true);
recovered.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.Good && Equals(i.Value, 11.0));
// Positive control for the empty status list above: a real outage of the CURRENT incarnation IS stamped.
host.Tell(new ReconnectDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
var outage = publish.FishForMessage<OpcUaPublishActor.AttributeStatusBatchUpdate>(_ => true, ReconnectBudget,
cancellationToken: TestContext.Current.CancellationToken);
outage.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadNoCommunication);
}
/// <summary>
/// The old child stops FIRST (the replacement's initialise is held), so its <c>PostStop</c> Bad is processed
/// while the replacement is not yet connected — the interleaving in which it used to stamp
/// <c>BadNoCommunication</c> and latch every ref for the comms-recovery audit. A respawn is not an outage: no
/// comms-loss stamp, no latch, no audit Warning / <c>otopcua.driver.comms_latched_refs</c> — even though the
/// new driver never publishes <c>flow</c> (pre-fix, exactly that ref was reported). The raw + UNS nodes sit at
/// <c>BadWaitingForInitialData</c> until the first value.
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public void An_old_child_stopping_before_the_replacement_connects_does_not_latch_or_audit(bool configChange)
{
var oldDriver = new GatedDriver(DriverId);
var newDriver = new GatedDriver(DriverId);
var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
newDriver.InitializeGate = hold.Task;
var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver);
SeedGoodFromOldDriver(oldDriver, publish);
using var meter = new MeterRecorder("otopcua.driver.comms_latched_refs");
Replace(configChange, host, coordinator, db);
var stamp = ExpectStampBeforeAnyValue(publish);
stamp.Items.Select(i => i.NodeId).ShouldBe(AllOldNodes, ignoreOrder: true);
stamp.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadWaitingForInitialData);
// The old child has stopped: its PostStop Bad is in the host's mailbox before the replacement can connect.
AwaitCondition(() => oldDriver.ShutdownCalled, PresenceBudget, TestContext.Current.CancellationToken);
hold.SetResult();
AwaitFinalSubscribe(newDriver, configChange);
newDriver.Fire(SpeedRef, 11.0);
var (statusBatches, recovered) = DrainUntilValueBatch(publish, PresenceBudget);
statusBatches.ShouldBeEmpty("a respawn is not a comms loss — the old child's Bad must not re-stamp the nodes");
recovered.Items.Select(i => i.NodeId).ShouldBe(new[] { SpeedRef, UnsSpeedNode }, ignoreOrder: true);
recovered.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.Good && Equals(i.Value, 11.0));
// flow never re-published. Had the respawn latched it, the audit armed by the replacement's Connected would
// report it after AuditDelay.
EventFilter.Warning(contains: "still BadNoCommunication")
.Expect(0, AuditDelay + TimeSpan.FromSeconds(2), () => { }, TestContext.Current.CancellationToken);
meter.SumWithTag("driver_instance", DriverId).ShouldBe(0);
// Positive control: a real outage of the current incarnation (silent re-subscribe: GatedDriver pushes nothing)
// DOES latch and DOES audit, through the same meter.
EventFilter.Warning(contains: "still BadNoCommunication").ExpectOne(ReconnectBudget + AuditDelay,
() => host.Tell(new ReconnectDriver("c1", DriverId, "test-operator", Guid.NewGuid())),
TestContext.Current.CancellationToken);
AwaitCondition(() => meter.SumWithTag("driver_instance", DriverId) > 0, TimeSpan.FromSeconds(5),
TestContext.Current.CancellationToken);
}
private (IActorRef Host, TestProbe Publish, TestProbe Coordinator, Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> Db)
Arrange(GatedDriver oldDriver, GatedDriver newDriver)
{
var db = NewInMemoryDbFactory();
var deploymentId = SeedV3Deployment(db, RevA,
rawTags:
[
(Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false),
(Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "flow", DataType: "Double", Writable: false),
],
unsRefs:
[
(Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null),
(Area: "filling", Line: "line1", Equip: "station1", BackingTag: "flow", Effective: (string?)null),
],
enabled: true);
var (host, publish, _, coordinator) = SpawnHostAndApplyWithCoordinator(this, db, TestNode, deploymentId, RevA,
driverFactory: new SequenceDriverFactory(oldDriver, newDriver), commsRecoveryAuditDelay: AuditDelay);
AwaitAssert(() => (oldDriver.LastSubscribedRefs ?? []).ShouldContain(SpeedRef), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
return (host, publish, coordinator, db);
}
private void SeedGoodFromOldDriver(GatedDriver oldDriver, TestProbe publish)
{
oldDriver.Fire(SpeedRef, 11.0);
oldDriver.Fire(FlowRef, 3.0);
var seen = new HashSet<string>();
publish.FishForMessage(m =>
{
if (m is OpcUaPublishActor.AttributeValueBatchUpdate v)
foreach (var i in v.Items.Where(i => OpcUaStatus.IsGood(i.StatusCode))) seen.Add(i.NodeId);
return AllOldNodes.All(seen.Contains);
}, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>Config change: a new deployment edits the driver's config (adds <c>temp</c>), so the planner respawns
/// it. Restart: the operator command.</summary>
private static void Replace(bool configChange, IActorRef host, TestProbe coordinator,
Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> db)
{
if (!configChange)
{
host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
return;
}
var revB = SeedV3Deployment(db, RevB,
rawTags:
[
(Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false),
(Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "flow", DataType: "Double", Writable: false),
(Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "temp", DataType: "Double", Writable: false),
],
unsRefs:
[
(Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null),
(Area: "filling", Line: "line1", Equip: "station1", BackingTag: "flow", Effective: (string?)null),
],
enabled: true);
// Waits for the Applied ack; the publish probe keeps every message in arrival order meanwhile.
Dispatch(host, coordinator, revB, RevB);
}
/// <summary>The first status batch for the speed node, failing if a value batch for it arrives first.</summary>
private static OpcUaPublishActor.AttributeStatusBatchUpdate ExpectStampBeforeAnyValue(TestProbe publish)
{
var msg = publish.FishForMessage(m =>
m is OpcUaPublishActor.AttributeStatusBatchUpdate s && s.Items.Any(i => i.NodeId == SpeedRef)
|| m is OpcUaPublishActor.AttributeValueBatchUpdate v && v.Items.Any(i => i.NodeId == SpeedRef),
PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
return msg.ShouldBeOfType<OpcUaPublishActor.AttributeStatusBatchUpdate>(
"the respawn must stamp the value nodes before the new driver's first value");
}
/// <summary>A config-change spawn hands the child the PREVIOUS apply's set and the bulk push re-subscribes with
/// the new one; a value fired between the two can be lost, so wait for the final set.</summary>
private void AwaitFinalSubscribe(GatedDriver newDriver, bool configChange) =>
AwaitAssert(() => (newDriver.LastSubscribedRefs ?? []).ShouldContain(configChange ? TempRef : SpeedRef),
PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
/// <summary>Status batches naming speed, up to (and returning) the next value batch naming speed.</summary>
private static (List<OpcUaPublishActor.AttributeStatusBatchUpdate> Statuses, OpcUaPublishActor.AttributeValueBatchUpdate Value)
DrainUntilValueBatch(TestProbe publish, TimeSpan budget)
{
var statuses = new List<OpcUaPublishActor.AttributeStatusBatchUpdate>();
var msg = publish.FishForMessage(m =>
{
if (m is OpcUaPublishActor.AttributeStatusBatchUpdate s && s.Items.Any(i => i.NodeId == SpeedRef)) statuses.Add(s);
return m is OpcUaPublishActor.AttributeValueBatchUpdate v && v.Items.Any(i => i.NodeId == SpeedRef);
}, budget, cancellationToken: TestContext.Current.CancellationToken);
return (statuses, (OpcUaPublishActor.AttributeValueBatchUpdate)msg);
}
/// <summary>Hands out the given drivers in order, one per spawn (the last one repeats).</summary>
private sealed class SequenceDriverFactory(params IDriver[] drivers) : IDriverFactory
{
private int _next;
public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson) =>
drivers[Math.Min(Interlocked.Increment(ref _next) - 1, drivers.Length - 1)];
public IReadOnlyCollection<string> SupportedTypes { get; } = ["Modbus"];
}
/// <summary>A subscribable driver that publishes only when told to (so a re-subscribe is silent), whose
/// <see cref="GetHostStatuses"/> can block the owning child's mailbox thread, and whose initialise can be held.</summary>
private sealed class GatedDriver(string instanceId) : IDriver, ISubscribable, IHostConnectivityProbe
{
private readonly StubHandle _handle = new();
private readonly ManualResetEventSlim _release = new(initialState: true);
private readonly Lock _gate = new();
private IReadOnlyList<string>? _lastSubscribedRefs;
private volatile bool _blocking;
private volatile bool _shutdownCalled;
public event EventHandler<DataChangeEventArgs>? OnDataChange;
public event EventHandler<HostStatusChangedEventArgs>? OnHostStatusChanged;
public ManualResetEventSlim HostStatusesEntered { get; } = new();
public Task? InitializeGate { get; set; }
public bool ShutdownCalled => _shutdownCalled;
public string DriverInstanceId => instanceId;
public string DriverType => "Modbus";
public IReadOnlyList<string>? LastSubscribedRefs
{
get { lock (_gate) return _lastSubscribedRefs; }
}
public void BlockHostStatuses()
{
_release.Reset();
_blocking = true;
}
public void ReleaseHostStatuses()
{
_blocking = false;
_release.Set();
}
public void RaiseHostStatusChanged() =>
OnHostStatusChanged?.Invoke(this, new HostStatusChangedEventArgs("dev1", HostState.Running, HostState.Stopped));
public void Fire(string fullReference, object value) =>
OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, fullReference,
new DataValueSnapshot(value, OpcUaStatus.Good, DateTime.UtcNow, DateTime.UtcNow)));
public IReadOnlyList<HostConnectivityStatus> GetHostStatuses()
{
if (_blocking)
{
HostStatusesEntered.Set();
_release.Wait(TimeSpan.FromSeconds(60));
}
return [new HostConnectivityStatus("dev1", HostState.Running, DateTime.UnixEpoch)];
}
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) =>
InitializeGate is { } gate ? gate.WaitAsync(cancellationToken) : Task.CompletedTask;
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
public Task ShutdownAsync(CancellationToken cancellationToken)
{
_shutdownCalled = true;
return Task.CompletedTask;
}
// Stable health so the #527 watchdog never trips on its own.
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
public Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken)
{
lock (_gate) _lastSubscribedRefs = fullReferences.ToArray();
return Task.FromResult<ISubscriptionHandle>(_handle);
}
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) => Task.CompletedTask;
}
/// <summary>Tag-filtered counter recorder (instrument name alone would collect a parallel test's measurements).</summary>
private sealed class MeterRecorder : IDisposable
{
private readonly MeterListener _listener;
private readonly List<(long Value, KeyValuePair<string, object?>[] Tags)> _measurements = new();
private readonly Lock _gate = new();
public MeterRecorder(string instrumentName)
{
_listener = new MeterListener
{
InstrumentPublished = (instrument, listener) =>
{
if (instrument.Meter.Name == OtOpcUaTelemetry.MeterName && instrument.Name == instrumentName)
listener.EnableMeasurementEvents(instrument);
},
};
_listener.SetMeasurementEventCallback<long>((_, value, tags, _) =>
{
lock (_gate) _measurements.Add((value, tags.ToArray()));
});
_listener.Start();
}
public long SumWithTag(string key, string value)
{
lock (_gate)
return _measurements.Where(m => m.Tags.Any(t => t.Key == key && Equals(t.Value, value))).Sum(m => m.Value);
}
public void Dispose() => _listener.Dispose();
}
}
@@ -40,6 +40,7 @@ public sealed class DriverHostStaleConnectivityTests : RuntimeActorTestBase
private const string DriverId = "drv-stale";
private const string SpeedRef = "Plant/Modbus/dev1/speed";
private const string UnsSpeedNode = "filling/line1/station1/speed";
/// <summary>
/// The old incarnation's Bad edge lands after the new incarnation connected and pushed Good. It must be dropped.
@@ -68,8 +69,12 @@ public sealed class DriverHostStaleConnectivityTests : RuntimeActorTestBase
// Restart: the old child is stopped (its stop cannot run yet) and the new one spawns, connects and pushes.
host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
// #1112 changed this expectation (it was "no status batch at all while the old child is wedged"): the HOST now
// stamps the value nodes BadWaitingForInitialData at the restart (owner decision "Brief Bad on restart"), so
// exactly that one batch precedes the new incarnation's push — and still no comms-loss Bad.
var statusBefore = DrainUntilValueBatch(publish, PresenceBudget);
statusBefore.ShouldBe(0, "nothing may stamp Bad while the old child is wedged");
statusBefore.ToArray().ShouldBe(new[] { OpcUaStatus.BadWaitingForInitialData },
"only the host's awaiting-first-value stamp may precede the new push while the old child is wedged");
newDriver.SubscribeCount.ShouldBeGreaterThanOrEqualTo(1);
// Let the old child stop. Its PostStop Tells ConnectivityChanged(false) and THEN shuts the driver down, so once
@@ -81,16 +86,19 @@ public sealed class DriverHostStaleConnectivityTests : RuntimeActorTestBase
// Positive control: a real outage of the CURRENT incarnation.
host.Tell(new ReconnectDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
var statusAfter = DrainUntilValueBatch(publish, ReconnectBudget);
statusAfter.ShouldBe(1,
statusAfter.ToArray().ShouldBe(new[] { OpcUaStatus.BadNoCommunication },
"exactly the live incarnation's comms loss — a second batch is the stopped incarnation's late Bad overruling a connected driver");
}
/// <summary>
/// The other side of the rule (03/S15, kept): while the replacement has NOT yet connected, the stopped
/// incarnation's Bad edge is still the only thing covering the gap and must be applied.
/// The other side of the rule. Before #1112 the stopped incarnation's Bad edge, applied while the replacement
/// had not yet connected, was the only thing covering the gap (and it latched the refs as a comms loss). Now the
/// HOST covers it at the restart with <c>BadWaitingForInitialData</c>, and the old child's late edge no longer
/// stamps value nodes while a replacement exists — so it is processed (the old child has shut down before the
/// replacement may connect) but adds no <c>BadNoCommunication</c> batch.
/// </summary>
[Fact]
public void A_stopped_incarnations_comms_loss_before_the_new_one_connects_still_stamps_Bad()
public void A_stopped_incarnations_comms_loss_before_the_new_one_connects_is_covered_by_the_hosts_stamp()
{
var oldDriver = new GatedProbeDriver(DriverId);
var newDriver = new GatedProbeDriver(DriverId);
@@ -104,14 +112,15 @@ public sealed class DriverHostStaleConnectivityTests : RuntimeActorTestBase
var staled = publish.FishForMessage<OpcUaPublishActor.AttributeStatusBatchUpdate>(_ => true, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
staled.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadNoCommunication);
staled.Items.Select(i => i.NodeId).ShouldContain(SpeedRef);
staled.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadWaitingForInitialData);
staled.Items.Select(i => i.NodeId).ShouldBe(new[] { SpeedRef, UnsSpeedNode }, ignoreOrder: true);
// And the replacement's own push still recovers them.
// The old child's PostStop Bad is in the host's mailbox once its driver shut down — before the replacement
// can connect. And the replacement's own push still recovers the nodes, with nothing stamped in between.
AwaitCondition(() => oldDriver.ShutdownCalled, PresenceBudget, TestContext.Current.CancellationToken);
hold.SetResult();
var recovered = publish.FishForMessage<OpcUaPublishActor.AttributeValueBatchUpdate>(_ => true, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
recovered.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.Good);
DrainUntilValueBatch(publish, PresenceBudget).ShouldBeEmpty(
"the stopped incarnation's Bad must not re-stamp the nodes as a comms loss while a replacement exists");
}
private (IActorRef Host, Akka.TestKit.TestProbe Publish) Arrange(IDriverFactory factory)
@@ -125,15 +134,18 @@ public sealed class DriverHostStaleConnectivityTests : RuntimeActorTestBase
return (host, publish);
}
/// <summary>Counts status batches arriving at the publish probe until the next value batch, which it consumes.</summary>
private static int DrainUntilValueBatch(Akka.TestKit.TestProbe publish, TimeSpan budget)
/// <summary>The status code of each status batch (naming speed) arriving at the publish probe until the next
/// value batch, which it consumes; that value batch must be all Good.</summary>
private static List<uint> DrainUntilValueBatch(Akka.TestKit.TestProbe publish, TimeSpan budget)
{
var statusBatches = 0;
publish.FishForMessage(m =>
var statusBatches = new List<uint>();
var value = publish.FishForMessage(m =>
{
if (m is OpcUaPublishActor.AttributeStatusBatchUpdate s && s.Items.Any(i => i.NodeId == SpeedRef)) statusBatches++;
if (m is OpcUaPublishActor.AttributeStatusBatchUpdate s && s.Items.Any(i => i.NodeId == SpeedRef))
statusBatches.Add(s.Items.First(i => i.NodeId == SpeedRef).StatusCode);
return m is OpcUaPublishActor.AttributeValueBatchUpdate;
}, budget, cancellationToken: TestContext.Current.CancellationToken);
((OpcUaPublishActor.AttributeValueBatchUpdate)value).Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.Good);
return statusBatches;
}