diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index d279e4be6..00462c4c4 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -642,6 +642,15 @@ supervision restart (same driver object — unchanged, still covered by that chi disable (`RemovedInputStatus` + node removal). ScadaBridge sees a brief Bad per respawn/Restart — accepted. Pinned by `DriverHostRespawnValueNodeGapTests` (both seams, both interleavings, no-latch with a positive control). +- **The gRPC data plane's origin side is covered by the producer fence, not by this stamp (#1113).** Projected consumers + (DataConnectionService read / subscribe) do not read the OPC UA node state: they read the `PartitionedSampleHub`, fed + by the driver callback through `SourceSamplePublisher`. `StopChild` / `HandleRestartDriver` call + `RetireCurrentDriver` at the stop, which removes every one of the driver's sources (cached sample released, readiness + `Invalidated`), and spawning the replacement registers a new incarnation (retiring the old fence a second time). Until the + replacement's first value binds a fresh generation there is no current source — a read answers `WaitingForInitialData`, + the old ticket reads not-ready — so the stopped object's last Good is never served there either. Pinned by + `GrpcDataRespawnOriginGapTests` (both seams). + ### The connect path feeds the circuit breaker (R2-10 T10 closure) `IDriver.InitializeAsync` is routed through the capability invoker as diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataRespawnOriginGapTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataRespawnOriginGapTests.cs new file mode 100644 index 000000000..bed912237 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataRespawnOriginGapTests.cs @@ -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; + +/// +/// #1113 item 1 — the gRPC data plane's origin side across a driver-object change. Projected consumers +/// (DataConnectionService read / subscribe) are NOT served from the OPC UA node state: they read the +/// , a value cache of its own that the driver's callback feeds through +/// . So #1112's node stamp does not reach them — this pins that they are covered +/// by the producer fence instead: StopChild / HandleRestartDriver call +/// at the stop, which removes every one of the driver's +/// sources (cache released, readiness ), 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 ) and the old ticket reads not-ready. +/// +[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 { "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); + } + + /// Hands out the given drivers in order, one per spawn (the last one repeats). + 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 SupportedTypes { get; } = ["Modbus"]; + } + + /// A subscribable driver that publishes only when told to, and whose initialise can be held. + private sealed class FiringDriver : IDriver, ISubscribable + { + private readonly StubHandle _handle = new(); + private readonly Lock _gate = new(); + private IReadOnlyList _subscribed = []; + + public event EventHandler? OnDataChange; + + public Task? InitializeGate { get; set; } + public string DriverInstanceId => DriverId; + public string DriverType => "Modbus"; + + public IReadOnlyList 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 SubscribeAsync( + IReadOnlyList fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken) + { + lock (_gate) _subscribed = fullReferences.ToArray(); + return Task.FromResult(_handle); + } + + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) => Task.CompletedTask; + } +}