diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs index b50689ac7..4701bf779 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs @@ -19,6 +19,10 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable public TimeProvider Clock { get; } internal Func? RetryJitterForTests { 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); /// #920: runs on the stream pump after a publish passed its demand check, before the duplicate-baseline check. internal Action? AfterPublishDemandCheckForTests { get; set; } private readonly IFederatedProjectionCatalog _catalog; @@ -1554,8 +1558,12 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable Math.Min(TimeSpan.FromMilliseconds(250).Ticks, minimumLease.Ticks / 4))); renewalTimer = _owner.Clock.CreateTimer(_ => { - if (Interlocked.Exchange(ref renewalQueued, 1) == 0 && !_events.Writer.TryWrite(new RenewalEvent())) - Interlocked.Exchange(ref renewalQueued, 0); + if (Interlocked.Exchange(ref renewalQueued, 1) == 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); pump = PumpAsync(stream, route.Token); foreach (var demand in initial) @@ -1645,20 +1653,24 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable else if (message is RenewalEvent) { Interlocked.Exchange(ref renewalQueued, 0); - if (_registrations.Values.Any(registration => registration.Renewal && - 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()) + try { - 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); + if (_registrations.Values.Any(registration => registration.Renewal && + 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 (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) { @@ -1865,7 +1877,11 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } 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(); } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalContinuityWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalContinuityWireTests.cs index dcbcce8e6..1a9b37365 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalContinuityWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalContinuityWireTests.cs @@ -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(); } } + /// 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). + private static async Task 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(); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPredecessorWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPredecessorWireTests.cs index 3ce3f35c9..051d6493c 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPredecessorWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPredecessorWireTests.cs @@ -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 NextPublishedRenewal(ChannelReader reader, + Func 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; + } + } + + /// 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). + 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; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/ManualTimeProvider.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/ManualTimeProvider.cs index 4b0c25409..2e1f5e6e4 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/ManualTimeProvider.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/ManualTimeProvider.cs @@ -68,6 +68,27 @@ internal sealed class ManualTimeProvider : TimeProvider } } + /// Like , but time reaches now + by 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. + 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