diff --git a/.claude/rules/alarms.md b/.claude/rules/alarms.md index 7d70f2de3..b70a66163 100644 --- a/.claude/rules/alarms.md +++ b/.claude/rules/alarms.md @@ -75,3 +75,11 @@ under their condition's scope). ⚠️ The shelve methods resolve by the `AlarmC because `New` adopts those (a fixed set) as their `MethodDeclarationId`; calls by the `ShelvedStateMachineType_*` id are no longer supported (pinned by a test). Condition teardown must forget the whole `PredefinedNodes` subtree (`ForgetPredefinedSubtree`) or a removed condition's children keep answering. + +**A redeploy is a restatement, a restart is not (#935).** `ScriptedAlarmEngine.LoadAsync` runs on every deploy and seeds +each alarm `previous ?? persisted ?? Fresh`: a surviving alarm id starts from the last completed generation's in-memory +condition (captured under `_evalGate`, kept across a failed load). The production store has no `Active` column, so seeding a +survivor from it made every deploy re-activate a still-active alarm. That reset the ack, sent a duplicate `alerts` row, +moved condition Time and bumped the activation marker. Do not reintroduce a store read for survivors. Identity is the alarm +id (edits carry over). A disabled or removed alarm re-added later, and every process restart, still read the store. +See `docs/ScriptedAlarms.md` §"A redeploy is a restatement". diff --git a/docs/ScriptedAlarms.md b/docs/ScriptedAlarms.md index 42f2615cc..565b699ed 100644 --- a/docs/ScriptedAlarms.md +++ b/docs/ScriptedAlarms.md @@ -157,15 +157,49 @@ Predicate evaluation and message-template resolution deliberately treat tag-inpu `IAlarmStateStore` (`IAlarmStateStore.cs`) is the persistence contract: `LoadAsync(alarmId)`, `LoadAllAsync`, `SaveAsync(state)`, `RemoveAsync(alarmId)`. `InMemoryAlarmStateStore` in the same file is the default for tests and dev deployments without a SQL backend. The production implementation is `EfAlarmActorStateStore` (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/EfAlarmActorStateStore.cs`), which persists to the `ScriptedAlarmState` config-DB table via `IAlarmActorStateStore`. -Persisted scope per plan decision #14: `Enabled`, `Acked`, `Confirmed`, `Shelving`, `LastTransitionUtc`, the `LastAck*` / `LastConfirm*` audit fields, and the append-only `Comments` list. `Active` is **not** trusted across restart — the engine re-runs the predicate at `LoadAsync` so operators never re-ack an alarm that was already acknowledged before an outage, and alarms whose condition cleared during downtime settle to `Inactive` without a spurious clear-event. +Persisted scope per plan decision #14: `Enabled`, `Acked`, `Confirmed`, `Shelving`, `LastTransitionUtc`, the `LastAck*` / `LastConfirm*` audit fields, and the append-only `Comments` list. `Active` is **not** trusted across restart (the production `LocalDbAlarmConditionStateStore` has no column for it — a loaded row is `Inactive`) — the engine re-runs the predicate at `LoadAsync`, so alarms whose condition cleared during downtime settle to `Inactive` without a spurious clear-event, and the ack/confirm audit trail survives. Across a **process restart** an alarm whose predicate is still true is therefore a new occurrence: `Activated`, `Unacknowledged`, `LastTransitionUtc` = the load instant — the operator re-acks once after an outage. + +### A redeploy is a restatement (#935) + +`LoadAsync` runs on **every deploy** (`ScriptedAlarmHostActor.ApplyScriptedAlarms`), not just at startup. Seeding every alarm +from the store made each deploy the restart case above for every still-active alarm: an operator-acknowledged alarm came back +`Unacknowledged`, an `Activated` emission reached the `alerts` topic (a duplicate historian / AVEVA row per deploy), the +condition `Time` moved to the deploy instant, and the origin's activation marker bumped (gRPC data consumers minted new EventIds). + +The seed is now **`previous ?? persisted ?? Fresh`**: before it clears its alarm table, `LoadAsync` captures the last +**completed** generation's in-memory condition for every alarm, under the engine's `_evalGate`, and an alarm id that survives +the reload starts from it. A still-true predicate then yields no transition — no emission, `Acked` / `Confirmed` / +`LastTransitionUtc` unchanged, so the activation marker does not advance either. The #487 re-assert below still restores the node +after a full rebuild, carrying the unchanged `LastTransitionUtc`. Decisions: + +- **Identity is the alarm id.** An edited predicate, severity, message template or equipment placement on the same id is the + same alarm. Its condition carries over, the new predicate decides the next transition (a predicate that is now false is a real + `Cleared`), and the next projection carries the new severity and message. +- **Removed and re-added in one deploy** is the same id in both generations, so it carries over. An alarm **removed or disabled** + (the host does not load a disabled plan) by one deploy and re-added by a later one is absent from the previous generation, so it + is seeded from the store like a restart: the engine stopped evaluating it, so it is a new occurrence. +- **Shelving** (including a timed shelve's expiry instant), `Confirmed`, an operator `Disable` and the comment trail carry + verbatim; the shelving timer restarts with the load. +- **A failed load** (compile error, store fault) never becomes a seed. The last completed generation stays the seed for the next load. +- **Concurrency.** The capture happens under `_evalGate`, so it includes every evaluation and operator command that completed + before the load. Work queued behind the gate runs against the new generation. +- **Inputs not ready at the reload** (Bad / never-pushed, cold-start guard) hold the *carried* condition. Before the change they + held the store's `Inactive`, which silently de-activated the engine and re-fired `Activated` on the next push. +- **Out-of-process runner** (`Scripting:Runner` with the `ScriptedAlarm` seam): the batch startup pass seeds the same way. A + runner that is not up at the reload freezes the carried condition (`BadResourceUnavailable`), not the store's `Inactive`. +- **Warm standby.** Each node's engine receives every operator command (the `alarm-commands` topic is a cluster broadcast), so + its in-memory condition is what that node already serves. A deploy no longer re-reads the replicated store row for a surviving + alarm, so it does not repair a command this node missed. The next process restart does. +- **Known state (A1) is unchanged.** Every reload still clears the established set and re-raises + `OnInputsEstablished` after the first completed evaluation. The host holds it until the post-load re-assert. Every mutation the state machine produces is immediately persisted inside the engine's `_evalGate` semaphore, so the store's view is always consistent with the in-memory state. ### Post-(re)load condition-node re-assert (#487) A deploy that triggers a **full address-space rebuild** clears `_alarmConditions` and re-materialises every -condition node fresh — inactive, acked, confirmed, unshelved. The engine, reloading in parallel, restores each -alarm's persisted state and re-derives `Active` from the predicate, so it ends up *correct*; but a still-active +condition node fresh — inactive, acked, confirmed, unshelved. The engine, reloading in parallel, restates each +surviving alarm from its previous in-memory condition (#935; persisted state only for an alarm new to the process) and re-derives `Active` from the predicate, so it ends up *correct*; but a still-active alarm has **no transition to report**, so `LoadAsync` yields `EmissionKind.None` and `OnEngineEmission` drops it. Nothing then writes the node. Before this fix, an active alarm with static dependencies read **normal** to every OPC UA client after such a deploy, until its next real transition — which for a static-dependency alarm may @@ -396,7 +430,7 @@ In the v2 actor system, scripted-alarm engine composition is owned by the driver 1. The host reads the generation's `ScriptedAlarm` + `Script` rows and resolves each row's `PredicateScriptId` to produce a `ScriptedAlarmDefinition` list. Unknown or disabled scripts fail fast — the DB publish guarantees referential integrity but this is a belt-and-braces check. 2. A `ScriptedAlarmEngine` is constructed with the upstream-tag source, an `IAlarmStateStore` (production: `EfAlarmActorStateStore`), a shared `ScriptLoggerFactory` keyed to `scripts-*.log`, and the root Serilog logger. 3. `alarmEngine.OnEvent` is wired to the historian sink. Fire-and-forget — the SQLite store-and-forward sink is already non-blocking. -4. `LoadAsync(alarmDefs)` runs on startup: it compiles every predicate, subscribes to the union of predicate inputs and message-template tokens, seeds the value cache, loads persisted state, re-derives `ActiveState` from a fresh predicate evaluation, and starts the 5s shelving timer. Compile failures are aggregated into one `InvalidOperationException` so operators see every bad predicate in one startup log line rather than one at a time. +4. `LoadAsync(alarmDefs)` runs on startup and on every deploy: it compiles every predicate, subscribes to the union of predicate inputs and message-template tokens, seeds the value cache, seeds each alarm's condition (`previous ?? persisted ?? Fresh`, #935), re-derives `ActiveState` from a fresh predicate evaluation, and starts the 5s shelving timer. Compile failures are aggregated into one `InvalidOperationException` so operators see every bad predicate in one startup log line rather than one at a time. 5. A `ScriptedAlarmSource` is created for the event stream. The v2 `ScriptedAlarmActor` (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmActor.cs`) owns the active-state surface for OPC UA variable reads on the alarm's condition-state node — unknown alarm ids return `BadNodeIdUnknown` rather than silently reading `false`. Both engine and source are disposed on server shutdown via the driver-role host teardown path. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/AlarmConditionState.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/AlarmConditionState.cs index 8b1cc7f91..e34f9ca90 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/AlarmConditionState.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/AlarmConditionState.cs @@ -13,8 +13,9 @@ namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms; /// runs every alarm's predicate against current tag /// values at Load, overriding whatever Active state is in the store. /// Every other state field persists verbatim across server restarts so -/// operators don't re-ack active alarms after an outage + shelved alarms stay -/// shelved + audit history survives. +/// shelved alarms stay shelved + audit history survives. (A still-true alarm is a +/// new occurrence after a restart, since the production store does not persist +/// Active; a same-process redeploy instead restates the in-memory condition, #935.) /// /// /// is append-only; comments + ack/confirm user identities