fix(scripted-alarms): a same-process reload restates a surviving alarm from its in-memory condition (#935)

ScriptedAlarmEngine.LoadAsync runs on every deploy and used to seed each alarm
from IAlarmStateStore, which in production does not persist Active. A
still-true predicate then made every deploy an Inactive->Active transition:
Acked reset, Activated emission (duplicate alerts row), LastTransitionUtc moved.

Seed is now previous ?? persisted ?? Fresh: the last COMPLETED generation's
in-memory condition is captured under _evalGate before the clear and kept
across a failed load. Process restart is unchanged.
This commit is contained in:
Joseph Doherty
2026-11-25 10:54:45 -05:00
parent 179881f45c
commit ec245b84a9
2 changed files with 419 additions and 8 deletions
@@ -217,6 +217,23 @@ public sealed class ScriptedAlarmEngine : IDisposable
private Timer? _shelvingTimer;
private bool _loaded;
/// <summary>
/// #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>.
/// </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
@@ -343,9 +360,13 @@ public sealed class ScriptedAlarmEngine : IDisposable
/// <summary>
/// Load a batch of alarm definitions. Compiles every predicate, aggregates any
/// compile failures into one <see cref="InvalidOperationException"/>, subscribes
/// to upstream input tags, seeds the value cache, loads persisted state from
/// the store (falling back to Fresh for first-load alarms), and recomputes
/// ActiveState from the current predicate (startup recovery).
/// to upstream input tags, seeds the value cache, seeds each alarm's condition, and
/// recomputes ActiveState from the current predicate (startup recovery).
/// <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>
/// </summary>
/// <param name="definitions">The alarm definitions to load.</param>
/// <param name="ct">The cancellation token.</param>
@@ -371,6 +392,19 @@ public sealed class ScriptedAlarmEngine : IDisposable
_shelvingTimer?.Dispose();
_shelvingTimer = null;
// #935: capture the live generation's conditions BEFORE clearing — a surviving alarm id is seeded
// from them below (previous ?? persisted ?? Fresh). Taken under _evalGate, so it reflects every
// evaluation / operator command that completed before this load; anything queued behind the gate
// 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.
if (_generationComplete)
{
_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();
_alarmsReferencing.Clear();
@@ -459,8 +493,9 @@ public sealed class ScriptedAlarmEngine : IDisposable
foreach (var path in _alarmsReferencing.Keys)
_valueCache[path] = _upstream.ReadTag(path);
// Restore persisted state, falling back to Fresh where nothing was saved,
// then re-derive ActiveState from the current predicate.
// Restore state — the previous generation's in-memory condition for a surviving alarm id (#935: a
// same-process reload is a restatement), else the persisted state (a process restart, or an alarm new
// to this process), else Fresh — then re-derive ActiveState from the current predicate.
// Any predicate emissions queue into `pending` and fire after the gate
// is released — so a startup-recovery activation event can call back into
// the engine without deadlocking.
@@ -468,8 +503,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
{
foreach (var (alarmId, state) in _alarms)
{
var persisted = await _store.LoadAsync(alarmId, ct).ConfigureAwait(false);
var seed = persisted ?? state.Condition;
var seed = await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false);
var afterPredicate = await EvaluatePredicateToStateAsync(state, seed, nowUtc: _clock(), ct, pending)
.ConfigureAwait(false);
_alarms[alarmId] = state with { Condition = afterPredicate };
@@ -482,7 +516,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
// same order the serial loop above uses.
var seeds = new List<(AlarmState State, AlarmConditionState Seed)>(_alarms.Count);
foreach (var (alarmId, state) in _alarms)
seeds.Add((state, await _store.LoadAsync(alarmId, ct).ConfigureAwait(false) ?? state.Condition));
seeds.Add((state, await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false)));
var after = await EvaluatePredicateBatchToStatesAsync(seeds, _clock(), ct, pending).ConfigureAwait(false);
for (var i = 0; i < seeds.Count; i++)
{
@@ -493,6 +527,8 @@ public sealed class ScriptedAlarmEngine : IDisposable
}
_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
@@ -520,6 +556,22 @@ public sealed class ScriptedAlarmEngine : IDisposable
FirePending(pending);
}
/// <summary>
/// #935: the state a loaded alarm starts its first evaluation from — <c>previous ?? persisted ?? Fresh</c>.
/// The previous generation's in-memory condition wins for a surviving alarm id: it is exactly what this node
/// is already serving (every node receives every operator command), and it still knows <c>Active</c>, which
/// the production store does not persist. Seeding from the store instead turned every deploy into an
/// Inactive→Active transition for a still-active alarm (Acked reset, <c>Activated</c> emission, a new
/// <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(
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;
}
/// <summary>
/// Current persisted state for <paramref name="alarmId"/>. Returns null for
/// unknown alarm. Mainly used for diagnostics + the Admin UI status page.