Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPredecessorWireTests.cs
T
Joseph Doherty 34014190a7 test(runtime): #965 pace metadata-renewal wire tests by observed progress, not wall-clock delays
- ProjectedDataAccess: internal queued/handled renewal-tick counters (RenewalTicksQuiescentForTests) so a test can wait until every tick a clock advance fired has been handled.
- ManualTimeProvider.AdvanceInOneStep: all timers see the final instant (successor lease is stamped from request start).
- Live_predecessor_cadence...: Task.Delay(20/100) pacing replaced by advance-and-settle; 10 s waits widened.
- Two_sdk_cadences...: 9 s jump in one step (deterministic successor issue time, fixes the 7.45 s margin flake); read each item's notifications until its expected value (8 vs 9 flake); barrier timeout widened.
Residual ~1% hang tracked in #968.
2026-12-02 13:54:50 -05:00

176 lines
11 KiB
C#

using System.Collections;
using System.Reflection;
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;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
[Fact(Timeout = 90000), Trait("Phase", "P11Renewal")]
public async Task Live_predecessor_cadence_publishes_ordinary_delta_after_peer_adopts_next_authority()
{
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 started = origin.Clock.GetTimestamp();
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
var connections = new RenewalConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, 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);
await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot, ct);
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
origin.Clock.Advance(TimeSpan.FromMilliseconds(125));
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);
fastStream.Interval.ShouldNotBe(slowStream.Interval);
(await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good);
while (published.Reader.TryRead(out _)) { }
// Stagger timer phases so each cadence establishes P2 independently.
while (origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp()) < TimeSpan.FromSeconds(7.5))
{ await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromMilliseconds(125), ct); }
var p2First = await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > started, ct);
await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromMilliseconds(125), ct);
var p2Fast = await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2First.ReceivedTimestamp, ct);
p2Fast.SourceProof.IsValid.ShouldBeTrue();
// Hold only the fast cadence's next renewal tick. Its transport, demand,
// original P2 lease and value stream continue to run independently.
PauseFastRenewalTimer(origin.Clock);
while (published.Reader.TryRead(out _)) { }
var remaining = TimeSpan.FromSeconds(15) - origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp());
if (remaining > TimeSpan.Zero) await AdvanceAndSettle(origin.Clock, access, remaining, ct);
p2First.SourceProof.IsValid.ShouldBeTrue(); // Also releases the expired P1 cache pin.
var p3Task = NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2Fast.ReceivedTimestamp, ct);
// A subscription renewal never queues and retries on the next tick, so p3 needs a tick or two; give each
// one a generous real-time window to complete before moving the clock again (no fixed wall-clock cadence).
for (var i = 0; i < 4 && !p3Task.IsCompleted; i++)
{ await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromMilliseconds(250), ct); await Task.WhenAny(p3Task, Task.Delay(RenewalWait, ct)); }
var p3 = await p3Task;
p3.SourceProof.IsValid.ShouldBeTrue();
var state = CapturePredecessorAuthority(access, sink);
state.SlowDemand.IsValid.ShouldBeTrue();
state.FastDemand.IsValid.ShouldBeTrue();
state.Current.ShouldBeSameAs(state.SlowProof);
state.Previous.ShouldBeSameAs(state.FastProof);
state.FastProof.Lease.IsValid.ShouldBeTrue();
state.Current.Lease.IsValid.ShouldBeTrue();
p2Fast.SourceProof.IsValid.ShouldBeTrue();
p2Fast.SourceProof.IsSourceValid.ShouldBeTrue();
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
var before = ProjectedStreamDiagnostics.Capture()["FreshAge"];
fastStream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero);
SpinWait.SpinUntil(() => ProjectedStreamDiagnostics.Capture()["FreshAge"] > before, SetupWait).ShouldBeTrue(
"the fast cadence's ordinary frame must reach Runtime admission");
var delta = await NextPublishedRenewal(published.Reader, x => Equals(x.Snapshot.Value, 8), ct);
delta.IsCompleteSnapshot.ShouldBeFalse();
delta.SourceProof.ShouldBeSameAs(p2Fast.SourceProof);
delta.SourceProof.IsValid.ShouldBeTrue();
delta.SourceVersion.ShouldBe(2);
subscriptions.Opens.ShouldBe(2);
var originalP2Lease = state.FastProof.Lease;
var originalP3Lease = state.Current.Lease;
var untilP2Expired = TimeSpan.FromSeconds(23) - origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp());
if (untilP2Expired > TimeSpan.Zero) await AdvanceAndSettle(origin.Clock, access, untilP2Expired, ct);
delta.OriginAgeBounds.Advance(origin.Clock.GetElapsedTime(delta.ReceivedTimestamp, origin.Clock.GetTimestamp()))
.IsFresh(TimeSpan.FromSeconds(30)).ShouldBeTrue("the sample must still be fresh when its original authority expires");
originalP2Lease.IsValid.ShouldBeFalse();
delta.SourceProof.IsValid.ShouldBeFalse("P2 evidence cannot borrow P3's longer authority lifetime");
originalP3Lease.IsValid.ShouldBeTrue();
p3.SourceProof.IsValid.ShouldBeTrue();
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
}
// The shared NextPublished allows 10 s of wall clock, which a renewal round trip (metadata fetch, remove/add, baseline)
// can exceed on a loaded host (#965); the fake clock is frozen meanwhile, so a longer wait costs nothing when healthy.
private static readonly TimeSpan SetupWait = TimeSpan.FromSeconds(30);
private static readonly TimeSpan RenewalWait = TimeSpan.FromSeconds(5);
private static async Task<ProjectedValueUpdate> NextPublishedRenewal(ChannelReader<ProjectedValueUpdate> reader,
Func<ProjectedValueUpdate, bool> predicate, CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(60));
while (true)
{
var update = await reader.ReadAsync(timeout.Token);
if (predicate(update)) return update;
}
}
/// <summary>Moves the fake clock, then waits (positively, not by wall-clock cadence) until every renewal tick that
/// advance fired has been handled, so each tick is evaluated at the fake instant that fired it. Without this a
/// loaded host handles a tick after the test thread has already stepped further, merging cadences the test
/// deliberately staggers (#965).</summary>
private static async Task AdvanceAndSettle(ManualTimeProvider clock, ProjectedDataAccess access, TimeSpan by,
CancellationToken ct, bool oneStep = false)
{
if (oneStep) clock.AdvanceInOneStep(by); else clock.Advance(by);
var giveUp = DateTime.UtcNow + SetupWait;
while (!access.RenewalTicksQuiescentForTests)
{
if (DateTime.UtcNow > giveUp) throw new TimeoutException("Renewal ticks fired by the clock advance were never handled.");
await Task.Delay(1, ct);
}
}
private static void PauseFastRenewalTimer(ManualTimeProvider clock)
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
var sync = typeof(ManualTimeProvider).GetField("_lock", flags)!.GetValue(clock)!;
lock (sync)
{
var timers = (IEnumerable)typeof(ManualTimeProvider).GetField("_timers", flags)!.GetValue(clock)!;
var fastDue = clock.GetUtcNow().AddMilliseconds(250);
var matches = timers.Cast<object>().Where(timer =>
Equals(timer.GetType().GetField("Period", flags)!.GetValue(timer), TimeSpan.FromMilliseconds(250)) &&
Equals(timer.GetType().GetField("Due", flags)!.GetValue(timer), fastDue)).ToArray();
matches.Length.ShouldBe(1, "the staggered fast renewal timer must be uniquely identifiable");
((ITimer)matches[0]).Dispose();
}
}
private static (ProjectedNodeProof Current, ProjectedNodeProof? Previous, ProjectedNodeProof SlowProof,
ProjectedNodeProof FastProof, IProjectedDemandLease SlowDemand, IProjectedDemandLease FastDemand)
CapturePredecessorAuthority(ProjectedDataAccess access, SdkAddressSpaceSink sink)
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
var keys = (IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
var items = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Where(item => item.ClientHandle is 1 or 2).ToArray();
IProjectedDemandLease Demand(uint handle) => (IProjectedDemandLease)items.Single(item => item.ClientHandle == handle)
.GetType().GetField("_demand", flags)!.GetValue(items.Single(item => item.ClientHandle == handle))!;
ProjectedNodeProof Proof(IProjectedDemandLease demand) => (ProjectedNodeProof)demand.GetType().GetProperty("Proof", flags)!.GetValue(demand)!;
var slow = Demand(1); var fast = Demand(2);
var sync = typeof(ProjectedDataAccess).GetField("_sync", flags)!.GetValue(access)!;
object source;
lock (sync) source = ((IDictionary)typeof(ProjectedDataAccess).GetField("_sources", flags)!.GetValue(access)!).Values.Cast<object>().Single();
var sourceGate = source.GetType().GetField("Gate", flags)!.GetValue(source)!;
lock (sourceGate)
{
var current = (ProjectedNodeProof)source.GetType().GetField("_proof", flags)!.GetValue(source)!;
var previous = (ProjectedNodeProof?)source.GetType().GetField("_previousProof", flags)!.GetValue(source);
return (current, previous, Proof(slow), Proof(fast), slow, fast);
}
}
}