Merge #965: metadata-renewal wire tests pace the fake clock deterministically (tick-quiescence counters, AdvanceInOneStep); residual ~1% heavy-load hang tracked #968
v2-ci / unit-tests (push) Has been cancelled
v2-ci / unit-tests (push) Has been cancelled
This commit is contained in:
+31
-11
@@ -34,7 +34,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
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(TimeSpan.FromSeconds(10), ct);
|
||||
var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
|
||||
var original = await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot, ct);
|
||||
var notification = await PublishComposedNotification(client, 1, ct);
|
||||
notification.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
||||
var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
||||
@@ -47,23 +47,29 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
using var simultaneousSuccessors = new Barrier(2);
|
||||
access.BeforeSuccessorAdoptionForTests = () =>
|
||||
{
|
||||
if (!simultaneousSuccessors.SignalAndWait(TimeSpan.FromSeconds(5)))
|
||||
if (!simultaneousSuccessors.SignalAndWait(SetupWait))
|
||||
throw new TimeoutException("Both cadence successors must prepare before either adopts.");
|
||||
};
|
||||
|
||||
// The 15-second lease must be renewed and a successor baseline accepted
|
||||
// while its predecessor still has authority. Metadata alone is not data.
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(9));
|
||||
// Jump in ONE step: a renewal starts at the fake time its tick is processed at (the successor
|
||||
// lease is stamped from the request start), so stepping through 7.5..9 s would let the
|
||||
// successor be issued anywhere in that range depending on real thread scheduling.
|
||||
await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromSeconds(9), ct, oneStep: true);
|
||||
await connections.MetadataRequests.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct);
|
||||
var freshTask = NextPublished(published.Reader,
|
||||
var freshTask = NextPublishedRenewal(published.Reader,
|
||||
x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct);
|
||||
// A subscription renewal never queues: an attempt refused while the other cadence's renewal is in
|
||||
// flight retries on the NEXT tick. Supply those ticks (each settled before the next), as the
|
||||
// original 8 x 500 ms loop did, but only while the renewal has not completed.
|
||||
for (var i = 0; i < 8 && !freshTask.IsCompleted; i++)
|
||||
{
|
||||
origin.Clock.Advance(TimeSpan.FromMilliseconds(500));
|
||||
await Task.Delay(100, ct);
|
||||
await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromMilliseconds(500), ct);
|
||||
await Task.WhenAny(freshTask, Task.Delay(100, ct));
|
||||
}
|
||||
var fresh = await freshTask;
|
||||
var otherFresh = await NextPublished(published.Reader,
|
||||
var otherFresh = await NextPublishedRenewal(published.Reader,
|
||||
x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct);
|
||||
access.BeforeSuccessorAdoptionForTests = null;
|
||||
otherFresh.SourceProof.ShouldNotBeSameAs(fresh.SourceProof, "each cadence must establish its own successor coverage");
|
||||
@@ -92,19 +98,19 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
try
|
||||
{
|
||||
slowStream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero);
|
||||
slowUpdate = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 8), ct);
|
||||
slowUpdate = await NextPublishedRenewal(published.Reader, x => Equals(x.Snapshot.Value, 8), ct);
|
||||
slowUpdate.SourceProof.IsValid.ShouldBeTrue();
|
||||
slowUpdate.SourceProof.IsSourceValid.ShouldBeTrue();
|
||||
var slowValue = await PublishComposedValue(client, 1, ct);
|
||||
var slowValue = await PublishComposedValueEqualTo(client, 1, 8, ct);
|
||||
slowValue.StatusCode.ShouldBe(StatusCodes.Good);
|
||||
slowValue.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
|
||||
fastStream.EmitValue(3, 9, origin.Clock.GetUtcNow(), TimeSpan.Zero);
|
||||
// NextPublished is signaled only after the SDK sink accepts this
|
||||
// actual sample; it is not merely publisher queue admission.
|
||||
fastUpdate = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 9), ct);
|
||||
fastUpdate = await NextPublishedRenewal(published.Reader, x => Equals(x.Snapshot.Value, 9), ct);
|
||||
fastUpdate.SourceProof.IsValid.ShouldBeTrue();
|
||||
fastUpdate.SourceProof.IsSourceValid.ShouldBeTrue();
|
||||
var fastValue = await PublishComposedValue(client, 2, ct);
|
||||
var fastValue = await PublishComposedValueEqualTo(client, 2, 9, ct);
|
||||
fastValue.StatusCode.ShouldBe(StatusCodes.Good);
|
||||
fastValue.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(9);
|
||||
}
|
||||
@@ -450,6 +456,20 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
finally { connections.ReleaseMetadata.TrySetResult(); }
|
||||
}
|
||||
|
||||
/// <summary>Both items monitor the same node, so one cadence's emitted value is also queued for the other
|
||||
/// item; a publish cycle that lands between the two emits legitimately delivers the earlier value first.
|
||||
/// Reads this item's notifications until the expected value arrives (ordering is preserved, so it must).</summary>
|
||||
private static async Task<Opc.Ua.DataValue> PublishComposedValueEqualTo(SessionClient client, uint handle, int expected, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
while (true)
|
||||
{
|
||||
var value = await PublishComposedValue(client, handle, timeout.Token);
|
||||
if (Equals(value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy), expected)) return value;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RenewalConnections(LocalDataFixture fixture, bool identified = true) : IGrpcDataAdapterConnectionSource
|
||||
{
|
||||
private readonly object _routeIdentity = new();
|
||||
|
||||
+48
-13
@@ -31,23 +31,23 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
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(TimeSpan.FromSeconds(10), ct);
|
||||
await NextPublished(published.Reader, x => x.IsCompleteSnapshot, 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(TimeSpan.FromSeconds(10), 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))
|
||||
{ origin.Clock.Advance(TimeSpan.FromMilliseconds(125)); await Task.Delay(20, ct); }
|
||||
var p2First = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > started, ct);
|
||||
origin.Clock.Advance(TimeSpan.FromMilliseconds(125));
|
||||
var p2Fast = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2First.ReceivedTimestamp, ct);
|
||||
{ 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,
|
||||
@@ -55,11 +55,13 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
PauseFastRenewalTimer(origin.Clock);
|
||||
while (published.Reader.TryRead(out _)) { }
|
||||
var remaining = TimeSpan.FromSeconds(15) - origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp());
|
||||
if (remaining > TimeSpan.Zero) origin.Clock.Advance(remaining);
|
||||
if (remaining > TimeSpan.Zero) await AdvanceAndSettle(origin.Clock, access, remaining, ct);
|
||||
p2First.SourceProof.IsValid.ShouldBeTrue(); // Also releases the expired P1 cache pin.
|
||||
var p3Task = NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2Fast.ReceivedTimestamp, ct);
|
||||
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++)
|
||||
{ origin.Clock.Advance(TimeSpan.FromMilliseconds(250)); await Task.Delay(100, ct); }
|
||||
{ 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);
|
||||
@@ -75,9 +77,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
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, TimeSpan.FromSeconds(5)).ShouldBeTrue(
|
||||
SpinWait.SpinUntil(() => ProjectedStreamDiagnostics.Capture()["FreshAge"] > before, SetupWait).ShouldBeTrue(
|
||||
"the fast cadence's ordinary frame must reach Runtime admission");
|
||||
var delta = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 8), ct);
|
||||
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();
|
||||
@@ -87,7 +89,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
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) origin.Clock.Advance(untilP2Expired);
|
||||
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();
|
||||
@@ -97,6 +99,39 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
}, 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;
|
||||
|
||||
@@ -68,6 +68,27 @@ internal sealed class ManualTimeProvider : TimeProvider
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Like <see cref="Advance"/>, but time reaches <c>now + by</c> BEFORE any timer fires, so every
|
||||
/// callback (and any thread it wakes) observes the final instant, never an intermediate due time. Periodic
|
||||
/// timers still fire once per elapsed period, in due order. Use it where a test must not let work woken by an
|
||||
/// early tick start at an intermediate fake time that depends on real-time thread scheduling.</summary>
|
||||
public void AdvanceInOneStep(TimeSpan by)
|
||||
{
|
||||
DateTimeOffset target;
|
||||
lock (_lock) { target = _now + by; _now = target; }
|
||||
while (true)
|
||||
{
|
||||
ManualTimer? next;
|
||||
lock (_lock)
|
||||
{
|
||||
next = _timers.Where(t => t.Due <= target).MinBy(t => t.Due);
|
||||
if (next is null) return;
|
||||
next.Due = next.Period is { } p ? next.Due + p : null;
|
||||
}
|
||||
next.Fire();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ManualTimer(ManualTimeProvider owner, TimerCallback callback, object? state) : ITimer
|
||||
{
|
||||
public DateTimeOffset? Due; // guarded by owner._lock
|
||||
|
||||
Reference in New Issue
Block a user