Merge #1109 flake: respawn/restart dependent gap was a real race (#1070 stale-connectivity drop vs #1041's PostStop Bad) — host now tells dependents BadNoCommunication directly at child stop/restart; deterministic regression test

This commit is contained in:
Joseph Doherty
2026-12-04 22:36:18 -05:00
4 changed files with 248 additions and 2 deletions
@@ -0,0 +1,203 @@
using Akka.Actor;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// <b>#1109 — a respawn's "not Good until the new driver publishes" gap must not depend on the stopped child's
/// timing.</b>
/// <para>
/// #1041 relied on the stopped child's <c>PostStop</c> <c>ConnectivityChanged(false)</c> to hand dependents
/// <c>BadNoCommunication</c> while the new driver object has not published. #1070 then (correctly) drops that
/// announcement once the replacement has connected. Messages from two children are not ordered, so when the old
/// child reaches its stop late (busy in a synchronous driver call, or just a loaded dispatcher) the replacement
/// connects first, the Bad edge is dropped, and every dependent keeps computing from the stopped object's last
/// Good until the new driver happens to publish — which for an on-change source can be never. That is the
/// interleaving behind the intermittent failure of
/// <c>DriverHostActorSourceRemovedTests.A_config_change_respawn_tells_dependents_the_ref_is_not_Good_until_the_new_driver_publishes</c>.
/// </para>
/// <para>
/// Made deterministic here the way <see cref="DriverHostStaleConnectivityTests"/> does: the old driver's
/// <see cref="IHostConnectivityProbe.GetHostStatuses"/> (called synchronously on the child's mailbox thread)
/// blocks until the replacement has connected and subscribed, then the old child is released.
/// </para>
/// </summary>
public sealed class DriverHostRespawnDependentGapTests : RuntimeActorTestBase
{
private static readonly NodeId TestNode = NodeId.Parse("driver-respawn-gap-test");
private static readonly RevisionHash RevA = RevisionHash.Parse(new string('c', 64));
private static readonly RevisionHash RevB = RevisionHash.Parse(new string('d', 64));
private const string DriverId = "DI-1";
private const string Path1 = "Plant/Modbus/dev1/speed";
private static readonly (string, string, string, string, string?)[] NoRefs = [];
[Theory]
[InlineData(false)]
[InlineData(true)]
public void A_late_stopping_old_child_still_leaves_dependents_a_non_Good_gap(bool configChange)
{
var oldDriver = new GatedDriver(DriverId);
var newDriver = new GatedDriver(DriverId);
var db = NewInMemoryDbFactory();
var revA = V3ArtifactSeeder.SeedV3Deployment(db, RevA,
[(DriverId, "Modbus", "dev1", "speed", "Double", false)], NoRefs, enabled: true);
var mux = Sys.ActorOf(DependencyMuxActor.Props());
var coordinator = CreateTestProbe();
var holder = CreateTestProbe();
var host = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
driverFactory: new SequenceDriverFactory(oldDriver, newDriver),
localRoles: new HashSet<string> { "driver" },
dependencyMux: mux,
virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref));
V3ArtifactSeeder.Dispatch(host, coordinator, revA, RevA);
AwaitAssert(() => (oldDriver.LastSubscribedRefs ?? []).ShouldContain(Path1), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
mux.Tell(new DependencyMuxActor.RegisterInterest(new[] { Path1 }, holder.Ref, ReplayRetained: true));
oldDriver.Fire(Path1, 11.0);
holder.FishForMessage<VirtualTagActor.DependencyValueBatch>(
b => b.Items.Any(i => i.TagId == Path1 && Equals(i.Value, 11.0) && OpcUaStatus.IsGood(i.StatusCode)), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
// Wedge the old child's mailbox thread inside a synchronous driver call, so it cannot process its stop.
oldDriver.BlockHostStatuses();
oldDriver.RaiseHostStatusChanged();
oldDriver.HostStatusesEntered.Wait(PresenceBudget, TestContext.Current.CancellationToken)
.ShouldBeTrue("the old child must be parked inside GetHostStatuses before the respawn");
if (configChange)
{
var revB = V3ArtifactSeeder.SeedV3Deployment(db, RevB,
[(DriverId, "Modbus", "dev1", "speed", "Double", false), (DriverId, "Modbus", "dev1", "temp", "Double", false)],
NoRefs, enabled: true);
V3ArtifactSeeder.Dispatch(host, coordinator, revB, RevB);
}
else
{
host.Tell(new RestartDriver("c1", DriverId, "tester", Guid.NewGuid()));
}
// The replacement connects and subscribes while the old child is still wedged. A config-change spawn hands
// the child the PREVIOUS apply's set and the bulk push then re-subscribes with the new one; a value fired
// between the two can be lost, so wait for the final set (it names the added tag).
var finalRef = configChange ? "Plant/Modbus/dev1/temp" : Path1;
AwaitAssert(() => (newDriver.LastSubscribedRefs ?? []).ShouldContain(finalRef), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
// Release the old child: its PostStop announces comms loss and THEN shuts the driver down, so once
// ShutdownAsync ran that (now stale) announcement is already in the host's mailbox.
oldDriver.ReleaseHostStatuses();
AwaitCondition(() => oldDriver.ShutdownCalled, PresenceBudget, TestContext.Current.CancellationToken);
// The new driver's first value — the IDENTICAL value, so only a status edge in between can show the gap.
newDriver.Fire(Path1, 11.0);
var sawGap = false;
holder.FishForMessage<VirtualTagActor.DependencyValueBatch>(b =>
{
foreach (var i in b.Items.Where(i => i.TagId == Path1))
{
if (!OpcUaStatus.IsGood(i.StatusCode)) sawGap = true;
else if (Equals(i.Value, 11.0)) return true;
}
return false;
}, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
sawGap.ShouldBeTrue("dependents kept the stopped driver object's last Good until the new one published");
}
/// <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 publishes only when told to, and whose <see cref="GetHostStatuses"/> can be
/// made to block the owning child's mailbox thread.</summary>
private sealed class GatedDriver(string instanceId) : IDriver, ISubscribable, IHostConnectivityProbe
{
private readonly StubHandle _handle = new();
private readonly ManualResetEventSlim _release = new(initialState: true);
private readonly Lock _gate = new();
private IReadOnlyList<string>? _lastSubscribedRefs;
private volatile bool _blocking;
private volatile bool _shutdownCalled;
public event EventHandler<DataChangeEventArgs>? OnDataChange;
public event EventHandler<HostStatusChangedEventArgs>? OnHostStatusChanged;
public ManualResetEventSlim HostStatusesEntered { get; } = new();
public bool ShutdownCalled => _shutdownCalled;
public string DriverInstanceId => instanceId;
public string DriverType => "Modbus";
public IReadOnlyList<string>? LastSubscribedRefs
{
get { lock (_gate) return _lastSubscribedRefs; }
}
public void BlockHostStatuses()
{
_release.Reset();
_blocking = true;
}
public void ReleaseHostStatuses()
{
_blocking = false;
_release.Set();
}
public void RaiseHostStatusChanged() =>
OnHostStatusChanged?.Invoke(this, new HostStatusChangedEventArgs("dev1", HostState.Running, HostState.Stopped));
public void Fire(string fullReference, object value) =>
OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, fullReference,
new DataValueSnapshot(value, OpcUaStatus.Good, DateTime.UtcNow, DateTime.UtcNow)));
public IReadOnlyList<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) => Task.CompletedTask;
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
public Task ShutdownAsync(CancellationToken cancellationToken)
{
_shutdownCalled = true;
return Task.CompletedTask;
}
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
public Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken)
{
lock (_gate) _lastSubscribedRefs = fullReferences.ToArray();
return Task.FromResult<ISubscriptionHandle>(_handle);
}
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) => Task.CompletedTask;
}
}