fix(opcuaclient): RefreshEnd signals initial alarm state only for a lossless refresh bracket (#926)

Track RefreshStart..RefreshEnd per alarm subscription. EventQueueOverflow (matched by
EventType before the source filter - it comes from the Server object), RefreshRequired,
a publish-sequence gap the SDK skipped (EventFieldList.Message.SequenceNumber; SDK 2.0.1's
Republish publish-state never fires for a gap that blocks delivery) or a missing
RefreshStart suppress the A1 signal and re-run ConditionRefresh, bounded (3, 2/4/8 s);
exhausted = conditions stay unknown (Uncertain), never Unsignalable. Alarm event queue
1000 -> 10000; new counters alarm_event_queue_overflow / alarm_refresh_lossy.
Unit + real-SDK gap tests, live overflow gate on opc-plc --alm; plan G2 text corrected.
This commit is contained in:
Joseph Doherty
2026-11-28 09:42:06 -05:00
parent 05f431f5d8
commit 99f2b9d8b7
11 changed files with 978 additions and 36 deletions
+6 -2
View File
@@ -479,8 +479,12 @@ 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. If every retry is lossy, the conditions stay unknown and the timeout diagnostic
reports them. See `docs/drivers/OpcUaClient.md`.
### Condition key (`DataConnections:ConditionKeySecret`)
+20 -2
View File
@@ -449,8 +449,26 @@ 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 lossy bracket logs a Warning and re-runs ConditionRefresh on that subscription. At most 3 re-refreshes run per
> episode, backing off 2 s, 4 s and 8 s, and a clean RefreshEnd resets the budget. When it is spent, nothing signals:
> the conditions stay unknown (`Uncertain`) and the host's `ConditionKnownSignalTimeout` diagnostic reports them.
> An overflow outside a bracket (lost live transitions) also requests a re-refresh. The alarm event item asks for a
> 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
@@ -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,28 @@ 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 lossy bracket re-runs ConditionRefresh on that subscription. This is bounded: at most 3 re-refreshes per lossy
episode, backing off 2 s, 4 s and 8 s, and a clean RefreshEnd resets the budget. A RefreshRequired keeps its own
sweep. When the budget is spent, nothing signals. The conditions stay unknown (`Uncertain`) and F5's
`ConditionKnownSignalTimeout` diagnostic reports them. They are never declared known-inactive, and the
`Unsignalable` backstop is not used for this.
- 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
@@ -0,0 +1,118 @@
# #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.
@@ -222,6 +222,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.