Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalConcurrentCommitTests.cs
T
Joseph Doherty a571a0fc99 fix(grpc-data): #969 concurrent cadence renewals of one predecessor share one metadata call and one commit
Two Subscribe cadences of one node reach the renewal window on the same tick
and each ran its own overlap renewal of the same predecessor: two origin
metadata calls, and the second commit adopted the first's successor yet
replaced the node's committed definition again (harmless since #968, wasted).

ProjectedDataAccess now keeps in-flight cadence renewals per predecessor proof
(reference identity, same node). A cadence that finds one waits for it; a
committed shared renewal is its success too (it adopts the committed successor
exactly as the existing already-committed shortcut does, its own caller
re-authorized by TryPrepareBinding). A shared renewal that did not commit is no
verdict: the joiner renews for itself, so one cadence stopping or being refused
only delays the other. No sink interface change.

Tests: Concurrent_cadence_renewals_of_one_predecessor_share_one_metadata_call_and_one_commit
(red: 2 metadata calls; green: 1 call, 1 definition replacement, both streams
kept) plus a variant where the shared renewal fails and the joiner renews
itself. The #968 adoption wire test keeps exercising the unshared path via a
test switch.
2026-12-02 15:10:02 -05:00

247 lines
16 KiB
C#

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
{
/// <summary>
/// #968: a metadata renewal replaces the node's committed definition. <c>TryResolve</c> 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.
/// </summary>
[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);
});
}
/// <summary>
/// #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.
/// </summary>
[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<ProjectedValueUpdate>();
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);
}
/// <summary>
/// #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).
/// </summary>
[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<ProjectedValueUpdate>();
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<ProjectedVariableDefinition> nodes, Func<bool> 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<bool> commit) => inner.TryApplyRootLeaf(node, definition, commit);
public bool TryRenewExact(NodeId node, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func<bool> 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<bool> 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<ProjectedVariableDefinition> nodes, Func<bool> 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<bool> commit) => inner.TryApplyRootLeaf(node, definition, commit);
public bool TryRenewExact(NodeId node, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func<bool> 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;
}
}
}
}