diff --git a/.claude/rules/alarms.md b/.claude/rules/alarms.md
index 7d70f2de3..4f3a5ec8e 100644
--- a/.claude/rules/alarms.md
+++ b/.claude/rules/alarms.md
@@ -75,3 +75,16 @@ 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`). 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, every new **engine incarnation** (process restart or a
+supervision restart of `ScriptedAlarmHostActor`) and the first good load after a **failed** load (the engine was blind) still
+read the store — a new occurrence. Keep (review round 1): `ApplyAsync` looks the alarm up **under** the gate (a lookup before
+it saved a racing load's `Fresh` entry over the carried Active condition); commands throw
+`ScriptedAlarmCommandRejectedException` while a failed load left no trusted generation; a value-equal result (load,
+re-evaluation or command) is not saved — the LocalDb row is replicated last-writer-wins, so re-saving pushed stale state.
+See `docs/ScriptedAlarms.md` §"A redeploy is a restatement".
diff --git a/docs/ScriptedAlarms.md b/docs/ScriptedAlarms.md
index 42f2615cc..0b0ab7008 100644
--- a/docs/ScriptedAlarms.md
+++ b/docs/ScriptedAlarms.md
@@ -155,17 +155,71 @@ 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 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. 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).
-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.
+### 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) **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. 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; 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 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, 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 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
@@ -394,9 +448,9 @@ 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: 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.
@@ -454,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
diff --git a/docs/plans/evidence/followups/935.md b/docs/plans/evidence/followups/935.md
new file mode 100644
index 000000000..2a8e6d252
--- /dev/null
+++ b/docs/plans/evidence/followups/935.md
@@ -0,0 +1,36 @@
+# #935 — scripted alarms re-activated on every deploy: review round 1
+
+Fix under review: `ec245b84a`, `a310ba278`, `f0526753a` (seed `previous ?? persisted ?? Fresh` from the last completed
+load's in-memory conditions). Round 1 fixes: `02d227cc3` (engine + tests), the docs commit after it, and this file.
+
+## Findings and outcomes
+
+| # | Finding | Outcome | Red on revert |
+|---|---|---|---|
+| S1 | `ApplyAsync` looked the alarm up before `_evalGate`; a command racing a load saved the interim `Fresh` entry over the carried Active condition (or an old-generation state over the new one) | **Fixed.** Lookup under the gate; the command applies after the load to the generation it produced (unknown alarm if the deploy removed it). A value-equal result is not saved. | `An_ack_racing_a_reload_applies_to_the_new_generation` (load held at its value-cache seed via `FakeUpstream.OnRead`; pre-fix: HighTemp Inactive after the load). `An_idempotent_command_does_not_write_the_store` red with the equality skip removed. |
+| S2 | Load re-saved every alarm, so a node that missed a command upserted stale carried state over the LocalDb last-writer-wins row on every deploy | **Fixed.** A held seed (carried or persisted) left value-equal is not written. Extended: the push path's `ReferenceEquals` skip (always false: `ApplyPredicate` returns a clone, so every push wrote and replicated) is now value equality. The docs bullet is corrected. | `A_restatement_does_not_write_the_store_but_a_real_change_does`, and `A_runner_unavailable…` (its no-save leg). `A_push_that_changes_nothing_does_not_write_the_store` red with `ReferenceEquals` restored. |
+| S3 | A failed load kept carrying the last good snapshot across an unbounded blind window: commands applied to Fresh were lost, and a clear plus re-fire inside the window was restated as the old occurrence | **Decision: a failed load ends the generation.** The next good load reads the store, so a still-true alarm is a new occurrence. This is the same rule as an alarm a deploy removed or disabled. While blind, commands throw `ScriptedAlarmCommandRejectedException` (nothing persisted), and queued re-evaluations and shelving checks are dropped. The command topic is fire-and-forget, so the caller already has Good: the host logs a distinct Warning, and the next good load re-asserts the node from the store. | `An_operator_command_after_a_failed_reload_is_rejected_and_persists_nothing` (rejection removed). `A_reevaluation_after_a_failed_reload…` (guard removed). `A_failed_reload_ends_the_generation…` and `A_store_fault_mid_seed…` (stale carry restored). |
+| S4 | Missing tests: runner Unavailable at reload, store fault mid-seed then a good load, the S1 race | **Added** (see the rows above). The runner-Unavailable test asserts the carried condition is frozen, annotated BadResourceUnavailable, not established and not saved, then that recovery establishes with no `Activated`. | Runner test: red only through its S2 leg, since the freeze itself was already correct. |
+| N1 | "process restart" in the docs should say "engine incarnation" (a supervision restart of the host actor also builds a fresh engine) | Fixed in `docs/ScriptedAlarms.md`, `.claude/rules/alarms.md` and the `LoadAsync` XML doc | docs |
+| N2 | `EfAlarmActorStateStore` was named as the production store in three places | Fixed: the production store is `LocalDbAlarmConditionStateStore` | docs |
+| N3 | "the store's view is always consistent" | Reworded: persist-before-update on one node, no write for a no-op, last-writer-wins lag across the pair | docs |
+| N4 | `A_reload_whose_input_is_bad…` waited on a `QualityChanged` that the load's Bad annotation already satisfied | It now asserts the Bad annotation at the load and waits on a **Good-bucket** `QualityChanged` | Test-strength only. It was not separately reverted. |
+| N5 | A carried timed shelve that expired before the load was silently unshelved by `ApplyPredicate` | **Fixed** (trivial): the load runs `ApplyShelvingCheck` first, giving an `AutoUnshelve` comment and an `Unshelved` emission | `A_timed_shelve_that_expired_before_a_reload_is_unshelved_with_audit` |
+
+## Accepted consequences
+
+- **A failed deploy is followed by one new occurrence.** After a failed load, the next good deploy re-activates every still-true alarm: `Activated`, Unacknowledged, and one `alerts` row. This is the restart behaviour, and it is the conservative choice because the engine was not evaluating.
+- **Stale fields can still replicate on a real transition.** A node that missed a command keeps its stale fields in memory until its next engine incarnation. A later real transition on that node saves its whole condition, and that write replicates. A restatement no longer does.
+
+## Gates (at `4df38b864`)
+
+| Gate | Result |
+|---|---|
+| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings / 0 errors |
+| Core.ScriptedAlarms.Tests (full) | 145/145 (reload-restatement class 21/21 after the push-save test) |
+| Runtime.Tests (full) | 2084 passed, 3 skipped, 0 failed |
+| OpcUaServer.Tests (full) | 1458 passed, 2 skipped, 0 failed |
+| ScriptWorker.Tests `AlarmSeamTests` + `ShadowModeTests` | 6/6 |
+| `run-unit-phase.py A1` | passed (OpcUaServer 31, Runtime 126, Core.ScriptedAlarms 59, Commons 20, Abstractions 7, Host 40, Galaxy 5, OpcUaClient 5, FOCAS 4) |
+| `run-unit-phase.py A4` | passed |
+| Live, run `fu935-2` (`rig.py up --conditions` → seed → 85 s → `deploy --timeout 300`) | F935 live check PASS (origin + consumer stay Active/Acknowledged across a deploy, no new condition event, same EventId and pre-deploy Time on a fresh refresh, positive-control clear arrives once at each end); `conditions_scenarios.py` A01–A08 8/8 PASS; rig down |
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
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmCommandRejectedException.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmCommandRejectedException.cs
new file mode 100644
index 000000000..8e2d2e073
--- /dev/null
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmCommandRejectedException.cs
@@ -0,0 +1,21 @@
+namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
+
+///
+/// #935 review S3: an operator command (acknowledge, confirm, shelve, enable/disable, comment) refused because the
+/// engine's last failed and it holds no trusted generation — its
+/// entries are a half-built, Fresh-seeded set, so applying the command would persist a state derived from
+/// Fresh over the alarm's real row. The command is not queued: the next successful load reads the store and
+/// re-asserts every condition node, which also undoes whatever the OPC UA method already showed on the node.
+///
+public sealed class ScriptedAlarmCommandRejectedException : InvalidOperationException
+{
+ /// Creates the rejection for .
+ /// The alarm the command was for.
+ public ScriptedAlarmCommandRejectedException(string alarmId)
+ : base($"Command for alarm {alarmId} rejected: the last scripted-alarm load failed, so the engine holds no "
+ + "trusted condition state until the next successful deploy.")
+ => AlarmId = alarmId;
+
+ /// The alarm the rejected command was for.
+ public string AlarmId { get; }
+}
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs
index d66c3a117..b55e6538f 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs
@@ -217,6 +217,19 @@ public sealed class ScriptedAlarmEngine : IDisposable
private Timer? _shelvingTimer;
private bool _loaded;
+ ///
+ /// #935: whether holds a COMPLETED generation — set at the end of a successful
+ /// , cleared as soon as a load starts mutating . Only touched
+ /// under _evalGate.
+ /// While it is false after a FAILED load (the engine is unsubscribed, its timer stopped, and
+ /// holds a half-built Fresh-seeded generation) the engine is BLIND: operator commands are
+ /// rejected (), queued re-evaluations and shelving checks
+ /// are dropped, and the next good load does NOT carry the last good generation over — it reads the store, like
+ /// a new engine incarnation (#935 review S3: the engine stopped evaluating, so a still-true alarm is a new
+ /// occurrence, the same rule as an alarm a deploy removed or disabled).
+ ///
+ private bool _generationComplete;
+
// volatile: written by Dispose and read unsynchronized from every background
// path (LoadAsync's guard, OnUpstreamChange, the drain loop, ReevaluateAsync /
// ShelvingCheckAsync's post-gate re-checks, TrackBackgroundTask's registration
@@ -343,9 +356,15 @@ public sealed class ScriptedAlarmEngine : IDisposable
///
/// Load a batch of alarm definitions. Compiles every predicate, aggregates any
/// compile failures into one , subscribes
- /// to upstream input tags, seeds the value cache, loads persisted state from
- /// the store (falling back to Fresh for first-load alarms), and recomputes
- /// ActiveState from the current predicate (startup recovery).
+ /// to upstream input tags, seeds the value cache, seeds each alarm's condition, and
+ /// recomputes ActiveState from the current predicate (startup recovery).
+ /// #935: the seed is previous ?? persisted ?? Fresh. An alarm id that was loaded in the
+ /// last completed generation of THIS engine incarnation (a redeploy) keeps its in-memory condition, so a
+ /// still-true predicate is a restatement (no emission, Ack/Confirm/LastTransitionUtc unchanged, and no
+ /// store write — review S2); an alarm new to this incarnation (the first load of a new engine — a process
+ /// restart or a supervision restart of the host actor — an alarm re-added after a deploy that removed /
+ /// disabled it, or every alarm on the first good load after a FAILED load, review S3) reads the store,
+ /// which does not carry Active.
///
/// The alarm definitions to load.
/// The cancellation token.
@@ -371,6 +390,20 @@ public sealed class ScriptedAlarmEngine : IDisposable
_shelvingTimer?.Dispose();
_shelvingTimer = null;
+ // #935: capture the live generation's conditions BEFORE clearing — a surviving alarm id is seeded
+ // from them below (previous ?? persisted ?? Fresh). Taken under _evalGate, so it reflects every
+ // evaluation / operator command that completed before this load; anything queued behind the gate
+ // (ApplyAsync looks its alarm up only once it holds the gate) runs against the new generation.
+ // Only a COMPLETED generation is carried: after a failed load there is nothing to carry (review S3 —
+ // the engine was blind since, so the next good load reads the store like a new engine incarnation).
+ Dictionary? carryOver = null;
+ if (_generationComplete)
+ {
+ carryOver = new Dictionary(_alarms.Count, StringComparer.Ordinal);
+ foreach (var (alarmId, prior) in _alarms) carryOver[alarmId] = prior.Condition;
+ }
+ _generationComplete = false;
+
UnsubscribeFromUpstream();
_alarms.Clear();
_alarmsReferencing.Clear();
@@ -459,8 +492,9 @@ public sealed class ScriptedAlarmEngine : IDisposable
foreach (var path in _alarmsReferencing.Keys)
_valueCache[path] = _upstream.ReadTag(path);
- // Restore persisted state, falling back to Fresh where nothing was saved,
- // then re-derive ActiveState from the current predicate.
+ // Restore state — the previous generation's in-memory condition for a surviving alarm id (#935: a
+ // same-process reload is a restatement), else the persisted state (a process restart, or an alarm new
+ // to this process), else Fresh — then re-derive ActiveState from the current predicate.
// Any predicate emissions queue into `pending` and fire after the gate
// is released — so a startup-recovery activation event can call back into
// the engine without deadlocking.
@@ -468,12 +502,12 @@ public sealed class ScriptedAlarmEngine : IDisposable
{
foreach (var (alarmId, state) in _alarms)
{
- var persisted = await _store.LoadAsync(alarmId, ct).ConfigureAwait(false);
- var seed = persisted ?? state.Condition;
- var afterPredicate = await EvaluatePredicateToStateAsync(state, seed, nowUtc: _clock(), ct, pending)
+ var seed = await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false);
+ var evalSeed = ExpireTimedShelveAtLoad(state, seed.State, pending);
+ var afterPredicate = await EvaluatePredicateToStateAsync(state, evalSeed, nowUtc: _clock(), ct, pending)
.ConfigureAwait(false);
+ await SaveLoadedAsync(seed, afterPredicate, ct).ConfigureAwait(false);
_alarms[alarmId] = state with { Condition = afterPredicate };
- await _store.SaveAsync(afterPredicate, ct).ConfigureAwait(false);
}
}
else
@@ -481,18 +515,24 @@ public sealed class ScriptedAlarmEngine : IDisposable
// Out of process: every predicate goes in one batch, then each alarm is applied and saved in the
// same order the serial loop above uses.
var seeds = new List<(AlarmState State, AlarmConditionState Seed)>(_alarms.Count);
+ var sources = new List(_alarms.Count);
foreach (var (alarmId, state) in _alarms)
- seeds.Add((state, await _store.LoadAsync(alarmId, ct).ConfigureAwait(false) ?? state.Condition));
+ {
+ var seed = await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false);
+ sources.Add(seed);
+ seeds.Add((state, ExpireTimedShelveAtLoad(state, seed.State, pending)));
+ }
var after = await EvaluatePredicateBatchToStatesAsync(seeds, _clock(), ct, pending).ConfigureAwait(false);
for (var i = 0; i < seeds.Count; i++)
{
var state = seeds[i].State;
+ await SaveLoadedAsync(sources[i], after[i], ct).ConfigureAwait(false);
_alarms[state.Definition.AlarmId] = state with { Condition = after[i] };
- await _store.SaveAsync(after[i], ct).ConfigureAwait(false);
}
}
_loaded = true;
+ _generationComplete = true;
// Subscribe after _loaded = true and full state restore. If an upstream
// implementation pushes its initial value synchronously from inside
@@ -520,6 +560,57 @@ public sealed class ScriptedAlarmEngine : IDisposable
FirePending(pending);
}
+ ///
+ /// #935: the state a loaded alarm starts its first evaluation from — previous ?? persisted ?? Fresh.
+ /// The previous generation's in-memory condition wins for a surviving alarm id: it is exactly what this node
+ /// is already serving (every node receives every operator command), and it still knows Active, which
+ /// the production store does not persist. Seeding from the store instead turned every deploy into an
+ /// Inactive→Active transition for a still-active alarm (Acked reset, Activated emission, a new
+ /// LastTransitionUtc). Identity is the alarm id alone — an edited predicate, severity, message or
+ /// placement is the same alarm, and its new predicate decides the next transition.
+ ///
+ private async Task SeedAsync(
+ string alarmId, AlarmState state, Dictionary? carryOver, CancellationToken ct)
+ {
+ if (carryOver is not null && carryOver.TryGetValue(alarmId, out var previous)) return new(previous, Held: true);
+ var persisted = await _store.LoadAsync(alarmId, ct).ConfigureAwait(false);
+ return persisted is null ? new(state.Condition, Held: false) : new(persisted, Held: true);
+ }
+
+ ///
+ /// A load's seed for one alarm. : the seed is a state the store already has from this node's
+ /// point of view — the previous generation's condition (persisted when it was reached) or the persisted row
+ /// itself — as opposed to Fresh for an alarm with no row.
+ ///
+ private readonly record struct LoadSeed(AlarmConditionState State, bool Held);
+
+ ///
+ /// #935 review S2: persist a loaded alarm's post-predicate state only if the load CHANGED it. A held seed that
+ /// the reload left value-equal (a restatement) is not written back: the store row is replicated last-writer-wins
+ /// (LocalDb), so re-saving a node's carried condition on every deploy would push a node that missed an operator
+ /// command back over the converged row on every deploy — and costs one replicated write per alarm per deploy.
+ /// Value equality, not reference: always returns a with
+ /// clone. Persist-before-update ordering is kept by the caller.
+ ///
+ private Task SaveLoadedAsync(LoadSeed seed, AlarmConditionState after, CancellationToken ct)
+ => seed.Held && after.Equals(seed.State) ? Task.CompletedTask : _store.SaveAsync(after, ct);
+
+ ///
+ /// #935 review N5: a timed shelve whose expiry passed before (or during) a load is unshelved through the
+ /// shelving check — with its AutoUnshelve audit comment and its Unshelved emission — before the
+ /// predicate runs. Otherwise 's own expiry silently unshelved it
+ /// (no audit entry, no event) and the shelving timer found nothing left to expire.
+ ///
+ private AlarmConditionState ExpireTimedShelveAtLoad(
+ AlarmState state, AlarmConditionState seed, List pendingEmissions)
+ {
+ var check = Part9StateMachine.ApplyShelvingCheck(seed, _clock());
+ if (check.Emission == EmissionKind.None) return seed;
+ var evt = BuildEmission(state, check.State, check.Emission, LastWorstStatus(state.Definition.AlarmId));
+ if (evt is not null) pendingEmissions.Add(evt);
+ return check.State;
+ }
+
///
/// Current persisted state for . Returns null for
/// unknown alarm. Mainly used for diagnostics + the Admin UI status page.
@@ -650,20 +741,32 @@ public sealed class ScriptedAlarmEngine : IDisposable
private async Task ApplyAsync(string alarmId, CancellationToken ct, Func op)
{
EnsureLoaded();
- if (!_alarms.TryGetValue(alarmId, out var state))
- throw new ArgumentException($"Unknown alarm {alarmId}", nameof(alarmId));
ScriptedAlarmEvent? pending = null;
await _evalGate.WaitAsync(ct).ConfigureAwait(false);
try
{
+ // #935 review S1: look the alarm up only once the gate is held. Looked up before it, a command racing a
+ // LoadAsync captured either the old generation's entry (and wrote its state over the new one) or the
+ // load's interim Fresh entry (and, an ack being a no-op on Fresh, saved Fresh over the carried Active
+ // condition — known-inactive while active at the origin, then a second Activated on the next push). Now
+ // a command queued behind a load applies to the generation that load produced.
+ if (!_generationComplete)
+ throw new ScriptedAlarmCommandRejectedException(alarmId);
+ if (!_alarms.TryGetValue(alarmId, out var state))
+ throw new ArgumentException($"Unknown alarm {alarmId}", nameof(alarmId));
+
var result = op(state.Condition);
// Persist BEFORE updating in-memory so a store failure leaves both
// in-memory and persisted at the prior state rather than diverging.
// If SaveAsync throws the in-memory _alarms entry stays unchanged and
- // the exception propagates to the caller.
- await _store.SaveAsync(result.State, ct).ConfigureAwait(false);
- _alarms[alarmId] = state with { Condition = result.State };
+ // the exception propagates to the caller. A command that changed nothing
+ // (an idempotent re-ack / re-shelve) writes nothing — the row already holds it.
+ if (!result.State.Equals(state.Condition))
+ {
+ await _store.SaveAsync(result.State, ct).ConfigureAwait(false);
+ _alarms[alarmId] = state with { Condition = result.State };
+ }
// Build the emission event under the gate (it captures a coherent
// snapshot of state + message-template values) but defer the actual
// OnEvent dispatch until after Release() so a slow subscriber or a
@@ -846,7 +949,9 @@ public sealed class ScriptedAlarmEngine : IDisposable
// Re-check after acquiring the gate: a Dispose() call may have
// completed between our _evalGate.WaitAsync and here. Writing to a
// disposing store or mutating _alarms after clear is unsafe.
- if (_disposed) return;
+ // #935 review S3: nor is evaluating the half-built generation a failed load left
+ // (Fresh seeds — an Activated emission from one is a phantom occurrence).
+ if (_disposed || !_generationComplete) return;
if (_runner is not null)
{
@@ -860,7 +965,9 @@ public sealed class ScriptedAlarmEngine : IDisposable
if (!_alarms.TryGetValue(id, out var state)) continue;
var newState = await EvaluatePredicateToStateAsync(
state, state.Condition, _clock(), ct, pending).ConfigureAwait(false);
- if (!ReferenceEquals(newState, state.Condition))
+ // Value equality: ApplyPredicate returns a `with` clone even when nothing
+ // changed, so a reference check saved (and replicated) on every push.
+ if (!newState.Equals(state.Condition))
{
// Persist before updating in-memory so a store failure leaves
// both sides at the prior state.
@@ -1037,7 +1144,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
for (var i = 0; i < items.Count; i++)
{
var (state, seed) = items[i];
- if (ReferenceEquals(after[i], seed)) continue;
+ if (after[i].Equals(seed)) continue;
// Persist before updating in-memory so a store failure leaves both sides at the prior state.
await _store.SaveAsync(after[i], ct).ConfigureAwait(false);
_alarms[state.Definition.AlarmId] = state with { Condition = after[i] };
@@ -1632,7 +1739,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
// running callbacks, so a shelving-check callback that passed the _disposed
// check in RunShelvingCheck can arrive here after Dispose() has returned.
// Mutating _alarms or saving to a disposed store here is unsafe.
- if (_disposed) return;
+ if (_disposed || !_generationComplete) return;
var now = _clock();
foreach (var id in alarmIds)
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs
index a30374476..9f4aa2223 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs
@@ -812,6 +812,15 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
_log.Warning("ScriptedAlarmHost: engine op {Op} for alarm {AlarmId} timed out after {Timeout} — the condition-state store is stalled",
cmd.Operation, cmd.AlarmId, _commandTimeout);
}
+ catch (ScriptedAlarmCommandRejectedException ex)
+ {
+ // #935 review S3: the last LoadAsync failed, so the engine holds no trusted state and refuses the
+ // command rather than persist one derived from a Fresh seed. The command is a fire-and-forget topic
+ // broadcast (the OPC UA method / AdminUI already returned), so this Warning is the operator-visible
+ // record; the next successful deploy re-asserts the condition node from the store.
+ _log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} NOT applied — {Reason}",
+ cmd.Operation, cmd.AlarmId, ex.Message);
+ }
catch (Exception ex)
{
// A failing engine op must not crash the actor — mirror OnLoadFailed's log-and-stay-inert style.
diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/FakeUpstream.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/FakeUpstream.cs
index 61316199a..58a691840 100644
--- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/FakeUpstream.cs
+++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/FakeUpstream.cs
@@ -53,8 +53,15 @@ public sealed class FakeUpstream : ITagUpstreamSource
/// Reads the current value of a tag, or returns a never-pushed snapshot if not set.
/// The tag path to read.
public DataValueSnapshot ReadTag(string path)
- => _values.TryGetValue(path, out var v) ? v
+ {
+ OnRead?.Invoke(path);
+ return _values.TryGetValue(path, out var v) ? v
: new DataValueSnapshot(null, StatusNeverPushed, null, DateTime.UtcNow);
+ }
+
+ /// Optional hook run synchronously at the start of every — lets a test hold a
+ /// LoadAsync at its value-cache seed, after every alarm entry is in place but before any is seeded.
+ public Action? OnRead { get; set; }
/// Subscribes an observer to tag changes for the given path.
/// The tag path to subscribe to.
diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs
new file mode 100644
index 000000000..887c0dc14
--- /dev/null
+++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs
@@ -0,0 +1,620 @@
+using System.Collections.Concurrent;
+using Serilog;
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
+using ZB.MOM.WW.OtOpcUa.Core.Scripting;
+
+namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests;
+
+///
+/// #935 — a same-process reload (every deploy runs ) is a
+/// RESTATEMENT, not a new occurrence. The production store does not persist Active, so seeding a surviving
+/// alarm from the store turned every deploy into an Inactive→Active transition: Acked reset to Unacknowledged, an
+/// Activated emission (a duplicate alerts / historian row), and LastTransitionUtc moved to the
+/// deploy instant. A surviving alarm id is now seeded from the engine's previous in-memory condition
+/// (previous ?? persisted ?? Fresh); a process restart keeps the documented persisted-state behaviour.
+///
+[Trait("Category", "Unit")]
+public sealed class ScriptedAlarmEngineReloadRestatementTests
+{
+ private const string Hot = """return (int)ctx.GetTag("Temp").Value > 100;""";
+ private static CancellationToken Ct => TestContext.Current.CancellationToken;
+
+ /// Behaves like LocalDbAlarmConditionStateStore: there is no Active column, so a loaded row is
+ /// Inactive with no LastActive/LastCleared — which is exactly what made every reload re-activate.
+ private sealed class ActiveDroppingStore : IAlarmStateStore
+ {
+ private readonly ConcurrentDictionary _rows = new(StringComparer.Ordinal);
+
+ public int Loads;
+
+ /// Every saved state, in order (S2: which loads write the replicated row).
+ public ConcurrentQueue Saves { get; } = new();
+
+ /// Optional hook run by before it answers — block it (S1) or throw (S4).
+ public Func? OnLoad { get; set; }
+
+ /// Overwrites a row directly — what a replicated write from the peer node does.
+ public void Put(AlarmConditionState row) => _rows[row.AlarmId] = row;
+
+ public async Task LoadAsync(string alarmId, CancellationToken ct)
+ {
+ Interlocked.Increment(ref Loads);
+ if (OnLoad is { } hook) await hook(alarmId);
+ return _rows.TryGetValue(alarmId, out var r)
+ ? r with { Active = AlarmActiveState.Inactive, LastActiveUtc = null, LastClearedUtc = null }
+ : null;
+ }
+
+ public Task> LoadAllAsync(CancellationToken ct)
+ => Task.FromResult>(_rows.Values.ToArray());
+
+ public Task SaveAsync(AlarmConditionState state, CancellationToken ct)
+ {
+ Saves.Enqueue(state);
+ _rows[state.AlarmId] = state;
+ return Task.CompletedTask;
+ }
+
+ public Task RemoveAsync(string alarmId, CancellationToken ct)
+ {
+ _rows.TryRemove(alarmId, out _);
+ return Task.CompletedTask;
+ }
+ }
+
+ /// A stepping clock, so "unchanged LastTransitionUtc" is not satisfied by two reads in the same tick.
+ private sealed class StepClock
+ {
+ private DateTime _now = new(2026, 11, 25, 8, 0, 0, DateTimeKind.Utc);
+ public DateTime Now() => _now = _now.AddSeconds(1);
+ }
+
+ private sealed class Rig : IDisposable
+ {
+ public FakeUpstream Up { get; } = new();
+ public ActiveDroppingStore Store { get; }
+ public StepClock Clock { get; } = new();
+ public ScriptedAlarmEngine Engine { get; }
+ public ConcurrentQueue Events { get; } = new();
+ public ConcurrentQueue Flips { get; } = new();
+
+ public Rig(ActiveDroppingStore? store = null, IScriptRunner? runner = null)
+ {
+ Store = store ?? new ActiveDroppingStore();
+ var logger = new LoggerConfiguration().CreateLogger();
+ Engine = new ScriptedAlarmEngine(Up, Store, new ScriptLoggerFactory(logger), logger, Clock.Now,
+ scriptRunner: runner);
+ Engine.OnEvent += (_, e) => Events.Enqueue(e);
+ Engine.OnInputsEstablished += (_, e) => Flips.Enqueue($"{e.AlarmId}:{e.Established}");
+ }
+
+ public void Dispose() => Engine.Dispose();
+ }
+
+ private static ScriptedAlarmDefinition Alarm(string id = "HighTemp", string predicate = Hot,
+ AlarmSeverity severity = AlarmSeverity.High, string message = "hot", string equipment = "Plant/Line1/Reactor") =>
+ new(AlarmId: id, EquipmentPath: equipment, AlarmName: id, Kind: AlarmKind.AlarmCondition,
+ Severity: severity, MessageTemplate: message, PredicateScriptSource: predicate);
+
+ /// Activate (Temp=150 at load) and acknowledge — the state an operator leaves behind before a deploy.
+ private static async Task ActiveAndAcked(Rig rig, params ScriptedAlarmDefinition[] defs)
+ {
+ rig.Up.Set("Temp", 150);
+ await rig.Engine.LoadAsync(defs.Length == 0 ? [Alarm()] : defs, Ct);
+ rig.Engine.GetState("HighTemp")!.Active.ShouldBe(AlarmActiveState.Active);
+ await rig.Engine.AcknowledgeAsync("HighTemp", "alice", "seen", Ct);
+ var before = rig.Engine.GetState("HighTemp")!;
+ before.Acked.ShouldBe(AlarmAckedState.Acknowledged);
+ rig.Events.Clear();
+ rig.Flips.Clear();
+ return before;
+ }
+
+ /// The regression: an acknowledged active alarm survives a reload still Active + Acked, with NO
+ /// emission (so nothing reaches alerts), the same LastTransitionUtc (the condition Time the
+ /// re-assert writes) and no Ack reset — which is what keeps the origin's activation marker from bumping
+ /// (it advances only on an Active rise or an Acked→Unacked fall). Known-state semantics are unchanged: the
+ /// reload still re-raises the established flip once its first evaluation completes.
+ [Fact]
+ public async Task An_acked_active_alarm_survives_a_reload_as_a_restatement()
+ {
+ using var rig = new Rig();
+ var before = await ActiveAndAcked(rig);
+
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+
+ var after = rig.Engine.GetState("HighTemp")!;
+ after.Active.ShouldBe(AlarmActiveState.Active);
+ after.Acked.ShouldBe(AlarmAckedState.Acknowledged, "an operator never re-acks because someone deployed");
+ after.Confirmed.ShouldBe(before.Confirmed);
+ after.LastTransitionUtc.ShouldBe(before.LastTransitionUtc, "condition Time must not move to the deploy instant");
+ after.LastActiveUtc.ShouldBe(before.LastActiveUtc);
+ after.LastAckUser.ShouldBe("alice");
+ after.Comments.ShouldBe(before.Comments);
+ rig.Events.ShouldBeEmpty("a restatement is not a transition — no Activated, so no alerts row");
+ rig.Flips.ShouldBe(["HighTemp:True"]);
+ // The ack was persisted when it was applied, so a later engine incarnation still restores it.
+ (await rig.Store.LoadAsync("HighTemp", Ct))!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
+ }
+
+ /// An unacked active alarm stays exactly that — Unacknowledged, Unconfirmed — with no emission.
+ [Fact]
+ public async Task An_unacked_active_alarm_is_restated_unchanged()
+ {
+ using var rig = new Rig();
+ rig.Up.Set("Temp", 150);
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+ var before = rig.Engine.GetState("HighTemp")!;
+ rig.Events.Clear();
+
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+
+ rig.Engine.GetState("HighTemp").ShouldBe(before);
+ rig.Events.ShouldBeEmpty();
+ }
+
+ /// A predicate that went false while the reload was pending still clears properly: one Cleared
+ /// transition, the ack carried over (Part 9: ack belongs to the occurrence that just cleared).
+ [Fact]
+ public async Task A_predicate_that_went_false_during_the_reload_clears()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+
+ rig.Up.Set("Temp", 50);
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+
+ var after = rig.Engine.GetState("HighTemp")!;
+ after.Active.ShouldBe(AlarmActiveState.Inactive);
+ after.Acked.ShouldBe(AlarmAckedState.Acknowledged);
+ rig.Events.Select(e => e.Emission).ShouldBe([EmissionKind.Cleared]);
+ }
+
+ /// Decision: identity is the alarm id. An edited severity / message / equipment path on the same id is
+ /// the same alarm — its condition carries over (no new occurrence) and the next projection carries the new
+ /// definition.
+ [Fact]
+ public async Task An_edited_definition_with_a_still_true_predicate_is_the_same_alarm()
+ {
+ using var rig = new Rig();
+ var before = await ActiveAndAcked(rig);
+
+ await rig.Engine.LoadAsync([Alarm(
+ predicate: """return (int)ctx.GetTag("Temp").Value > 120;""",
+ severity: AlarmSeverity.Critical, message: "very hot", equipment: "Plant/Line2/Reactor")], Ct);
+
+ var after = rig.Engine.GetState("HighTemp")!;
+ after.Active.ShouldBe(AlarmActiveState.Active);
+ after.Acked.ShouldBe(AlarmAckedState.Acknowledged);
+ after.LastTransitionUtc.ShouldBe(before.LastTransitionUtc);
+ rig.Events.ShouldBeEmpty();
+ var projection = rig.Engine.GetProjections().Single();
+ projection.Severity.ShouldBe(AlarmSeverity.Critical);
+ projection.Message.ShouldBe("very hot");
+ }
+
+ /// …and an edited predicate that is now false is a real clear of that same occurrence.
+ [Fact]
+ public async Task An_edited_predicate_that_is_now_false_clears_the_carried_occurrence()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+
+ await rig.Engine.LoadAsync([Alarm(predicate: """return (int)ctx.GetTag("Temp").Value > 200;""")], Ct);
+
+ rig.Engine.GetState("HighTemp")!.Active.ShouldBe(AlarmActiveState.Inactive);
+ rig.Events.Select(e => e.Emission).ShouldBe([EmissionKind.Cleared]);
+ }
+
+ /// Decision: removed-and-re-added in ONE deploy is indistinguishable from surviving (same id in both
+ /// generations) ⇒ carried. Removed by one deploy (or disabled — the host does not load a disabled plan) and
+ /// re-added by a later one is a NEW occurrence: the engine stopped evaluating it, so it falls back to the
+ /// persisted state exactly like a restart (Active re-derived ⇒ Activated, Unacknowledged).
+ [Fact]
+ public async Task An_alarm_absent_from_the_previous_generation_falls_back_to_the_store()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+
+ await rig.Engine.LoadAsync([Alarm("Other", """return false;""")], Ct); // HighTemp removed / disabled
+ rig.Events.Clear();
+ await rig.Engine.LoadAsync([Alarm(), Alarm("Other", """return false;""")], Ct); // re-added
+
+ var after = rig.Engine.GetState("HighTemp")!;
+ after.Active.ShouldBe(AlarmActiveState.Active);
+ after.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
+ rig.Events.Select(e => (e.AlarmId, e.Emission)).ShouldBe([("HighTemp", EmissionKind.Activated)]);
+ }
+
+ /// Shelving (incl. a timed shelve's expiry instant), Confirmed and an operator Disable carry over
+ /// verbatim; the shelving timer restarts with the load and still expires against the carried instant.
+ [Fact]
+ public async Task Shelving_confirm_and_disable_carry_over()
+ {
+ using var rig = new Rig();
+ rig.Up.Set("Temp", 150);
+ await rig.Engine.LoadAsync([Alarm(), Alarm("Disabled", Hot)], Ct);
+ var unshelveAt = new DateTime(2026, 11, 26, 0, 0, 0, DateTimeKind.Utc);
+ await rig.Engine.TimedShelveAsync("HighTemp", "bob", unshelveAt, Ct);
+ await rig.Engine.AcknowledgeAsync("HighTemp", "bob", null, Ct);
+ await rig.Engine.ConfirmAsync("HighTemp", "bob", null, Ct);
+ await rig.Engine.DisableAsync("Disabled", "bob", Ct);
+ var shelved = rig.Engine.GetState("HighTemp")!;
+ var disabled = rig.Engine.GetState("Disabled")!;
+ rig.Events.Clear();
+
+ await rig.Engine.LoadAsync([Alarm(), Alarm("Disabled", Hot)], Ct);
+
+ rig.Engine.GetState("HighTemp").ShouldBe(shelved);
+ rig.Engine.GetState("HighTemp")!.Shelving.ShouldBe(new ShelvingState(ShelvingKind.Timed, unshelveAt));
+ rig.Engine.GetState("HighTemp")!.Confirmed.ShouldBe(AlarmConfirmedState.Confirmed);
+ rig.Engine.GetState("Disabled").ShouldBe(disabled);
+ rig.Events.ShouldBeEmpty();
+ }
+
+ /// The surviving alarm is seeded from memory — the store is not consulted for it (it would answer
+ /// Inactive). A new alarm in the same load still reads the store.
+ [Fact]
+ public async Task A_surviving_alarm_does_not_read_the_store_but_a_new_one_does()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+ var loads = rig.Store.Loads;
+
+ await rig.Engine.LoadAsync([Alarm(), Alarm("New", """return false;""")], Ct);
+
+ (rig.Store.Loads - loads).ShouldBe(1);
+ }
+
+ /// #935 review S3 decision: a failed reload (compile error) ends the generation. The engine was
+ /// unsubscribed and blind from then until the next good load, so — like an alarm a deploy removed or disabled —
+ /// a still-true alarm is a NEW occurrence on that load: seeded from the store (Activated, Unacknowledged), never
+ /// restated from the pre-failure snapshot (which could hide a clear + re-fire inside the window).
+ [Fact]
+ public async Task A_failed_reload_ends_the_generation_so_the_next_good_load_reads_the_store()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+
+ await Should.ThrowAsync(
+ () => rig.Engine.LoadAsync([Alarm(), Alarm("Broken", "return unknownIdentifier;")], Ct));
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+
+ var after = rig.Engine.GetState("HighTemp")!;
+ after.Active.ShouldBe(AlarmActiveState.Active);
+ after.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
+ after.LastAckUser.ShouldBe("alice", "the persisted audit trail survives, as on a restart");
+ rig.Events.Select(e => (e.AlarmId, e.Emission)).ShouldBe([("HighTemp", EmissionKind.Activated)]);
+ }
+
+ /// #935 review S3: while a failed load has left no trusted generation, an operator command is REJECTED
+ /// (a distinct exception the host logs) rather than applied to a Fresh entry and persisted over the real row —
+ /// which the next good load then reads (it used to be discarded by the stale carry-over instead).
+ [Fact]
+ public async Task An_operator_command_after_a_failed_reload_is_rejected_and_persists_nothing()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+ await Should.ThrowAsync(
+ () => rig.Engine.LoadAsync([Alarm(), Alarm("Broken", "return unknownIdentifier;")], Ct));
+ rig.Store.Saves.Clear();
+
+ var ex = await Should.ThrowAsync(
+ () => rig.Engine.OneShotShelveAsync("HighTemp", "bob", Ct));
+ ex.AlarmId.ShouldBe("HighTemp");
+ await Should.ThrowAsync(
+ () => rig.Engine.AddCommentAsync("HighTemp", "bob", "note", Ct));
+
+ rig.Store.Saves.ShouldBeEmpty();
+ (await rig.Store.LoadAsync("HighTemp", Ct))!.Acked.ShouldBe(AlarmAckedState.Acknowledged,
+ "the row still holds alice's ack — not a Fresh-derived state");
+
+ // …and the next good load serves commands again.
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+ await rig.Engine.OneShotShelveAsync("HighTemp", "bob", Ct);
+ rig.Engine.GetState("HighTemp")!.Shelving.Kind.ShouldBe(ShelvingKind.OneShot);
+ }
+
+ /// #935 review S3: a re-evaluation queued behind a failed load does not evaluate its Fresh entries — an
+ /// Activated from one would be a phantom occurrence (and its save would overwrite the real row).
+ [Fact]
+ public async Task A_reevaluation_after_a_failed_reload_does_not_evaluate_the_half_built_generation()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+ await Should.ThrowAsync(
+ () => rig.Engine.LoadAsync([Alarm(), Alarm("Broken", "return unknownIdentifier;")], Ct));
+ rig.Store.Saves.Clear();
+
+ rig.Engine.OnUpstreamChange("Temp", new DataValueSnapshot(170, 0u, DateTime.UtcNow, DateTime.UtcNow));
+ await Task.Delay(500, Ct); // let the drainer run against the failed generation
+ rig.Events.ShouldBeEmpty();
+ rig.Store.Saves.ShouldBeEmpty();
+ // Positive control: a good load afterwards does evaluate (and fires the new-occurrence Activated) — so the
+ // absence below is not just "nothing ran yet".
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+
+ rig.Events.Select(e => e.Emission).ShouldBe([EmissionKind.Activated], "exactly one — from the good load");
+ }
+
+ /// #935 review S1 decision: an operator command racing a LoadAsync is applied AFTER the load, to the
+ /// generation it produced. The alarm is looked up under the gate — looked up before it, the ack captured the
+ /// load's interim Fresh entry, was a no-op on it, and then saved Fresh over the carried Active condition (engine
+ /// Inactive while the predicate is true; the next push re-fired Activated and wrote a duplicate alerts row).
+ [Fact]
+ public async Task An_ack_racing_a_reload_applies_to_the_new_generation()
+ {
+ using var rig = new Rig();
+ rig.Up.Set("Temp", 150);
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+ rig.Engine.GetState("HighTemp")!.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
+ var activatedAt = rig.Engine.GetState("HighTemp")!.LastActiveUtc;
+ rig.Events.Clear();
+
+ // Hold the reload at its value-cache seed: it owns the gate and every entry is the interim Fresh one.
+ using var loadReached = new ManualResetEventSlim();
+ using var release = new ManualResetEventSlim();
+ rig.Up.OnRead = _ => { loadReached.Set(); release.Wait(TimeSpan.FromSeconds(30)); };
+ var load = Task.Run(() => rig.Engine.LoadAsync([Alarm()], Ct), Ct);
+ loadReached.Wait(TimeSpan.FromSeconds(10), Ct).ShouldBeTrue();
+ rig.Up.OnRead = null;
+ rig.Engine.GetState("HighTemp")!.Active.ShouldBe(AlarmActiveState.Inactive, "precondition: the interim entry is Fresh");
+
+ var ack = rig.Engine.AcknowledgeAsync("HighTemp", "alice", "seen", Ct);
+ await Task.Delay(100, Ct);
+ ack.IsCompleted.ShouldBeFalse("the ack waits for the load's gate");
+ release.Set();
+ await load;
+ await ack;
+
+ var after = rig.Engine.GetState("HighTemp")!;
+ after.Active.ShouldBe(AlarmActiveState.Active, "the carried Active condition was not overwritten");
+ after.Acked.ShouldBe(AlarmAckedState.Acknowledged, "the ack applied to the new generation");
+ after.LastAckUser.ShouldBe("alice");
+ after.LastActiveUtc.ShouldBe(activatedAt, "the same occurrence");
+ var row = (await rig.Store.LoadAsync("HighTemp", Ct))!;
+ row.Acked.ShouldBe(AlarmAckedState.Acknowledged);
+
+ rig.Up.Push("Temp", 160); // still true — must stay a non-event
+ await WaitFor(() => rig.Flips.Contains("HighTemp:True"));
+ await Task.Delay(100, Ct);
+ rig.Events.ShouldNotContain(e => e.Emission == EmissionKind.Activated);
+ rig.Events.Where(e => e.AlarmId == "HighTemp").Select(e => e.Emission).ShouldBe([EmissionKind.Acknowledged]);
+ }
+
+ /// #935 review S1: a command that changes nothing (an uncommented re-ack) writes nothing.
+ [Fact]
+ public async Task An_idempotent_command_does_not_write_the_store()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+ rig.Store.Saves.Clear();
+
+ await rig.Engine.AcknowledgeAsync("HighTemp", "bob", null, Ct);
+
+ rig.Store.Saves.ShouldBeEmpty();
+ rig.Engine.GetState("HighTemp")!.LastAckUser.ShouldBe("alice");
+ }
+
+ /// #935 review S2: a restatement writes nothing back. The row is replicated last-writer-wins, so a node
+ /// that missed an operator command (here: the peer's ack replicated into the row, not into this node's memory)
+ /// must not push its stale carried state over the converged row on every deploy — the next engine incarnation
+ /// then restores the peer's ack. A reload that CHANGES the alarm still writes it.
+ [Fact]
+ public async Task A_restatement_does_not_write_the_store_but_a_real_change_does()
+ {
+ using var rig = new Rig();
+ rig.Up.Set("Temp", 150);
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+ var stale = rig.Engine.GetState("HighTemp")!;
+ stale.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
+ // The peer acked; replication delivered its row, this node never saw the command.
+ rig.Store.Put(stale with { Acked = AlarmAckedState.Acknowledged, LastAckUser = "peer" });
+ rig.Store.Saves.Clear();
+
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+
+ rig.Store.Saves.ShouldBeEmpty("an unchanged carried alarm is not re-saved");
+ (await rig.Store.LoadAsync("HighTemp", Ct))!.LastAckUser.ShouldBe("peer", "the converged row is intact");
+
+ rig.Up.Set("Temp", 50);
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+ rig.Store.Saves.Select(s => s.Active).ShouldBe([AlarmActiveState.Inactive], "the clear is persisted");
+ }
+
+ /// #935 review S2 (same rule on the push path): a re-evaluation whose predicate agrees with the held
+ /// condition writes nothing — the reference check it used saved (and replicated) on every push, because
+ /// ApplyPredicate always returns a clone. A push that does change it (a clear) is still persisted.
+ [Fact]
+ public async Task A_push_that_changes_nothing_does_not_write_the_store()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+ rig.Store.Saves.Clear();
+
+ rig.Up.Push("Temp", 160); // still true
+ rig.Up.Push("Temp", 50); // positive control: clears
+ await WaitFor(() => rig.Events.Any(e => e.Emission == EmissionKind.Cleared));
+
+ rig.Store.Saves.Select(x => x.Active).ShouldBe([AlarmActiveState.Inactive]);
+ }
+
+ /// #935 review S4: the out-of-process runner is Unavailable at the reload — the carried condition is
+ /// frozen (Active, Acked, same LastTransitionUtc), annotated BadResourceUnavailable, NOT established and NOT
+ /// re-saved; when the runner recovers the alarm re-evaluates to a non-event and is established.
+ [Fact]
+ public async Task A_runner_unavailable_at_reload_freezes_the_carried_condition_until_recovery()
+ {
+ var runner = new SwitchableRunner();
+ using var rig = new Rig(runner: runner);
+ var before = await ActiveAndAcked(rig);
+ rig.Store.Saves.Clear();
+
+ var recovery = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ runner.UnavailableUntil = recovery.Task;
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+
+ rig.Engine.GetState("HighTemp").ShouldBe(before);
+ rig.Events.Select(e => (e.Emission, e.WorstInputStatusCode))
+ .ShouldBe([(EmissionKind.QualityChanged, 0x80040000u)]);
+ rig.Flips.ShouldBeEmpty("a frozen condition is not established");
+ rig.Store.Saves.ShouldBeEmpty();
+
+ runner.UnavailableUntil = null;
+ recovery.SetResult();
+ await WaitFor(() => rig.Flips.Contains("HighTemp:True"));
+ rig.Engine.GetState("HighTemp")!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
+ rig.Engine.GetState("HighTemp")!.LastTransitionUtc.ShouldBe(before.LastTransitionUtc);
+ rig.Events.ShouldNotContain(e => e.Emission == EmissionKind.Activated);
+ }
+
+ /// #935 review S4: a store fault mid-seed fails the load; the next good load is a new occurrence read
+ /// from the store (the S3 rule), with exactly one Activated — the failed load's own emissions were dropped.
+ [Fact]
+ public async Task A_store_fault_mid_seed_then_a_good_load_is_a_single_new_occurrence()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+ rig.Store.OnLoad = id => id == "New" ? throw new IOException("database is locked") : Task.CompletedTask;
+
+ await Should.ThrowAsync(
+ () => rig.Engine.LoadAsync([Alarm(), Alarm("New", """return false;""")], Ct));
+ rig.Events.ShouldBeEmpty("a failed load fires nothing");
+ rig.Store.OnLoad = null;
+ await rig.Engine.LoadAsync([Alarm(), Alarm("New", """return false;""")], Ct);
+
+ rig.Engine.GetState("HighTemp")!.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
+ rig.Engine.GetState("HighTemp")!.LastAckUser.ShouldBe("alice");
+ rig.Events.Select(e => (e.AlarmId, e.Emission)).ShouldBe([("HighTemp", EmissionKind.Activated)]);
+ }
+
+ /// #935 review N5: a carried timed shelve that expired before the reload is unshelved through the
+ /// shelving check — an AutoUnshelve audit entry and an Unshelved emission — not silently by the predicate.
+ [Fact]
+ public async Task A_timed_shelve_that_expired_before_a_reload_is_unshelved_with_audit()
+ {
+ using var rig = new Rig();
+ await ActiveAndAcked(rig);
+ var soon = rig.Clock.Now().AddSeconds(2);
+ await rig.Engine.TimedShelveAsync("HighTemp", "bob", soon, Ct);
+ rig.Clock.Now(); rig.Clock.Now(); rig.Clock.Now(); // past `soon`
+ rig.Events.Clear();
+
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+
+ var after = rig.Engine.GetState("HighTemp")!;
+ after.Shelving.ShouldBe(ShelvingState.Unshelved);
+ after.Comments.Last().Kind.ShouldBe("AutoUnshelve");
+ rig.Events.Select(e => e.Emission).ShouldBe([EmissionKind.Unshelved]);
+ (await rig.Store.LoadAsync("HighTemp", Ct))!.Shelving.ShouldBe(ShelvingState.Unshelved);
+ }
+
+ /// Process restart is unchanged and documented: a new engine has no previous generation, the store
+ /// does not persist Active, so a still-true predicate is a new occurrence (Activated, Unacknowledged) — while
+ /// the persisted ack audit trail survives.
+ [Fact]
+ public async Task A_process_restart_still_seeds_from_the_store()
+ {
+ var store = new ActiveDroppingStore();
+ using (var first = new Rig(store)) await ActiveAndAcked(first);
+
+ using var restarted = new Rig(store);
+ restarted.Up.Set("Temp", 150);
+ await restarted.Engine.LoadAsync([Alarm()], Ct);
+
+ var s = restarted.Engine.GetState("HighTemp")!;
+ s.Active.ShouldBe(AlarmActiveState.Active);
+ s.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
+ s.LastAckUser.ShouldBe("alice");
+ restarted.Events.Select(e => e.Emission).ShouldBe([EmissionKind.Activated]);
+ }
+
+ /// An input that is not ready at the reload (cold-start guard) holds the CARRIED condition — before
+ /// #935 it held the store's Inactive, silently de-activating the engine and re-firing Activated on the next push.
+ [Fact]
+ public async Task A_reload_whose_input_is_bad_holds_the_carried_condition()
+ {
+ using var rig = new Rig();
+ var before = await ActiveAndAcked(rig);
+
+ rig.Up.Set("Temp", 150, statusCode: 0x80000000u); // Bad
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+ rig.Engine.GetState("HighTemp")!.Active.ShouldBe(AlarmActiveState.Active);
+
+ rig.Events.ShouldContain(e => e.Emission == EmissionKind.QualityChanged && e.WorstInputStatusCode != 0u,
+ "the load annotates the frozen condition Bad");
+
+ rig.Up.Push("Temp", 160); // Good again, still true
+ // N4: wait on the GOOD-bucket QualityChanged the recovery produces — the Bad one above is already queued.
+ await WaitFor(() => rig.Events.Any(e => e.Emission == EmissionKind.QualityChanged && e.WorstInputStatusCode == 0u)
+ && rig.Flips.Contains("HighTemp:True"));
+ rig.Engine.GetState("HighTemp")!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
+ rig.Engine.GetState("HighTemp")!.LastTransitionUtc.ShouldBe(before.LastTransitionUtc);
+ rig.Events.ShouldNotContain(e => e.Emission == EmissionKind.Activated);
+ }
+
+ /// The out-of-process (ScriptedAlarm seam) batch path seeds the same way.
+ [Fact]
+ public async Task The_out_of_process_batch_path_restates_too()
+ {
+ using var rig = new Rig(runner: new ThresholdRunner());
+ var before = await ActiveAndAcked(rig);
+
+ await rig.Engine.LoadAsync([Alarm()], Ct);
+
+ var after = rig.Engine.GetState("HighTemp")!;
+ after.Acked.ShouldBe(AlarmAckedState.Acknowledged);
+ after.LastTransitionUtc.ShouldBe(before.LastTransitionUtc);
+ rig.Events.ShouldBeEmpty();
+ }
+
+ /// that answers Unavailable (with a recovery) while
+ /// is set.
+ private sealed class SwitchableRunner : IScriptRunner
+ {
+ public volatile Task? UnavailableUntil;
+
+ private ScriptRunOutcome Answer(ScriptInvocation i) => UnavailableUntil is { } recovery
+ ? ScriptRunOutcome.Unavailable(ScriptRunOutcome.RunnerUnavailableReason) with { Recovery = recovery }
+ : ScriptRunOutcome.Ok((int)i.Inputs["Temp"].Value! > 100);
+
+ public Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
+ => Task.FromResult(Answer(invocation));
+
+ public IReadOnlyList> RunBatch(IReadOnlyList invocations, CancellationToken ct = default)
+ => invocations.Select(i => Task.FromResult(Answer(i))).ToArray();
+
+ public void Reset(ScriptContextKind kind) { }
+
+ public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => [];
+ }
+
+ /// Answers Temp > 100 for every predicate, in one batch.
+ private sealed class ThresholdRunner : IScriptRunner
+ {
+ private static ScriptRunOutcome Answer(ScriptInvocation i) => ScriptRunOutcome.Ok((int)i.Inputs["Temp"].Value! > 100);
+
+ public Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
+ => Task.FromResult(Answer(invocation));
+
+ public IReadOnlyList> RunBatch(IReadOnlyList invocations, CancellationToken ct = default)
+ => invocations.Select(i => Task.FromResult(Answer(i))).ToArray();
+
+ public void Reset(ScriptContextKind kind) { }
+
+ public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => [];
+ }
+
+ private static async Task WaitFor(Func probe)
+ {
+ var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
+ while (DateTime.UtcNow < deadline)
+ {
+ if (probe()) return;
+ await Task.Delay(10);
+ }
+ throw new TimeoutException("condition not reached");
+ }
+}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostActorTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostActorTests.cs
index 455299d3e..6d4be94e7 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostActorTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostActorTests.cs
@@ -975,4 +975,66 @@ public sealed class ScriptedAlarmHostActorTests : RuntimeActorTestBase
publish.ExpectNoMsg(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken);
}
+
+ // ---------------------------------------------------------------------------------------------
+ // #935 — a redeploy is a restatement. The production store (LocalDb) has no Active column, so the
+ // engine used to re-seed a still-active alarm Inactive on every ApplyScriptedAlarms and re-activate it:
+ // Acked reset, an Activated row on `alerts`, and a re-assert stamped with the deploy instant.
+ // ---------------------------------------------------------------------------------------------
+
+ /// Mirrors LocalDbAlarmConditionStateStore: a loaded row is always Inactive.
+ private sealed class ActiveDroppingStore : IAlarmStateStore
+ {
+ private readonly InMemoryAlarmStateStore _inner = new();
+
+ public async Task LoadAsync(string alarmId, CancellationToken ct)
+ => await _inner.LoadAsync(alarmId, ct) is { } row
+ ? row with { Active = AlarmActiveState.Inactive, LastActiveUtc = null, LastClearedUtc = null }
+ : null;
+
+ public Task> LoadAllAsync(CancellationToken ct) => _inner.LoadAllAsync(ct);
+ public Task SaveAsync(AlarmConditionState state, CancellationToken ct) => _inner.SaveAsync(state, ct);
+ public Task RemoveAsync(string alarmId, CancellationToken ct) => _inner.RemoveAsync(alarmId, ct);
+ }
+
+ /// #935: an acknowledged active alarm, redeployed, is re-asserted still Active + Acknowledged with the
+ /// timestamp of its last real transition (the ack), and nothing reaches alerts.
+ [Fact]
+ public void A_redeploy_restates_an_acked_active_alarm_without_reactivating_it()
+ {
+ var publish = CreateTestProbe();
+ var mux = CreateTestProbe();
+ var alerts = CreateTestProbe();
+ SubscribeToAlerts(alerts);
+ var ct = TestContext.Current.CancellationToken;
+
+ var (host, _) = Spawn(publish, mux, store: new ActiveDroppingStore());
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms(new[] { Plan() }));
+ mux.ExpectMsg(Timeout, cancellationToken: ct);
+
+ host.Tell(new VirtualTagActor.DependencyValueChanged("M.T", 99, DateTime.UtcNow));
+ publish.FishForMessage(
+ m => m.State.Active && !m.State.Acknowledged, Timeout, cancellationToken: ct);
+ alerts.FishForMessage(e => e.TransitionKind == "Activated", Timeout, cancellationToken: ct);
+
+ host.Tell(new AlarmCommand(AlarmId: "alm-1", Operation: "Acknowledge", User: "alice", Comment: null, UnshelveAtUtc: null));
+ publish.FishForMessage(m => m.State.Acknowledged, Timeout, cancellationToken: ct);
+ alerts.FishForMessage(e => e.TransitionKind == "Acknowledged", Timeout, cancellationToken: ct);
+
+ // The deploy.
+ var deployAt = DateTime.UtcNow;
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms(new[] { Plan() }));
+ mux.ExpectMsg(Timeout, cancellationToken: ct);
+
+ var reasserted = publish.ExpectMsg(Timeout, cancellationToken: ct);
+ reasserted.State.Active.ShouldBeTrue();
+ reasserted.State.Acknowledged.ShouldBeTrue("a deploy must not un-acknowledge an operator-acked alarm");
+ // The re-assert carries LastTransitionUtc — the ack instant, before the deploy (it used to be the load instant).
+ reasserted.TimestampUtc.ShouldBeLessThan(deployAt, "condition Time stays at its last real transition, not the deploy");
+ // Known-state semantics unchanged (A1): the reload's held established-flip lands AFTER the re-assert…
+ publish.ExpectMsg(Timeout, cancellationToken: ct).Known.ShouldBeTrue();
+ // …and nothing else follows: no re-activation projection, no alerts row.
+ publish.ExpectNoMsg(TimeSpan.FromMilliseconds(500), ct);
+ alerts.ExpectNoMsg(TimeSpan.FromMilliseconds(500), ct);
+ }
}