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
+5 -1
View File
@@ -143,7 +143,11 @@ non-`Healthy` state **and** its `LastSuccessfulRead` has been frozen for 90 s. T
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`.
edge still covers the gap. `DriverHostStaleConnectivityTests`. ⚠️ So that Bad edge can NOT be what tells
**mux dependents** (VTs, scripted alarms, Calculation) the old object ended — it raced the replacement and was
dropped, leaving them on the stopped object's last Good (#1109). The host itself fans `BadNoCommunication` to the
mux at the stop (`TellDependentsDriverObjectEnded`, before `SourceRemoved`); value nodes keep the #1070 rule.
`DriverHostRespawnDependentGapTests`.
- **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
+9
View File
@@ -614,6 +614,15 @@ A retired child's Bad edge is still applied while the replacement has not connec
cover above. Same rule the condition-signal tracker already applied. Pinned by `DriverHostStaleConnectivityTests` (the race
made deterministic by wedging the old child in `GetHostStatuses`).
⚠️ **…so mux dependents are told by the HOST, not by that edge (#1109).** #1041 relied on the old child's `PostStop` Bad to
hand dependency-mux dependents (virtual tags, scripted alarms, Calculation) a non-Good input until the new driver object
publishes. With the rule above that edge is dropped whenever the replacement connects first, which left dependents computing
from the stopped object's last Good — indefinitely for an on-change source that does not republish an unchanged value (the
#1109 flake: 15 of 30 stressed runs). `StopChild` and an operator Restart now fan `BadNoCommunication` for the driver's value
refs to the mux themselves (`TellDependentsDriverObjectEnded`), on the host→mux pair the new incarnation's values travel and
before `SourceRemoved`, so it is ordered ahead of the new driver's first value and is never retained. Value nodes are
unchanged (they keep the #1070 rule). Pinned by `DriverHostRespawnDependentGapTests` (same wedge).
### The connect path feeds the circuit breaker (R2-10 T10 closure)
`IDriver.InitializeAsync` is routed through the capability invoker as
@@ -5101,6 +5101,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
WithdrawDriverConditionsKnown(driverInstanceId);
ForgetConditionSignals(driverInstanceId);
PublishAckPreflight();
TellDependentsDriverObjectEnded(driverInstanceId);
EvictRetainedValues(driverInstanceId);
// The instance left the plan (StopChild is only reached via plan.ToStop), so its cached
// Health/Resilience snapshots must not replay to new telemetry subscribers. Release the shared
@@ -5146,6 +5147,34 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
private void EvictRetainedValues(string driverInstanceId) =>
_dependencyMux?.Tell(new DependencyMuxActor.SourceRemoved(driverInstanceId));
/// <summary>
/// Gitea #1109 — hands every dependent of <paramref name="driverInstanceId"/>'s value refs
/// <see cref="OpcUaStatus.BadNoCommunication"/> the moment the host ends the driver OBJECT (config-change
/// respawn, operator Restart, deploy removal), so no dependent keeps computing from the stopped object's last
/// Good until the replacement publishes.
/// </summary>
/// <remarks>
/// <para>
/// This gap used to be covered only by the stopped child's own <c>PostStop</c>
/// <c>ConnectivityChanged(false)</c> (#1041). That announcement races the replacement: <c>Context.Stop</c> is
/// asynchronous, two children's messages are not ordered, and a child busy in a synchronous driver call (or
/// a loaded dispatcher) reaches its stop late. Once the replacement has connected, #1070 rightly drops the
/// late announcement (<see cref="IsStaleRetiredConnectivity"/>) — which left dependents on the old Good,
/// indefinitely for an on-change source that never republishes an unchanged value. Sent HERE, on the
/// host→mux pair the new incarnation's values also travel, it is ordered ahead of every one of them.
/// </para>
/// <para>
/// Mux only, deliberately: the external value nodes keep the #1070 rule (the retired child's Bad edge is
/// applied only while the replacement has not connected) — stamping them here would also latch them for
/// the comms-recovery audit. Sent BEFORE <see cref="EvictRetainedValues"/> so the Bad it retains is
/// evicted with the old object's values and never replayed. Not sent on a supervision restart (same
/// driver object). For a deploy removal it precedes the apply's <c>RemovedInputStatus</c>; a duplicate
/// Bad from the old child's <c>PostStop</c> is absorbed by the (value, status) dedup downstream.
/// </para>
/// </remarks>
/// <param name="driverInstanceId">The driver instance whose object ended.</param>
private void TellDependentsDriverObjectEnded(string driverInstanceId) => FanCommsLossToDependencyMux(driverInstanceId);
/// <summary>Marks a child this host is about to stop as retired and watches it until it terminates.</summary>
/// <param name="child">The child being stopped.</param>
private void RetireChild(IActorRef child)
@@ -5247,7 +5276,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
Context.Stop(entry.Actor);
_children.Remove(msg.DriverInstanceId);
// An operator Restart builds a NEW driver object, so the old one's retained values are evicted like a
// removal's; the respawned driver republishes its own.
// removal's; the respawned driver republishes its own. Dependents are told first (#1109).
TellDependentsDriverObjectEnded(msg.DriverInstanceId);
EvictRetainedValues(msg.DriverInstanceId);
// The old incarnation's health must not read as the new one's until it publishes its own.
_healthPublisher.Forget(msg.DriverInstanceId);
@@ -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;
}
}