diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 00462c4c4..6999d8754 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -594,9 +594,14 @@ latched Bad, as a Warning naming the driver plus the `otopcua.driver.comms_latch a push driver missing its initial push, or a value-only dedup swallowing an unchanged value. It is a tripwire, not a repair: nothing downstream depends on it. -The latch and its audit timer belong to one driver incarnation: `StopChild` (a deploy removal, a disable, the stop half of -a config-change respawn) drops the latch and cancels the pending audit (R-16), so a removed driver never fires a false -Warning / counter increment and a disable then re-enable of the same id never inherits a stale latch. `StopChild` also +The latch and its audit timer belong to one driver incarnation: `StopChild` for a deploy removal or a disable drops the +latch and cancels the pending audit (R-16), so a removed driver never fires a false Warning / counter increment and a +disable then re-enable of the same id never inherits a stale latch. The stop half of a **config-change respawn** keeps it +instead (#1113 — it used to drop it, so a respawn of an already comms-lost driver was never audited, unlike a Restart): +the replacement is what must re-publish those refs. Every apply's reindex trims every outstanding latch to the refs the new +composition still routes for that driver (`TrimCommsLatchesToIndex`) — a ref the deploy dropped is no longer subscribed and +can never be re-published, so it must not be reported — and drops a latch left empty; this runs inside the same apply +message as the respawn, so before the replacement's `Connected` can arm the audit. `StopChild` also holds the id in the `ChildHealthLedger` (`Forget` then `Readmit` on the next spawn), so the stopped child's late health publish cannot resurrect its diagnostics entry. 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 552e83bea..fa1f482ee 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -2364,7 +2364,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn { if (!_commsLatched.TryGetValue(driverInstanceId, out var latched)) return; if (!latched.Remove(fullReference)) return; - if (latched.Count == 0) _commsLatched.Remove(driverInstanceId); + if (latched.Count == 0) ForgetCommsLatch(driverInstanceId); } /// @@ -2384,6 +2384,40 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn private static string CommsAuditTimerKey(string driverInstanceId) => $"comms-audit:{driverInstanceId}"; + /// Drops 's comms-loss latch. + /// The driver whose latch ends. + private void ForgetCommsLatch(string driverInstanceId) + { + _commsLatched.Remove(driverInstanceId); + } + + /// + /// Gitea #1113 item 2: trims every outstanding comms-loss latch to the value refs the just-rebuilt index still + /// routes for that driver, so a ref a deploy dropped (or a respawn's new composition no longer carries) can never + /// be reported by the recovery audit — it cannot re-publish a ref nobody subscribes it to. A latch left empty is + /// dropped. Runs after every reindex (), which is also where a + /// config-change respawn's kept latch () meets the new composition — before the new + /// incarnation's Connected can arm the audit, since both happen inside the same apply message. + /// + private void TrimCommsLatchesToIndex() + { + if (_commsLatched.Count == 0) return; + foreach (var driverId in _commsLatched.Keys.ToArray()) + { + var latched = _commsLatched[driverId]; + if (!_valueRefsByDriver.TryGetValue(driverId, out var entries) || entries.Count == 0) + { + ForgetCommsLatch(driverId); + continue; + } + + var current = new HashSet(entries.Count, StringComparer.Ordinal); + foreach (var (rawPath, _) in entries) current.Add(rawPath); + latched.IntersectWith(current); + if (latched.Count == 0) ForgetCommsLatch(driverId); + } + } + /// /// The 03/S15 tripwire firing: refs this host latched BadNoCommunication that the driver has /// still not re-published after it reconnected. @@ -2406,7 +2440,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn { if (!_commsLatched.TryGetValue(msg.DriverInstanceId, out var latched) || latched.Count == 0) { - _commsLatched.Remove(msg.DriverInstanceId); + ForgetCommsLatch(msg.DriverInstanceId); return; } @@ -2423,7 +2457,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _localNode, msg.DriverInstanceId, driverType, latched.Count, _commsRecoveryAuditDelay, latched.OrderBy(r => r, StringComparer.Ordinal).First()); - _commsLatched.Remove(msg.DriverInstanceId); + ForgetCommsLatch(msg.DriverInstanceId); } /// @@ -4503,6 +4537,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _dataWriteRuntime.Routes.ReplaceRoutes(mapped); } + // #1113 item 2: no comms latch may outlive the ref it names (a respawn's kept latch, or a kept driver's dropped ref). + TrimCommsLatchesToIndex(); + // Gitea #979 (review 2026-12-02 R-6): a value ref that left the composition (raw tag deleted or renamed, or its // driver removed) used to be only forgotten — a surviving VirtualTag / Calculation tag / scripted alarm that // still reads it kept computing Good from its last value. Tell the mux, which hands every dependent naming it @@ -5253,7 +5290,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // behind, a removed-while-comms-lost driver kept its whole RawPath set forever, a removal within the audit // window still fired a false Warning + otopcua.driver.comms_latched_refs increment, and a disable -> // re-enable of the same id inherited the stale latch. - _commsLatched.Remove(driverInstanceId); + // #1113 item 2: EXCEPT on a config-change respawn — like an operator Restart (#1053), the replacement is what + // must re-publish those refs, so the latch is kept for its Connected to audit. This apply's reindex trims it to + // the refs the new composition still carries (TrimCommsLatchesToIndex), so a dropped ref is never reported. + // The old incarnation's armed audit is cancelled either way. + if (!respawning) ForgetCommsLatch(driverInstanceId); Timers.Cancel(CommsAuditTimerKey(driverInstanceId)); _healthPublisher.Forget(driverInstanceId); _log.Info("DriverHost {Node}: stopped driver child {Id}", _localNode, driverInstanceId); 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 index 97ea762f6..e5864a500 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostRespawnValueNodeGapTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostRespawnValueNodeGapTests.cs @@ -151,11 +151,92 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase TestContext.Current.CancellationToken); } - private (IActorRef Host, TestProbe Publish, TestProbe Coordinator, Microsoft.EntityFrameworkCore.IDbContextFactory Db) - Arrange(GatedDriver oldDriver, GatedDriver newDriver) + // ---- #1113 item 2: a config-change respawn of a driver that was ALREADY comms-lost ---- + + /// Long enough that a test can fire the replacement's first value before the audit runs. + private static readonly TimeSpan LongAuditDelay = TimeSpan.FromSeconds(3); + + /// + /// #1113 item 2: a config-change respawn of a comms-lost driver KEEPS the latch (it used to be cleared, so the + /// replacement was never audited — unlike an operator Restart, #1053), trimmed to the refs the new composition + /// still carries. The new deployment drops flow and adds temp; the silent replacement is reported + /// for exactly speed — not flow (dropped: a false warning) and not temp (never latched). + /// + [Fact] + public void A_config_change_respawn_of_a_comms_lost_driver_audits_the_replacement_for_the_kept_refs_only() { - var db = NewInMemoryDbFactory(); - var deploymentId = SeedV3Deployment(db, RevA, + var oldDriver = new GatedDriver(DriverId); + var newDriver = new GatedDriver(DriverId); + var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver, LongAuditDelay); + SeedGoodFromOldDriver(oldDriver, publish); + using var meter = new MeterRecorder("otopcua.driver.comms_latched_refs"); + GoCommsLost(oldDriver, host, publish); + + EventFilter.Warning(contains: "1 ref(s) still BadNoCommunication").ExpectOne( + LongAuditDelay + PresenceBudget, + () => DispatchDroppingFlow(host, coordinator, db), + TestContext.Current.CancellationToken); + AwaitCondition(() => meter.SumWithTag("driver_instance", DriverId) == 1, TimeSpan.FromSeconds(5), + TestContext.Current.CancellationToken); + } + + /// + /// #1113 item 2, the other half: when the replacement re-publishes every KEPT ref, the audit is silent — the + /// dropped flow (no longer subscribed, so it can never be re-published) is trimmed from the latch. + /// Without the trim this reported flow; without the kept latch the test above stays silent. + /// + [Fact] + public void A_ref_dropped_by_the_respawning_deploy_never_raises_a_false_audit_warning() + { + var oldDriver = new GatedDriver(DriverId); + var newDriver = new GatedDriver(DriverId); + var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver, LongAuditDelay); + SeedGoodFromOldDriver(oldDriver, publish); + using var meter = new MeterRecorder("otopcua.driver.comms_latched_refs"); + GoCommsLost(oldDriver, host, publish); + + DispatchDroppingFlow(host, coordinator, db); + AwaitFinalSubscribe(newDriver, configChange: true); + newDriver.Fire(SpeedRef, 11.0); + + EventFilter.Warning(contains: "ref(s) still") + .Expect(0, LongAuditDelay + TimeSpan.FromSeconds(2), () => { }, TestContext.Current.CancellationToken); + meter.SumWithTag("driver_instance", DriverId).ShouldBe(0); + } + + /// Takes the old driver comms-lost (Force Reconnect with its re-initialise held forever) and waits for the + /// host's latched BadNoCommunication stamp. + private static void GoCommsLost(GatedDriver oldDriver, IActorRef host, TestProbe publish) + { + oldDriver.InitializeGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously).Task; + host.Tell(new ReconnectDriver("c1", DriverId, "test-operator", Guid.NewGuid())); + var outage = publish.FishForMessage( + s => s.Items.Any(i => i.NodeId == SpeedRef), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + outage.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadNoCommunication); + } + + /// A config change that keeps speed, DROPS flow (and its UNS mirror) and adds temp. + private static void DispatchDroppingFlow(IActorRef host, TestProbe coordinator, + Microsoft.EntityFrameworkCore.IDbContextFactory db) + { + 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: "temp", DataType: "Double", Writable: false), + ], + unsRefs: + [ + (Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null), + ], + enabled: true); + Dispatch(host, coordinator, revB, RevB); + } + + private static DeploymentId SeedTwoTagDeployment( + Microsoft.EntityFrameworkCore.IDbContextFactory db) => + SeedV3Deployment(db, RevA, rawTags: [ (Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false), @@ -167,8 +248,14 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase (Area: "filling", Line: "line1", Equip: "station1", BackingTag: "flow", Effective: (string?)null), ], enabled: true); + + private (IActorRef Host, TestProbe Publish, TestProbe Coordinator, Microsoft.EntityFrameworkCore.IDbContextFactory Db) + Arrange(GatedDriver oldDriver, GatedDriver newDriver, TimeSpan? auditDelay = null) + { + var db = NewInMemoryDbFactory(); + var deploymentId = SeedTwoTagDeployment(db); var (host, publish, _, coordinator) = SpawnHostAndApplyWithCoordinator(this, db, TestNode, deploymentId, RevA, - driverFactory: new SequenceDriverFactory(oldDriver, newDriver), commsRecoveryAuditDelay: AuditDelay); + driverFactory: new SequenceDriverFactory(oldDriver, newDriver), commsRecoveryAuditDelay: auditDelay ?? AuditDelay); AwaitAssert(() => (oldDriver.LastSubscribedRefs ?? []).ShouldContain(SpeedRef), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); return (host, publish, coordinator, db);