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 8f1eb26d9..b55e6538f 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs
@@ -221,19 +221,15 @@ public sealed class ScriptedAlarmEngine : IDisposable
/// #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;
- ///
- /// #935: the condition state of every alarm of the last completed generation, captured by
- /// before it clears . A same-process reload is a
- /// RESTATEMENT, not a new occurrence: an alarm id that survives the reload is seeded from this (in
- /// preference to the store, which does not persist Active), so a still-true predicate yields no
- /// transition. Kept across a FAILED load (the failed generation is never trusted as a seed) and dropped
- /// when a load completes. Only touched under _evalGate.
- ///
- private Dictionary? _carryOver;
-
// 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
@@ -363,10 +359,12 @@ public sealed class ScriptedAlarmEngine : IDisposable
/// 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 (a redeploy) keeps its in-memory condition, so a
- /// still-true predicate is a restatement (no emission, Ack/Confirm/LastTransitionUtc unchanged);
- /// only an alarm new to this process (first load after a restart, or re-added after a deploy that
- /// removed / disabled it) reads the store, which does not carry Active.
+ /// 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.
@@ -395,15 +393,16 @@ public sealed class ScriptedAlarmEngine : IDisposable
// #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
- // runs against the new generation. A failed previous load leaves _generationComplete false, so its
- // (untrusted, partly Fresh) entries are not captured and the last good snapshot is kept instead.
+ // (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;
+ carryOver = new Dictionary(_alarms.Count, StringComparer.Ordinal);
+ foreach (var (alarmId, prior) in _alarms) carryOver[alarmId] = prior.Condition;
}
_generationComplete = false;
- var carryOver = _carryOver;
UnsubscribeFromUpstream();
_alarms.Clear();
@@ -504,10 +503,11 @@ public sealed class ScriptedAlarmEngine : IDisposable
foreach (var (alarmId, state) in _alarms)
{
var seed = await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false);
- var afterPredicate = await EvaluatePredicateToStateAsync(state, seed, nowUtc: _clock(), ct, pending)
+ 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
@@ -515,20 +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 SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false)));
+ {
+ 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;
- _carryOver = null;
// Subscribe after _loaded = true and full state restore. If an upstream
// implementation pushes its initial value synchronously from inside
@@ -565,11 +569,46 @@ public sealed class ScriptedAlarmEngine : IDisposable
/// 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(
+ private async Task SeedAsync(
string alarmId, AlarmState state, Dictionary? carryOver, CancellationToken ct)
{
- if (carryOver is not null && carryOver.TryGetValue(alarmId, out var previous)) return previous;
- return await _store.LoadAsync(alarmId, ct).ConfigureAwait(false) ?? state.Condition;
+ 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;
}
///
@@ -702,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
@@ -898,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)
{
@@ -912,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.
@@ -1089,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] };
@@ -1684,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
index 861b2c3bb..887c0dc14 100644
--- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs
+++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs
@@ -29,12 +29,22 @@ public sealed class ScriptedAlarmEngineReloadRestatementTests
public int Loads;
- public Task LoadAsync(string alarmId, CancellationToken ct)
+ /// 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);
- return Task.FromResult(_rows.TryGetValue(alarmId, out var r)
+ if (OnLoad is { } hook) await hook(alarmId);
+ return _rows.TryGetValue(alarmId, out var r)
? r with { Active = AlarmActiveState.Inactive, LastActiveUtc = null, LastClearedUtc = null }
- : null);
+ : null;
}
public Task> LoadAllAsync(CancellationToken ct)
@@ -42,6 +52,7 @@ public sealed class ScriptedAlarmEngineReloadRestatementTests
public Task SaveAsync(AlarmConditionState state, CancellationToken ct)
{
+ Saves.Enqueue(state);
_rows[state.AlarmId] = state;
return Task.CompletedTask;
}
@@ -124,7 +135,7 @@ public sealed class ScriptedAlarmEngineReloadRestatementTests
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"]);
- // Persisted too, so a later process restart still restores the ack.
+ // 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);
}
@@ -257,22 +268,247 @@ public sealed class ScriptedAlarmEngineReloadRestatementTests
(rig.Store.Loads - loads).ShouldBe(1);
}
- /// A failed reload (compile error) leaves a half-built, Fresh-seeded generation. It must not become the
- /// seed: the next good load still restates from the last COMPLETED generation.
+ /// #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_keeps_the_last_good_generation_as_the_seed()
+ public async Task A_failed_reload_ends_the_generation_so_the_next_good_load_reads_the_store()
{
using var rig = new Rig();
- var before = await ActiveAndAcked(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.Acked.ShouldBe(AlarmAckedState.Acknowledged);
- after.LastTransitionUtc.ShouldBe(before.LastTransitionUtc);
+ 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
@@ -307,10 +543,14 @@ public sealed class ScriptedAlarmEngineReloadRestatementTests
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
- await WaitFor(() => rig.Events.Any(e => e.Emission == EmissionKind.QualityChanged)
- && rig.Engine.GetState("HighTemp")!.Acked == AlarmAckedState.Acknowledged
+ // 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);
}
@@ -330,6 +570,27 @@ public sealed class ScriptedAlarmEngineReloadRestatementTests
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
{