fix(site-runtime): failed trigger evaluation keeps state, RateOfChange clears when flat, WhileTrue re-fires after seed adoption (SRT-2, SRT-3, SRT-4, WP3 task 3.7)

This commit is contained in:
Joseph Doherty
2026-12-03 10:11:15 -05:00
parent a730bc0558
commit bc7fae2652
6 changed files with 394 additions and 78 deletions
@@ -33,8 +33,11 @@ namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors;
///
/// Supervision: Resume on exception (from the Instance Actor). This actor has no children.
/// </summary>
public class AlarmActor : ReceiveActor
public class AlarmActor : ReceiveActor, IWithTimers
{
/// <inheritdoc />
public ITimerScheduler Timers { get; set; } = null!;
private readonly string _alarmName;
private readonly string _instanceName;
private readonly IActorRef _instanceActor;
@@ -171,6 +174,15 @@ public class AlarmActor : ReceiveActor
private readonly Queue<(DateTimeOffset Timestamp, double Value)> _rateOfChangeWindow = new();
private readonly TimeSpan _rateOfChangeWindowDuration;
/// <summary>
/// SRT-3: the newest sample folded into the rate window, and the wall-clock instant it was
/// processed — so the window-expiry tick can tell how far (in the samples' own time base)
/// the window has advanced since a value that has simply stopped changing.
/// </summary>
private (DateTimeOffset Timestamp, double Value, DateTimeOffset ProcessedAtUtc)? _rateLastSample;
private const string RateWindowTimerKey = "rate-window";
private int _executionCounter;
/// <summary>Initializes a new <see cref="AlarmActor"/> and configures message handlers for the alarm.</summary>
@@ -266,6 +278,9 @@ public class AlarmActor : ReceiveActor
// Handle a faulted off-dispatcher evaluation task (N2) — clears in-flight
// instead of stranding the alarm trigger with an unhandled Status.Failure.
Receive<ExpressionEvalFailed>(HandleExpressionEvalFailed);
// SRT-3: a RateOfChange window that ages out while the value holds re-evaluates.
Receive<RateWindowTick>(_ => HandleRateWindowTick());
}
/// <summary>
@@ -350,6 +365,9 @@ public class AlarmActor : ReceiveActor
};
ApplyTriggeredState(isTriggered, observedSource);
if (_triggerType == AlarmTriggerType.RateOfChange)
ScheduleRateWindowExpiry();
}
catch (Exception ex)
{
@@ -586,27 +604,9 @@ public class AlarmActor : ReceiveActor
// Add to window
_rateOfChangeWindow.Enqueue((timestamp, numericValue));
_rateLastSample = (timestamp, numericValue, DateTimeOffset.UtcNow);
// Remove old entries outside the window
var cutoff = timestamp - _rateOfChangeWindowDuration;
while (_rateOfChangeWindow.Count > 0 && _rateOfChangeWindow.Peek().Timestamp < cutoff)
{
_rateOfChangeWindow.Dequeue();
}
if (_rateOfChangeWindow.Count < 2) return false;
var oldest = _rateOfChangeWindow.Peek();
var timeDelta = (timestamp - oldest.Timestamp).TotalSeconds;
if (timeDelta <= 0) return false;
var signedRate = (numericValue - oldest.Value) / timeDelta;
return config.Direction switch
{
RateOfChangeDirection.Rising => signedRate > config.ThresholdPerSecond,
RateOfChangeDirection.Falling => -signedRate > config.ThresholdPerSecond,
_ => Math.Abs(signedRate) > config.ThresholdPerSecond
};
return EvaluateRateWindow(config, timestamp, numericValue);
}
catch
{
@@ -614,13 +614,97 @@ public class AlarmActor : ReceiveActor
}
}
/// <summary>
/// Prunes the rate window to <paramref name="now"/> and evaluates the rate from the oldest
/// surviving sample to <paramref name="currentValue"/> at <paramref name="now"/>. Fewer than two
/// samples in the window ⇒ not triggered.
/// </summary>
private bool EvaluateRateWindow(RateOfChangeEvalConfig config, DateTimeOffset now, double currentValue)
{
// Remove old entries outside the window
var cutoff = now - _rateOfChangeWindowDuration;
while (_rateOfChangeWindow.Count > 0 && _rateOfChangeWindow.Peek().Timestamp < cutoff)
{
_rateOfChangeWindow.Dequeue();
}
if (_rateOfChangeWindow.Count < 2) return false;
var oldest = _rateOfChangeWindow.Peek();
var timeDelta = (now - oldest.Timestamp).TotalSeconds;
if (timeDelta <= 0) return false;
var signedRate = (currentValue - oldest.Value) / timeDelta;
return config.Direction switch
{
RateOfChangeDirection.Rising => signedRate > config.ThresholdPerSecond,
RateOfChangeDirection.Falling => -signedRate > config.ThresholdPerSecond,
_ => Math.Abs(signedRate) > config.ThresholdPerSecond
};
}
/// <summary>
/// SRT-3 (2026-12-02 review): tag subscriptions report on CHANGE, so a value that steps and
/// then holds produces no further sample, and the window — pruned only when a sample arrived —
/// used to keep the alarm Active indefinitely although the rate had been 0 since the step.
/// While the window holds two or more samples, a single-shot tick is armed for the moment its
/// oldest sample ages out; the tick re-evaluates with the value held flat since the newest
/// sample. Each new sample re-arms it (the timer key replaces any pending tick).
/// </summary>
private void ScheduleRateWindowExpiry()
{
if (_rateOfChangeWindow.Count < 2 || _rateLastSample is not { } last)
{
Timers.Cancel(RateWindowTimerKey);
return;
}
// In the samples' own time base the oldest sample leaves the window at
// oldest + window; it was `last.Timestamp` when the newest sample was processed.
// +10 ms because the prune keeps a sample exactly AT the cutoff.
var dueIn = _rateOfChangeWindow.Peek().Timestamp + _rateOfChangeWindowDuration - last.Timestamp
- (DateTimeOffset.UtcNow - last.ProcessedAtUtc)
+ TimeSpan.FromMilliseconds(10);
if (dueIn < TimeSpan.Zero) dueIn = TimeSpan.Zero;
Timers.StartSingleTimer(RateWindowTimerKey, RateWindowTick.Instance, dueIn);
}
private void HandleRateWindowTick()
{
if (_evalConfig is not RateOfChangeEvalConfig config || _rateLastSample is not { } last)
return;
try
{
// "Now" in the samples' time base: the newest sample's timestamp advanced by the wall
// time since it was processed. The value has been flat at last.Value since then.
var now = last.Timestamp + (DateTimeOffset.UtcNow - last.ProcessedAtUtc);
ApplyTriggeredState(EvaluateRateWindow(config, now, last.Value), sourceExecutionId: null);
ScheduleRateWindowExpiry();
}
catch (Exception ex)
{
_healthCollector?.IncrementAlarmError();
_logger.LogError(ex, "Alarm {Alarm} rate-window re-evaluation error on {Instance}", _alarmName, _instanceName);
}
}
/// <summary>SRT-3: the RateOfChange window-expiry tick.</summary>
internal sealed class RateWindowTick
{
public static readonly RateWindowTick Instance = new();
private RateWindowTick() { }
}
/// <summary>
/// Evaluates the compiled trigger expression against the current attribute
/// snapshot, returning the resulting bool. This bool feeds the existing
/// binary Normal↔Active state path — the alarm is active while true. A
/// throwing, non-bool, or timed-out expression is treated as false (logged
/// as an alarm error) so that the state machine still runs — an Active
/// alarm correctly clears if the expression starts throwing.
/// non-bool result is an evaluated false. A THROWING or TIMED-OUT evaluation
/// is "unknown", not false (2026-12-02 review SRT-2): it is logged (node log,
/// alarm-error counter, a rate-limited site event) and the alarm KEEPS its
/// current state. Coercing it to false cleared an Active alarm on a single slow
/// evaluation under load, then re-raised it — with a second on-trigger run — on
/// the next successful one, for a condition that never cleared.
/// </summary>
private void StartExpressionEvaluation()
{
@@ -656,7 +740,7 @@ public class AlarmActor : ReceiveActor
// compile-checked pre-deploy.
var state = await expression.RunAsync(
new TriggerExpressionGlobals(snapshot), cancellationToken: cts.Token);
return state.ReturnValue is bool b && b;
return (bool?)(state.ReturnValue is bool b && b);
}
finally
{
@@ -666,14 +750,11 @@ public class AlarmActor : ReceiveActor
catch (Exception ex)
{
// OperationCanceledException (timeout, INCLUDING one that fired while still
// waiting on the gate) falls through here too and is treated as false.
// _healthCollector (Interlocked) and _logger are thread-safe, so this catch
// is safe off the actor thread.
_healthCollector?.IncrementAlarmError();
_logger.LogError(ex,
"Alarm {Alarm} trigger expression evaluation failed on {Instance}; treated as false",
_alarmName, _instanceName);
return false;
// waiting on the gate) falls through here too. The outcome is UNKNOWN (null),
// never false (SRT-2). ReportEvalError touches only thread-safe members, so this
// catch is safe off the actor thread.
ReportEvalError(ex);
return null;
}
finally
{
@@ -694,7 +775,9 @@ public class AlarmActor : ReceiveActor
_evalInFlight = false;
try
{
ApplyTriggeredState(msg.Result, msg.SourceExecutionId);
// Unknown (the evaluation threw or timed out): keep the current state (SRT-2).
if (msg.Result is { } result)
ApplyTriggeredState(result, msg.SourceExecutionId);
}
catch (Exception ex)
{
@@ -708,18 +791,37 @@ public class AlarmActor : ReceiveActor
/// <summary>
/// Applies a faulted off-dispatcher evaluation task (N2): logs the fault, then
/// delegates to the false result (per the class contract — a throwing expression
/// is treated as false so the state machine still runs, an Active alarm clears)
/// which clears in-flight and drains any pending evaluation. Without this the
/// alarm trigger would be permanently parked with _evalInFlight stuck true.
/// delegates to the UNKNOWN result (SRT-2 — the alarm keeps its state), which clears
/// in-flight and drains any pending evaluation. Without this the alarm trigger would
/// be permanently parked with _evalInFlight stuck true.
/// </summary>
private void HandleExpressionEvalFailed(ExpressionEvalFailed msg)
{
ReportEvalError(msg.Cause);
HandleExpressionEvalResult(new ExpressionEvalResult(null, msg.SourceExecutionId));
}
/// <summary>One "evaluation failed" site event per minute per alarm (SRT-2).</summary>
private readonly EventRateLimiter _evalErrorEvents = new(TimeSpan.FromMinutes(1));
/// <summary>
/// Records a failed/timed-out trigger-expression evaluation: alarm-error counter and node log
/// every time, a <c>site_events</c> Warning at most once a minute. Thread-safe (called from the
/// off-dispatcher evaluation task).
/// </summary>
private void ReportEvalError(Exception ex)
{
_healthCollector?.IncrementAlarmError();
_logger.LogError(msg.Cause,
"Alarm {Alarm} trigger-expression evaluation task faulted on {Instance}; treated as false",
_logger.LogError(ex,
"Alarm {Alarm} trigger expression evaluation failed on {Instance}; alarm state unchanged",
_alarmName, _instanceName);
HandleExpressionEvalResult(new ExpressionEvalResult(false, msg.SourceExecutionId));
if (_evalErrorEvents.TryAcquire(out var suppressed))
{
var note = suppressed > 0 ? $" ({suppressed} more failure(s) since the last event)" : string.Empty;
LogAlarmEvent("Warning",
$"Alarm '{_alarmName}' on '{_instanceName}': trigger expression could not be evaluated " +
$"({ex.GetType().Name}: {ex.Message}); alarm state left unchanged{note}");
}
}
/// <summary>
@@ -1032,7 +1134,9 @@ public class AlarmActor : ReceiveActor
/// to the execution that actually wrote the value it evaluated — not to a
/// later change that arrived while the evaluation was in flight.
/// </summary>
private sealed record ExpressionEvalResult(bool Result, Guid? SourceExecutionId = null);
/// <param name="Result">The truth value, or null when the evaluation threw or timed out (SRT-2: keep state).</param>
/// <param name="SourceExecutionId">Writer of the newest value in the evaluated snapshot.</param>
private sealed record ExpressionEvalResult(bool? Result, Guid? SourceExecutionId = null);
/// <summary>
/// Piped back to self when the off-dispatcher evaluation TASK itself faults
@@ -0,0 +1,39 @@
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors;
/// <summary>
/// Thread-safe "at most one per interval" gate for an operational site event that a failure
/// path could otherwise emit on every occurrence — e.g. a trigger expression that times out on
/// every attribute change during a burst (2026-12-02 review SRT-2). The node log and the health
/// counter still record every occurrence; only the <c>site_events</c> row is rate-limited.
/// </summary>
internal sealed class EventRateLimiter
{
private readonly long _intervalMs;
private long _nextAllowedMs = long.MinValue;
private int _suppressed;
/// <summary>Creates a limiter that admits one event per <paramref name="interval"/>.</summary>
/// <param name="interval">Minimum spacing between admitted events.</param>
public EventRateLimiter(TimeSpan interval) => _intervalMs = (long)interval.TotalMilliseconds;
/// <summary>
/// True when an event may be emitted now; the caller then emits it, naming
/// <paramref name="suppressedSinceLast"/> occurrences that were dropped since the previous one.
/// </summary>
/// <param name="suppressedSinceLast">Occurrences suppressed since the last admitted event.</param>
/// <returns>Whether the event is admitted.</returns>
public bool TryAcquire(out int suppressedSinceLast)
{
var now = Environment.TickCount64;
var next = Interlocked.Read(ref _nextAllowedMs);
if (now >= next && Interlocked.CompareExchange(ref _nextAllowedMs, now + _intervalMs, next) == next)
{
suppressedSinceLast = Interlocked.Exchange(ref _suppressed, 0);
return true;
}
Interlocked.Increment(ref _suppressed);
suppressedSinceLast = 0;
return false;
}
}
@@ -366,7 +366,8 @@ public class ScriptActor : ReceiveActor, IWithTimers
/// to date — a Conditional's truth value, an Expression's last result (evaluated, never fired) —
/// so the NEXT real change is judged against the real value: no spurious edge from the replay,
/// and no missed edge afterwards. A WhileTrue trigger whose condition already holds is seeded
/// true without starting its re-fire timer; it fires on its next false→true edge.
/// true WITH its re-fire timer running but without the immediate edge run (2026-12-02 review
/// SRT-4 — it used to lose its periodic re-fire until the condition went false and back).
/// </summary>
private void HandleAttributeValueSeed(Messages.AttributeValueSeed seed)
{
@@ -376,7 +377,10 @@ public class ScriptActor : ReceiveActor, IWithTimers
if (_triggerConfig is ConditionalTriggerConfig conditional &&
conditional.AttributeName == changed.AttributeName)
{
_conditionState = EvaluateCondition(conditional, changed.Value);
var seeded = EvaluateCondition(conditional, changed.Value);
if (conditional.Mode == TriggerMode.WhileTrue)
AdoptWhileTrueFromSeed(seeded, _conditionState);
_conditionState = seeded;
}
else if (_triggerConfig is ExpressionTriggerConfig)
{
@@ -441,7 +445,7 @@ public class ScriptActor : ReceiveActor, IWithTimers
// compile-checked pre-deploy.
var state = await expression.RunAsync(
new TriggerExpressionGlobals(snapshot), cancellationToken: cts.Token);
return state.ReturnValue is bool b && b;
return (bool?)(state.ReturnValue is bool b && b);
}
finally
{
@@ -451,12 +455,15 @@ public class ScriptActor : ReceiveActor, IWithTimers
catch (Exception ex)
{
// OperationCanceledException (timeout, INCLUDING a timeout that fired while
// still waiting on the gate) falls through here too and is treated as false.
// still waiting on the gate) falls through here too. The outcome is UNKNOWN
// (null), never false (2026-12-02 review SRT-2): coercing it to false stopped a
// WhileTrue timer / re-armed an OnTrue edge, so the next successful evaluation
// fired an extra run for a condition that never went false.
// LogExpressionError touches only thread-safe members (_healthCollector
// Interlocked, _logger, DI-resolved singleton logger) so it is safe off the
// actor thread.
// Interlocked, _logger, DI-resolved singleton logger, the rate limiter) so it is
// safe off the actor thread.
LogExpressionError(ex);
return false;
return null;
}
finally
{
@@ -476,17 +483,22 @@ public class ScriptActor : ReceiveActor, IWithTimers
private void HandleExpressionEvalResult(ExpressionEvalResult msg)
{
_evalInFlight = false;
if (_triggerConfig is ExpressionTriggerConfig exprConfig)
// Unknown (the evaluation threw or timed out): adopt nothing, fire nothing (SRT-2).
if (_triggerConfig is ExpressionTriggerConfig exprConfig && msg.Result is { } result)
{
if (msg.SeedOnly)
{
// 01/SR-U1: a seed adopts the truth value and never fires.
// 01/SR-U1: a seed adopts the truth value and never fires — but a WhileTrue
// trigger it leaves true keeps re-firing on its cadence (SRT-4), exactly as it
// did before the restart that made this a seed.
if (exprConfig.Mode == TriggerMode.WhileTrue)
AdoptWhileTrueFromSeed(result, _lastExpressionResult);
}
else if (exprConfig.Mode == TriggerMode.WhileTrue)
HandleWhileTrueTransition(msg.Result, _lastExpressionResult);
else if (msg.Result && !_lastExpressionResult)
HandleWhileTrueTransition(result, _lastExpressionResult);
else if (result && !_lastExpressionResult)
TrySpawnExecution(null);
_lastExpressionResult = msg.Result;
_lastExpressionResult = result;
}
if (_evalPending)
{
@@ -497,29 +509,34 @@ public class ScriptActor : ReceiveActor, IWithTimers
/// <summary>
/// Applies a faulted off-dispatcher evaluation task (N2): logs the fault via the
/// existing error path (which also increments the health counter), then reuses the
/// false-result path — clearing in-flight, applying the false edge, and draining any
/// pending evaluation — so a transient scheduler fault cannot permanently park the trigger.
/// A faulted SEED evaluation (review 2026-10-21 follow-up L4) carries no truth value at all:
/// it only clears in-flight and drains the pending evaluation, adopting nothing — replaying it
/// as a real false stopped a running WhileTrue timer, and even as a seeded false it would make
/// the next true evaluation look like a fresh edge and fire spuriously.
/// existing error path (which also increments the health counter), then clears in-flight
/// and drains any pending evaluation, so a transient scheduler fault cannot permanently
/// park the trigger. A faulted evaluation carries no truth value at all and adopts nothing
/// (review 2026-10-21 follow-up L4 for seeds; 2026-12-02 review SRT-2 for real changes) —
/// replaying it as a false stopped a running WhileTrue timer, and made the next true
/// evaluation look like a fresh edge and fire spuriously.
/// </summary>
private void HandleExpressionEvalFailed(ExpressionEvalFailed msg)
{
// A faulted evaluation — seed or real — carries no truth value: clear in-flight, drain
// the pending evaluation, adopt nothing (SRT-2; the seed case was already so, L4).
LogExpressionError(msg.Cause);
if (!msg.SeedOnly)
{
HandleExpressionEvalResult(new ExpressionEvalResult(false));
return;
}
HandleExpressionEvalResult(new ExpressionEvalResult(null, msg.SeedOnly));
}
_evalInFlight = false;
if (_evalPending)
{
_evalPending = false;
StartExpressionEvaluation(_evalPendingSeedOnly);
}
/// <summary>
/// SRT-4 (2026-12-02 review): a seed that leaves a WhileTrue trigger's condition TRUE starts
/// the periodic re-fire timer WITHOUT the immediate edge run (a seed never fires — 01/SR-U1);
/// one that leaves it false stops it. Before this, a WhileTrue script whose condition was
/// adopted from a persisted static override (failover, restart, disable/enable) never
/// re-fired again until the condition went false and back to true.
/// </summary>
private void AdoptWhileTrueFromSeed(bool nowTrue, bool wasTrue)
{
if (nowTrue && !wasTrue)
StartWhileTrueTimer();
else if (!nowTrue && wasTrue)
StopWhileTrueTimer();
}
/// <summary>
@@ -586,13 +603,23 @@ public class ScriptActor : ReceiveActor, IWithTimers
private void LogExpressionError(Exception ex)
{
_healthCollector?.IncrementScriptError();
var errorMsg = $"Trigger expression for script '{_scriptName}' on instance '{_instanceName}' failed: {ex.Message}";
_logger.LogError(ex, "Trigger expression evaluation failed: {Script} on {Instance}", _scriptName, _instanceName);
_logger.LogError(ex, "Trigger expression evaluation failed: {Script} on {Instance}; trigger state unchanged",
_scriptName, _instanceName);
// The site_events row is rate-limited (SRT-2): a burst that times out every evaluation
// would otherwise mint one Error row per attribute change.
if (!_evalErrorEvents.TryAcquire(out var suppressed))
return;
var note = suppressed > 0 ? $" ({suppressed} more failure(s) since the last event)" : string.Empty;
var errorMsg = $"Trigger expression for script '{_scriptName}' on instance '{_instanceName}' failed: {ex.Message}; " +
$"trigger state left unchanged{note}";
_ = _serviceProvider?.GetService<ISiteEventLogger>()?.LogEventAsync(
"script", "Error", _instanceName, $"ScriptActor:{_scriptName}", errorMsg, ex.ToString());
}
/// <summary>One "trigger expression failed" site event per minute per script (SRT-2).</summary>
private readonly EventRateLimiter _evalErrorEvents = new(TimeSpan.FromMinutes(1));
/// <summary>
/// Attempts to spawn a script execution, respecting MinTimeBetweenRuns.
/// </summary>
@@ -952,7 +979,9 @@ public class ScriptActor : ReceiveActor, IWithTimers
/// carries the boolean truth value so the OnTrue/WhileTrue edge logic runs on
/// the actor thread.
/// </summary>
private sealed record ExpressionEvalResult(bool Result, bool SeedOnly = false);
/// <param name="Result">The truth value, or null when the evaluation threw or timed out (SRT-2: adopt nothing).</param>
/// <param name="SeedOnly">Whether this evaluation only seeds the edge state (01/SR-U1).</param>
private sealed record ExpressionEvalResult(bool? Result, bool SeedOnly = false);
/// <summary>
/// Piped back to self when the off-dispatcher evaluation TASK itself faults