89aee3268b
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.
370 lines
20 KiB
C#
370 lines
20 KiB
C#
using System.Diagnostics.Metrics;
|
|
using Akka.Actor;
|
|
using Akka.TestKit;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
|
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>#1112 — "Brief Bad on restart" (owner decision).</b> When the host replaces a driver OBJECT (a config-change
|
|
/// respawn or an operator Restart), the driver's OPC UA value nodes — the raw NodeId AND every referencing UNS
|
|
/// mirror — go <c>BadWaitingForInitialData</c> at the stop and stay there until the NEW driver's first value.
|
|
/// <para>
|
|
/// Before this, only the dependency mux was told (#1109); the value nodes kept the stopped object's last Good
|
|
/// whenever the stopped child's own <c>PostStop</c> Bad edge reached the host after its replacement connected
|
|
/// (and #1070 dropped it). And when that edge DID land first, it stamped <c>BadNoCommunication</c> and latched
|
|
/// the refs for the comms-recovery audit, as if a respawn were an outage.
|
|
/// </para>
|
|
/// <para>
|
|
/// Every test drives both seams (config change and Restart). The race is made deterministic the way
|
|
/// <see cref="DriverHostStaleConnectivityTests"/> does it: either the old driver's
|
|
/// <see cref="IHostConnectivityProbe.GetHostStatuses"/> wedges the old child's mailbox (its stop lands late) or
|
|
/// the new driver's initialise is held (the stop lands first).
|
|
/// </para>
|
|
/// </summary>
|
|
public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase
|
|
{
|
|
private static readonly NodeId TestNode = NodeId.Parse("driver-respawn-value-gap");
|
|
private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64));
|
|
private static readonly RevisionHash RevB = RevisionHash.Parse(new string('b', 64));
|
|
|
|
/// <summary>The child's reconnect retry runs on <c>DriverInstanceActor.DefaultReconnectInterval</c> (10 s).</summary>
|
|
private static readonly TimeSpan ReconnectBudget = TimeSpan.FromSeconds(25);
|
|
|
|
private static readonly TimeSpan AuditDelay = TimeSpan.FromSeconds(1);
|
|
|
|
private const string DriverId = "drv-gap";
|
|
private const string SpeedRef = "Plant/Modbus/dev1/speed";
|
|
private const string FlowRef = "Plant/Modbus/dev1/flow";
|
|
private const string TempRef = "Plant/Modbus/dev1/temp";
|
|
private const string UnsSpeedNode = "filling/line1/station1/speed";
|
|
private const string UnsFlowNode = "filling/line1/station1/flow";
|
|
|
|
private static readonly string[] AllOldNodes = [SpeedRef, UnsSpeedNode, FlowRef, UnsFlowNode];
|
|
|
|
/// <summary>
|
|
/// The old child stops LATE (after the replacement connected and subscribed). The host's own stamp still puts
|
|
/// raw + UNS non-Good at the stop, the stopped child's late Bad never lands on top of the new Good, and the new
|
|
/// driver's first value — the IDENTICAL value, so only a status edge can show the gap — makes them Good again.
|
|
/// </summary>
|
|
[Theory]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public void A_late_stopping_old_child_value_nodes_go_awaiting_first_value_then_Good(bool configChange)
|
|
{
|
|
var oldDriver = new GatedDriver(DriverId);
|
|
var newDriver = new GatedDriver(DriverId);
|
|
var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver);
|
|
SeedGoodFromOldDriver(oldDriver, publish);
|
|
|
|
oldDriver.BlockHostStatuses();
|
|
oldDriver.RaiseHostStatusChanged();
|
|
oldDriver.HostStatusesEntered.Wait(PresenceBudget, TestContext.Current.CancellationToken)
|
|
.ShouldBeTrue("the old child must be parked inside GetHostStatuses before the respawn");
|
|
|
|
Replace(configChange, host, coordinator, db);
|
|
|
|
// The stamp is the host's, sent at the stop: it arrives although the old child cannot stop yet.
|
|
var stamp = ExpectStampBeforeAnyValue(publish);
|
|
stamp.Items.Select(i => i.NodeId).ShouldBe(AllOldNodes, ignoreOrder: true);
|
|
stamp.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadWaitingForInitialData);
|
|
|
|
AwaitFinalSubscribe(newDriver, configChange);
|
|
|
|
// Release the old child: PostStop announces comms loss THEN shuts the driver down, so once ShutdownAsync ran
|
|
// the stale Bad is already in the host's mailbox, ahead of the value fired next.
|
|
oldDriver.ReleaseHostStatuses();
|
|
AwaitCondition(() => oldDriver.ShutdownCalled, PresenceBudget, TestContext.Current.CancellationToken);
|
|
|
|
newDriver.Fire(SpeedRef, 11.0);
|
|
var (statusBatches, recovered) = DrainUntilValueBatch(publish, PresenceBudget);
|
|
statusBatches.ShouldBeEmpty("the stopped incarnation's late Bad must not be stamped once its replacement exists");
|
|
recovered.Items.Select(i => i.NodeId).ShouldBe(new[] { SpeedRef, UnsSpeedNode }, ignoreOrder: true);
|
|
recovered.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.Good && Equals(i.Value, 11.0));
|
|
|
|
// Positive control for the empty status list above: a real outage of the CURRENT incarnation IS stamped.
|
|
host.Tell(new ReconnectDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
|
|
var outage = publish.FishForMessage<OpcUaPublishActor.AttributeStatusBatchUpdate>(_ => true, ReconnectBudget,
|
|
cancellationToken: TestContext.Current.CancellationToken);
|
|
outage.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadNoCommunication);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The old child stops FIRST (the replacement's initialise is held), so its <c>PostStop</c> Bad is processed
|
|
/// while the replacement is not yet connected — the interleaving in which it used to stamp
|
|
/// <c>BadNoCommunication</c> and latch every ref for the comms-recovery audit. A respawn is not an outage: no
|
|
/// comms-loss stamp, no latch, no audit Warning / <c>otopcua.driver.comms_latched_refs</c> — even though the
|
|
/// new driver never publishes <c>flow</c> (pre-fix, exactly that ref was reported). The raw + UNS nodes sit at
|
|
/// <c>BadWaitingForInitialData</c> until the first value.
|
|
/// </summary>
|
|
[Theory]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public void An_old_child_stopping_before_the_replacement_connects_does_not_latch_or_audit(bool configChange)
|
|
{
|
|
var oldDriver = new GatedDriver(DriverId);
|
|
var newDriver = new GatedDriver(DriverId);
|
|
var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
newDriver.InitializeGate = hold.Task;
|
|
var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver);
|
|
SeedGoodFromOldDriver(oldDriver, publish);
|
|
using var meter = new MeterRecorder("otopcua.driver.comms_latched_refs");
|
|
|
|
Replace(configChange, host, coordinator, db);
|
|
|
|
var stamp = ExpectStampBeforeAnyValue(publish);
|
|
stamp.Items.Select(i => i.NodeId).ShouldBe(AllOldNodes, ignoreOrder: true);
|
|
stamp.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadWaitingForInitialData);
|
|
|
|
// The old child has stopped: its PostStop Bad is in the host's mailbox before the replacement can connect.
|
|
AwaitCondition(() => oldDriver.ShutdownCalled, PresenceBudget, TestContext.Current.CancellationToken);
|
|
hold.SetResult();
|
|
AwaitFinalSubscribe(newDriver, configChange);
|
|
|
|
newDriver.Fire(SpeedRef, 11.0);
|
|
var (statusBatches, recovered) = DrainUntilValueBatch(publish, PresenceBudget);
|
|
statusBatches.ShouldBeEmpty("a respawn is not a comms loss — the old child's Bad must not re-stamp the nodes");
|
|
recovered.Items.Select(i => i.NodeId).ShouldBe(new[] { SpeedRef, UnsSpeedNode }, ignoreOrder: true);
|
|
recovered.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.Good && Equals(i.Value, 11.0));
|
|
|
|
// 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")
|
|
.Expect(0, AuditDelay + TimeSpan.FromSeconds(2), () => { }, TestContext.Current.CancellationToken);
|
|
meter.SumWithTag("driver_instance", DriverId).ShouldBe(0);
|
|
|
|
// Positive control: a real outage of the current incarnation (silent re-subscribe: GatedDriver pushes nothing)
|
|
// DOES latch and DOES audit, through the same meter.
|
|
EventFilter.Warning(contains: "still BadNoCommunication").ExpectOne(ReconnectBudget + AuditDelay,
|
|
() => host.Tell(new ReconnectDriver("c1", DriverId, "test-operator", Guid.NewGuid())),
|
|
TestContext.Current.CancellationToken);
|
|
AwaitCondition(() => meter.SumWithTag("driver_instance", DriverId) > 0, TimeSpan.FromSeconds(5),
|
|
TestContext.Current.CancellationToken);
|
|
}
|
|
|
|
private (IActorRef Host, TestProbe Publish, TestProbe Coordinator, Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> Db)
|
|
Arrange(GatedDriver oldDriver, GatedDriver newDriver)
|
|
{
|
|
var db = NewInMemoryDbFactory();
|
|
var deploymentId = SeedV3Deployment(db, RevA,
|
|
rawTags:
|
|
[
|
|
(Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false),
|
|
(Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "flow", DataType: "Double", Writable: false),
|
|
],
|
|
unsRefs:
|
|
[
|
|
(Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null),
|
|
(Area: "filling", Line: "line1", Equip: "station1", BackingTag: "flow", Effective: (string?)null),
|
|
],
|
|
enabled: true);
|
|
var (host, publish, _, coordinator) = SpawnHostAndApplyWithCoordinator(this, db, TestNode, deploymentId, RevA,
|
|
driverFactory: new SequenceDriverFactory(oldDriver, newDriver), commsRecoveryAuditDelay: AuditDelay);
|
|
AwaitAssert(() => (oldDriver.LastSubscribedRefs ?? []).ShouldContain(SpeedRef), PresenceBudget,
|
|
cancellationToken: TestContext.Current.CancellationToken);
|
|
return (host, publish, coordinator, db);
|
|
}
|
|
|
|
private void SeedGoodFromOldDriver(GatedDriver oldDriver, TestProbe publish)
|
|
{
|
|
oldDriver.Fire(SpeedRef, 11.0);
|
|
oldDriver.Fire(FlowRef, 3.0);
|
|
var seen = new HashSet<string>();
|
|
publish.FishForMessage(m =>
|
|
{
|
|
if (m is OpcUaPublishActor.AttributeValueBatchUpdate v)
|
|
foreach (var i in v.Items.Where(i => OpcUaStatus.IsGood(i.StatusCode))) seen.Add(i.NodeId);
|
|
return AllOldNodes.All(seen.Contains);
|
|
}, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
}
|
|
|
|
/// <summary>Config change: a new deployment edits the driver's config (adds <c>temp</c>), so the planner respawns
|
|
/// it. Restart: the operator command.</summary>
|
|
private static void Replace(bool configChange, IActorRef host, TestProbe coordinator,
|
|
Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> db)
|
|
{
|
|
if (!configChange)
|
|
{
|
|
host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
|
|
return;
|
|
}
|
|
|
|
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: "flow", 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),
|
|
(Area: "filling", Line: "line1", Equip: "station1", BackingTag: "flow", Effective: (string?)null),
|
|
],
|
|
enabled: true);
|
|
// Waits for the Applied ack; the publish probe keeps every message in arrival order meanwhile.
|
|
Dispatch(host, coordinator, revB, RevB);
|
|
}
|
|
|
|
/// <summary>The first status batch for the speed node, failing if a value batch for it arrives first.</summary>
|
|
private static OpcUaPublishActor.AttributeStatusBatchUpdate ExpectStampBeforeAnyValue(TestProbe publish)
|
|
{
|
|
var msg = publish.FishForMessage(m =>
|
|
m is OpcUaPublishActor.AttributeStatusBatchUpdate s && s.Items.Any(i => i.NodeId == SpeedRef)
|
|
|| m is OpcUaPublishActor.AttributeValueBatchUpdate v && v.Items.Any(i => i.NodeId == SpeedRef),
|
|
PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
return msg.ShouldBeOfType<OpcUaPublishActor.AttributeStatusBatchUpdate>(
|
|
"the respawn must stamp the value nodes before the new driver's first value");
|
|
}
|
|
|
|
/// <summary>A config-change spawn hands the child the PREVIOUS apply's set and the bulk push re-subscribes with
|
|
/// the new one; a value fired between the two can be lost, so wait for the final set.</summary>
|
|
private void AwaitFinalSubscribe(GatedDriver newDriver, bool configChange) =>
|
|
AwaitAssert(() => (newDriver.LastSubscribedRefs ?? []).ShouldContain(configChange ? TempRef : SpeedRef),
|
|
PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
|
|
/// <summary>Status batches naming speed, up to (and returning) the next value batch naming speed.</summary>
|
|
private static (List<OpcUaPublishActor.AttributeStatusBatchUpdate> Statuses, OpcUaPublishActor.AttributeValueBatchUpdate Value)
|
|
DrainUntilValueBatch(TestProbe publish, TimeSpan budget)
|
|
{
|
|
var statuses = new List<OpcUaPublishActor.AttributeStatusBatchUpdate>();
|
|
var msg = publish.FishForMessage(m =>
|
|
{
|
|
if (m is OpcUaPublishActor.AttributeStatusBatchUpdate s && s.Items.Any(i => i.NodeId == SpeedRef)) statuses.Add(s);
|
|
return m is OpcUaPublishActor.AttributeValueBatchUpdate v && v.Items.Any(i => i.NodeId == SpeedRef);
|
|
}, budget, cancellationToken: TestContext.Current.CancellationToken);
|
|
return (statuses, (OpcUaPublishActor.AttributeValueBatchUpdate)msg);
|
|
}
|
|
|
|
/// <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 (so a re-subscribe is silent), whose
|
|
/// <see cref="GetHostStatuses"/> can block the owning child's mailbox thread, and whose initialise can be held.</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 Task? InitializeGate { get; set; }
|
|
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) =>
|
|
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)
|
|
{
|
|
lock (_gate) _lastSubscribedRefs = fullReferences.ToArray();
|
|
return Task.FromResult<ISubscriptionHandle>(_handle);
|
|
}
|
|
|
|
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) => Task.CompletedTask;
|
|
}
|
|
|
|
/// <summary>Tag-filtered counter recorder (instrument name alone would collect a parallel test's measurements).</summary>
|
|
private sealed class MeterRecorder : IDisposable
|
|
{
|
|
private readonly MeterListener _listener;
|
|
private readonly List<(long Value, KeyValuePair<string, object?>[] Tags)> _measurements = new();
|
|
private readonly Lock _gate = new();
|
|
|
|
public MeterRecorder(string instrumentName)
|
|
{
|
|
_listener = new MeterListener
|
|
{
|
|
InstrumentPublished = (instrument, listener) =>
|
|
{
|
|
if (instrument.Meter.Name == OtOpcUaTelemetry.MeterName && instrument.Name == instrumentName)
|
|
listener.EnableMeasurementEvents(instrument);
|
|
},
|
|
};
|
|
_listener.SetMeasurementEventCallback<long>((_, value, tags, _) =>
|
|
{
|
|
lock (_gate) _measurements.Add((value, tags.ToArray()));
|
|
});
|
|
_listener.Start();
|
|
}
|
|
|
|
public long SumWithTag(string key, string value)
|
|
{
|
|
lock (_gate)
|
|
return _measurements.Where(m => m.Tags.Any(t => t.Key == key && Equals(t.Value, value))).Sum(m => m.Value);
|
|
}
|
|
|
|
public void Dispose() => _listener.Dispose();
|
|
}
|
|
}
|