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.
This commit is contained in:
@@ -19,6 +19,10 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
|||||||
public TimeProvider Clock { get; }
|
public TimeProvider Clock { get; }
|
||||||
internal Func<TimeSpan, TimeSpan>? RetryJitterForTests { get; set; }
|
internal Func<TimeSpan, TimeSpan>? RetryJitterForTests { get; set; }
|
||||||
internal Action? BeforeSuccessorAdoptionForTests { get; set; }
|
internal Action? BeforeSuccessorAdoptionForTests { get; set; }
|
||||||
|
// #965: renewal ticks queued by cohort timers vs. ticks whose handler has finished. A test that steps a fake clock waits
|
||||||
|
// 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);
|
||||||
/// <summary>#920: runs on the stream pump after a publish passed its demand check, before the duplicate-baseline check.</summary>
|
/// <summary>#920: runs on the stream pump after a publish passed its demand check, before the duplicate-baseline check.</summary>
|
||||||
internal Action<IProjectedDemandLease>? AfterPublishDemandCheckForTests { get; set; }
|
internal Action<IProjectedDemandLease>? AfterPublishDemandCheckForTests { get; set; }
|
||||||
private readonly IFederatedProjectionCatalog _catalog;
|
private readonly IFederatedProjectionCatalog _catalog;
|
||||||
@@ -1554,8 +1558,12 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
|||||||
Math.Min(TimeSpan.FromMilliseconds(250).Ticks, minimumLease.Ticks / 4)));
|
Math.Min(TimeSpan.FromMilliseconds(250).Ticks, minimumLease.Ticks / 4)));
|
||||||
renewalTimer = _owner.Clock.CreateTimer(_ =>
|
renewalTimer = _owner.Clock.CreateTimer(_ =>
|
||||||
{
|
{
|
||||||
if (Interlocked.Exchange(ref renewalQueued, 1) == 0 && !_events.Writer.TryWrite(new RenewalEvent()))
|
if (Interlocked.Exchange(ref renewalQueued, 1) == 0)
|
||||||
Interlocked.Exchange(ref renewalQueued, 0);
|
{
|
||||||
|
Interlocked.Increment(ref _owner._renewalTicksQueued);
|
||||||
|
if (!_events.Writer.TryWrite(new RenewalEvent()))
|
||||||
|
{ Interlocked.Decrement(ref _owner._renewalTicksQueued); Interlocked.Exchange(ref renewalQueued, 0); }
|
||||||
|
}
|
||||||
}, null, renewalInterval, renewalInterval);
|
}, null, renewalInterval, renewalInterval);
|
||||||
pump = PumpAsync(stream, route.Token);
|
pump = PumpAsync(stream, route.Token);
|
||||||
foreach (var demand in initial)
|
foreach (var demand in initial)
|
||||||
@@ -1645,20 +1653,24 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
|||||||
else if (message is RenewalEvent)
|
else if (message is RenewalEvent)
|
||||||
{
|
{
|
||||||
Interlocked.Exchange(ref renewalQueued, 0);
|
Interlocked.Exchange(ref renewalQueued, 0);
|
||||||
if (_registrations.Values.Any(registration => registration.Renewal &&
|
try
|
||||||
registration.RenewalPredecessor is not { IsValid: true }))
|
|
||||||
throw new InvalidDataException("The predecessor expired before its successor baseline completed.");
|
|
||||||
foreach (var witnesses in evidence.Values)
|
|
||||||
foreach (var expired in witnesses.Where(proof => !proof.LeaseValid).ToArray()) { expired.Close(); witnesses.Remove(expired); }
|
|
||||||
foreach (var registration in _registrations.Values.ToArray())
|
|
||||||
{
|
{
|
||||||
var demand = registration.Demand;
|
if (_registrations.Values.Any(registration => registration.Renewal &&
|
||||||
if (registration.Removed || renewals.ContainsKey(demand) || !demand.IsValid ||
|
registration.RenewalPredecessor is not { IsValid: true }))
|
||||||
demand.Proof.Lease is not BoundProjectionLease lease || lease.RouteIdentity is null ||
|
throw new InvalidDataException("The predecessor expired before its successor baseline completed.");
|
||||||
lease.Remaining <= TimeSpan.Zero || lease.Remaining > lease.UsableDuration / 2) continue;
|
foreach (var witnesses in evidence.Values)
|
||||||
var expected = demand.CurrentBinding;
|
foreach (var expired in witnesses.Where(proof => !proof.LeaseValid).ToArray()) { expired.Close(); witnesses.Remove(expired); }
|
||||||
renewals[demand] = RenewAsync(demand, expected, route.Token);
|
foreach (var registration in _registrations.Values.ToArray())
|
||||||
|
{
|
||||||
|
var demand = registration.Demand;
|
||||||
|
if (registration.Removed || renewals.ContainsKey(demand) || !demand.IsValid ||
|
||||||
|
demand.Proof.Lease is not BoundProjectionLease lease || lease.RouteIdentity is null ||
|
||||||
|
lease.Remaining <= TimeSpan.Zero || lease.Remaining > lease.UsableDuration / 2) continue;
|
||||||
|
var expected = demand.CurrentBinding;
|
||||||
|
renewals[demand] = RenewAsync(demand, expected, route.Token);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
finally { Interlocked.Increment(ref _owner._renewalTicksHandled); }
|
||||||
}
|
}
|
||||||
else if (message is RenewedEvent renewed)
|
else if (message is RenewedEvent renewed)
|
||||||
{
|
{
|
||||||
@@ -1865,7 +1877,11 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
|||||||
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
|
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
|
||||||
catch (Exception) { }
|
catch (Exception) { }
|
||||||
route?.Dispose();
|
route?.Dispose();
|
||||||
while (_events.Reader.TryRead(out var remaining)) if (remaining is FrameEvent f) { Interlocked.Add(ref _frameBytes, -f.Bytes); (f.Frame as IDisposable)?.Dispose(); }
|
while (_events.Reader.TryRead(out var remaining))
|
||||||
|
{
|
||||||
|
if (remaining is RenewalEvent) Interlocked.Increment(ref _owner._renewalTicksHandled);
|
||||||
|
else if (remaining is FrameEvent f) { Interlocked.Add(ref _frameBytes, -f.Bytes); (f.Frame as IDisposable)?.Dispose(); }
|
||||||
|
}
|
||||||
lock (_owner._sync) _refreshRequests.Clear();
|
lock (_owner._sync) _refreshRequests.Clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+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;
|
var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
||||||
await AddComposedItem(client, slow, anchor, 1, 200, ct);
|
await AddComposedItem(client, slow, anchor, 1, 200, ct);
|
||||||
var slowStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), 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);
|
var notification = await PublishComposedNotification(client, 1, ct);
|
||||||
notification.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
notification.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
||||||
var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
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);
|
using var simultaneousSuccessors = new Barrier(2);
|
||||||
access.BeforeSuccessorAdoptionForTests = () =>
|
access.BeforeSuccessorAdoptionForTests = () =>
|
||||||
{
|
{
|
||||||
if (!simultaneousSuccessors.SignalAndWait(TimeSpan.FromSeconds(5)))
|
if (!simultaneousSuccessors.SignalAndWait(SetupWait))
|
||||||
throw new TimeoutException("Both cadence successors must prepare before either adopts.");
|
throw new TimeoutException("Both cadence successors must prepare before either adopts.");
|
||||||
};
|
};
|
||||||
|
|
||||||
// The 15-second lease must be renewed and a successor baseline accepted
|
// The 15-second lease must be renewed and a successor baseline accepted
|
||||||
// while its predecessor still has authority. Metadata alone is not data.
|
// 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);
|
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);
|
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++)
|
for (var i = 0; i < 8 && !freshTask.IsCompleted; i++)
|
||||||
{
|
{
|
||||||
origin.Clock.Advance(TimeSpan.FromMilliseconds(500));
|
await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromMilliseconds(500), ct);
|
||||||
await Task.Delay(100, ct);
|
await Task.WhenAny(freshTask, Task.Delay(100, ct));
|
||||||
}
|
}
|
||||||
var fresh = await freshTask;
|
var fresh = await freshTask;
|
||||||
var otherFresh = await NextPublished(published.Reader,
|
var otherFresh = await NextPublishedRenewal(published.Reader,
|
||||||
x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct);
|
x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct);
|
||||||
access.BeforeSuccessorAdoptionForTests = null;
|
access.BeforeSuccessorAdoptionForTests = null;
|
||||||
otherFresh.SourceProof.ShouldNotBeSameAs(fresh.SourceProof, "each cadence must establish its own successor coverage");
|
otherFresh.SourceProof.ShouldNotBeSameAs(fresh.SourceProof, "each cadence must establish its own successor coverage");
|
||||||
@@ -92,19 +98,19 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
slowStream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero);
|
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.IsValid.ShouldBeTrue();
|
||||||
slowUpdate.SourceProof.IsSourceValid.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.StatusCode.ShouldBe(StatusCodes.Good);
|
||||||
slowValue.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
|
slowValue.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
|
||||||
fastStream.EmitValue(3, 9, origin.Clock.GetUtcNow(), TimeSpan.Zero);
|
fastStream.EmitValue(3, 9, origin.Clock.GetUtcNow(), TimeSpan.Zero);
|
||||||
// NextPublished is signaled only after the SDK sink accepts this
|
// NextPublished is signaled only after the SDK sink accepts this
|
||||||
// actual sample; it is not merely publisher queue admission.
|
// 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.IsValid.ShouldBeTrue();
|
||||||
fastUpdate.SourceProof.IsSourceValid.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.StatusCode.ShouldBe(StatusCodes.Good);
|
||||||
fastValue.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(9);
|
fastValue.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(9);
|
||||||
}
|
}
|
||||||
@@ -450,6 +456,20 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|||||||
finally { connections.ReleaseMetadata.TrySetResult(); }
|
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 sealed class RenewalConnections(LocalDataFixture fixture, bool identified = true) : IGrpcDataAdapterConnectionSource
|
||||||
{
|
{
|
||||||
private readonly object _routeIdentity = new();
|
private readonly object _routeIdentity = new();
|
||||||
|
|||||||
+48
-13
@@ -31,23 +31,23 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|||||||
await BrowseAll(client, anchor, 1);
|
await BrowseAll(client, anchor, 1);
|
||||||
var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
||||||
await AddComposedItem(client, slow, anchor, 1, 200, ct);
|
await AddComposedItem(client, slow, anchor, 1, 200, ct);
|
||||||
var slowStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
var slowStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct);
|
||||||
await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct);
|
await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot, ct);
|
||||||
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
||||||
origin.Clock.Advance(TimeSpan.FromMilliseconds(125));
|
origin.Clock.Advance(TimeSpan.FromMilliseconds(125));
|
||||||
var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
||||||
await AddComposedItem(client, fast, anchor, 2, 50, ct);
|
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);
|
fastStream.Interval.ShouldNotBe(slowStream.Interval);
|
||||||
(await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
(await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
||||||
while (published.Reader.TryRead(out _)) { }
|
while (published.Reader.TryRead(out _)) { }
|
||||||
|
|
||||||
// Stagger timer phases so each cadence establishes P2 independently.
|
// Stagger timer phases so each cadence establishes P2 independently.
|
||||||
while (origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp()) < TimeSpan.FromSeconds(7.5))
|
while (origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp()) < TimeSpan.FromSeconds(7.5))
|
||||||
{ origin.Clock.Advance(TimeSpan.FromMilliseconds(125)); await Task.Delay(20, ct); }
|
{ await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromMilliseconds(125), ct); }
|
||||||
var p2First = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > started, ct);
|
var p2First = await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > started, ct);
|
||||||
origin.Clock.Advance(TimeSpan.FromMilliseconds(125));
|
await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromMilliseconds(125), ct);
|
||||||
var p2Fast = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2First.ReceivedTimestamp, ct);
|
var p2Fast = await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2First.ReceivedTimestamp, ct);
|
||||||
p2Fast.SourceProof.IsValid.ShouldBeTrue();
|
p2Fast.SourceProof.IsValid.ShouldBeTrue();
|
||||||
|
|
||||||
// Hold only the fast cadence's next renewal tick. Its transport, demand,
|
// Hold only the fast cadence's next renewal tick. Its transport, demand,
|
||||||
@@ -55,11 +55,13 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|||||||
PauseFastRenewalTimer(origin.Clock);
|
PauseFastRenewalTimer(origin.Clock);
|
||||||
while (published.Reader.TryRead(out _)) { }
|
while (published.Reader.TryRead(out _)) { }
|
||||||
var remaining = TimeSpan.FromSeconds(15) - origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp());
|
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.
|
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++)
|
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;
|
var p3 = await p3Task;
|
||||||
p3.SourceProof.IsValid.ShouldBeTrue();
|
p3.SourceProof.IsValid.ShouldBeTrue();
|
||||||
var state = CapturePredecessorAuthority(access, sink);
|
var state = CapturePredecessorAuthority(access, sink);
|
||||||
@@ -75,9 +77,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|||||||
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
|
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
|
||||||
var before = ProjectedStreamDiagnostics.Capture()["FreshAge"];
|
var before = ProjectedStreamDiagnostics.Capture()["FreshAge"];
|
||||||
fastStream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero);
|
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");
|
"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.IsCompleteSnapshot.ShouldBeFalse();
|
||||||
delta.SourceProof.ShouldBeSameAs(p2Fast.SourceProof);
|
delta.SourceProof.ShouldBeSameAs(p2Fast.SourceProof);
|
||||||
delta.SourceProof.IsValid.ShouldBeTrue();
|
delta.SourceProof.IsValid.ShouldBeTrue();
|
||||||
@@ -87,7 +89,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|||||||
var originalP2Lease = state.FastProof.Lease;
|
var originalP2Lease = state.FastProof.Lease;
|
||||||
var originalP3Lease = state.Current.Lease;
|
var originalP3Lease = state.Current.Lease;
|
||||||
var untilP2Expired = TimeSpan.FromSeconds(23) - origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp());
|
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()))
|
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");
|
.IsFresh(TimeSpan.FromSeconds(30)).ShouldBeTrue("the sample must still be fresh when its original authority expires");
|
||||||
originalP2Lease.IsValid.ShouldBeFalse();
|
originalP2Lease.IsValid.ShouldBeFalse();
|
||||||
@@ -97,6 +99,39 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|||||||
}, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections);
|
}, 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)
|
private static void PauseFastRenewalTimer(ManualTimeProvider clock)
|
||||||
{
|
{
|
||||||
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
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
|
private sealed class ManualTimer(ManualTimeProvider owner, TimerCallback callback, object? state) : ITimer
|
||||||
{
|
{
|
||||||
public DateTimeOffset? Due; // guarded by owner._lock
|
public DateTimeOffset? Due; // guarded by owner._lock
|
||||||
|
|||||||
Reference in New Issue
Block a user