fix(scripted-alarms): #935 review round 1 — commands look up under the gate, a restatement writes nothing, a failed load ends the generation

S1: ApplyAsync looked its alarm up before taking _evalGate, so a command racing a
LoadAsync applied to the load's interim Fresh entry (an ack no-op that then saved Fresh
over the carried Active condition — the #935 re-Activate on the next push) or wrote an
old-generation state over the new one. The lookup is now under the gate: a command
queued behind a load applies to the generation that load produced. A command that
changes nothing (value-equal result) writes nothing.

S2: a load re-saved every alarm's post-predicate state, so a node that missed an
operator command upserted its stale carried state over the LocalDb last-writer-wins row
on every deploy. A held seed (carried or persisted) left value-equal is not written.
The push path's ReferenceEquals check (always false: ApplyPredicate returns a clone)
is now value equality too, so a no-op re-evaluation no longer writes/replicates.

S3: a failed load ends the generation. The engine is blind until the next good load,
so (decision, same rule as removed/disabled alarms) that load reads the store — a
still-true alarm is a new occurrence — instead of restating the pre-failure snapshot.
While blind, operator commands throw ScriptedAlarmCommandRejectedException (the host
logs it distinctly; the command topic is fire-and-forget, so that Warning is the
record) and queued re-evaluations / shelving checks are dropped.

N5: a timed shelve that expired before a load is unshelved through the shelving check
(AutoUnshelve audit + Unshelved emission), not silently by ApplyPredicate.

Tests (each red on revert, verified): ack racing a held load (S1), idempotent command
(S1), restatement vs real change saves (S2), no-op push saves (S2), command rejected
after failed load (S3), re-evaluation after failed load (S3), failed load -> new
occurrence + store fault mid-seed -> one Activated (S3/S4), runner Unavailable at
reload freezes carried state (S4), expired timed shelve at load (N5). N4: the Bad-input
reload test now waits on a Good-bucket QualityChanged.
This commit is contained in:
Joseph Doherty
2026-11-25 11:44:20 -05:00
parent f0526753ac
commit 02d227cc32
5 changed files with 402 additions and 49 deletions
@@ -0,0 +1,21 @@
namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
/// <summary>
/// #935 review S3: an operator command (acknowledge, confirm, shelve, enable/disable, comment) refused because the
/// engine's last <see cref="ScriptedAlarmEngine.LoadAsync"/> 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
/// <c>Fresh</c> 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.
/// </summary>
public sealed class ScriptedAlarmCommandRejectedException : InvalidOperationException
{
/// <summary>Creates the rejection for <paramref name="alarmId"/>.</summary>
/// <param name="alarmId">The alarm the command was for.</param>
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;
/// <summary>The alarm the rejected command was for.</summary>
public string AlarmId { get; }
}
@@ -221,19 +221,15 @@ public sealed class ScriptedAlarmEngine : IDisposable
/// #935: whether <see cref="_alarms"/> holds a COMPLETED generation — set at the end of a successful
/// <see cref="LoadAsync"/>, cleared as soon as a load starts mutating <see cref="_alarms"/>. Only touched
/// under <c>_evalGate</c>.
/// <para>While it is false after a FAILED load (the engine is unsubscribed, its timer stopped, and
/// <see cref="_alarms"/> holds a half-built Fresh-seeded generation) the engine is BLIND: operator commands are
/// rejected (<see cref="ScriptedAlarmCommandRejectedException"/>), 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).</para>
/// </summary>
private bool _generationComplete;
/// <summary>
/// #935: the condition state of every alarm of the last completed generation, captured by
/// <see cref="LoadAsync"/> before it clears <see cref="_alarms"/>. 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 <c>Active</c>), 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 <c>_evalGate</c>.
/// </summary>
private Dictionary<string, AlarmConditionState>? _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).
/// <para>#935: the seed is <c>previous ?? persisted ?? Fresh</c>. 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.</para>
/// 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.</para>
/// </summary>
/// <param name="definitions">The alarm definitions to load.</param>
/// <param name="ct">The cancellation token.</param>
@@ -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<string, AlarmConditionState>? carryOver = null;
if (_generationComplete)
{
_carryOver = new Dictionary<string, AlarmConditionState>(_alarms.Count, StringComparer.Ordinal);
foreach (var (alarmId, prior) in _alarms) _carryOver[alarmId] = prior.Condition;
carryOver = new Dictionary<string, AlarmConditionState>(_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<LoadSeed>(_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
/// <c>LastTransitionUtc</c>). 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.
/// </summary>
private async Task<AlarmConditionState> SeedAsync(
private async Task<LoadSeed> SeedAsync(
string alarmId, AlarmState state, Dictionary<string, AlarmConditionState>? 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);
}
/// <summary>
/// A load's seed for one alarm. <see cref="Held"/>: 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 <c>Fresh</c> for an alarm with no row.
/// </summary>
private readonly record struct LoadSeed(AlarmConditionState State, bool Held);
/// <summary>
/// #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: <see cref="Part9StateMachine.ApplyPredicate"/> always returns a <c>with</c>
/// clone. Persist-before-update ordering is kept by the caller.
/// </summary>
private Task SaveLoadedAsync(LoadSeed seed, AlarmConditionState after, CancellationToken ct)
=> seed.Held && after.Equals(seed.State) ? Task.CompletedTask : _store.SaveAsync(after, ct);
/// <summary>
/// #935 review N5: a timed shelve whose expiry passed before (or during) a load is unshelved through the
/// shelving check — with its <c>AutoUnshelve</c> audit comment and its <c>Unshelved</c> emission — before the
/// predicate runs. Otherwise <see cref="Part9StateMachine.ApplyPredicate"/>'s own expiry silently unshelved it
/// (no audit entry, no event) and the shelving timer found nothing left to expire.
/// </summary>
private AlarmConditionState ExpireTimedShelveAtLoad(
AlarmState state, AlarmConditionState seed, List<ScriptedAlarmEvent> 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;
}
/// <summary>
@@ -702,20 +741,32 @@ public sealed class ScriptedAlarmEngine : IDisposable
private async Task ApplyAsync(string alarmId, CancellationToken ct, Func<AlarmConditionState, TransitionResult> 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)
@@ -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.
@@ -53,8 +53,15 @@ public sealed class FakeUpstream : ITagUpstreamSource
/// <summary>Reads the current value of a tag, or returns a never-pushed snapshot if not set.</summary>
/// <param name="path">The tag path to read.</param>
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);
}
/// <summary>Optional hook run synchronously at the start of every <see cref="ReadTag"/> — lets a test hold a
/// <c>LoadAsync</c> at its value-cache seed, after every alarm entry is in place but before any is seeded.</summary>
public Action<string>? OnRead { get; set; }
/// <summary>Subscribes an observer to tag changes for the given path.</summary>
/// <param name="path">The tag path to subscribe to.</param>
@@ -29,12 +29,22 @@ public sealed class ScriptedAlarmEngineReloadRestatementTests
public int Loads;
public Task<AlarmConditionState?> LoadAsync(string alarmId, CancellationToken ct)
/// <summary>Every saved state, in order (S2: which loads write the replicated row).</summary>
public ConcurrentQueue<AlarmConditionState> Saves { get; } = new();
/// <summary>Optional hook run by <see cref="LoadAsync"/> before it answers — block it (S1) or throw (S4).</summary>
public Func<string, Task>? OnLoad { get; set; }
/// <summary>Overwrites a row directly — what a replicated write from the peer node does.</summary>
public void Put(AlarmConditionState row) => _rows[row.AlarmId] = row;
public async Task<AlarmConditionState?> 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<IReadOnlyList<AlarmConditionState>> 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);
}
/// <summary>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.</summary>
/// <summary>#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).</summary>
[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<InvalidOperationException>(
() => 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)]);
}
/// <summary>#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).</summary>
[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<InvalidOperationException>(
() => rig.Engine.LoadAsync([Alarm(), Alarm("Broken", "return unknownIdentifier;")], Ct));
rig.Store.Saves.Clear();
var ex = await Should.ThrowAsync<ScriptedAlarmCommandRejectedException>(
() => rig.Engine.OneShotShelveAsync("HighTemp", "bob", Ct));
ex.AlarmId.ShouldBe("HighTemp");
await Should.ThrowAsync<ScriptedAlarmCommandRejectedException>(
() => 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);
}
/// <summary>#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).</summary>
[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<InvalidOperationException>(
() => 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");
}
/// <summary>#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).</summary>
[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]);
}
/// <summary>#935 review S1: a command that changes nothing (an uncommented re-ack) writes nothing.</summary>
[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");
}
/// <summary>#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.</summary>
[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");
}
/// <summary>#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.</summary>
[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]);
}
/// <summary>#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.</summary>
[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);
}
/// <summary>#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.</summary>
[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<IOException>(
() => 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)]);
}
/// <summary>#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.</summary>
[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);
}
/// <summary>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();
}
/// <summary><see cref="ThresholdRunner"/> that answers Unavailable (with a recovery) while
/// <see cref="UnavailableUntil"/> is set.</summary>
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<ScriptRunOutcome> RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
=> Task.FromResult(Answer(invocation));
public IReadOnlyList<Task<ScriptRunOutcome>> RunBatch(IReadOnlyList<ScriptInvocation> invocations, CancellationToken ct = default)
=> invocations.Select(i => Task.FromResult(Answer(i))).ToArray();
public void Reset(ScriptContextKind kind) { }
public IReadOnlyCollection<string> QuarantinedKeys(ScriptContextKind kind) => [];
}
/// <summary>Answers <c>Temp &gt; 100</c> for every predicate, in one batch.</summary>
private sealed class ThresholdRunner : IScriptRunner
{