fix(alarms): #999 K-4 a timed shelve expiring on a predicate evaluation emits Unshelved + AutoUnshelve audit
This commit is contained in:
@@ -122,7 +122,7 @@ rationale is recorded in the engine's class doc so it is not re-proposed:
|
||||
- `ApplyOneShotShelve` / `ApplyTimedShelve(unshelveAtUtc)` / `ApplyUnshelve` — shelving transitions. `Timed` requires `unshelveAtUtc > nowUtc`.
|
||||
- `ApplyEnable` / `ApplyDisable` — operator enable/disable. Disabled alarms ignore predicate results until re-enabled; on enable, `ActiveState` is re-derived from the next evaluation.
|
||||
- `ApplyAddComment(text)` — append-only audit entry, no state change.
|
||||
- `ApplyShelvingCheck(nowUtc)` — called by the 5s timer; promotes expired `Timed` shelving to `Unshelved` with a `system / AutoUnshelve` audit entry. The sole owner of timed-shelve expiry — the OPC UA node's own SDK timer does nothing.
|
||||
- `ApplyShelvingCheck(nowUtc)` — called by the 5s timer **and by the engine before every completed predicate evaluation** (serial and out-of-process batch paths, and at load); promotes expired `Timed` shelving to `Unshelved` with a `system / AutoUnshelve` audit entry and an `Unshelved` emission queued ahead of the predicate's own transition. The sole owner of timed-shelve expiry — the OPC UA node's own SDK timer does nothing, and `ApplyPredicate` no longer expires a timed shelve itself (#999 / review K-4: an input push that crossed the deadline before the timer used to unshelve the alarm silently — no event, no audit, the node stuck at TimedShelved).
|
||||
- `ApplyAcknowledge` on an already-acknowledged alarm is a no-op **unless it carries a comment**, which is recorded as an `AddComment` (emission `CommentAdded`; `LastAck*` untouched) — the OPC UA node reports a commented re-ack, so the system of record must hold the comment too.
|
||||
|
||||
Two invariants the machine enforces:
|
||||
|
||||
@@ -22,7 +22,8 @@ namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
|
||||
/// (2) Shelved alarms (OneShot / Timed) don't fire active transitions to
|
||||
/// subscribers, but the state record still advances so that when shelving
|
||||
/// expires the ActiveState reflects current reality. OneShot expires on the
|
||||
/// next clear; Timed expires at <see cref="ShelvingState.UnshelveAtUtc"/>.
|
||||
/// next clear; Timed expires at <see cref="ShelvingState.UnshelveAtUtc"/>, and only through
|
||||
/// <see cref="ApplyShelvingCheck"/> (#999 / K-4) — never inside <see cref="ApplyPredicate"/>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class Part9StateMachine
|
||||
@@ -44,8 +45,10 @@ public static class Part9StateMachine
|
||||
if (current.Enabled == AlarmEnabledState.Disabled)
|
||||
return TransitionResult.NoOp(current, "disabled — predicate result ignored");
|
||||
|
||||
// Expire timed shelving if the configured clock has passed.
|
||||
var shelving = MaybeExpireShelving(current.Shelving, nowUtc);
|
||||
// #999 / review K-4: a timed shelve is NOT expired here. Expiry belongs to ApplyShelvingCheck alone (it carries
|
||||
// the AutoUnshelve audit comment and the Unshelved emission); the engine runs it before this call. Expiring it
|
||||
// here returned EmissionKind.None — the alarm unshelved with no event and no audit.
|
||||
var shelving = current.Shelving;
|
||||
var stateWithShelving = current with { Shelving = shelving };
|
||||
|
||||
// Shelved alarms still update state but skip event emission.
|
||||
@@ -84,8 +87,7 @@ public static class Part9StateMachine
|
||||
return new TransitionResult(next, shelved ? EmissionKind.Suppressed : EmissionKind.Cleared);
|
||||
}
|
||||
|
||||
// Predicate matches current Active — no state change beyond possible shelving
|
||||
// expiry.
|
||||
// Predicate matches current Active — no state change.
|
||||
return new TransitionResult(stateWithShelving, EmissionKind.None);
|
||||
}
|
||||
|
||||
@@ -325,12 +327,6 @@ public static class Part9StateMachine
|
||||
return TransitionResult.None(current);
|
||||
}
|
||||
|
||||
private static ShelvingState MaybeExpireShelving(ShelvingState s, DateTime nowUtc)
|
||||
{
|
||||
if (s.Kind != ShelvingKind.Timed) return s;
|
||||
return s.UnshelveAtUtc is DateTime t && nowUtc >= t ? ShelvingState.Unshelved : s;
|
||||
}
|
||||
|
||||
private static ImmutableList<AlarmComment> AppendComment(
|
||||
ImmutableList<AlarmComment> existing, DateTime ts, string user, string kind, string? text)
|
||||
=> existing.Add(new AlarmComment(ts, user, kind, text ?? string.Empty));
|
||||
|
||||
@@ -508,7 +508,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
foreach (var (alarmId, state) in _alarms)
|
||||
{
|
||||
var seed = await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false);
|
||||
var evalSeed = ExpireTimedShelveAtLoad(state, seed.State, pending);
|
||||
var evalSeed = ExpireTimedShelve(state, seed.State, _clock(), pending);
|
||||
var afterPredicate = await EvaluatePredicateToStateAsync(state, evalSeed, nowUtc: _clock(), ct, pending)
|
||||
.ConfigureAwait(false);
|
||||
await SaveLoadedAsync(seed, afterPredicate, ct).ConfigureAwait(false);
|
||||
@@ -525,7 +525,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
{
|
||||
var seed = await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false);
|
||||
sources.Add(seed);
|
||||
seeds.Add((state, ExpireTimedShelveAtLoad(state, seed.State, pending)));
|
||||
seeds.Add((state, ExpireTimedShelve(state, seed.State, _clock(), pending)));
|
||||
}
|
||||
var after = await EvaluatePredicateBatchToStatesAsync(seeds, _clock(), ct, pending).ConfigureAwait(false);
|
||||
for (var i = 0; i < seeds.Count; i++)
|
||||
@@ -605,10 +605,16 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
/// 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)
|
||||
/// <remarks>
|
||||
/// #999 / review K-4: the same expiry runs before every completed predicate evaluation (serial and batch paths),
|
||||
/// not only at load — a push that crossed the deadline before the 5 s shelving timer otherwise unshelved the alarm
|
||||
/// silently and the OPC UA node stayed TimedShelved. <see cref="Part9StateMachine.ApplyPredicate"/> no longer
|
||||
/// expires a timed shelve itself, so the shelving check is the only place one expires.
|
||||
/// </remarks>
|
||||
private AlarmConditionState ExpireTimedShelve(
|
||||
AlarmState state, AlarmConditionState seed, DateTime nowUtc, List<ScriptedAlarmEvent> pendingEmissions)
|
||||
{
|
||||
var check = Part9StateMachine.ApplyShelvingCheck(seed, _clock());
|
||||
var check = Part9StateMachine.ApplyShelvingCheck(seed, nowUtc);
|
||||
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);
|
||||
@@ -1109,7 +1115,10 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
// QualityChanged on every push instead of once per real bucket change.
|
||||
var qualityBucketChanged = TrackQualityBucket(state.Definition.AlarmId, worstStatus);
|
||||
|
||||
var result = Part9StateMachine.ApplyPredicate(seed, predicateTrue, nowUtc);
|
||||
// #999 / K-4: an expired timed shelve is unshelved by the shelving check (Unshelved event + AutoUnshelve audit),
|
||||
// queued BEFORE the predicate's own transition, never silently inside ApplyPredicate.
|
||||
var result = Part9StateMachine.ApplyPredicate(
|
||||
ExpireTimedShelve(state, seed, nowUtc, pendingEmissions), predicateTrue, nowUtc);
|
||||
var transition = result.Emission != EmissionKind.None
|
||||
? BuildEmission(state, result.State, result.Emission, worstStatus, captured)
|
||||
: null;
|
||||
@@ -1285,7 +1294,10 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
|
||||
// From here on, identical to the serial path: the bucket is tracked only once the predicate completed (I3).
|
||||
var qualityBucketChanged = TrackQualityBucket(state.Definition.AlarmId, worstStatus);
|
||||
var result = Part9StateMachine.ApplyPredicate(seed, predicateTrue, nowUtc);
|
||||
// #999 / K-4: an expired timed shelve is unshelved by the shelving check (Unshelved event + AutoUnshelve audit),
|
||||
// queued BEFORE the predicate's own transition, never silently inside ApplyPredicate.
|
||||
var result = Part9StateMachine.ApplyPredicate(
|
||||
ExpireTimedShelve(state, seed, nowUtc, pendingEmissions), predicateTrue, nowUtc);
|
||||
var transition = result.Emission != EmissionKind.None
|
||||
? BuildEmission(state, result.State, result.Emission, worstStatus, captured)
|
||||
: null;
|
||||
|
||||
@@ -174,6 +174,18 @@ public sealed class Part9StateMachineTests
|
||||
after.State.Comments.Any(c => c.Kind == "AutoUnshelve").ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>#999 / K-4: ApplyPredicate never expires a timed shelve itself — that would unshelve silently.</summary>
|
||||
[Fact]
|
||||
public void ApplyPredicate_does_not_expire_a_timed_shelve()
|
||||
{
|
||||
var active = Part9StateMachine.ApplyPredicate(Fresh(), true, T0.AddSeconds(1)).State;
|
||||
var shelved = Part9StateMachine.ApplyTimedShelve(active, "alice", T0.AddMinutes(5), T0.AddSeconds(2)).State;
|
||||
|
||||
var r = Part9StateMachine.ApplyPredicate(shelved, true, T0.AddMinutes(6));
|
||||
r.State.Shelving.Kind.ShouldBe(ShelvingKind.Timed, "expiry is ApplyShelvingCheck's alone");
|
||||
r.Emission.ShouldBe(EmissionKind.None);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that unshelving an unshelved alarm is a no-op.</summary>
|
||||
[Fact]
|
||||
public void Unshelve_from_unshelved_is_noop()
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
using Serilog;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// #999 / review K-4 — a timed shelve whose deadline passes is unshelved by a predicate evaluation that
|
||||
/// arrives before the 5 s shelving timer. It must be the shelving check that expires it, so the evaluation emits
|
||||
/// exactly one <see cref="EmissionKind.Unshelved"/> and records exactly one <c>AutoUnshelve</c> audit comment
|
||||
/// (before the fix <c>ApplyPredicate</c> unshelved it silently: no event, no audit, the OPC UA node stayed
|
||||
/// TimedShelved). Covered on both the in-process path and the <see cref="IScriptRunner"/> batch path.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ScriptedAlarmEngineTimedShelveExpiryTests
|
||||
{
|
||||
private sealed class ThresholdRunner : IScriptRunner
|
||||
{
|
||||
private static ScriptRunOutcome Answer(ScriptInvocation i) => ScriptRunOutcome.Ok((int)i.Inputs["Temp"].Value! > 100);
|
||||
|
||||
public Task<ScriptRunOutcome> RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
|
||||
=> Task.FromResult(Answer(invocation));
|
||||
|
||||
public IReadOnlyList<Task<ScriptRunOutcome>> RunBatch(IReadOnlyList<ScriptInvocation> invocations, CancellationToken ct = default)
|
||||
=> invocations.Select(i => Task.FromResult(Answer(i))).ToArray();
|
||||
|
||||
public void Reset(ScriptContextKind kind) { }
|
||||
|
||||
public IReadOnlyCollection<string> QuarantinedKeys(ScriptContextKind kind) => [];
|
||||
}
|
||||
|
||||
private static async Task WaitFor(Func<bool> probe, string what)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
if (probe()) return;
|
||||
await Task.Delay(10);
|
||||
}
|
||||
throw new TimeoutException(what);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task A_predicate_evaluation_after_the_deadline_emits_Unshelved_and_audits_AutoUnshelve(bool outOfProcess)
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var now = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
var up = new FakeUpstream();
|
||||
up.Set("Temp", 150);
|
||||
var logger = new LoggerConfiguration().CreateLogger();
|
||||
using var eng = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger,
|
||||
clock: () => now, scriptRunner: outOfProcess ? new ThresholdRunner() : null);
|
||||
await eng.LoadAsync(
|
||||
[new ScriptedAlarmDefinition("HighTemp", "Plant/Line1/Reactor", "HighTemp", AlarmKind.AlarmCondition,
|
||||
AlarmSeverity.High, "condition", """return (int)ctx.GetTag("Temp").Value > 100;""")],
|
||||
ct);
|
||||
eng.GetState("HighTemp")!.Active.ShouldBe(AlarmActiveState.Active);
|
||||
|
||||
await eng.TimedShelveAsync("HighTemp", "alice", now.AddMinutes(10), ct);
|
||||
var events = new List<ScriptedAlarmEvent>();
|
||||
eng.OnEvent += (_, e) => { lock (events) events.Add(e); };
|
||||
|
||||
// Past the deadline; the input moves but the predicate stays true, so the only possible transition is the
|
||||
// expiry. The shelving check is NOT run — the evaluation alone has to surface it.
|
||||
now = now.AddMinutes(11);
|
||||
up.Push("Temp", 160);
|
||||
|
||||
await WaitFor(() => { lock (events) return events.Any(e => e.Emission == EmissionKind.Unshelved); },
|
||||
"the evaluation that crossed the deadline emitted Unshelved");
|
||||
var state = eng.GetState("HighTemp")!;
|
||||
state.Shelving.Kind.ShouldBe(ShelvingKind.Unshelved);
|
||||
state.Active.ShouldBe(AlarmActiveState.Active);
|
||||
state.Comments.Count(c => c.Kind == "AutoUnshelve").ShouldBe(1);
|
||||
|
||||
// The shelving timer, running afterwards, finds nothing left to expire: still exactly one event.
|
||||
eng.RunShelvingCheckForTest();
|
||||
await WaitFor(() => eng.InFlightCountForTest == 0, "shelving check finished");
|
||||
// Positive control: a later clear does arrive, so an absent second Unshelved is not just "not processed yet".
|
||||
up.Push("Temp", 50);
|
||||
await WaitFor(() => { lock (events) return events.Any(e => e.Emission == EmissionKind.Cleared); }, "clear arrives");
|
||||
lock (events) events.Count(e => e.Emission == EmissionKind.Unshelved).ShouldBe(1);
|
||||
eng.GetState("HighTemp")!.Comments.Count(c => c.Kind == "AutoUnshelve").ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_activation_that_crosses_the_deadline_emits_Unshelved_then_Activated()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var now = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
var up = new FakeUpstream();
|
||||
up.Set("Temp", 50);
|
||||
var logger = new LoggerConfiguration().CreateLogger();
|
||||
using var eng = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger,
|
||||
clock: () => now);
|
||||
await eng.LoadAsync(
|
||||
[new ScriptedAlarmDefinition("HighTemp", "Plant/Line1/Reactor", "HighTemp", AlarmKind.AlarmCondition,
|
||||
AlarmSeverity.High, "condition", """return (int)ctx.GetTag("Temp").Value > 100;""")],
|
||||
ct);
|
||||
await eng.TimedShelveAsync("HighTemp", "alice", now.AddMinutes(10), ct);
|
||||
var events = new List<ScriptedAlarmEvent>();
|
||||
eng.OnEvent += (_, e) => { lock (events) events.Add(e); };
|
||||
|
||||
now = now.AddMinutes(11);
|
||||
up.Push("Temp", 150);
|
||||
|
||||
await WaitFor(() => { lock (events) return events.Any(e => e.Emission == EmissionKind.Activated); },
|
||||
"activation after expiry is not suppressed");
|
||||
lock (events)
|
||||
events.Select(e => e.Emission).ShouldBe([EmissionKind.Unshelved, EmissionKind.Activated]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user