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
+3 -3
View File
@@ -241,7 +241,7 @@ flowchart TD
> **Routed multi-attribute reads and writes are one message each (review 2026-10-21 01/SR-P4).** `Route.To().GetAttributes()` / `SetAttributes()` used to cost one Ask — a temp actor, a mailbox round trip and a 30 s timer — per attribute. The Deployment Manager now sends the Instance Actor a single site-local `InstanceGetAttributesRequest` / `InstanceSetAttributesRequest` (`SiteRuntime/Messages/InstanceAttributeBatch.cs`, never on the wire). Reads are answered in one pass from one consistent point in the mailbox. Writes are applied in order exactly as the equivalent single `SetStaticAttributeCommand`s (static → in-memory + coalesced persist, data-sourced → DCL write, unknown/poison values rejected); data-sourced writes are issued concurrently and the reply waits only for those, each still bounded by its own 30 s DCL Ask (the batch Ask allows that 30 s plus 10 s of mailbox slack, so a device timeout or a busy instance mailbox surfaces as that attribute's own failure, not as a whole-batch timeout over writes that were applied). Both replies carry the per-attribute `GetAttributeResponse` / `SetStaticAttributeResponse`, so the routed response is unchanged: a failed device write or unknown attribute is still reported by name. > **Routed multi-attribute reads and writes are one message each (review 2026-10-21 01/SR-P4).** `Route.To().GetAttributes()` / `SetAttributes()` used to cost one Ask — a temp actor, a mailbox round trip and a 30 s timer — per attribute. The Deployment Manager now sends the Instance Actor a single site-local `InstanceGetAttributesRequest` / `InstanceSetAttributesRequest` (`SiteRuntime/Messages/InstanceAttributeBatch.cs`, never on the wire). Reads are answered in one pass from one consistent point in the mailbox. Writes are applied in order exactly as the equivalent single `SetStaticAttributeCommand`s (static → in-memory + coalesced persist, data-sourced → DCL write, unknown/poison values rejected); data-sourced writes are issued concurrently and the reply waits only for those, each still bounded by its own 30 s DCL Ask (the batch Ask allows that 30 s plus 10 s of mailbox slack, so a device timeout or a busy instance mailbox surfaces as that attribute's own failure, not as a whole-batch timeout over writes that were applied). Both replies carry the per-attribute `GetAttributeResponse` / `SetStaticAttributeResponse`, so the routed response is unchanged: a failed device write or unknown attribute is still reported by name.
> **Loaded overrides are republished to the children and the stream (review 2026-10-21 01/SR-U1).** The override load is asynchronous and lands *after* `PreStart` has already created the Script/Alarm Actors, whose trigger snapshots are seeded from the attribute set at that moment — the deploy **defaults**. Static attributes never re-emit a change on their own, so before this fix every trigger on an instance that restarted, failed over, was enabled or was started by the reconcile sweep evaluated an overridden attribute at its default indefinitely (an Expression alarm on `Mode == "Auto"` never raised), and the Debug View live stream showed the default, while `GetAttribute` answered correctly. The load now republishes each override that changed the in-memory value or quality (quality from the load, no `SourceExecutionId`), with waiter evaluation **off** — nothing can legitimately be waiting on a replay. The site stream / Debug View receive it as an ordinary `AttributeValueChanged`; the children receive it as a site-local **`AttributeValueSeed`** (decision 2026-10-22): **Script Actors adopt the value without running** — the snapshot, a Conditional trigger's truth value and an Expression trigger's last result (evaluated, never fired) are brought up to date, so a restart/failover never re-fires ValueChange/Conditional/Expression scripts and the next real change is judged against the real value; a WhileTrue trigger whose condition already holds is seeded true without starting its re-fire timer. A seed evaluation whose task **faults** adopts nothing — it is not replayed as a real `false`, which would stop a running WhileTrue timer and make the next true evaluation fire as a spurious fresh edge (review 2026-10-21 follow-up L4). **Alarm Actors evaluate the seed like any change**, so an alarm whose condition already holds raises. A static write that lands before the load is newer than the stored row, so the load skips that attribute rather than rolling it back. Overrides for attributes the deployed config no longer defines are still applied (unchanged) but not republished. > **Loaded overrides are republished to the children and the stream (review 2026-10-21 01/SR-U1).** The override load is asynchronous and lands *after* `PreStart` has already created the Script/Alarm Actors, whose trigger snapshots are seeded from the attribute set at that moment — the deploy **defaults**. Static attributes never re-emit a change on their own, so before this fix every trigger on an instance that restarted, failed over, was enabled or was started by the reconcile sweep evaluated an overridden attribute at its default indefinitely (an Expression alarm on `Mode == "Auto"` never raised), and the Debug View live stream showed the default, while `GetAttribute` answered correctly. The load now republishes each override that changed the in-memory value or quality (quality from the load, no `SourceExecutionId`), with waiter evaluation **off** — nothing can legitimately be waiting on a replay. The site stream / Debug View receive it as an ordinary `AttributeValueChanged`; the children receive it as a site-local **`AttributeValueSeed`** (decision 2026-10-22): **Script Actors adopt the value without running** — the snapshot, a Conditional trigger's truth value and an Expression trigger's last result (evaluated, never fired) are brought up to date, so a restart/failover never re-fires ValueChange/Conditional/Expression scripts and the next real change is judged against the real value; a WhileTrue trigger whose condition already holds is seeded true **and starts its re-fire timer** (first run one cadence later — the seed itself still never fires; 2026-12-02 review SRT-4: it used to lose its periodic re-fire until the condition went false and back to true). A seed evaluation whose task **faults** adopts nothing — it is not replayed as a real `false`, which would stop a running WhileTrue timer and make the next true evaluation fire as a spurious fresh edge (review 2026-10-21 follow-up L4). **Alarm Actors evaluate the seed like any change**, so an alarm whose condition already holds raises. A static write that lands before the load is newer than the stored row, so the load skips that attribute rather than rolling it back. Overrides for attributes the deployed config no longer defines are still applied (unchanged) but not republished.
> **Stopping an instance answers its pending waits (review 2026-10-21 01/SR-M3).** `PostStop` cancels every registered `WaitForAttribute` timeout and replies `Matched=false, TimedOut=false, ErrorMessage="… abandoned: instance stopped"`, so a script parked in `Attributes.WaitAsync` across a redeploy/disable/delete learns why immediately instead of burning its whole wait plus the Ask timeout and reporting a time-out, and no `WaitForAttributeTimeout` lands in dead letters (a monitored health metric). > **Stopping an instance answers its pending waits (review 2026-10-21 01/SR-M3).** `PostStop` cancels every registered `WaitForAttribute` timeout and replies `Matched=false, TimedOut=false, ErrorMessage="… abandoned: instance stopped"`, so a script parked in `Attributes.WaitAsync` across a redeploy/disable/delete learns why immediately instead of burning its whole wait plus the Ask timeout and reporting a time-out, and no `WaitForAttributeTimeout` lands in dead letters (a monitored health metric).
@@ -330,9 +330,9 @@ When the Instance Actor is stopped (due to disable, delete, or redeployment), Ak
- On each value update, evaluates the trigger condition: - On each value update, evaluates the trigger condition:
- **Value Match**: Incoming value equals the predefined target. Supports `"!=X"` prefix for not-equals semantics. - **Value Match**: Incoming value equals the predefined target. Supports `"!=X"` prefix for not-equals semantics.
- **Range Violation**: Value is outside the allowed min/max range. - **Range Violation**: Value is outside the allowed min/max range.
- **Rate of Change**: Value change rate exceeds the defined threshold over a configurable time window. Direction filter (rising / falling / either) restricts which side of the rate triggers. - **Rate of Change**: Value change rate exceeds the defined threshold over a configurable time window. Direction filter (rising / falling / either) restricts which side of the rate triggers. Because subscriptions report on change, a value that steps and then holds produces no further sample; while the window holds two or more samples the Alarm Actor arms a single-shot tick for the moment the oldest sample ages out and re-evaluates with the value held flat — fewer than two samples in the window is "not triggered", so the alarm clears once the step has left the window (2026-12-02 review SRT-3; it used to stay Active indefinitely).
- **HiLo**: Multi-setpoint level alarm with up to four configurable setpoints (LoLo, Lo, Hi, HiHi). Any subset may be configured. Each setpoint may carry its own priority that overrides the alarm-level priority for that band. - **HiLo**: Multi-setpoint level alarm with up to four configurable setpoints (LoLo, Lo, Hi, HiHi). Any subset may be configured. Each setpoint may carry its own priority that overrides the alarm-level priority for that band.
- **Expression** trigger evaluation runs on the shared .NET thread pool behind a process-wide concurrency gate (`TriggerEvalGate`, sized by `TriggerEvalMaxConcurrency`, default `max(2, ProcessorCount)`) — **not** on the bounded script-execution pool. This is the WP3.1 fix for arch-review finding #4 (High): when evaluation shared that pool, N script bodies blocked in synchronous I/O stalled *every* Expression trigger on the node — scripts and alarms alike — for an unbounded time, and the evaluation's own 2 s timeout was constructed inside the queued body, so it did not start ticking until dequeue. An alarm that should have raised in milliseconds simply never raised, with neither a raise nor a timeout visible to the operator. Trigger expressions are non-blocking **by construction** (`TriggerExpressionGlobals` exposes only reads over an in-memory snapshot, and the script trust gate has already denied I/O, network, threading, and reflection), so the shared pool is where they belong; a second dedicated pool was considered and rejected as adding threads, gauges, and a second starvation surface for no isolation gain. The evaluation deadline (`TriggerEvalTimeoutSeconds`, default 2, previously hardcoded) is now armed **at enqueue**, so gate-wait time burns the same budget and a saturated gate yields a timely `false` rather than an unbounded stall. Per-actor coalescing (one evaluation in flight, one pending) is unchanged and caps waiters at one per Expression trigger, so the gate queue is bounded by trigger count. - **Expression** trigger evaluation runs on the shared .NET thread pool behind a process-wide concurrency gate (`TriggerEvalGate`, sized by `TriggerEvalMaxConcurrency`, default `max(2, ProcessorCount)`) — **not** on the bounded script-execution pool. This is the WP3.1 fix for arch-review finding #4 (High): when evaluation shared that pool, N script bodies blocked in synchronous I/O stalled *every* Expression trigger on the node — scripts and alarms alike — for an unbounded time, and the evaluation's own 2 s timeout was constructed inside the queued body, so it did not start ticking until dequeue. An alarm that should have raised in milliseconds simply never raised, with neither a raise nor a timeout visible to the operator. Trigger expressions are non-blocking **by construction** (`TriggerExpressionGlobals` exposes only reads over an in-memory snapshot, and the script trust gate has already denied I/O, network, threading, and reflection), so the shared pool is where they belong; a second dedicated pool was considered and rejected as adding threads, gauges, and a second starvation surface for no isolation gain. The evaluation deadline (`TriggerEvalTimeoutSeconds`, default 2, previously hardcoded) is now armed **at enqueue**, so gate-wait time burns the same budget and a saturated gate yields a timely result rather than an unbounded stall. **A throwing or timed-out evaluation is "unknown", never `false` (2026-12-02 review SRT-2):** the alarm keeps its current state and a Script Actor's Expression trigger adopts nothing (an OnTrue edge is not re-armed, a WhileTrue timer keeps running); the error is still logged and counted every time, and a `site_events` row is written at most once a minute per alarm/script (naming how many failures it suppressed). Coercing it to `false` used to clear an Active alarm on one slow evaluation under load and re-raise it — with a second on-trigger run — on the next successful one. A non-bool result is still an evaluated `false`. Per-actor coalescing (one evaluation in flight, one pending) is unchanged and caps waiters at one per Expression trigger, so the gate queue is bounded by trigger count.
- For binary trigger types (ValueMatch / RangeViolation / RateOfChange), when the condition is met and the alarm is currently in **normal** state, the alarm transitions to **active**: - For binary trigger types (ValueMatch / RangeViolation / RateOfChange), when the condition is met and the alarm is currently in **normal** state, the alarm transitions to **active**:
- Updates the alarm state on the parent Instance Actor (which publishes to the Akka stream). - Updates the alarm state on the parent Instance Actor (which publishes to the Akka stream).
- If an on-trigger script is defined, launches its run via `ScriptRunLauncher` (see Alarm On-Trigger Run below) — no per-run child actor. - If an on-trigger script is defined, launches its run via `ScriptRunLauncher` (see Alarm On-Trigger Run below) — no per-run child actor.
@@ -33,8 +33,11 @@ namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors;
/// ///
/// Supervision: Resume on exception (from the Instance Actor). This actor has no children. /// Supervision: Resume on exception (from the Instance Actor). This actor has no children.
/// </summary> /// </summary>
public class AlarmActor : ReceiveActor public class AlarmActor : ReceiveActor, IWithTimers
{ {
/// <inheritdoc />
public ITimerScheduler Timers { get; set; } = null!;
private readonly string _alarmName; private readonly string _alarmName;
private readonly string _instanceName; private readonly string _instanceName;
private readonly IActorRef _instanceActor; private readonly IActorRef _instanceActor;
@@ -171,6 +174,15 @@ public class AlarmActor : ReceiveActor
private readonly Queue<(DateTimeOffset Timestamp, double Value)> _rateOfChangeWindow = new(); private readonly Queue<(DateTimeOffset Timestamp, double Value)> _rateOfChangeWindow = new();
private readonly TimeSpan _rateOfChangeWindowDuration; 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; private int _executionCounter;
/// <summary>Initializes a new <see cref="AlarmActor"/> and configures message handlers for the alarm.</summary> /// <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 // Handle a faulted off-dispatcher evaluation task (N2) — clears in-flight
// instead of stranding the alarm trigger with an unhandled Status.Failure. // instead of stranding the alarm trigger with an unhandled Status.Failure.
Receive<ExpressionEvalFailed>(HandleExpressionEvalFailed); Receive<ExpressionEvalFailed>(HandleExpressionEvalFailed);
// SRT-3: a RateOfChange window that ages out while the value holds re-evaluates.
Receive<RateWindowTick>(_ => HandleRateWindowTick());
} }
/// <summary> /// <summary>
@@ -350,6 +365,9 @@ public class AlarmActor : ReceiveActor
}; };
ApplyTriggeredState(isTriggered, observedSource); ApplyTriggeredState(isTriggered, observedSource);
if (_triggerType == AlarmTriggerType.RateOfChange)
ScheduleRateWindowExpiry();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -586,27 +604,9 @@ public class AlarmActor : ReceiveActor
// Add to window // Add to window
_rateOfChangeWindow.Enqueue((timestamp, numericValue)); _rateOfChangeWindow.Enqueue((timestamp, numericValue));
_rateLastSample = (timestamp, numericValue, DateTimeOffset.UtcNow);
// Remove old entries outside the window return EvaluateRateWindow(config, timestamp, numericValue);
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
};
} }
catch 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> /// <summary>
/// Evaluates the compiled trigger expression against the current attribute /// Evaluates the compiled trigger expression against the current attribute
/// snapshot, returning the resulting bool. This bool feeds the existing /// snapshot, returning the resulting bool. This bool feeds the existing
/// binary Normal↔Active state path — the alarm is active while true. A /// binary Normal↔Active state path — the alarm is active while true. A
/// throwing, non-bool, or timed-out expression is treated as false (logged /// non-bool result is an evaluated false. A THROWING or TIMED-OUT evaluation
/// as an alarm error) so that the state machine still runs — an Active /// is "unknown", not false (2026-12-02 review SRT-2): it is logged (node log,
/// alarm correctly clears if the expression starts throwing. /// 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> /// </summary>
private void StartExpressionEvaluation() private void StartExpressionEvaluation()
{ {
@@ -656,7 +740,7 @@ public class AlarmActor : ReceiveActor
// compile-checked pre-deploy. // compile-checked pre-deploy.
var state = await expression.RunAsync( var state = await expression.RunAsync(
new TriggerExpressionGlobals(snapshot), cancellationToken: cts.Token); new TriggerExpressionGlobals(snapshot), cancellationToken: cts.Token);
return state.ReturnValue is bool b && b; return (bool?)(state.ReturnValue is bool b && b);
} }
finally finally
{ {
@@ -666,14 +750,11 @@ public class AlarmActor : ReceiveActor
catch (Exception ex) catch (Exception ex)
{ {
// OperationCanceledException (timeout, INCLUDING one that fired while still // OperationCanceledException (timeout, INCLUDING one that fired while still
// waiting on the gate) falls through here too and is treated as false. // waiting on the gate) falls through here too. The outcome is UNKNOWN (null),
// _healthCollector (Interlocked) and _logger are thread-safe, so this catch // never false (SRT-2). ReportEvalError touches only thread-safe members, so this
// is safe off the actor thread. // catch is safe off the actor thread.
_healthCollector?.IncrementAlarmError(); ReportEvalError(ex);
_logger.LogError(ex, return null;
"Alarm {Alarm} trigger expression evaluation failed on {Instance}; treated as false",
_alarmName, _instanceName);
return false;
} }
finally finally
{ {
@@ -694,7 +775,9 @@ public class AlarmActor : ReceiveActor
_evalInFlight = false; _evalInFlight = false;
try 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) catch (Exception ex)
{ {
@@ -708,18 +791,37 @@ public class AlarmActor : ReceiveActor
/// <summary> /// <summary>
/// Applies a faulted off-dispatcher evaluation task (N2): logs the fault, then /// Applies a faulted off-dispatcher evaluation task (N2): logs the fault, then
/// delegates to the false result (per the class contract — a throwing expression /// delegates to the UNKNOWN result (SRT-2 — the alarm keeps its state), which clears
/// is treated as false so the state machine still runs, an Active alarm clears) /// in-flight and drains any pending evaluation. Without this the alarm trigger would
/// which clears in-flight and drains any pending evaluation. Without this the /// be permanently parked with _evalInFlight stuck true.
/// alarm trigger would be permanently parked with _evalInFlight stuck true.
/// </summary> /// </summary>
private void HandleExpressionEvalFailed(ExpressionEvalFailed msg) 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(); _healthCollector?.IncrementAlarmError();
_logger.LogError(msg.Cause, _logger.LogError(ex,
"Alarm {Alarm} trigger-expression evaluation task faulted on {Instance}; treated as false", "Alarm {Alarm} trigger expression evaluation failed on {Instance}; alarm state unchanged",
_alarmName, _instanceName); _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> /// <summary>
@@ -1032,7 +1134,9 @@ public class AlarmActor : ReceiveActor
/// to the execution that actually wrote the value it evaluated — not to a /// to the execution that actually wrote the value it evaluated — not to a
/// later change that arrived while the evaluation was in flight. /// later change that arrived while the evaluation was in flight.
/// </summary> /// </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> /// <summary>
/// Piped back to self when the off-dispatcher evaluation TASK itself faults /// 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) — /// 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, /// 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 /// 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> /// </summary>
private void HandleAttributeValueSeed(Messages.AttributeValueSeed seed) private void HandleAttributeValueSeed(Messages.AttributeValueSeed seed)
{ {
@@ -376,7 +377,10 @@ public class ScriptActor : ReceiveActor, IWithTimers
if (_triggerConfig is ConditionalTriggerConfig conditional && if (_triggerConfig is ConditionalTriggerConfig conditional &&
conditional.AttributeName == changed.AttributeName) 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) else if (_triggerConfig is ExpressionTriggerConfig)
{ {
@@ -441,7 +445,7 @@ public class ScriptActor : ReceiveActor, IWithTimers
// compile-checked pre-deploy. // compile-checked pre-deploy.
var state = await expression.RunAsync( var state = await expression.RunAsync(
new TriggerExpressionGlobals(snapshot), cancellationToken: cts.Token); new TriggerExpressionGlobals(snapshot), cancellationToken: cts.Token);
return state.ReturnValue is bool b && b; return (bool?)(state.ReturnValue is bool b && b);
} }
finally finally
{ {
@@ -451,12 +455,15 @@ public class ScriptActor : ReceiveActor, IWithTimers
catch (Exception ex) catch (Exception ex)
{ {
// OperationCanceledException (timeout, INCLUDING a timeout that fired while // 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 // LogExpressionError touches only thread-safe members (_healthCollector
// Interlocked, _logger, DI-resolved singleton logger) so it is safe off the // Interlocked, _logger, DI-resolved singleton logger, the rate limiter) so it is
// actor thread. // safe off the actor thread.
LogExpressionError(ex); LogExpressionError(ex);
return false; return null;
} }
finally finally
{ {
@@ -476,17 +483,22 @@ public class ScriptActor : ReceiveActor, IWithTimers
private void HandleExpressionEvalResult(ExpressionEvalResult msg) private void HandleExpressionEvalResult(ExpressionEvalResult msg)
{ {
_evalInFlight = false; _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) 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) else if (exprConfig.Mode == TriggerMode.WhileTrue)
HandleWhileTrueTransition(msg.Result, _lastExpressionResult); HandleWhileTrueTransition(result, _lastExpressionResult);
else if (msg.Result && !_lastExpressionResult) else if (result && !_lastExpressionResult)
TrySpawnExecution(null); TrySpawnExecution(null);
_lastExpressionResult = msg.Result; _lastExpressionResult = result;
} }
if (_evalPending) if (_evalPending)
{ {
@@ -497,29 +509,34 @@ public class ScriptActor : ReceiveActor, IWithTimers
/// <summary> /// <summary>
/// Applies a faulted off-dispatcher evaluation task (N2): logs the fault via the /// 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 /// existing error path (which also increments the health counter), then clears in-flight
/// false-result path — clearing in-flight, applying the false edge, and draining any /// and drains any pending evaluation, so a transient scheduler fault cannot permanently
/// pending evaluation — so a transient scheduler fault cannot permanently park the trigger. /// park the trigger. A faulted evaluation carries no truth value at all and adopts nothing
/// A faulted SEED evaluation (review 2026-10-21 follow-up L4) carries no truth value at all: /// (review 2026-10-21 follow-up L4 for seeds; 2026-12-02 review SRT-2 for real changes) —
/// it only clears in-flight and drains the pending evaluation, adopting nothing — replaying it /// replaying it as a false stopped a running WhileTrue timer, and made the next true
/// as a real false stopped a running WhileTrue timer, and even as a seeded false it would make /// evaluation look like a fresh edge and fire spuriously.
/// the next true evaluation look like a fresh edge and fire spuriously.
/// </summary> /// </summary>
private void HandleExpressionEvalFailed(ExpressionEvalFailed msg) 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); LogExpressionError(msg.Cause);
if (!msg.SeedOnly) HandleExpressionEvalResult(new ExpressionEvalResult(null, msg.SeedOnly));
{ }
HandleExpressionEvalResult(new ExpressionEvalResult(false));
return;
}
_evalInFlight = false; /// <summary>
if (_evalPending) /// 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);
_evalPending = false; /// one that leaves it false stops it. Before this, a WhileTrue script whose condition was
StartExpressionEvaluation(_evalPendingSeedOnly); /// 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> /// <summary>
@@ -586,13 +603,23 @@ public class ScriptActor : ReceiveActor, IWithTimers
private void LogExpressionError(Exception ex) private void LogExpressionError(Exception ex)
{ {
_healthCollector?.IncrementScriptError(); _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}; trigger state unchanged",
_logger.LogError(ex, "Trigger expression evaluation failed: {Script} on {Instance}", _scriptName, _instanceName); _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( _ = _serviceProvider?.GetService<ISiteEventLogger>()?.LogEventAsync(
"script", "Error", _instanceName, $"ScriptActor:{_scriptName}", errorMsg, ex.ToString()); "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> /// <summary>
/// Attempts to spawn a script execution, respecting MinTimeBetweenRuns. /// Attempts to spawn a script execution, respecting MinTimeBetweenRuns.
/// </summary> /// </summary>
@@ -952,7 +979,9 @@ public class ScriptActor : ReceiveActor, IWithTimers
/// carries the boolean truth value so the OnTrue/WhileTrue edge logic runs on /// carries the boolean truth value so the OnTrue/WhileTrue edge logic runs on
/// the actor thread. /// the actor thread.
/// </summary> /// </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> /// <summary>
/// Piped back to self when the off-dispatcher evaluation TASK itself faults /// Piped back to self when the off-dispatcher evaluation TASK itself faults
@@ -352,6 +352,45 @@ public class AlarmActorTests : TestKit, IDisposable
Assert.Equal(AlarmState.Active, msg.State); Assert.Equal(AlarmState.Active, msg.State);
} }
/// <summary>
/// SRT-3: a value that steps and then HOLDS produces no further sample (subscriptions report on
/// change). The alarm must clear once the step ages out of the window — pre-fix it stayed
/// Active indefinitely although the rate had been 0 since the step.
/// </summary>
[Fact]
public void AlarmActor_RateOfChange_ClearsWhenTheValueStopsChanging()
{
var instanceProbe = CreateTestProbe();
// 10 units/sec threshold, 1 sec window.
var alarm = SpawnRocAlarm(RocConfig(10, 1, "either"), instanceProbe);
var t0 = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
alarm.Tell(PressureSample(0, t0));
alarm.Tell(PressureSample(100, t0.AddMilliseconds(500))); // 200 units/sec → Active
Assert.Equal(AlarmState.Active, instanceProbe.ExpectMsg<AlarmStateChanged>(TimeSpan.FromSeconds(5)).State);
// No further sample: the 0 leaves the window ~0.5 s later and the alarm clears on its own.
var cleared = instanceProbe.ExpectMsg<AlarmStateChanged>(TimeSpan.FromSeconds(5));
Assert.Equal(AlarmState.Normal, cleared.State);
}
/// <summary>SRT-3: while the value keeps changing fast, the window tick does not clear the alarm.</summary>
[Fact]
public void AlarmActor_RateOfChange_StaysActiveWhileTheValueKeepsChangingFast()
{
var instanceProbe = CreateTestProbe();
var alarm = SpawnRocAlarm(RocConfig(10, 1, "either"), instanceProbe);
var t0 = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
alarm.Tell(PressureSample(0, t0));
alarm.Tell(PressureSample(100, t0.AddMilliseconds(500)));
Assert.Equal(AlarmState.Active, instanceProbe.ExpectMsg<AlarmStateChanged>(TimeSpan.FromSeconds(5)).State);
// A second steep step re-arms the tick; the rate over the window stays above threshold.
alarm.Tell(PressureSample(200, t0.AddMilliseconds(900)));
instanceProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
}
/// <summary>Verifies that an either-direction rate-of-change alarm activates on a rapid fall.</summary> /// <summary>Verifies that an either-direction rate-of-change alarm activates on a rapid fall.</summary>
[Fact] [Fact]
public void AlarmActor_RateOfChange_Either_ActivatesOnRapidFall() public void AlarmActor_RateOfChange_Either_ActivatesOnRapidFall()
@@ -1153,4 +1192,40 @@ public class AlarmActorTests : TestKit, IDisposable
var change = instanceProbe.ExpectMsg<AlarmStateChanged>(TimeSpan.FromSeconds(10)); var change = instanceProbe.ExpectMsg<AlarmStateChanged>(TimeSpan.FromSeconds(10));
Assert.Equal(AlarmState.Active, change.State); Assert.Equal(AlarmState.Active, change.State);
} }
/// <summary>
/// SRT-2: a failed/timed-out expression evaluation is "unknown" and leaves an Active alarm
/// Active. Pre-fix it was coerced to false: Active → Normal on the failure, then Normal →
/// Active (and a second on-trigger run) on the next successful evaluation.
/// </summary>
[Fact]
public void ExpressionEvalFailure_LeavesAnActiveAlarmActive()
{
var expr = CompileRawTriggerExpression("Attributes[\"A\"]?.ToString() == \"1\"");
var alarmConfig = new ResolvedAlarm
{
CanonicalName = "ExprKeepAlarm",
TriggerType = "Expression",
TriggerConfiguration = "{\"expression\":\"Attributes[\\\"A\\\"]?.ToString() == \\\"1\\\"\"}",
PriorityLevel = 1
};
var instanceProbe = CreateTestProbe();
var alarm = ActorOf(Props.Create(() => new AlarmActor(
"ExprKeepAlarm", "Pump1", instanceProbe.Ref, alarmConfig,
null, _sharedLibrary, _options,
NullLogger<AlarmActor>.Instance, expr)));
alarm.Tell(new AttributeValueChanged("Pump1", "A", "A", "1", "Good", DateTimeOffset.UtcNow));
Assert.Equal(AlarmState.Active, instanceProbe.ExpectMsg<AlarmStateChanged>(TimeSpan.FromSeconds(10)).State);
// One evaluation cannot be completed (timeout under load / task fault).
alarm.Tell(new AlarmActor.ExpressionEvalFailed(new TimeoutException("eval timed out")));
// The condition still holds; then it genuinely clears.
alarm.Tell(new AttributeValueChanged("Pump1", "A", "A", "1", "Good", DateTimeOffset.UtcNow));
alarm.Tell(new AttributeValueChanged("Pump1", "A", "A", "0", "Good", DateTimeOffset.UtcNow));
// Exactly one transition — the genuine clear. Pre-fix: Normal (the failure), Active, Normal.
Assert.Equal(AlarmState.Normal, instanceProbe.ExpectMsg<AlarmStateChanged>(TimeSpan.FromSeconds(10)).State);
instanceProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
}
} }
@@ -616,6 +616,75 @@ public class ScriptActorTests : TestKit, IDisposable
instance.ExpectMsg<SetStaticAttributeCommand>(TimeSpan.FromSeconds(2)); instance.ExpectMsg<SetStaticAttributeCommand>(TimeSpan.FromSeconds(2));
} }
/// <summary>
/// SRT-2: a REAL (non-seed) evaluation that faults or times out is "unknown", not false. Pre-fix
/// it stopped the running WhileTrue timer (and the next true evaluation fired a spurious edge run).
/// </summary>
[Fact]
public void ScriptActor_ExpressionWhileTrue_FaultedRealEval_DoesNotStopReFiring()
{
var triggerExpr = CompileTriggerExpression("Attributes[\"Active\"]?.ToString() == \"yes\"");
var (actor, instance) = CreateTriggeredActor(
"ExprRealFault",
"Expression",
"{\"expression\":\"Attributes[\\\"Active\\\"]?.ToString() == \\\"yes\\\"\",\"mode\":\"WhileTrue\"}",
TimeSpan.FromMilliseconds(300),
triggerExpr);
actor.Tell(Change("Active", "yes"));
instance.ExpectMsg<SetStaticAttributeCommand>(TimeSpan.FromSeconds(2)); // edge fire
instance.ExpectMsg<SetStaticAttributeCommand>(TimeSpan.FromSeconds(2)); // tick 1
actor.Tell(new ScriptActor.ExpressionEvalFailed(new TimeoutException("eval timed out")));
// Nothing real said the condition went false: the timer keeps re-firing (pre-fix: stopped).
instance.ExpectMsg<SetStaticAttributeCommand>(TimeSpan.FromSeconds(2));
instance.ExpectMsg<SetStaticAttributeCommand>(TimeSpan.FromSeconds(2));
}
/// <summary>
/// SRT-4: a Conditional WhileTrue trigger whose condition is adopted TRUE from a seed (a
/// persisted static override after failover/restart) re-fires on its cadence — without the
/// immediate edge run a seed never makes. Pre-fix it never fired again.
/// </summary>
[Fact]
public void ScriptActor_ConditionalWhileTrue_SeededTrue_StartsReFiringWithoutAnEdgeRun()
{
var (actor, instance) = CreateTriggeredActor(
"CondSeed",
"Conditional",
"{\"attributeName\":\"Temp\",\"operator\":\">\",\"threshold\":50,\"mode\":\"WhileTrue\"}",
TimeSpan.FromMilliseconds(300));
var sw = System.Diagnostics.Stopwatch.StartNew();
actor.Tell(new ZB.MOM.WW.ScadaBridge.SiteRuntime.Messages.AttributeValueSeed(Change("Temp", "100")));
instance.ExpectMsg<SetStaticAttributeCommand>(TimeSpan.FromSeconds(3)); // pre-fix: never
// The first run is a TIMER tick (≥ one 300 ms interval), not an immediate edge run.
Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(250), $"first run after {sw.Elapsed} — seed fired an edge run");
instance.ExpectMsg<SetStaticAttributeCommand>(TimeSpan.FromSeconds(3)); // and it keeps re-firing
}
/// <summary>SRT-4: the Expression twin — a seed-only evaluation that is true starts the WhileTrue timer.</summary>
[Fact]
public void ScriptActor_ExpressionWhileTrue_SeededTrue_StartsReFiringWithoutAnEdgeRun()
{
var triggerExpr = CompileTriggerExpression("Attributes[\"Active\"]?.ToString() == \"yes\"");
var (actor, instance) = CreateTriggeredActor(
"ExprSeed",
"Expression",
"{\"expression\":\"Attributes[\\\"Active\\\"]?.ToString() == \\\"yes\\\"\",\"mode\":\"WhileTrue\"}",
TimeSpan.FromMilliseconds(300),
triggerExpr);
var sw = System.Diagnostics.Stopwatch.StartNew();
actor.Tell(new ZB.MOM.WW.ScadaBridge.SiteRuntime.Messages.AttributeValueSeed(Change("Active", "yes")));
instance.ExpectMsg<SetStaticAttributeCommand>(TimeSpan.FromSeconds(3)); // pre-fix: never
Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(250), $"first run after {sw.Elapsed} — seed fired an edge run");
instance.ExpectMsg<SetStaticAttributeCommand>(TimeSpan.FromSeconds(3));
}
/// <summary>Verifies that an on-true expression trigger fires once per false-to-true edge.</summary> /// <summary>Verifies that an on-true expression trigger fires once per false-to-true edge.</summary>
[Fact] [Fact]
public void ScriptActor_ExpressionOnTrue_FiresOncePerFalseToTrueEdge() public void ScriptActor_ExpressionOnTrue_FiresOncePerFalseToTrueEdge()