From c28e5564d71ab3a00e8476c83202fb5421829991 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Fri, 4 Dec 2026 22:27:46 -0500 Subject: [PATCH] fix(runtime): #1109 a respawn/Restart tells mux dependents the ref is not Good itself, instead of racing the stopped child MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #1041 relied on the stopped child's PostStop ConnectivityChanged(false) to hand dependency-mux dependents (VTs, scripted alarms, Calculation) BadNoCommunication until the new driver object publishes. #1070 later (correctly) drops that announcement once the replacement has connected — and the two children's messages are unordered, so whenever the old child reaches its stop late (busy in a synchronous driver call, or a loaded dispatcher) the Bad edge was dropped and dependents kept the stopped object's last Good until the new driver published: indefinitely for an on-change source that does not republish an unchanged value. That is the #1109 flake (and its operator-Restart sibling): pre-fix 15 of 30 CPU-stressed runs of the two #1041 tests failed at the gap FishForMessage (11 config-change, 8 Restart); post-fix 30/30 pass. StopChild and HandleRestartDriver 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 never retained/replayed). Value nodes keep the #1070 rule. DriverHostRespawnDependentGapTests makes the interleaving deterministic (old child wedged in GetHostStatuses until the replacement subscribed), for both legs; mutation-checked — it fails in ~3 s with the fan removed. --- .claude/rules/drivers.md | 6 +- docs/DriverLifecycle.md | 9 + .../Drivers/DriverHostActor.cs | 32 ++- .../DriverHostRespawnDependentGapTests.cs | 203 ++++++++++++++++++ 4 files changed, 248 insertions(+), 2 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostRespawnDependentGapTests.cs diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index 5b44d4008..b8f9fbad8 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -143,7 +143,11 @@ non-`Healthy` state **and** its `LastSuccessfulRead` has been frozen for 90 s. T 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`. + 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`. - **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 5b05714ec..42560c56d 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -614,6 +614,15 @@ A retired child's Bad edge is still applied while the replacement has not connec cover above. 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 +hand dependency-mux dependents (virtual tags, scripted alarms, Calculation) a non-Good input until the new driver object +publishes. With the rule above that edge is dropped whenever the replacement connects first, which left dependents computing +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). + ### 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 6bf55fbb0..8b1c69686 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -5101,6 +5101,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn WithdrawDriverConditionsKnown(driverInstanceId); ForgetConditionSignals(driverInstanceId); PublishAckPreflight(); + TellDependentsDriverObjectEnded(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 @@ -5146,6 +5147,34 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn private void EvictRetainedValues(string driverInstanceId) => _dependencyMux?.Tell(new DependencyMuxActor.SourceRemoved(driverInstanceId)); + /// + /// Gitea #1109 — hands every dependent of 's value refs + /// the moment the host ends the driver OBJECT (config-change + /// respawn, operator Restart, deploy removal), so no dependent keeps computing from the stopped object's last + /// Good until the replacement publishes. + /// + /// + /// + /// This gap used to be covered only by the stopped child's own PostStop + /// ConnectivityChanged(false) (#1041). That announcement races the replacement: Context.Stop is + /// asynchronous, two children's messages are not ordered, and a child busy in a synchronous driver call (or + /// a loaded dispatcher) reaches its stop late. Once the replacement has connected, #1070 rightly drops the + /// late announcement () — which left dependents on the old Good, + /// indefinitely for an on-change source that never republishes an unchanged value. Sent HERE, on the + /// 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 + /// 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. + /// + /// + /// The driver instance whose object ended. + private void TellDependentsDriverObjectEnded(string driverInstanceId) => FanCommsLossToDependencyMux(driverInstanceId); + /// 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) @@ -5247,7 +5276,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn Context.Stop(entry.Actor); _children.Remove(msg.DriverInstanceId); // 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. + // removal's; the respawned driver republishes its own. Dependents are told first (#1109). + TellDependentsDriverObjectEnded(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/DriverHostRespawnDependentGapTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostRespawnDependentGapTests.cs new file mode 100644 index 000000000..5c238c627 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostRespawnDependentGapTests.cs @@ -0,0 +1,203 @@ +using Akka.Actor; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Engines; +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.Configuration; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +/// +/// #1109 — a respawn's "not Good until the new driver publishes" gap must not depend on the stopped child's +/// timing. +/// +/// #1041 relied on the stopped child's PostStop ConnectivityChanged(false) to hand dependents +/// BadNoCommunication while the new driver object has not published. #1070 then (correctly) drops that +/// announcement once the replacement has connected. Messages from two children are not ordered, so when the old +/// child reaches its stop late (busy in a synchronous driver call, or just a loaded dispatcher) the replacement +/// connects first, the Bad edge is dropped, and every dependent keeps computing from the stopped object's last +/// Good until the new driver happens to publish — which for an on-change source can be never. That is the +/// interleaving behind the intermittent failure of +/// DriverHostActorSourceRemovedTests.A_config_change_respawn_tells_dependents_the_ref_is_not_Good_until_the_new_driver_publishes. +/// +/// +/// Made deterministic here the way does: the old driver's +/// (called synchronously on the child's mailbox thread) +/// blocks until the replacement has connected and subscribed, then the old child is released. +/// +/// +public sealed class DriverHostRespawnDependentGapTests : RuntimeActorTestBase +{ + private static readonly NodeId TestNode = NodeId.Parse("driver-respawn-gap-test"); + private static readonly RevisionHash RevA = RevisionHash.Parse(new string('c', 64)); + private static readonly RevisionHash RevB = RevisionHash.Parse(new string('d', 64)); + private const string DriverId = "DI-1"; + private const string Path1 = "Plant/Modbus/dev1/speed"; + private static readonly (string, string, string, string, string?)[] NoRefs = []; + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void A_late_stopping_old_child_still_leaves_dependents_a_non_Good_gap(bool configChange) + { + var oldDriver = new GatedDriver(DriverId); + var newDriver = new GatedDriver(DriverId); + var db = NewInMemoryDbFactory(); + var revA = V3ArtifactSeeder.SeedV3Deployment(db, RevA, + [(DriverId, "Modbus", "dev1", "speed", "Double", false)], NoRefs, enabled: true); + var mux = Sys.ActorOf(DependencyMuxActor.Props()); + var coordinator = CreateTestProbe(); + var holder = CreateTestProbe(); + var host = Sys.ActorOf(DriverHostActor.Props( + db, TestNode, coordinator.Ref, + driverFactory: new SequenceDriverFactory(oldDriver, newDriver), + localRoles: new HashSet { "driver" }, + dependencyMux: mux, + virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: CreateTestProbe().Ref)); + V3ArtifactSeeder.Dispatch(host, coordinator, revA, RevA); + AwaitAssert(() => (oldDriver.LastSubscribedRefs ?? []).ShouldContain(Path1), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + + mux.Tell(new DependencyMuxActor.RegisterInterest(new[] { Path1 }, holder.Ref, ReplayRetained: true)); + oldDriver.Fire(Path1, 11.0); + holder.FishForMessage( + b => b.Items.Any(i => i.TagId == Path1 && Equals(i.Value, 11.0) && OpcUaStatus.IsGood(i.StatusCode)), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + + // Wedge the old child's mailbox thread inside a synchronous driver call, so it cannot process its stop. + oldDriver.BlockHostStatuses(); + oldDriver.RaiseHostStatusChanged(); + oldDriver.HostStatusesEntered.Wait(PresenceBudget, TestContext.Current.CancellationToken) + .ShouldBeTrue("the old child must be parked inside GetHostStatuses before the respawn"); + + if (configChange) + { + var revB = V3ArtifactSeeder.SeedV3Deployment(db, RevB, + [(DriverId, "Modbus", "dev1", "speed", "Double", false), (DriverId, "Modbus", "dev1", "temp", "Double", false)], + NoRefs, enabled: true); + V3ArtifactSeeder.Dispatch(host, coordinator, revB, RevB); + } + else + { + host.Tell(new RestartDriver("c1", DriverId, "tester", Guid.NewGuid())); + } + + // The replacement connects and subscribes while the old child is still wedged. A config-change spawn hands + // the child the PREVIOUS apply's set and the bulk push then re-subscribes with the new one; a value fired + // between the two can be lost, so wait for the final set (it names the added tag). + var finalRef = configChange ? "Plant/Modbus/dev1/temp" : Path1; + AwaitAssert(() => (newDriver.LastSubscribedRefs ?? []).ShouldContain(finalRef), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + + // Release the old child: its PostStop announces comms loss and THEN shuts the driver down, so once + // ShutdownAsync ran that (now stale) announcement is already in the host's mailbox. + oldDriver.ReleaseHostStatuses(); + AwaitCondition(() => oldDriver.ShutdownCalled, PresenceBudget, TestContext.Current.CancellationToken); + + // The new driver's first value — the IDENTICAL value, so only a status edge in between can show the gap. + newDriver.Fire(Path1, 11.0); + var sawGap = false; + holder.FishForMessage(b => + { + foreach (var i in b.Items.Where(i => i.TagId == Path1)) + { + if (!OpcUaStatus.IsGood(i.StatusCode)) sawGap = true; + else if (Equals(i.Value, 11.0)) return true; + } + return false; + }, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + sawGap.ShouldBeTrue("dependents kept the stopped driver object's last Good until the new one published"); + } + + /// 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, and whose can be + /// made to block the owning child's mailbox thread. + 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 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) => Task.CompletedTask; + public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask; + + public Task ShutdownAsync(CancellationToken cancellationToken) + { + _shutdownCalled = true; + return Task.CompletedTask; + } + + 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; + } +}