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