using System.Threading.Channels; using Opc.Ua; using Opc.Ua.Client; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.OpcUaServer; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; public sealed partial class GrpcDataConfiguredDiscoveryWireTests { /// /// #968: a metadata renewal replaces the node's committed definition. TryResolve read the committed map twice /// and answered "no such node" when the definition was replaced between the reads, so every subscription demand /// check racing a renewal (its freshness check, the source lookup of a frame, a rebind) saw a live node as gone for /// an instant and tore its physical stream down. Two cadences renewing the same node made it likely: the second, /// redundant renewal replaces the definition again while the first cadence is mid-rebind. /// [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] public async Task A_definition_replaced_by_a_renewal_never_resolves_as_missing() { var ct = TestContext.Current.CancellationToken; LocalDataFixture? peer = null; var subscriptions = new FakeSubscriptions(() => peer!.Serving); using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); peer = origin; subscriptions.SampleClock = origin.Clock; await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => { await BrowseAll((SessionClient)session, anchor, 1); var lookup = (IProjectedNodeLookup)sink; var pages = (IProjectedNamespacePageSink)sink; lookup.TryResolve(anchor, out var initial).ShouldBeTrue(); using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(2)); long replacements = 0, resolutions = 0, missing = 0; // Replace the committed definition with an identical one as fast as possible: exactly what a renewal // commits, minus the metadata round trip. var renewer = Task.Run(() => { while (!stop.IsCancellationRequested) { if (!lookup.TryResolve(anchor, out var current) || current is null) continue; if (pages.TryRenewExact(anchor, current, current with { }, () => true)) replacements++; } }, CancellationToken.None); var readers = Enumerable.Range(0, 2).Select(_ => Task.Run(() => { while (!stop.IsCancellationRequested) { Interlocked.Increment(ref resolutions); if (!lookup.TryResolve(anchor, out var resolved) || resolved is null) Interlocked.Increment(ref missing); } }, CancellationToken.None)).ToArray(); await Task.WhenAll([renewer, .. readers]).WaitAsync(TimeSpan.FromSeconds(30), ct); replacements.ShouldBeGreaterThan(100, "the renewer must actually replace the definition"); resolutions.ShouldBeGreaterThan(1000); missing.ShouldBe(0, $"a live node resolved as missing {missing} times in {resolutions} lookups racing {replacements} renewals"); lookup.TryResolve(anchor, out var final).ShouldBeTrue(); final.ShouldNotBeSameAs(initial); }); } /// /// #970: the #968 lookup gave up after 16 back-to-back replacements and answered "no such node" for a live node (a /// reader preempted while a renewer swapped the definition). A lookup now retries for as long as the node's entry keeps /// being replaced — every retry is a committed replacement, so it ends when the replacements stop. Deterministic: the /// definition's own authority check commits a replacement each time the lookup evaluates it, 64 times in a row. /// [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] public async Task A_lookup_outlasting_many_back_to_back_replacements_never_resolves_as_missing() { LocalDataFixture? peer = null; var subscriptions = new FakeSubscriptions(() => peer!.Serving); using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); peer = origin; subscriptions.SampleClock = origin.Clock; await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => { await BrowseAll((SessionClient)session, anchor, 1); var lookup = (IProjectedNodeLookup)sink; var pages = (IProjectedNamespacePageSink)sink; lookup.TryResolve(anchor, out var initial).ShouldBeTrue(); const int Swaps = 64; bool armed = false, replacing = false; var replacements = 0; bool Authority() { if (armed && !replacing && replacements < Swaps) { replacing = true; // TryRenewExact evaluates the replacement's authority itself try { if (pages.TryRenewExact(anchor, initial!, initial! with { AuthorityIsCurrent = Authority }, () => true)) replacements++; } finally { replacing = false; } } return initial!.AuthorityIsCurrent(); } pages.TryRenewExact(anchor, initial!, initial! with { AuthorityIsCurrent = Authority }, () => true).ShouldBeTrue(); armed = true; lookup.TryResolve(anchor, out var resolved).ShouldBeTrue("a live node replaced 64 times mid-lookup is not missing"); replacements.ShouldBe(Swaps, "the lookup must actually have raced every replacement"); resolved.ShouldNotBeNull(); lookup.TryResolve(anchor, out var final).ShouldBeTrue(); final.ShouldBeSameAs(resolved); }); } /// /// #968: both cadences reach the renewal window on the same tick and each renews the same predecessor. The second /// commit adopts the successor the first already committed (and replaces the node's definition once more) after the /// first cadence has rebound; neither physical stream may be torn down. /// [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] public async Task Concurrent_cadence_renewals_committing_the_same_successor_keep_both_streams() { var ct = TestContext.Current.CancellationToken; LocalDataFixture? peer = null; var subscriptions = new FakeSubscriptions(() => peer!.Serving); using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); peer = origin; subscriptions.SampleClock = origin.Clock; var published = Channel.CreateUnbounded(); var connections = new RenewalConnections(origin); var gate = new HoldSecondRenewalCommit(); await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) => { // #969 de-duplicates concurrent cadence renewals of one predecessor; this test pins the adoption path a second, // concurrent renewal still takes when it is not shared (e.g. an on-demand lapse renewal racing a cadence). access.DeduplicateOverlapRenewalsForTests = false; var client = (SessionClient)session; await BrowseAll(client, anchor, 1); var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; await AddComposedItem(client, slow, anchor, 1, 200, ct); var slowStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct); var original = await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot, ct); (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; await AddComposedItem(client, fast, anchor, 2, 50, ct); var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct); (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); while (connections.MetadataRequests.Reader.TryRead(out _)) { } while (published.Reader.TryRead(out _)) { } // Hold the origin until BOTH renewals are in flight, let one commit and its cadence rebind, then let the // other (identical) renewal commit. connections.HoldMetadata = true; await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromSeconds(9), ct, oneStep: true); await connections.MetadataRequests.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct); await connections.MetadataRequests.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct); connections.ReleaseMetadata.TrySetResult(); await gate.SecondHeld.Task.WaitAsync(SetupWait, ct); var first = await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct); gate.ReleaseSecond.TrySetResult(); (await gate.SecondCommitted.Task.WaitAsync(SetupWait, ct)).ShouldBeTrue("the second renewal adopts the committed successor"); var second = await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct); first.SourceProof.IsValid.ShouldBeTrue(); second.SourceProof.IsValid.ShouldBeTrue(); slowStream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero); (await NextPublishedRenewal(published.Reader, x => Equals(x.Snapshot.Value, 8), ct)).SourceProof.IsValid.ShouldBeTrue(); fastStream.EmitValue(3, 9, origin.Clock.GetUtcNow(), TimeSpan.Zero); (await NextPublishedRenewal(published.Reader, x => Equals(x.Snapshot.Value, 9), ct)).SourceProof.IsValid.ShouldBeTrue(); subscriptions.Opens.ShouldBe(2, "a renewal another cadence already committed must not tear down a physical stream"); }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections, renewalSinkFactory: gate.Wrap); } /// /// #969: both cadences reach the renewal window on the same tick. They share ONE renewal of the predecessor — one /// metadata call, one replacement of the node's committed definition — and both rebind onto its successor without /// tearing down either physical stream. Before #969 each cadence ran its own renewal (2 metadata calls, 2 replacements). /// [Theory(Timeout = 90000), Trait("Phase", "P11Renewal")] [InlineData(false)] [InlineData(true)] public async Task Concurrent_cadence_renewals_of_one_predecessor_share_one_metadata_call_and_one_commit(bool sharedRenewalFails) { var ct = TestContext.Current.CancellationToken; LocalDataFixture? peer = null; var subscriptions = new FakeSubscriptions(() => peer!.Serving); using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); peer = origin; subscriptions.SampleClock = origin.Clock; var published = Channel.CreateUnbounded(); var connections = new RenewalConnections(origin); var commits = new CountRenewalCommits(); await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) => { var client = (SessionClient)session; await BrowseAll(client, anchor, 1); var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; await AddComposedItem(client, slow, anchor, 1, 200, ct); var slowStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct); var original = await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot, ct); (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; await AddComposedItem(client, fast, anchor, 2, 50, ct); var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct); (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); while (connections.MetadataRequests.Reader.TryRead(out _)) { } while (published.Reader.TryRead(out _)) { } Volatile.Write(ref commits.Calls, 0); // Hold the origin until the second cadence has either joined the first one's renewal (#969) or sent its own // metadata request (before #969), so both renewals are provably concurrent. connections.HoldMetadata = true; // A shared renewal that does not commit is no verdict for the cadence that joined it: it renews for itself. if (sharedRenewalFails) connections.FailHeldMetadata = 1; await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromSeconds(9), ct, oneStep: true); await connections.MetadataRequests.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct); var metadataCalls = 1; var giveUp = DateTime.UtcNow + SetupWait; while (access.OverlapRenewalsJoinedForTests == 0 && connections.MetadataRequests.Reader.Count == 0) { if (DateTime.UtcNow > giveUp) throw new TimeoutException("The second cadence never reached its renewal."); await Task.Delay(1, ct); } connections.ReleaseMetadata.TrySetResult(); if (sharedRenewalFails) { // Only the joiner renews now; the failed cadence retries on a later tick (not stepped here). (await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct)).SourceProof.IsValid.ShouldBeTrue(); while (connections.MetadataRequests.Reader.TryRead(out _)) metadataCalls++; metadataCalls.ShouldBe(2, "the joiner renews for itself after the shared renewal failed"); Volatile.Read(ref commits.Calls).ShouldBe(1); access.OverlapRenewalsJoinedForTests.ShouldBe(1); subscriptions.Opens.ShouldBe(2); return; } (await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct)).SourceProof.IsValid.ShouldBeTrue(); (await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct)).SourceProof.IsValid.ShouldBeTrue(); slowStream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero); (await NextPublishedRenewal(published.Reader, x => Equals(x.Snapshot.Value, 8), ct)).SourceProof.IsValid.ShouldBeTrue(); fastStream.EmitValue(3, 9, origin.Clock.GetUtcNow(), TimeSpan.Zero); (await NextPublishedRenewal(published.Reader, x => Equals(x.Snapshot.Value, 9), ct)).SourceProof.IsValid.ShouldBeTrue(); while (connections.MetadataRequests.Reader.TryRead(out _)) metadataCalls++; metadataCalls.ShouldBe(1, "concurrent cadences renewing one predecessor must share one metadata call"); Volatile.Read(ref commits.Calls).ShouldBe(1, "concurrent cadences renewing one predecessor must replace the definition once"); access.OverlapRenewalsJoinedForTests.ShouldBe(1); subscriptions.Opens.ShouldBe(2, "a shared renewal must not tear down a physical stream"); }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections, renewalSinkFactory: commits.Wrap); } private sealed class CountRenewalCommits { public int Calls; public IProjectedNamespacePageSink Wrap(IProjectedNamespacePageSink inner) => new Sink(inner, this); private sealed class Sink(IProjectedNamespacePageSink inner, CountRenewalCommits owner) : IProjectedNamespacePageSink { public bool TryApply(NodeId parent, IReadOnlyList nodes, Func commit) => inner.TryApply(parent, nodes, commit); public bool TryRemove(NodeId node, ProjectedVariableDefinition expected) => inner.TryRemove(node, expected); public bool TryApplyRootLeaf(NodeId node, ProjectedVariableDefinition definition, Func commit) => inner.TryApplyRootLeaf(node, definition, commit); public bool TryRenewExact(NodeId node, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func commit) { var committed = inner.TryRenewExact(node, expected, replacement, commit); if (committed) Interlocked.Increment(ref owner.Calls); return committed; } } } private sealed class HoldSecondRenewalCommit { private int _calls; public readonly TaskCompletionSource SecondHeld = new(TaskCreationOptions.RunContinuationsAsynchronously); public readonly TaskCompletionSource ReleaseSecond = new(TaskCreationOptions.RunContinuationsAsynchronously); public readonly TaskCompletionSource SecondCommitted = new(TaskCreationOptions.RunContinuationsAsynchronously); public IProjectedNamespacePageSink Wrap(IProjectedNamespacePageSink inner) => new Sink(inner, this); private sealed class Sink(IProjectedNamespacePageSink inner, HoldSecondRenewalCommit owner) : IProjectedNamespacePageSink { public bool TryApply(NodeId parent, IReadOnlyList nodes, Func commit) => inner.TryApply(parent, nodes, commit); public bool TryRemove(NodeId node, ProjectedVariableDefinition expected) => inner.TryRemove(node, expected); public bool TryApplyRootLeaf(NodeId node, ProjectedVariableDefinition definition, Func commit) => inner.TryApplyRootLeaf(node, definition, commit); public bool TryRenewExact(NodeId node, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func commit) { if (Interlocked.Increment(ref owner._calls) != 2) return inner.TryRenewExact(node, expected, replacement, commit); owner.SecondHeld.TrySetResult(); owner.ReleaseSecond.Task.Wait(TimeSpan.FromSeconds(30)); var result = inner.TryRenewExact(node, expected, replacement, commit); owner.SecondCommitted.TrySetResult(result); return result; } } } }