diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026RenewalBatchWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026RenewalBatchWireTests.cs index 1fa63d29a..2a9a5e0d0 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026RenewalBatchWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026RenewalBatchWireTests.cs @@ -132,13 +132,73 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); while (published.Reader.TryRead(out _)) { } + var before = ProjectedStreamDiagnostics.Capture(); + var stream = subscriptions.Opens; await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromSeconds(9), ct, oneStep: true); - // Each registration rebinds onto the successor with its own fresh complete baseline (before the fix neither did: the - // batch waited for the joiner, the joiner for the batch's verdict). Whether the first rebind's witness is still valid - // once the second rebinds is the shared source's business, not this test's. - for (var i = 0; i < 2; i++) - await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct); + var seen = new List(); + var completes = 0; + using (var wait = CancellationTokenSource.CreateLinkedTokenSource(ct)) + { + wait.CancelAfter(TimeSpan.FromSeconds(20)); + try + { + while (completes < 2) + { + var u = await published.Reader.ReadAsync(wait.Token); + seen.Add($"complete={u.IsCompleteSnapshot} v={u.SourceVersion} route={u.Route.GetHashCode():x} proof={u.SourceProof.GetHashCode():x} valid={u.SourceProof.IsValid} late={u.ReceivedTimestamp > original.ReceivedTimestamp}"); + if (u.IsCompleteSnapshot && u.ReceivedTimestamp > original.ReceivedTimestamp) completes++; + } + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + var after = ProjectedStreamDiagnostics.Capture(); + var delta = after.Where(kv => kv.Value != before.GetValueOrDefault(kv.Key)).Select(kv => $"{kv.Key}+{kv.Value - before.GetValueOrDefault(kv.Key)}"); + const System.Reflection.BindingFlags f = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var gate = typeof(ProjectedDataAccess).GetField("_sync", f)!.GetValue(access)!; + string demands, overlaps; + lock (gate) + { + demands = string.Join(" | ", ((System.Collections.IEnumerable)typeof(ProjectedDataAccess).GetField("_demands", f)!.GetValue(access)!).Cast() + .Select(d => { var b = d.GetType().GetProperty("CurrentBinding", f)!.GetValue(d)!; + return $"valid={((ZB.MOM.WW.OtOpcUa.OpcUaServer.IProjectedDemandLease)d).IsValid} proof={b.GetType().GetProperty("Proof")!.GetValue(b)!.GetHashCode():x} recov={b.GetType().GetProperty("RecoveryOnly")!.GetValue(b)}"; })); + overlaps = ((System.Collections.ICollection)typeof(ProjectedDataAccess).GetField("_overlapRenewals", f)!.GetValue(access)!).Count.ToString(); + } + throw new TimeoutException($"completes={completes} joined={access.OverlapRenewalsJoinedForTests} opens={subscriptions.Opens}/{stream} " + + $"overlaps={overlaps}\nseen:\n{string.Join("\n", seen)}\ndelta: {string.Join(", ", delta)}\ndemands: {demands}"); + } + } access.OverlapRenewalsJoinedForTests.ShouldBe(1, "the second demand joined the first one's renewal"); + subscriptions.Opens.ShouldBe(1, "a renewal rebinds on the same physical stream; it never ends the cohort's attempt"); }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); } + + /// + /// #1026 (flake root cause): the fake origin must answer an Add of several items with a snapshot value for EACH, as a real + /// origin does for ready sources. It answered with the first item's only, so when both demands of one node rebound in ONE + /// Add (the renewals completed in the same batch, timing-dependent) the second had no baseline, the cohort ended its + /// attempt ("Renewal snapshot did not establish a complete baseline") and the test above waited for a snapshot that the + /// reopened stream again sent for one item only. + /// + [Fact, Trait("Issue", "1026")] + public async Task The_fake_origin_snapshots_every_item_one_add_command_carries() + { + var ct = TestContext.Current.CancellationToken; + using var origin = new LocalDataFixture(servingGeneration: 1); + var subscriptions = new FakeSubscriptions(() => origin.Serving) { SampleClock = origin.Clock }; + await using var stream = await subscriptions.SubscribeAsync(ct); + var settings = new DataSubscriptionSettings(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100), + ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataChangeTrigger.StatusValueTimestamp, null); + await stream.SendAsync(new AddSubscriptionItems("s", 1, "c1", TimeSpan.FromSeconds(5), + [new DataSubscriptionItem("a", origin.Raw, settings), new DataSubscriptionItem("b", origin.Raw, settings)]), ct); + var handles = new List(); + var acked = new List(); + await foreach (var frame in stream.ReadAllAsync(ct)) + { + if (frame is DataSubscriptionAck ack) acked.AddRange(ack.Items.Select(item => item.Handle!)); + else if (frame is DataSubscriptionValues { IsSnapshot: true } values) handles.AddRange(values.Items.Select(item => item.Handle)); + else if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) break; + } + acked.Count.ShouldBe(2); + handles.ShouldBe(acked, ignoreOrder: true, "each added item gets its own snapshot value before the snapshot ends"); + } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredDiscoveryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredDiscoveryWireTests.cs index 4d40de772..9fd63e1c2 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredDiscoveryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredDiscoveryWireTests.cs @@ -276,8 +276,13 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests Interval = items[0].Settings.PublishingInterval; _currentHandle = acks[0].Handle; _frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotBegin, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); + // #1026: like a real origin, the snapshot carries a value for EVERY item the command added. It used to carry + // one (the first): two items re-added by one command (two demands of one node rebinding after one renewal) + // left the second without a baseline, which ends the cohort's attempt as a failed renewal. if (owner.SampleClock is { } clock) - EmitValueCore(owner.SnapshotVersion, owner.SnapshotValue, clock.GetUtcNow(), TimeSpan.Zero, snapshot: true); + foreach (var ack in acks) + if (ack.Handle is { } snapshotHandle) + EmitValueCore(snapshotHandle, owner.SnapshotVersion, owner.SnapshotValue, clock.GetUtcNow(), TimeSpan.Zero, snapshot: true); if (owner.HoldNextSnapshotEnd) { owner.HoldNextSnapshotEnd = false; _snapshotEndHeld = true; @@ -291,19 +296,19 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests } public void EmitValue(long version, int value, DateTimeOffset sourceTimestamp, TimeSpan age) { - lock (_gate) EmitValueCore(version, value, sourceTimestamp, age, snapshot: false); + lock (_gate) EmitValueCore(_currentHandle!, version, value, sourceTimestamp, age, snapshot: false); } public void EmitValueWithoutSourceTimestamp(long version, int value, TimeSpan age) { - lock (_gate) EmitValueCore(version, value, null, age, snapshot: false); + lock (_gate) EmitValueCore(_currentHandle!, version, value, null, age, snapshot: false); } - private void EmitValueCore(long version, int value, DateTimeOffset? sourceTimestamp, TimeSpan age, bool snapshot) + private void EmitValueCore(DataItemHandle handle, long version, int value, DateTimeOffset? sourceTimestamp, TimeSpan age, bool snapshot) { var sample = new DataSample( ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(DataValueKind.Int32, value), 0, sourceTimestamp, sourceTimestamp, serving, version); _frames.Writer.TryWrite(new DataSubscriptionValues(_subscriptionId!, _epoch, ++_sequence, snapshot, - [new DataSubscriptionValue(_currentHandle!, sample, new(age, age), DataReadiness.Ready)])); + [new DataSubscriptionValue(handle, sample, new(age, age), DataReadiness.Ready)])); } private void EndSnapshot() => _frames.Writer.TryWrite(new DataSubscriptionControl(_subscriptionId!, _epoch, ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null));