diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md
index 24094d6b7..c20978143 100644
--- a/.claude/rules/drivers.md
+++ b/.claude/rules/drivers.md
@@ -294,6 +294,15 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
AFTER configured ones; more than one discovered server without `discoveryServerUri` fails the connect. Session
events are the OTel counter `otopcua.driver.opcuaclient.events`. `HistoryAggregateType` carries the full Part 13
set; an aggregate the gateway can't serve is `BadAggregateNotSupported` per node.
+- **OpcUaClient RefreshEnd = A1 known-state signal, lossless brackets only (#926):** no RefreshStart, an
+ `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 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 0078a261d..faff40845 100644
--- a/docs/DataConnections.md
+++ b/docs/DataConnections.md
@@ -483,8 +483,14 @@ refresh, EventIds) is documented in [Alarm tracking § Imported conditions](Alar
is raised on the hub.
- `DataConnections:ConditionKnownSettle:OpcUaClient` (default 60 s) is the only backstop timer. It exists for upstreams
without ConditionRefresh.
- - Open gaps: #924 (L4 latency for Galaxy, Heidenhain and real Logix ALMD), #925 (Galaxy deploy-added conditions stay
- unknown) and #926 (an OpcUaClient RefreshEnd can signal known over lost events).
+ - Open gaps: #924 (L4 latency for Galaxy, Heidenhain and real Logix ALMD) and #925 (Galaxy deploy-added conditions stay
+ 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 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 27fe1c400..9441a47c8 100644
--- a/docs/drivers/OpcUaClient.md
+++ b/docs/drivers/OpcUaClient.md
@@ -449,8 +449,33 @@ initialise (the AdminUI form drops them on the next save). Pinned by
> `Unspecified` the host wrote as "Activated", and a retained-Active host condition stayed Active). So the host writes no
> duplicate row when its condition already shows that state (see `docs/AlarmTracking.md`). Condition **branch** events (non-null `BranchId`) are ignored.
> **`ConditionRefresh`** is called after the event item is created, after a keep-alive outage the session survived, and on a
-> `RefreshRequired` event, so a condition already active upstream is reported at subscribe; `RefreshStart`/`RefreshEnd`
-> markers are dropped. A server without it (`BadNotSupported`/`BadMethodInvalid`/…) is logged once and tolerated.
+> `RefreshRequired` event, so a condition already active upstream is reported at subscribe. The `RefreshStart`/`RefreshEnd`
+> markers are never projected as alarms. A server without ConditionRefresh (`BadNotSupported`/`BadMethodInvalid`/…) is logged once and tolerated.
+>
+> **A RefreshEnd signals "initial alarm state delivered" only for a lossless bracket (#926).** That signal is grpc-data
+> A1's known-state signal. The driver tracks RefreshStart…RefreshEnd per alarm subscription, and the RefreshEnd does
+> not signal when any of these happened:
+>
+> - no RefreshStart was seen;
+> - the server sent an `EventQueueOverflowEventType`. That notice comes from the Server object, so it is matched before
+> the source filter, and it is never projected as an alarm;
+> - a `RefreshRequired` arrived;
+> - 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 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
> forgotten when the subscribed set changes (the host rebuilt, recreating the nodes inactive). Index keys are server-stable (`nsu=`), so a namespace reorder across a re-initialise keeps
> matching. docker-dev seeds an opc-plc driver (`MAIN-opcua`); the alarm tag 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 b975e8c44..b456a1343 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
@@ -88,7 +88,7 @@ found while verifying M1 (row M1).
| Galaxy one-shot signal per feed instance | Accepted (verified `GatewayGalaxyAlarmFeed.cs:69,140-152,168`) | §5.1: signal raised on **every** sentinel (not the one-shot task), and drivers re-signal each complete cycle, so conditions become known again after a reopen or a deploy that adds them; A1 test (vii) |
| **Fifth pass (revision 7)** | | |
| G1 driver-wide signal scope | Accepted (verified `FocasAlarmProjection.cs:253-276`, `AbCipAlarmProjection.cs:211`, `HeidenhainAlarmProjection.cs:214`) | §5.1: `AlarmInitialStateEventArgs.ConditionIds`; `MarkConditionsKnown` takes a condition-id set; per-host / per-node hooks in the driver table; MTConnect excludes `Unavailable`; A1 test (viii) |
-| G2 RefreshEnd ordering across publish responses | Accepted; **settled by decompiling** `Opc.Ua.Client` 2.0.1: not ordered by default (`SequentialPublishing` false; parallel workers) | §5.1: `SequentialPublishing = true` on the alarm subscription (`OpcUaClientDriver.cs:2445`); gap ⇒ no signal; A1 test (ix) |
+| G2 RefreshEnd ordering across publish responses | Accepted; **settled by decompiling** `Opc.Ua.Client` 2.0.1: not ordered by default (`SequentialPublishing` false; parallel workers) | §5.1: `SequentialPublishing = true` on the alarm subscription (`OpcUaClientDriver.cs:2445`); A1 test (ix). Loss inside the refresh bracket (EventQueueOverflow, RefreshRequired, a publish-sequence gap the SDK skipped, or a missing RefreshStart) ⇒ that RefreshEnd does not signal and ConditionRefresh is re-run, bounded (#926) |
| G3 deferred signal outliving a dropped alarm | Accepted (verified `OpcUaPublishActor.cs:1048-1051`, `:1106-1112`) | §5.1 loss rule: a drop or skip discards that source's deferred `MarkConditionsKnown`; A1 test (x) |
| G4 re-bind rarely holds across failover | Accepted | §5.6 step 3: client-visible behaviour stated (`BadEventIdUnknown` → `RefreshRequired` → ConditionRefresh → Good); A03 corrected |
| G5 suppression gate | Accepted (verified `DriverInstanceActor.cs:184-188,1144-1148,2536-2541`) | §5.1: signal attached/gated with `OnAlarmEvent`; A1 test (xi) |
@@ -492,11 +492,39 @@ conditions re-report (`NM:5639-5651`). Some state changes never produce an event
- So the RefreshEnd of a multi-response replay could be processed before an earlier response. A1 therefore sets
**`SequentialPublishing = true` on the alarm subscription** (`OpcUaClientDriver.cs:2445`). The data subscriptions
are unchanged.
- - **As implemented (A1):** there is no gap-based suppression. The SDK 2.0.1 surface the driver sees (the per-item
- `Notification` callback) exposes no per-message gap or republish failure. With `SequentialPublishing` the worker
- waits for a missing sequence number (republish) before it delivers later ones, so an ordinary gap still orders the
- RefreshEnd last. **Residual:** a gap the SDK gives up on could let a RefreshEnd signal over a lost refreshed event.
- The mitigation for notification-queue overflow and abandoned gaps is tracked in #926.
+ - With `SequentialPublishing` the worker waits for a missing sequence number (republish) before it delivers later
+ ones, so an ordinary (recovered) gap still orders the RefreshEnd last.
+ - **As implemented (#926): a RefreshEnd signals only for a lossless RefreshStart…RefreshEnd bracket.** The driver
+ tracks the bracket per alarm subscription. It does **not** signal when:
+ - no RefreshStart opened the bracket (the head of the replay was discarded);
+ - an `EventQueueOverflowEventType` arrived since the RefreshStart. That notice comes from the Server object, so it
+ is matched by EventType **before** the source filter;
+ - a `RefreshRequired` arrived since the RefreshStart;
+ - a **publish-sequence gap** was seen inside the bracket. That is a delivered message whose sequence number is
+ neither the previous one nor its successor; the SDK sets `EventFieldList.Message`, and the alarm subscription has
+ 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 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
+ is refused. Before the fix it signalled. Evidence: `docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md`.
- **OpcUaClient upstream without ConditionRefresh** (`:2887-2893`, "conditions already active are reported only on their
next transition"). This is the one case with no signal at all. The driver reports `InitialStateUnsignalable` for that
subscription, and the per-driver-type **backstop timer** (`DataConnections:ConditionKnownSettle:OpcUaClient`, default
@@ -517,8 +545,13 @@ conditions re-report (`NM:5639-5651`). Some state changes never produce an event
- `DriverHostActor` turns it into `MarkConditionsKnown(driverInstanceId, conditionIds)` and sends it to `OpcUaPublishActor` **after**
the `AlarmStateUpdate`s it already forwarded (Akka preserves per-sender-pair order).
- `OpcUaPublishActor` treats it as an alarm message. While a plan apply is in progress (`PlanPipelineBusy`) it is
- deferred beside the `AlarmStateUpdate`s (`HandleAlarmUpdate`/`DeferAlarm`) and replayed **after** the deferred
- alarms.
+ deferred beside the `AlarmStateUpdate`s (`HandleAlarmUpdate`/`DeferAlarm`). **As implemented after #926 review
+ r2:** the deferred alarm states, alarm qualities and marks are replayed in **arrival order** (one list, per-entry
+ sequence). Marks are held per condition, so a later mark of the same condition replaces an earlier one, and
+ withdrawals are bounded by the number of conditions.
+ - A "known" mark still lands after the projections it summarises, because it arrived after them.
+ - A withdrawal followed by a re-establishing transition now ends known, as the live path leaves it. Replaying all
+ marks last had ended it unknown.
- **Loss rule (G3).** The deferral is a bounded keyed store, not a queue. An `AlarmStateUpdate` that does not fit is
dropped (`DeferAlarm` → `WarnDeferredOverflow`, `OpcUaPublishActor.cs:1048-1051`), and replay skips alarms outside the
applied scope (`:1106-1112`).
diff --git a/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md b/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md
new file mode 100644
index 000000000..27073486b
--- /dev/null
+++ b/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md
@@ -0,0 +1,177 @@
+# #926 — OpcUaClient RefreshEnd signals only for a lossless refresh bracket
+
+2026-11-28. Follow-up to A1 (plan §5.1, OpcUaClient row, G2).
+
+## Defect
+
+A1 takes the alarm subscription's `RefreshEndEventType` as `InitialAlarmStateDelivered`. That signal declares the
+conditions it covers state-known. The driver raised it on every RefreshEnd, including one that closed a replay that had
+lost events. A condition that was active upstream could then be declared known-inactive.
+
+## Ways a replay can lose events
+
+- **Event-queue overflow.** The upstream inserts an `EventQueueOverflowEventType` notice. Its SourceNode is the Server
+ object, so the driver's source filter dropped it, and in pass-through mode it would have been projected as an alarm.
+ Where the notice lands depends on `DiscardOldest`:
+ - With `DiscardOldest` false (production), the newest events, often the RefreshEnd itself, are dropped.
+ - With `DiscardOldest` true, or on a server that refreshes asynchronously, the RefreshStart and the head of the
+ replay are dropped, but the RefreshEnd still arrives.
+- **RefreshRequired** arriving during the replay.
+- **A publish gap the SDK gives up on.** With `SequentialPublishing` the SDK holds later messages while it republishes
+ the missing one. If that republish fails (`BadMessageNotAvailable`), it skips the gap and delivers the next message.
+ - Decompiling SDK 2.0.1 (`Subscription` message worker) shows that `PublishStateChangedMask.Republish` is raised only
+ inside `if (messagesToDeliver != null)`.
+ - So when the gap is holding every later message back, which is exactly this case, no callback fires. Verified with a
+ real `Subscription`: the order was `live:1, start:2, end:4` and no Republish state was raised.
+
+## Fix (`OpcUaClientDriver`)
+
+**Per-subscription bracket state.** Each `RemoteAlarmSubscription` has an `AlarmRefreshBracket`, guarded by
+`_alarmStateLock`.
+
+**Bracket events are matched by EventType before projection** (`RouteBracketEvent`):
+- RefreshStart opens the bracket.
+- EventQueueOverflow records a loss and requests a re-refresh.
+- RefreshRequired records a loss; its existing sweep is the re-refresh.
+- RefreshEnd signals only if the bracket was opened and saw no loss. Otherwise it logs a Warning, increments
+ `alarm_refresh_lossy`, and requests a re-refresh unless one was already requested.
+
+**Publish-sequence check.** `RouteAlarmEventFieldList` reads `NoteAlarmMessageSequence(efl.Message.SequenceNumber)`
+before it routes the event. The alarm subscription has one monitored item, so every message that carries data
+consumes one sequence number. Inside a bracket, a number that is neither the same as the last nor its successor
+(wrap-aware) is a loss.
+
+**Bounded re-refresh.** `ScheduleAlarmRefreshRetryLocked` → `RetryAlarmRefreshAsync`:
+- At most 3 re-refreshes per episode, backing off 2 s, 4 s, then 8 s. A clean RefreshEnd resets the budget.
+- Requests are coalesced while one is pending.
+- The retry is cancelled with the session's work token, and skipped if the subscription is no longer the one
+ registered.
+- When the budget is spent, one Warning is logged (it includes the revised queue size) and nothing signals. The
+ conditions stay unknown (`Uncertain`) and F5's `ConditionKnownSignalTimeout` diagnostic reports them.
+ `Unsignalable` is deliberately not used: it starts the backstop that marks the conditions known.
+
+**Queue size.** The alarm event item's queue is now 10,000 (it was 1,000), so overflow is rarer. The detection above is
+the actual fix.
+
+**New counters.** `otopcua.driver.opcuaclient.events{event=alarm_event_queue_overflow|alarm_refresh_lossy}`.
+
+## Tests
+
+### Unit: `OpcUaClientRefreshBracketLossTests`
+
+11 tests:
+
+- an overflow inside the bracket, a RefreshEnd with no RefreshStart, and a RefreshRequired inside the bracket each
+ suppress the signal, and each has a positive control;
+- an overflow outside a bracket requests a re-refresh;
+- the retry bound, and the budget reset after a clean bracket;
+- a re-refresh whose own RefreshStart is lost can request the next one;
+- sequence gap, repeat, wrap and gap-outside-bracket;
+- the overflow notice is never projected;
+- queue-size pin;
+- the real-SDK abandoned gap, plus a lossless real-SDK positive control.
+
+`OpcUaClientInitialAlarmStateSignalTests`: the two tests that routed a RefreshEnd with no RefreshStart now route the
+RefreshStart first. A real server always sends one, and the live latency test below passes with the new requirement.
+
+### Red
+
+These mutations were run as red checks:
+
+- **RefreshEnd always signals:** 6 of 10 bracket tests fail.
+- **Sequence check removed:** the real-SDK gap test fails.
+- **Live:** the same always-signal mutation gives `signals=3` over lossy replays (run `discardOldest=True`, below).
+
+### Live: `OpcUaClientRefreshOverflowLiveTests`
+
+Run against the shared `opc-plc --alm` at `opc.tcp://10.100.0.35:50000`, read-only, using test seams for the item's queue
+size and `DiscardOldest`. No local docker, so the rig lock was not needed.
+
+| Case | Overflow notices seen | Lossy RefreshEnds refused | Signals |
+|---|---|---|---|
+| `DiscardOldest=false`, queue 1 | 25 | 0 (the RefreshEnd was dropped by the server) | 0 |
+| `DiscardOldest=true`, queue 2 | 11–20 across runs | 1–3 across runs (≤ 1 + 3, bounded) | 0 |
+| Production queue (control) | 0 | 0 | signalled |
+| Mutation (always signal), `DiscardOldest=true` | 15 | — | **3** |
+
+The lossy-RefreshEnd count varies because opc-plc keeps firing live alarms, which can push a RefreshEnd out of a
+2-entry queue.
+
+Two observations from the runs:
+
+- `DiscardOldest=false` with queue 2 produced no overflow notice and no RefreshEnd on this opc-plc. It still never
+ signalled, so the outcome was safe.
+- A `MeterListener` filtered by `ReferenceEquals` on `OtOpcUaTelemetry.OpcUaClientEvents` never enabled the counter
+ when that class ran alone. The instrument is published inside the type's static initializer, where the field still
+ reads null. The test now reads the field before calling `Start()`.
+
+`OpcUaClientAlarmSignalLatencyTests` (L4) still passes 20 out of 20 samples, which means opc-plc sends RefreshStart.
+
+## Residuals
+
+- **False positives.** A StatusChange-only message on the alarm subscription consumes a sequence number and reads as a
+ 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
+ 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.~~ 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.
+
+## Review round 2 (2026-11-28)
+
+| # | Finding | Outcome |
+|---|---|---|
+| 1 | `OpcUaPublishActor` replayed every deferred alarm first and every mark last. So a withdrawal followed by a transition, both deferred by a plan, ended **unknown** although the transition had re-established the condition, and the host no longer counted it in F5. | **Fixed.** Deferred alarm states, alarm qualities and marks replay as **one list in arrival order**. Each entry carries a sequence number, and consecutive marks of the same (source, realm, known) are batched into one sink call. The G3 out-of-scope check is a pre-pass, so a source's known marks are still discarded wherever they sit in the list. Pinned by `Deferred_alarms_and_marks_replay_in_arrival_order`, which also checks the mirror order (transition then withdrawal ends unknown). That test is red against the previous actor. |
+| 5 | The deferred-withdrawal list was "bounded by connectivity edges", which stopped being true once #926 made withdrawals routine. | **Fixed.** Deferred marks are now held **per (realm, condition)**, and the latest mark wins. Withdrawals are never dropped, and are bounded by the number of conditions. Known marks for a new condition beyond `Capacity` still overflow, as before. `A_withdrawal_beyond_the_deferral_capacity_is_never_dropped` now expects one coalesced replay instead of three (it is red against the old list). |
+| 2 | The driver looked up the subscription outside `_alarmStateLock`, so a stale record could signal or withdraw. | **Fixed.** `IsRegisteredLocked` is re-checked under the lock before a RefreshEnd signals and before a withdrawal, and both removals (`UnsubscribeAlarmsAsync`, the shutdown loop) now take the lock. There is no deterministic unit test for this race; the lock is the guarantee. |
+| 3 | A withdrawal after F5 had already raised its diagnostic did not update the diagnostic's count. | **Fixed.** The host calls `Hub.UpdateUnsignalled` when the pending set grows under a raised diagnostic. Covered by `A_withdrawal_after_the_diagnostic_updates_its_count`, which is red with the call removed. |
+| 4 | Conditions on unsignalable subscriptions never withdraw. | **Documented** in `IAlarmInitialStateSignal`. Only a source that signalled withdraws; conditions made known by the backstop stay known through a later loss. That is the backstop's own residual. |
+| 6 | The backstop test had no positive control. | **Fixed.** The sibling condition that was not withdrawn is marked known by the same backstop. |
+| — | `AlarmInitialStatePublished` serialization | A comment now says it must stay in-process: a serialized copy that lost `Withdrawn` would default it to false and turn a withdrawal into a known mark. |
+
+**Found, not mine.** `OpcUaPublishActorWarmTests.A_deployed_cluster_mode_that_disagrees_with_the_local_mode_is_logged_and_counted`
+fails when run in isolation. It has the same `MeterListener` and static-initializer trap fixed in the live test above:
+it matches `ReferenceEquals(instrument, OtOpcUaTelemetry.RedundancyModeMismatch)` before that field has been initialized.
+Reported as a follow-up.
+
+**Round 2 gates:**
+
+- Full Release build: 0 warnings.
+- OpcUaClient.Tests: 430/430.
+- OpcUaClient.IntegrationTests: 13/13, live against opc-plc.
+- `GrpcDataV1CompatibilityTests`: 49/49.
+- Runtime.Tests: 2095 of 2100 passed and 3 were skipped.
+ - The 2 failures are pre-existing; neither is caused by #926.
+ - `DriverHostActorApplyingStashTests.ACompletedApply_NeverReportsAWedge` fails every time on base `05f431f5d` too. I
+ confirmed this in a clean worktree at that commit.
+ - `GrpcDataConfiguredDiscoveryWireTests.Bad_null_sdk_notification_cannot_borrow_unproven_sample_evidence(different_timestamp)`
+ fails only under full-suite load. It passes in isolation, both on this branch and on base.
diff --git a/docs/plans/evidence/grpc-data-ext/A1-core.md b/docs/plans/evidence/grpc-data-ext/A1-core.md
index a4b3c7ce6..92ccf20df 100644
--- a/docs/plans/evidence/grpc-data-ext/A1-core.md
+++ b/docs/plans/evidence/grpc-data-ext/A1-core.md
@@ -242,6 +242,9 @@ Heidenhain legs are **blocked**: Galaxy needs the VPN and mxaccessgw, and Heiden
- With `SequentialPublishing` the worker waits for the missing sequence number (republish) before delivering later ones.
- Residual: a gap the SDK gives up on could let a `RefreshEnd` signal over a lost refreshed event. **Resolved in review
round 2:** the plan's G2 text now states what is implemented, and the overflow and gap mitigation is tracked in #926.
+ - **#926 (2026-11-28) closes the residual.** The driver now detects the skipped gap itself, from the delivered message's
+ sequence number. It also detects queue overflow, RefreshRequired and a missing RefreshStart inside the refresh
+ bracket, and re-runs ConditionRefresh, bounded. See `926-refresh-bracket.md`.
- **MTConnect also signals on a mid-stream `/current` re-baseline** (OUT_OF_RANGE / Agent restart), not only on the subscribe
resync and the pump's first act. A re-baseline is a complete re-read, and without the signal a restarted Agent's
conditions would wait for the next reconnect.
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..c7f059d06 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,15 @@ 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. Only a source
+/// that SIGNALLED withdraws: conditions that became known through the
+/// backstop are not withdrawn by a later loss (the OPC UA client has no refresh bracket there, and its loss
+/// detection never re-arms the backstop) — that residual is the backstop's own.
+///
///
public interface IAlarmInitialStateSignal
{
@@ -50,11 +59,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 +81,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/OpcUaClientDiagnostics.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDiagnostics.cs
index 7ac3da945..3059f720c 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDiagnostics.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDiagnostics.cs
@@ -26,6 +26,10 @@ internal sealed class OpcUaClientDiagnostics
public const string KeepAliveRecovered = "keepalive_recovered";
/// A late replayed notification (source time at or below the ref's high-water mark) was dropped inside the post-recovery replay window.
public const string StaleNotificationDropped = "stale_notification_dropped";
+ /// #926: the upstream reported an EventQueueOverflowEventType on an alarm event item (events lost).
+ public const string AlarmEventQueueOverflow = "alarm_event_queue_overflow";
+ /// #926: a RefreshEnd was NOT taken as "initial alarm state delivered" because its replay was lossy.
+ public const string AlarmRefreshLossy = "alarm_refresh_lossy";
private readonly string _driverInstanceId;
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 0c5ba3f50..fe9d23324 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
@@ -1365,7 +1374,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
foreach (var key in _alarmSubscriptions.Keys)
{
- if (!_alarmSubscriptions.TryRemove(key, out var ras)) continue;
+ RemoteAlarmSubscription? ras;
+ // #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it.
+ lock (_alarmStateLock)
+ if (!_alarmSubscriptions.TryRemove(key, out ras)) continue;
try { ras.EventItem.Notification -= ras.Handler; }
catch { /* best-effort */ }
if (sessionAlive) deletes.Add(DeleteSubscriptionBestEffortAsync(ras.Subscription, budget.Token));
@@ -2434,6 +2446,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
private const int AlarmFieldAckedState = 8;
private const int AlarmFieldBranchId = 9;
+ /// #926: the requested queue size of the alarm event item (was 1000). See its use.
+ internal const uint AlarmEventQueueSize = 10_000;
+
+ /// #926 test seam (the live overflow gate shrinks it): the queue size the alarm event item requests.
+ internal uint AlarmEventItemQueueSize { get; set; } = AlarmEventQueueSize;
+
+ /// #926 test seam (the live gate flips it to make a lossy replay KEEP its RefreshEnd): the alarm event
+ /// item's DiscardOldest. Production: false (the newest events are dropped on overflow).
+ internal bool AlarmEventItemDiscardOldest { get; set; }
+
///
public async Task SubscribeAlarmsAsync(
IReadOnlyList sourceNodeIds, CancellationToken cancellationToken)
@@ -2574,8 +2596,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
StartNodeId = ObjectIds.Server,
AttributeId = Attributes.EventNotifier,
MonitoringMode = MonitoringMode.Reporting,
- QueueSize = 1000, // deep queue — a server can fire many alarms in bursts
- DiscardOldest = false,
+ // #926: deep queue — a ConditionRefresh replays EVERY retained upstream condition in one burst, and a
+ // server can fire many alarms at once. An overflow is still detected (EventQueueOverflowEventType ⇒ the
+ // refresh's RefreshEnd does not signal and it is re-run); the depth only makes it rarer. The server
+ // may revise it down (logged with the retry budget's exhaustion).
+ QueueSize = AlarmEventItemQueueSize,
+ DiscardOldest = AlarmEventItemDiscardOldest,
Filter = filter,
})
{
@@ -2623,7 +2649,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
public async Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken)
{
if (handle is not OpcUaAlarmSubscriptionHandle h) return;
- if (!_alarmSubscriptions.TryRemove(h.Id, out var rs)) return;
+ RemoteAlarmSubscription? rs;
+ // #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it.
+ lock (_alarmStateLock)
+ if (!_alarmSubscriptions.TryRemove(h.Id, out rs)) return;
var emptied = NoteSubscriptionDeleted();
await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false);
@@ -2790,6 +2819,21 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// without this it would feed RouteAlarmEvent alongside the real one.
if (!_alarmSubscriptions.ContainsKey(handle.Id)) return;
RecordLivenessEvidence();
+ RouteAlarmEventFieldList(efl, sourceFilter, handle);
+ }
+
+ ///
+ /// Route one delivered event: first #926's publish-sequence check (a gap inside a refresh bracket makes it
+ /// lossy — checked BEFORE the event, so a RefreshEnd in the first message after the gap is already suppressed),
+ /// then .
+ ///
+ /// The delivered event (the SDK sets Message to its notification message).
+ /// The subscription's upstream-key → RawPath index.
+ /// The subscription handle.
+ internal void RouteAlarmEventFieldList(
+ EventFieldList efl, IReadOnlyDictionary sourceFilter, IAlarmSubscriptionHandle handle)
+ {
+ NoteAlarmMessageSequence(handle, efl.Message?.SequenceNumber ?? 0);
RouteAlarmEvent(efl.EventFields.ToList(), sourceFilter, handle);
}
@@ -2826,25 +2870,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
internal void RouteAlarmEvent(
IReadOnlyList fields, IReadOnlyDictionary sourceFilter, IAlarmSubscriptionHandle handle)
{
- if (IsRefreshRequired(fields))
+ if (fields.Count > AlarmFieldEventType && UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId markerType
+ && IsBracketEventType(markerType))
{
- // 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));
- return;
- }
-
- if (IsRefreshEnd(fields))
- {
- // grpc-data A1 (F1): the refresh replay this subscription requested is complete 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.
- lock (_alarmStateLock)
- {
- if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras))
- RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false);
- }
+ RouteBracketEvent(markerType, handle);
return;
}
@@ -2893,6 +2922,346 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// Exact severity last told (null before any event).
private readonly record struct AlarmToldState(bool Active, bool Acked, string? Message, int? Severity);
+ /// #926: the event types that drive the refresh bracket (never alarms): the three ConditionRefresh
+ /// markers and the server's EventQueueOverflowEventType.
+ /// The event's EventType.
+ /// Whether it is a bracket event.
+ private static bool IsBracketEventType(NodeId t) =>
+ t == ObjectTypeIds.RefreshStartEventType || t == ObjectTypeIds.RefreshEndEventType
+ || t == ObjectTypeIds.RefreshRequiredEventType || t == ObjectTypeIds.EventQueueOverflowEventType;
+
+ ///
+ /// #926 — route one bracket event. Matched by EventType BEFORE any source filtering: an
+ /// 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 — 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 (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.
+ private void RouteBracketEvent(NodeId type, IAlarmSubscriptionHandle handle)
+ {
+ RemoteAlarmSubscription? ras = null;
+ if (handle is OpcUaAlarmSubscriptionHandle h) _alarmSubscriptions.TryGetValue(h.Id, out ras);
+
+ if (type == ObjectTypeIds.RefreshRequiredEventType)
+ {
+ if (ras is not null)
+ lock (_alarmStateLock)
+ {
+ // The sweep below re-refreshes this subscription, so no driver retry is requested for it.
+ NoteBracketLoss(ras, "RefreshRequired", requestRetry: false);
+ ras.Bracket.RetryRequestedSinceStart = true;
+ }
+ RequestRefreshRequiredSweep();
+ return;
+ }
+
+ if (ras is null) return; // a released / stray subscription: no bracket, no signal (G5)
+ lock (_alarmStateLock)
+ {
+ 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;
+ }
+ else if (type == ObjectTypeIds.EventQueueOverflowEventType)
+ {
+ _diag.Record(OpcUaClientDiagnostics.AlarmEventQueueOverflow);
+ NoteBracketLoss(ras, "EventQueueOverflow (the upstream discarded events of this subscription)",
+ requestRetry: true);
+ }
+ else if (type == ObjectTypeIds.RefreshEndEventType)
+ {
+ var opened = b.Open;
+ b.Open = false;
+ if (opened && b.LossSinceStart is null)
+ {
+ // #926 review r2: re-checked UNDER the lock (the lookup above ran outside it, and an unsubscribe
+ // removes the record under this lock): a released subscription never signals.
+ if (!IsRegisteredLocked(ras)) return;
+ // 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. 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;
+ }
+
+ var reason = b.LossSinceStart ?? "RefreshEnd without its RefreshStart (the bracket start was lost)";
+ _diag.Record(OpcUaClientDiagnostics.AlarmRefreshLossy);
+ _logger.LogWarning(
+ "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 = ScheduleAlarmRefreshRetryLocked(ras, reason);
+ }
+ }
+ }
+
+ ///
+ /// #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.
+ private void NoteBracketLoss(RemoteAlarmSubscription ras, string reason, bool requestRetry)
+ {
+ var b = ras.Bracket;
+ b.LossSinceStart ??= reason;
+ WithdrawKnownLocked(ras, reason);
+ if (!requestRetry || b.RetryRequestedSinceStart) return;
+ // 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;
+ // #926 review r2: a stale record (unsubscribed after the caller's lookup, still Signalled) must not withdraw
+ // refs that may now belong to a NEW subscription. Checked under the lock the unsubscribe removes it under.
+ if (!IsRegisteredLocked(ras)) return;
+ _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);
+ }
+
+ /// #926 review r2: is still the registered subscription for its handle. Caller holds
+ /// _alarmStateLock; removals take it too, so the answer holds for the rest of the critical section.
+ /// The alarm subscription record.
+ /// Whether it is the live registration.
+ private bool IsRegisteredLocked(RemoteAlarmSubscription ras) =>
+ _alarmSubscriptions.TryGetValue(ras.Handle.Id, out var current) && ReferenceEquals(current, ras);
+
+ ///
+ /// #926: the publish-sequence check of alarm subscription . The alarm subscription holds
+ /// exactly one (event) monitored item, so every data-bearing notification message it receives carries its
+ /// events and consumes one sequence number (keep-alives consume none). With SequentialPublishing the SDK
+ /// delivers messages in order and waits for a missing one (republish); if the republish fails it SKIPS the gap
+ /// 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 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).
+ internal void NoteAlarmMessageSequence(IAlarmSubscriptionHandle handle, uint sequenceNumber)
+ {
+ if (sequenceNumber == 0) return;
+ if (handle is not OpcUaAlarmSubscriptionHandle h || !_alarmSubscriptions.TryGetValue(h.Id, out var ras)) return;
+ lock (_alarmStateLock)
+ {
+ 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;
+ var next = last == uint.MaxValue ? 1u : last + 1;
+ if (sequenceNumber == next) return;
+ NoteBracketLoss(ras,
+ $"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 (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. 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; }
+
+ /// #926: schedule one bounded re-refresh of (coalesced while one is pending).
+ /// Caller holds _alarmStateLock.
+ /// The alarm subscription.
+ /// Why (logged).
+ /// 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 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)
+ {
+ b.ExhaustedLogged = true;
+ _logger.LogWarning(
+ "OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId} lost refresh events " +
+ "{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 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, 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, long generation, TimeSpan delay, CancellationToken cancellationToken)
+ {
+ var gateHeld = false;
+ try
+ {
+ if (delay > TimeSpan.Zero) await Task.Delay(delay, Clock, cancellationToken).ConfigureAwait(false);
+ await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ gateHeld = true;
+ if (!_alarmSubscriptions.TryGetValue(ras.Handle.Id, out var current) || !ReferenceEquals(current, ras)) return;
+ // From here a further loss may request the next retry: it belongs to THIS refresh's replay. That matters
+ // 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.
+ 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)
+ await TryConditionRefreshAsync(ras.Subscription, cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) { /* shutdown / re-init: the subscription is being released */ }
+ catch (ObjectDisposedException) { /* driver disposed */ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "OpcUaClientDriver '{DriverInstanceId}': alarm re-refresh of {SubscriptionId} failed; " +
+ "its conditions stay unknown until a later lossless ConditionRefresh.",
+ _driverInstanceId, ras.Handle.DiagnosticId);
+ }
+ finally
+ {
+ // 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) { }
+ }
+ }
+ }
+
+ /// #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.
@@ -2907,12 +3276,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)
{
@@ -2967,6 +3336,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)
{
@@ -2992,9 +3363,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
{
@@ -3146,6 +3519,9 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
if (fields.Count <= AlarmFieldConditionId) return null;
// ConditionRefresh brackets its re-delivery with RefreshStart/RefreshEnd — markers, never alarms.
if (IsRefreshMarker(UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]))) return null;
+ // #926: the server's queue-overflow notice is not an alarm either (pass-through would otherwise project it).
+ if (UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId et && et == ObjectTypeIds.EventQueueOverflowEventType)
+ return null;
// A condition BRANCH event reports a previous state with its own EventId: projecting it would flip the
// trunk's state, remembering it would make Acknowledge ack the branch.
if (fields.Count > AlarmFieldBranchId && UpstreamValueMapping.ToClr(fields[AlarmFieldBranchId]) is NodeId branch && !branch.IsNull)
@@ -3238,7 +3614,54 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
OpcUaAlarmSubscriptionHandle Handle,
MonitoredItem EventItem,
MonitoredItemNotificationEventHandler Handler,
- IReadOnlyList AlarmRefs);
+ IReadOnlyList AlarmRefs)
+ {
+ /// #926: this subscription's ConditionRefresh bracket + bounded re-refresh state. Mutated only
+ /// under _alarmStateLock.
+ public AlarmRefreshBracket Bracket { get; } = new();
+ }
+
+ ///
+ /// #926 — the RefreshStart…RefreshEnd bracket of one alarm subscription. A RefreshEnd declares the conditions it
+ /// covers state-known (grpc-data A1), so it may only signal when the replay it closes is provably complete: its
+ /// RefreshStart was seen and no loss (EventQueueOverflow, RefreshRequired, a publish-sequence gap) was
+ /// observed since. Every field is read and written under _alarmStateLock.
+ ///
+ internal sealed class AlarmRefreshBracket
+ {
+ /// A RefreshStart was routed and its RefreshEnd not yet.
+ public bool Open;
+
+ /// The first loss observed since the last RefreshStart (null = none). A RefreshEnd with a loss
+ /// does not signal.
+ public string? LossSinceStart;
+
+ /// A re-refresh was already requested for the loss since the last RefreshStart or the last re-refresh's
+ /// start (so the lossy RefreshEnd that follows does not request a second one).
+ public bool RetryRequestedSinceStart;
+
+ /// A driver re-refresh is scheduled and has not started its ConditionRefresh call yet.
+ public bool RetryPending;
+
+ /// Driver re-refreshes spent since the last clean (signalled) RefreshEnd.
+ public int Retries;
+
+ /// The retry budget is spent and that was logged (once per episode).
+ public bool ExhaustedLogged;
+
+ /// 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..e5508bc3e 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,31 @@ 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. A diagnostic already raised for
+ // that window must count them too (#926 review r2).
+ if (t.Pending.Count != before)
+ {
+ if (t.PendingSinceUtc is null) ArmSignalTimeout(msg.DriverInstanceId, t);
+ else if (t.DiagnosticRaised) _conditionSignals.Hub?.UpdateUnsignalled(msg.DriverInstanceId, t.Pending.Count);
+ }
+ }
+ _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 +352,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 +369,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/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs
index a97c84030..c444541bf 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs
@@ -238,7 +238,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// , so it reaches after every alarm event the
/// driver raised before it.
/// A1 review S2: is the connection (Connected entry) the driver raised
- /// it under, matching of that Good edge.
+ /// it under, matching of that Good edge. #926: keep this message
+ /// IN-PROCESS (child → parent only) — it carries by reference, and a
+ /// serialized copy that dropped Withdrawn would default it to false and turn a withdrawal into a "known" mark.
public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args,
long? ConnectionEpoch = null);
private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args, long Epoch);
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs
index dc173ba12..850d97126 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs
@@ -1165,47 +1165,89 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying {Count} deferred status writes threw", statuses.Count); }
}
+ // G3 pre-pass: a deferred projection outside the applied scope is skipped — its source's KNOWN marks are discarded
+ // wherever they sit in the arrival order (the conservative reading of "never known over a projection that did
+ // not land").
+ foreach (var (alarm, _) in _deferred.Alarms)
+ if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) _deferred.NoteAlarmLoss(alarm.Source);
+
+ // #926 review r2: alarm states, alarm qualities and condition-known marks replay as ONE list in ARRIVAL order.
+ // Marks used to replay after every alarm, which was right for a "known" mark (it summarises the projections
+ // before it) but wrong for a withdrawal followed by a live transition: replayed transition-then-withdrawal,
+ // the condition ended unknown although the transition had re-established it — and the host, which saw the
+ // transition last, no longer counted it in F5. Arrival order is exactly what the live path applies.
+ var items = new List<(long Seq, int Kind, int Index)>();
+ var alarmList = _deferred.Alarms.ToList();
+ var qualityList = _deferred.AlarmQualities.ToList();
+ var markList = _deferred.Marks.ToList();
+ for (var i = 0; i < alarmList.Count; i++) items.Add((alarmList[i].Seq, 0, i));
+ for (var i = 0; i < qualityList.Count; i++) items.Add((qualityList[i].Seq, 1, i));
+ for (var i = 0; i < markList.Count; i++) items.Add((markList[i].Seq, 2, i));
+ items.Sort((x, y) => x.Seq.CompareTo(y.Seq));
+
var alarms = 0;
- foreach (var alarm in _deferred.Alarms)
- {
- if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId)))
- {
- _deferred.NoteAlarmLoss(alarm.Source); // G3: a skipped projection — the source's marks go too
- continue;
- }
-
- alarms++;
- try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); }
- catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); }
- }
-
var qualities = 0;
- foreach (var quality in _deferred.AlarmQualities)
- {
- if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue;
- qualities++;
- try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); }
- catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); }
- }
-
- // A1 F2/G3: the deferred "known" marks replay LAST, after every deferred alarm — and only for a source none of
- // whose deferred projections was dropped or skipped. A discarded mark leaves its conditions unknown (Uncertain)
- // until the source's next signal.
var marks = 0;
var discarded = 0;
- foreach (var (mark, sender) in _deferred.Marks)
+ var discardedBySender = new Dictionary<(string Source, AddressSpaceRealm Realm), (IActorRef? Sender, List Ids)>();
+ // Consecutive marks of one (source, realm, known) are applied as one sink call.
+ string? runSource = null;
+ AddressSpaceRealm runRealm = default;
+ var runKnown = false;
+ var runIds = new List();
+ void FlushRun()
{
- // A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe.
- if (mark.Known && _deferred.SourceLost(mark.Source))
+ if (runIds.Count == 0) return;
+ marks++;
+ ApplyMark(new MarkConditionsKnown(runSource!, runIds.ToList(), runRealm, runKnown));
+ runIds.Clear();
+ }
+
+ foreach (var (_, kind, index) in items)
+ {
+ if (kind == 2)
{
- discarded++;
- TellDiscarded(sender, new ConditionMarksDiscarded(mark.Source, mark.ConditionIds, mark.Realm));
+ var m = markList[index];
+ // A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe.
+ if (m.Known && _deferred.SourceLost(m.Source))
+ {
+ discarded++;
+ if (!discardedBySender.TryGetValue((m.Source, m.Realm), out var d))
+ discardedBySender[(m.Source, m.Realm)] = d = (m.Sender, new List());
+ d.Ids.Add(m.ConditionId);
+ continue;
+ }
+
+ if (runIds.Count > 0 && (runSource != m.Source || runRealm != m.Realm || runKnown != m.Known)) FlushRun();
+ runSource = m.Source;
+ runRealm = m.Realm;
+ runKnown = m.Known;
+ runIds.Add(m.ConditionId);
continue;
}
- marks++;
- ApplyMark(mark);
+ FlushRun();
+ if (kind == 0)
+ {
+ var alarm = alarmList[index].Msg;
+ if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) continue; // counted in the pre-pass
+ alarms++;
+ try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); }
+ catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); }
+ }
+ else
+ {
+ var quality = qualityList[index].Msg;
+ if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue;
+ qualities++;
+ try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); }
+ catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); }
+ }
}
+ FlushRun();
+
+ foreach (var ((source, realm), (sender, ids)) in discardedBySender)
+ TellDiscarded(sender, new ConditionMarksDiscarded(source, ids, realm));
// N1: a KNOWN mark that did not fit the deferral was dropped (staying unknown is safe) — its sender hears it.
foreach (var (source, sender) in _deferred.OverflowedMarkSources)
@@ -1233,6 +1275,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// the two live writes leave on the node). Bounded by distinct keys across all kinds;
/// beyond it a NEW key is not held (an existing key still updates), counted in .
///
+ /// One deferred condition-known mark (#926 review r2: per condition, with its arrival sequence).
+ private sealed record DeferredMark(
+ string Source, string ConditionId, AddressSpaceRealm Realm, bool Known, IActorRef? Sender, long Seq);
+
private sealed class DeferredWrites(int capacity)
{
private struct VariableEntry
@@ -1246,11 +1292,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
}
private readonly Dictionary<(AddressSpaceRealm, string), VariableEntry> _variables = new();
- private readonly Dictionary<(AddressSpaceRealm, string), AlarmStateUpdate> _alarms = new();
- private readonly Dictionary<(AddressSpaceRealm, string), AlarmQualityUpdate> _qualities = new();
- // A1: condition-known marks in arrival order (bounded by Capacity — a dropped mark only keeps conditions
- // unknown, which is always safe), and the sources that lost a deferred alarm projection (G3).
- private readonly List<(MarkConditionsKnown Msg, IActorRef? Sender)> _marks = new();
+ private readonly Dictionary<(AddressSpaceRealm, string), (AlarmStateUpdate Msg, long Seq)> _alarms = new();
+ private readonly Dictionary<(AddressSpaceRealm, string), (AlarmQualityUpdate Msg, long Seq)> _qualities = new();
+ // A1 / #926 review r2: the LATEST condition-known mark per (realm, condition id), with its arrival sequence, and
+ // the sources that lost a deferred alarm projection (G3). Per-condition, so a withdrawal-heavy plan window holds
+ // at most one entry per condition (bounded by the address space), and replay can interleave marks with alarm
+ // states in arrival order.
+ private readonly Dictionary<(AddressSpaceRealm, string), DeferredMark> _marks = new();
+ private long _seq;
private readonly Dictionary _overflowedMarkSources = new(StringComparer.Ordinal);
private readonly HashSet _lossySources = new(StringComparer.Ordinal);
private bool _unattributedLoss;
@@ -1259,20 +1308,31 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
public long Dropped { get; private set; }
public int Count => _variables.Count + _alarms.Count + _qualities.Count;
public bool IsEmpty => Count == 0 && _marks.Count == 0;
- public IEnumerable Alarms => _alarms.Values;
- public IEnumerable AlarmQualities => _qualities.Values;
- public IReadOnlyList<(MarkConditionsKnown Msg, IActorRef? Sender)> Marks => _marks;
+ public IEnumerable<(AlarmStateUpdate Msg, long Seq)> Alarms => _alarms.Values;
+ public IEnumerable<(AlarmQualityUpdate Msg, long Seq)> AlarmQualities => _qualities.Values;
+ public IEnumerable Marks => _marks.Values;
///
- /// Defer a mark. A withdrawal (Known: false) is never dropped — review round 2 N1: staying KNOWN over a
- /// lost withdrawal is the unsafe direction, and withdrawals are bounded by connectivity edges. A known mark
- /// beyond is dropped (unknown is safe) and its source is remembered so the sender hears
- /// of it at replay (N2).
+ /// Defer a mark, per condition: a later mark of the same condition replaces the earlier (the later one is what
+ /// the live path leaves). A withdrawal (Known: false) is never dropped — review round 2 N1: staying KNOWN
+ /// over a lost withdrawal is the unsafe direction. It is bounded anyway: one entry per condition, so at most
+ /// the number of conditions in the address space (#926 made withdrawals routine, so the old "bounded by
+ /// connectivity edges" no longer held). A known mark for a NEW condition beyond marks is
+ /// dropped (unknown is safe) and its source is remembered so the sender hears of it at replay (N2).
///
public void Mark(MarkConditionsKnown msg, IActorRef? sender)
{
- if (!msg.Known || _marks.Count < Capacity) _marks.Add((msg, sender));
- else _overflowedMarkSources[msg.Source] = sender;
+ foreach (var id in msg.ConditionIds)
+ {
+ if (string.IsNullOrEmpty(id)) continue;
+ var key = (msg.Realm, id);
+ if (msg.Known && !_marks.ContainsKey(key) && _marks.Count >= Capacity)
+ {
+ _overflowedMarkSources[msg.Source] = sender;
+ continue;
+ }
+ _marks[key] = new DeferredMark(msg.Source, id, msg.Realm, msg.Known, sender, ++_seq);
+ }
}
public IEnumerable<(string Source, IActorRef? Sender)> OverflowedMarkSources =>
@@ -1325,12 +1385,18 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
public bool Alarm(AlarmStateUpdate msg)
{
var key = (msg.Realm, msg.AlarmNodeId);
- if (!Put(_alarms, key, msg)) return false;
+ if (!Put(_alarms, key, (msg, _seq + 1))) return false;
+ _seq++;
_qualities.Remove(key);
return true;
}
- public bool AlarmQuality(AlarmQualityUpdate msg) => Put(_qualities, (msg.Realm, msg.AlarmNodeId), msg);
+ public bool AlarmQuality(AlarmQualityUpdate msg)
+ {
+ if (!Put(_qualities, (msg.Realm, msg.AlarmNodeId), (msg, _seq + 1))) return false;
+ _seq++;
+ return true;
+ }
public (List Values, List Statuses) VariableWrites(Func<(AddressSpaceRealm, string), bool> include)
{
@@ -1357,6 +1423,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
_lossySources.Clear();
_unattributedLoss = false;
Dropped = 0;
+ _seq = 0;
}
private bool Put(Dictionary<(AddressSpaceRealm, string), T> map, (AddressSpaceRealm, string) key, T value)
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/OpcUaClientRefreshOverflowLiveTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/OpcUaClientRefreshOverflowLiveTests.cs
new file mode 100644
index 000000000..7fb2ac904
--- /dev/null
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/OpcUaClientRefreshOverflowLiveTests.cs
@@ -0,0 +1,126 @@
+using System.Diagnostics.Metrics;
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Commons.Observability;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
+
+namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests;
+
+///
+/// #926 live gate against opc-plc --alm: an alarm event item whose queue is far smaller than one
+/// ConditionRefresh replay overflows on the REAL server. The server's EventQueueOverflowEventType must reach
+/// the driver (it comes from the Server object, past the source filter), the RefreshEnd must NOT signal, and the
+/// driver's re-refresh is bounded. The positive control is the same driver with the production queue, which signals.
+/// Read-only against the fixture.
+///
+[Collection(OpcPlcCollection.Name)]
+[Trait("Category", "LiveIntegration")]
+[Trait("Feature", "GrpcData")]
+[Trait("Issue", "926")]
+public sealed class OpcUaClientRefreshOverflowLiveTests(OpcPlcFixture sim, ITestOutputHelper output)
+{
+ ///
+ /// discardOldest: false (production): the overflowing replay loses its RefreshEnd too (the newest events
+ /// are dropped), so nothing can signal. true: the RefreshEnd survives but the RefreshStart and the head of
+ /// the replay do not — the case a naive RefreshEnd signal gets wrong. (Observed on the fixture's opc-plc, 2026-11-28:
+ /// with discardOldest false a queue of 1 yields overflow notices; a queue of 2 yielded none at all — and no
+ /// RefreshEnd either, so it still never signalled.)
+ ///
+ [Theory]
+ [InlineData(false, 1u)]
+ [InlineData(true, 2u)]
+ public async Task Overflowing_refresh_never_signals_and_re_refresh_is_bounded(bool discardOldest, uint queueSize)
+ {
+ if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
+ var ct = TestContext.Current.CancellationToken;
+ var id = $"opcua-926-live-{Guid.NewGuid():N}";
+ using var counts = new EventCounts(id);
+
+ await using var drv = new OpcUaClientDriver(OpcPlcProfile.BuildOptions(sim.EndpointUrl), id)
+ {
+ AlarmEventItemQueueSize = queueSize, // one replay = RefreshStart + every retained condition + RefreshEnd
+ AlarmEventItemDiscardOldest = discardOldest,
+ AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(250),
+ };
+ var signals = 0;
+ drv.InitialAlarmStateDelivered += (_, _) => Interlocked.Increment(ref signals);
+ drv.OnAlarmEvent += (_, _) => { };
+ await drv.InitializeAsync("{}", ct);
+ await drv.SubscribeAlarmsAsync(["Plant/opc/plc/926"], ct);
+
+ // 1 + 3 retries, back-off 0.25 + 0.5 + 1 s; allow the replays to arrive.
+ var until = DateTime.UtcNow.AddSeconds(20);
+ while (counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy) < 1 + OpcUaClientDriver.MaxAlarmRefreshRetries
+ && DateTime.UtcNow < until)
+ await Task.Delay(100, ct);
+ await Task.Delay(3000, ct); // quiet window: nothing further may arrive
+ output.WriteLine($"discardOldest={discardOldest} overflows={counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow)} " +
+ $"lossyRefreshEnds={counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy)} signals={signals}");
+
+ counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow).ShouldBeGreaterThan(0,
+ "the server's EventQueueOverflowEventType reached the driver past the source filter");
+ Volatile.Read(ref signals).ShouldBe(0, "a lossy replay must never declare its conditions known");
+ if (discardOldest)
+ counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBeGreaterThan(0,
+ "the RefreshEnd arrived and was refused as lossy (its RefreshStart was discarded)");
+ counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBeLessThanOrEqualTo(
+ 1 + OpcUaClientDriver.MaxAlarmRefreshRetries, "re-refresh is bounded — no refresh storm");
+ await drv.ShutdownAsync(ct);
+ }
+
+ [Fact]
+ public async Task Production_queue_refresh_signals()
+ {
+ if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
+ var ct = TestContext.Current.CancellationToken;
+ var id = $"opcua-926-live-ctl-{Guid.NewGuid():N}";
+ using var counts = new EventCounts(id);
+ await using var drv = new OpcUaClientDriver(OpcPlcProfile.BuildOptions(sim.EndpointUrl), id);
+ var signalled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ drv.InitialAlarmStateDelivered += (_, e) => signalled.TrySetResult(e);
+ drv.OnAlarmEvent += (_, _) => { };
+ await drv.InitializeAsync("{}", ct);
+ await drv.SubscribeAlarmsAsync(["Plant/opc/plc/926"], ct);
+
+ (await signalled.Task.WaitAsync(TimeSpan.FromSeconds(30), ct)).Unsignalable.ShouldBeFalse();
+ counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow).ShouldBe(0);
+ counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBe(0);
+ await drv.ShutdownAsync(ct);
+ }
+
+ /// Counts otopcua.driver.opcuaclient.events for ONE driver instance (the instance tag filters out
+ /// parallel tests' measurements).
+ private sealed class EventCounts : IDisposable
+ {
+ private readonly MeterListener _listener = new();
+ private readonly Dictionary _counts = new();
+
+ public EventCounts(string driverInstanceId)
+ {
+ // Run the telemetry type's static initializer FIRST: if the counter is created while this listener is
+ // live, InstrumentPublished runs inside that initializer, where the field still reads null — the counter
+ // would never be enabled and every count would read 0 (seen when this class ran alone).
+ var counter = OtOpcUaTelemetry.OpcUaClientEvents;
+ _listener.InstrumentPublished = (inst, l) =>
+ {
+ if (ReferenceEquals(inst, counter)) l.EnableMeasurementEvents(inst);
+ };
+ _listener.SetMeasurementEventCallback((_, value, tags, _) =>
+ {
+ string? instance = null, evt = null;
+ foreach (var t in tags)
+ {
+ if (t.Key == OtOpcUaTelemetry.PollOverrunDriverInstanceTag) instance = t.Value as string;
+ else if (t.Key == "event") evt = t.Value as string;
+ }
+ if (instance != driverInstanceId || evt is null) return;
+ lock (_counts) _counts[evt] = _counts.GetValueOrDefault(evt) + value;
+ });
+ _listener.Start();
+ }
+
+ public long Get(string evt) { lock (_counts) return _counts.GetValueOrDefault(evt); }
+
+ public void Dispose() => _listener.Dispose();
+ }
+}
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 01c4f3c34..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
@@ -53,7 +53,8 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, new StrayHandle());
trace.ShouldBeEmpty();
- // Positive control: the live subscription's RefreshEnd does signal.
+ // Positive control: the live subscription's bracket does signal.
+ drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshStartEventType), index, live);
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, live);
trace.ShouldBe(["signal:" + Trip1]);
}
@@ -97,6 +98,8 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
var handle = drv.AddAlarmSubscriptionForTest([Trip1]);
var index = new Dictionary { ["ns=3;s=Alarms.Trip1"] = Trip1 };
+ // #926: the bracket's RefreshStart was routed in an earlier publish response.
+ drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshStartEventType), index, handle);
var replay = await SdkReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1),
[(2u, Marker(ObjectTypeIds.RefreshEndEventType)), (1u, Condition(active: true, acked: false))],
fields => drv.RouteAlarmEvent(fields, index, handle));
@@ -105,18 +108,18 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]);
}
- private static List Record(OpcUaClientDriver drv)
+ internal static List Record(OpcUaClientDriver drv)
{
var trace = new List();
drv.OnAlarmEvent += (_, e) => { lock (trace) trace.Add($"event:{e.ConditionId}:{e.Kind}"); };
drv.InitialAlarmStateDelivered += (_, e) =>
{
- lock (trace) trace.Add("signal:" + string.Join(',', e.ConditionIds));
+ lock (trace) trace.Add((e.Withdrawn ? "withdraw:" : "signal:") + string.Join(',', e.ConditionIds));
};
return trace;
}
- private static List Marker(NodeId type) =>
+ internal static List Marker(NodeId type) =>
[
Variant.From(new byte[] { 9 }.ToByteString()),
new Variant(type),
@@ -130,7 +133,7 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
Variant.Null,
];
- private static List Condition(bool active, bool acked) =>
+ internal static List Condition(bool active, bool acked) =>
[
Variant.From(new byte[] { 1 }.ToByteString()),
new Variant(new NodeId("TripAlarmType", 3)),
@@ -227,7 +230,7 @@ internal static class SdkReplay
return delivered;
}
- private static object ToParam(System.Reflection.MethodInfo save, uint[] available)
+ internal static object ToParam(System.Reflection.MethodInfo save, uint[] available)
{
var t = save.GetParameters()[0].ParameterType;
if (t.IsInstanceOfType(available)) return available;
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
new file mode 100644
index 000000000..343eacf09
--- /dev/null
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientRefreshBracketLossTests.cs
@@ -0,0 +1,547 @@
+using Opc.Ua;
+using Opc.Ua.Client;
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
+using static ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests.OpcUaClientInitialAlarmStateSignalTests;
+
+namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
+
+///
+/// #926 — a RefreshEnd declares the conditions it covers state-known (grpc-data A1), so it may signal only for a
+/// LOSSLESS RefreshStart…RefreshEnd bracket. A loss inside the bracket (the server's EventQueueOverflowEventType, a
+/// RefreshRequired, a publish-sequence gap the SDK skipped) or a missing RefreshStart suppresses the signal
+/// and re-runs ConditionRefresh, bounded; a never-signal outcome leaves the conditions unknown (Uncertain).
+///
+[Trait("Category", "Unit")]
+[Trait("Feature", "GrpcData")]
+[Trait("Issue", "926")]
+public sealed class OpcUaClientRefreshBracketLossTests
+{
+ private const string Trip1 = "Plant/opc/plc/Trip1";
+
+ /// The authored source index: the overflow notice (SourceNode = Server) is NOT in it, so this also proves
+ /// the notice is seen before the source filter.
+ private static readonly Dictionary Index = new() { ["ns=3;s=Alarms.Trip1"] = Trip1 };
+
+ private static (OpcUaClientDriver Drv, List Trace, IAlarmSubscriptionHandle Handle, RetryProbe Retries) NewDriver(string id)
+ {
+ var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), id)
+ {
+ // Long enough that a replay's own (lossy) RefreshEnd is routed before its re-refresh starts, as in production
+ // (2 s back-off vs. a 500 ms publishing interval); short enough to keep the suite fast.
+ AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(100),
+ };
+ var trace = Record(drv);
+ var handle = drv.AddAlarmSubscriptionForTest([Trip1]);
+ var retries = new RetryProbe();
+ drv.AlarmRefreshRetryInvokerForTest = (_, _) => { retries.Hit(); return Task.CompletedTask; };
+ return (drv, trace, handle, retries);
+ }
+
+ private static void Route(OpcUaClientDriver drv, IAlarmSubscriptionHandle h, NodeId type) =>
+ drv.RouteAlarmEvent(Marker(type), Index, h);
+
+ /// The issue's scenario: refreshed events overflowed the upstream queue, RefreshEnd still arrived. No signal
+ /// (the condition stays unknown), a re-refresh is run, and ITS clean bracket signals.
+ [Fact]
+ public async Task Overflow_inside_the_bracket_suppresses_the_signal_and_re_refreshes()
+ {
+ var (drv, trace, h, retries) = NewDriver("opcua-926-overflow");
+ using var _ = drv;
+
+ Route(drv, h, ObjectTypeIds.RefreshStartEventType);
+ drv.RouteAlarmEvent(Condition(active: false, acked: true), Index, h); // what survived; the active one was lost
+ Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
+ Route(drv, h, ObjectTypeIds.RefreshEndEventType);
+
+ trace.ShouldNotContain(t => t.StartsWith("signal:"), "a lossy replay must never declare its conditions known");
+ await retries.WaitForAsync(1);
+
+ // The re-refresh's replay is lossless ⇒ signalled (positive control: the bracket CAN signal).
+ Route(drv, h, ObjectTypeIds.RefreshStartEventType);
+ drv.RouteAlarmEvent(Condition(active: true, acked: false), Index, h);
+ Route(drv, h, ObjectTypeIds.RefreshEndEventType);
+ trace.Last().ShouldBe("signal:" + Trip1);
+ trace.Count(t => t.StartsWith("signal:")).ShouldBe(1);
+ retries.Count.ShouldBe(1, "one loss ⇒ one re-refresh (the lossy RefreshEnd does not request a second)");
+ }
+
+ /// A bracket whose RefreshStart never arrived (lost with the head of the replay) does not signal.
+ [Fact]
+ public async Task RefreshEnd_without_its_RefreshStart_does_not_signal()
+ {
+ var (drv, trace, h, retries) = NewDriver("opcua-926-nostart");
+ using var _ = drv;
+
+ Route(drv, h, ObjectTypeIds.RefreshEndEventType);
+ trace.ShouldBeEmpty();
+ await retries.WaitForAsync(1);
+ }
+
+ /// A RefreshRequired inside the bracket is a loss; its own sweep is the re-refresh, so the driver adds none.
+ [Fact]
+ public async Task RefreshRequired_inside_the_bracket_suppresses_the_signal()
+ {
+ var (drv, trace, h, retries) = NewDriver("opcua-926-required");
+ using var _ = drv;
+
+ Route(drv, h, ObjectTypeIds.RefreshStartEventType);
+ Route(drv, h, ObjectTypeIds.RefreshRequiredEventType);
+ Route(drv, h, ObjectTypeIds.RefreshEndEventType);
+ trace.ShouldBeEmpty();
+ await Task.Delay(200, TestContext.Current.CancellationToken);
+ retries.Count.ShouldBe(0);
+
+ // Positive control: the next clean bracket signals.
+ Route(drv, h, ObjectTypeIds.RefreshStartEventType);
+ Route(drv, h, ObjectTypeIds.RefreshEndEventType);
+ trace.ShouldBe(["signal:" + Trip1]);
+ }
+
+ /// An overflow OUTSIDE a bracket lost live events: a re-refresh repairs them (and its bracket signals).
+ [Fact]
+ public async Task Overflow_outside_a_bracket_requests_a_re_refresh()
+ {
+ var (drv, trace, h, retries) = NewDriver("opcua-926-live-overflow");
+ using var _ = drv;
+
+ Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
+ await retries.WaitForAsync(1);
+ trace.ShouldBeEmpty("the overflow notice is never projected as an alarm");
+
+ Route(drv, h, ObjectTypeIds.RefreshStartEventType);
+ Route(drv, h, ObjectTypeIds.RefreshEndEventType);
+ trace.ShouldBe(["signal:" + Trip1]);
+ }
+
+ /// Liveness: a re-refresh whose own RefreshStart is lost (the queue is still full, so only overflow notices
+ /// arrive and no bracket ever opens) can still request the next one, up to the bound.
+ [Fact]
+ public async Task A_re_refresh_whose_RefreshStart_is_lost_can_request_the_next()
+ {
+ var (drv, trace, h, retries) = NewDriver("opcua-926-start-lost");
+ using var _ = drv;
+
+ for (var n = 1; n <= OpcUaClientDriver.MaxAlarmRefreshRetries; n++)
+ {
+ Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
+ Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); // coalesced into the same request
+ await retries.WaitForAsync(n);
+ }
+ Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
+ await Task.Delay(500, TestContext.Current.CancellationToken);
+ retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries);
+ trace.ShouldBeEmpty();
+ }
+
+ /// A structurally lossy upstream (every replay overflows) costs at most
+ /// re-refreshes, then never signals — the conditions stay unknown. A later clean bracket signals and resets the budget.
+ [Fact]
+ public async Task Re_refresh_is_bounded_and_the_budget_resets_on_a_clean_bracket()
+ {
+ var (drv, trace, h, retries) = NewDriver("opcua-926-bounded");
+ using var _ = drv;
+
+ for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries + 3; i++)
+ {
+ Route(drv, h, ObjectTypeIds.RefreshStartEventType);
+ Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
+ Route(drv, h, ObjectTypeIds.RefreshEndEventType);
+ await retries.WaitForAsync(Math.Min(i + 1, OpcUaClientDriver.MaxAlarmRefreshRetries));
+ }
+ await Task.Delay(200, TestContext.Current.CancellationToken);
+ retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries, "no refresh storm");
+ trace.ShouldBeEmpty("never-signal is the safe outcome: Uncertain, not known-inactive");
+
+ // A lossless bracket (a RefreshRequired sweep, a reconnect) signals and gives the budget back.
+ Route(drv, h, ObjectTypeIds.RefreshStartEventType);
+ Route(drv, h, ObjectTypeIds.RefreshEndEventType);
+ trace.ShouldBe(["signal:" + Trip1]);
+ Route(drv, h, ObjectTypeIds.RefreshStartEventType);
+ Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
+ await retries.WaitForAsync(OpcUaClientDriver.MaxAlarmRefreshRetries + 1);
+ }
+
+ /// A publish-sequence gap inside a bracket (a message the SDK gave up on) suppresses its signal; contiguous
+ /// numbers, a repeat (several events in one message), an unknown number and the wrap are no loss.
+ [Fact]
+ public async Task Sequence_gap_inside_the_bracket_suppresses_the_signal()
+ {
+ var (drv, trace, h, retries) = NewDriver("opcua-926-seqgap");
+ using var _ = drv;
+
+ drv.NoteAlarmMessageSequence(h, 9);
+ Route(drv, h, ObjectTypeIds.RefreshStartEventType);
+ drv.NoteAlarmMessageSequence(h, 10);
+ drv.NoteAlarmMessageSequence(h, 10); // a second event of the same message
+ drv.NoteAlarmMessageSequence(h, 0); // unknown (no message): ignored
+ drv.NoteAlarmMessageSequence(h, 11);
+ Route(drv, h, ObjectTypeIds.RefreshEndEventType);
+ trace.ShouldBe(["signal:" + Trip1], "no loss inside that bracket");
+
+ retries.Count.ShouldBe(0);
+
+ Route(drv, h, ObjectTypeIds.RefreshStartEventType);
+ drv.NoteAlarmMessageSequence(h, 12);
+ drv.NoteAlarmMessageSequence(h, 14); // message 13 lost
+ Route(drv, h, ObjectTypeIds.RefreshEndEventType);
+ trace.Count(t => t.StartsWith("signal:")).ShouldBe(1, "the replay with a lost message did not signal");
+ await retries.WaitForAsync(1);
+ }
+
+ /// 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()
+ {
+ OpcUaClientDriver.ProjectEvent(Marker(ObjectTypeIds.EventQueueOverflowEventType), new Dictionary(),
+ new StrayHandle(), n => n.ToString(), (_, _) => { }).ShouldBeNull();
+ // Positive control: a non-marker event from the same source projects pass-through.
+ OpcUaClientDriver.ProjectEvent(Marker(ObjectTypeIds.BaseEventType), new Dictionary(),
+ new StrayHandle(), n => n.ToString(), (_, _) => { }).ShouldNotBeNull();
+ }
+
+ /// The alarm event item asks for the deeper queue.
+ [Fact]
+ public void Alarm_event_queue_is_deep() => OpcUaClientDriver.AlarmEventQueueSize.ShouldBeGreaterThanOrEqualTo(10_000u);
+
+ ///
+ /// Through a REAL SDK subscription with the driver's alarm options: the publish message carrying a refreshed
+ /// event (seq 3) is lost and its republish fails (not available). The SDK skips the gap and delivers the
+ /// RefreshEnd (seq 4) — reporting the skip to nothing observable: its Republish publish-state is raised
+ /// only in a worker pass that also delivers a message, which the gap prevents. The driver's own sequence check
+ /// () suppresses that RefreshEnd.
+ ///
+ [Fact]
+ public async Task Abandoned_publish_gap_suppresses_the_RefreshEnd_through_the_real_SDK()
+ {
+ var (drv, trace, h, retries) = NewDriver("opcua-926-sdk-gap");
+ using var _ = drv;
+
+ var order = await GapReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1), drv, h, Index, skip: 3);
+
+ order.ShouldBe(["live:1", "start:2", "end:4"], "the SDK skipped the lost message and delivered the RefreshEnd");
+ trace.ShouldNotContain(t => t.StartsWith("signal:"), "a replay with a lost message must not declare its conditions known");
+ await retries.WaitForAsync(1);
+ }
+
+ /// Positive control for the real-SDK test: the same replay with nothing lost signals.
+ [Fact]
+ public async Task Lossless_publish_sequence_signals_through_the_real_SDK()
+ {
+ var (drv, trace, h, retries) = NewDriver("opcua-926-sdk-nogap");
+ using var _ = drv;
+
+ var order = await GapReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1), drv, h, Index, skip: null);
+
+ order.ShouldBe(["live:1", "start:2", "refreshed:3", "end:4"]);
+ trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]);
+ retries.Count.ShouldBe(0);
+ }
+
+ private sealed class StrayHandle : IAlarmSubscriptionHandle
+ {
+ public string DiagnosticId => "stray";
+ }
+
+ private sealed class RetryProbe
+ {
+ private int _count;
+ public int Count => Volatile.Read(ref _count);
+ public void Hit() => Interlocked.Increment(ref _count);
+
+ public async Task WaitForAsync(int n)
+ {
+ var until = DateTime.UtcNow.AddSeconds(10);
+ while (Count < n && DateTime.UtcNow < until) await Task.Delay(10);
+ Count.ShouldBeGreaterThanOrEqualTo(n);
+ }
+ }
+
+ ///
+ /// Feeds publish responses 1 (a live event), 2 (RefreshStart), 3 (a refreshed Active event), 4 (RefreshEnd) and
+ /// 5..8 (unrelated events) into a real SDK , routing every delivered event through the
+ /// driver's production entry. skip: a sequence number that never arrives and is not available for
+ /// republish. Returns the order of what was delivered (kind:sequence) up to the RefreshEnd.
+ ///
+ private static class GapReplay
+ {
+ public static async Task> DeliverAsync(SubscriptionOptions options, OpcUaClientDriver drv,
+ IAlarmSubscriptionHandle handle, Dictionary index, uint? skip)
+ {
+ var order = new List();
+ var ended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var subscription = new Subscription(telemetry: null!, options);
+ var item = new MonitoredItem(telemetry: null!, new MonitoredItemOptions
+ {
+ DisplayName = "Server/Events",
+ StartNodeId = ObjectIds.Server,
+ AttributeId = Attributes.EventNotifier,
+ Filter = new EventFilter(),
+ });
+ item.Notification += (_, args) =>
+ {
+ if (args.NotificationValue is not EventFieldList efl) return;
+ lock (order)
+ {
+ if (ended.Task.IsCompleted) return;
+ var seq = efl.Message?.SequenceNumber ?? 0;
+ var kind = UpstreamValueMapping.ToClr(efl.EventFields[1]) is NodeId t
+ ? t == ObjectTypeIds.RefreshStartEventType ? "start"
+ : t == ObjectTypeIds.RefreshEndEventType ? "end"
+ : seq == 3 ? "refreshed" : "live"
+ : "?";
+ order.Add($"{kind}:{seq}");
+ drv.RouteAlarmEventFieldList(efl, index, handle);
+ if (kind == "end") ended.TrySetResult();
+ }
+ };
+ subscription.AddItem(item);
+ subscription.AddItem(item);
+
+ const System.Reflection.BindingFlags all = System.Reflection.BindingFlags.Instance
+ | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic;
+ var save = typeof(Subscription).GetMethods(all)
+ .First(m => m.Name == "SaveMessageInCache" && m.GetParameters().Length == 2);
+ typeof(Subscription).GetMethod("StartKeepAliveTimer", all)!.Invoke(subscription, null);
+
+ var available = new uint[] { 1, 2, 3, 4, 5, 6, 7, 8 }.Where(n => n != skip).ToArray();
+ async Task Send(uint seq, List fields, int pauseMs)
+ {
+ var message = new NotificationMessage
+ {
+ SequenceNumber = seq,
+ PublishTime = DateTime.UtcNow,
+ NotificationData =
+ [
+ new ExtensionObject(new EventNotificationList
+ {
+ Events = [new EventFieldList { ClientHandle = item.ClientHandle, EventFields = fields.ToArray() }],
+ }),
+ ],
+ };
+ save.Invoke(subscription, [SdkReplay.ToParam(save, available), message]);
+ await Task.Delay(pauseMs);
+ }
+
+ try
+ {
+ // seq 1 is a live event before the refresh: the SDK's first message only re-syncs its sequence.
+ await Send(1, Unrelated(), 300);
+ await Send(2, Marker(ObjectTypeIds.RefreshStartEventType), 300);
+ if (skip != 3) await Send(3, Condition(active: true, acked: false), 300);
+ await Send(4, Marker(ObjectTypeIds.RefreshEndEventType), 300);
+ await Send(5, Unrelated(), 300);
+ // The SDK republishes a gap once it is > 2.5 s old with later messages behind it, then skips it once
+ // the republish has failed; each step runs on a later arrival.
+ for (uint seq = 6; seq <= 8 && !ended.Task.IsCompleted; seq++)
+ await Send(seq, Unrelated(), 2700);
+ await ended.Task.WaitAsync(TimeSpan.FromSeconds(15));
+ }
+ finally
+ {
+ subscription.Dispose();
+ }
+
+ lock (order) return order.ToList();
+ }
+
+ private static List Unrelated()
+ {
+ var f = Marker(ObjectTypeIds.BaseEventType);
+ f[2] = new Variant(NodeId.Parse("ns=9;s=Elsewhere")); // not an authored source ⇒ dropped by the filter
+ return f;
+ }
+ }
+}
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..661ddb660 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,82 @@ 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