02d227cc32
S1: ApplyAsync looked its alarm up before taking _evalGate, so a command racing a LoadAsync applied to the load's interim Fresh entry (an ack no-op that then saved Fresh over the carried Active condition — the #935 re-Activate on the next push) or wrote an old-generation state over the new one. The lookup is now under the gate: a command queued behind a load applies to the generation that load produced. A command that changes nothing (value-equal result) writes nothing. S2: a load re-saved every alarm's post-predicate state, so a node that missed an operator command upserted its stale carried state over the LocalDb last-writer-wins row on every deploy. A held seed (carried or persisted) left value-equal is not written. The push path's ReferenceEquals check (always false: ApplyPredicate returns a clone) is now value equality too, so a no-op re-evaluation no longer writes/replicates. S3: a failed load ends the generation. The engine is blind until the next good load, so (decision, same rule as removed/disabled alarms) that load reads the store — a still-true alarm is a new occurrence — instead of restating the pre-failure snapshot. While blind, operator commands throw ScriptedAlarmCommandRejectedException (the host logs it distinctly; the command topic is fire-and-forget, so that Warning is the record) and queued re-evaluations / shelving checks are dropped. N5: a timed shelve that expired before a load is unshelved through the shelving check (AutoUnshelve audit + Unshelved emission), not silently by ApplyPredicate. Tests (each red on revert, verified): ack racing a held load (S1), idempotent command (S1), restatement vs real change saves (S2), no-op push saves (S2), command rejected after failed load (S3), re-evaluation after failed load (S3), failed load -> new occurrence + store fault mid-seed -> one Activated (S3/S4), runner Unavailable at reload freezes carried state (S4), expired timed shelve at load (N5). N4: the Bad-input reload test now waits on a Good-bucket QualityChanged.
621 lines
31 KiB
C#
621 lines
31 KiB
C#
using System.Collections.Concurrent;
|
|
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>
|
|
/// #935 — a same-process reload (every deploy runs <see cref="ScriptedAlarmEngine.LoadAsync"/>) is a
|
|
/// RESTATEMENT, not a new occurrence. The production store does not persist <c>Active</c>, so seeding a surviving
|
|
/// alarm from the store turned every deploy into an Inactive→Active transition: Acked reset to Unacknowledged, an
|
|
/// <c>Activated</c> emission (a duplicate <c>alerts</c> / historian row), and <c>LastTransitionUtc</c> moved to the
|
|
/// deploy instant. A surviving alarm id is now seeded from the engine's previous in-memory condition
|
|
/// (<c>previous ?? persisted ?? Fresh</c>); a process restart keeps the documented persisted-state behaviour.
|
|
/// </summary>
|
|
[Trait("Category", "Unit")]
|
|
public sealed class ScriptedAlarmEngineReloadRestatementTests
|
|
{
|
|
private const string Hot = """return (int)ctx.GetTag("Temp").Value > 100;""";
|
|
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
|
|
|
/// <summary>Behaves like <c>LocalDbAlarmConditionStateStore</c>: there is no Active column, so a loaded row is
|
|
/// Inactive with no LastActive/LastCleared — which is exactly what made every reload re-activate.</summary>
|
|
private sealed class ActiveDroppingStore : IAlarmStateStore
|
|
{
|
|
private readonly ConcurrentDictionary<string, AlarmConditionState> _rows = new(StringComparer.Ordinal);
|
|
|
|
public int Loads;
|
|
|
|
/// <summary>Every saved state, in order (S2: which loads write the replicated row).</summary>
|
|
public ConcurrentQueue<AlarmConditionState> Saves { get; } = new();
|
|
|
|
/// <summary>Optional hook run by <see cref="LoadAsync"/> before it answers — block it (S1) or throw (S4).</summary>
|
|
public Func<string, Task>? OnLoad { get; set; }
|
|
|
|
/// <summary>Overwrites a row directly — what a replicated write from the peer node does.</summary>
|
|
public void Put(AlarmConditionState row) => _rows[row.AlarmId] = row;
|
|
|
|
public async Task<AlarmConditionState?> LoadAsync(string alarmId, CancellationToken ct)
|
|
{
|
|
Interlocked.Increment(ref Loads);
|
|
if (OnLoad is { } hook) await hook(alarmId);
|
|
return _rows.TryGetValue(alarmId, out var r)
|
|
? r with { Active = AlarmActiveState.Inactive, LastActiveUtc = null, LastClearedUtc = null }
|
|
: null;
|
|
}
|
|
|
|
public Task<IReadOnlyList<AlarmConditionState>> LoadAllAsync(CancellationToken ct)
|
|
=> Task.FromResult<IReadOnlyList<AlarmConditionState>>(_rows.Values.ToArray());
|
|
|
|
public Task SaveAsync(AlarmConditionState state, CancellationToken ct)
|
|
{
|
|
Saves.Enqueue(state);
|
|
_rows[state.AlarmId] = state;
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task RemoveAsync(string alarmId, CancellationToken ct)
|
|
{
|
|
_rows.TryRemove(alarmId, out _);
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
|
|
/// <summary>A stepping clock, so "unchanged LastTransitionUtc" is not satisfied by two reads in the same tick.</summary>
|
|
private sealed class StepClock
|
|
{
|
|
private DateTime _now = new(2026, 11, 25, 8, 0, 0, DateTimeKind.Utc);
|
|
public DateTime Now() => _now = _now.AddSeconds(1);
|
|
}
|
|
|
|
private sealed class Rig : IDisposable
|
|
{
|
|
public FakeUpstream Up { get; } = new();
|
|
public ActiveDroppingStore Store { get; }
|
|
public StepClock Clock { get; } = new();
|
|
public ScriptedAlarmEngine Engine { get; }
|
|
public ConcurrentQueue<ScriptedAlarmEvent> Events { get; } = new();
|
|
public ConcurrentQueue<string> Flips { get; } = new();
|
|
|
|
public Rig(ActiveDroppingStore? store = null, IScriptRunner? runner = null)
|
|
{
|
|
Store = store ?? new ActiveDroppingStore();
|
|
var logger = new LoggerConfiguration().CreateLogger();
|
|
Engine = new ScriptedAlarmEngine(Up, Store, new ScriptLoggerFactory(logger), logger, Clock.Now,
|
|
scriptRunner: runner);
|
|
Engine.OnEvent += (_, e) => Events.Enqueue(e);
|
|
Engine.OnInputsEstablished += (_, e) => Flips.Enqueue($"{e.AlarmId}:{e.Established}");
|
|
}
|
|
|
|
public void Dispose() => Engine.Dispose();
|
|
}
|
|
|
|
private static ScriptedAlarmDefinition Alarm(string id = "HighTemp", string predicate = Hot,
|
|
AlarmSeverity severity = AlarmSeverity.High, string message = "hot", string equipment = "Plant/Line1/Reactor") =>
|
|
new(AlarmId: id, EquipmentPath: equipment, AlarmName: id, Kind: AlarmKind.AlarmCondition,
|
|
Severity: severity, MessageTemplate: message, PredicateScriptSource: predicate);
|
|
|
|
/// <summary>Activate (Temp=150 at load) and acknowledge — the state an operator leaves behind before a deploy.</summary>
|
|
private static async Task<AlarmConditionState> ActiveAndAcked(Rig rig, params ScriptedAlarmDefinition[] defs)
|
|
{
|
|
rig.Up.Set("Temp", 150);
|
|
await rig.Engine.LoadAsync(defs.Length == 0 ? [Alarm()] : defs, Ct);
|
|
rig.Engine.GetState("HighTemp")!.Active.ShouldBe(AlarmActiveState.Active);
|
|
await rig.Engine.AcknowledgeAsync("HighTemp", "alice", "seen", Ct);
|
|
var before = rig.Engine.GetState("HighTemp")!;
|
|
before.Acked.ShouldBe(AlarmAckedState.Acknowledged);
|
|
rig.Events.Clear();
|
|
rig.Flips.Clear();
|
|
return before;
|
|
}
|
|
|
|
/// <summary>The regression: an acknowledged active alarm survives a reload still Active + Acked, with NO
|
|
/// emission (so nothing reaches <c>alerts</c>), the same <c>LastTransitionUtc</c> (the condition Time the
|
|
/// re-assert writes) and no Ack reset — which is what keeps the origin's activation marker from bumping
|
|
/// (it advances only on an Active rise or an Acked→Unacked fall). Known-state semantics are unchanged: the
|
|
/// reload still re-raises the established flip once its first evaluation completes.</summary>
|
|
[Fact]
|
|
public async Task An_acked_active_alarm_survives_a_reload_as_a_restatement()
|
|
{
|
|
using var rig = new Rig();
|
|
var before = await ActiveAndAcked(rig);
|
|
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
|
|
var after = rig.Engine.GetState("HighTemp")!;
|
|
after.Active.ShouldBe(AlarmActiveState.Active);
|
|
after.Acked.ShouldBe(AlarmAckedState.Acknowledged, "an operator never re-acks because someone deployed");
|
|
after.Confirmed.ShouldBe(before.Confirmed);
|
|
after.LastTransitionUtc.ShouldBe(before.LastTransitionUtc, "condition Time must not move to the deploy instant");
|
|
after.LastActiveUtc.ShouldBe(before.LastActiveUtc);
|
|
after.LastAckUser.ShouldBe("alice");
|
|
after.Comments.ShouldBe(before.Comments);
|
|
rig.Events.ShouldBeEmpty("a restatement is not a transition — no Activated, so no alerts row");
|
|
rig.Flips.ShouldBe(["HighTemp:True"]);
|
|
// The ack was persisted when it was applied, so a later engine incarnation still restores it.
|
|
(await rig.Store.LoadAsync("HighTemp", Ct))!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
|
|
}
|
|
|
|
/// <summary>An unacked active alarm stays exactly that — Unacknowledged, Unconfirmed — with no emission.</summary>
|
|
[Fact]
|
|
public async Task An_unacked_active_alarm_is_restated_unchanged()
|
|
{
|
|
using var rig = new Rig();
|
|
rig.Up.Set("Temp", 150);
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
var before = rig.Engine.GetState("HighTemp")!;
|
|
rig.Events.Clear();
|
|
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
|
|
rig.Engine.GetState("HighTemp").ShouldBe(before);
|
|
rig.Events.ShouldBeEmpty();
|
|
}
|
|
|
|
/// <summary>A predicate that went false while the reload was pending still clears properly: one Cleared
|
|
/// transition, the ack carried over (Part 9: ack belongs to the occurrence that just cleared).</summary>
|
|
[Fact]
|
|
public async Task A_predicate_that_went_false_during_the_reload_clears()
|
|
{
|
|
using var rig = new Rig();
|
|
await ActiveAndAcked(rig);
|
|
|
|
rig.Up.Set("Temp", 50);
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
|
|
var after = rig.Engine.GetState("HighTemp")!;
|
|
after.Active.ShouldBe(AlarmActiveState.Inactive);
|
|
after.Acked.ShouldBe(AlarmAckedState.Acknowledged);
|
|
rig.Events.Select(e => e.Emission).ShouldBe([EmissionKind.Cleared]);
|
|
}
|
|
|
|
/// <summary>Decision: identity is the alarm id. An edited severity / message / equipment path on the same id is
|
|
/// the same alarm — its condition carries over (no new occurrence) and the next projection carries the new
|
|
/// definition.</summary>
|
|
[Fact]
|
|
public async Task An_edited_definition_with_a_still_true_predicate_is_the_same_alarm()
|
|
{
|
|
using var rig = new Rig();
|
|
var before = await ActiveAndAcked(rig);
|
|
|
|
await rig.Engine.LoadAsync([Alarm(
|
|
predicate: """return (int)ctx.GetTag("Temp").Value > 120;""",
|
|
severity: AlarmSeverity.Critical, message: "very hot", equipment: "Plant/Line2/Reactor")], Ct);
|
|
|
|
var after = rig.Engine.GetState("HighTemp")!;
|
|
after.Active.ShouldBe(AlarmActiveState.Active);
|
|
after.Acked.ShouldBe(AlarmAckedState.Acknowledged);
|
|
after.LastTransitionUtc.ShouldBe(before.LastTransitionUtc);
|
|
rig.Events.ShouldBeEmpty();
|
|
var projection = rig.Engine.GetProjections().Single();
|
|
projection.Severity.ShouldBe(AlarmSeverity.Critical);
|
|
projection.Message.ShouldBe("very hot");
|
|
}
|
|
|
|
/// <summary>…and an edited predicate that is now false is a real clear of that same occurrence.</summary>
|
|
[Fact]
|
|
public async Task An_edited_predicate_that_is_now_false_clears_the_carried_occurrence()
|
|
{
|
|
using var rig = new Rig();
|
|
await ActiveAndAcked(rig);
|
|
|
|
await rig.Engine.LoadAsync([Alarm(predicate: """return (int)ctx.GetTag("Temp").Value > 200;""")], Ct);
|
|
|
|
rig.Engine.GetState("HighTemp")!.Active.ShouldBe(AlarmActiveState.Inactive);
|
|
rig.Events.Select(e => e.Emission).ShouldBe([EmissionKind.Cleared]);
|
|
}
|
|
|
|
/// <summary>Decision: removed-and-re-added in ONE deploy is indistinguishable from surviving (same id in both
|
|
/// generations) ⇒ carried. Removed by one deploy (or disabled — the host does not load a disabled plan) and
|
|
/// re-added by a later one is a NEW occurrence: the engine stopped evaluating it, so it falls back to the
|
|
/// persisted state exactly like a restart (Active re-derived ⇒ Activated, Unacknowledged).</summary>
|
|
[Fact]
|
|
public async Task An_alarm_absent_from_the_previous_generation_falls_back_to_the_store()
|
|
{
|
|
using var rig = new Rig();
|
|
await ActiveAndAcked(rig);
|
|
|
|
await rig.Engine.LoadAsync([Alarm("Other", """return false;""")], Ct); // HighTemp removed / disabled
|
|
rig.Events.Clear();
|
|
await rig.Engine.LoadAsync([Alarm(), Alarm("Other", """return false;""")], Ct); // re-added
|
|
|
|
var after = rig.Engine.GetState("HighTemp")!;
|
|
after.Active.ShouldBe(AlarmActiveState.Active);
|
|
after.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
|
|
rig.Events.Select(e => (e.AlarmId, e.Emission)).ShouldBe([("HighTemp", EmissionKind.Activated)]);
|
|
}
|
|
|
|
/// <summary>Shelving (incl. a timed shelve's expiry instant), Confirmed and an operator Disable carry over
|
|
/// verbatim; the shelving timer restarts with the load and still expires against the carried instant.</summary>
|
|
[Fact]
|
|
public async Task Shelving_confirm_and_disable_carry_over()
|
|
{
|
|
using var rig = new Rig();
|
|
rig.Up.Set("Temp", 150);
|
|
await rig.Engine.LoadAsync([Alarm(), Alarm("Disabled", Hot)], Ct);
|
|
var unshelveAt = new DateTime(2026, 11, 26, 0, 0, 0, DateTimeKind.Utc);
|
|
await rig.Engine.TimedShelveAsync("HighTemp", "bob", unshelveAt, Ct);
|
|
await rig.Engine.AcknowledgeAsync("HighTemp", "bob", null, Ct);
|
|
await rig.Engine.ConfirmAsync("HighTemp", "bob", null, Ct);
|
|
await rig.Engine.DisableAsync("Disabled", "bob", Ct);
|
|
var shelved = rig.Engine.GetState("HighTemp")!;
|
|
var disabled = rig.Engine.GetState("Disabled")!;
|
|
rig.Events.Clear();
|
|
|
|
await rig.Engine.LoadAsync([Alarm(), Alarm("Disabled", Hot)], Ct);
|
|
|
|
rig.Engine.GetState("HighTemp").ShouldBe(shelved);
|
|
rig.Engine.GetState("HighTemp")!.Shelving.ShouldBe(new ShelvingState(ShelvingKind.Timed, unshelveAt));
|
|
rig.Engine.GetState("HighTemp")!.Confirmed.ShouldBe(AlarmConfirmedState.Confirmed);
|
|
rig.Engine.GetState("Disabled").ShouldBe(disabled);
|
|
rig.Events.ShouldBeEmpty();
|
|
}
|
|
|
|
/// <summary>The surviving alarm is seeded from memory — the store is not consulted for it (it would answer
|
|
/// Inactive). A new alarm in the same load still reads the store.</summary>
|
|
[Fact]
|
|
public async Task A_surviving_alarm_does_not_read_the_store_but_a_new_one_does()
|
|
{
|
|
using var rig = new Rig();
|
|
await ActiveAndAcked(rig);
|
|
var loads = rig.Store.Loads;
|
|
|
|
await rig.Engine.LoadAsync([Alarm(), Alarm("New", """return false;""")], Ct);
|
|
|
|
(rig.Store.Loads - loads).ShouldBe(1);
|
|
}
|
|
|
|
/// <summary>#935 review S3 decision: a failed reload (compile error) ends the generation. The engine was
|
|
/// unsubscribed and blind from then until the next good load, so — like an alarm a deploy removed or disabled —
|
|
/// a still-true alarm is a NEW occurrence on that load: seeded from the store (Activated, Unacknowledged), never
|
|
/// restated from the pre-failure snapshot (which could hide a clear + re-fire inside the window).</summary>
|
|
[Fact]
|
|
public async Task A_failed_reload_ends_the_generation_so_the_next_good_load_reads_the_store()
|
|
{
|
|
using var rig = new Rig();
|
|
await ActiveAndAcked(rig);
|
|
|
|
await Should.ThrowAsync<InvalidOperationException>(
|
|
() => rig.Engine.LoadAsync([Alarm(), Alarm("Broken", "return unknownIdentifier;")], Ct));
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
|
|
var after = rig.Engine.GetState("HighTemp")!;
|
|
after.Active.ShouldBe(AlarmActiveState.Active);
|
|
after.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
|
|
after.LastAckUser.ShouldBe("alice", "the persisted audit trail survives, as on a restart");
|
|
rig.Events.Select(e => (e.AlarmId, e.Emission)).ShouldBe([("HighTemp", EmissionKind.Activated)]);
|
|
}
|
|
|
|
/// <summary>#935 review S3: while a failed load has left no trusted generation, an operator command is REJECTED
|
|
/// (a distinct exception the host logs) rather than applied to a Fresh entry and persisted over the real row —
|
|
/// which the next good load then reads (it used to be discarded by the stale carry-over instead).</summary>
|
|
[Fact]
|
|
public async Task An_operator_command_after_a_failed_reload_is_rejected_and_persists_nothing()
|
|
{
|
|
using var rig = new Rig();
|
|
await ActiveAndAcked(rig);
|
|
await Should.ThrowAsync<InvalidOperationException>(
|
|
() => rig.Engine.LoadAsync([Alarm(), Alarm("Broken", "return unknownIdentifier;")], Ct));
|
|
rig.Store.Saves.Clear();
|
|
|
|
var ex = await Should.ThrowAsync<ScriptedAlarmCommandRejectedException>(
|
|
() => rig.Engine.OneShotShelveAsync("HighTemp", "bob", Ct));
|
|
ex.AlarmId.ShouldBe("HighTemp");
|
|
await Should.ThrowAsync<ScriptedAlarmCommandRejectedException>(
|
|
() => rig.Engine.AddCommentAsync("HighTemp", "bob", "note", Ct));
|
|
|
|
rig.Store.Saves.ShouldBeEmpty();
|
|
(await rig.Store.LoadAsync("HighTemp", Ct))!.Acked.ShouldBe(AlarmAckedState.Acknowledged,
|
|
"the row still holds alice's ack — not a Fresh-derived state");
|
|
|
|
// …and the next good load serves commands again.
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
await rig.Engine.OneShotShelveAsync("HighTemp", "bob", Ct);
|
|
rig.Engine.GetState("HighTemp")!.Shelving.Kind.ShouldBe(ShelvingKind.OneShot);
|
|
}
|
|
|
|
/// <summary>#935 review S3: a re-evaluation queued behind a failed load does not evaluate its Fresh entries — an
|
|
/// Activated from one would be a phantom occurrence (and its save would overwrite the real row).</summary>
|
|
[Fact]
|
|
public async Task A_reevaluation_after_a_failed_reload_does_not_evaluate_the_half_built_generation()
|
|
{
|
|
using var rig = new Rig();
|
|
await ActiveAndAcked(rig);
|
|
await Should.ThrowAsync<InvalidOperationException>(
|
|
() => rig.Engine.LoadAsync([Alarm(), Alarm("Broken", "return unknownIdentifier;")], Ct));
|
|
rig.Store.Saves.Clear();
|
|
|
|
rig.Engine.OnUpstreamChange("Temp", new DataValueSnapshot(170, 0u, DateTime.UtcNow, DateTime.UtcNow));
|
|
await Task.Delay(500, Ct); // let the drainer run against the failed generation
|
|
rig.Events.ShouldBeEmpty();
|
|
rig.Store.Saves.ShouldBeEmpty();
|
|
// Positive control: a good load afterwards does evaluate (and fires the new-occurrence Activated) — so the
|
|
// absence below is not just "nothing ran yet".
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
|
|
rig.Events.Select(e => e.Emission).ShouldBe([EmissionKind.Activated], "exactly one — from the good load");
|
|
}
|
|
|
|
/// <summary>#935 review S1 decision: an operator command racing a LoadAsync is applied AFTER the load, to the
|
|
/// generation it produced. The alarm is looked up under the gate — looked up before it, the ack captured the
|
|
/// load's interim Fresh entry, was a no-op on it, and then saved Fresh over the carried Active condition (engine
|
|
/// Inactive while the predicate is true; the next push re-fired Activated and wrote a duplicate alerts row).</summary>
|
|
[Fact]
|
|
public async Task An_ack_racing_a_reload_applies_to_the_new_generation()
|
|
{
|
|
using var rig = new Rig();
|
|
rig.Up.Set("Temp", 150);
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
rig.Engine.GetState("HighTemp")!.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
|
|
var activatedAt = rig.Engine.GetState("HighTemp")!.LastActiveUtc;
|
|
rig.Events.Clear();
|
|
|
|
// Hold the reload at its value-cache seed: it owns the gate and every entry is the interim Fresh one.
|
|
using var loadReached = new ManualResetEventSlim();
|
|
using var release = new ManualResetEventSlim();
|
|
rig.Up.OnRead = _ => { loadReached.Set(); release.Wait(TimeSpan.FromSeconds(30)); };
|
|
var load = Task.Run(() => rig.Engine.LoadAsync([Alarm()], Ct), Ct);
|
|
loadReached.Wait(TimeSpan.FromSeconds(10), Ct).ShouldBeTrue();
|
|
rig.Up.OnRead = null;
|
|
rig.Engine.GetState("HighTemp")!.Active.ShouldBe(AlarmActiveState.Inactive, "precondition: the interim entry is Fresh");
|
|
|
|
var ack = rig.Engine.AcknowledgeAsync("HighTemp", "alice", "seen", Ct);
|
|
await Task.Delay(100, Ct);
|
|
ack.IsCompleted.ShouldBeFalse("the ack waits for the load's gate");
|
|
release.Set();
|
|
await load;
|
|
await ack;
|
|
|
|
var after = rig.Engine.GetState("HighTemp")!;
|
|
after.Active.ShouldBe(AlarmActiveState.Active, "the carried Active condition was not overwritten");
|
|
after.Acked.ShouldBe(AlarmAckedState.Acknowledged, "the ack applied to the new generation");
|
|
after.LastAckUser.ShouldBe("alice");
|
|
after.LastActiveUtc.ShouldBe(activatedAt, "the same occurrence");
|
|
var row = (await rig.Store.LoadAsync("HighTemp", Ct))!;
|
|
row.Acked.ShouldBe(AlarmAckedState.Acknowledged);
|
|
|
|
rig.Up.Push("Temp", 160); // still true — must stay a non-event
|
|
await WaitFor(() => rig.Flips.Contains("HighTemp:True"));
|
|
await Task.Delay(100, Ct);
|
|
rig.Events.ShouldNotContain(e => e.Emission == EmissionKind.Activated);
|
|
rig.Events.Where(e => e.AlarmId == "HighTemp").Select(e => e.Emission).ShouldBe([EmissionKind.Acknowledged]);
|
|
}
|
|
|
|
/// <summary>#935 review S1: a command that changes nothing (an uncommented re-ack) writes nothing.</summary>
|
|
[Fact]
|
|
public async Task An_idempotent_command_does_not_write_the_store()
|
|
{
|
|
using var rig = new Rig();
|
|
await ActiveAndAcked(rig);
|
|
rig.Store.Saves.Clear();
|
|
|
|
await rig.Engine.AcknowledgeAsync("HighTemp", "bob", null, Ct);
|
|
|
|
rig.Store.Saves.ShouldBeEmpty();
|
|
rig.Engine.GetState("HighTemp")!.LastAckUser.ShouldBe("alice");
|
|
}
|
|
|
|
/// <summary>#935 review S2: a restatement writes nothing back. The row is replicated last-writer-wins, so a node
|
|
/// that missed an operator command (here: the peer's ack replicated into the row, not into this node's memory)
|
|
/// must not push its stale carried state over the converged row on every deploy — the next engine incarnation
|
|
/// then restores the peer's ack. A reload that CHANGES the alarm still writes it.</summary>
|
|
[Fact]
|
|
public async Task A_restatement_does_not_write_the_store_but_a_real_change_does()
|
|
{
|
|
using var rig = new Rig();
|
|
rig.Up.Set("Temp", 150);
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
var stale = rig.Engine.GetState("HighTemp")!;
|
|
stale.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
|
|
// The peer acked; replication delivered its row, this node never saw the command.
|
|
rig.Store.Put(stale with { Acked = AlarmAckedState.Acknowledged, LastAckUser = "peer" });
|
|
rig.Store.Saves.Clear();
|
|
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
|
|
rig.Store.Saves.ShouldBeEmpty("an unchanged carried alarm is not re-saved");
|
|
(await rig.Store.LoadAsync("HighTemp", Ct))!.LastAckUser.ShouldBe("peer", "the converged row is intact");
|
|
|
|
rig.Up.Set("Temp", 50);
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
rig.Store.Saves.Select(s => s.Active).ShouldBe([AlarmActiveState.Inactive], "the clear is persisted");
|
|
}
|
|
|
|
/// <summary>#935 review S2 (same rule on the push path): a re-evaluation whose predicate agrees with the held
|
|
/// condition writes nothing — the reference check it used saved (and replicated) on every push, because
|
|
/// ApplyPredicate always returns a clone. A push that does change it (a clear) is still persisted.</summary>
|
|
[Fact]
|
|
public async Task A_push_that_changes_nothing_does_not_write_the_store()
|
|
{
|
|
using var rig = new Rig();
|
|
await ActiveAndAcked(rig);
|
|
rig.Store.Saves.Clear();
|
|
|
|
rig.Up.Push("Temp", 160); // still true
|
|
rig.Up.Push("Temp", 50); // positive control: clears
|
|
await WaitFor(() => rig.Events.Any(e => e.Emission == EmissionKind.Cleared));
|
|
|
|
rig.Store.Saves.Select(x => x.Active).ShouldBe([AlarmActiveState.Inactive]);
|
|
}
|
|
|
|
/// <summary>#935 review S4: the out-of-process runner is Unavailable at the reload — the carried condition is
|
|
/// frozen (Active, Acked, same LastTransitionUtc), annotated BadResourceUnavailable, NOT established and NOT
|
|
/// re-saved; when the runner recovers the alarm re-evaluates to a non-event and is established.</summary>
|
|
[Fact]
|
|
public async Task A_runner_unavailable_at_reload_freezes_the_carried_condition_until_recovery()
|
|
{
|
|
var runner = new SwitchableRunner();
|
|
using var rig = new Rig(runner: runner);
|
|
var before = await ActiveAndAcked(rig);
|
|
rig.Store.Saves.Clear();
|
|
|
|
var recovery = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
runner.UnavailableUntil = recovery.Task;
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
|
|
rig.Engine.GetState("HighTemp").ShouldBe(before);
|
|
rig.Events.Select(e => (e.Emission, e.WorstInputStatusCode))
|
|
.ShouldBe([(EmissionKind.QualityChanged, 0x80040000u)]);
|
|
rig.Flips.ShouldBeEmpty("a frozen condition is not established");
|
|
rig.Store.Saves.ShouldBeEmpty();
|
|
|
|
runner.UnavailableUntil = null;
|
|
recovery.SetResult();
|
|
await WaitFor(() => rig.Flips.Contains("HighTemp:True"));
|
|
rig.Engine.GetState("HighTemp")!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
|
|
rig.Engine.GetState("HighTemp")!.LastTransitionUtc.ShouldBe(before.LastTransitionUtc);
|
|
rig.Events.ShouldNotContain(e => e.Emission == EmissionKind.Activated);
|
|
}
|
|
|
|
/// <summary>#935 review S4: a store fault mid-seed fails the load; the next good load is a new occurrence read
|
|
/// from the store (the S3 rule), with exactly one Activated — the failed load's own emissions were dropped.</summary>
|
|
[Fact]
|
|
public async Task A_store_fault_mid_seed_then_a_good_load_is_a_single_new_occurrence()
|
|
{
|
|
using var rig = new Rig();
|
|
await ActiveAndAcked(rig);
|
|
rig.Store.OnLoad = id => id == "New" ? throw new IOException("database is locked") : Task.CompletedTask;
|
|
|
|
await Should.ThrowAsync<IOException>(
|
|
() => rig.Engine.LoadAsync([Alarm(), Alarm("New", """return false;""")], Ct));
|
|
rig.Events.ShouldBeEmpty("a failed load fires nothing");
|
|
rig.Store.OnLoad = null;
|
|
await rig.Engine.LoadAsync([Alarm(), Alarm("New", """return false;""")], Ct);
|
|
|
|
rig.Engine.GetState("HighTemp")!.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
|
|
rig.Engine.GetState("HighTemp")!.LastAckUser.ShouldBe("alice");
|
|
rig.Events.Select(e => (e.AlarmId, e.Emission)).ShouldBe([("HighTemp", EmissionKind.Activated)]);
|
|
}
|
|
|
|
/// <summary>#935 review N5: a carried timed shelve that expired before the reload is unshelved through the
|
|
/// shelving check — an AutoUnshelve audit entry and an Unshelved emission — not silently by the predicate.</summary>
|
|
[Fact]
|
|
public async Task A_timed_shelve_that_expired_before_a_reload_is_unshelved_with_audit()
|
|
{
|
|
using var rig = new Rig();
|
|
await ActiveAndAcked(rig);
|
|
var soon = rig.Clock.Now().AddSeconds(2);
|
|
await rig.Engine.TimedShelveAsync("HighTemp", "bob", soon, Ct);
|
|
rig.Clock.Now(); rig.Clock.Now(); rig.Clock.Now(); // past `soon`
|
|
rig.Events.Clear();
|
|
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
|
|
var after = rig.Engine.GetState("HighTemp")!;
|
|
after.Shelving.ShouldBe(ShelvingState.Unshelved);
|
|
after.Comments.Last().Kind.ShouldBe("AutoUnshelve");
|
|
rig.Events.Select(e => e.Emission).ShouldBe([EmissionKind.Unshelved]);
|
|
(await rig.Store.LoadAsync("HighTemp", Ct))!.Shelving.ShouldBe(ShelvingState.Unshelved);
|
|
}
|
|
|
|
/// <summary>Process restart is unchanged and documented: a new engine has no previous generation, the store
|
|
/// does not persist Active, so a still-true predicate is a new occurrence (Activated, Unacknowledged) — while
|
|
/// the persisted ack audit trail survives.</summary>
|
|
[Fact]
|
|
public async Task A_process_restart_still_seeds_from_the_store()
|
|
{
|
|
var store = new ActiveDroppingStore();
|
|
using (var first = new Rig(store)) await ActiveAndAcked(first);
|
|
|
|
using var restarted = new Rig(store);
|
|
restarted.Up.Set("Temp", 150);
|
|
await restarted.Engine.LoadAsync([Alarm()], Ct);
|
|
|
|
var s = restarted.Engine.GetState("HighTemp")!;
|
|
s.Active.ShouldBe(AlarmActiveState.Active);
|
|
s.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
|
|
s.LastAckUser.ShouldBe("alice");
|
|
restarted.Events.Select(e => e.Emission).ShouldBe([EmissionKind.Activated]);
|
|
}
|
|
|
|
/// <summary>An input that is not ready at the reload (cold-start guard) holds the CARRIED condition — before
|
|
/// #935 it held the store's Inactive, silently de-activating the engine and re-firing Activated on the next push.</summary>
|
|
[Fact]
|
|
public async Task A_reload_whose_input_is_bad_holds_the_carried_condition()
|
|
{
|
|
using var rig = new Rig();
|
|
var before = await ActiveAndAcked(rig);
|
|
|
|
rig.Up.Set("Temp", 150, statusCode: 0x80000000u); // Bad
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
rig.Engine.GetState("HighTemp")!.Active.ShouldBe(AlarmActiveState.Active);
|
|
|
|
rig.Events.ShouldContain(e => e.Emission == EmissionKind.QualityChanged && e.WorstInputStatusCode != 0u,
|
|
"the load annotates the frozen condition Bad");
|
|
|
|
rig.Up.Push("Temp", 160); // Good again, still true
|
|
// N4: wait on the GOOD-bucket QualityChanged the recovery produces — the Bad one above is already queued.
|
|
await WaitFor(() => rig.Events.Any(e => e.Emission == EmissionKind.QualityChanged && e.WorstInputStatusCode == 0u)
|
|
&& rig.Flips.Contains("HighTemp:True"));
|
|
rig.Engine.GetState("HighTemp")!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
|
|
rig.Engine.GetState("HighTemp")!.LastTransitionUtc.ShouldBe(before.LastTransitionUtc);
|
|
rig.Events.ShouldNotContain(e => e.Emission == EmissionKind.Activated);
|
|
}
|
|
|
|
/// <summary>The out-of-process (ScriptedAlarm seam) batch path seeds the same way.</summary>
|
|
[Fact]
|
|
public async Task The_out_of_process_batch_path_restates_too()
|
|
{
|
|
using var rig = new Rig(runner: new ThresholdRunner());
|
|
var before = await ActiveAndAcked(rig);
|
|
|
|
await rig.Engine.LoadAsync([Alarm()], Ct);
|
|
|
|
var after = rig.Engine.GetState("HighTemp")!;
|
|
after.Acked.ShouldBe(AlarmAckedState.Acknowledged);
|
|
after.LastTransitionUtc.ShouldBe(before.LastTransitionUtc);
|
|
rig.Events.ShouldBeEmpty();
|
|
}
|
|
|
|
/// <summary><see cref="ThresholdRunner"/> that answers Unavailable (with a recovery) while
|
|
/// <see cref="UnavailableUntil"/> is set.</summary>
|
|
private sealed class SwitchableRunner : IScriptRunner
|
|
{
|
|
public volatile Task? UnavailableUntil;
|
|
|
|
private ScriptRunOutcome Answer(ScriptInvocation i) => UnavailableUntil is { } recovery
|
|
? ScriptRunOutcome.Unavailable(ScriptRunOutcome.RunnerUnavailableReason) with { Recovery = recovery }
|
|
: 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) => [];
|
|
}
|
|
|
|
/// <summary>Answers <c>Temp > 100</c> for every predicate, in one batch.</summary>
|
|
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)
|
|
{
|
|
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
|
|
while (DateTime.UtcNow < deadline)
|
|
{
|
|
if (probe()) return;
|
|
await Task.Delay(10);
|
|
}
|
|
throw new TimeoutException("condition not reached");
|
|
}
|
|
}
|