Merge #926: OpcUaClient RefreshEnd signals initial alarm state only for a lossless bracket; post-signal loss withdraws known; deferred alarm/mark replay in arrival order; 2 review rounds

This commit is contained in:
Joseph Doherty
2026-11-28 10:26:58 -05:00
18 changed files with 1689 additions and 101 deletions
@@ -0,0 +1,126 @@
using System.Diagnostics.Metrics;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests;
/// <summary>
/// #926 live gate against <c>opc-plc --alm</c>: an alarm event item whose queue is far smaller than one
/// ConditionRefresh replay overflows on the REAL server. The server's <c>EventQueueOverflowEventType</c> must reach
/// the driver (it comes from the Server object, past the source filter), the RefreshEnd must NOT signal, and the
/// driver's re-refresh is bounded. The positive control is the same driver with the production queue, which signals.
/// Read-only against the fixture.
/// </summary>
[Collection(OpcPlcCollection.Name)]
[Trait("Category", "LiveIntegration")]
[Trait("Feature", "GrpcData")]
[Trait("Issue", "926")]
public sealed class OpcUaClientRefreshOverflowLiveTests(OpcPlcFixture sim, ITestOutputHelper output)
{
/// <summary>
/// <c>discardOldest: false</c> (production): the overflowing replay loses its RefreshEnd too (the newest events
/// are dropped), so nothing can signal. <c>true</c>: the RefreshEnd survives but the RefreshStart and the head of
/// the replay do not — the case a naive RefreshEnd signal gets wrong. (Observed on the fixture's opc-plc, 2026-11-28:
/// with discardOldest false a queue of 1 yields overflow notices; a queue of 2 yielded none at all — and no
/// RefreshEnd either, so it still never signalled.)
/// </summary>
[Theory]
[InlineData(false, 1u)]
[InlineData(true, 2u)]
public async Task Overflowing_refresh_never_signals_and_re_refresh_is_bounded(bool discardOldest, uint queueSize)
{
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
var ct = TestContext.Current.CancellationToken;
var id = $"opcua-926-live-{Guid.NewGuid():N}";
using var counts = new EventCounts(id);
await using var drv = new OpcUaClientDriver(OpcPlcProfile.BuildOptions(sim.EndpointUrl), id)
{
AlarmEventItemQueueSize = queueSize, // one replay = RefreshStart + every retained condition + RefreshEnd
AlarmEventItemDiscardOldest = discardOldest,
AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(250),
};
var signals = 0;
drv.InitialAlarmStateDelivered += (_, _) => Interlocked.Increment(ref signals);
drv.OnAlarmEvent += (_, _) => { };
await drv.InitializeAsync("{}", ct);
await drv.SubscribeAlarmsAsync(["Plant/opc/plc/926"], ct);
// 1 + 3 retries, back-off 0.25 + 0.5 + 1 s; allow the replays to arrive.
var until = DateTime.UtcNow.AddSeconds(20);
while (counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy) < 1 + OpcUaClientDriver.MaxAlarmRefreshRetries
&& DateTime.UtcNow < until)
await Task.Delay(100, ct);
await Task.Delay(3000, ct); // quiet window: nothing further may arrive
output.WriteLine($"discardOldest={discardOldest} overflows={counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow)} " +
$"lossyRefreshEnds={counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy)} signals={signals}");
counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow).ShouldBeGreaterThan(0,
"the server's EventQueueOverflowEventType reached the driver past the source filter");
Volatile.Read(ref signals).ShouldBe(0, "a lossy replay must never declare its conditions known");
if (discardOldest)
counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBeGreaterThan(0,
"the RefreshEnd arrived and was refused as lossy (its RefreshStart was discarded)");
counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBeLessThanOrEqualTo(
1 + OpcUaClientDriver.MaxAlarmRefreshRetries, "re-refresh is bounded — no refresh storm");
await drv.ShutdownAsync(ct);
}
[Fact]
public async Task Production_queue_refresh_signals()
{
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
var ct = TestContext.Current.CancellationToken;
var id = $"opcua-926-live-ctl-{Guid.NewGuid():N}";
using var counts = new EventCounts(id);
await using var drv = new OpcUaClientDriver(OpcPlcProfile.BuildOptions(sim.EndpointUrl), id);
var signalled = new TaskCompletionSource<AlarmInitialStateEventArgs>(TaskCreationOptions.RunContinuationsAsynchronously);
drv.InitialAlarmStateDelivered += (_, e) => signalled.TrySetResult(e);
drv.OnAlarmEvent += (_, _) => { };
await drv.InitializeAsync("{}", ct);
await drv.SubscribeAlarmsAsync(["Plant/opc/plc/926"], ct);
(await signalled.Task.WaitAsync(TimeSpan.FromSeconds(30), ct)).Unsignalable.ShouldBeFalse();
counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow).ShouldBe(0);
counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBe(0);
await drv.ShutdownAsync(ct);
}
/// <summary>Counts <c>otopcua.driver.opcuaclient.events</c> for ONE driver instance (the instance tag filters out
/// parallel tests' measurements).</summary>
private sealed class EventCounts : IDisposable
{
private readonly MeterListener _listener = new();
private readonly Dictionary<string, long> _counts = new();
public EventCounts(string driverInstanceId)
{
// Run the telemetry type's static initializer FIRST: if the counter is created while this listener is
// live, InstrumentPublished runs inside that initializer, where the field still reads null — the counter
// would never be enabled and every count would read 0 (seen when this class ran alone).
var counter = OtOpcUaTelemetry.OpcUaClientEvents;
_listener.InstrumentPublished = (inst, l) =>
{
if (ReferenceEquals(inst, counter)) l.EnableMeasurementEvents(inst);
};
_listener.SetMeasurementEventCallback<long>((_, value, tags, _) =>
{
string? instance = null, evt = null;
foreach (var t in tags)
{
if (t.Key == OtOpcUaTelemetry.PollOverrunDriverInstanceTag) instance = t.Value as string;
else if (t.Key == "event") evt = t.Value as string;
}
if (instance != driverInstanceId || evt is null) return;
lock (_counts) _counts[evt] = _counts.GetValueOrDefault(evt) + value;
});
_listener.Start();
}
public long Get(string evt) { lock (_counts) return _counts.GetValueOrDefault(evt); }
public void Dispose() => _listener.Dispose();
}
}
@@ -53,7 +53,8 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, new StrayHandle());
trace.ShouldBeEmpty();
// Positive control: the live subscription's RefreshEnd does signal.
// Positive control: the live subscription's bracket does signal.
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshStartEventType), index, live);
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, live);
trace.ShouldBe(["signal:" + Trip1]);
}
@@ -97,6 +98,8 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
var handle = drv.AddAlarmSubscriptionForTest([Trip1]);
var index = new Dictionary<string, string> { ["ns=3;s=Alarms.Trip1"] = Trip1 };
// #926: the bracket's RefreshStart was routed in an earlier publish response.
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshStartEventType), index, handle);
var replay = await SdkReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1),
[(2u, Marker(ObjectTypeIds.RefreshEndEventType)), (1u, Condition(active: true, acked: false))],
fields => drv.RouteAlarmEvent(fields, index, handle));
@@ -105,18 +108,18 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]);
}
private static List<string> Record(OpcUaClientDriver drv)
internal static List<string> Record(OpcUaClientDriver drv)
{
var trace = new List<string>();
drv.OnAlarmEvent += (_, e) => { lock (trace) trace.Add($"event:{e.ConditionId}:{e.Kind}"); };
drv.InitialAlarmStateDelivered += (_, e) =>
{
lock (trace) trace.Add("signal:" + string.Join(',', e.ConditionIds));
lock (trace) trace.Add((e.Withdrawn ? "withdraw:" : "signal:") + string.Join(',', e.ConditionIds));
};
return trace;
}
private static List<Variant> Marker(NodeId type) =>
internal static List<Variant> Marker(NodeId type) =>
[
Variant.From(new byte[] { 9 }.ToByteString()),
new Variant(type),
@@ -130,7 +133,7 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
Variant.Null,
];
private static List<Variant> Condition(bool active, bool acked) =>
internal static List<Variant> Condition(bool active, bool acked) =>
[
Variant.From(new byte[] { 1 }.ToByteString()),
new Variant(new NodeId("TripAlarmType", 3)),
@@ -227,7 +230,7 @@ internal static class SdkReplay
return delivered;
}
private static object ToParam(System.Reflection.MethodInfo save, uint[] available)
internal static object ToParam(System.Reflection.MethodInfo save, uint[] available)
{
var t = save.GetParameters()[0].ParameterType;
if (t.IsInstanceOfType(available)) return available;
@@ -0,0 +1,547 @@
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;
/// <summary>
/// #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).
/// </summary>
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Issue", "926")]
public sealed class OpcUaClientRefreshBracketLossTests
{
private const string Trip1 = "Plant/opc/plc/Trip1";
/// <summary>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.</summary>
private static readonly Dictionary<string, string> Index = new() { ["ns=3;s=Alarms.Trip1"] = Trip1 };
private static (OpcUaClientDriver Drv, List<string> 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);
/// <summary>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.</summary>
[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)");
}
/// <summary>A bracket whose RefreshStart never arrived (lost with the head of the replay) does not signal.</summary>
[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);
}
/// <summary>A RefreshRequired inside the bracket is a loss; its own sweep is the re-refresh, so the driver adds none.</summary>
[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]);
}
/// <summary>An overflow OUTSIDE a bracket lost live events: a re-refresh repairs them (and its bracket signals).</summary>
[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]);
}
/// <summary>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.</summary>
[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();
}
/// <summary>A structurally lossy upstream (every replay overflows) costs at most <see cref="OpcUaClientDriver.MaxAlarmRefreshRetries"/>
/// re-refreshes, then never signals — the conditions stay unknown. A later clean bracket signals and resets the budget.</summary>
[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);
}
/// <summary>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.</summary>
[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);
}
/// <summary>The sequence-number wrap (… uint.MaxValue, 1 …) is contiguous.</summary>
[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);
}
/// <summary>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.</summary>
[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);
}
/// <summary>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.</summary>
[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]);
}
/// <summary>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.</summary>
[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]);
}
/// <summary>A RefreshRequired after the signal withdraws "known" too.</summary>
[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]);
}
/// <summary>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.</summary>
[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]);
}
/// <summary>Review r1 #4: a failed ConditionRefresh call (no RefreshEnd will come) is retried, bounded.</summary>
[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();
}
/// <summary>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.</summary>
[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();
}
/// <summary>A spent budget is not a permanent give-up: after the cool-down a further loss gets a new budget.</summary>
[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);
}
/// <summary>The overflow notice is never an alarm, even pass-through (no authored refs).</summary>
[Fact]
public void Overflow_notice_is_never_projected()
{
OpcUaClientDriver.ProjectEvent(Marker(ObjectTypeIds.EventQueueOverflowEventType), new Dictionary<string, string>(),
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<string, string>(),
new StrayHandle(), n => n.ToString(), (_, _) => { }).ShouldNotBeNull();
}
/// <summary>The alarm event item asks for the deeper queue.</summary>
[Fact]
public void Alarm_event_queue_is_deep() => OpcUaClientDriver.AlarmEventQueueSize.ShouldBeGreaterThanOrEqualTo(10_000u);
/// <summary>
/// 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 <c>Republish</c> publish-state is raised
/// only in a worker pass that also delivers a message, which the gap prevents. The driver's own sequence check
/// (<see cref="OpcUaClientDriver.RouteAlarmEventFieldList"/>) suppresses that RefreshEnd.
/// </summary>
[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);
}
/// <summary>Positive control for the real-SDK test: the same replay with nothing lost signals.</summary>
[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);
}
}
/// <summary>
/// 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 <see cref="Subscription"/>, routing every delivered event through the
/// driver's production entry. <c>skip</c>: 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.
/// </summary>
private static class GapReplay
{
public static async Task<List<string>> DeliverAsync(SubscriptionOptions options, OpcUaClientDriver drv,
IAlarmSubscriptionHandle handle, Dictionary<string, string> index, uint? skip)
{
var order = new List<string>();
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<Variant> 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<Variant> 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;
}
}
}
@@ -115,6 +115,82 @@ public sealed class NativeAlarmInitialStateSignalTests : NativeAlarmSignalTestBa
AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300));
}
/// <summary>
/// #926: a driver that signalled and then lost events WITHDRAWS: the host sends <c>Known: false</c> for exactly
/// those conditions (after the projections before it), puts them back in the F5 window (diagnosed if the driver
/// never re-signals), and a later real signal marks them known again.
/// </summary>
[Fact]
public void A_withdrawn_signal_takes_known_back_and_rearms_F5_until_the_next_signal()
{
var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi", "lo"],
o => o.WithSignalTimeout(DriverTypeNames.OpcUaClient, TimeSpan.FromMilliseconds(400)));
rig.Driver.Signal([A, B]).ShouldBeTrue();
rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct)
.ConditionIds.ShouldBe([A, B], ignoreOrder: true);
rig.Hub.Unsignalled.ContainsKey(DriverId).ShouldBeFalse();
rig.Driver.Raise(A).ShouldBeTrue();
rig.Driver.Signal([A], withdrawn: true).ShouldBeTrue();
var traffic = new List<object>();
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
while (DateTime.UtcNow < deadline)
{
var m = rig.Publish.ReceiveOne(deadline - DateTime.UtcNow, Ct);
if (m is null) break;
if (m is not (OpcUaPublishActor.AlarmStateUpdate or OpcUaPublishActor.MarkConditionsKnown)) continue;
traffic.Add(m);
if (m is OpcUaPublishActor.MarkConditionsKnown { Known: false }) break;
}
traffic[^1].ShouldBeOfType<OpcUaPublishActor.MarkConditionsKnown>().Known.ShouldBeFalse();
traffic.FindIndex(m => m is OpcUaPublishActor.AlarmStateUpdate u && u.AlarmNodeId == A)
.ShouldBeLessThan(traffic.Count - 1, "the withdrawal follows the projection raised before it");
var withdrawal = (OpcUaPublishActor.MarkConditionsKnown)traffic[^1];
withdrawal.ConditionIds.ShouldBe([A], "only the withdrawn conditions");
// Never re-signalled ⇒ F5 diagnoses it (and it is never marked known by a timer).
AwaitCondition(() => rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct);
rig.Hub.Unsignalled[DriverId].Conditions.ShouldBe(1);
AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300));
// Positive control: the next real signal marks it known again and clears the diagnostic.
rig.Driver.Signal([A, B]).ShouldBeTrue();
rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct);
AwaitCondition(() => !rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct);
}
/// <summary>#926: a withdrawal removes the conditions from the OpcUaClient backstop — the timer must never mark a
/// condition known whose source just said it lost events. Positive control: the sibling it did not withdraw IS
/// marked by the same backstop.</summary>
[Fact]
public void A_withdrawal_cancels_the_backstop_for_its_conditions()
{
var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi", "lo"], o => o.WithOpcUaClientSettle(TimeSpan.FromMilliseconds(600)));
rig.Driver.Signal([A, B], unsignalable: true);
rig.Driver.Signal([A], withdrawn: true);
var mark = rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct);
mark.ConditionIds.ShouldBe([B], "only the sibling the driver did not withdraw");
AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(800));
}
/// <summary>#926 review r2: a withdrawal after F5 already raised its diagnostic updates the diagnostic's count.</summary>
[Fact]
public void A_withdrawal_after_the_diagnostic_updates_its_count()
{
var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi", "lo"],
o => o.WithSignalTimeout(DriverTypeNames.OpcUaClient, TimeSpan.FromMilliseconds(300)));
rig.Driver.Signal([A]).ShouldBeTrue(); // B stays pending
AwaitCondition(() => rig.Hub.Unsignalled.TryGetValue(DriverId, out var d) && d.Conditions == 1, TimeSpan.FromSeconds(5), Ct);
rig.Driver.Signal([A], withdrawn: true).ShouldBeTrue();
AwaitCondition(() => rig.Hub.Unsignalled.TryGetValue(DriverId, out var d) && d.Conditions == 2, TimeSpan.FromSeconds(5), Ct);
}
/// <summary>#926: the payload is either unsignalable or a withdrawal.</summary>
[Fact]
public void Unsignalable_and_withdrawn_are_exclusive() =>
Should.Throw<ArgumentException>(() => new AlarmInitialStateEventArgs([A], unsignalable: true, withdrawn: true));
// ---------------------------------------------------------------- review S2 / re-arm F5 / nits
/// <summary>
@@ -290,10 +290,10 @@ public sealed class FakeSignallingAlarmDriver(string driverInstanceId, string dr
/// <param name="conditionIds">The conditions it covers.</param>
/// <param name="unsignalable">Report InitialStateUnsignalable instead.</param>
/// <returns>Whether it was raised.</returns>
public bool Signal(IReadOnlyList<string> conditionIds, bool unsignalable = false)
public bool Signal(IReadOnlyList<string> conditionIds, bool unsignalable = false, bool withdrawn = false)
{
if (!_subscribed) return false;
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(conditionIds, unsignalable));
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(conditionIds, unsignalable, withdrawn));
return true;
}
@@ -13,8 +13,9 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.OpcUa;
/// <summary>
/// A1 (plan §5.1 F2/G3): <see cref="OpcUaPublishActor.MarkConditionsKnown"/> is an alarm message. Live it applies in
/// arrival order; while a plan is in flight it is deferred beside the alarm states and replayed AFTER them — and a
/// source that lost a deferred projection (overflow or out-of-scope skip) has its deferred marks discarded.
/// arrival order; while a plan is in flight it is deferred beside the alarm states and replayed with them in arrival
/// order (#926 review r2) — and a source that lost a deferred projection (overflow or out-of-scope skip) has its
/// deferred KNOWN marks discarded.
/// </summary>
[Trait("Feature", "GrpcData")]
[Trait("Phase", "A1")]
@@ -171,7 +172,8 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase
}
/// <summary>Review round 2 N1: a deferred withdrawal is never dropped by the deferral's capacity (a known mark may be —
/// unknown is the safe side).</summary>
/// unknown is the safe side). #926 review r2: deferred marks are held per condition, so repeated withdrawals of one
/// condition coalesce into one replayed withdrawal (bounded by the number of conditions).</summary>
[Fact]
public void A_withdrawal_beyond_the_deferral_capacity_is_never_dropped()
{
@@ -187,7 +189,45 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(6), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(4), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.IsKnown("al-1").ShouldBeFalse();
}
/// <summary>
/// #926 review r2: a withdrawal followed by a live transition of the same condition, both deferred by a plan,
/// replays in ARRIVAL order — withdrawal, then the transition that re-establishes it — so the condition ends known,
/// as the live path leaves it (marks used to replay after every alarm, ending it unknown while the host no longer
/// counted it in F5). The mirror order (transition, then withdrawal) ends unknown.
/// </summary>
[Fact]
public void Deferred_alarms_and_marks_replay_in_arrival_order()
{
var sink = new OrderSink();
using var gate = new ManualResetEventSlim(false);
var actor = Spawn(sink, gate);
actor.Tell(Rebuild());
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns, Known: false));
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, "drv-1"));
AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.Log.ShouldBe(["unknown:al-1", "alarm:al-1:True"], "replayed in arrival order");
sink.IsKnown("al-1").ShouldBeTrue("the transition after the withdrawal re-established it");
// Mirror (positive control for the order): transition, then withdrawal ⇒ unknown.
var sink2 = new OrderSink();
using var gate2 = new ManualResetEventSlim(false);
var actor2 = Spawn(sink2, gate2);
actor2.Tell(Rebuild());
actor2.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, "drv-1"));
actor2.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns, Known: false));
AwaitAssert(() => sink2.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
gate2.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink2.Log.ShouldBe(["alarm:al-1:True", "unknown:al-1"]);
sink2.IsKnown("al-1").ShouldBeFalse();
}
/// <summary>Review round 2 N2: a G3 discard of a driver's deferred mark is reported back to the mark's sender, so its