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
@@ -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
{