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 d4c1cea41..53db90580 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 @@ -1,6 +1,6 @@ # gRPC data connections: remote history and alarm/event forwarding -Date: 2026-11-23 (revision 5: review third pass folded in; revision 4 settled open items from code and the pinned SDK; revision 3 folded in the first two passes and the owner decisions of 2026-11-23) +Date: 2026-11-23 (revision 7: review fifth pass folded in; revision 6: fourth pass; revision 5: third pass; revision 4 settled open items from code and the pinned SDK; revision 3 folded in the first two passes and the owner decisions of 2026-11-23) Status: **Design + phased plan, not approved, not implemented.** No code, schema or issue changes accompany this document. It extends the merged v1 feature (`95c5e484`), whose design is [`2026-11-15-grpc-data-connections-design.md`](2026-11-15-grpc-data-connections-design.md) ("v1 design") and whose @@ -78,6 +78,21 @@ found while verifying M1 (row M1). | m-T5 L4/L2 gate placement | Accepted | L4 → A1 exit; L2 at A3 exit with A2 defaults provisional; A1–A3 not fleet-deployable before A4 (§9.1) | | m-T6 ConditionId depends on principal | Accepted, **alternative fix** | §5.2: `condition_key` derived with a cluster-wide key (not per principal), because the validator cannot see per-node credentials; A06 asserts equal ConditionIds | | m-T7 what 157 KiB excludes | Accepted | §5.5: exclusions listed; L2 is the authority for `MaxImportedConditionBytes` | +| **Fourth pass (revision 6)** | | | +| F1 OpcUaClient signal taken when the refresh call returns | Accepted (verified `OpcUaClientDriver.cs:2552,2860-2864,2881-2900,3066`) | §5.1 driver table: signal on `RefreshEndEventType` (no longer discarded); no-refresh upstreams ⇒ backstop timer, residual stated; A1 test (iii) | +| F2 signal ordering | Accepted (verified `GatewayGalaxyAlarmFeed.cs:69` `RunContinuationsAsynchronously`; `ScriptedAlarmEngine.cs:447-449` pending emissions); **plus** a third hazard found: `OpcUaPublishActor` defers alarm writes while a plan apply is busy | §5.1: ordered event on the `OnAlarmEvent` thread, same mailbox chain, same deferral queue; scripted callback queued last in `pending`; invariant stated; A1 test (iv) | +| F3 real signals for poll/current drivers | Accepted (verified `FocasAlarmProjection.cs:273`, `AbCipAlarmProjection.cs:195,251`, `HeidenhainAlarmProjection.cs:214`, `MTConnectDriver.cs:3388-3389` + `MTConnectDriver.Alarms.cs:117`) | §5.1 driver table with exact hooks; the timer survives only for OpcUaClient upstreams without ConditionRefresh | +| F4 un-ack while inactive | Accepted (verified `NativeAlarmProjector.cs:63-65,116-119`) | §5.6 step 3: bump on Active false→true or **any** Acked true→false | +| F5 unbounded unsignalled state | Accepted; resolved per the coordinator's rule (stay Uncertain + diagnostic), **not** the review's "timer marks known" | §5.1: `ConditionKnownSignalTimeout` ⇒ diagnostic + counter, never known-inactive; A1 test (v) | +| F6 re-binding ignores Time | Accepted (verified `NM:2329-2339` excludes Time) | §5.6 step 3: re-bind only when state **and** `time` match; A03 clear-and-re-raise case | +| 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) | +| 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) | +| Heidenhain line | Fixed | `OnWalk` is `HeidenhainAlarmProjection.cs:214` | | Owner decisions 2026-11-23 | Applied | Q1 → §5.5 (service principal upstream, per-caller re-gating); Q2 → §5.2 (NodeIds stable across mapping disable; residual change accepted) | --- @@ -414,37 +429,90 @@ conditions re-report (`NM:5639-5651`). Some state changes never produce an event seeded by `ReadTag` before any driver has published (`ScriptedAlarmEngine.cs:440-461`), and the engine already tells a never-pushed input apart (`StatusNeverPushed`, `ScriptedAlarmEngine.cs:58-67`; `WorstInputStatus`, `:1325`). So a scripted condition is known only when **none of its inputs is still `StatusNeverPushed`** — not when load completes. - - A1 adds an engine callback, `OnInputsEstablished(alarmId)`, raised from the evaluation path the first time after load - that an alarm's read cache holds no never-pushed input, and re-raised if an input reverts to never-pushed (a tag - re-created by a deploy). `ScriptedAlarmHostActor` turns it into the sink call below. + - A1 adds an engine callback, `OnInputsEstablished(alarmId)`, for the first time after load that an alarm's read cache + (`scratch.ReadCache`, in hand at `ScriptedAlarmEngine.cs:903` and `:1055`) holds no never-pushed input. It is re-raised + if an input reverts to never-pushed, for example a tag re-created by a deploy. + - This is a **new predicate**. `WorstInputStatus` (`:1325-1330`) filters never-pushed values out, so it cannot be reused. + - **Ordering (F2):** the callback is queued as the **last** item of the evaluation's `pending` emissions + (`ScriptedAlarmEngine.cs:447-449`), so it fires only after that evaluation's own Active emission has been dispatched. + `ScriptedAlarmHostActor` then sends `MarkConditionsKnown` on the same actor-to-`OpcUaPublishActor` chain as its + `AlarmStateUpdate`s. - A scripted condition whose inputs never arrive stays unknown: Uncertain on the consumer, which is honest. The origin cannot know its state either. - - **Native, normal-state conditions (T2).** A transition-only source never projects a condition that stays normal. In - order of preference: - 1. **A real driver signal, where one exists.** A new optional capability - `IAlarmInitialStateSignal { Task InitialAlarmStateDelivered { get; } }` (`Abstractions/`), completed when the driver - has delivered its standing alarms after a (re)connect. Two drivers already have the event to wire it to: Galaxy's - `IGalaxyAlarmFeed.InitialSnapshotCompleted` (`Drivers/…Galaxy/Runtime/IGalaxyAlarmFeed.cs:38`), and OpcUaClient's - ConditionRefresh sweep after subscribing (`OpcUaClientDriver.cs:2552`, `TryConditionRefreshAsync`). - 2. **A per-driver-type settle timer as the fallback,** for MTConnect, FOCAS, AbCip ALMD and Heidenhain: the remaining - `IAlarmSource` implementers. It starts when native `Quality` turns Good (materialise sets `BadWaitingForInitialData`, - `NM:2527`; `WriteAlarmQuality`, `NM:1480`). - - Configured as `DataConnections:ConditionKnownSettle:`. - - **Default 60 s** for any driver type not calibrated by L4 (§9.3); a calibrated type uses ≥ 2× its measured p99. - - **Residual, stated:** for a fallback-timer driver whose initial replay exceeds its configured window, a false clear - remains possible. L4 must measure each shipped fallback driver. The invariant test (A1) covers the signal-bearing - drivers and scripted conditions exactly, and the timer drivers at their calibrated window. - - **Every unknown → known transition is a hub delta (T1).** Neither the signal nor the timer changes node state, so neither - existing tap would fire. Both paths therefore end in one sink call that raises the deltas itself: - - `IOpcUaAddressSpaceSink.MarkConditionsKnown(scope)` (`Commons/OpcUa/IOpcUaAddressSpaceSink.cs`), where scope is - `(driverInstanceId)` for native or `(alarmIds)` for scripted. - - It is sent as an actor message through `OpcUaPublishActor`. Native sends come from `DriverHostActor`, which owns the - driver-signal continuation and the per-driver one-shot settle timer (an Akka scheduled message, started on the - connectivity edge and cancelled on disconnect). Scripted sends come from `ScriptedAlarmHostActor` on - `OnInputsEstablished`. - - NM sets the flags under `Lock` and raises one **state-only hub record per newly-known condition**. There is no - snapshot-time evaluation: a consumer whose snapshot was cut before the transition receives the known record as an - ordinary delta. + - **Native, normal-state conditions (T2, F1, F3).** Every shipped native alarm source gets a **real** "standing alarms + delivered" signal. A timer is only a backstop. The signal is an **ordered callback, not a `Task`** (F2): + `IAlarmInitialStateSignal` (`Abstractions/`) declares `event EventHandler + InitialAlarmStateDelivered`, raised **synchronously on the same thread and callback path as `OnAlarmEvent`, after the + last alarm event it covers.** + - **The signal carries what it covers (G1).** `AlarmInitialStateEventArgs.ConditionIds` is the set of driver + `ConditionId`s (= the condition's RawPath, the exact-match routing key of `DriverHostActor.ForwardNativeAlarm`) whose + state the completed read established. It is never "the whole driver instance". One unreachable device therefore + never holds back another device's conditions: those stay unknown, consistent with their Bad `Quality`. + - Drivers raise it on **every** completed read or cycle, not only the first. NM only raises records for conditions that + become newly known, so repeats are no-ops — and this is what makes conditions known again after a reconnect or a + deploy that adds conditions. + - **Suppression gate (G5).** The signal obeys exactly the gate `OnAlarmEvent` obeys. It is attached and detached with + the alarm handler (`DriverInstanceActor.AttachAlarmSource`, `DriverInstanceActor.cs:2536-2541`), and a driver raises + it only while it has a live alarm subscription (`DriverInstanceActor.cs:184-188`; re-asserted at `:1144-1148`). A + sentinel, refresh or poll that completes while events are suppressed raises nothing. The first signal after + (re)subscribe follows the post-subscribe replay of standing alarms. + + | Driver | Exact hook | Signal raised | + |---|---|---| + | Galaxy | `GatewayGalaxyAlarmFeed.cs:168`, where the gateway's `snapshot_complete` sentinel is handled in `Dispatch` on the feed thread after the snapshot entries (`:155-169`) | On **every** sentinel, covering every condition of the feed's current subscription. The existing `InitialSnapshotCompleted` task (`:69`) stays for its current users but is not the signal: it is one-shot per feed instance (the reopen loop `:140-152` does not reset it), and its `RunContinuationsAsynchronously` continuation could overtake queued transitions. After a gateway stream reopen, the reopened stream's sentinel signals again | + | OpcUaClient (**F1**, **G2**) | The per-event route that today drops `RefreshEndEventType` as a marker (`OpcUaClientDriver.cs:3066-3067`, `IsRefreshMarker` `:2860-2864`), reached from `OnEventNotification` (`:2749-2762`) | On receipt of `RefreshEndEventType`, covering every condition of that alarm subscription, after the refreshed events delivered before it were projected. **Not** when `TryConditionRefreshAsync` returns (`:2881-2900`). See G2 below for ordering across publish responses | + | FOCAS | `FocasAlarmProjection.PollOnceAsync` per-host loop (`:243-276`): after `NoteAlarmReadSucceeded(host)` (`:273`) and that host's `Tick` (`:274`). The `continue` path for a failed host (`:253-272`) raises nothing | **Per host**: the condition ids of that host's alarm tags, after its read succeeded and its transitions were emitted. Raised again on each later successful read | + | AbCip ALMD/ALMA | `AbCipAlarmProjection.Tick` (`:195`), called from `RunPollLoopAsync` (`:251`); a node whose `InAlarm` read is non-Good is skipped (`:211`) | **Per node**: at the end of each `Tick`, the condition ids of the nodes whose `InAlarm` (and, for ALMA, all plan refs) read Good in that tick. Skipped nodes are excluded | + | Heidenhain | `HeidenhainAlarmProjection.OnWalk(hostName, status, alarms)` (`HeidenhainAlarmProjection.cs:214`), one call per host per walk | **Per host**: after an `OnWalk` with a Good status has applied that host's alarms, the condition ids of that host's `ALARM:` tags. A non-Good walk raises nothing | + | MTConnect | The condition tracker built from the session's `/current` baseline (`MTConnectDriver.cs:3388-3389`) and delivered by the resync emission in `SubscribeAlarmsAsync` (`MTConnectDriver.Alarms.cs:117`, `EmitConditionTransitions(..., resync: true)`) or as the restarted pump's first act | After that resync emission over a tracker built from a `/current` document, covering every subscribed condition whose current level is **not** `Unavailable` (an `Unavailable` data item is the device not reporting, so it stays unknown) | + + - **OpcUaClient publish ordering (G2), settled from the decompiled client SDK 2.0.1** (`Opc.Ua.Client.Subscription`): + - With `SequentialPublishing = false` — the `SubscriptionOptions` default, and the alarm subscription at + `OpcUaClientDriver.cs:2445` does not set it — the message worker processes any received message without waiting + for missing earlier sequence numbers. More than one worker can run (`m_outstandingMessageWorkers`). + - Only `SequentialPublishing = true` gates on `ValidSequentialPublishMessage`, and its remarks say callbacks are then + not invoked in parallel. + - 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. + - If the SDK reports a sequence gap it could not republish during a refresh, that RefreshEnd does not signal. F5 then + applies, and the next refresh signals. + - **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 + 60 s from quality Good) marks its conditions known. + - **Residual, stated:** an upstream alarm already active and never re-transitioned is invisible to OtOpcUa itself + (the driver cannot see it either). The consumer then shows inactive, exactly as the origin's own clients do. No + shipped driver type relies on the timer otherwise. + - **A signal that never completes (F5).** Examples: a Galaxy gateway that sends no sentinel; a ConditionRefresh call that + fails (`:2894-2900`); a RefreshEnd that never arrives; a host that never answers a poll. These are bounded by + `DataConnections:ConditionKnownSignalTimeout:` (default 120 s from quality Good). On expiry the conditions + **stay unknown** — `Uncertain` on the consumer, **never known-inactive**. A data-connection diagnostic "initial alarm + state not signalled" (driver instance, elapsed time) is raised, and `otopcua.dataconn.conditions.unsignalled` is + counted. A later signal clears it. + - **Every unknown → known transition is a hub delta (T1), ordered behind the projections it summarises (F2).** + - Native path: the driver raises `InitialAlarmStateDelivered` after its alarm events, on the same thread. + `DriverInstanceActor` handles it exactly like an alarm event — the same self-`Tell` into its own mailbox, then the same + forward to `DriverHostActor`. + - `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. + - **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`). + - Any such drop or skip for a driver instance (or for the scripted host) **discards that source's deferred + `MarkConditionsKnown`**. Its conditions then stay unknown (Uncertain) until the source's next signal — never known + over a projection that did not land. + - Signals repeat every cycle (Galaxy: on the next sentinel), and F5's diagnostic covers a source that does not + re-signal. + - Only then does `IOpcUaAddressSpaceSink.MarkConditionsKnown(driverInstanceId, conditionIds)` (or the scripted alarm-id set) set the flags under `Lock` and raise one state-only + hub record per newly-known condition. No continuation of a `Task` is ever used as the signal. + - The backstop timer and the F5 timeout are Akka scheduled messages to `DriverHostActor`, which enter the same chain. + - **Ordering invariant (stated and tested):** for any condition, the `MarkConditionsKnown` that makes it known is applied + by NM after every alarm projection its driver (or the scripted engine) emitted before raising the signal. A known + record therefore never precedes the Active projection it summarises. - On a Warm standby native drivers do not run, so native conditions stay unknown until promotion. The standby's scripted engine is warm, so its scripted conditions are already known. The stream is Primary-only by default. `snapshot_complete` is withheld until the origin's current address-space apply has completed (`CompleteAddressSpaceApply` @@ -753,9 +821,9 @@ Defaults (conditions get their **own** budget; worst case is 49 nodes): Instead the origin keeps an **activation marker** per condition in NM: `(serving incarnation, sequence)`, under `Lock`. - **Bumped only on a new occurrence:** - an Active false→true edge; - - an Acked true→false edge while Active. This is #647's changed-message re-raise, which un-acks and so needs a new - acknowledgement; this extends the review's inactive→active rule, because otherwise an old EventId could acknowledge - the new statement. + - **any** Acked true→false edge, active or not (F4). This covers #647's changed-message re-raise, the #760 ack-revert, + and `InactiveUnacknowledged`, which projects inactive+unacked in one update for an occurrence that came and went + (`NativeAlarmProjector.cs:63-65,116-119`). Without it, an old EventId could acknowledge the new occurrence. - **Never bumped** by a re-projection that leaves Active/Acked unchanged: severity or message updates, same-message re-raises, re-asserts, method echoes. - `RestoreCarryOver` carries the marker through a rebuild; `NativeConditionCarryOver` already carries @@ -769,10 +837,26 @@ Defaults (conditions get their **own** budget; worst case is 49 nodes): The origin rejects a mismatch with `BadEventIdUnknown`, which covers a new occurrence not yet streamed. - - **N6 re-checked:** a resync (origin failover or restart) yields a new incarnation and therefore a new marker. When the - resynced record's state is unchanged under the shared delta gate, the consumer **re-binds** that condition's retained - EventIds to the new marker, so pre-failover EventIds stay ackable without a ConditionRefresh. A changed state does not - re-bind. Gated in A03. + - **N6 re-checked:** a resync (origin failover or restart) yields a new incarnation and therefore a new marker. The + consumer **re-binds** a condition's retained EventIds to the new marker only when **both** hold: + - the resynced record's state is unchanged under the shared delta gate; + - its `time` equals the `time` of the record those EventIds were bound to (F6). + + The delta gate does not compare `Time` (`NM:2329-2339`), so an alarm that cleared and re-raised during the gap with the + same message and severity would otherwise re-bind to a different occurrence. + + **What the client sees (G4).** `time` survives only where the condition node itself survives with its carried state: + a consumer stream reset against the same serving incarnation (no new marker, so nothing to re-bind) and an in-process + rebuild (`RestoreCarryOver`). Across an **origin pair failover or process restart**, times generally differ: each + node's scripted engine stamps with its own clock, and native drivers re-deliver standing alarms with new timestamps + (e.g. AbCip stamps `DateTime.UtcNow`, `AbCipAlarmProjection.cs:231,241`). So: + 1. pre-failover EventIds are **not** re-bound; + 2. an ack with one answers `BadEventIdUnknown` (never acks the wrong occurrence); + 3. when a resync leaves any retained condition un-re-bindable, the consumer emits **`RefreshRequiredEventType`** on that + mapping's notifiers and to authorized Server-object items; + 4. the client's ConditionRefresh returns current EventIds, and an ack with one succeeds. + + Documented in `docs/AlarmTracking.md` "Imported conditions" (A4). Gated in A03. - **A2 test (T3):** re-project an unchanged active alarm at the origin (message-only change, then a scripted re-assert), then ack with the pre-re-projection EventId ⇒ Good. A changed-message re-raise ⇒ the old EventId answers `BadEventIdUnknown`. @@ -858,7 +942,7 @@ NodeId: accepted under owner decision Q2, as removal + addition + RefreshRequire |---|---|---| | H2 | `AddDataConnectionHistory` | `DataConnection.HistoryTimeoutMilliseconds` (30000); `DataExport.MaxConcurrentHistoryReads` (4), `MaxHistoryValuesPerPage` (10000), `MaxHistoryResponseBytes` (4 MiB); `RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest` (16 MiB) | | A2 | `AddDataConnectionConditions` | `DataExport.MaxConditions` (1000), `AllowGalaxyServiceAck` (false); `RemoteNamespaceMapping.MaxConditions` (1000), `ConditionStaleTimeoutMilliseconds` (30000), `ConditionMethodTimeoutMilliseconds` (5000), `ConditionSnapshotTimeoutMilliseconds` (30000) | -| A2 (host options, not ConfigDb) | — | `DataConnections:MaxImportedConditionNodes` (122500), `DataConnections:MaxImportedConditionBytes` (400 MiB), `DataConnections:ConditionKnownSettle:` (origin; 60 s default for uncalibrated fallback drivers, L4-calibrated otherwise), `DataConnections:ConditionKeySecret` (secret) | +| A2 (host options, not ConfigDb) | — | `DataConnections:MaxImportedConditionNodes` (122500), `DataConnections:MaxImportedConditionBytes` (400 MiB), `DataConnections:ConditionKnownSignalTimeout:` (origin; 120 s), `DataConnections:ConditionKnownSettle:OpcUaClient` (origin backstop for upstreams without ConditionRefresh; 60 s), `DataConnections:ConditionKeySecret` (secret) | Each migration phase also adds the bits to `KnownOperations`, extends `DeploymentArtifact.DataConnections.cs`, and includes the new fields in `DataConnectionScopeRevision` (so DB-less nodes and the LocalDb artifact cache receive them). It also adds @@ -1057,9 +1141,11 @@ Expected: identical rows/status/timestamps to the origin; continuation followed - Tasks: - `SnapshotConditions(scope)` under a short `Lock` hold with watermark; - the delta callback in `ReportConditionEvent` (before the standby return) and in `WriteAlarmCondition` for silent applies; - - `state_known`: `_conditionStateKnown` in NM; `IOpcUaAddressSpaceSink.MarkConditionsKnown(scope)` raising state-only - deltas; `IAlarmInitialStateSignal` (Abstractions) wired for Galaxy and OpcUaClient; per-driver-type settle timer in - `DriverHostActor`; `ScriptedAlarmEngine.OnInputsEstablished` → `ScriptedAlarmHostActor`; + - `state_known`: `_conditionStateKnown` in NM; `IOpcUaAddressSpaceSink.MarkConditionsKnown(source, conditionIds)` raising state-only + deltas; `IAlarmInitialStateSignal` as an ordered event wired for all six native drivers (hooks in §5.1); backstop timer + (OpcUaClient-without-refresh only) and F5 signal timeout in `DriverHostActor`; `MarkConditionsKnown` deferred with + `AlarmStateUpdate`s in `OpcUaPublishActor`; `ScriptedAlarmEngine.OnInputsEstablished` queued last in `pending` → + `ScriptedAlarmHostActor`; - the per-condition activation marker in NM, carried by `RestoreCarryOver` (T3); - the `ConditionStateHub`; - realm-local placement enumeration per export: Raw = RawPath; UNS = reference variable ids and ScriptedAlarmId; @@ -1070,7 +1156,9 @@ Expected: identical rows/status/timestamps to the origin; continuation followed `SdkAddressSpaceSink`, the no-op sink), `Runtime/OpcUa/OpcUaPublishActor.cs` (forwarding), `Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs`, `src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs` (`OnInputsEstablished`), `Runtime/Drivers/DriverHostActor.cs` (signal/timer), new `Abstractions/IAlarmInitialStateSignal.cs`, - `Drivers/…Galaxy/GalaxyDriver.cs`, `Drivers/…OpcUaClient/OpcUaClientDriver.cs`, new `Runtime/DataConnections/ConditionStateHub.cs`, + `Drivers/…Galaxy/{GalaxyDriver.cs,Runtime/GatewayGalaxyAlarmFeed.cs}`, `Drivers/…OpcUaClient/OpcUaClientDriver.cs`, + `Drivers/…FOCAS/FocasAlarmProjection.cs`, `Drivers/…AbCip/AbCipAlarmProjection.cs`, `Drivers/…Heidenhain/HeidenhainAlarmProjection.cs`, + `Drivers/…MTConnect/MTConnectDriver.Alarms.cs`, `Runtime/Drivers/DriverInstanceActor.cs`, new `Runtime/DataConnections/ConditionStateHub.cs`, `LocalExportCatalog*.cs` (placement enumeration; the catalog stays v1-shaped), `LocalCatalogCoordinator.cs`, `Abstractions/DataConnections/ProjectedDataIds.cs` (or a sibling `ImportedConditionIds.cs`). - Tests: @@ -1085,9 +1173,27 @@ Expected: identical rows/status/timestamps to the origin; continuation followed condition that is active at the origin, checked against origin node state after settling. Cases: - (i) a standing scripted alarm whose input arrives 30 s late ⇒ no `known, inactive` record before the first real evaluation; - - (ii) a Galaxy/OpcUaClient-style driver whose initial replay arrives after quality Good ⇒ known only on + - (ii) per native driver (fakes for all six): the initial replay arrives after quality Good ⇒ known only on `InitialAlarmStateDelivered`; - - (iii) a fallback-timer driver ⇒ known only after its configured window; + - (iii) **F1:** an OpcUaClient upstream with a standing active alarm whose refreshed events arrive **after** + `ConditionRefreshAsync` returns ⇒ no `known, inactive` record precedes its raise; known only on RefreshEnd; + - (iv) **F2 ordering, artificially delayed:** delay `DriverInstanceActor` and `OpcUaPublishActor` (and the scripted + pending dispatch) ⇒ `MarkConditionsKnown` is still applied after the Active projection, for Galaxy and for scripted; + - (v) **F5:** a signal that never completes ⇒ after `ConditionKnownSignalTimeout` the condition is still unknown + (Uncertain), the diagnostic is raised, and a late signal clears it; + - (vi) OpcUaClient upstream without ConditionRefresh ⇒ known after the backstop timer (residual documented); + - (vii) a Galaxy gateway stream reopen, then a deploy adding a condition ⇒ that condition becomes known on the next + sentinel; + - (viii) **G1:** FOCAS, Heidenhain and AbCip fakes with two devices/nodes, one unreachable ⇒ the reachable device's + normal-state conditions become known; the unreachable one's stay unknown (Uncertain, Bad quality) with no F5 effect on + the reachable one; + - (ix) **G2:** a refresh replay split across publish responses delivered out of order ⇒ with `SequentialPublishing` + the RefreshEnd signal is processed after every refreshed event; a configuration-pinning test asserts the alarm + subscription sets it; + - (x) **G3:** force a deferred-alarm overflow (and an out-of-scope skip) during a plan apply ⇒ the deferred + `MarkConditionsKnown` is discarded and the condition stays unknown until the next signal; + - (xi) **G5:** a signal raised while the alarm feed is suppressed (no alarm subscription) is not delivered; after + re-subscribe the first signal follows the replayed standing alarms; - a carried-over condition is known at once; an input reverting to never-pushed makes the scripted condition unknown again; - a UNS-only export lists no RawPath anywhere in the record (property test over generated topologies); - `condition_key` stable across restart and pair members, and equal across listings and principals (m-T6); @@ -1158,7 +1264,7 @@ Expected: identical rows/status/timestamps to the origin; continuation followed |---|---| | A01 | Scripted raise, ack, confirm via consumer; origin and consumer both show it | | A02 | Native condition: OpcUaClient driver → the opc-plc fixture, which already runs `mcr.microsoft.com/iotedge/opc-plc:2.14.10` with `--alm` (`tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/Docker/docker-compose.yml:9,29-35`). Ack + AddComment; Confirm refused | -| A03 | Origin failover mid-stream with standing active alarms ⇒ resync retires nothing still active, no duplicate events, positive control; an ack with a **pre-failover** EventId succeeds after the unchanged resync (N6) | +| A03 | Origin failover mid-stream with standing active alarms ⇒ resync retires nothing still active, no duplicate events, positive control. **EventIds (G4):** an ack with a pre-failover EventId ⇒ `BadEventIdUnknown`; the client receives `RefreshRequiredEventType`; after ConditionRefresh the new EventId acks Good. A consumer stream reset against the **same** origin incarnation keeps old EventIds ackable. A clear-and-re-raise during the gap never re-binds | | A04 | One native alarm referenced by two equipment + a Raw mapping ⇒ one consumer condition (same `ConditionId` regardless of which mapping's subscriber came first), three notifiers, one `i=2253` event; a UNS-only principal's records carry no RawPath | | A05 | ACLs off, session without mapping grant at `i=2253` ⇒ zero imported events (with positive control) | | A06 | Consumer Primary change with clients connected to both consumer nodes ⇒ both converge, no duplicates; the same alarm has the **same `ConditionId` on both consumer nodes**, including when they authenticate as different principals (m-T6) | @@ -1203,7 +1309,9 @@ Use two-state id selection via `SimpleAttributeOperand(type, [X, Id])`, as the C | Remote ack is a no-op at origin | A2 | Session-less entry factored from the SDK path; origin-subscriber assertion | | Partial condition sets make ConditionRefresh lie | A3 | Per-mapping all-or-nothing decided at snapshot begin from `total`; own budget sized ≈ 4× expected counts | | Failover/restart clears live alarms on the consumer | A1/A3 | Snapshot from node state; `state_known` only on established state (driver signal, inputs established, per-driver window); withheld `snapshot_complete`; retire-only-on-complete; T2 invariant test, A03 | -| A fallback-timer driver replays slower than its window | A1 | Per-driver window, L4 per driver, 60 s default for unmeasured types; residual documented (§5.1) | +| A known signal overtakes the projections it summarises | A1 | Ordered event on the `OnAlarmEvent` path; same mailbox chain and deferral queue; F2 ordering test | +| A signal never arrives | A1 | F5 timeout ⇒ stays Uncertain + diagnostic, never known-inactive | +| OpcUaClient upstream without ConditionRefresh | A1 | Only remaining timer case; residual stated (§5.1) | | Acks fail on busy alarms because the precondition moves | A2 | Origin-owned activation marker, bumped only on a new occurrence (T3) | | RawPath disclosure to UNS-only principals | A1 | Realm-local placements; keyed `condition_key`; property test; pre-existing `stable_source_id` disclosure is #916 | | Imported-condition method path regresses local methods | A3 | Claimed items only (`Processed`), `base.Call` unchanged for the rest; lock-freedom gate; existing `ConditionMethodEventTests` stay green | @@ -1233,7 +1341,7 @@ delta over 2,000 instances, and times the snapshot field copy. It is not in the | L1 | A1 | `SnapshotConditions` `Lock` hold inside a running origin with 1,000 conditions in scope while drivers publish | p99 ≤ 10 ms; no data Publish on the origin delayed > 50 ms during a snapshot | | L2 | A3 exit | Consumer memory with 1,000 imported conditions (one mapping), including ids, registries and indexes (m-T7) | Working-set growth ≤ 200 MiB; set `MaxImportedConditionBytes` = measured per-condition bytes × 2,500 and lower `MaxConditions` if needed, before A4 freezes defaults | | L3 | A3 | Lock-freedom: origin method handler stalled 5 s | Concurrent consumer Read/Browse/Publish < 200 ms; no local ack state before the origin record (§5.6 step 6) | -| L4 | **A1 exit** (m-T5) | Per native alarm source shipped: time from quality Good to the driver's standing alarms all projected. Galaxy and OpcUaClient (→ opc-plc `--alm`): signal latency. MTConnect, FOCAS, AbCip ALMD, Heidenhain: settle window, on their software fixtures or the hardware rigs recorded in memory | Each fallback driver's `ConditionKnownSettle:` ≥ 2× its observed p99; an unmeasured driver type keeps the conservative 60 s default and is listed as unmeasured; the T2 invariant test passes for every measured source | +| L4 | **A1 exit** (m-T5) | Per native alarm source shipped: latency from quality Good to `InitialAlarmStateDelivered` (Galaxy, OpcUaClient → opc-plc `--alm` RefreshEnd, FOCAS, AbCip, Heidenhain, MTConnect) on their fixtures or recorded hardware rigs | `ConditionKnownSignalTimeout:` ≥ 3× the observed p99 (default 120 s otherwise); the T2 invariant and F2 ordering tests pass for every measured source; the OpcUaClient-without-refresh backstop needs no calibration (documented residual) | | L5 | A4 | Condition counts of the docker-dev export and of one real production export (read-only count via the origin's existing AdminUI `/alerts` or ConfigDb authoring counts) | Each mapping ≤ 80% of `MaxConditions` and each consumer node ≤ 80% of the host caps; else adjust the defaults and record why | --- diff --git a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-relay-plan-review.md b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-relay-plan-review.md index 6d9bd78a2..fe669eb8c 100644 --- a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-relay-plan-review.md +++ b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-relay-plan-review.md @@ -829,3 +829,82 @@ the marker) to match as well before re-binding. ### Open Major items at close **F1** (OpcUaClient signal point) and **F2** (signal ordering), both Phase A1. Everything else is closed or Minor. + +--- + +## Fifth pass (2026-11-23) + +Scope: revision 6, the F1–F6 fixes and the Galaxy reconnect handling only (§5.1 driver table, §5.6 step 3). Baseline +`649f2ecd2`. Read from code; nothing run. The OPC UA **client** SDK's publish-ordering default was not decompiled (G2). + +### Final verdict per phase + +- **X0 — approve. Phase H — approve.** Unchanged. +- **Phase A — approve with one change.** F1–F6 are closed in design. One new Major (G1): the poll-driver signals are + scoped to the whole driver instance, so a single unreachable device keeps every other device's normal-state alarms + `Uncertain` on the consumer. It is a scope change to one event-args type and one sink parameter, in A1. + +### F1–F6 and Galaxy + +| Item | Status | Evidence | +|---|---|---| +| **F1** OpcUaClient signal | **Closed.** The marker is dropped in the per-event route (`OpcUaClientDriver.cs:3066-3067`, `IsRefreshMarker` `:2861-2864`), reached from `OnEventNotification` (`:2749-2762`), which is the same callback that projects the refreshed events — so raising on `RefreshEndEventType` there is "behind the events". Refresh-unsupported (`:2887-2893`) correctly falls to the backstop timer with the residual stated honestly (the driver cannot see such an alarm either). Ordering across publish responses: G2. | +| **F2** signal ordering | **Closed.** An event raised on the driver's alarm thread is marshalled like an alarm event (`Runtime/Drivers/DriverInstanceActor.cs:987`), so Akka ordering holds end to end. Scripted: last item of `pending` (`ScriptedAlarmEngine.cs:447-449`). The deploy-deferral leg has one gap: G3. | +| **F3** poll/current hooks | **Hooks exist and are the right places; scope is wrong (G1).** FOCAS `FocasAlarmProjection.cs:273` (`NoteAlarmReadSucceeded`, inside the per-host loop of `PollOnceAsync` `:243-276`; `Tick` follows at `:274`, so the signal must be raised after the loop, as the plan words it). AbCip `AbCipAlarmProjection.cs:195` (`Tick`) and `:251` (`RunPollLoopAsync`); a non-Good `InAlarm` read is skipped per node at `:211`. Heidenhain `HeidenhainAlarmProjection.OnWalk` is at `:214` (plan says `:215`), one call per host with a status. MTConnect `MTConnectDriver.cs:3388-3389` (tracker built from `/current`, `baseline: true`) and `MTConnectDriver.Alarms.cs:117` (`EmitConditionTransitions(…, resync: true)`). | +| **F4** un-ack while inactive | **Closed.** Bump on Active false→true or any Acked true→false; matches `NativeAlarmProjector.cs:63-65,116-119`. | +| **F5** unsignalled state | **Closed as intended** (stay `Uncertain` + diagnostic, never known-inactive). It preserves the invariant and creates no defect by itself; it is what turns G1 from a delay into a permanent state. | +| **F6** re-bind requires equal `time` | **Closed for safety; it now defeats N6 in the failover case (G4).** | +| **Galaxy reconnect** | **Closed.** The sentinel is handled in `Dispatch` on the feed thread, after the snapshot entries (`GatewayGalaxyAlarmFeed.cs:155-169`), so a per-sentinel event is ordered and fires again after the reopen loop (`:140-152`). Not using the one-shot `InitialSnapshotCompleted` task (`:69`) is right. One condition to state: G5. | + +### New findings + +#### G1 (Major) — "every subscribed host/node" makes one dead device degrade the whole driver instance + +The FOCAS, Heidenhain and AbCip rows raise the signal only when **every** subscribed host (or source node) has read +successfully, and `MarkConditionsKnown` is scoped to `driverInstanceId`. These drivers are multi-device: FOCAS polls a +list of device hosts per subscription and simply `continue`s past a failed one (`FocasAlarmProjection.cs:253-272`); +Heidenhain walks per host (`OnWalk(hostName, status, …)`, `:214`); AbCip skips a non-Good node (`:211`). One powered-off +machine therefore means the signal never fires, and under F5 every normal-state condition of the *reachable* machines +stays `Uncertain` on the consumer indefinitely — while the origin shows them Good. On a fleet where some devices are +routinely unreachable this is the steady state. + +**Fix.** Make the signal carry what it covers: `AlarmInitialStateEventArgs` names the device host (or the condition +ids) whose read completed, and `MarkConditionsKnown` takes that set instead of a driver instance. Each driver already +has the per-host/per-node success point cited above. Conditions of an unreachable device stay unknown, which is correct +and is already explained by their Bad `Quality`. A1 test: two devices, one unreachable ⇒ the reachable device's +conditions become known; the other's do not. + +#### G2 (Minor) — RefreshEnd ordering across publish responses + +A ConditionRefresh replay can span several publish responses. The signal is correct only if the client processes them in +sequence. Nothing in `src/` sets `SequentialPublishing` on the alarm subscription (no match in the tree). Set it for that +subscription, or record in the A1 evidence that the pinned client SDK orders event callbacks across responses. + +#### G3 (Minor) — a deferred known-signal must not survive a dropped deferred alarm + +`OpcUaPublishActor`'s deferral is a bounded, keyed store, not a queue: an `AlarmStateUpdate` that does not fit is dropped +with a warning (`Runtime/OpcUa/OpcUaPublishActor.cs:1048-1051`, `WarnDeferredOverflow`), and replay skips conditions that +no longer fit the applied scope (`:1106-1112`). Replaying `MarkConditionsKnown` after such a loss marks a condition known +whose Active projection never reached the node. Rule: an overflow or a skipped alarm for a driver discards that driver's +deferred known-signal (it will be raised again on the driver's next cycle, since signals repeat). + +#### G4 (Minor) — strict `time` equality means pre-failover EventIds rarely re-bind + +The plan says the origin-side time "survives failover". It does for a rebuild on the same node (`RestoreCarryOver`), but +not across pair members: each node's scripted engine stamps transitions with its own clock, and a promoted node's native +drivers re-deliver standing alarms with new timestamps (AbCip stamps `DateTime.UtcNow`, `AbCipAlarmProjection.cs:231,241`). +So after an origin failover the times differ, nothing re-binds, and every pre-failover EventId answers +`BadEventIdUnknown`. That is safe, but A03's expectation ("an ack with a pre-failover EventId succeeds") will not hold in +general. Either scope that expectation to a same-node restart, or, when a retained condition cannot be re-bound, send +`RefreshRequiredEventType` so clients obtain current EventIds — and say so in the docs. + +#### G5 (Minor) — the signal must obey the alarm-event suppression gate + +`OnAlarmEvent` is suppressed until an alarm subscription exists and is re-asserted on re-subscribe +(`DriverInstanceActor.cs:186`, `:1146`, `:2541`). A sentinel or completed poll that arrives while events are suppressed +must not signal; the signal is raised after the post-subscribe replay. One sentence in §5.1 and one case in the A1 +ordering test. + +### Open Major at close + +**G1** only (Phase A1). No Blocker. X0 and Phase H are clear to start.