099238894c
- OpcUaPublishActor: deferred alarm states, qualities and condition marks replay as one arrival-ordered list (a withdrawal followed by a re-establishing transition ended unknown); marks held per (realm, condition) so withdrawals are bounded by the condition set - OpcUaClientDriver: signal/withdraw re-check the registration under _alarmStateLock; removals take the lock - DriverHostActor: a withdrawal under a raised F5 diagnostic updates its count - docs: Unsignalable/backstop residual; AlarmInitialStatePublished must stay in-process - tests: arrival-order replay (+ mirror), backstop positive control, F5 count
178 lines
14 KiB
Markdown
178 lines
14 KiB
Markdown
# #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.
|