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
@@ -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