docs(scripted-alarms): #935 review round 1 — engine incarnation, failed load ends the generation, commands under the gate, no write-back of a restatement, production store is LocalDb

This commit is contained in:
Joseph Doherty
2026-11-25 11:45:00 -05:00
parent 02d227cc32
commit 4df38b8642
2 changed files with 36 additions and 11 deletions
+29 -9
View File
@@ -155,9 +155,9 @@ Predicate evaluation and message-template resolution deliberately treat tag-inpu
## State persistence
`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`.
`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 `LocalDbAlarmConditionStateStore` (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/LocalDbAlarmConditionStateStore.cs`), which persists to the node's replicated LocalDb (condition row + one row per comment) and mirrors to the redundant pair peer last-writer-wins. It replaced the config-DB `EfAlarmActorStateStore` / `ScriptedAlarmState` table, which no longer exist.
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.
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. For a **new engine incarnation** an alarm whose predicate is still true is therefore a new occurrence: `Activated`, `Unacknowledged`, `LastTransitionUtc` = the load instant — the operator re-acks once. A new incarnation is a process restart **or a supervision restart of `ScriptedAlarmHostActor`** (its Props factory builds a fresh engine, which then re-applies), and the same holds for the first good load after a failed one (below).
### A redeploy is a restatement (#935)
@@ -180,26 +180,46 @@ after a full rebuild, carrying the unchanged `LastTransitionUtc`. Decisions:
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.
- **A failed load** (compile error, store fault) **ends the generation** (review round 1, S3). From then until the next good load
the engine is unsubscribed with its timer stopped — blind — so, by the same rule as a removed or disabled alarm, the next
good load does not carry anything over: it reads the store like a new engine incarnation, and a still-true alarm is a new
occurrence (`Activated`, `Unacknowledged`). Restating the pre-failure snapshot instead would hide an alarm that cleared and
re-fired inside the window. While blind, an operator command is **rejected** with `ScriptedAlarmCommandRejectedException`
(nothing is persisted — applying it to the half-built Fresh entry would overwrite the real row), and queued re-evaluations
and shelving checks are dropped. The command topic is fire-and-forget (the OPC UA method / AdminUI call already returned
Good), so the rejection's only record is the host's Warning `… NOT applied — …`; the next good load re-asserts the node
from the store, undoing whatever the method showed.
- **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.
before the load. An operator command looks its alarm up only once it holds the gate (review S1 — it used to look up first,
so a command racing a load could save the load's interim `Fresh` entry over the carried Active condition), so a command
queued behind a load applies **after** it, to the generation it produced (or is refused as an unknown alarm if the deploy
removed it). A command whose result equals the current condition (an uncommented re-ack) writes nothing.
- **A restatement writes nothing** (review S2). A load persists an alarm only if the load changed it; a carried or persisted
seed left value-equal is not re-saved, and neither is a re-evaluation that left the condition unchanged. The row replicates
last-writer-wins, so re-saving would push a node's stale carried state over the converged row on every deploy (and every
push), and cost one replicated write per alarm per deploy.
- **A timed shelve that expired before the load** is unshelved through the shelving check at the load (an `AutoUnshelve`
comment and an `Unshelved` emission, review N5). Before, the predicate's own expiry unshelved it silently.
- **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.
alarm, so it does not repair a command this node missed; because a restatement is not written back, the converged row is not
overwritten either, and the next engine incarnation reads it. Accepted divergence: a later **real** transition on that node
(its predicate flips, or another command) still saves the node's whole condition, stale fields included, and that write
replicates.
- **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.
Every state change the engine makes is persisted inside the engine's `_evalGate` semaphore **before** the in-memory update (a store failure leaves both at the prior state), and a change that alters nothing is not written. On one node the row therefore matches the engine except where a command was rejected or missed; across the redundant pair the row is last-writer-wins and can lag a node that missed a command (warm standby, above).
### 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, 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
surviving alarm from its previous in-memory condition (#935; persisted state only for an alarm new to the engine incarnation) 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
@@ -428,7 +448,7 @@ Emissions map into `AlarmEventArgs` as `AlarmType = Kind.ToString()`, `SourceNod
In the v2 actor system, scripted-alarm engine composition is owned by the driver-role host:
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.
2. A `ScriptedAlarmEngine` is constructed with the upstream-tag source, an `IAlarmStateStore` (production: `LocalDbAlarmConditionStateStore`), 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 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`.
@@ -488,5 +508,5 @@ apply.
- `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceComposer.cs` — pure data composer: config-DB entities → `AddressSpaceComposition` (UNS topology + raw subtree + driver/alarm plans)
- `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceApplier.cs` — applies the composed plan into the SDK node manager
- `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmActor.cs` — actor that owns the per-alarm state machine; publishes `AlarmTransitionEvent` on the cluster `alerts` DPS topic
- `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/EfAlarmActorStateStore.cs` — production `IAlarmActorStateStore` backed by the `ScriptedAlarmState` config-DB table
- `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/LocalDbAlarmConditionStateStore.cs` — production `IAlarmStateStore` backed by the node's replicated LocalDb
- `src/Server/ZB.MOM.WW.OtOpcUa.Host/Engines/RoslynScriptedAlarmEvaluator.cs` — production Roslyn predicate evaluator