fix(opcuaclient): #946 rate-limit RefreshRequired sweeps; #947 refused per-ack status throws DriverOperationRefusedException

#946: AlarmRefreshRequiredMinInterval (default 10 s, 0 disables) spaces RefreshRequired-triggered ConditionRefresh sweeps per session; a request inside the window is deferred to its end and coalesced, never dropped.
#947: AcknowledgeAsync throws the breaker-exempt DriverOperationRefusedException for Bad per-ack statuses and unresolvable condition ids (BadConditionBranchAlreadyAcked is success) so the #760 revert fires. Docs reverse the O-8 decision.
This commit is contained in:
Joseph Doherty
2026-12-01 19:24:01 -05:00
parent 6b60845931
commit 0ccfd88a23
5 changed files with 434 additions and 33 deletions
+23 -7
View File
@@ -289,10 +289,10 @@ The session keep-alive (`KeepAliveInterval`, default 5 s) is the liveness signal
no health — including a write the host cancelled at its own write deadline against a hung upstream; the session no health — including a write the host cancelled at its own write deadline against a hung upstream; the session
keep-alive owns liveness and reports that outage itself. A reply that was in flight across a bad keep-alive advances keep-alive owns liveness and reports that outage itself. A reply that was in flight across a bad keep-alive advances
the stamp but does not write `Healthy` while the outage is published — the keep-alive recovery ends the outage. the stamp but does not write `Healthy` while the outage is published — the keep-alive recovery ends the outage.
An ack none of whose condition ids resolves sends nothing and logs a Warning — it does **not** throw (a deterministic An ack none of whose condition ids resolves sends nothing, logs a Warning and **throws the breaker-exempt
per-ack refusal must not count toward the host's AlarmAcknowledge circuit breaker, or five re-acks of one `DriverOperationRefusedException`** (#947 — it used to return silently; see "A refused ack is refused" below). A call
unresolvable condition would block every genuine ack). Only a call with no reply throws; with no session an ack with no reply throws a `ServiceResultException`; with no session an ack fails `BadNotConnected` (before or inside the
fails `BadNotConnected` (before or inside the gate alike). gate alike).
- **Bad keep-alive** ⇒ health `Degraded` (`LastError = "keep-alive: <status>"`, read stamp preserved), host status - **Bad keep-alive** ⇒ health `Degraded` (`LastError = "keep-alive: <status>"`, read stamp preserved), host status
`Stopped`, and — **once per outage**, not per keep-alive — every subscribed ref is published `BadNoCommunication` `Stopped`, and — **once per outage**, not per keep-alive — every subscribed ref is published `BadNoCommunication`
with its last value retained and **source + server timestamp = the detection time** (live-gate F1: stamped with the with its last value retained and **source + server timestamp = the detection time** (live-gate F1: stamped with the
@@ -473,7 +473,11 @@ initialise (the AdminUI form drops them on the next save). Pinned by
> consumer), keeps them out of the backstop, and diagnoses them if no signal follows. > consumer), keeps them out of the backstop, and diagnoses them if no signal follows.
> - **Retry bounds:** at most 3 re-refreshes run per episode, backing off 2 s, 4 s and 8 s. A clean RefreshEnd resets > - **Retry bounds:** at most 3 re-refreshes run per episode, backing off 2 s, 4 s and 8 s. A clean RefreshEnd resets
> the budget. Once the budget is spent, a further loss gets a new budget only after a 5-minute cool-down. > the budget. Once the budget is spent, a further loss gets a new budget only after a 5-minute cool-down.
> - **RefreshRequired:** its sweeps are coalesced while one is queued. The alarm event item asks for a > - **RefreshRequired:** its sweeps are coalesced while one is queued **and rate-limited (#946)**: at least
> `alarmRefreshRequiredMinInterval` (default 10 s, start to start; `00:00:00` disables) separates two sweeps on one
> session. A request inside the window is **deferred** to the window's end, never dropped, and everything arriving
> meanwhile coalesces into that one sweep; a new session starts a fresh window. Reconnect / re-subscribe / loss-retry
> refreshes (own 3-attempt budget) are not subject to it. The alarm event item asks for a
> queue of 10,000 (previously 1,000); the server may revise it down. Counters on `otopcua.driver.opcuaclient.events`: > queue of 10,000 (previously 1,000); the server may revise it down. Counters on `otopcua.driver.opcuaclient.events`:
> `alarm_event_queue_overflow` and `alarm_refresh_lossy`. > `alarm_event_queue_overflow` and `alarm_refresh_lossy`.
> Last-told state survives a re-initialise (the host re-subscribes the same set over nodes it did not rebuild) and is > Last-told state survives a re-initialise (the host re-subscribes the same set over nodes it did not rebuild) and is
@@ -484,8 +488,20 @@ initialise (the AdminUI form drops them on the next save). Pinned by
> **An ack that never got a reply fails (review 2026-10-21 O-8).** A transport failure on the `Acknowledge` call > **An ack that never got a reply fails (review 2026-10-21 O-8).** A transport failure on the `Acknowledge` call
> (closed channel, faulted session) — or a session lost while the ack queued — now throws with its status > (closed channel, faulted session) — or a session lost while the ack queued — now throws with its status
> (`ServiceResultException`, e.g. `BadConnectionClosed` / `BadNotConnected`), so the host logs the ack as failed > (`ServiceResultException`, e.g. `BadConnectionClosed` / `BadNotConnected`), so the host logs the ack as failed
> instead of applied. A *reply* still returns normally, including per-ack refusals such as > instead of applied.
> `BadConditionBranchAlreadyAcked` (logged per ack): a refusal is the server answering. >
> **A refused ack is refused (#947, reverses the O-8 decision).** A *reply* carrying a Bad per-ack status
> (`BadUserAccessDenied`, `BadNodeIdUnknown`, `BadEventIdUnknown`, `BadInvalidState`, …) — or a condition id that does
> not resolve against the live session — used to be logged and swallowed, so the host never saw a failure, the #760
> revert never fired, and the node kept showing an ack upstream had refused. It now throws
> `DriverOperationRefusedException` (one per call, naming each refused condition + status). That type is exempt from the
> resilience pipeline's retry **and** circuit breaker, which is the reason the earlier decision gave for *not* throwing
> (five refused re-acks opening the AlarmAcknowledge breaker); with it gone the reason is gone. The refusal is a reply,
> so it neither degrades health nor counts as a comms fault. Results are matched to the acks actually sent (an
> unresolvable id in a batch is refused after the resolvable ones are sent). **`BadConditionBranchAlreadyAcked` is
> success** (logged at Information): the condition is already in the requested end state, and reverting would un-ack
> a condition that IS acked. Part 9 defines no other already-acked status. This driver implements no Confirm / Shelve /
> Enable / Disable — `AcknowledgeAsync` is the only upstream condition method it calls, so there is no sibling path.
> This driver does **not** implement `IRediscoverable` — there is no > This driver does **not** implement `IRediscoverable` — there is no
> push-driven rediscovery signal from a remote OPC UA server in this driver. > push-driven rediscovery signal from a remote OPC UA server in this driver.
@@ -112,6 +112,15 @@ public sealed record OpcUaClientDriverOptions
/// <summary>Client-side keep-alive interval.</summary> /// <summary>Client-side keep-alive interval.</summary>
public TimeSpan KeepAliveInterval { get; init; } = TimeSpan.FromSeconds(5); public TimeSpan KeepAliveInterval { get; init; } = TimeSpan.FromSeconds(5);
/// <summary>
/// Minimum time between two <c>RefreshRequired</c>-triggered ConditionRefresh sweeps on one session (#946). An
/// upstream that raises <c>RefreshRequired</c> continuously (e.g. on every event-queue overflow during a replay)
/// would otherwise get back-to-back sweeps of every alarm subscription. A request inside the window is
/// <b>deferred</b> to the window's end (and coalesced with any others), never dropped. <see cref="TimeSpan.Zero"/>
/// disables the limit; default 10 s. Reconnect / re-subscribe / loss-retry refreshes are not limited by this.
/// </summary>
public TimeSpan AlarmRefreshRequiredMinInterval { get; init; } = TimeSpan.FromSeconds(10);
/// <summary> /// <summary>
/// When <c>true</c>, the driver accepts any self-signed / untrusted server certificate. /// When <c>true</c>, the driver accepts any self-signed / untrusted server certificate.
/// Dev-only — must be <c>false</c> in production so MITM attacks against the opc.tcp /// Dev-only — must be <c>false</c> in production so MITM attacks against the opc.tcp
@@ -2707,6 +2707,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// condition node with EventId + Comment arguments. CallAsync accepts a batch — // condition node with EventId + Comment arguments. CallAsync accepts a batch —
// one CallMethodRequest per ack. // one CallMethodRequest per ack.
var callRequests = new List<CallMethodRequest>(); var callRequests = new List<CallMethodRequest>();
// #947: the ack behind each callRequests[i] (results come back index-aligned with the SENT calls, not with
// the batch), and the per-ack refusals collected for ONE breaker-exempt DriverOperationRefusedException.
var sentAcks = new List<AlarmAcknowledgeRequest>();
List<string>? refusals = null;
foreach (var ack in acknowledgements) foreach (var ack in acknowledgements)
{ {
// the host acks by RawPath; Acknowledge must hit the upstream CONDITION node. // the host acks by RawPath; Acknowledge must hit the upstream CONDITION node.
@@ -2718,15 +2722,24 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
byte[] eventId; byte[] eventId;
if (_alarmConditionByRawPath.TryGetValue(ack.ConditionId, out var seen)) if (_alarmConditionByRawPath.TryGetValue(ack.ConditionId, out var seen))
{ {
if (!NamespaceMap.TryResolve(session, seen.ConditionRef, out conditionId)) continue; if (!NamespaceMap.TryResolve(session, seen.ConditionRef, out conditionId))
{
(refusals ??= []).Add($"{ack.ConditionId}: condition id could not be resolved against the live session");
continue;
}
eventId = seen.EventId; eventId = seen.EventId;
} }
else else
{ {
if (!TryResolveTagNode(session, ack.ConditionId, out conditionId) if (!TryResolveTagNode(session, ack.ConditionId, out conditionId)
&& !NamespaceMap.TryResolve(session, ack.ConditionId, out conditionId)) continue; && !NamespaceMap.TryResolve(session, ack.ConditionId, out conditionId))
{
(refusals ??= []).Add($"{ack.ConditionId}: condition id could not be resolved against the live session");
continue;
}
eventId = Array.Empty<byte>(); eventId = Array.Empty<byte>();
} }
sentAcks.Add(ack);
callRequests.Add(new CallMethodRequest callRequests.Add(new CallMethodRequest
{ {
ObjectId = conditionId, ObjectId = conditionId,
@@ -2740,16 +2753,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
if (callRequests.Count == 0) if (callRequests.Count == 0)
{ {
// Review m3 / r1 N-1: nothing resolved to a condition node, so nothing was sent — say so at Warning. NOT // Review m3 / r1 N-1 / #947: nothing resolved to a condition node, so nothing was sent — a deterministic
// thrown: this is a deterministic per-ack refusal, and a throw would count toward the host's // per-ack refusal. It used to be logged and swallowed; a DriverOperationRefusedException is breaker-exempt
// AlarmAcknowledge circuit breaker (5 failures), so an operator re-acking an unresolvable condition // (no retry, no circuit-breaker count), so it is thrown now — otherwise the host believes the ack took
// would block every genuine ack on this driver. Only a no-reply transport failure throws (F2 owns a // and the #760 revert never fires.
// per-ack result surface).
_logger.LogWarning( _logger.LogWarning(
"OpcUaClientDriver '{DriverInstanceId}': AcknowledgeAsync resolved none of {Count} condition id(s) " + "OpcUaClientDriver '{DriverInstanceId}': AcknowledgeAsync resolved none of {Count} condition id(s) " +
"against the live session; nothing was sent upstream and the acknowledgement was NOT applied.", "against the live session; nothing was sent upstream and the acknowledgement was NOT applied.",
_driverInstanceId, acknowledgements.Count); _driverInstanceId, acknowledgements.Count);
return; throw new DriverOperationRefusedException(
"the OPC UA acknowledge was refused: " + string.Join("; ", refusals ?? []));
} }
try try
@@ -2770,14 +2783,24 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
for (var i = 0; i < resp.Results.Count; i++) for (var i = 0; i < resp.Results.Count; i++)
{ {
var result = resp.Results[i]; var result = resp.Results[i];
if (StatusCode.IsBad(result.StatusCode)) if (!StatusCode.IsBad(result.StatusCode)) continue;
// #947: "already acknowledged" is the outcome the operator asked for — upstream agrees with the
// node — so it is success, not a refusal (a revert would un-ack a condition that IS acked).
if (IsAckAlreadyApplied(result.StatusCode))
{ {
_logger.LogInformation(
"OpcUaClientDriver '{DriverInstanceId}': AcknowledgeAsync ack[{Index}] " +
"answered {StatusCode:X8}: the condition was already acknowledged upstream.",
_driverInstanceId, i, result.StatusCode.Code);
continue;
}
_logger.LogWarning( _logger.LogWarning(
"OpcUaClientDriver '{DriverInstanceId}': AcknowledgeAsync ack[{Index}] " + "OpcUaClientDriver '{DriverInstanceId}': AcknowledgeAsync ack[{Index}] " +
"rejected by upstream server with StatusCode {StatusCode:X8}. " + "rejected by upstream server with StatusCode {StatusCode:X8}. " +
"The acknowledgement may not have been applied.", "The acknowledgement was NOT applied.",
_driverInstanceId, i, result.StatusCode.Code); _driverInstanceId, i, result.StatusCode.Code);
} var target = i < sentAcks.Count ? sentAcks[i].ConditionId : $"ack[{i}]";
(refusals ??= []).Add($"{target}: upstream server rejected the acknowledge with {result.StatusCode.Code:X8}");
} }
} }
} }
@@ -2803,10 +2826,26 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
RecordCommsFault(generation, $"ack: {ex.Message}"); RecordCommsFault(generation, $"ack: {ex.Message}");
throw; throw;
} }
// #947: a REPLY carrying refusals (or ids that never resolved) is not a comms fault, but it is not an applied
// ack either. DriverOperationRefusedException is exempt from the resilience retry + circuit breaker, so
// repeated refused acks cannot block genuine ones; the host reverts the node (#760).
if (refusals is { Count: > 0 })
throw new DriverOperationRefusedException(
"the OPC UA acknowledge was refused: " + string.Join("; ", refusals));
} }
finally { _gate.Release(); } finally { _gate.Release(); }
} }
/// <summary>
/// #947: a per-ack status meaning the condition is ALREADY acknowledged upstream — the requested end state — so the
/// ack is treated as applied. Part 9 defines only <c>BadConditionBranchAlreadyAcked</c> for this.
/// </summary>
/// <param name="code">The per-ack status.</param>
/// <returns>Whether the status says the condition was already acknowledged.</returns>
internal static bool IsAckAlreadyApplied(StatusCode code) =>
code.Code == StatusCodes.BadConditionBranchAlreadyAcked;
private void OnEventNotification( private void OnEventNotification(
OpcUaAlarmSubscriptionHandle handle, OpcUaAlarmSubscriptionHandle handle,
IReadOnlyDictionary<string, string> sourceFilter, IReadOnlyDictionary<string, string> sourceFilter,
@@ -3258,9 +3297,57 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// Part 9 §5.11.7: the server lost events (queue overflow / restart) and asks for a refresh. // Part 9 §5.11.7: the server lost events (queue overflow / restart) and asks for a refresh.
// r2 R2-1: bound to the session's work token, which a shutdown cancels first thing. // r2 R2-1: bound to the session's work token, which a shutdown cancels first thing.
var sessionWork = _sessionWorkCts.Token; var sessionWork = _sessionWorkCts.Token;
_ = Task.Run(() => RefreshAllAlarmSubscriptionsAsync(sessionWork, // #946: rate-limit per session — a request inside the minimum interval is DEFERRED to the window's end (the queued
onStart: () => Interlocked.Exchange(ref _refreshRequiredSweepQueued, 0))); // flag stays set meanwhile, so everything arriving in the wait coalesces into this one sweep), never dropped.
var delay = RefreshRequiredSweepDelay(Session);
// The wait is armed HERE (not inside the pool task) so its due time is the request's, however late the pool runs.
var wait = delay > TimeSpan.Zero ? Task.Delay(delay, Clock, sessionWork) : null;
_ = Task.Run(async () =>
{
if (wait is not null)
{
try { await wait.ConfigureAwait(false); }
catch (OperationCanceledException)
{
// The session's work was cancelled (shutdown / re-init): the sweep it asked for is moot.
Interlocked.Exchange(ref _refreshRequiredSweepQueued, 0);
return;
} }
}
await RefreshAllAlarmSubscriptionsAsync(sessionWork, onStart: () =>
{
Interlocked.Exchange(ref _refreshRequiredSweepQueued, 0);
// Stamp the START (the window runs start-to-start) against the session the sweep will run on.
Volatile.Write(ref _lastRefreshRequiredSweepTicks, Clock.GetUtcNow().UtcTicks);
Volatile.Write(ref _lastRefreshRequiredSweepSession, Session);
}).ConfigureAwait(false);
});
}
/// <summary>UTC ticks at which the last RefreshRequired-triggered sweep started (0 = none).</summary>
private long _lastRefreshRequiredSweepTicks;
/// <summary>The session that sweep ran on — a new session starts a fresh window.</summary>
private object? _lastRefreshRequiredSweepSession;
/// <summary>#946: how long a RefreshRequired sweep requested now must wait to respect the per-session minimum interval.</summary>
/// <param name="session">The session the sweep would run on.</param>
/// <returns>Zero when it may start immediately.</returns>
private TimeSpan RefreshRequiredSweepDelay(object? session)
{
var min = _options.AlarmRefreshRequiredMinInterval;
var last = Volatile.Read(ref _lastRefreshRequiredSweepTicks);
if (min <= TimeSpan.Zero || last == 0 || !ReferenceEquals(Volatile.Read(ref _lastRefreshRequiredSweepSession), session))
return TimeSpan.Zero;
var remaining = new DateTime(last, DateTimeKind.Utc) + min - Clock.GetUtcNow().UtcDateTime;
return remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero;
}
/// <summary>Test seam (#946): invoked each time an alarm ConditionRefresh sweep starts.</summary>
internal Action? RefreshSweepStartedForTest { get; set; }
/// <summary>Test seam (#946): request a RefreshRequired-triggered sweep exactly as an upstream RefreshRequired event does.</summary>
internal void RequestRefreshRequiredSweepForTest() => RequestRefreshRequiredSweep();
/// <summary>True for a <c>RefreshRequiredEventType</c> event (the server asks the client to ConditionRefresh).</summary> /// <summary>True for a <c>RefreshRequiredEventType</c> event (the server asks the client to ConditionRefresh).</summary>
/// <param name="fields">The event's fields.</param> /// <param name="fields">The event's fields.</param>
@@ -3368,6 +3455,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
private async Task RefreshAllAlarmSubscriptionsAsync(CancellationToken cancellationToken, Action? onStart = null) private async Task RefreshAllAlarmSubscriptionsAsync(CancellationToken cancellationToken, Action? onStart = null)
{ {
onStart?.Invoke(); onStart?.Invoke();
RefreshSweepStartedForTest?.Invoke();
if (_alarmSubscriptions.IsEmpty) return; if (_alarmSubscriptions.IsEmpty) return;
try try
{ {
@@ -10,8 +10,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
/// <summary> /// <summary>
/// Review 2026-10-21 R06:O-8 — <c>AcknowledgeAsync</c> swallowed every non-cancellation transport failure, so /// Review 2026-10-21 R06:O-8 — <c>AcknowledgeAsync</c> swallowed every non-cancellation transport failure, so
/// the host logged the Part 9 ack as applied while upstream still showed the condition unacknowledged. A /// the host logged the Part 9 ack as applied while upstream still showed the condition unacknowledged. A
/// transport failure (no reply) now propagates with its status; a reply — even one carrying per-ack refusals — /// transport failure (no reply) now propagates with its status; a reply returns normally unless it carries a per-ack
/// still returns normally (that is the server answering, logged per ack). /// refusal, which (#947) throws the breaker-exempt <see cref="DriverOperationRefusedException"/> so the host's #760
/// revert fires. <c>BadConditionBranchAlreadyAcked</c> is the requested end state and stays a success.
/// </summary> /// </summary>
[Trait("Category", "Unit")] [Trait("Category", "Unit")]
public sealed class OpcUaClientAcknowledgeFailureTests public sealed class OpcUaClientAcknowledgeFailureTests
@@ -46,7 +47,7 @@ public sealed class OpcUaClientAcknowledgeFailureTests
/// <summary>Positive control: a reply returns normally and the call reached the wire.</summary> /// <summary>Positive control: a reply returns normally and the call reached the wire.</summary>
[Fact] [Fact]
public async Task Positive_control_a_reply_returns_normally() public async Task Positive_control_a_reply_returns_normally_and_already_acked_is_success()
{ {
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-o8-ok"); using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-o8-ok");
var session = NewSession(); var session = NewSession();
@@ -65,6 +66,120 @@ public sealed class OpcUaClientAcknowledgeFailureTests
Times.Once); Times.Once);
} }
private static Mock<ISession> SessionAnswering(params StatusCode[] statuses)
{
var session = NewSession();
session.Setup(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new CallResponse
{
ResponseHeader = new ResponseHeader(),
Results = statuses.Select(c => new CallMethodResult { StatusCode = c }).ToArray(),
DiagnosticInfos = [],
});
return session;
}
/// <summary>#947: an upstream per-ack refusal throws the breaker-exempt refusal (the #760 revert depends on it).</summary>
public static TheoryData<uint> RefusalStatuses => new()
{
StatusCodes.BadUserAccessDenied.Code, StatusCodes.BadNodeIdUnknown.Code,
StatusCodes.BadEventIdUnknown.Code, StatusCodes.BadInvalidState.Code,
};
[Theory]
[MemberData(nameof(RefusalStatuses))]
public async Task A_bad_per_ack_status_throws_the_breaker_exempt_refusal(uint status)
{
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-947");
drv.SetSessionForTest(SessionAnswering(new StatusCode(status)).Object);
var ex = await Should.ThrowAsync<DriverOperationRefusedException>(() =>
drv.AcknowledgeAsync(Ack(), TestContext.Current.CancellationToken));
ex.Message.ShouldContain(Condition);
ex.Message.ShouldContain(status.ToString("X8"));
}
/// <summary>A refusal is the server ANSWERING: health stays Healthy, not Degraded.</summary>
[Fact]
public async Task A_refused_ack_does_not_degrade_health()
{
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-947-health");
drv.SetHealthForTest(new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null));
drv.SetSessionForTest(SessionAnswering(StatusCodes.BadUserAccessDenied).Object);
await Should.ThrowAsync<DriverOperationRefusedException>(() =>
drv.AcknowledgeAsync(Ack(), TestContext.Current.CancellationToken));
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
}
/// <summary>
/// #947 through the host's real resilience pipeline: six refused acks (above the AlarmAcknowledge breaker's
/// threshold of five) must not open the breaker — a genuine ack that follows still reaches the server.
/// </summary>
[Fact]
public async Task Refused_acks_do_not_open_the_ack_breaker_and_are_not_retried()
{
var ct = TestContext.Current.CancellationToken;
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-947-breaker");
var calls = 0;
var session = NewSession();
session.Setup(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(() => new CallResponse
{
ResponseHeader = new ResponseHeader(),
Results = [new CallMethodResult { StatusCode = Interlocked.Increment(ref calls) <= 6 ? StatusCodes.BadUserAccessDenied : StatusCodes.Good }],
DiagnosticInfos = [],
});
drv.SetSessionForTest(session.Object);
var options = new ZB.MOM.WW.OtOpcUa.Core.Resilience.DriverResilienceOptions { Tier = DriverTier.A };
var invoker = new ZB.MOM.WW.OtOpcUa.Core.Resilience.CapabilityInvoker(
new ZB.MOM.WW.OtOpcUa.Core.Resilience.DriverResiliencePipelineBuilder(), "opcua-947-breaker", () => options, "OpcUaClient");
for (var i = 0; i < 6; i++)
await Should.ThrowAsync<DriverOperationRefusedException>(() => invoker.ExecuteAsync(
DriverCapability.AlarmAcknowledge, "host", async c => await drv.AcknowledgeAsync(Ack(), c), ct).AsTask());
calls.ShouldBe(6, "a refusal is not retried");
await invoker.ExecuteAsync(DriverCapability.AlarmAcknowledge, "host", async c => await drv.AcknowledgeAsync(Ack(), c), ct);
calls.ShouldBe(7, "the genuine ack still reaches the server");
}
/// <summary>A batch: results are index-aligned with the SENT calls — the refusal names the right condition.</summary>
[Fact]
public async Task A_refusal_in_a_batch_names_the_refused_condition_and_ignores_already_acked()
{
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-947-batch");
drv.SetSessionForTest(SessionAnswering(
StatusCodes.BadConditionBranchAlreadyAcked, StatusCodes.BadUserAccessDenied, StatusCodes.Good).Object);
var ex = await Should.ThrowAsync<DriverOperationRefusedException>(() => drv.AcknowledgeAsync(
[new("ns=2;s=A", "ns=2;s=A", null), new("ns=2;s=B", "ns=2;s=B", null), new("ns=2;s=C", "ns=2;s=C", null)],
TestContext.Current.CancellationToken));
ex.Message.ShouldContain("ns=2;s=B");
ex.Message.ShouldNotContain("ns=2;s=A");
ex.Message.ShouldNotContain("ns=2;s=C");
}
/// <summary>An unresolvable id alongside a resolvable one: the resolvable one is still sent, then the refusal is thrown.</summary>
[Fact]
public async Task A_partly_unresolvable_batch_sends_the_rest_then_refuses()
{
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-947-partial");
var session = SessionAnswering(StatusCodes.Good);
drv.SetSessionForTest(session.Object);
var ex = await Should.ThrowAsync<DriverOperationRefusedException>(() => drv.AcknowledgeAsync(
[new("ns=2;s=A", "ns=2;s=A", null), new("nsu=urn:not-in-table;s=X", "nsu=urn:not-in-table;s=X", null)],
TestContext.Current.CancellationToken));
ex.Message.ShouldContain("urn:not-in-table");
session.Verify(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()),
Times.Once);
}
[Fact] [Fact]
public async Task Acknowledge_encodes_EventId_as_scalar_ByteString_and_never_retries_a_transport_failure() public async Task Acknowledge_encodes_EventId_as_scalar_ByteString_and_never_retries_a_transport_failure()
{ {
@@ -117,18 +232,19 @@ public sealed class OpcUaClientAcknowledgeFailureTests
[new("nsu=urn:not-in-table;s=X", "nsu=urn:not-in-table;s=X", "ack")]; [new("nsu=urn:not-in-table;s=X", "nsu=urn:not-in-table;s=X", "ack")];
/// <summary> /// <summary>
/// Review m3 / r1 N-1: an ack none of whose condition ids resolves sends nothing upstream and says so at Warning — /// Review m3 / r1 N-1 / #947: an ack none of whose condition ids resolves sends nothing upstream, says so at Warning
/// but does NOT throw (a deterministic per-ack refusal must not count toward the AlarmAcknowledge breaker). /// and throws the breaker-exempt refusal (it used to return silently, so the host never reverted the node).
/// </summary> /// </summary>
[Fact] [Fact]
public async Task An_ack_with_no_resolvable_condition_warns_and_does_not_throw() public async Task An_ack_with_no_resolvable_condition_warns_and_is_refused()
{ {
var logger = new ListLogger(); var logger = new ListLogger();
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-m3", logger); using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-m3", logger);
var session = NewSession(); var session = NewSession();
drv.SetSessionForTest(session.Object); drv.SetSessionForTest(session.Object);
await drv.AcknowledgeAsync(Unresolvable(), TestContext.Current.CancellationToken); await Should.ThrowAsync<DriverOperationRefusedException>(() =>
drv.AcknowledgeAsync(Unresolvable(), TestContext.Current.CancellationToken));
session.Verify(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()), session.Verify(s => s.CallAsync(It.IsAny<RequestHeader>(), It.IsAny<ArrayOf<CallMethodRequest>>(), It.IsAny<CancellationToken>()),
Times.Never); Times.Never);
@@ -138,8 +254,8 @@ public sealed class OpcUaClientAcknowledgeFailureTests
/// <summary> /// <summary>
/// r1 N-1 through the host's real resilience pipeline: six unresolvable acks (more than the AlarmAcknowledge /// r1 N-1 through the host's real resilience pipeline: six unresolvable acks (more than the AlarmAcknowledge
/// breaker's threshold of five) must not open the breaker — a genuine ack that follows is still delivered /// breaker's threshold of five) must not open the breaker (they now THROW the exempt refusal, #947) — a genuine
/// upstream (the positive control). /// ack that follows is still delivered upstream (the positive control).
/// </summary> /// </summary>
[Fact] [Fact]
public async Task Unresolvable_acks_do_not_open_the_ack_breaker_for_real_acks() public async Task Unresolvable_acks_do_not_open_the_ack_breaker_for_real_acks()
@@ -159,8 +275,8 @@ public sealed class OpcUaClientAcknowledgeFailureTests
var invoker = new ZB.MOM.WW.OtOpcUa.Core.Resilience.CapabilityInvoker( var invoker = new ZB.MOM.WW.OtOpcUa.Core.Resilience.CapabilityInvoker(
new ZB.MOM.WW.OtOpcUa.Core.Resilience.DriverResiliencePipelineBuilder(), "opcua-n1", () => options, "OpcUaClient"); new ZB.MOM.WW.OtOpcUa.Core.Resilience.DriverResiliencePipelineBuilder(), "opcua-n1", () => options, "OpcUaClient");
// Failures are tolerated here on purpose (the host logs and drops them): what is asserted is that the six do // Refusals are tolerated here on purpose: what is asserted is that the six do not trip the breaker — a
// not trip the breaker — a driver that THREW for them would fail the genuine ack below with an open circuit. // non-exempt exception would fail the genuine ack below with an open circuit.
for (var i = 0; i < 6; i++) for (var i = 0; i < 6; i++)
{ {
try try
@@ -168,7 +284,7 @@ public sealed class OpcUaClientAcknowledgeFailureTests
await invoker.ExecuteAsync(DriverCapability.AlarmAcknowledge, "host", await invoker.ExecuteAsync(DriverCapability.AlarmAcknowledge, "host",
async c => await drv.AcknowledgeAsync(Unresolvable(), c), ct); async c => await drv.AcknowledgeAsync(Unresolvable(), c), ct);
} }
catch (ServiceResultException) { } catch (DriverOperationRefusedException) { }
} }
await invoker.ExecuteAsync(DriverCapability.AlarmAcknowledge, "host", await invoker.ExecuteAsync(DriverCapability.AlarmAcknowledge, "host",
@@ -0,0 +1,172 @@
using Moq;
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
/// <summary>
/// #946 — RefreshRequired sweeps were coalesced but not rate-limited: an upstream raising RefreshRequired
/// continuously got back-to-back ConditionRefresh sweeps of every alarm subscription. A minimum interval per
/// session now spaces them; a request inside the window is DEFERRED to the window's end, never dropped.
/// </summary>
[Trait("Category", "Unit")]
[Trait("Issue", "946")]
public sealed class OpcUaClientRefreshRequiredRateLimitTests
{
/// <summary>A TimeProvider whose time and timers move only when the test says so.</summary>
private sealed class ManualTimeProvider(DateTimeOffset start) : TimeProvider
{
private readonly object _lock = new();
private readonly List<ManualTimer> _timers = [];
private DateTimeOffset _now = start;
public override DateTimeOffset GetUtcNow() { lock (_lock) return _now; }
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
var t = new ManualTimer(this, callback, state);
t.Change(dueTime, period);
return t;
}
public void Advance(TimeSpan by)
{
List<ManualTimer> due;
lock (_lock)
{
_now += by;
due = _timers.Where(t => t.Due is { } d && d <= _now).ToList();
foreach (var t in due) t.Due = null;
}
foreach (var t in due) t.Fire();
}
private sealed class ManualTimer(ManualTimeProvider owner, TimerCallback cb, object? state) : ITimer
{
public DateTimeOffset? Due { get; set; }
public void Fire() => cb(state);
public bool Change(TimeSpan dueTime, TimeSpan period)
{
lock (owner._lock)
{
owner._timers.Remove(this);
if (dueTime == Timeout.InfiniteTimeSpan) { Due = null; return true; }
Due = owner._now + dueTime;
owner._timers.Add(this);
}
return true;
}
public void Dispose() { lock (owner._lock) owner._timers.Remove(this); }
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
}
}
private static (OpcUaClientDriver Drv, ManualTimeProvider Clock, Func<int> Sweeps) NewDriver(
string id, OpcUaClientDriverOptions? options = null)
{
var drv = new OpcUaClientDriver(options ?? new OpcUaClientDriverOptions(), id);
var clock = new ManualTimeProvider(new DateTimeOffset(2026, 11, 28, 12, 0, 0, TimeSpan.Zero));
drv.Clock = clock;
var session = new Mock<ISession>(MockBehavior.Loose);
drv.SetSessionForTest(session.Object);
drv.AddAlarmSubscriptionForTest(["Plant/opc/plc/Trip1"]);
var sweeps = 0;
drv.RefreshSweepStartedForTest = () => Interlocked.Increment(ref sweeps);
return (drv, clock, () => Volatile.Read(ref sweeps));
}
private static async Task Eventually(Func<bool> condition)
{
for (var i = 0; i < 200 && !condition(); i++) await Task.Delay(10, TestContext.Current.CancellationToken);
condition().ShouldBeTrue();
}
/// <summary>The default is a real limit (10 s), and zero is the opt-out.</summary>
[Fact]
public void Default_minimum_interval_is_ten_seconds()
=> new OpcUaClientDriverOptions().AlarmRefreshRequiredMinInterval.ShouldBe(TimeSpan.FromSeconds(10));
/// <summary>
/// The first sweep runs at once; a request inside the window waits for the window's end (and runs — deferred,
/// not dropped); however many requests arrive during the wait they coalesce into ONE sweep.
/// </summary>
[Fact]
public async Task A_request_inside_the_window_is_deferred_to_its_end_and_coalesced()
{
var (drv, clock, sweeps) = NewDriver("opcua-946-defer");
using var _ = drv;
drv.RequestRefreshRequiredSweepForTest();
await Eventually(() => sweeps() == 1);
clock.Advance(TimeSpan.FromSeconds(1));
drv.RequestRefreshRequiredSweepForTest();
drv.RequestRefreshRequiredSweepForTest();
drv.RequestRefreshRequiredSweepForTest();
// Absence is only meaningful with a positive control (below): the window has not elapsed, so nothing runs.
clock.Advance(TimeSpan.FromSeconds(8));
await Task.Delay(150, TestContext.Current.CancellationToken);
sweeps().ShouldBe(1, "9 s into a 10 s window");
// Positive control: the window's end releases exactly one deferred sweep.
clock.Advance(TimeSpan.FromSeconds(1));
await Eventually(() => sweeps() == 2);
await Task.Delay(150, TestContext.Current.CancellationToken);
sweeps().ShouldBe(2, "three coalesced requests are one sweep");
}
/// <summary>The window then restarts from the deferred sweep: a later request is deferred again.</summary>
[Fact]
public async Task The_window_restarts_from_each_sweep()
{
var (drv, clock, sweeps) = NewDriver("opcua-946-restart");
using var _ = drv;
drv.RequestRefreshRequiredSweepForTest();
await Eventually(() => sweeps() == 1);
clock.Advance(TimeSpan.FromSeconds(10));
drv.RequestRefreshRequiredSweepForTest(); // exactly at the end of the first window: runs at once
await Eventually(() => sweeps() == 2);
drv.RequestRefreshRequiredSweepForTest(); // inside the second window
await Task.Delay(150, TestContext.Current.CancellationToken);
sweeps().ShouldBe(2);
clock.Advance(TimeSpan.FromSeconds(10));
await Eventually(() => sweeps() == 3);
}
/// <summary>Zero disables the limit: back-to-back requests each sweep.</summary>
[Fact]
public async Task Zero_interval_disables_the_limit()
{
var (drv, _, sweeps) = NewDriver("opcua-946-off",
new OpcUaClientDriverOptions { AlarmRefreshRequiredMinInterval = TimeSpan.Zero });
using var _d = drv;
drv.RequestRefreshRequiredSweepForTest();
await Eventually(() => sweeps() == 1);
drv.RequestRefreshRequiredSweepForTest();
await Eventually(() => sweeps() == 2);
}
/// <summary>A new session starts a fresh window (its first RefreshRequired must not wait on the old session's).</summary>
[Fact]
public async Task A_new_session_starts_a_fresh_window()
{
var (drv, _, sweeps) = NewDriver("opcua-946-session");
using var _d = drv;
drv.RequestRefreshRequiredSweepForTest();
await Eventually(() => sweeps() == 1);
drv.SetSessionForTest(new Mock<ISession>(MockBehavior.Loose).Object);
drv.RequestRefreshRequiredSweepForTest();
await Eventually(() => sweeps() == 2);
}
}