diff --git a/docs/DataConnections.md b/docs/DataConnections.md index a69987c28..f8830312d 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -373,6 +373,13 @@ Follow-ups (#1105): - The hub read (`CachedSourceRead`): public, escapes into `LocalDataServices`' publication lease and `SnapshotLease`, and its dispose/transfer guards are once-only by object identity. A struct copy would duplicate those guards. +Fixed (#1102): **a client filter can no longer leave the client on a superseded value.** The filter (trigger / deadband) compares +against the last *committed* value, while the reader may hold an earlier value that passed its eligibility check but has not +committed yet. A tick in that window that saw a newer value equal to the old baseline dropped it; the earlier value then committed +and the client kept it until the source changed again. The worker now records the version it suppressed (cleared when a later +version is queued), and a commit older than that version re-considers the source against the new baseline. Pre-existing (not +caused by #1098's sample hand-off), and independent of whether the hub sample and the item share a serving. + ### Mixed versions (X0 rollout) The remote history and alarm work (`docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Delivery.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Delivery.cs index c02bcfed5..263f11010 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Delivery.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Delivery.cs @@ -143,6 +143,15 @@ internal sealed partial class DataSubscriptionSession item.LastPublished = owned.Version; var now = session._services.Clock.GetTimestamp(); item.LastDeliveryTimestamp = now; item.NextDue = session.DueFor(now, item.Settings); + // #1102: a newer version was suppressed while this value was in flight, against the baseline this commit just + // replaced. If it equals the OLD baseline it was dropped, and without this the client would hold this + // superseded value until the source changed again. Re-consider the source against the new baseline. + if (item.SuppressedVersion > owned.Version) + { + item.SuppressedVersion = 0; + if (item.LastConsidered > owned.Version) item.LastConsidered = owned.Version; + session.MarkDirty(item.View.Source); session.QueueTick(); + } return true; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs index 620ac6b51..c28093660 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs @@ -112,6 +112,12 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo internal IDisposable? BaselineCharge; internal SourceTicket? Ticket; internal long LastConsidered, LastPublished, NextDue = 0; + /// + /// #1102: the newest version the client filter suppressed on the worker, 0 once a later version was queued. The + /// filter compares against the COMMITTED baseline, so a value still in flight (dequeued, not yet committed) can + /// commit after it and make that suppression wrong; the commit re-considers the source then (see ValueDelivery). + /// + internal long SuppressedVersion; internal long? LastDeliveryTimestamp; internal long? QueuedDue; internal LinkedListNode? WaitingNode; @@ -1094,7 +1100,8 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo return; } item.LastConsidered = read.Sample.Version; - if (!item.Filter.ShouldDeliver(read.Sample, item.Settings)) return; + if (!item.Filter.ShouldDeliver(read.Sample, item.Settings)) { item.SuppressedVersion = read.Sample.Version; return; } + item.SuppressedVersion = 0; // a queued newer value supersedes whatever an in-flight commit would re-consider } var version = read.Sample.Version; var delivery = MakeValue(item, read.Sample, read.ReceivedTimestamp, false, null, read: read); 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 new file mode 100644 index 000000000..9c2c892cb --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1102FilterBaselineTests.cs @@ -0,0 +1,120 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// #1102: a client filter's baseline is the last COMMITTED value, but a tick may consider a newer source version while an +/// earlier value is still in flight (dequeued and past its eligibility check, not yet committed). A newer value equal to the +/// old baseline was dropped against it, then the in-flight value committed, and the client held that superseded value until +/// the source changed again. Each test parks the in-flight value at the reader's pre-commit seam and drives the tick that +/// considers the newer version to completion before releasing it: no wall-clock waits decide the interleaving. +/// +[Trait("Feature", "GrpcData"), Trait("Category", "Unit")] +public sealed class GrpcData1102FilterBaselineTests +{ + private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10); + + [Theory(Timeout = 30000)] + [InlineData(false)] + [InlineData(true)] + public async Task A_newer_value_equal_to_the_old_baseline_is_delivered_after_an_in_flight_value_commits(bool deadband) + { + var frames = await RunInFlightRaceAsync(newerValue: 1, deadband ? 0.5 : null); + // v2 (value 2) was in flight while v3 (value 1, equal to the committed baseline) was considered. The client must end on + // the source's current value 1, not hold 2. + frames.ShouldBe([2, 1]); + } + + [Fact(Timeout = 30000)] + public async Task A_newer_value_queued_behind_an_in_flight_value_is_delivered_once() + { + // Control: the newer value differs from the baseline, so it is queued while v2 is in flight. Re-evaluating at commit + // must not deliver it twice. + var frames = await RunInFlightRaceAsync(newerValue: 3, null); + frames.ShouldBe([2, 3]); + } + + /// + /// Snapshot v1=1 (the baseline), then v2=2 goes in flight; at its pre-commit seam v3= is + /// published and a whole tick runs. Returns the live values the reader saw up to a probe acknowledgement queued after + /// the commit (the commit's own re-evaluation, if any, runs on the worker before that probe). + /// + private static async Task RunInFlightRaceAsync(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))) + { + // Every sample comes through HubTest.Publish (same status, no timestamps) so only the value differs. + 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 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 using var reader = subscription.ReadAllAsync(ct).GetAsyncEnumerator(ct); + (await reader.MoveNextAsync().AsTask().WaitAsync(Wait, ct)).ShouldBeTrue(); + reader.Current.ShouldBeOfType(); + (await reader.MoveNextAsync().AsTask().WaitAsync(Wait, ct)).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin); + (await reader.MoveNextAsync().AsTask().WaitAsync(Wait, ct)).ShouldBeTrue(); + using (var snapshot = reader.Current.ShouldBeOfType()) + ValueOf(snapshot).ShouldBe(1); + (await reader.MoveNextAsync().AsTask().WaitAsync(Wait, ct)).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd); + + // A tick that STARTS after v3 is in the hub has considered v3 by the time it ends. + var armed = 0; var started = 0; + var considered = new ManualResetEventSlim(); + session.BeforeTickForTests = () => { if (Volatile.Read(ref armed) == 1) Volatile.Write(ref started, 1); }; + session.AfterTickForTests = () => { if (Volatile.Read(ref started) == 1) considered.Set(); }; + var parked = 0; + session.BeforeDirectCommitForTests = () => + { + if (Interlocked.Exchange(ref parked, 1) != 0) return; + // v2 is past IsEligible and not yet committed: 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)); + if (!considered.Wait(Wait)) throw new TimeoutException("The tick considering v3 never completed."); + }; + + HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending(); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + var values = new List(); + (await Task.Run(async () => await reader.MoveNextAsync(), ct).WaitAsync(Wait, ct)).ShouldBeTrue(); + using (var live = reader.Current.ShouldBeOfType()) values.Add(ValueOf(live)); + Volatile.Read(ref parked).ShouldBe(1); + considered.IsSet.ShouldBeTrue(); + + await subscription.SendAsync(new AddSubscriptionItems("s", 1, "probe", TimeSpan.FromSeconds(10), []), ct); + while (true) + { + (await reader.MoveNextAsync().AsTask().WaitAsync(Wait, ct)).ShouldBeTrue(); + if (reader.Current is DataSubscriptionAck { CommandId: "probe" }) break; + if (reader.Current is DataSubscriptionValues more) using (more) values.Add(ValueOf(more)); + } + // 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)); + while (true) + { + (await reader.MoveNextAsync().AsTask().WaitAsync(Wait, ct)).ShouldBeTrue(); + if (reader.Current is DataSubscriptionAck { CommandId: "probe-2" }) break; + if (reader.Current is DataSubscriptionValues more) using (more) values.Add(ValueOf(more)); + } + return [.. values]; + } + } + + private static int ValueOf(DataSubscriptionValues values) => + (int)values.Items.ShouldHaveSingleItem().Sample.Value.GetScalar()!; +}