using Opc.Ua; using Opc.Ua.Client; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using static ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests.OpcUaClientInitialAlarmStateSignalTests; namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests; /// /// #926 — a RefreshEnd declares the conditions it covers state-known (grpc-data A1), so it may signal only for a /// LOSSLESS RefreshStart…RefreshEnd bracket. A loss inside the bracket (the server's EventQueueOverflowEventType, a /// RefreshRequired, a publish-sequence gap the SDK skipped) or a missing RefreshStart suppresses the signal /// and re-runs ConditionRefresh, bounded; a never-signal outcome leaves the conditions unknown (Uncertain). /// [Trait("Category", "Unit")] [Trait("Feature", "GrpcData")] [Trait("Issue", "926")] public sealed class OpcUaClientRefreshBracketLossTests { private const string Trip1 = "Plant/opc/plc/Trip1"; /// The authored source index: the overflow notice (SourceNode = Server) is NOT in it, so this also proves /// the notice is seen before the source filter. private static readonly Dictionary Index = new() { ["ns=3;s=Alarms.Trip1"] = Trip1 }; private static (OpcUaClientDriver Drv, List Trace, IAlarmSubscriptionHandle Handle, RetryProbe Retries) NewDriver(string id) { var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), id) { // Long enough that a replay's own (lossy) RefreshEnd is routed before its re-refresh starts, as in production // (2 s back-off vs. a 500 ms publishing interval); short enough to keep the suite fast. AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(100), }; var trace = Record(drv); var handle = drv.AddAlarmSubscriptionForTest([Trip1]); var retries = new RetryProbe(); drv.AlarmRefreshRetryInvokerForTest = (_, _) => { retries.Hit(); return Task.CompletedTask; }; return (drv, trace, handle, retries); } private static void Route(OpcUaClientDriver drv, IAlarmSubscriptionHandle h, NodeId type) => drv.RouteAlarmEvent(Marker(type), Index, h); /// The issue's scenario: refreshed events overflowed the upstream queue, RefreshEnd still arrived. No signal /// (the condition stays unknown), a re-refresh is run, and ITS clean bracket signals. [Fact] public async Task Overflow_inside_the_bracket_suppresses_the_signal_and_re_refreshes() { var (drv, trace, h, retries) = NewDriver("opcua-926-overflow"); using var _ = drv; Route(drv, h, ObjectTypeIds.RefreshStartEventType); drv.RouteAlarmEvent(Condition(active: false, acked: true), Index, h); // what survived; the active one was lost Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.ShouldNotContain(t => t.StartsWith("signal:"), "a lossy replay must never declare its conditions known"); await retries.WaitForAsync(1); // The re-refresh's replay is lossless ⇒ signalled (positive control: the bracket CAN signal). Route(drv, h, ObjectTypeIds.RefreshStartEventType); drv.RouteAlarmEvent(Condition(active: true, acked: false), Index, h); Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.Last().ShouldBe("signal:" + Trip1); trace.Count(t => t.StartsWith("signal:")).ShouldBe(1); retries.Count.ShouldBe(1, "one loss ⇒ one re-refresh (the lossy RefreshEnd does not request a second)"); } /// A bracket whose RefreshStart never arrived (lost with the head of the replay) does not signal. [Fact] public async Task RefreshEnd_without_its_RefreshStart_does_not_signal() { var (drv, trace, h, retries) = NewDriver("opcua-926-nostart"); using var _ = drv; Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.ShouldBeEmpty(); await retries.WaitForAsync(1); } /// A RefreshRequired inside the bracket is a loss; its own sweep is the re-refresh, so the driver adds none. [Fact] public async Task RefreshRequired_inside_the_bracket_suppresses_the_signal() { var (drv, trace, h, retries) = NewDriver("opcua-926-required"); using var _ = drv; Route(drv, h, ObjectTypeIds.RefreshStartEventType); Route(drv, h, ObjectTypeIds.RefreshRequiredEventType); Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.ShouldBeEmpty(); await Task.Delay(200, TestContext.Current.CancellationToken); retries.Count.ShouldBe(0); // Positive control: the next clean bracket signals. Route(drv, h, ObjectTypeIds.RefreshStartEventType); Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.ShouldBe(["signal:" + Trip1]); } /// An overflow OUTSIDE a bracket lost live events: a re-refresh repairs them (and its bracket signals). [Fact] public async Task Overflow_outside_a_bracket_requests_a_re_refresh() { var (drv, trace, h, retries) = NewDriver("opcua-926-live-overflow"); using var _ = drv; Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); await retries.WaitForAsync(1); trace.ShouldBeEmpty("the overflow notice is never projected as an alarm"); Route(drv, h, ObjectTypeIds.RefreshStartEventType); Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.ShouldBe(["signal:" + Trip1]); } /// Liveness: a re-refresh whose own RefreshStart is lost (the queue is still full, so only overflow notices /// arrive and no bracket ever opens) can still request the next one, up to the bound. [Fact] public async Task A_re_refresh_whose_RefreshStart_is_lost_can_request_the_next() { var (drv, trace, h, retries) = NewDriver("opcua-926-start-lost"); using var _ = drv; for (var n = 1; n <= OpcUaClientDriver.MaxAlarmRefreshRetries; n++) { Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); // coalesced into the same request await retries.WaitForAsync(n); } Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); await Task.Delay(500, TestContext.Current.CancellationToken); retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries); trace.ShouldBeEmpty(); } /// A structurally lossy upstream (every replay overflows) costs at most /// re-refreshes, then never signals — the conditions stay unknown. A later clean bracket signals and resets the budget. [Fact] public async Task Re_refresh_is_bounded_and_the_budget_resets_on_a_clean_bracket() { var (drv, trace, h, retries) = NewDriver("opcua-926-bounded"); using var _ = drv; for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries + 3; i++) { Route(drv, h, ObjectTypeIds.RefreshStartEventType); Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); Route(drv, h, ObjectTypeIds.RefreshEndEventType); await retries.WaitForAsync(Math.Min(i + 1, OpcUaClientDriver.MaxAlarmRefreshRetries)); } await Task.Delay(200, TestContext.Current.CancellationToken); retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries, "no refresh storm"); trace.ShouldBeEmpty("never-signal is the safe outcome: Uncertain, not known-inactive"); // A lossless bracket (a RefreshRequired sweep, a reconnect) signals and gives the budget back. Route(drv, h, ObjectTypeIds.RefreshStartEventType); Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.ShouldBe(["signal:" + Trip1]); Route(drv, h, ObjectTypeIds.RefreshStartEventType); Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); await retries.WaitForAsync(OpcUaClientDriver.MaxAlarmRefreshRetries + 1); } /// A publish-sequence gap inside a bracket (a message the SDK gave up on) suppresses its signal; contiguous /// numbers, a repeat (several events in one message), an unknown number and the wrap are no loss. [Fact] public async Task Sequence_gap_inside_the_bracket_suppresses_the_signal() { var (drv, trace, h, retries) = NewDriver("opcua-926-seqgap"); using var _ = drv; drv.NoteAlarmMessageSequence(h, 9); Route(drv, h, ObjectTypeIds.RefreshStartEventType); drv.NoteAlarmMessageSequence(h, 10); drv.NoteAlarmMessageSequence(h, 10); // a second event of the same message drv.NoteAlarmMessageSequence(h, 0); // unknown (no message): ignored drv.NoteAlarmMessageSequence(h, 11); Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.ShouldBe(["signal:" + Trip1], "no loss inside that bracket"); retries.Count.ShouldBe(0); Route(drv, h, ObjectTypeIds.RefreshStartEventType); drv.NoteAlarmMessageSequence(h, 12); drv.NoteAlarmMessageSequence(h, 14); // message 13 lost Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.Count(t => t.StartsWith("signal:")).ShouldBe(1, "the replay with a lost message did not signal"); await retries.WaitForAsync(1); } /// The sequence-number wrap (… uint.MaxValue, 1 …) is contiguous. [Fact] public void Sequence_wrap_is_contiguous() { var (drv, trace, h, retries) = NewDriver("opcua-926-seqwrap"); using var _ = drv; drv.NoteAlarmMessageSequence(h, uint.MaxValue); Route(drv, h, ObjectTypeIds.RefreshStartEventType); drv.NoteAlarmMessageSequence(h, 1); drv.NoteAlarmMessageSequence(h, 2); Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.ShouldBe(["signal:" + Trip1]); retries.Count.ShouldBe(0); } /// Review r1 #6: an OLDER sequence number (a stray late message) is ignored and not recorded, so the next /// in-order message is not a second, false gap. [Fact] public void An_older_sequence_number_is_ignored_and_not_recorded() { var (drv, trace, h, retries) = NewDriver("opcua-926-seqold"); using var _ = drv; drv.NoteAlarmMessageSequence(h, 20); Route(drv, h, ObjectTypeIds.RefreshStartEventType); drv.NoteAlarmMessageSequence(h, 18); // late duplicate of an old message drv.NoteAlarmMessageSequence(h, 21); // in order relative to 20 Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.ShouldBe(["signal:" + Trip1]); retries.Count.ShouldBe(0); } /// Review r1 #1: a gap OUTSIDE a bracket can hold a live transition (a Raise) — it is a loss: withdraw /// "known" (the subscription had signalled) and re-refresh, whose clean bracket signals again. [Fact] public async Task Sequence_gap_outside_a_bracket_withdraws_known_and_re_refreshes() { var (drv, trace, h, retries) = NewDriver("opcua-926-seqgap-live"); using var _ = drv; SignalClean(drv, h); drv.NoteAlarmMessageSequence(h, 1); drv.NoteAlarmMessageSequence(h, 2); trace.ShouldBe(["signal:" + Trip1], "contiguous live messages are no loss"); drv.NoteAlarmMessageSequence(h, 4); // message 3 (a live Raise) lost trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1]); await retries.WaitForAsync(1); SignalClean(drv, h); trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1, "signal:" + Trip1]); } /// Review r1 #2: an overflow AFTER the conditions were declared known withdraws "known" — once, until a /// clean bracket re-signals — and the episode gets its own retry budget. [Fact] public async Task Loss_after_the_signal_withdraws_known_once_until_a_clean_bracket() { var (drv, trace, h, retries) = NewDriver("opcua-926-withdraw"); using var _ = drv; // Episode 1 spends its whole budget, then ends clean. for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries; i++) { Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); await retries.WaitForAsync(i + 1); } SignalClean(drv, h); trace.ShouldBe(["signal:" + Trip1], "no withdrawal before anything was known"); // Episode 2: a live overflow withdraws, a second loss does not withdraw again, and retries are available. Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); Route(drv, h, ObjectTypeIds.RefreshRequiredEventType); trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1]); await retries.WaitForAsync(OpcUaClientDriver.MaxAlarmRefreshRetries + 1); SignalClean(drv, h); trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1, "signal:" + Trip1]); } /// A RefreshRequired after the signal withdraws "known" too. [Fact] public void RefreshRequired_after_the_signal_withdraws_known() { var (drv, trace, h, _) = NewDriver("opcua-926-required-withdraw"); using var __ = drv; SignalClean(drv, h); Route(drv, h, ObjectTypeIds.RefreshRequiredEventType); trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1]); } /// Review r1 #3: a RefreshStart while a bracket is still open (its RefreshEnd never arrived) must not erase the /// open bracket's loss; the overlapping start is itself a loss. [Fact] public async Task An_overlapping_RefreshStart_does_not_erase_the_loss() { var (drv, trace, h, retries) = NewDriver("opcua-926-nested"); using var _ = drv; Route(drv, h, ObjectTypeIds.RefreshStartEventType); Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); await retries.WaitForAsync(1); Route(drv, h, ObjectTypeIds.RefreshStartEventType); // the first RefreshEnd never arrived Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.ShouldBeEmpty("an End only signals when no overlapping / lossy bracket remains"); // Positive control: a bracket that opens on a closed one, lossless, signals. Route(drv, h, ObjectTypeIds.RefreshStartEventType); Route(drv, h, ObjectTypeIds.RefreshEndEventType); trace.ShouldBe(["signal:" + Trip1]); } /// Review r1 #4: a failed ConditionRefresh call (no RefreshEnd will come) is retried, bounded. [Fact] public async Task A_failed_ConditionRefresh_is_retried_bounded() { var (drv, trace, h, retries) = NewDriver("opcua-926-refresh-failed"); using var _ = drv; for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries + 2; i++) { drv.ReportRefreshFailedForTest(h); await retries.WaitForAsync(Math.Min(i + 1, OpcUaClientDriver.MaxAlarmRefreshRetries)); } await Task.Delay(300, TestContext.Current.CancellationToken); retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries); trace.ShouldBeEmpty(); } /// Review r1 #5: a retry scheduled WHILE the previous retry's refresh call runs keeps its pending flag (the /// earlier retry's completion must not clear it), so a further loss before it starts is coalesced into it. [Fact] public async Task A_retry_scheduled_during_a_refresh_call_keeps_coalescing() { var (drv, trace, h, retries) = NewDriver("opcua-926-generation"); using var _ = drv; var first = true; drv.AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(300); drv.AlarmRefreshRetryInvokerForTest = (_, _) => { retries.Hit(); if (first) { first = false; // A loss inside the first retry's call schedules the second retry. Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); } return Task.CompletedTask; }; Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); await retries.WaitForAsync(1); await Task.Delay(50, TestContext.Current.CancellationToken); // the first retry's finally has run // Still pending ⇒ coalesced, not a third retry. (Before the generation token the first retry's finally cleared // the second's pending flag, so this scheduled one more.) A failed refresh call schedules without the // per-bracket request flag, so it exercises the pending flag alone. drv.ReportRefreshFailedForTest(h); await retries.WaitForAsync(2); await Task.Delay(1500, TestContext.Current.CancellationToken); retries.Count.ShouldBe(2); trace.ShouldBeEmpty(); } /// A spent budget is not a permanent give-up: after the cool-down a further loss gets a new budget. [Fact] public async Task A_spent_budget_renews_after_the_cooldown() { var (drv, _, h, retries) = NewDriver("opcua-926-cooldown"); using var __ = drv; drv.AlarmRefreshRetryCooldown = TimeSpan.FromSeconds(1); for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries; i++) { Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); await retries.WaitForAsync(i + 1); } Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); await Task.Delay(200, TestContext.Current.CancellationToken); retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries, "inside the cool-down: no more"); await Task.Delay(1500, TestContext.Current.CancellationToken); Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); await retries.WaitForAsync(OpcUaClientDriver.MaxAlarmRefreshRetries + 1); } private static void SignalClean(OpcUaClientDriver drv, IAlarmSubscriptionHandle h) { Route(drv, h, ObjectTypeIds.RefreshStartEventType); Route(drv, h, ObjectTypeIds.RefreshEndEventType); } /// The overflow notice is never an alarm, even pass-through (no authored refs). [Fact] public void Overflow_notice_is_never_projected() { OpcUaClientDriver.ProjectEvent(Marker(ObjectTypeIds.EventQueueOverflowEventType), new Dictionary(), new StrayHandle(), n => n.ToString(), (_, _) => { }).ShouldBeNull(); // Positive control: a non-marker event from the same source projects pass-through. OpcUaClientDriver.ProjectEvent(Marker(ObjectTypeIds.BaseEventType), new Dictionary(), new StrayHandle(), n => n.ToString(), (_, _) => { }).ShouldNotBeNull(); } /// The alarm event item asks for the deeper queue. [Fact] public void Alarm_event_queue_is_deep() => OpcUaClientDriver.AlarmEventQueueSize.ShouldBeGreaterThanOrEqualTo(10_000u); /// /// Through a REAL SDK subscription with the driver's alarm options: the publish message carrying a refreshed /// event (seq 3) is lost and its republish fails (not available). The SDK skips the gap and delivers the /// RefreshEnd (seq 4) — reporting the skip to nothing observable: its Republish publish-state is raised /// only in a worker pass that also delivers a message, which the gap prevents. The driver's own sequence check /// () suppresses that RefreshEnd. /// [Fact] public async Task Abandoned_publish_gap_suppresses_the_RefreshEnd_through_the_real_SDK() { var (drv, trace, h, retries) = NewDriver("opcua-926-sdk-gap"); using var _ = drv; var order = await GapReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1), drv, h, Index, skip: 3); order.ShouldBe(["live:1", "start:2", "end:4"], "the SDK skipped the lost message and delivered the RefreshEnd"); trace.ShouldNotContain(t => t.StartsWith("signal:"), "a replay with a lost message must not declare its conditions known"); await retries.WaitForAsync(1); } /// Positive control for the real-SDK test: the same replay with nothing lost signals. [Fact] public async Task Lossless_publish_sequence_signals_through_the_real_SDK() { var (drv, trace, h, retries) = NewDriver("opcua-926-sdk-nogap"); using var _ = drv; var order = await GapReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1), drv, h, Index, skip: null); order.ShouldBe(["live:1", "start:2", "refreshed:3", "end:4"]); trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]); retries.Count.ShouldBe(0); } private sealed class StrayHandle : IAlarmSubscriptionHandle { public string DiagnosticId => "stray"; } private sealed class RetryProbe { private int _count; public int Count => Volatile.Read(ref _count); public void Hit() => Interlocked.Increment(ref _count); public async Task WaitForAsync(int n) { var until = DateTime.UtcNow.AddSeconds(10); while (Count < n && DateTime.UtcNow < until) await Task.Delay(10); Count.ShouldBeGreaterThanOrEqualTo(n); } } /// /// Feeds publish responses 1 (a live event), 2 (RefreshStart), 3 (a refreshed Active event), 4 (RefreshEnd) and /// 5..8 (unrelated events) into a real SDK , routing every delivered event through the /// driver's production entry. skip: a sequence number that never arrives and is not available for /// republish. Returns the order of what was delivered (kind:sequence) up to the RefreshEnd. /// private static class GapReplay { public static async Task> DeliverAsync(SubscriptionOptions options, OpcUaClientDriver drv, IAlarmSubscriptionHandle handle, Dictionary index, uint? skip) { var order = new List(); var ended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var subscription = new Subscription(telemetry: null!, options); var item = new MonitoredItem(telemetry: null!, new MonitoredItemOptions { DisplayName = "Server/Events", StartNodeId = ObjectIds.Server, AttributeId = Attributes.EventNotifier, Filter = new EventFilter(), }); item.Notification += (_, args) => { if (args.NotificationValue is not EventFieldList efl) return; lock (order) { if (ended.Task.IsCompleted) return; var seq = efl.Message?.SequenceNumber ?? 0; var kind = UpstreamValueMapping.ToClr(efl.EventFields[1]) is NodeId t ? t == ObjectTypeIds.RefreshStartEventType ? "start" : t == ObjectTypeIds.RefreshEndEventType ? "end" : seq == 3 ? "refreshed" : "live" : "?"; order.Add($"{kind}:{seq}"); drv.RouteAlarmEventFieldList(efl, index, handle); if (kind == "end") ended.TrySetResult(); } }; subscription.AddItem(item); subscription.AddItem(item); const System.Reflection.BindingFlags all = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic; var save = typeof(Subscription).GetMethods(all) .First(m => m.Name == "SaveMessageInCache" && m.GetParameters().Length == 2); typeof(Subscription).GetMethod("StartKeepAliveTimer", all)!.Invoke(subscription, null); var available = new uint[] { 1, 2, 3, 4, 5, 6, 7, 8 }.Where(n => n != skip).ToArray(); async Task Send(uint seq, List fields, int pauseMs) { var message = new NotificationMessage { SequenceNumber = seq, PublishTime = DateTime.UtcNow, NotificationData = [ new ExtensionObject(new EventNotificationList { Events = [new EventFieldList { ClientHandle = item.ClientHandle, EventFields = fields.ToArray() }], }), ], }; save.Invoke(subscription, [SdkReplay.ToParam(save, available), message]); await Task.Delay(pauseMs); } try { // seq 1 is a live event before the refresh: the SDK's first message only re-syncs its sequence. await Send(1, Unrelated(), 300); await Send(2, Marker(ObjectTypeIds.RefreshStartEventType), 300); if (skip != 3) await Send(3, Condition(active: true, acked: false), 300); await Send(4, Marker(ObjectTypeIds.RefreshEndEventType), 300); await Send(5, Unrelated(), 300); // The SDK republishes a gap once it is > 2.5 s old with later messages behind it, then skips it once // the republish has failed; each step runs on a later arrival. for (uint seq = 6; seq <= 8 && !ended.Task.IsCompleted; seq++) await Send(seq, Unrelated(), 2700); await ended.Task.WaitAsync(TimeSpan.FromSeconds(15)); } finally { subscription.Dispose(); } lock (order) return order.ToList(); } private static List Unrelated() { var f = Marker(ObjectTypeIds.BaseEventType); f[2] = new Variant(NodeId.Parse("ns=9;s=Elsewhere")); // not an authored source ⇒ dropped by the filter return f; } } }