Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostStaleConnectivityTests.cs
T
Joseph Doherty 89aee3268b fix(runtime): #1112 value nodes go BadWaitingForInitialData on a driver respawn/Restart until the new driver's first value
Owner decision 'Brief Bad on restart'. A config-change respawn (StopChild with
respawning=true, i.e. an id the planner both stops and spawns) and an operator
Restart now stamp BadWaitingForInitialData on the driver's raw NodeIds and every
referencing UNS NodeId at the stop, on the host->publish-actor pair the new
driver's values travel, so the new Good always lands after it.

Not a comms loss: the stamp is not latched (no recovery audit, no
comms_latched_refs, no driver status), and a retired child's late PostStop Bad no
longer stamps value nodes while a replacement exists (it used to latch them).
A Restart therefore cancels the old incarnation's armed audit itself (#1053
keeps the latch). Supervision restarts, deploy removals/disables, native
conditions and historization (mux-fed, #1109) are unchanged.

Tests: DriverHostRespawnValueNodeGapTests (config change + Restart, late and
early old-child stop, raw + UNS, no-latch with positive control);
DriverHostStaleConnectivityTests expectations updated for the host stamp.
Docs: DriverLifecycle.md quality contract + .claude/rules/drivers.md.
2026-12-05 00:24:50 -05:00

247 lines
13 KiB
C#

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;
/// <summary>
/// <b>#1070 — a stopped incarnation's late <c>ConnectivityChanged(false)</c> must not overrule the live one.</b>
/// <para>
/// An operator Restart stops the old child (<c>Context.Stop</c> is asynchronous) and spawns its replacement in
/// the same handler. The old child announces comms loss from <c>PostStop</c>, 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
/// <c>BadNoCommunication</c> (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.
/// </para>
/// <para>
/// The race is made deterministic here: the old driver's <see cref="IHostConnectivityProbe.GetHostStatuses"/>
/// (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.
/// </para>
/// </summary>
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));
/// <summary>The child's reconnect retry runs on <c>DriverInstanceActor.DefaultReconnectInterval</c> (10 s), which the
/// host exposes no seam to shorten.</summary>
private static readonly TimeSpan ReconnectBudget = TimeSpan.FromSeconds(25);
private const string DriverId = "drv-stale";
private const string SpeedRef = "Plant/Modbus/dev1/speed";
private const string UnsSpeedNode = "filling/line1/station1/speed";
/// <summary>
/// The old incarnation's Bad edge lands after the new incarnation connected and pushed Good. It must be dropped.
/// <para>
/// 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.
/// </para>
/// </summary>
[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<OpcUaPublishActor.AttributeValueBatchUpdate>(_ => 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()));
// #1112 changed this expectation (it was "no status batch at all while the old child is wedged"): the HOST now
// stamps the value nodes BadWaitingForInitialData at the restart (owner decision "Brief Bad on restart"), so
// exactly that one batch precedes the new incarnation's push — and still no comms-loss Bad.
var statusBefore = DrainUntilValueBatch(publish, PresenceBudget);
statusBefore.ToArray().ShouldBe(new[] { OpcUaStatus.BadWaitingForInitialData },
"only the host's awaiting-first-value stamp may precede the new push 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.ToArray().ShouldBe(new[] { OpcUaStatus.BadNoCommunication },
"exactly the live incarnation's comms loss — a second batch is the stopped incarnation's late Bad overruling a connected driver");
}
/// <summary>
/// The other side of the rule. Before #1112 the stopped incarnation's Bad edge, applied while the replacement
/// had not yet connected, was the only thing covering the gap (and it latched the refs as a comms loss). Now the
/// HOST covers it at the restart with <c>BadWaitingForInitialData</c>, and the old child's late edge no longer
/// stamps value nodes while a replacement exists — so it is processed (the old child has shut down before the
/// replacement may connect) but adds no <c>BadNoCommunication</c> batch.
/// </summary>
[Fact]
public void A_stopped_incarnations_comms_loss_before_the_new_one_connects_is_covered_by_the_hosts_stamp()
{
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<OpcUaPublishActor.AttributeValueBatchUpdate>(_ => true, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
var staled = publish.FishForMessage<OpcUaPublishActor.AttributeStatusBatchUpdate>(_ => true, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
staled.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadWaitingForInitialData);
staled.Items.Select(i => i.NodeId).ShouldBe(new[] { SpeedRef, UnsSpeedNode }, ignoreOrder: true);
// The old child's PostStop Bad is in the host's mailbox once its driver shut down — before the replacement
// can connect. And the replacement's own push still recovers the nodes, with nothing stamped in between.
AwaitCondition(() => oldDriver.ShutdownCalled, PresenceBudget, TestContext.Current.CancellationToken);
hold.SetResult();
DrainUntilValueBatch(publish, PresenceBudget).ShouldBeEmpty(
"the stopped incarnation's Bad must not re-stamp the nodes as a comms loss while a replacement exists");
}
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);
}
/// <summary>The status code of each status batch (naming speed) arriving at the publish probe until the next
/// value batch, which it consumes; that value batch must be all Good.</summary>
private static List<uint> DrainUntilValueBatch(Akka.TestKit.TestProbe publish, TimeSpan budget)
{
var statusBatches = new List<uint>();
var value = publish.FishForMessage(m =>
{
if (m is OpcUaPublishActor.AttributeStatusBatchUpdate s && s.Items.Any(i => i.NodeId == SpeedRef))
statusBatches.Add(s.Items.First(i => i.NodeId == SpeedRef).StatusCode);
return m is OpcUaPublishActor.AttributeValueBatchUpdate;
}, budget, cancellationToken: TestContext.Current.CancellationToken);
((OpcUaPublishActor.AttributeValueBatchUpdate)value).Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.Good);
return statusBatches;
}
/// <summary>Hands out the given drivers in order, one per spawn (the last one repeats).</summary>
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<string> SupportedTypes { get; } = ["Modbus"];
}
/// <summary>
/// A subscribable driver that pushes the same 5 Good on every subscribe and whose
/// <see cref="GetHostStatuses"/> 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.
/// </summary>
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<DataChangeEventArgs>? OnDataChange;
public event EventHandler<HostStatusChangedEventArgs>? 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<HostConnectivityStatus> 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<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> 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<ISubscriptionHandle>(_handle);
}
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) => Task.CompletedTask;
}
}