diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index bd14264f2..c20978143 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -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 = diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 482fa032f..3ad1f3b84 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -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`) diff --git a/docs/drivers/OpcUaClient.md b/docs/drivers/OpcUaClient.md index af6a1f71a..9441a47c8 100644 --- a/docs/drivers/OpcUaClient.md +++ b/docs/drivers/OpcUaClient.md @@ -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 diff --git a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md index 0f279ae13..6039f7e72 100644 --- a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md +++ b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md @@ -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 diff --git a/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md b/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md index b88448563..b51bf7d54 100644 --- a/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md +++ b/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md @@ -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. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs index 00c5af02d..8983ae9d9 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs @@ -34,6 +34,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions; /// once with set: the host then applies its /// per-driver-type backstop timer to those conditions instead. No other shipped source should use it. /// +/// +/// Withdrawing (#926). A source that signalled and then LOSES events for those conditions (an OPC UA +/// event-queue overflow, a publish gap) raises the event with +/// 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. +/// /// public interface IAlarmInitialStateSignal { @@ -50,11 +56,18 @@ public sealed class AlarmInitialStateEventArgs : EventArgs /// when the source can never signal for these conditions (no refresh upstream); /// the host's backstop timer applies instead of an immediate mark. /// - public AlarmInitialStateEventArgs(IReadOnlyList conditionIds, bool unsignalable = false) + /// + /// (#926) when the source can no longer vouch for these conditions' state (it lost events + /// after establishing them): the host withdraws "known". Exclusive with . + /// + public AlarmInitialStateEventArgs(IReadOnlyList 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; } /// The driver condition ids (= RawPaths) the completed read covers. Never "everything". @@ -65,4 +78,10 @@ public sealed class AlarmInitialStateEventArgs : EventArgs /// so the per-driver-type backstop timer (OpcUaClient only) decides when they become known. /// public bool Unsignalable { get; } + + /// + /// #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. + /// + public bool Withdrawn { get; } } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs index bad924c8f..b28c97282 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs @@ -268,6 +268,15 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit ReportRefreshUnsignalable(ras.Subscription); } + /// Test-only seam (#926): a ConditionRefresh call of 's subscription failed, as the + /// refresh catch reports it. + /// The alarm subscription handle. + internal void ReportRefreshFailedForTest(IAlarmSubscriptionHandle handle) + { + if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras)) + NoteConditionRefreshFailed(ras.Subscription); + } + /// /// Test-only seam to install the 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 /// EventQueueOverflowEventType (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. /// - /// RefreshStart opens a bracket and clears the loss record. + /// 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. /// 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). - /// RefreshRequired is a loss too; it keeps its existing sweep, which IS the re-refresh. + /// RefreshRequired is a loss too; it keeps its existing (coalesced) sweep, which IS the re-refresh. /// 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. /// + /// Any loss after the subscription signalled also WITHDRAWS "known" from its conditions (see + /// ). /// /// The bracket event's EventType. /// The subscription the event arrived on. @@ -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); } } } - /// #926: record a loss against 's bracket and (once per bracket) request a - /// bounded re-refresh. Caller holds _alarmStateLock. + /// + /// #926: record a loss against '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 _alarmStateLock. + /// /// The alarm subscription. /// What was lost (logged). /// Whether the driver itself should re-run ConditionRefresh. @@ -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); + } + + /// #926: if signalled since its last loss, tell the host its conditions are no longer + /// known () — ordered after every alarm event already raised, as the + /// signal is. A later clean RefreshEnd signals them known again. Caller holds _alarmStateLock. + /// The alarm subscription. + /// Why (logged). + 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); } /// @@ -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 /// PublishStateChangedMask.Republish 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. /// /// The alarm subscription handle. /// The delivered message's sequence number (0 = unknown, ignored). @@ -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); } } - /// #926: the bounded number of driver-initiated re-refreshes per lossy episode (reset by a clean + /// #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 - /// ConditionKnownSignalTimeout diagnostic reports them — never known-inactive. + /// ConditionKnownSignalTimeout diagnostic reports them — never known-inactive. After + /// without a retry, a further loss starts a new budget, so a structurally + /// lossy upstream is retried at most times per cool-down — no storm, and no + /// permanent give-up either. internal const int MaxAlarmRefreshRetries = 3; /// #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. internal TimeSpan AlarmRefreshRetryBaseDelay { get; set; } = TimeSpan.FromSeconds(2); + /// #926: after the budget is spent, how long since the last retry before a new loss gets a new budget. + /// Test seam. + internal TimeSpan AlarmRefreshRetryCooldown { get; set; } = TimeSpan.FromMinutes(5); + /// #926 test seam: replaces the ConditionRefresh call of a driver re-refresh. internal Func? AlarmRefreshRetryInvokerForTest { get; set; } @@ -3060,10 +3113,17 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit /// Caller holds _alarmStateLock. /// The alarm subscription. /// Why (logged). - private void ScheduleAlarmRefreshRetryLocked(RemoteAlarmSubscription ras, string reason) + /// Whether a retry is now pending (scheduled here or already) — false when the budget is spent. + 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; } /// #926: after , re-run ConditionRefresh on — only while it /// is still the registered subscription for its handle (an unsubscribe / re-init releases it). /// The alarm subscription. + /// This retry's generation: only it may clear RetryPending. /// The back-off. /// The session's work token (cancelled by shutdown / re-init). /// A task completing when the refresh call returned (or was skipped). - 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 } } + /// #926: clear RetryPending if it still belongs to retry . + /// The alarm subscription. + /// The retry's generation. + /// Also re-allow a retry request for the current bracket. + 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; + } + } + + /// #926: a ConditionRefresh call on failed (not "unsupported"): no + /// RefreshEnd will come for it, so request a bounded re-refresh instead of waiting for the next external trigger. + /// The SDK alarm subscription. + private void NoteConditionRefreshFailed(Subscription subscription) + { + foreach (var ras in _alarmSubscriptions.Values) + { + if (!ReferenceEquals(ras.Subscription, subscription)) continue; + lock (_alarmStateLock) _ = ScheduleAlarmRefreshRetryLocked(ras, "ConditionRefresh call failed"); + } + } + + /// 1 while a RefreshRequired-triggered sweep is queued and has not started (coalescing). + private int _refreshRequiredSweepQueued; + + /// + /// #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. + /// + 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))); + } + /// True for a RefreshRequiredEventType event (the server asks the client to ConditionRefresh). /// The event's fields. /// Whether the event is a RefreshRequired marker. @@ -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 refs, bool unsignalable) + private void RaiseInitialAlarmState(IReadOnlyList 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. /// /// Cancellation. + /// Invoked first thing (the RefreshRequired coalescing flag's release). /// A task completing when every refresh call has returned. - 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 /// Sequence number of the last delivered notification message (0 = none yet). public uint LastSequenceNumber; + + /// This subscription's conditions were declared known (a clean RefreshEnd) and no loss since: a loss + /// now must withdraw "known". + public bool Signalled; + + /// When the last driver re-refresh was scheduled (cool-down of a spent budget). + public DateTime? LastRetryUtc; + + /// Generation of the last scheduled re-refresh; only that retry may clear . + public long RetryGeneration; } private sealed record OpcUaAlarmSubscriptionHandle(long Id) : IAlarmSubscriptionHandle diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.ConditionSignals.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.ConditionSignals.cs index c24eb455e..0fe0adc7c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.ConditionSignals.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.ConditionSignals.cs @@ -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 } /// Route driver condition ids (RawPaths) to their condition nodes and send one mark per realm. - private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection conditionIds) + private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection conditionIds, bool known = true) { if (_opcUaPublishActor is null || conditionIds.Count == 0) return 0; var byRealm = new Dictionary>(); @@ -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; } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientInitialAlarmStateSignalTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientInitialAlarmStateSignalTests.cs index 4cdee83a1..de86380e9 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientInitialAlarmStateSignalTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientInitialAlarmStateSignalTests.cs @@ -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; } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientRefreshBracketLossTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientRefreshBracketLossTests.cs index 31ac2d1ac..343eacf09 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientRefreshBracketLossTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientRefreshBracketLossTests.cs @@ -164,15 +164,14 @@ public sealed class OpcUaClientRefreshBracketLossTests } /// 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. + /// numbers, a repeat (several events in one message), an unknown number and the wrap are no loss. [Fact] - public async Task Sequence_gap_inside_the_bracket_suppresses_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); } + /// The sequence-number wrap (… uint.MaxValue, 1 …) is contiguous. + [Fact] + public void Sequence_wrap_is_contiguous() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-seqwrap"); + using var _ = drv; + + drv.NoteAlarmMessageSequence(h, uint.MaxValue); + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + drv.NoteAlarmMessageSequence(h, 1); + drv.NoteAlarmMessageSequence(h, 2); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBe(["signal:" + Trip1]); + retries.Count.ShouldBe(0); + } + + /// Review r1 #6: an OLDER sequence number (a stray late message) is ignored and not recorded, so the next + /// in-order message is not a second, false gap. + [Fact] + public void An_older_sequence_number_is_ignored_and_not_recorded() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-seqold"); + using var _ = drv; + + drv.NoteAlarmMessageSequence(h, 20); + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + drv.NoteAlarmMessageSequence(h, 18); // late duplicate of an old message + drv.NoteAlarmMessageSequence(h, 21); // in order relative to 20 + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBe(["signal:" + Trip1]); + retries.Count.ShouldBe(0); + } + + /// Review r1 #1: a gap OUTSIDE a bracket can hold a live transition (a Raise) — it is a loss: withdraw + /// "known" (the subscription had signalled) and re-refresh, whose clean bracket signals again. + [Fact] + public async Task Sequence_gap_outside_a_bracket_withdraws_known_and_re_refreshes() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-seqgap-live"); + using var _ = drv; + SignalClean(drv, h); + drv.NoteAlarmMessageSequence(h, 1); + drv.NoteAlarmMessageSequence(h, 2); + trace.ShouldBe(["signal:" + Trip1], "contiguous live messages are no loss"); + + drv.NoteAlarmMessageSequence(h, 4); // message 3 (a live Raise) lost + trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1]); + await retries.WaitForAsync(1); + + SignalClean(drv, h); + trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1, "signal:" + Trip1]); + } + + /// Review r1 #2: an overflow AFTER the conditions were declared known withdraws "known" — once, until a + /// clean bracket re-signals — and the episode gets its own retry budget. + [Fact] + public async Task Loss_after_the_signal_withdraws_known_once_until_a_clean_bracket() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-withdraw"); + using var _ = drv; + + // Episode 1 spends its whole budget, then ends clean. + for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries; i++) + { + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await retries.WaitForAsync(i + 1); + } + SignalClean(drv, h); + trace.ShouldBe(["signal:" + Trip1], "no withdrawal before anything was known"); + + // Episode 2: a live overflow withdraws, a second loss does not withdraw again, and retries are available. + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + Route(drv, h, ObjectTypeIds.RefreshRequiredEventType); + trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1]); + await retries.WaitForAsync(OpcUaClientDriver.MaxAlarmRefreshRetries + 1); + + SignalClean(drv, h); + trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1, "signal:" + Trip1]); + } + + /// A RefreshRequired after the signal withdraws "known" too. + [Fact] + public void RefreshRequired_after_the_signal_withdraws_known() + { + var (drv, trace, h, _) = NewDriver("opcua-926-required-withdraw"); + using var __ = drv; + SignalClean(drv, h); + Route(drv, h, ObjectTypeIds.RefreshRequiredEventType); + trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1]); + } + + /// Review r1 #3: a RefreshStart while a bracket is still open (its RefreshEnd never arrived) must not erase the + /// open bracket's loss; the overlapping start is itself a loss. + [Fact] + public async Task An_overlapping_RefreshStart_does_not_erase_the_loss() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-nested"); + using var _ = drv; + + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await retries.WaitForAsync(1); + Route(drv, h, ObjectTypeIds.RefreshStartEventType); // the first RefreshEnd never arrived + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBeEmpty("an End only signals when no overlapping / lossy bracket remains"); + + // Positive control: a bracket that opens on a closed one, lossless, signals. + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBe(["signal:" + Trip1]); + } + + /// Review r1 #4: a failed ConditionRefresh call (no RefreshEnd will come) is retried, bounded. + [Fact] + public async Task A_failed_ConditionRefresh_is_retried_bounded() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-refresh-failed"); + using var _ = drv; + + for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries + 2; i++) + { + drv.ReportRefreshFailedForTest(h); + await retries.WaitForAsync(Math.Min(i + 1, OpcUaClientDriver.MaxAlarmRefreshRetries)); + } + await Task.Delay(300, TestContext.Current.CancellationToken); + retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries); + trace.ShouldBeEmpty(); + } + + /// Review r1 #5: a retry scheduled WHILE the previous retry's refresh call runs keeps its pending flag (the + /// earlier retry's completion must not clear it), so a further loss before it starts is coalesced into it. + [Fact] + public async Task A_retry_scheduled_during_a_refresh_call_keeps_coalescing() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-generation"); + using var _ = drv; + var first = true; + drv.AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(300); + drv.AlarmRefreshRetryInvokerForTest = (_, _) => + { + retries.Hit(); + if (first) + { + first = false; + // A loss inside the first retry's call schedules the second retry. + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + } + return Task.CompletedTask; + }; + + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await retries.WaitForAsync(1); + await Task.Delay(50, TestContext.Current.CancellationToken); // the first retry's finally has run + // Still pending ⇒ coalesced, not a third retry. (Before the generation token the first retry's finally cleared + // the second's pending flag, so this scheduled one more.) A failed refresh call schedules without the + // per-bracket request flag, so it exercises the pending flag alone. + drv.ReportRefreshFailedForTest(h); + await retries.WaitForAsync(2); + await Task.Delay(1500, TestContext.Current.CancellationToken); + retries.Count.ShouldBe(2); + trace.ShouldBeEmpty(); + } + + /// A spent budget is not a permanent give-up: after the cool-down a further loss gets a new budget. + [Fact] + public async Task A_spent_budget_renews_after_the_cooldown() + { + var (drv, _, h, retries) = NewDriver("opcua-926-cooldown"); + using var __ = drv; + drv.AlarmRefreshRetryCooldown = TimeSpan.FromSeconds(1); + + for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries; i++) + { + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await retries.WaitForAsync(i + 1); + } + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await Task.Delay(200, TestContext.Current.CancellationToken); + retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries, "inside the cool-down: no more"); + + await Task.Delay(1500, TestContext.Current.CancellationToken); + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await retries.WaitForAsync(OpcUaClientDriver.MaxAlarmRefreshRetries + 1); + } + + private static void SignalClean(OpcUaClientDriver drv, IAlarmSubscriptionHandle h) + { + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + } + /// The overflow notice is never an alarm, even pass-through (no authored refs). [Fact] public void Overflow_notice_is_never_projected() diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs index bfd05f067..86bed3f56 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs @@ -115,6 +115,66 @@ public sealed class NativeAlarmInitialStateSignalTests : NativeAlarmSignalTestBa AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300)); } + /// + /// #926: a driver that signalled and then lost events WITHDRAWS: the host sends Known: false 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. + /// + [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(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(); + 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().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(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct); + AwaitCondition(() => !rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct); + } + + /// #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. + [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)); + } + + /// #926: the payload is either unsignalable or a withdrawal. + [Fact] + public void Unsignalable_and_withdrawn_are_exclusive() => + Should.Throw(() => new AlarmInitialStateEventArgs([A], unsignalable: true, withdrawn: true)); + // ---------------------------------------------------------------- review S2 / re-arm F5 / nits /// diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs index eeb65ca06..b125b4f8f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs @@ -290,10 +290,10 @@ public sealed class FakeSignallingAlarmDriver(string driverInstanceId, string dr /// The conditions it covers. /// Report InitialStateUnsignalable instead. /// Whether it was raised. - public bool Signal(IReadOnlyList conditionIds, bool unsignalable = false) + public bool Signal(IReadOnlyList 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; }