diff --git a/docs/DataConnections.md b/docs/DataConnections.md index efd304f14..b17931ec1 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -181,6 +181,14 @@ replaces the origin item (trigger, deadband or view change) could also produce i acknowledgement released the replaced item's interest while a session tick was reading it. That release is no longer counted as a lost history; the replacement continues with its own snapshot. +An item's first frames on a Subscribe stream are its snapshot (`SnapshotBegin`, its snapshot value, `SnapshotEnd`). A +live delta for that item comes only after them. This applies to an added item, an item recovered from waiting for +initial data, and the new handle a `Modify` returns when it replaces the item. Until #966 a replacement could break +this. If a source change was read (for example through another item on the same source) while the modify's ack was +being committed, the replacement could send that newer value as a live delta before its `SnapshotBegin`. The +snapshot that followed then carried the older captured value. Now the change waits until the item's snapshot is +complete, and the item then delivers it as a live delta. + ### 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.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs index 4d1cdce3d..f475e05eb 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs @@ -1031,7 +1031,16 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo private async Task ConsiderAsync(Item item) { - lock (_gate) if (_challengedHandles.ContainsKey(item.Handle.Handle)) return; + lock (_gate) + { + if (_challengedHandles.ContainsKey(item.Handle.Handle)) return; + // #966: no live delta before the item's own snapshot. A modify's replacement (or an added/recovered item) is + // scheduler-registered and in _items before its SnapshotEnd commits; a dirty mark for its source (from a + // sibling group, or a commit landing mid-tick after the snapshot dequeue) would otherwise emit a newer live + // value ahead of its SnapshotBegin. Nothing is lost: LastConsidered is untouched and the group's own lease + // (cursor from the snapshot capture) yields the change once the group is snapshot-complete. + if (item.Interest is { SnapshotComplete: false }) return; + } if (item.Ticket is not { } ticket) return; using var read = _services.SubscriptionHub.Read(ticket); if (read.Readiness != DataReadiness.Ready || read.Sample is null) { CloseWithReset("Source became unavailable."); return; } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs index a9b836591..7e78845ff 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs @@ -988,6 +988,81 @@ public sealed class GrpcDataStreamOrderingTests } } + // #966: the modify's replacement item enters _items (and was registered with the delivery scheduler at staging) the + // moment the ack commits on the delivery side, but its snapshot job only reaches the pump on the NEXT tick. A tick + // already past that dequeue which then reads a source change (here from a sibling item on the same source, whose + // interest group survives the modify) marks the source dirty, and the scheduler hands it the replacement's handle. + // Before the fix that emitted a live delta for the replacement ahead of its SnapshotBegin/Snapshot/End. + [Fact(Timeout = 30000)] + public async Task Modify_committed_mid_tick_does_not_emit_a_replacement_delta_before_its_snapshot() + { + var ct = TestContext.Current.CancellationToken; + using var demand = new FirstLeaseReleaseSignalDemand(); + 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))) + { + fixture.Publish(10); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(ct); + var session = subscription.ShouldBeOfType(); + var sink = new HeldModifyAckSink(); + var writer = subscription.ShouldBeAssignableTo().RunDeliveryAsync(sink, ct); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + // "one" and "two" share a source and one interest group, so the group outlives the modify of "one". + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings), new("two", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), + LocalDataFixture.Budget), ct); + await sink.FirstSnapshotEnd.Task.WaitAsync(ct); + + var armed = 0; + var tickHolding = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + session.BeforeDirtyTickForTests = (_, _, interests) => + { + if (interests == 0 || Interlocked.Exchange(ref armed, 0) == 0) return; + tickHolding.TrySetResult(true); + // Past this tick's committed-snapshot dequeue: hold it until the modify commits on the delivery side. + demand.FirstReleased.Wait(TimeSpan.FromSeconds(10)); + }; + await subscription.SendAsync(new ModifySubscriptionItems("s", 1, "modify", TimeSpan.FromSeconds(5), + [new("one", fixture.Raw, settings with { Deadband = 5 })]), ct); + await sink.ModifyAckHeld.Task.WaitAsync(ct); // replacement snapshot captured (10), ack not yet committed + Volatile.Write(ref armed, 1); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(100)); // the session tick timer queues a tick + await tickHolding.Task.WaitAsync(ct); + HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 20); fixture.Hub.ProcessPending(); // a change after the replacement's capture, readable from the surviving group + demand.FirstReleased.IsSet.ShouldBeFalse(); // positive control: the held tick predates the commit + sink.ReleaseModifyAck(); + await Task.WhenAny(sink.SecondSnapshotEnd.Task, writer).WaitAsync(ct); + demand.FirstReleased.IsSet.ShouldBeTrue(); + + var ackIndex = -1; + string? replacement = null; + var deadline = DateTime.UtcNow.AddSeconds(10); + while (true) + { + var frames = sink.Frames.ToArray(); + var trace = string.Join(" | ", frames); + frames.ShouldNotContain(frame => frame.StartsWith("reset", StringComparison.Ordinal), trace); + ackIndex = Array.FindIndex(frames, frame => frame.StartsWith("ack:modify:", StringComparison.Ordinal)); + ackIndex.ShouldBeGreaterThan(0, trace); + replacement = frames[ackIndex]["ack:modify:".Length..]; + replacement.ShouldNotBe(sink.OriginalHandle); + var after = frames.Skip(ackIndex + 1).Where(frame => frame.Contains($":{replacement}:", StringComparison.Ordinal) || + frame is "begin" or "end").ToArray(); + // The replacement's first frames are its snapshot; its live delta (20) only after the snapshot end. + after.Take(3).ShouldBe(["begin", $"snapshot:{replacement}:10", "end"], trace); + // Positive control: the change the guard deferred is not lost; the replacement's own interest delivers it. + if (after.Contains($"value:{replacement}:20")) break; + if (DateTime.UtcNow > deadline) throw new ShouldAssertException("Replacement never delivered 20: " + trace); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(100)); + await Task.Delay(20, ct); + } + } + } + [Fact(Timeout = 30000)] public async Task Quiet_control_only_session_expires_without_renewal_or_further_commands() {