diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 373cc2a3a..73a774a08 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -158,6 +158,15 @@ Two cadences of the same node made it likely, because both renew on the same tic (redundant) renewal replaces the definition again while the first cadence rebinds. A lookup now re-evaluates a definition replaced mid-check instead of reporting it missing. +Since #969 cadences of the same node no longer renew it twice: a cadence that reaches the renewal window +while another cadence is already renewing the same predecessor waits for that renewal (one origin +metadata call, one definition replacement) and, if it committed, rebinds onto its successor exactly as +when it finds the successor already committed (its own caller is re-authorized against the successor). +A shared renewal that did not commit (the other cadence stopped, its caller was refused, the origin +failed) is no verdict for the waiting cadence, which then renews for itself, so one cadence's failure only +delays another's renewal. On-demand lapse renewals (Read/HistoryRead/Write of a lapsed node) are not +shared with cadence renewals; a racing pair still commits one successor and the second adopts it. + ## Rollout and diagnosis 1. Provision TLS trust and connection-scoped target credentials on each consumer; configure the diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs index 4701bf779..12375c8ee 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs @@ -23,6 +23,14 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable // until they are equal so a tick is always evaluated at the fake instant that fired it, never at a later one under load. private long _renewalTicksQueued, _renewalTicksHandled; internal bool RenewalTicksQuiescentForTests => Volatile.Read(ref _renewalTicksHandled) == Volatile.Read(ref _renewalTicksQueued); + // #969: cadence (overlap) renewals in flight, per predecessor proof. Two Subscribe cadences of one node reach the renewal + // window on the same tick; the second joins the first's renewal instead of running its own metadata call and replacing + // the node's committed definition a second time. A joiner whose shared renewal did not commit renews for itself, so one + // cadence stopping (or its caller being refused) only delays the other's renewal, never fails it. + private readonly Dictionary Renewal)> _overlapRenewals = new(System.Collections.Generic.ReferenceEqualityComparer.Instance); + internal bool DeduplicateOverlapRenewalsForTests { get; set; } = true; + private int _overlapRenewalsJoined; + internal int OverlapRenewalsJoinedForTests => Volatile.Read(ref _overlapRenewalsJoined); /// #920: runs on the stream pump after a publish passed its demand check, before the duplicate-baseline check. internal Action? AfterPublishDemandCheckForTests { get; set; } private readonly IFederatedProjectionCatalog _catalog; @@ -415,6 +423,53 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable DataOperations.HistoryRead => OpcUaOperation.HistoryRead, _ => throw new ArgumentOutOfRangeException(nameof(operation)) }; + /// + /// #969: runs (a cadence's overlap renewal of ) unless another + /// cadence is already renewing the same predecessor of the same node, in which case it waits for that renewal. A + /// shared renewal that committed is this cadence's success too: its successor is then the node's committed proof, + /// which the cadence adopts exactly as when it finds the successor already committed (its own caller is re-authorized + /// by ). One that did not commit is no verdict for this cadence, which renews for + /// itself. + /// + private async Task RenewOverlapOnceAsync(ProjectedNodeProof predecessor, NodeId nodeId, Func> renew, + CancellationToken cancellationToken) + { + Task? shared = null; + TaskCompletionSource? owned = null; + lock (_sync) + { + if (DeduplicateOverlapRenewalsForTests) + { + if (_overlapRenewals.TryGetValue(predecessor, out var running)) + { + if (running.NodeId == nodeId) shared = running.Renewal; + } + else + { + owned = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _overlapRenewals.Add(predecessor, (nodeId, owned.Task)); + } + } + } + if (shared is not null) + { + Interlocked.Increment(ref _overlapRenewalsJoined); + bool sharedRenewed; + // Cancelled while waiting: the same verdict as this cadence's own renewal being cancelled. + try { sharedRenewed = await shared.WaitAsync(cancellationToken).ConfigureAwait(false); } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { return false; } + return sharedRenewed || await renew().ConfigureAwait(false); + } + if (owned is null) return await renew().ConfigureAwait(false); + var renewed = false; + try { renewed = await renew().ConfigureAwait(false); return renewed; } + finally + { + lock (_sync) _overlapRenewals.Remove(predecessor); + owned.TrySetResult(renewed); + } + } + private sealed class Demand(ProjectedDataAccess owner, NodeId nodeId, ProjectedVariableDefinition definition, ProjectedNodeProof proof, DataCallerIdentity? caller, DataOperations operation, IDisposable pin, IProjectedNodePin nodePin, string connectionId, long writeRoleGeneration, ConfiguredProjectionCapability? configured) : IProjectedDemandLease { @@ -1529,7 +1584,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable else if (_owner._catalog is RemoteNamespaceResolver resolver && _owner._renewalSink is { } sink) { using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, demand.CancellationToken); - success = await RenewOwnedAsync(demand, expected, resolver, sink, linked.Token, overlap: true).ConfigureAwait(false); + success = await _owner.RenewOverlapOnceAsync(expected.Proof, demand.NodeId, + () => RenewOwnedAsync(demand, expected, resolver, sink, linked.Token, overlap: true), linked.Token).ConfigureAwait(false); } await _events.Writer.WriteAsync(new RenewedEvent(demand, expected, success), token).ConfigureAwait(false); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalConcurrentCommitTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalConcurrentCommitTests.cs index 47cba7290..708475e6a 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalConcurrentCommitTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalConcurrentCommitTests.cs @@ -79,6 +79,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests 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; @@ -119,6 +122,104 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests 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; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalContinuityWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalContinuityWireTests.cs index 1a9b37365..96552505d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalContinuityWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalContinuityWireTests.cs @@ -475,6 +475,8 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests private readonly object _routeIdentity = new(); internal readonly Channel MetadataRequests = Channel.CreateUnbounded(); internal bool HoldMetadata; + /// #969: the first held metadata request fails once released (the shared renewal does not commit). + internal int FailHeldMetadata; internal bool SuppressFirstRenewalSnapshot; internal bool BadFirstRenewalSnapshot, BadEverySnapshot; internal bool HoldFirstRenewalRemoveAck; @@ -509,6 +511,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests { owner.MetadataHeld.TrySetResult(); await owner.ReleaseMetadata.Task; + if (Interlocked.Exchange(ref owner.FailHeldMetadata, 0) != 0) throw new IOException("origin unavailable"); } return await inner.GetMetadataAsync(request, ct); }