diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1102FilterBaselineTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1102FilterBaselineTests.cs index 9c2c892cb..23e0aec53 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1102FilterBaselineTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1102FilterBaselineTests.cs @@ -117,4 +117,113 @@ public sealed class GrpcData1102FilterBaselineTests private static int ValueOf(DataSubscriptionValues values) => (int)values.Items.ShouldHaveSingleItem().Sample.Value.GetScalar()!; + + // #1109: the same race through the SINK delivery path (RunDeliveryAsync -> DeliverAsync), which commits after an awaited + // transport write rather than at the direct reader's pre-commit seam. v2 is parked inside sink.WriteAsync — past its + // eligibility and publication checks, not yet committed — while a whole tick considers v3. + [Theory(Timeout = 30000)] + [InlineData(false)] + [InlineData(true)] + public async Task Sink_path_a_newer_value_equal_to_the_old_baseline_is_delivered_after_an_in_flight_write_commits(bool deadband) + { + var values = await RunSinkInFlightRaceAsync(newerValue: 1, deadband ? 0.5 : null); + values.ShouldBe([2, 1]); + } + + [Fact(Timeout = 30000)] + public async Task Sink_path_a_newer_value_queued_behind_an_in_flight_write_is_delivered_once() + { + var values = await RunSinkInFlightRaceAsync(newerValue: 3, null); + values.ShouldBe([2, 3]); + } + + private static async Task RunSinkInFlightRaceAsync(int newerValue, double? deadband) + { + var ct = TestContext.Current.CancellationToken; + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + HubTest.Publish(fixture.Hub, fixture.Ticket, 1, 1); fixture.Hub.ProcessPending(); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(ct); + var session = subscription.ShouldBeOfType(); + var sink = new BaselineRaceSink(); + var writer = subscription.ShouldBeAssignableTo().RunDeliveryAsync(sink, ct); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, deadband); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), + [new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), ct); + await sink.SnapshotEnd.Task.WaitAsync(Wait, ct); + + var armed = 0; var started = 0; + var considered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + session.BeforeTickForTests = () => { if (Volatile.Read(ref armed) == 1) Volatile.Write(ref started, 1); }; + session.AfterTickForTests = () => { if (Volatile.Read(ref started) == 1) considered.TrySetResult(true); }; + + HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending(); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + await sink.FirstLiveWriteEntered.Task.WaitAsync(Wait, ct); + + // v2 is inside the transport write: the committed baseline is still v1. + HubTest.Publish(fixture.Hub, fixture.Ticket, 3, newerValue); fixture.Hub.ProcessPending(); + Volatile.Write(ref armed, 1); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + await considered.Task.WaitAsync(Wait, ct); + sink.LiveValues.ShouldBeEmpty(); // positive control: v2 has not committed yet + sink.ReleaseFirstLive(); + + // The commit's re-consideration (if any) is queued on the worker before this probe's ack. + await subscription.SendAsync(new AddSubscriptionItems("s", 1, "probe", TimeSpan.FromSeconds(10), []), ct); + await sink.AckFor("probe").WaitAsync(Wait, ct); + // Nothing is left behind the probe either: a later tick must not deliver a duplicate. + await subscription.SendAsync(new AddSubscriptionItems("s", 1, "probe-2", TimeSpan.FromSeconds(10), []), ct); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + await sink.AckFor("probe-2").WaitAsync(Wait, ct); + writer.IsCompleted.ShouldBeFalse(); // the stream is still healthy + return [.. sink.LiveValues]; + } + } + + /// Records committed live values; holds the FIRST live value's transport write until released. + private sealed class BaselineRaceSink : IDataSubscriptionDeliverySink + { + internal readonly TaskCompletionSource SnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource FirstLiveWriteEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly System.Collections.Concurrent.ConcurrentQueue LiveValues = new(); + private readonly TaskCompletionSource _releaseFirst = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly System.Collections.Concurrent.ConcurrentDictionary> _acks = new(); + private int _firstLive; + + internal Task AckFor(string commandId) => Ack(commandId).Task; + private TaskCompletionSource Ack(string commandId) => + _acks.GetOrAdd(commandId, _ => new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)); + internal void ReleaseFirstLive() => _releaseFirst.TrySetResult(true); + + public ValueTask PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, + CancellationToken cancellationToken) => ValueTask.FromResult(new Prepared(frame)); + + public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken) + { + var frame = ((Prepared)prepared).Frame; + if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) SnapshotEnd.TrySetResult(true); + if (frame is DataSubscriptionAck ack) Ack(ack.CommandId).TrySetResult(true); + if (frame is not DataSubscriptionValues { IsSnapshot: false } values) return; + if (Interlocked.Exchange(ref _firstLive, 1) == 0) + { + FirstLiveWriteEntered.TrySetResult(true); + await _releaseFirst.Task; // the transport write v2 is parked in + } + LiveValues.Enqueue(ValueOf(values)); + } + + private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery + { + internal DataSubscriptionFrame Frame { get; } = frame; + public long RetainedBytes => 1; + public void Dispose() { } + } + } }