diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md
index 873b4955e..0bfe87bf2 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/docs/security.md b/docs/security.md
index 8419d0be9..5b86a8c2f 100644
--- a/docs/security.md
+++ b/docs/security.md
@@ -853,7 +853,9 @@ Behaviours worth knowing before enabling it:
deploy; only gRPC-data projected / imported-condition items, gated in both modes, can lapse (#972 — between
`8ad03e9c5` and the fix, the pass enforced grants with the flag off). With the flag off a local Raw/UNS item is
answered allow before the pass's memo (#1033: a 10k-item pass ~6.5–7 ms / ~1.4 MB ⇒ ~0.5–1 ms / ~0.2 KB; the same
- shortcut in the per-request `Permits` was measured and not taken — a 1,000-node Read did not change). Without the timer a key that expired by the
+ shortcut in the per-request `Permits` was measured and not taken — a 1,000-node Read did not change; it relies on the node
+ manager being the only wirer of the authorizer's `ImportedConditionClassifier` / `MappedNamespacePredicate`, to its own
+ delegates — source-scan guard `AuthorizerClassifierWiringGuardTests`, #1079). Without the timer a key that expired by the
clock kept streaming until a deployment happened to land — **indefinitely** on a fleet that has been
deployed once and left running, which is exactly the shape a production fleet settles into.
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs
index 8d28c4600..2520112df 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs
@@ -6314,7 +6314,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// () only [2]/[3], and AuthorizeIfRequired then takes the
/// localBypass. The one wiring where the full path differs — a mapped-subject resolver with no projected
/// predicate, which asks the resolver about every node and denies the local ones it cannot place — is excluded, so
- /// that configuration keeps its existing verdict.
+ /// that configuration keeps its existing verdict. Sound only because this manager is the sole wirer of both delegates,
+ /// to its own methods — pinned by AuthorizerClassifierWiringGuardTests (#1079).
///
///
/// Measured (10k flag-off items): a pass went from ~6.5–7 ms and ~1.4 MB (the pass-local memo's tuple keys and
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.OpcUaServer.Tests/AuthorizerClassifierWiringGuardTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AuthorizerClassifierWiringGuardTests.cs
new file mode 100644
index 000000000..43097e119
--- /dev/null
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AuthorizerClassifierWiringGuardTests.cs
@@ -0,0 +1,147 @@
+using System.Text.RegularExpressions;
+using Shouldly;
+using Xunit;
+
+namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
+
+///
+/// #1079 — the node manager is the ONLY code that wires DataPlaneAuthorizer.ImportedConditionClassifier and
+/// DataPlaneAuthorizer.MappedNamespacePredicate, and it wires them only to its own
+/// ClassifyImportedCondition / IsProjectedDescendant.
+///
+///
+///
+/// Why it matters: the #1033 flag-off revalidation fast path (OtOpcUaNodeManager.IsLocalNodeUngated) answers a
+/// local Raw/UNS item "allow" WITHOUT consulting the authorizer, on the reasoning that the imported-condition
+/// classifier answers only the imported-condition namespace and the projected predicate only the projected ones —
+/// so for a node in the manager's own Raw/UNS namespaces both would have passed it through to the
+/// localBypass. That holds only for the node manager's own delegates. A second wiring site (a host, a
+/// service, a test seam promoted to production) that installed a broader classifier would change the full path's
+/// verdict while the fast path kept answering allow — two answers to one question, with nothing failing.
+///
+///
+/// A textual scan over src/**/*.cs (the RoleAuthorityGuardTests idiom), because the thing guarded is
+/// an assignment site, which reflection cannot see. Tests are not scanned: they set these on a standalone
+/// authorizer that has no node manager and so no fast path.
+///
+///
+/// Falsification control: feeds the
+/// same scan offending snippets and asserts it flags each — proof the guard can fail.
+///
+///
+public sealed class AuthorizerClassifierWiringGuardTests
+{
+ private const string NodeManagerFile = "OtOpcUaNodeManager.cs";
+
+ /// The one delegate each property may be given (or null, via a ternary's null arm).
+ private static readonly IReadOnlyDictionary AllowedDelegate = new Dictionary
+ {
+ ["ImportedConditionClassifier"] = "ClassifyImportedCondition",
+ ["MappedNamespacePredicate"] = "IsProjectedDescendant",
+ };
+
+ /// An assignment (plain, ??=, or an object-initializer member) — not == or =>.
+ private static readonly Regex Assignment = new(
+ @"\b(?ImportedConditionClassifier|MappedNamespacePredicate)\s*(?:\?\?=|=(?![=>]))\s*(?[^;,}]*)",
+ RegexOptions.Compiled);
+
+ /// An allowed right-hand side: the method group alone, or cond ? null : MethodGroup.
+ private static readonly Regex AllowedRhs = new(
+ @"^(?:[^?;]+\?\s*null\s*:\s*)?(?[A-Za-z_][A-Za-z0-9_]*)\s*$",
+ RegexOptions.Compiled);
+
+ [Fact]
+ public void Only_the_node_manager_wires_the_classifier_and_the_predicate_and_only_to_its_own_delegates()
+ {
+ var found = new Dictionary();
+ var violations = new List();
+ foreach (var path in SourceFiles())
+ {
+ var (fileViolations, assignments) = Scan(Path.GetFileName(path), File.ReadAllText(path));
+ violations.AddRange(fileViolations.Select(v => $"{Path.GetRelativePath(SolutionRoot(), path)}:{v}"));
+ if (Path.GetFileName(path) == NodeManagerFile)
+ foreach (var prop in assignments) found[prop] = found.GetValueOrDefault(prop) + 1;
+ }
+
+ violations.ShouldBeEmpty(
+ "the #1033 flag-off fast path (IsLocalNodeUngated) assumes only OtOpcUaNodeManager wires these, to its own delegates");
+
+ // Non-vacuity: the scan must actually see the real wiring sites, or a regex drift would pass silently.
+ found.GetValueOrDefault("ImportedConditionClassifier").ShouldBeGreaterThanOrEqualTo(1);
+ found.GetValueOrDefault("MappedNamespacePredicate").ShouldBeGreaterThanOrEqualTo(1);
+ }
+
+ [Fact]
+ public void The_scan_detects_a_second_wiring_site_and_a_foreign_delegate()
+ {
+ Scan("Rogue.cs", " authorizer.MappedNamespacePredicate = _ => true;").Violations.Count.ShouldBe(1);
+ Scan("Rogue.cs", " var a = new DataPlaneAuthorizer(p) { ImportedConditionClassifier = (_, _, _) => null };")
+ .Violations.Count.ShouldBe(1);
+ Scan("Rogue.cs", " authorizer.ImportedConditionClassifier ??= Classify;").Violations.Count.ShouldBe(1);
+ Scan(NodeManagerFile, " value.MappedNamespacePredicate = _ => true;").Violations.Count.ShouldBe(1);
+ Scan(NodeManagerFile, " value.ImportedConditionClassifier = IsProjectedDescendant;").Violations.Count.ShouldBe(1);
+
+ // …and does not flag what is not a wiring: reads, comparisons, the declaration, a comment, the real shapes.
+ Scan("Rogue.cs", " if (authorizer.MappedNamespacePredicate is not null && x.ImportedConditionClassifier == y) { }")
+ .Violations.ShouldBeEmpty();
+ Scan("DataPlaneAuthorizer.cs", " public Func? MappedNamespacePredicate { get; set; }").Violations.ShouldBeEmpty();
+ Scan("Rogue.cs", " // authorizer.MappedNamespacePredicate = _ => true;").Violations.ShouldBeEmpty();
+ Scan(NodeManagerFile,
+ " value.MappedNamespacePredicate = _projectedDataAccess is null ? null : IsProjectedDescendant;\n" +
+ " value.ImportedConditionClassifier = ClassifyImportedCondition; // A3: before RealmOf, always")
+ .Violations.ShouldBeEmpty();
+ }
+
+ /// Scans one file's text; returns violations (line: text) and the property of every assignment seen.
+ private static (List Violations, List Assignments) Scan(string fileName, string text)
+ {
+ var violations = new List();
+ var assignments = new List();
+ var lines = text.Split('\n');
+ for (var i = 0; i < lines.Length; i++)
+ {
+ var line = lines[i];
+ if (line.TrimStart().StartsWith("//", StringComparison.Ordinal)) continue;
+ var code = StripTrailingComment(line);
+ foreach (Match m in Assignment.Matches(code))
+ {
+ var prop = m.Groups["prop"].Value;
+ assignments.Add(prop);
+ if (fileName != NodeManagerFile)
+ {
+ violations.Add($"{i + 1}: {line.Trim()} (only {NodeManagerFile} may wire {prop})");
+ continue;
+ }
+
+ var rhs = AllowedRhs.Match(m.Groups["rhs"].Value.Trim());
+ if (!rhs.Success || rhs.Groups["method"].Value != AllowedDelegate[prop])
+ violations.Add($"{i + 1}: {line.Trim()} ({prop} may only be {AllowedDelegate[prop]} or null)");
+ }
+ }
+
+ return (violations, assignments);
+ }
+
+ private static string StripTrailingComment(string line)
+ {
+ var idx = line.IndexOf("//", StringComparison.Ordinal);
+ return idx < 0 ? line : line[..idx];
+ }
+
+ private static string SolutionRoot()
+ {
+ var dir = new DirectoryInfo(AppContext.BaseDirectory);
+ while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "ZB.MOM.WW.OtOpcUa.slnx")))
+ dir = dir.Parent;
+ dir.ShouldNotBeNull("Could not find solution root (ZB.MOM.WW.OtOpcUa.slnx).");
+ return dir!.FullName;
+ }
+
+ private static IEnumerable SourceFiles()
+ {
+ var sep = Path.DirectorySeparatorChar;
+ return Directory.EnumerateFiles(Path.Combine(SolutionRoot(), "src"), "*.cs", SearchOption.AllDirectories)
+ .Where(f => !f.Contains($"{sep}obj{sep}", StringComparison.Ordinal)
+ && !f.Contains($"{sep}bin{sep}", StringComparison.Ordinal));
+ }
+}
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;
+ }
+}