fix(opcuaclient): #926 review r1 - loss after the signal withdraws known; gaps outside a bracket, overlapping starts, failed refreshes

- a sequence gap outside a bracket is a loss (re-refresh, same budget); older/repeated
  sequence numbers are ignored and not recorded
- AlarmInitialStateEventArgs.Withdrawn (additive): the driver withdraws 'known' once per
  signalled episode on its first loss; DriverHostActor sends MarkConditionsKnown(Known:false)
  for those conditions, drops them from the backstop and re-arms F5
- a RefreshStart while a bracket is open is a loss (never erases the open bracket's)
- a failed ConditionRefresh call is retried through the same bounded retry
- retry generation token (a finished retry never clears a newer retry's pending flag)
- spent budget renews after a 5-min cool-down; RefreshRequired sweeps coalesced
Red/green per fix (7 mutations) + live opc-plc gate re-run.
This commit is contained in:
Joseph Doherty
2026-11-28 10:07:08 -05:00
parent 99f2b9d8b7
commit 06da40a909
12 changed files with 534 additions and 75 deletions
+5 -1
View File
@@ -298,7 +298,11 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
`EventQueueOverflowEventType` (matched by EventType BEFORE the source filter — it comes from the Server object), a
RefreshRequired, or a publish-sequence gap (`EventFieldList.Message.SequenceNumber`; SDK 2.0.1's `Republish` publish-state
never fires for a gap that blocks delivery — do not rely on it) inside the bracket ⇒ no signal + bounded re-refresh
(3, 2/4/8 s). Exhausted ⇒ stays unknown; never fall back to `Unsignalable` (that starts the backstop that marks known).
(3 per episode, 2/4/8 s; a new budget only after a 5-min
cool-down). A loss OUTSIDE a bracket (overflow, gap) re-refreshes too, and any loss after a signal raises
`AlarmInitialStateEventArgs.Withdrawn` (host ⇒ `Known: false`, F5 re-armed, out of the backstop). A Start while a
bracket is open is a loss. Exhausted ⇒ stays unknown; never fall back to `Unsignalable` (that starts the backstop that
marks known).
- **OpcUaClient server host-name check (#816):** the SDK checks the server certificate's host only with
`checkDomain: true`; its 8-arg `DefaultSessionFactory.CreateAsync` hard-codes `false`, so driver, AdminUI browser and
Client.Shared never checked before #816. Now `certificateValidation.validateServerHostName` (tri-state, unset = off =
+4 -2
View File
@@ -483,8 +483,10 @@ refresh, EventIds) is documented in [Alarm tracking § Imported conditions](Alar
unknown).
- An OpcUaClient RefreshEnd signals only for a lossless refresh bracket (#926). Loss inside the bracket — queue
overflow, RefreshRequired, a skipped publish gap, or a missing RefreshStart — suppresses the signal and re-runs
ConditionRefresh, at most 3 times. If every retry is lossy, the conditions stay unknown and the timeout diagnostic
reports them. See `docs/drivers/OpcUaClient.md`.
ConditionRefresh, at most 3 times per episode. If every retry is lossy, the conditions stay unknown and the timeout
diagnostic reports them. A loss after the signal **withdraws** "known" for that subscription's conditions
(`AlarmInitialStateEventArgs.Withdrawn` ⇒ `MarkConditionsKnown(Known: false)`, F5 re-armed, no backstop) until a
clean refresh signals again. See `docs/drivers/OpcUaClient.md`.
### Condition key (`DataConnections:ConditionKeySecret`)
+11 -4
View File
@@ -463,10 +463,17 @@ initialise (the AdminUI form drops them on the next save). Pinned by
> - a delivered publish message skipped a sequence number. This catches the gap the SDK gives up on after a failed
> republish, which the SDK reports nowhere else.
>
> A lossy bracket logs a Warning and re-runs ConditionRefresh on that subscription. At most 3 re-refreshes run per
> episode, backing off 2 s, 4 s and 8 s, and a clean RefreshEnd resets the budget. When it is spent, nothing signals:
> the conditions stay unknown (`Uncertain`) and the host's `ConditionKnownSignalTimeout` diagnostic reports them.
> An overflow outside a bracket (lost live transitions) also requests a re-refresh. The alarm event item asks for a
> A RefreshStart that arrives while a bracket is still open is a loss too.
>
> Any loss logs a Warning and re-runs ConditionRefresh on that subscription. That includes an overflow or sequence gap
> outside a bracket, which can hold a lost live transition, and a failed ConditionRefresh call.
>
> - **Withdraw on a later loss:** a loss after the subscription signalled also **withdraws "known"**
> (`AlarmInitialStateEventArgs.Withdrawn`). The host takes known back for those conditions (`Uncertain` on a
> 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
> 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
> 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`.
> Last-told state survives a re-initialise (the host re-subscribes the same set over nodes it did not rebuild) and is
@@ -505,11 +505,22 @@ conditions re-report (`NM:5639-5651`). Some state changes never produce an event
one monitored item. This is how a gap the SDK gave up on is detected. SDK 2.0.1 reports that skip to nothing
else: its `PublishStateChangedMask.Republish` callback fires only in a worker pass that also delivers a message,
which the blocking gap prevents (verified by decompiling, and pinned by a real-SDK test).
- A lossy bracket re-runs ConditionRefresh on that subscription. This is bounded: at most 3 re-refreshes per lossy
episode, backing off 2 s, 4 s and 8 s, and a clean RefreshEnd resets the budget. A RefreshRequired keeps its own
sweep. When the budget is spent, nothing signals. The conditions stay unknown (`Uncertain`) and F5's
`ConditionKnownSignalTimeout` diagnostic reports them. They are never declared known-inactive, and the
`Unsignalable` backstop is not used for this.
- A RefreshStart that arrives while a bracket is still open is itself a loss. It never erases the open bracket's
loss.
- **A loss after the signal withdraws "known"** (review r1). This covers an overflow or sequence gap outside a
bracket, which can hold a live Raise. The driver raises `AlarmInitialStateEventArgs.Withdrawn` once per signalled
episode, ordered like the signal. The host sends `MarkConditionsKnown(Known: false)` for exactly those
conditions, removes them from the backstop, and puts them back in the F5 window. A clean RefreshEnd, or a
transition, makes them known again.
- Every loss, inside or outside a bracket, re-runs ConditionRefresh on that subscription. A failed ConditionRefresh
call is retried the same way. The retries are bounded:
- at most 3 per lossy episode, backing off 2 s, 4 s and 8 s;
- a clean RefreshEnd ends the episode and resets the budget;
- once the budget is spent, a further loss gets a new budget only after a 5-minute cool-down. So the driver
never storms the upstream and never gives up permanently.
- A RefreshRequired keeps its own sweep, now coalesced while one is queued.
- With no signal, the conditions stay unknown (`Uncertain`) and F5's `ConditionKnownSignalTimeout` diagnostic
reports them. They are never declared known-inactive, and the `Unsignalable` backstop is not used for this.
- The alarm event item's queue is now 10,000 (it was 1,000), so overflow is rarer. The detection above is the fix.
- Live on `opc-plc --alm` with a test-sized queue: the overflow notices reach the driver. With `DiscardOldest`
false the RefreshEnd is itself dropped. With `DiscardOldest` true the RefreshEnd arrives over a lossy replay and
@@ -113,6 +113,35 @@ Two observations from the runs:
gap. So can an SDK sequence resync after a transfer. Either costs one bounded re-refresh and is never a wrong signal.
- **Stale RefreshEnd.** If the previous replay's lossy RefreshEnd is still in flight when a re-refresh starts, it can
request one extra refresh. That stays inside the bound.
- **Live losses after the conditions are known.** An overflow outside a bracket is repaired by a re-refresh. A gap
- ~~**Live losses after the conditions are known.** An overflow outside a bracket is repaired by a re-refresh. A gap
outside a bracket is not detected, but the next bracket replays the full state. In both cases conditions that are
already known are not taken back to unknown.
already known are not taken back to unknown.~~ Superseded by review round 1 (below): both are losses, re-refreshed,
and they withdraw "known".
## Review round 1 (2026-11-28)
| # | Finding | Outcome |
|---|---|---|
| 1 | A sequence gap outside a bracket was detected and ignored, although it can hold a live Raise. | **Fixed.** Every newer, non-successor sequence number is a loss, inside or outside a bracket. It withdraws "known" if the subscription signalled, and requests a re-refresh from the same budget. |
| 2 | A loss after the signal never withdrew "known". The budget was shared across episodes. | **Fixed with a new host contract.** `AlarmInitialStateEventArgs.Withdrawn` is an additive constructor flag, exclusive with `Unsignalable`. The driver raises it once per signalled episode, on the first loss, ordered like the signal. `DriverHostActor` turns it into `MarkConditionsKnown(Known: false)` for exactly those conditions (the existing withdraw primitive), removes them from the backstop, and re-adds them to the F5 pending set. The budget was already per episode, because a clean RefreshEnd resets it. A spent budget now also renews after a 5-minute cool-down (`AlarmRefreshRetryCooldown`). While spent, a loss leaves the request open (`ScheduleAlarmRefreshRetryLocked` returns false), so the post-cool-down loss can start a retry. |
| 3 | A nested RefreshStart erased the outer bracket's loss. | **Fixed.** A Start while a bracket is open is recorded as a loss with `??=`, so it never clears the existing one. A depth counter was rejected: in the serial case a lost RefreshEnd would keep the depth above zero forever, so nothing would ever signal. |
| 4 | A failed ConditionRefresh (at subscribe, in a sweep, or in a retry) was never retried. | **Fixed.** The catch in `TryConditionRefreshAsync` calls `NoteConditionRefreshFailed`, which uses the same bounded retry. |
| 5 | A retry's `finally` cleared a `RetryPending` that a newer retry had set. | **Fixed** with a generation token (`RetryGeneration`). |
| 6 | Backward sequence numbers were written back, which produced a second, false gap. | **Fixed.** A repeated or older number (wrap-aware, forward distance ≥ 2³¹) is ignored and not recorded. |
| 7 | The RefreshRequired sweep was unbounded. | **Coalesced**: a RefreshRequired is a no-op while a sweep is queued and not yet started. It is not rate-limited, so a server that sends RefreshRequired continuously still gets back-to-back sweeps. That limit existed before this change and is reported as a follow-up. |
**Red checks.** One mutation per fix, each run against the new tests:
- M1 (gap outside a bracket ignored): `Sequence_gap_outside_a_bracket_withdraws_known_and_re_refreshes` fails.
- M2 (no withdraw): the 3 withdraw tests fail.
- M3 (a nested Start erases the loss): `An_overlapping_RefreshStart_does_not_erase_the_loss` fails.
- M4 (no generation token): `A_retry_scheduled_during_a_refresh_call_keeps_coalescing` fails.
- M5 (older numbers recorded): `An_older_sequence_number_is_ignored_and_not_recorded` fails.
- M6 (a failed refresh is not retried): `A_failed_ConditionRefresh_is_retried_bounded` fails.
- M7 (host ignores `Withdrawn`): Runtime `A_withdrawn_signal_takes_known_back_and_rearms_F5_until_the_next_signal` and
`A_withdrawal_cancels_the_backstop_for_its_conditions` fail.
M6 goes through the `ReportRefreshFailedForTest` seam. The catch that calls it is covered by review.
**Residual.** If a subscription never signalled (its initial refresh is still pending), a loss withdraws nothing,
because nothing was known.
@@ -34,6 +34,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
/// once with <see cref="AlarmInitialStateEventArgs.Unsignalable"/> set: the host then applies its
/// per-driver-type backstop timer to those conditions instead. No other shipped source should use it.
/// </para>
/// <para>
/// <b>Withdrawing (#926).</b> A source that signalled and then LOSES events for those conditions (an OPC UA
/// event-queue overflow, a publish gap) raises the event with <see cref="AlarmInitialStateEventArgs.Withdrawn"/>
/// set: the host takes "known" back from them (Uncertain on a consumer) until the source signals again or a
/// transition re-establishes one. Same ordering rule: after every alarm event raised before it.
/// </para>
/// </remarks>
public interface IAlarmInitialStateSignal
{
@@ -50,11 +56,18 @@ public sealed class AlarmInitialStateEventArgs : EventArgs
/// <see langword="true"/> when the source can never signal for these conditions (no refresh upstream);
/// the host's backstop timer applies instead of an immediate mark.
/// </param>
public AlarmInitialStateEventArgs(IReadOnlyList<string> conditionIds, bool unsignalable = false)
/// <param name="withdrawn">
/// <see langword="true"/> (#926) when the source can no longer vouch for these conditions' state (it lost events
/// after establishing them): the host withdraws "known". Exclusive with <paramref name="unsignalable"/>.
/// </param>
public AlarmInitialStateEventArgs(IReadOnlyList<string> conditionIds, bool unsignalable = false, bool withdrawn = false)
{
ArgumentNullException.ThrowIfNull(conditionIds);
if (unsignalable && withdrawn)
throw new ArgumentException("A signal is either unsignalable or a withdrawal, not both.", nameof(withdrawn));
ConditionIds = conditionIds;
Unsignalable = unsignalable;
Withdrawn = withdrawn;
}
/// <summary>The driver condition ids (= RawPaths) the completed read covers. Never "everything".</summary>
@@ -65,4 +78,10 @@ public sealed class AlarmInitialStateEventArgs : EventArgs
/// so the per-driver-type backstop timer (OpcUaClient only) decides when they become known.
/// </summary>
public bool Unsignalable { get; }
/// <summary>
/// #926: the source lost events for these conditions after establishing them, so their state is no longer
/// known. The host withdraws "known" (never starting a backstop) until the next real signal.
/// </summary>
public bool Withdrawn { get; }
}
@@ -268,6 +268,15 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
ReportRefreshUnsignalable(ras.Subscription);
}
/// <summary>Test-only seam (#926): a ConditionRefresh call of <paramref name="handle"/>'s subscription failed, as the
/// refresh catch reports it.</summary>
/// <param name="handle">The alarm subscription handle.</param>
internal void ReportRefreshFailedForTest(IAlarmSubscriptionHandle handle)
{
if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras))
NoteConditionRefreshFailed(ras.Subscription);
}
/// <summary>
/// Test-only seam to install the <see cref="NamespaceMap"/> that connect builds at
/// runtime, so the v3 RawPath → upstream node id resolution can be exercised without a live
@@ -2920,14 +2929,17 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <c>EventQueueOverflowEventType</c> (Part 4) and the refresh markers come from the Server object, never
/// from an authored condition source, so the projector's source filter would drop them.
/// <list type="bullet">
/// <item>RefreshStart opens a bracket and clears the loss record.</item>
/// <item>RefreshStart opens a bracket and clears the loss record — unless a bracket is still open (its
/// RefreshEnd never arrived): an overlapping start is itself a loss, kept.</item>
/// <item>EventQueueOverflow is a definite loss: the bracket's RefreshEnd will not signal, and a bounded driver
/// re-refresh is requested (also outside a bracket — a lost live transition is repaired by a replay).</item>
/// <item>RefreshRequired is a loss too; it keeps its existing sweep, which IS the re-refresh.</item>
/// <item>RefreshRequired is a loss too; it keeps its existing (coalesced) sweep, which IS the re-refresh.</item>
/// <item>RefreshEnd signals (grpc-data A1) only for a bracket that was opened and saw no loss; otherwise it
/// stays silent — the conditions stay unknown (Uncertain), the safe invariant — and requests the
/// re-refresh if none was yet.</item>
/// </list>
/// Any loss after the subscription signalled also WITHDRAWS "known" from its conditions (see
/// <see cref="NoteBracketLoss"/>).
/// </summary>
/// <param name="type">The bracket event's EventType.</param>
/// <param name="handle">The subscription the event arrived on.</param>
@@ -2945,10 +2957,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
NoteBracketLoss(ras, "RefreshRequired", requestRetry: false);
ras.Bracket.RetryRequestedSinceStart = true;
}
// 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.
var sessionWork = _sessionWorkCts.Token;
_ = Task.Run(() => RefreshAllAlarmSubscriptionsAsync(sessionWork));
RequestRefreshRequiredSweep();
return;
}
@@ -2958,9 +2967,18 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
var b = ras.Bracket;
if (type == ObjectTypeIds.RefreshStartEventType)
{
if (b.Open)
{
// The previous bracket's RefreshEnd never arrived (or brackets overlap): that is a loss, and it must
// not be erased by this start.
NoteBracketLoss(ras, "overlapping RefreshStart (the previous RefreshEnd never arrived)", requestRetry: false);
}
else
{
b.LossSinceStart = null;
b.RetryRequestedSinceStart = false;
}
b.Open = true;
b.LossSinceStart = null;
b.RetryRequestedSinceStart = false;
}
else if (type == ObjectTypeIds.EventQueueOverflowEventType)
{
@@ -2976,9 +2994,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
{
// grpc-data A1 (F1): the refresh replay this subscription requested is complete, lossless, and every
// refreshed event before it was routed (sequential publishing, G2). Under the emission lock, so the
// signal is ordered behind every emission. Covers the subscription's alarm RawPaths.
// signal is ordered behind every emission. Covers the subscription's alarm RawPaths. Ends the
// lossy episode: the next loss gets a fresh budget.
b.Retries = 0;
b.ExhaustedLogged = false;
b.Signalled = true;
RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false);
return;
}
@@ -2989,17 +3009,19 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
"OpcUaClientDriver '{DriverInstanceId}': RefreshEnd on alarm subscription {SubscriptionId} NOT taken " +
"as 'initial alarm state delivered' — {Reason}; its conditions stay unknown until a lossless refresh.",
_driverInstanceId, ras.Handle.DiagnosticId, reason);
WithdrawKnownLocked(ras, reason);
if (!b.RetryRequestedSinceStart)
{
b.RetryRequestedSinceStart = true;
ScheduleAlarmRefreshRetryLocked(ras, reason);
}
b.RetryRequestedSinceStart = ScheduleAlarmRefreshRetryLocked(ras, reason);
}
}
}
/// <summary>#926: record a loss against <paramref name="ras"/>'s bracket and (once per bracket) request a
/// bounded re-refresh. Caller holds <c>_alarmStateLock</c>.</summary>
/// <summary>
/// #926: record a loss against <paramref name="ras"/>'s bracket, withdraw "known" if the subscription had
/// signalled (an event lost AFTER the conditions were declared known — a live Raise in an overflowed queue or a
/// skipped publish message — would otherwise leave a consumer holding a known-inactive condition that is active
/// upstream), and (once per bracket) request a bounded re-refresh. Caller holds <c>_alarmStateLock</c>.
/// </summary>
/// <param name="ras">The alarm subscription.</param>
/// <param name="reason">What was lost (logged).</param>
/// <param name="requestRetry">Whether the driver itself should re-run ConditionRefresh.</param>
@@ -3007,9 +3029,27 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
{
var b = ras.Bracket;
b.LossSinceStart ??= reason;
WithdrawKnownLocked(ras, reason);
if (!requestRetry || b.RetryRequestedSinceStart) return;
b.RetryRequestedSinceStart = true;
ScheduleAlarmRefreshRetryLocked(ras, reason);
// Only a retry actually scheduled (or already pending) covers this bracket's loss; a spent budget leaves the
// request open, so a loss after the cool-down can still start one.
b.RetryRequestedSinceStart = ScheduleAlarmRefreshRetryLocked(ras, reason);
}
/// <summary>#926: if <paramref name="ras"/> signalled since its last loss, tell the host its conditions are no longer
/// known (<see cref="AlarmInitialStateEventArgs.Withdrawn"/>) — ordered after every alarm event already raised, as the
/// signal is. A later clean RefreshEnd signals them known again. Caller holds <c>_alarmStateLock</c>.</summary>
/// <param name="ras">The alarm subscription.</param>
/// <param name="reason">Why (logged).</param>
private void WithdrawKnownLocked(RemoteAlarmSubscription ras, string reason)
{
if (!ras.Bracket.Signalled) return;
ras.Bracket.Signalled = false;
_logger.LogWarning(
"OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId} lost events after its conditions " +
"were declared known ({Reason}); withdrawing 'known' until a lossless ConditionRefresh.",
_driverInstanceId, ras.Handle.DiagnosticId, reason);
RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false, withdrawn: true);
}
/// <summary>
@@ -3020,10 +3060,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// and delivers the next message. That skip is reported to nothing the driver can observe — SDK 2.0.1 raises its
/// <c>PublishStateChangedMask.Republish</c> only in a message-worker pass that also delivers a message, which a
/// gap holding every later message prevents (pinned by the real-SDK test). So the driver compares sequence
/// numbers itself: a message that is not the previous one or its successor means messages were lost, and
/// inside a bracket that replay is lossy. Outside a bracket the next bracket replays the full state.
/// A StatusChange-only message (transfer / timeout) also consumes a number and reads as a gap: a bounded
/// extra refresh, never a wrong signal.
/// numbers itself: a newer message that is not the successor of the previous one means messages were lost —
/// inside a bracket the replay is lossy, outside it a live transition may be lost; either way it is a loss
/// (withdraw if signalled + bounded re-refresh). An OLDER (or repeated) number is ignored and not recorded, so a
/// stray late message cannot make the next in-order one read as a second gap. A StatusChange-only message
/// (transfer / timeout) also consumes a number and reads as a gap: a bounded extra refresh, never a wrong signal.
/// </summary>
/// <param name="handle">The alarm subscription handle.</param>
/// <param name="sequenceNumber">The delivered message's sequence number (0 = unknown, ignored).</param>
@@ -3035,24 +3076,36 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
{
var b = ras.Bracket;
var last = b.LastSequenceNumber;
if (last == 0) { b.LastSequenceNumber = sequenceNumber; return; }
// Wrap-aware "newer" (RFC 1982-style, as the SDK compares): forward distance in (0, 2^31). Sequence numbers
// skip 0 on the wrap (… uint.MaxValue, 1 …), so the successor of uint.MaxValue is 1.
var forward = unchecked(sequenceNumber - last);
if (forward == 0 || forward >= 0x8000_0000u) return; // repeat or older: ignore, do not record
b.LastSequenceNumber = sequenceNumber;
if (last == 0 || sequenceNumber == last) return;
var next = last == uint.MaxValue ? 1u : last + 1;
if (sequenceNumber == next || !b.Open) return;
if (sequenceNumber == next) return;
NoteBracketLoss(ras,
$"publish message(s) of the replay were lost (sequence {last} → {sequenceNumber})", requestRetry: true);
$"publish message(s) lost (sequence {last} → {sequenceNumber}){(b.Open ? " during a refresh replay" : "")}",
requestRetry: true);
}
}
/// <summary>#926: the bounded number of driver-initiated re-refreshes per lossy episode (reset by a clean
/// <summary>#926: the bounded number of driver-initiated re-refreshes per lossy episode (an episode ends with a clean
/// RefreshEnd). When spent, the conditions stay unknown (Uncertain) and the host's
/// <c>ConditionKnownSignalTimeout</c> diagnostic reports them — never known-inactive.</summary>
/// <c>ConditionKnownSignalTimeout</c> diagnostic reports them — never known-inactive. After
/// <see cref="AlarmRefreshRetryCooldown"/> without a retry, a further loss starts a new budget, so a structurally
/// lossy upstream is retried at most <see cref="MaxAlarmRefreshRetries"/> times per cool-down — no storm, and no
/// permanent give-up either.</summary>
internal const int MaxAlarmRefreshRetries = 3;
/// <summary>#926: the first re-refresh delay; each further retry doubles it (2 s, 4 s, 8 s), giving the
/// upstream time to drain whatever overflowed. Test seam.</summary>
internal TimeSpan AlarmRefreshRetryBaseDelay { get; set; } = TimeSpan.FromSeconds(2);
/// <summary>#926: after the budget is spent, how long since the last retry before a new loss gets a new budget.
/// Test seam.</summary>
internal TimeSpan AlarmRefreshRetryCooldown { get; set; } = TimeSpan.FromMinutes(5);
/// <summary>#926 test seam: replaces the ConditionRefresh call of a driver re-refresh.</summary>
internal Func<Subscription, CancellationToken, Task>? AlarmRefreshRetryInvokerForTest { get; set; }
@@ -3060,10 +3113,17 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// Caller holds <c>_alarmStateLock</c>.</summary>
/// <param name="ras">The alarm subscription.</param>
/// <param name="reason">Why (logged).</param>
private void ScheduleAlarmRefreshRetryLocked(RemoteAlarmSubscription ras, string reason)
/// <returns>Whether a retry is now pending (scheduled here or already) — false when the budget is spent.</returns>
private bool ScheduleAlarmRefreshRetryLocked(RemoteAlarmSubscription ras, string reason)
{
var b = ras.Bracket;
if (b.RetryPending) return;
if (b.RetryPending) return true;
var now = Clock.GetUtcNow().UtcDateTime;
if (b.Retries >= MaxAlarmRefreshRetries && b.LastRetryUtc is { } lastRetry && now - lastRetry >= AlarmRefreshRetryCooldown)
{
b.Retries = 0; // a new episode after the cool-down
b.ExhaustedLogged = false;
}
if (b.Retries >= MaxAlarmRefreshRetries)
{
if (!b.ExhaustedLogged)
@@ -3071,31 +3131,37 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
b.ExhaustedLogged = true;
_logger.LogWarning(
"OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId} lost refresh events " +
"{Retries} time(s) in a row ({Reason}); no further re-refresh. Its conditions stay unknown (Uncertain) " +
"until a later lossless ConditionRefresh (RefreshRequired, reconnect, resubscribe). The event item's " +
"revised queue size is {QueueSize}.",
_driverInstanceId, ras.Handle.DiagnosticId, b.Retries, reason, ras.EventItem.Status?.QueueSize);
"{Retries} time(s) in a row ({Reason}); no further re-refresh for {Cooldown}. Its conditions stay " +
"unknown (Uncertain) until a lossless ConditionRefresh (RefreshRequired, reconnect, resubscribe, or a " +
"loss after the cool-down). The event item's revised queue size is {QueueSize}.",
_driverInstanceId, ras.Handle.DiagnosticId, b.Retries, reason, AlarmRefreshRetryCooldown,
ras.EventItem.Status?.QueueSize);
}
return;
return false;
}
b.Retries++;
b.RetryPending = true;
b.LastRetryUtc = now;
var generation = ++b.RetryGeneration;
var delay = AlarmRefreshRetryBaseDelay * (1 << (b.Retries - 1));
_logger.LogWarning(
"OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId}: {Reason}; re-running " +
"ConditionRefresh in {Delay} (attempt {Attempt}/{Max}).",
_driverInstanceId, ras.Handle.DiagnosticId, reason, delay, b.Retries, MaxAlarmRefreshRetries);
var sessionWork = _sessionWorkCts.Token;
_ = Task.Run(() => RetryAlarmRefreshAsync(ras, delay, sessionWork));
_ = Task.Run(() => RetryAlarmRefreshAsync(ras, generation, delay, sessionWork));
return true;
}
/// <summary>#926: after <paramref name="delay"/>, re-run ConditionRefresh on <paramref name="ras"/> — only while it
/// is still the registered subscription for its handle (an unsubscribe / re-init releases it).</summary>
/// <param name="ras">The alarm subscription.</param>
/// <param name="generation">This retry's generation: only it may clear <c>RetryPending</c>.</param>
/// <param name="delay">The back-off.</param>
/// <param name="cancellationToken">The session's work token (cancelled by shutdown / re-init).</param>
/// <returns>A task completing when the refresh call returned (or was skipped).</returns>
private async Task RetryAlarmRefreshAsync(RemoteAlarmSubscription ras, TimeSpan delay, CancellationToken cancellationToken)
private async Task RetryAlarmRefreshAsync(
RemoteAlarmSubscription ras, long generation, TimeSpan delay, CancellationToken cancellationToken)
{
var gateHeld = false;
try
@@ -3108,11 +3174,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// when the replay's own RefreshStart is lost too (queue still full) — without the reset, no bracket opens
// and nothing could request again. A lossy RefreshEnd of the PREVIOUS replay still in flight can then
// request one extra refresh; that is inside the bound.
lock (_alarmStateLock)
{
ras.Bracket.RetryPending = false;
ras.Bracket.RetryRequestedSinceStart = false;
}
ReleaseRetryPending(ras, generation, resetRequested: true);
if (AlarmRefreshRetryInvokerForTest is { } invoke)
await invoke(ras.Subscription, cancellationToken).ConfigureAwait(false);
else if (ras.Subscription.Session is not null && ras.Subscription.Created)
@@ -3128,7 +3190,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
finally
{
lock (_alarmStateLock) ras.Bracket.RetryPending = false;
// Only THIS retry's pending flag: a retry scheduled while the refresh call ran (a new generation) stands.
ReleaseRetryPending(ras, generation, resetRequested: false);
if (gateHeld)
{
try { _subscriptionGate.Release(); } catch (ObjectDisposedException) { }
@@ -3136,6 +3199,50 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
}
}
/// <summary>#926: clear <c>RetryPending</c> if it still belongs to retry <paramref name="generation"/>.</summary>
/// <param name="ras">The alarm subscription.</param>
/// <param name="generation">The retry's generation.</param>
/// <param name="resetRequested">Also re-allow a retry request for the current bracket.</param>
private void ReleaseRetryPending(RemoteAlarmSubscription ras, long generation, bool resetRequested)
{
lock (_alarmStateLock)
{
if (ras.Bracket.RetryGeneration != generation) return;
ras.Bracket.RetryPending = false;
if (resetRequested) ras.Bracket.RetryRequestedSinceStart = false;
}
}
/// <summary>#926: a ConditionRefresh call on <paramref name="subscription"/> failed (not "unsupported"): no
/// RefreshEnd will come for it, so request a bounded re-refresh instead of waiting for the next external trigger.</summary>
/// <param name="subscription">The SDK alarm subscription.</param>
private void NoteConditionRefreshFailed(Subscription subscription)
{
foreach (var ras in _alarmSubscriptions.Values)
{
if (!ReferenceEquals(ras.Subscription, subscription)) continue;
lock (_alarmStateLock) _ = ScheduleAlarmRefreshRetryLocked(ras, "ConditionRefresh call failed");
}
}
/// <summary>1 while a RefreshRequired-triggered sweep is queued and has not started (coalescing).</summary>
private int _refreshRequiredSweepQueued;
/// <summary>
/// #926 (review r1 #7): a RefreshRequired asks for a refresh of every alarm subscription. Coalesced: while one
/// sweep is queued and not yet started, further RefreshRequired events add nothing (that sweep covers them). A
/// RefreshRequired arriving once the sweep has started queues the next one — it may report a later loss.
/// </summary>
private void RequestRefreshRequiredSweep()
{
if (Interlocked.CompareExchange(ref _refreshRequiredSweepQueued, 1, 0) != 0) return;
// 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.
var sessionWork = _sessionWorkCts.Token;
_ = Task.Run(() => RefreshAllAlarmSubscriptionsAsync(sessionWork,
onStart: () => Interlocked.Exchange(ref _refreshRequiredSweepQueued, 0)));
}
/// <summary>True for a <c>RefreshRequiredEventType</c> event (the server asks the client to ConditionRefresh).</summary>
/// <param name="fields">The event's fields.</param>
/// <returns>Whether the event is a RefreshRequired marker.</returns>
@@ -3150,12 +3257,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
fields.Count > AlarmFieldEventType && UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId t
&& t == ObjectTypeIds.RefreshEndEventType;
private void RaiseInitialAlarmState(IReadOnlyList<string> refs, bool unsignalable)
private void RaiseInitialAlarmState(IReadOnlyList<string> refs, bool unsignalable, bool withdrawn = false)
{
if (refs.Count == 0) return;
try
{
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs, unsignalable));
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs, unsignalable, withdrawn));
}
catch (Exception ex)
{
@@ -3210,6 +3317,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
"OpcUaClientDriver '{DriverInstanceId}': ConditionRefresh on alarm subscription {SubscriptionId} failed; " +
"conditions already active upstream may not be reported until their next transition.",
_driverInstanceId, subscription.Id);
// #926 (review r1 #4): no RefreshEnd will come for this call — retry it, bounded.
NoteConditionRefreshFailed(subscription);
}
catch (OperationCanceledException)
{
@@ -3235,9 +3344,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// outage reach the host through the normal deduplicated path.
/// </summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <param name="onStart">Invoked first thing (the RefreshRequired coalescing flag's release).</param>
/// <returns>A task completing when every refresh call has returned.</returns>
private async Task RefreshAllAlarmSubscriptionsAsync(CancellationToken cancellationToken)
private async Task RefreshAllAlarmSubscriptionsAsync(CancellationToken cancellationToken, Action? onStart = null)
{
onStart?.Invoke();
if (_alarmSubscriptions.IsEmpty) return;
try
{
@@ -3521,6 +3632,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <summary>Sequence number of the last delivered notification message (0 = none yet).</summary>
public uint LastSequenceNumber;
/// <summary>This subscription's conditions were declared known (a clean RefreshEnd) and no loss since: a loss
/// now must withdraw "known".</summary>
public bool Signalled;
/// <summary>When the last driver re-refresh was scheduled (cool-down of a spent budget).</summary>
public DateTime? LastRetryUtc;
/// <summary>Generation of the last scheduled re-refresh; only that retry may clear <see cref="RetryPending"/>.</summary>
public long RetryGeneration;
}
private sealed record OpcUaAlarmSubscriptionHandle(long Id) : IAlarmSubscriptionHandle
@@ -213,6 +213,26 @@ public sealed partial class DriverHostActor
return;
}
if (msg.Args.Withdrawn)
{
// #926: the source lost events after establishing these conditions. Take "known" back (same chain as its
// projections, so it lands after them), keep them out of the backstop (which would re-mark them known by
// timer), and put them back in the F5 window so a source that never re-signals is diagnosed.
t.Unsignalable.ExceptWith(msg.Args.ConditionIds);
var withdrawn = MarkDriverConditionsKnown(msg.DriverInstanceId, msg.Args.ConditionIds, known: false);
if (t.GoodSinceUtc is not null && _alarmRefsByDriver.TryGetValue(msg.DriverInstanceId, out var owned))
{
var ownedPaths = owned.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal);
var before = t.Pending.Count;
t.Pending.UnionWith(msg.Args.ConditionIds.Where(ownedPaths.Contains));
// An F5 window already running covers them; otherwise start one now.
if (t.Pending.Count != before && t.PendingSinceUtc is null) ArmSignalTimeout(msg.DriverInstanceId, t);
}
_log.Info("DriverHost {Node}: driver {Driver} withdrew {Count} condition(s) ({Routed} routed) — state no longer known (events lost)",
_localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, withdrawn);
return;
}
if (msg.Args.Unsignalable)
{
// InitialStateUnsignalable: no real signal will come. Only a driver type with a backstop (OpcUaClient) marks
@@ -327,7 +347,7 @@ public sealed partial class DriverHostActor
}
/// <summary>Route driver condition ids (RawPaths) to their condition nodes and send one mark per realm.</summary>
private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection<string> conditionIds)
private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection<string> conditionIds, bool known = true)
{
if (_opcUaPublishActor is null || conditionIds.Count == 0) return 0;
var byRealm = new Dictionary<AddressSpaceRealm, List<string>>();
@@ -344,7 +364,7 @@ public sealed partial class DriverHostActor
var count = 0;
foreach (var (realm, ids) in byRealm)
{
_opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm));
_opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm, Known: known));
count += ids.Count;
}
@@ -114,7 +114,7 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
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;
}
@@ -164,15 +164,14 @@ public sealed class OpcUaClientRefreshBracketLossTests
}
/// <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), the wrap and a gap outside a bracket are no loss.</summary>
/// 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_outside_is_ignored()
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, 5);
drv.NoteAlarmMessageSequence(h, 9); // gap outside a bracket: the next bracket replays everything
drv.NoteAlarmMessageSequence(h, 9);
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
drv.NoteAlarmMessageSequence(h, 10);
drv.NoteAlarmMessageSequence(h, 10); // a second event of the same message
@@ -181,20 +180,207 @@ public sealed class OpcUaClientRefreshBracketLossTests
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
trace.ShouldBe(["signal:" + Trip1], "no loss inside that bracket");
drv.NoteAlarmMessageSequence(h, uint.MaxValue);
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
drv.NoteAlarmMessageSequence(h, 1); // the wrap is contiguous
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
trace.Count(t => t.StartsWith("signal:")).ShouldBe(2);
retries.Count.ShouldBe(0);
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
drv.NoteAlarmMessageSequence(h, 3); // message 2 lost
drv.NoteAlarmMessageSequence(h, 12);
drv.NoteAlarmMessageSequence(h, 14); // message 13 lost
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
trace.Count(t => t.StartsWith("signal:")).ShouldBe(2, "the replay with a lost message did not signal");
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()
@@ -115,6 +115,66 @@ 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.</summary>
[Fact]
public void A_withdrawal_cancels_the_backstop_for_its_conditions()
{
var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi"], o => o.WithOpcUaClientSettle(TimeSpan.FromMilliseconds(600)));
rig.Driver.Signal([A], unsignalable: true);
rig.Driver.Signal([A], withdrawn: true);
AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(1500));
}
/// <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;
}