diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index b8f9fbad8..1f6d69121 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -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 diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 42560c56d..d279e4be6 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -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) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index 56ffd825e..0ea8a0922 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -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 Connected=true 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 Connected=false 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 - /// (OnConditionSignalConnectivity). 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 BadWaitingForInitialData 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 (OnConditionSignalConnectivity). A sender that was never a child of + /// this host is not filtered. /// /// /// The connectivity announcement; Sender is its producer. @@ -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? respawning = null; + foreach (var spec in plan.ToSpawn) + if (plan.ToStop.Contains(spec.DriverInstanceId)) + (respawning ??= new HashSet(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) + /// Stops a driver child that left the plan or is about to be respawned with a new config. + /// The driver instance to stop. + /// when the same apply spawns a replacement (a config-change + /// respawn): the driver's value nodes are then stamped until the + /// new driver object's first value (#1112, ). + 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. /// /// - /// 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 so the Bad it retains is + /// Mux only: the external value nodes get their own, un-latched stamp on a respawn / Restart + /// (, #1112) — routing them through the comms-loss fan here + /// would latch them for the comms-recovery audit. Sent BEFORE 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 RemovedInputStatus; a duplicate /// Bad from the old child's PostStop is absorbed by the (value, status) dedup downstream. @@ -5221,6 +5239,54 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn /// The driver instance whose object ended. private void TellDependentsDriverObjectEnded(string driverInstanceId) => FanCommsLossToDependencyMux(driverInstanceId); + /// + /// Gitea #1112 (owner decision "Brief Bad on restart") — stamps + /// on every raw NodeId and every referencing UNS NodeId + /// of '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. + /// + /// + /// + /// Ordering. 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 (), and its late + /// PostStop ConnectivityChanged(false) no longer stamps value nodes while a replacement exists + /// () — #1070 still drops it whole once the replacement connected. + /// + /// + /// Not a comms loss. BadWaitingForInitialData — what a freshly materialised node shows — rather + /// than BadNoCommunication, and deliberately NOT latched (): a + /// respawn is not an outage, so it arms no recovery audit, increments no + /// otopcua.driver.comms_latched_refs, and publishes no driver status. Status-only (the node keeps + /// its value server-side; the SDK serves null under a Bad status), through the same + /// 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 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). + /// + /// + /// The driver instance whose object is being replaced. + 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(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); + } + /// Marks a child this host is about to stop as retired and watches it until it terminates. /// The child being stopped. 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); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostCommsLossRecoveryTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostCommsLossRecoveryTests.cs index 91d043002..cf3a39c83 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostCommsLossRecoveryTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostCommsLossRecoveryTests.cs @@ -160,9 +160,10 @@ public sealed class DriverHostCommsLossRecoveryTests : RuntimeActorTestBase /// /// #1053 (decided: KEEP). Unlike a removal (R-16, ), /// 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 PostStop comms-loss announcement re-latches the CURRENT ref set and - /// cancels the audit the old incarnation armed, and the new incarnation's Connected 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 PostStop comms-loss announcement re-latching, which no longer stamps value nodes while a + /// replacement exists), and the new incarnation's Connected 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. /// diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostRespawnValueNodeGapTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostRespawnValueNodeGapTests.cs new file mode 100644 index 000000000..97ea762f6 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostRespawnValueNodeGapTests.cs @@ -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; + +/// +/// #1112 — "Brief Bad on restart" (owner decision). 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 BadWaitingForInitialData at the stop and stay there until the NEW driver's first value. +/// +/// 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 PostStop Bad edge reached the host after its replacement connected +/// (and #1070 dropped it). And when that edge DID land first, it stamped BadNoCommunication and latched +/// the refs for the comms-recovery audit, as if a respawn were an outage. +/// +/// +/// Every test drives both seams (config change and Restart). The race is made deterministic the way +/// does it: either the old driver's +/// wedges the old child's mailbox (its stop lands late) or +/// the new driver's initialise is held (the stop lands first). +/// +/// +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)); + + /// The child's reconnect retry runs on DriverInstanceActor.DefaultReconnectInterval (10 s). + 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]; + + /// + /// 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. + /// + [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(_ => true, ReconnectBudget, + cancellationToken: TestContext.Current.CancellationToken); + outage.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadNoCommunication); + } + + /// + /// The old child stops FIRST (the replacement's initialise is held), so its PostStop Bad is processed + /// while the replacement is not yet connected — the interleaving in which it used to stamp + /// BadNoCommunication and latch every ref for the comms-recovery audit. A respawn is not an outage: no + /// comms-loss stamp, no latch, no audit Warning / otopcua.driver.comms_latched_refs — even though the + /// new driver never publishes flow (pre-fix, exactly that ref was reported). The raw + UNS nodes sit at + /// BadWaitingForInitialData until the first value. + /// + [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 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(); + 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); + } + + /// Config change: a new deployment edits the driver's config (adds temp), so the planner respawns + /// it. Restart: the operator command. + private static void Replace(bool configChange, IActorRef host, TestProbe coordinator, + Microsoft.EntityFrameworkCore.IDbContextFactory 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); + } + + /// The first status batch for the speed node, failing if a value batch for it arrives first. + 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( + "the respawn must stamp the value nodes before the new driver's first value"); + } + + /// 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. + private void AwaitFinalSubscribe(GatedDriver newDriver, bool configChange) => + AwaitAssert(() => (newDriver.LastSubscribedRefs ?? []).ShouldContain(configChange ? TempRef : SpeedRef), + PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + + /// Status batches naming speed, up to (and returning) the next value batch naming speed. + private static (List Statuses, OpcUaPublishActor.AttributeValueBatchUpdate Value) + DrainUntilValueBatch(TestProbe publish, TimeSpan budget) + { + var statuses = new List(); + 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); + } + + /// Hands out the given drivers in order, one per spawn (the last one repeats). + 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 SupportedTypes { get; } = ["Modbus"]; + } + + /// A subscribable driver that publishes only when told to (so a re-subscribe is silent), whose + /// can block the owning child's mailbox thread, and whose initialise can be held. + 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? _lastSubscribedRefs; + private volatile bool _blocking; + private volatile bool _shutdownCalled; + + public event EventHandler? OnDataChange; + public event EventHandler? 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? 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 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 SubscribeAsync( + IReadOnlyList fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken) + { + lock (_gate) _lastSubscribedRefs = fullReferences.ToArray(); + return Task.FromResult(_handle); + } + + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) => Task.CompletedTask; + } + + /// Tag-filtered counter recorder (instrument name alone would collect a parallel test's measurements). + private sealed class MeterRecorder : IDisposable + { + private readonly MeterListener _listener; + private readonly List<(long Value, KeyValuePair[] 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((_, 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(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostStaleConnectivityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostStaleConnectivityTests.cs index db1a79a15..abc339e73 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostStaleConnectivityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostStaleConnectivityTests.cs @@ -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"; /// /// 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"); } /// - /// 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 BadWaitingForInitialData, 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 BadNoCommunication batch. /// [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(_ => 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(_ => 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); } - /// Counts status batches arriving at the publish probe until the next value batch, which it consumes. - private static int DrainUntilValueBatch(Akka.TestKit.TestProbe publish, TimeSpan budget) + /// 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. + private static List DrainUntilValueBatch(Akka.TestKit.TestProbe publish, TimeSpan budget) { - var statusBatches = 0; - publish.FishForMessage(m => + var statusBatches = new List(); + 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; }