From 5ef8089e1ff802d64ab716d60e3a908037a53ff6 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 5 Dec 2026 03:01:51 -0500 Subject: [PATCH 1/5] fix(runtime): #1113 pin that the gRPC origin hub never serves a stopped driver's last Good across a respawn/Restart Item 1. Projected consumers (DataConnectionService read/subscribe) do not read OPC UA node state; they read PartitionedSampleHub, fed by the driver callback through SourceSamplePublisher. It is already covered by the producer fence: StopChild / HandleRestartDriver call RetireCurrentDriver at the stop (sources removed, cache released, readiness Invalidated) and the replacement's first value binds a fresh generation. No product change; GrpcDataRespawnOriginGapTests pins it end-to-end through DriverHostActor for both seams (Restart variant fails with both fences removed). Docs: DriverLifecycle.md. --- docs/DriverLifecycle.md | 9 + .../Drivers/GrpcDataRespawnOriginGapTests.cs | 163 ++++++++++++++++++ 2 files changed, 172 insertions(+) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataRespawnOriginGapTests.cs diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index d279e4be6..00462c4c4 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -642,6 +642,15 @@ supervision restart (same driver object — unchanged, still covered by that chi 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 gRPC data plane's origin side is covered by the producer fence, not by this stamp (#1113).** Projected consumers + (DataConnectionService read / subscribe) do not read the OPC UA node state: they read the `PartitionedSampleHub`, fed + by the driver callback through `SourceSamplePublisher`. `StopChild` / `HandleRestartDriver` call + `RetireCurrentDriver` at the stop, which removes every one of the driver's sources (cached sample released, readiness + `Invalidated`), and spawning the replacement registers a new incarnation (retiring the old fence a second time). Until the + replacement's first value binds a fresh generation there is no current source — a read answers `WaitingForInitialData`, + the old ticket reads not-ready — so the stopped object's last Good is never served there either. Pinned by + `GrpcDataRespawnOriginGapTests` (both seams). + ### The connect path feeds the circuit breaker (R2-10 T10 closure) `IDriver.InitializeAsync` is routed through the capability invoker as diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataRespawnOriginGapTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataRespawnOriginGapTests.cs new file mode 100644 index 000000000..bed912237 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataRespawnOriginGapTests.cs @@ -0,0 +1,163 @@ +using Akka.Actor; +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.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +/// +/// #1113 item 1 — the gRPC data plane's origin side across a driver-object change. Projected consumers +/// (DataConnectionService read / subscribe) are NOT served from the OPC UA node state: they read the +/// , a value cache of its own that the driver's callback feeds through +/// . So #1112's node stamp does not reach them — this pins that they are covered +/// by the producer fence instead: StopChild / HandleRestartDriver call +/// at the stop, which removes every one of the driver's +/// sources (cache released, readiness ), and the replacement's first value +/// binds a fresh generation. Between the two, the stopped object's last Good is never served: there is no current +/// source (a read answers ) and the old ticket reads not-ready. +/// +[Trait("Feature", "GrpcData"), Trait("Category", "Unit")] +public sealed class GrpcDataRespawnOriginGapTests : RuntimeActorTestBase +{ + private const string DriverId = "DI-1"; + private const string SpeedRef = "Plant/Modbus/dev1/speed"; + private const string TempRef = "Plant/Modbus/dev1/temp"; + private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64)); + private static readonly RevisionHash RevB = RevisionHash.Parse(new string('b', 64)); + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void The_origin_hub_never_serves_the_stopped_drivers_last_Good_until_the_replacement_publishes(bool configChange) + { + var db = NewInMemoryDbFactory(); + var deploy = V3ArtifactSeeder.SeedV3Deployment(db, RevA, + [(DriverId, "Modbus", "dev1", "speed", "Double", false)], [], enabled: true); + var oldDriver = new FiringDriver(); + var newDriver = new FiringDriver(); + var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + newDriver.InitializeGate = hold.Task; + using var hub = HubTest.Create(); + var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1)); + var coordinator = CreateTestProbe(); + var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref, + driverFactory: new SequenceFactory(oldDriver, newDriver), localRoles: new HashSet { "driver" }, + dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, + acquisitionCapacity: new SubscriptionAcquisitionCapacity(8))); + V3ArtifactSeeder.Dispatch(host, coordinator, deploy, RevA); + AwaitAssert(() => oldDriver.Subscribed.ShouldContain(SpeedRef), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + + // The old driver object's Good reaches the origin hub. + oldDriver.Fire(SpeedRef, 11.0); + SourceTicket oldTicket = default; + AwaitAssert(() => + { + publisher.TryCaptureDriver(DriverId, SpeedRef, out oldTicket).ShouldBeTrue(); + hub.ProcessPending(); + using var read = hub.Read(oldTicket); + read.Readiness.ShouldBe(DataReadiness.Ready); + read.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(11.0); + }, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var key = oldTicket.Key; + + if (configChange) + { + var revB = V3ArtifactSeeder.SeedV3Deployment(db, RevB, + [(DriverId, "Modbus", "dev1", "speed", "Double", false), (DriverId, "Modbus", "dev1", "temp", "Double", false)], + [], enabled: true); + V3ArtifactSeeder.Dispatch(host, coordinator, revB, RevB); + } + else host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid())); + + // The replacement cannot publish (its initialise is held): what a consumer sees now is the whole gap. + AwaitAssert(() => + { + hub.ProcessPending(); + using (var stale = hub.Read(oldTicket)) stale.Readiness.ShouldNotBe(DataReadiness.Ready); + if (hub.TryGetCurrentTicket(key, out var current)) + { + using var read = hub.Read(current); + read.Readiness.ShouldNotBe(DataReadiness.Ready, "no current source may serve the stopped object's Good"); + } + }, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + publisher.TryCaptureDriver(DriverId, SpeedRef, out _).ShouldBeFalse("the stopped producer's sources are retired"); + + // The replacement's first value — the IDENTICAL value — is what makes the origin Good again. + hold.SetResult(); + AwaitAssert(() => newDriver.Subscribed.ShouldContain(configChange ? TempRef : SpeedRef), PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + newDriver.Fire(SpeedRef, 11.0); + AwaitAssert(() => + { + hub.ProcessPending(); + hub.TryGetCurrentTicket(key, out var current).ShouldBeTrue(); + current.ShouldNotBe(oldTicket); + using var read = hub.Read(current); + read.Readiness.ShouldBe(DataReadiness.Ready); + read.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(11.0); + read.Sample.StatusCode.ShouldBe(OpcUaStatus.Good); + }, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + /// Hands out the given drivers in order, one per spawn (the last one repeats). + private sealed class SequenceFactory(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 initialise can be held. + private sealed class FiringDriver : IDriver, ISubscribable + { + private readonly StubHandle _handle = new(); + private readonly Lock _gate = new(); + private IReadOnlyList _subscribed = []; + + public event EventHandler? OnDataChange; + + public Task? InitializeGate { get; set; } + public string DriverInstanceId => DriverId; + public string DriverType => "Modbus"; + + public IReadOnlyList Subscribed + { + get { lock (_gate) return _subscribed; } + } + + public void Fire(string fullReference, object value) => + OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, fullReference, + new DataValueSnapshot(value, OpcUaStatus.Good, DateTime.UtcNow, DateTime.UtcNow))); + + 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) => Task.CompletedTask; + public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null); + + public Task SubscribeAsync( + IReadOnlyList fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken) + { + lock (_gate) _subscribed = fullReferences.ToArray(); + return Task.FromResult(_handle); + } + + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) => Task.CompletedTask; + } +} From 77adf410df3144cbe72d5effec6bd5f26c8ed8b4 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 5 Dec 2026 03:03:43 -0500 Subject: [PATCH 2/5] fix(runtime): #1113 a config-change respawn keeps the comms latch, trimmed to the refs the new composition still routes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Item 2. StopChild cleared the comms-loss latch unconditionally, so a config-change respawn of an already comms-lost driver never audited its replacement (an operator Restart does, #1053). StopChild(respawning: true) now keeps it; every apply's reindex trims every outstanding latch to the refs still routed for that driver (TrimCommsLatchesToIndex) and drops an emptied one, so a ref the deploy dropped (no longer subscribed, cannot be re-published) never raises a false audit Warning. Both run inside the same apply message, before the replacement's Connected can arm the audit. Tests: DriverHostRespawnValueNodeGapTests — kept latch audits the silent replacement for exactly the kept ref (fails if the latch is cleared or not trimmed), and a replacement re-publishing every kept ref stays silent (fails without the trim). --- docs/DriverLifecycle.md | 11 ++- .../Drivers/DriverHostActor.cs | 49 +++++++++- .../DriverHostRespawnValueNodeGapTests.cs | 97 ++++++++++++++++++- 3 files changed, 145 insertions(+), 12 deletions(-) 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); From 4a5407f88fb7e0f9c3667c6ce4941f93bd6f2ca3 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 5 Dec 2026 03:05:35 -0500 Subject: [PATCH 3/5] fix(runtime): #1113 the comms-recovery audit names the status the latched nodes actually carry Item 3. After a respawn / Restart re-stamped a comms-lost driver's nodes BadWaitingForInitialData (#1112), the kept-latch audit still said the refs were 'still BadNoCommunication'. The host now records that the latched nodes were re-stamped (_commsLatchReplaced; cleared with the latch and by a fresh comms-loss stamp) and the Warning reads 'still BadWaitingForInitialData' in that case, 'still BadNoCommunication' otherwise. Tests: new Restart-of-a-comms-lost-driver case; the #1053 Restart test and the item-2 test expect the new wording; the no-audit absence checks match any 'ref(s) still' so they cannot pass vacuously on the wording change. --- docs/DriverLifecycle.md | 4 ++- .../Drivers/DriverHostActor.cs | 30 ++++++++++++++++--- .../DriverHostCommsLossRecoveryTests.cs | 7 +++-- .../DriverHostRespawnValueNodeGapTests.cs | 26 ++++++++++++++-- 4 files changed, 56 insertions(+), 11 deletions(-) diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 6999d8754..c75b2d9aa 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -601,7 +601,9 @@ instead (#1113 — it used to drop it, so a respawn of an already comms-lost dri 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 +message as the respawn, so before the replacement's `Connected` can arm the audit. The Warning names the status the nodes +actually carry: `still BadNoCommunication`, or `still BadWaitingForInitialData` once a respawn / Restart re-stamped them +(#1113). `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 fa1f482ee..bdef19b95 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -689,6 +689,14 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn /// private readonly Dictionary> _commsLatched = new(StringComparer.Ordinal); + /// + /// Gitea #1113 item 3: drivers whose refs were re-stamped + /// by a respawn / Restart after the comms-loss stamp + /// (), so the recovery audit names the status those nodes + /// actually carry. Cleared with the latch and by a fresh comms-loss stamp. + /// + private readonly HashSet _commsLatchReplaced = new(StringComparer.Ordinal); + /// Per-driver rate limit for the supervision-reprovision hook (see /// ). private readonly TimeSpan _reprovisionBackoff; @@ -2348,6 +2356,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn var latched = new HashSet(entries.Count, StringComparer.Ordinal); foreach (var (rawPath, _) in entries) latched.Add(rawPath); _commsLatched[driverInstanceId] = latched; + // The nodes carry BadNoCommunication again, whatever a respawn stamped before. + _commsLatchReplaced.Remove(driverInstanceId); // A previous reconnect's audit is now meaningless — this driver is down again. Timers.Cancel(CommsAuditTimerKey(driverInstanceId)); @@ -2384,11 +2394,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn private static string CommsAuditTimerKey(string driverInstanceId) => $"comms-audit:{driverInstanceId}"; - /// Drops 's comms-loss latch. + /// Drops 's comms-loss latch and its replaced marker. /// The driver whose latch ends. private void ForgetCommsLatch(string driverInstanceId) { _commsLatched.Remove(driverInstanceId); + _commsLatchReplaced.Remove(driverInstanceId); } /// @@ -2444,6 +2455,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn return; } + // #1113 item 3: a respawn / Restart since the outage re-stamped those nodes awaiting-first-value — name the + // status they actually carry. + var latchedStatus = _commsLatchReplaced.Contains(msg.DriverInstanceId) + ? nameof(OpcUaStatus.BadWaitingForInitialData) + : nameof(OpcUaStatus.BadNoCommunication); + var driverType = _children.TryGetValue(msg.DriverInstanceId, out var child) ? child.DriverType : "unknown"; OtOpcUaTelemetry.DriverCommsLatchedRefs.Add( latched.Count, @@ -2451,11 +2468,14 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn new KeyValuePair("driver_type", driverType)); _log.Warning( - "DriverHost {Node}: driver {Driver} ({Type}) — {Count} ref(s) still BadNoCommunication {Delay} after reconnect; " + "DriverHost {Node}: driver {Driver} ({Type}) — {Count} ref(s) still {Status} {Delay} after reconnect; " + "the driver did not re-publish them (missing initial push, or a value-only dedup swallowed an unchanged value). " + "First: {First}", - _localNode, msg.DriverInstanceId, driverType, latched.Count, _commsRecoveryAuditDelay, - latched.OrderBy(r => r, StringComparer.Ordinal).First()); + new object[] + { + _localNode, msg.DriverInstanceId, driverType, latched.Count, latchedStatus, _commsRecoveryAuditDelay, + latched.OrderBy(r => r, StringComparer.Ordinal).First(), + }); ForgetCommsLatch(msg.DriverInstanceId); } @@ -5391,6 +5411,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn if (writes.Count == 0) return; _opcUaPublishActor.Tell(new OpcUa.OpcUaPublishActor.AttributeStatusBatchUpdate(writes)); + // #1113 item 3: an outstanding comms latch now names nodes carrying THIS status, not BadNoCommunication. + if (_commsLatched.ContainsKey(driverInstanceId)) _commsLatchReplaced.Add(driverInstanceId); _log.Info( "DriverHost {Node}: driver {Driver} object replaced — {Count} value node(s) marked BadWaitingForInitialData until its first value", _localNode, driverInstanceId, writes.Count); 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 cf3a39c83..51202f185 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 @@ -192,12 +192,13 @@ public sealed class DriverHostCommsLossRecoveryTests : RuntimeActorTestBase driver.InitializeGate = release.Task; host.Tell(new RestartDriver("c1", "drv-restart", "test-operator", Guid.NewGuid())); - EventFilter.Warning(contains: "still BadNoCommunication") + EventFilter.Warning(contains: "ref(s) still") .Expect(0, audit + TimeSpan.FromSeconds(3), () => { }, TestContext.Current.CancellationToken); meter.SumWithTag("driver_instance", "drv-restart").ShouldBe(0); - // The new incarnation connects, re-subscribes silently, and its own audit reports the ref the restart kept. - EventFilter.Warning(contains: "still BadNoCommunication").ExpectOne(audit + ReconnectBudget, () => + // The new incarnation connects, re-subscribes silently, and its own audit reports the ref the restart kept — + // naming the status the Restart re-stamped (#1112), not BadNoCommunication (#1113 item 3). + EventFilter.Warning(contains: "1 ref(s) still BadWaitingForInitialData").ExpectOne(audit + ReconnectBudget, () => { driver.InitializeGate = null; release.SetResult(); 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 e5864a500..3618f5293 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 @@ -138,7 +138,7 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase // 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") + EventFilter.Warning(contains: "ref(s) still") .Expect(0, AuditDelay + TimeSpan.FromSeconds(2), () => { }, TestContext.Current.CancellationToken); meter.SumWithTag("driver_instance", DriverId).ShouldBe(0); @@ -151,7 +151,7 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase TestContext.Current.CancellationToken); } - // ---- #1113 item 2: a config-change respawn of a driver that was ALREADY comms-lost ---- + // ---- #1113 items 2 + 3: a respawn / Restart 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); @@ -161,6 +161,7 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase /// 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). + /// Item 3: the warning names the status the nodes carry, BadWaitingForInitialData. /// [Fact] public void A_config_change_respawn_of_a_comms_lost_driver_audits_the_replacement_for_the_kept_refs_only() @@ -172,7 +173,7 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase using var meter = new MeterRecorder("otopcua.driver.comms_latched_refs"); GoCommsLost(oldDriver, host, publish); - EventFilter.Warning(contains: "1 ref(s) still BadNoCommunication").ExpectOne( + EventFilter.Warning(contains: "1 ref(s) still BadWaitingForInitialData").ExpectOne( LongAuditDelay + PresenceBudget, () => DispatchDroppingFlow(host, coordinator, db), TestContext.Current.CancellationToken); @@ -204,6 +205,25 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase meter.SumWithTag("driver_instance", DriverId).ShouldBe(0); } + /// + /// #1113 item 3: an operator Restart keeps the latch (#1053), but the Restart re-stamped the nodes + /// BadWaitingForInitialData (#1112) — so the audit must not claim they are "still BadNoCommunication". + /// + [Fact] + public void A_restart_of_a_comms_lost_driver_audit_names_the_awaiting_first_value_status() + { + var oldDriver = new GatedDriver(DriverId); + var newDriver = new GatedDriver(DriverId); + var (host, publish, _, _) = Arrange(oldDriver, newDriver, LongAuditDelay); + SeedGoodFromOldDriver(oldDriver, publish); + GoCommsLost(oldDriver, host, publish); + + EventFilter.Warning(contains: "2 ref(s) still BadWaitingForInitialData").ExpectOne( + LongAuditDelay + PresenceBudget, + () => host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid())), + TestContext.Current.CancellationToken); + } + /// 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) From 399deea32fd24e3d870e19d7f63ed30b04d82b12 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 5 Dec 2026 03:05:41 -0500 Subject: [PATCH 4/5] fix(runtime): #1113 a stubbed driver's value nodes read BadConfigurationError, not BadWaitingForInitialData forever Item 4. A stub child (no factory for the type, a factory that rejected the config, or a type not allowed on the node's roles) never publishes, so its nodes sat at BadWaitingForInitialData forever. StampStubbedDriverValueNodes stamps BadConfigurationError (new OpcUaStatus constant, 0x80890000) on the raw + UNS value nodes of every stubbed child after each apply's RebuildAddressSpace Tell (deploy, boot-from-cache, bootstrap restore) - same host->publish-actor pair, so the publish actor defers it behind that plan and replays it onto the nodes the apply (re)creates - and after an operator Restart into a stub. A config-change respawn into a stub gets the respawn's BadWaitingForInitialData first, then this. Status-only, not latched; a stub drops any inherited latch. Tests: Restart + config-change into a stub, and a fresh deploy of a stub (all fail with the stamp disabled). --- docs/DriverLifecycle.md | 9 ++- .../OpcUa/OpcUaStatus.cs | 6 ++ .../Drivers/DriverHostActor.cs | 53 +++++++++++++++++ .../DriverHostRespawnValueNodeGapTests.cs | 57 ++++++++++++++++++- 4 files changed, 121 insertions(+), 4 deletions(-) diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index c75b2d9aa..49a580cd2 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -603,7 +603,7 @@ composition still routes for that driver (`TrimCommsLatchesToIndex`) — a ref t 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. The Warning names the status the nodes actually carry: `still BadNoCommunication`, or `still BadWaitingForInitialData` once a respawn / Restart re-stamped them -(#1113). `StopChild` also +(#1113). A stub replacement drops the latch (it never connects, so the audit could never arm). `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. @@ -649,6 +649,13 @@ supervision restart (same driver object — unchanged, still covered by that chi 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). +- **A stub replacement reads `BadConfigurationError` (#1113).** When the replacement (or a freshly deployed driver) is a + STUB — no factory for its type on this node, the factory rejected its config, or the type is not allowed on the node's + roles — it never publishes, so `BadWaitingForInitialData` would be a promise that cannot be kept. + `StampStubbedDriverValueNodes` stamps `BadConfigurationError` on the raw + UNS value nodes of every stubbed child after + each apply's `RebuildAddressSpace` Tell (deploy, boot-from-cache, bootstrap restore — on the same host→publish-actor pair, + so the publish actor defers it behind that plan and replays it onto the nodes the apply creates or recreates; re-sent every + apply because a rebuild resets them) and after an operator Restart that respawned a stub. Status-only, not latched. - **The gRPC data plane's origin side is covered by the producer fence, not by this stamp (#1113).** Projected consumers (DataConnectionService read / subscribe) do not read the OPC UA node state: they read the `PartitionedSampleHub`, fed by the driver callback through `SourceSamplePublisher`. `StopChild` / `HandleRestartDriver` call diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/OpcUaStatus.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/OpcUaStatus.cs index d8531a5cb..7f6185b4a 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/OpcUaStatus.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/OpcUaStatus.cs @@ -58,6 +58,12 @@ public static class OpcUaStatus /// (lmxopcua#787) — distinct from , which means the tag's own script failed. public const uint BadOutOfService = 0x808D0000; + /// The source is misconfigured and will produce nothing until the configuration changes. The status a + /// driver's value nodes carry while that driver runs as a STUB — its type has no factory on this node, the factory + /// rejected its config, or the type is not allowed on the node's roles (lmxopcua#1113) — instead of + /// , which would promise a first value that can never come. + public const uint BadConfigurationError = 0x80890000; + /// Part 4 severity bucket of : the top two bits. /// The status code to classify. /// 0 for Good, 1 for Uncertain, 2 or 3 for Bad. 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 bdef19b95..2f980b355 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -1853,6 +1853,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _opcUaPublishActor?.Tell( new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, blob, CatalogAttempt: _catalogAttempt, ArtifactRevision: ArtifactRevisionOf(blob))); + StampStubbedDriverValueNodes(); if (_opcUaPublishActor is null && _catalogAttempt is not null) _catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: true); return true; @@ -3628,6 +3629,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace( msg.Correlation, msg.DeploymentId, appliedBlob, ReportOutcome: true, CatalogAttempt: _catalogAttempt, ArtifactRevision: ArtifactRevisionOf(appliedBlob))); + // #1113 item 4: after the rebuild Tell, so it is replayed onto the nodes this apply (re)creates. + StampStubbedDriverValueNodes(); // Reaching here means the artifact came from central, so the node is no longer serving a // cache-sourced configuration. Note this only clears on a real apply: a dispatch of the // revision already booted from cache short-circuits in HandleDispatchFromSteady without @@ -4333,6 +4336,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn CacheAppliedArtifact(deploymentId, rev, appliedBlob); _opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, appliedBlob, CatalogAttempt: _catalogAttempt, ArtifactRevision: ArtifactRevisionOf(appliedBlob))); + if (appliedBlob is not null) StampStubbedDriverValueNodes(); _log.Info("DriverHost {Node}: restored served state for applied deployment {Id} on bootstrap", _localNode, deploymentId); } catch (Exception ex) @@ -5418,6 +5422,53 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _localNode, driverInstanceId, writes.Count); } + /// + /// Gitea #1113 item 4 — stamps on every raw NodeId and every + /// referencing UNS NodeId of each STUBBED child (or only ): a stub (no + /// factory for the type, a factory that rejected the config, or a type not allowed on this node's roles) never + /// publishes, so its nodes would otherwise sit at forever — + /// a promise of a first value that cannot come. + /// + /// + /// + /// Called after each apply's Tell (deploy, boot from + /// cache, bootstrap restore) on the same host→publish-actor pair, so the publish actor has already started + /// that plan: the write lands on the nodes that exist now AND is deferred and replayed onto the nodes the apply + /// creates or recreates (a fresh deploy, a rebuild) — re-sent every apply because a rebuild resets them. And + /// after an operator Restart that respawned a stub. A config-change respawn into a stub gets the respawn's + /// BadWaitingForInitialData first (at the stop), then this. + /// + /// + /// Status-only and not a comms loss: nothing is latched. A latch the previous incarnation left (a respawn + /// of a comms-lost driver, #1113 item 2) is dropped — a stub never connects, so its audit could never arm. + /// + /// + /// Restrict to this driver; for every stubbed child. + private void StampStubbedDriverValueNodes(string? onlyDriverInstanceId = null) + { + if (_opcUaPublishActor is null) return; + List? writes = null; + DateTime ts = default; + foreach (var (driverId, child) in _children) + { + if (!child.Stubbed) continue; + if (onlyDriverInstanceId is not null && !string.Equals(driverId, onlyDriverInstanceId, StringComparison.Ordinal)) continue; + ForgetCommsLatch(driverId); + if (!_valueRefsByDriver.TryGetValue(driverId, out var entries) || entries.Count == 0) continue; + if (writes is null) { writes = new List(); ts = DateTime.UtcNow; } + var before = writes.Count; + foreach (var (_, nodes) in entries) + foreach (var n in nodes) + writes.Add(new StatusWrite(n.NodeId, OpcUaStatus.BadConfigurationError, ts, n.Realm)); + _log.Info( + "DriverHost {Node}: driver {Driver} ({Type}) is a stub on this node — {Count} value node(s) marked BadConfigurationError", + _localNode, driverId, child.DriverType, writes.Count - before); + } + + if (writes is { Count: > 0 }) + _opcUaPublishActor.Tell(new OpcUa.OpcUaPublishActor.AttributeStatusBatchUpdate(writes)); + } + /// 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) @@ -5534,6 +5585,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // Respawn from the same spec the last reconcile used — preserves RowId, Name, ClusterId. SpawnChild(entry.Spec); + // #1113 item 4: a stub replacement will never publish — not "waiting for initial data". + StampStubbedDriverValueNodes(msg.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 3618f5293..c5247c905 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 @@ -224,6 +224,56 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase TestContext.Current.CancellationToken); } + // ---- #1113 item 4: a stubbed replacement / a stub deploy ---- + + /// + /// #1113 item 4: when the replacement is a STUB (here: no factory for the type), its nodes would otherwise sit at + /// BadWaitingForInitialData forever. They go BadConfigurationError, after the respawn stamp — for a + /// config change after the apply's RebuildAddressSpace (so the publish actor replays it onto the nodes the + /// apply recreates), including the ref the new deployment adds. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public void A_stubbed_replacement_marks_the_value_nodes_BadConfigurationError(bool configChange) + { + var oldDriver = new GatedDriver(DriverId); + var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver: null); + SeedGoodFromOldDriver(oldDriver, publish); + + Replace(configChange, host, coordinator, db); + + var stamp = ExpectStampBeforeAnyValue(publish); + stamp.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadWaitingForInitialData); + var rebuildSeen = false; + var config = (OpcUaPublishActor.AttributeStatusBatchUpdate)publish.FishForMessage(m => + { + if (m is OpcUaPublishActor.RebuildAddressSpace) rebuildSeen = true; + return m is OpcUaPublishActor.AttributeStatusBatchUpdate s + && s.Items.Any(i => i.StatusCode == OpcUaStatus.BadConfigurationError); + }, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var expected = configChange ? AllOldNodes.Append(TempRef).ToArray() : AllOldNodes; + config.Items.Select(i => i.NodeId).ShouldBe(expected, ignoreOrder: true); + config.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadConfigurationError); + rebuildSeen.ShouldBe(configChange, "a config change stamps after its apply's rebuild; a Restart has none"); + } + + /// #1113 item 4 on a fresh deploy: a driver that is a stub from the start never gets a first value either — + /// its nodes are marked BadConfigurationError right after the apply's RebuildAddressSpace. + [Fact] + public void A_fresh_deploy_of_a_stub_marks_its_value_nodes_BadConfigurationError() + { + var db = NewInMemoryDbFactory(); + var deploymentId = SeedTwoTagDeployment(db); + var (_, publish, _, _) = SpawnHostAndApplyWithCoordinator(this, db, TestNode, deploymentId, RevA, + driverFactory: new SequenceDriverFactory(new IDriver?[] { null })); + // SpawnHostAndApplyWithCoordinator consumed the RebuildAddressSpace: the stamp is what follows it. + var config = publish.FishForMessage(_ => true, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + config.Items.Select(i => i.NodeId).ShouldBe(AllOldNodes, ignoreOrder: true); + config.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadConfigurationError); + } + /// 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) @@ -270,7 +320,7 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase enabled: true); private (IActorRef Host, TestProbe Publish, TestProbe Coordinator, Microsoft.EntityFrameworkCore.IDbContextFactory Db) - Arrange(GatedDriver oldDriver, GatedDriver newDriver, TimeSpan? auditDelay = null) + Arrange(GatedDriver oldDriver, GatedDriver? newDriver, TimeSpan? auditDelay = null) { var db = NewInMemoryDbFactory(); var deploymentId = SeedTwoTagDeployment(db); @@ -352,8 +402,9 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase 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 + /// Hands out the given drivers in order, one per spawn (the last one repeats); a null is "no factory for + /// this type", which makes the host spawn a stub. + private sealed class SequenceDriverFactory(params IDriver?[] drivers) : IDriverFactory { private int _next; From b9a98f0f5924b2296f88e5aec4fced527bd7710e Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 5 Dec 2026 03:05:45 -0500 Subject: [PATCH 5/5] fix(runtime): #1113 document that a slow-connecting replacement reads BadWaitingForInitialData (accepted) Item 5 (owner decision, docs only). DriverLifecycle.md: the respawn/Restart stamp does not change while the replacement's initialise is still retrying - it has not lost anything, it has not connected yet; the nodes go BadNoCommunication only if the replacement connects and then loses its device. .claude/rules/drivers.md summarises the #1113 changes. --- .claude/rules/drivers.md | 6 ++++++ docs/DriverLifecycle.md | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index 1f6d69121..e6bf7ac18 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -154,6 +154,12 @@ non-`Healthy` state **and** its `LastSuccessfulRead` has been frozen for 90 s. T 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`. + #1113: a config-change respawn KEEPS an outstanding comms latch like Restart, and every apply trims latches to the + refs still routed (`TrimCommsLatchesToIndex` — a dropped ref is never audited); the audit Warning names the nodes' + real status (`still BadWaitingForInitialData` after a respawn/Restart). A STUB child's value nodes go + `BadConfigurationError` (`StampStubbedDriverValueNodes`, after each apply's rebuild Tell + after a Restart into a + stub). A slow-connecting replacement stays `BadWaitingForInitialData` (accepted). The gRPC origin hub is covered by + the producer fence (`RetireCurrentDriver` at the stop), not the node stamp — `GrpcDataRespawnOriginGapTests`. - **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 49a580cd2..d5187a3df 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -649,6 +649,12 @@ supervision restart (same driver object — unchanged, still covered by that chi 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). +- **A slow-connecting replacement reads `BadWaitingForInitialData`, not `BadNoCommunication` — accepted (#1113, owner + decision).** The stamp says "a new driver object, no value yet"; it does not change while the replacement's initialise is + still retrying, because the replacement has not lost anything — it has not connected yet. The nodes go + `BadNoCommunication` only if the replacement connects and then loses its device (its own comms-loss stamp, latched and + audited as usual). An operator watching a node stuck at `BadWaitingForInitialData` after a respawn should check the + driver's status on `/hosts` (Connecting / Reconnecting), not the node. - **A stub replacement reads `BadConfigurationError` (#1113).** When the replacement (or a freshly deployed driver) is a STUB — no factory for its type on this node, the factory rejected its config, or the type is not allowed on the node's roles — it never publishes, so `BadWaitingForInitialData` would be a promise that cannot be kept.