Files
lmxopcua/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md
T
Joseph Doherty 06da40a909 fix(opcuaclient): #926 review r1 - loss after the signal withdraws known; gaps outside a bracket, overlapping starts, failed refreshes
- a sequence gap outside a bracket is a loss (re-refresh, same budget); older/repeated
  sequence numbers are ignored and not recorded
- AlarmInitialStateEventArgs.Withdrawn (additive): the driver withdraws 'known' once per
  signalled episode on its first loss; DriverHostActor sends MarkConditionsKnown(Known:false)
  for those conditions, drops them from the backstop and re-arms F5
- a RefreshStart while a bracket is open is a loss (never erases the open bracket's)
- a failed ConditionRefresh call is retried through the same bounded retry
- retry generation token (a finished retry never clears a newer retry's pending flag)
- spent budget renews after a 5-min cool-down; RefreshRequired sweeps coalesced
Red/green per fix (7 mutations) + live opc-plc gate re-run.
2026-11-28 10:07:08 -05:00

10 KiB
Raw Blame History

#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.