From 90ae995bf4da33bf274d42f9d5603d81ee0c1a1b Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 16:40:11 -0500 Subject: [PATCH] fix(runtime): #1070 a stopped incarnation's late ConnectivityChanged no longer overrules a connected replacement Confirmed, deterministically: Context.Stop is asynchronous and messages from two children are unordered, so an operator Restart's old child announced comms loss from PostStop AFTER the replacement had connected and pushed its initial values (the old child reaches its stop only once a synchronous driver call returns). The host then stamped every value node BadNoCommunication with nothing left to re-publish them, re-latched them and cancelled the new incarnation's recovery audit - nodes stuck Bad, tripwire disarmed. Pre-fix the new test saw 2 status batches where 1 is correct. Fix at the root, in DriverHostActor.OnDriverConnectivityChanged: IsStaleRetiredConnectivity drops, whole, any Connected=true from a retired child, and its Connected=false once the current child of the same id has announced Connected (new ChildEntry.Connected, set only from the current child's own edges). A retired Bad edge is still applied while the replacement has not connected (or there is none) - the 03/S15 gap cover Restart/respawn rely on; same rule the condition-signal tracker already applied. Senders that were never children are not filtered. Tests (DriverHostStaleConnectivityTests): the race made deterministic by wedging the old child in a blocking GetHostStatuses; positive control = a Force Reconnect of the current child must yield exactly one status batch before the re-subscribe push. Companion: a retired Bad edge before the replacement connects still stamps Bad and the push recovers. Co-Authored-By: Claude --- .claude/rules/drivers.md | 5 + docs/DriverLifecycle.md | 11 + .../Drivers/DriverHostActor.cs | 54 +++- .../DriverHostStaleConnectivityTests.cs | 234 ++++++++++++++++++ 4 files changed, 302 insertions(+), 2 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostStaleConnectivityTests.cs diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index c0f7b3ad5..a4931f2e1 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -139,6 +139,11 @@ non-`Healthy` state **and** its `LastSuccessfulRead` has been frozen for 90 s. T `forceRaise`, MQTT's new initial push). Instead the host **audits**: refs still latched 30 s after a reconnect log a Warning and increment `otopcua.driver.comms_latched_refs`. Non-zero on that counter means a driver reconnects without re-publishing. + - ⚠️ **A stopped incarnation's late connectivity is dropped once its replacement connected (#1070).** A Restart / + respawn's old child announces Bad from `PostStop`, which can land AFTER the new child connected and pushed (two + senders, no ordering) — it used to stick the nodes Bad and cancel the audit. `IsStaleRetiredConnectivity` drops a + retired child's `Connected=true` always and its `false` once the current child is `Connected`; before that the Bad + edge still covers the gap. `DriverHostStaleConnectivityTests`. - **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 a079a834d..5b05714ec 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -603,6 +603,17 @@ An operator **Restart** deliberately KEEPS the latch (#1053): the nodes stay in 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. +⚠️ **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 +AFTER the replacement connected and pushed its initial values — the old child gets to its stop only once whatever it is +running returns (a synchronous driver call such as a health publish). Applied then, it stamped every value node +`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 +made deterministic by wedging the old child in `GetHostStatuses`). + ### The connect path feeds the circuit breaker (R2-10 T10 closure) `IDriver.InitializeAsync` is routed through the capability invoker as 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 75dd96cac..6bf55fbb0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -765,6 +765,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn /// When this child was spawned — the diagnostics' last-change time until it publishes health. public DateTime SpawnedUtc { get; } = DateTime.UtcNow; + /// + /// The last connectivity edge THIS incarnation announced (false until its first Connected=true). + /// #1070: a stopped predecessor's late Bad edge is dropped once this is true. + /// + public bool Connected { get; set; } + // Convenience accessors for sites that don't need the full spec. /// Gets the driver type name from the child's spec. public string DriverType => Spec.DriverType; @@ -2006,8 +2012,9 @@ 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 NOT filtered — the respawn path relies on - // that Bad fan to cover the gap. + // 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. if (_retiredChildren.Contains(Sender)) { _log.Debug("DriverHost {Node}: dropped a {Count}-item value burst from a stopped incarnation of {Id}", @@ -2125,6 +2132,17 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn /// private void OnDriverConnectivityChanged(DriverInstanceActor.ConnectivityChanged msg) { + if (IsStaleRetiredConnectivity(msg)) + { + _log.Debug( + "DriverHost {Node}: dropped a stale ConnectivityChanged(connected={Connected}) for {Id} from a stopped incarnation ({Stale})", + _localNode, msg.Connected, msg.DriverInstanceId, Sender); + return; + } + + if (_children.TryGetValue(msg.DriverInstanceId, out var announcing) && Equals(announcing.Actor, Sender)) + announcing.Connected = msg.Connected; + if (msg.Connected && _acquisitionDemands.ContainsKey(msg.DriverInstanceId) && _children.TryGetValue(msg.DriverInstanceId, out var activeChild) && Equals(activeChild.Actor, Sender)) SendDesiredSubscriptions(activeChild.Actor, msg.DriverInstanceId); @@ -2178,6 +2196,38 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _localNode, msg.DriverInstanceId, msg.Connected ? "connected" : "disconnected", annotated, statusCode); } + /// + /// #1070 — whether comes from a child this host already stopped (a + /// member) and would overrule the CURRENT incarnation's state. + /// + /// + /// + /// Context.Stop is asynchronous and messages from two different children are not ordered, so a + /// stopped child's PostStop comms-loss announcement can reach this host AFTER its replacement + /// connected and published its initial push — the old child only gets to its stop once whatever it is + /// running returns (a synchronous driver call, e.g. a health publish). Applied then, it stamped every value + /// node BadNoCommunication with nothing left to re-publish them, re-latched them and cancelled the + /// recovery audit the new incarnation had armed: nodes stuck Bad with the tripwire disarmed. + /// + /// + /// 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. + /// + /// + /// The connectivity announcement; Sender is its producer. + /// when the message must be dropped. + private bool IsStaleRetiredConnectivity(DriverInstanceActor.ConnectivityChanged msg) + { + if (!_retiredChildren.Contains(Sender)) return false; + if (msg.Connected) return true; + return _children.TryGetValue(msg.DriverInstanceId, out var current) && current.Connected; + } + /// /// Archreview 03/S15 — the value-node half of the comms-loss fan-out: stamp /// on every raw NodeId and every referencing UNS 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 new file mode 100644 index 000000000..db1a79a15 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostStaleConnectivityTests.cs @@ -0,0 +1,234 @@ +using Akka.Actor; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; +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; + +/// +/// #1070 — a stopped incarnation's late ConnectivityChanged(false) must not overrule the live one. +/// +/// An operator Restart stops the old child (Context.Stop is asynchronous) and spawns its replacement in +/// the same handler. The old child announces comms loss from PostStop, which runs only once its mailbox +/// gets to the stop — and a child busy in a synchronous driver call gets there late. Messages from two +/// different senders are not ordered, so that announcement can reach the host AFTER the new incarnation has +/// connected and published its initial push. Applied then, it stamped every value node +/// BadNoCommunication (nothing re-publishes: the new child already did), re-latched them and cancelled +/// the new incarnation's recovery audit — nodes stuck Bad with the tripwire disarmed. +/// +/// +/// The race is made deterministic here: the old driver's +/// (called synchronously on the child's mailbox thread by its health publish) blocks on a gate, so the old +/// child cannot process its stop until the test releases it — after the new child's initial push has been +/// observed at the publish actor. +/// +/// +public sealed class DriverHostStaleConnectivityTests : RuntimeActorTestBase +{ + private static readonly NodeId TestNode = NodeId.Parse("driver-stale-connectivity"); + private static readonly RevisionHash RevA = RevisionHash.Parse(new string('e', 64)); + + /// The child's reconnect retry runs on DriverInstanceActor.DefaultReconnectInterval (10 s), which the + /// host exposes no seam to shorten. + private static readonly TimeSpan ReconnectBudget = TimeSpan.FromSeconds(25); + + private const string DriverId = "drv-stale"; + private const string SpeedRef = "Plant/Modbus/dev1/speed"; + + /// + /// The old incarnation's Bad edge lands after the new incarnation connected and pushed Good. It must be dropped. + /// + /// Positive control (the absence half is otherwise vacuous): after the stale message is provably in the + /// host's mailbox, a Force Reconnect of the CURRENT child must produce exactly one status batch before the + /// re-subscribe's value push. Pre-fix the stale announcement adds a second, earlier status batch. + /// + /// + [Fact] + public void A_stopped_incarnations_late_comms_loss_after_the_new_one_connected_is_dropped() + { + var oldDriver = new GatedProbeDriver(DriverId); + var newDriver = new GatedProbeDriver(DriverId); + var (host, publish) = Arrange(new SequenceDriverFactory(oldDriver, newDriver)); + + // Steady state on the old incarnation: its subscribe pushed 5 Good. + publish.FishForMessage(_ => true, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + + // Wedge the old child's mailbox thread inside a synchronous driver call. + oldDriver.BlockHostStatuses(); + oldDriver.RaiseHostStatusChanged(); + oldDriver.HostStatusesEntered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue( + "the old child must be parked inside GetHostStatuses before the restart"); + + // 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())); + var statusBefore = DrainUntilValueBatch(publish, PresenceBudget); + statusBefore.ShouldBe(0, "nothing may stamp Bad 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 + // ShutdownAsync has been entered the stale message is already in the host's mailbox — ahead of anything the + // test sends from here on. + oldDriver.ReleaseHostStatuses(); + AwaitCondition(() => oldDriver.ShutdownCalled, PresenceBudget, TestContext.Current.CancellationToken); + + // 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, + "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. + /// + [Fact] + public void A_stopped_incarnations_comms_loss_before_the_new_one_connects_still_stamps_Bad() + { + var oldDriver = new GatedProbeDriver(DriverId); + var newDriver = new GatedProbeDriver(DriverId); + var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + newDriver.InitializeGate = hold.Task; + var (host, publish) = Arrange(new SequenceDriverFactory(oldDriver, newDriver)); + publish.FishForMessage(_ => true, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + + host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid())); + + 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); + + // And the replacement's own push still recovers them. + hold.SetResult(); + var recovered = publish.FishForMessage(_ => true, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + recovered.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.Good); + } + + private (IActorRef Host, Akka.TestKit.TestProbe Publish) Arrange(IDriverFactory factory) + { + var db = NewInMemoryDbFactory(); + var deploymentId = SeedV3Deployment(db, RevA, + rawTags: new[] { (Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false) }, + unsRefs: new[] { (Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null) }, + enabled: true); + var (host, publish, _) = SpawnHostAndApply(this, db, TestNode, deploymentId, RevA, driverFactory: factory); + 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) + { + var statusBatches = 0; + publish.FishForMessage(m => + { + if (m is OpcUaPublishActor.AttributeStatusBatchUpdate s && s.Items.Any(i => i.NodeId == SpeedRef)) statusBatches++; + return m is OpcUaPublishActor.AttributeValueBatchUpdate; + }, budget, cancellationToken: TestContext.Current.CancellationToken); + return statusBatches; + } + + /// 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 pushes the same 5 Good on every subscribe and whose + /// can be made to block — a synchronous call on the owning child's mailbox + /// thread, so a blocked call holds that child's stop back. + /// + private sealed class GatedProbeDriver(string instanceId) : IDriver, ISubscribable, IHostConnectivityProbe + { + private readonly StubHandle _handle = new(); + private readonly ManualResetEventSlim _release = new(initialState: true); + private int _subscribeCount; + 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 int SubscribeCount => Volatile.Read(ref _subscribeCount); + + public bool ShutdownCalled => _shutdownCalled; + + public string DriverInstanceId => instanceId; + + public string DriverType => "Modbus"; + + 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 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) + { + Interlocked.Increment(ref _subscribeCount); + if (fullReferences.Contains(SpeedRef)) + { + var snapshot = new DataValueSnapshot(5.0, OpcUaStatus.Good, DateTime.UtcNow, DateTime.UtcNow); + OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, SpeedRef, snapshot)); + } + + return Task.FromResult(_handle); + } + + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) => Task.CompletedTask; + } +}