Merge #1113: gRPC origin already retires a respawned driver's samples (pinned by test); config-change respawn keeps the comms latch trimmed to kept refs; audit warning names the real status; stubbed drivers' value nodes read BadConfigurationError; slow-connect behaviour documented

This commit is contained in:
Joseph Doherty
2026-12-05 03:06:25 -05:00
7 changed files with 499 additions and 20 deletions
@@ -192,12 +192,13 @@ public sealed class DriverHostCommsLossRecoveryTests : RuntimeActorTestBase
driver.InitializeGate = release.Task;
host.Tell(new RestartDriver("c1", "drv-restart", "test-operator", Guid.NewGuid()));
EventFilter.Warning(contains: "still BadNoCommunication")
EventFilter.Warning(contains: "ref(s) still")
.Expect(0, audit + TimeSpan.FromSeconds(3), () => { }, TestContext.Current.CancellationToken);
meter.SumWithTag("driver_instance", "drv-restart").ShouldBe(0);
// The new incarnation connects, re-subscribes silently, and its own audit reports the ref the restart kept.
EventFilter.Warning(contains: "still BadNoCommunication").ExpectOne(audit + ReconnectBudget, () =>
// The new incarnation connects, re-subscribes silently, and its own audit reports the ref the restart kept —
// naming the status the Restart re-stamped (#1112), not BadNoCommunication (#1113 item 3).
EventFilter.Warning(contains: "1 ref(s) still BadWaitingForInitialData").ExpectOne(audit + ReconnectBudget, () =>
{
driver.InitializeGate = null;
release.SetResult();
@@ -138,7 +138,7 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase
// 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")
EventFilter.Warning(contains: "ref(s) still")
.Expect(0, AuditDelay + TimeSpan.FromSeconds(2), () => { }, TestContext.Current.CancellationToken);
meter.SumWithTag("driver_instance", DriverId).ShouldBe(0);
@@ -151,11 +151,162 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase
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)
// ---- #1113 items 2 + 3: a respawn / Restart of a driver that was ALREADY comms-lost ----
/// <summary>Long enough that a test can fire the replacement's first value before the audit runs.</summary>
private static readonly TimeSpan LongAuditDelay = TimeSpan.FromSeconds(3);
/// <summary>
/// #1113 item 2: a config-change respawn of a comms-lost driver KEEPS the latch (it used to be cleared, so the
/// replacement was never audited — unlike an operator Restart, #1053), trimmed to the refs the new composition
/// still carries. The new deployment drops <c>flow</c> and adds <c>temp</c>; the silent replacement is reported
/// for exactly <c>speed</c> — not <c>flow</c> (dropped: a false warning) and not <c>temp</c> (never latched).
/// Item 3: the warning names the status the nodes carry, <c>BadWaitingForInitialData</c>.
/// </summary>
[Fact]
public void A_config_change_respawn_of_a_comms_lost_driver_audits_the_replacement_for_the_kept_refs_only()
{
var oldDriver = new GatedDriver(DriverId);
var newDriver = new GatedDriver(DriverId);
var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver, LongAuditDelay);
SeedGoodFromOldDriver(oldDriver, publish);
using var meter = new MeterRecorder("otopcua.driver.comms_latched_refs");
GoCommsLost(oldDriver, host, publish);
EventFilter.Warning(contains: "1 ref(s) still BadWaitingForInitialData").ExpectOne(
LongAuditDelay + PresenceBudget,
() => DispatchDroppingFlow(host, coordinator, db),
TestContext.Current.CancellationToken);
AwaitCondition(() => meter.SumWithTag("driver_instance", DriverId) == 1, TimeSpan.FromSeconds(5),
TestContext.Current.CancellationToken);
}
/// <summary>
/// #1113 item 2, the other half: when the replacement re-publishes every KEPT ref, the audit is silent — the
/// dropped <c>flow</c> (no longer subscribed, so it can never be re-published) is trimmed from the latch.
/// Without the trim this reported <c>flow</c>; without the kept latch the test above stays silent.
/// </summary>
[Fact]
public void A_ref_dropped_by_the_respawning_deploy_never_raises_a_false_audit_warning()
{
var oldDriver = new GatedDriver(DriverId);
var newDriver = new GatedDriver(DriverId);
var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver, LongAuditDelay);
SeedGoodFromOldDriver(oldDriver, publish);
using var meter = new MeterRecorder("otopcua.driver.comms_latched_refs");
GoCommsLost(oldDriver, host, publish);
DispatchDroppingFlow(host, coordinator, db);
AwaitFinalSubscribe(newDriver, configChange: true);
newDriver.Fire(SpeedRef, 11.0);
EventFilter.Warning(contains: "ref(s) still")
.Expect(0, LongAuditDelay + TimeSpan.FromSeconds(2), () => { }, TestContext.Current.CancellationToken);
meter.SumWithTag("driver_instance", DriverId).ShouldBe(0);
}
/// <summary>
/// #1113 item 3: an operator Restart keeps the latch (#1053), but the Restart re-stamped the nodes
/// <c>BadWaitingForInitialData</c> (#1112) — so the audit must not claim they are "still BadNoCommunication".
/// </summary>
[Fact]
public void A_restart_of_a_comms_lost_driver_audit_names_the_awaiting_first_value_status()
{
var oldDriver = new GatedDriver(DriverId);
var newDriver = new GatedDriver(DriverId);
var (host, publish, _, _) = Arrange(oldDriver, newDriver, LongAuditDelay);
SeedGoodFromOldDriver(oldDriver, publish);
GoCommsLost(oldDriver, host, publish);
EventFilter.Warning(contains: "2 ref(s) still BadWaitingForInitialData").ExpectOne(
LongAuditDelay + PresenceBudget,
() => host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid())),
TestContext.Current.CancellationToken);
}
// ---- #1113 item 4: a stubbed replacement / a stub deploy ----
/// <summary>
/// #1113 item 4: when the replacement is a STUB (here: no factory for the type), its nodes would otherwise sit at
/// <c>BadWaitingForInitialData</c> forever. They go <c>BadConfigurationError</c>, after the respawn stamp — for a
/// config change after the apply's <c>RebuildAddressSpace</c> (so the publish actor replays it onto the nodes the
/// apply recreates), including the ref the new deployment adds.
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public void A_stubbed_replacement_marks_the_value_nodes_BadConfigurationError(bool configChange)
{
var oldDriver = new GatedDriver(DriverId);
var (host, publish, coordinator, db) = Arrange(oldDriver, newDriver: null);
SeedGoodFromOldDriver(oldDriver, publish);
Replace(configChange, host, coordinator, db);
var stamp = ExpectStampBeforeAnyValue(publish);
stamp.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadWaitingForInitialData);
var rebuildSeen = false;
var config = (OpcUaPublishActor.AttributeStatusBatchUpdate)publish.FishForMessage(m =>
{
if (m is OpcUaPublishActor.RebuildAddressSpace) rebuildSeen = true;
return m is OpcUaPublishActor.AttributeStatusBatchUpdate s
&& s.Items.Any(i => i.StatusCode == OpcUaStatus.BadConfigurationError);
}, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var expected = configChange ? AllOldNodes.Append(TempRef).ToArray() : AllOldNodes;
config.Items.Select(i => i.NodeId).ShouldBe(expected, ignoreOrder: true);
config.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadConfigurationError);
rebuildSeen.ShouldBe(configChange, "a config change stamps after its apply's rebuild; a Restart has none");
}
/// <summary>#1113 item 4 on a fresh deploy: a driver that is a stub from the start never gets a first value either —
/// its nodes are marked <c>BadConfigurationError</c> right after the apply's <c>RebuildAddressSpace</c>.</summary>
[Fact]
public void A_fresh_deploy_of_a_stub_marks_its_value_nodes_BadConfigurationError()
{
var db = NewInMemoryDbFactory();
var deploymentId = SeedV3Deployment(db, RevA,
var deploymentId = SeedTwoTagDeployment(db);
var (_, publish, _, _) = SpawnHostAndApplyWithCoordinator(this, db, TestNode, deploymentId, RevA,
driverFactory: new SequenceDriverFactory(new IDriver?[] { null }));
// SpawnHostAndApplyWithCoordinator consumed the RebuildAddressSpace: the stamp is what follows it.
var config = publish.FishForMessage<OpcUaPublishActor.AttributeStatusBatchUpdate>(_ => true, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
config.Items.Select(i => i.NodeId).ShouldBe(AllOldNodes, ignoreOrder: true);
config.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadConfigurationError);
}
/// <summary>Takes the old driver comms-lost (Force Reconnect with its re-initialise held forever) and waits for the
/// host's latched <c>BadNoCommunication</c> stamp.</summary>
private static void GoCommsLost(GatedDriver oldDriver, IActorRef host, TestProbe publish)
{
oldDriver.InitializeGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously).Task;
host.Tell(new ReconnectDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
var outage = publish.FishForMessage<OpcUaPublishActor.AttributeStatusBatchUpdate>(
s => s.Items.Any(i => i.NodeId == SpeedRef), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
outage.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadNoCommunication);
}
/// <summary>A config change that keeps <c>speed</c>, DROPS <c>flow</c> (and its UNS mirror) and adds <c>temp</c>.</summary>
private static void DispatchDroppingFlow(IActorRef host, TestProbe coordinator,
Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> db)
{
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: "temp", DataType: "Double", Writable: false),
],
unsRefs:
[
(Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null),
],
enabled: true);
Dispatch(host, coordinator, revB, RevB);
}
private static DeploymentId SeedTwoTagDeployment(
Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> db) =>
SeedV3Deployment(db, RevA,
rawTags:
[
(Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false),
@@ -167,8 +318,14 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase
(Area: "filling", Line: "line1", Equip: "station1", BackingTag: "flow", Effective: (string?)null),
],
enabled: true);
private (IActorRef Host, TestProbe Publish, TestProbe Coordinator, Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> Db)
Arrange(GatedDriver oldDriver, GatedDriver? newDriver, TimeSpan? auditDelay = null)
{
var db = NewInMemoryDbFactory();
var deploymentId = SeedTwoTagDeployment(db);
var (host, publish, _, coordinator) = SpawnHostAndApplyWithCoordinator(this, db, TestNode, deploymentId, RevA,
driverFactory: new SequenceDriverFactory(oldDriver, newDriver), commsRecoveryAuditDelay: AuditDelay);
driverFactory: new SequenceDriverFactory(oldDriver, newDriver), commsRecoveryAuditDelay: auditDelay ?? AuditDelay);
AwaitAssert(() => (oldDriver.LastSubscribedRefs ?? []).ShouldContain(SpeedRef), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
return (host, publish, coordinator, db);
@@ -245,8 +402,9 @@ public sealed class DriverHostRespawnValueNodeGapTests : RuntimeActorTestBase
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
/// <summary>Hands out the given drivers in order, one per spawn (the last one repeats); a null is "no factory for
/// this type", which makes the host spawn a stub.</summary>
private sealed class SequenceDriverFactory(params IDriver?[] drivers) : IDriverFactory
{
private int _next;
@@ -0,0 +1,163 @@
using Akka.Actor;
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.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
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>#1113 item 1 — the gRPC data plane's origin side across a driver-object change.</b> Projected consumers
/// (DataConnectionService read / subscribe) are NOT served from the OPC UA node state: they read the
/// <see cref="PartitionedSampleHub"/>, a value cache of its own that the driver's callback feeds through
/// <see cref="SourceSamplePublisher"/>. So #1112's node stamp does not reach them — this pins that they are covered
/// by the producer fence instead: <c>StopChild</c> / <c>HandleRestartDriver</c> call
/// <see cref="SourceSamplePublisher.RetireCurrentDriver"/> at the stop, which removes every one of the driver's
/// sources (cache released, readiness <see cref="DataReadiness.Invalidated"/>), and the replacement's first value
/// binds a fresh generation. Between the two, the stopped object's last Good is never served: there is no current
/// source (a read answers <see cref="DataItemStatus.WaitingForInitialData"/>) and the old ticket reads not-ready.
/// </summary>
[Trait("Feature", "GrpcData"), Trait("Category", "Unit")]
public sealed class GrpcDataRespawnOriginGapTests : RuntimeActorTestBase
{
private const string DriverId = "DI-1";
private const string SpeedRef = "Plant/Modbus/dev1/speed";
private const string TempRef = "Plant/Modbus/dev1/temp";
private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64));
private static readonly RevisionHash RevB = RevisionHash.Parse(new string('b', 64));
[Theory]
[InlineData(false)]
[InlineData(true)]
public void The_origin_hub_never_serves_the_stopped_drivers_last_Good_until_the_replacement_publishes(bool configChange)
{
var db = NewInMemoryDbFactory();
var deploy = V3ArtifactSeeder.SeedV3Deployment(db, RevA,
[(DriverId, "Modbus", "dev1", "speed", "Double", false)], [], enabled: true);
var oldDriver = new FiringDriver();
var newDriver = new FiringDriver();
var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
newDriver.InitializeGate = hold.Task;
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1));
var coordinator = CreateTestProbe();
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
driverFactory: new SequenceFactory(oldDriver, newDriver), localRoles: new HashSet<string> { "driver" },
dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher,
acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)));
V3ArtifactSeeder.Dispatch(host, coordinator, deploy, RevA);
AwaitAssert(() => oldDriver.Subscribed.ShouldContain(SpeedRef), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
// The old driver object's Good reaches the origin hub.
oldDriver.Fire(SpeedRef, 11.0);
SourceTicket oldTicket = default;
AwaitAssert(() =>
{
publisher.TryCaptureDriver(DriverId, SpeedRef, out oldTicket).ShouldBeTrue();
hub.ProcessPending();
using var read = hub.Read(oldTicket);
read.Readiness.ShouldBe(DataReadiness.Ready);
read.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(11.0);
}, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var key = oldTicket.Key;
if (configChange)
{
var revB = V3ArtifactSeeder.SeedV3Deployment(db, RevB,
[(DriverId, "Modbus", "dev1", "speed", "Double", false), (DriverId, "Modbus", "dev1", "temp", "Double", false)],
[], enabled: true);
V3ArtifactSeeder.Dispatch(host, coordinator, revB, RevB);
}
else host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
// The replacement cannot publish (its initialise is held): what a consumer sees now is the whole gap.
AwaitAssert(() =>
{
hub.ProcessPending();
using (var stale = hub.Read(oldTicket)) stale.Readiness.ShouldNotBe(DataReadiness.Ready);
if (hub.TryGetCurrentTicket(key, out var current))
{
using var read = hub.Read(current);
read.Readiness.ShouldNotBe(DataReadiness.Ready, "no current source may serve the stopped object's Good");
}
}, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
publisher.TryCaptureDriver(DriverId, SpeedRef, out _).ShouldBeFalse("the stopped producer's sources are retired");
// The replacement's first value — the IDENTICAL value — is what makes the origin Good again.
hold.SetResult();
AwaitAssert(() => newDriver.Subscribed.ShouldContain(configChange ? TempRef : SpeedRef), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
newDriver.Fire(SpeedRef, 11.0);
AwaitAssert(() =>
{
hub.ProcessPending();
hub.TryGetCurrentTicket(key, out var current).ShouldBeTrue();
current.ShouldNotBe(oldTicket);
using var read = hub.Read(current);
read.Readiness.ShouldBe(DataReadiness.Ready);
read.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(11.0);
read.Sample.StatusCode.ShouldBe(OpcUaStatus.Good);
}, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>Hands out the given drivers in order, one per spawn (the last one repeats).</summary>
private sealed class SequenceFactory(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 initialise can be held.</summary>
private sealed class FiringDriver : IDriver, ISubscribable
{
private readonly StubHandle _handle = new();
private readonly Lock _gate = new();
private IReadOnlyList<string> _subscribed = [];
public event EventHandler<DataChangeEventArgs>? OnDataChange;
public Task? InitializeGate { get; set; }
public string DriverInstanceId => DriverId;
public string DriverType => "Modbus";
public IReadOnlyList<string> Subscribed
{
get { lock (_gate) return _subscribed; }
}
public void Fire(string fullReference, object value) =>
OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, fullReference,
new DataValueSnapshot(value, OpcUaStatus.Good, DateTime.UtcNow, DateTime.UtcNow)));
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) => Task.CompletedTask;
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
public Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken)
{
lock (_gate) _subscribed = fullReferences.ToArray();
return Task.FromResult<ISubscriptionHandle>(_handle);
}
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) => Task.CompletedTask;
}
}