Merge #968: node-manager resolve no longer reports a node missing when a renewal replaces its definition mid-check (real race behind the renewal-test hang)
v2-ci / unit-tests (push) Failing after 3h5m28s
v2-ci / unit-tests (push) Failing after 3h5m28s
This commit is contained in:
@@ -150,6 +150,14 @@ under the new stream epoch before it can publish again; old queued or Republish
|
|||||||
the new proof. Withdrawal or expiry of the original local Subscribe authority stops renewal.
|
the new proof. Withdrawal or expiry of the original local Subscribe authority stops renewal.
|
||||||
Consumers can miss intermediate changes during an interruption.
|
Consumers can miss intermediate changes during an interruption.
|
||||||
|
|
||||||
|
A renewal replaces the node's committed definition. Until #968 the lock-free node lookup that every
|
||||||
|
subscription demand check uses answered "no such node" when that replacement landed between its two
|
||||||
|
reads, so a stream racing a renewal could see its live node as gone for an instant and tear its physical
|
||||||
|
stream down (a freshness check breaking the attempt, or `Source unavailable` on the rebind's baseline).
|
||||||
|
Two cadences of the same node made it likely, because both renew on the same tick and the second
|
||||||
|
(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.
|
||||||
|
|
||||||
## Rollout and diagnosis
|
## Rollout and diagnosis
|
||||||
|
|
||||||
1. Provision TLS trust and connection-scoped target credentials on each consumer; configure the
|
1. Provision TLS trust and connection-scoped target credentials on each consumer; configure the
|
||||||
|
|||||||
@@ -4428,12 +4428,16 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
|||||||
{
|
{
|
||||||
// Runtime demand checks can hold a source gate that SDK publication also needs.
|
// Runtime demand checks can hold a source gate that SDK publication also needs.
|
||||||
// Resolve committed metadata without acquiring the SDK address-space lock.
|
// Resolve committed metadata without acquiring the SDK address-space lock.
|
||||||
var committed = Volatile.Read(ref _committedProjectedDefinitions);
|
// #968: the definition is re-read after its checks so a stale one is never answered. A renewal that REPLACED it in
|
||||||
if (!_disposing && committed.TryGetValue(nodeId, out var current) && current.Lifetime.IsActive &&
|
// between is not a missing node: evaluate the replacement. Answering false there made every subscription demand
|
||||||
current.AuthorityIsCurrent() && !_disposing && current.Lifetime.IsActive &&
|
// check racing a metadata renewal see a live node as gone and tear its physical stream down.
|
||||||
Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var latest) &&
|
for (var attempt = 0; attempt < MaxProjectedResolveAttempts; attempt++)
|
||||||
ReferenceEquals(current, latest))
|
|
||||||
{
|
{
|
||||||
|
if (_disposing || !Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var current)) break;
|
||||||
|
var usable = current.Lifetime.IsActive && current.AuthorityIsCurrent() && !_disposing && current.Lifetime.IsActive;
|
||||||
|
if (!Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var latest)) break;
|
||||||
|
if (!ReferenceEquals(current, latest)) continue;
|
||||||
|
if (!usable) break;
|
||||||
definition = current;
|
definition = current;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -4441,16 +4445,22 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>#968: replacements a lock-free projected lookup re-evaluates before giving up (renewals are seconds apart).</summary>
|
||||||
|
private const int MaxProjectedResolveAttempts = 16;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// #922: like <see cref="TryResolve"/> but WITHOUT the authority check, so a node whose metadata lease lapsed can be renewed
|
/// #922: like <see cref="TryResolve"/> but WITHOUT the authority check, so a node whose metadata lease lapsed can be renewed
|
||||||
/// in place. Lock-free (committed snapshot), confers nothing.
|
/// in place. Lock-free (committed snapshot), confers nothing.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition)
|
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition)
|
||||||
{
|
{
|
||||||
var committed = Volatile.Read(ref _committedProjectedDefinitions);
|
for (var attempt = 0; attempt < MaxProjectedResolveAttempts; attempt++)
|
||||||
if (!_disposing && committed.TryGetValue(nodeId, out var current) && current.Lifetime.IsActive &&
|
|
||||||
Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var latest) && ReferenceEquals(current, latest))
|
|
||||||
{
|
{
|
||||||
|
if (_disposing || !Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var current)) break;
|
||||||
|
var active = current.Lifetime.IsActive;
|
||||||
|
if (!Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var latest)) break;
|
||||||
|
if (!ReferenceEquals(current, latest)) continue; // #968: replaced mid-check, not missing
|
||||||
|
if (!active) break;
|
||||||
definition = current;
|
definition = current;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
+145
@@ -0,0 +1,145 @@
|
|||||||
|
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) =>
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user