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;
///
/// #935 — a same-process reload (every deploy runs ) is a
/// RESTATEMENT, not a new occurrence. The production store does not persist Active, so seeding a surviving
/// alarm from the store turned every deploy into an Inactive→Active transition: Acked reset to Unacknowledged, an
/// Activated emission (a duplicate alerts / historian row), and LastTransitionUtc moved to the
/// deploy instant. A surviving alarm id is now seeded from the engine's previous in-memory condition
/// (previous ?? persisted ?? Fresh); a process restart keeps the documented persisted-state behaviour.
///
[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;
/// Behaves like LocalDbAlarmConditionStateStore: there is no Active column, so a loaded row is
/// Inactive with no LastActive/LastCleared — which is exactly what made every reload re-activate.
private sealed class ActiveDroppingStore : IAlarmStateStore
{
private readonly ConcurrentDictionary _rows = new(StringComparer.Ordinal);
public int Loads;
public Task LoadAsync(string alarmId, CancellationToken ct)
{
Interlocked.Increment(ref Loads);
return Task.FromResult(_rows.TryGetValue(alarmId, out var r)
? r with { Active = AlarmActiveState.Inactive, LastActiveUtc = null, LastClearedUtc = null }
: null);
}
public Task> LoadAllAsync(CancellationToken ct)
=> Task.FromResult>(_rows.Values.ToArray());
public Task SaveAsync(AlarmConditionState state, CancellationToken ct)
{
_rows[state.AlarmId] = state;
return Task.CompletedTask;
}
public Task RemoveAsync(string alarmId, CancellationToken ct)
{
_rows.TryRemove(alarmId, out _);
return Task.CompletedTask;
}
}
/// A stepping clock, so "unchanged LastTransitionUtc" is not satisfied by two reads in the same tick.
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 Events { get; } = new();
public ConcurrentQueue 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);
/// Activate (Temp=150 at load) and acknowledge — the state an operator leaves behind before a deploy.
private static async Task 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;
}
/// The regression: an acknowledged active alarm survives a reload still Active + Acked, with NO
/// emission (so nothing reaches alerts), the same LastTransitionUtc (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.
[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"]);
// Persisted too, so a later process restart still restores the ack.
(await rig.Store.LoadAsync("HighTemp", Ct))!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
}
/// An unacked active alarm stays exactly that — Unacknowledged, Unconfirmed — with no emission.
[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();
}
/// 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).
[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]);
}
/// 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.
[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");
}
/// …and an edited predicate that is now false is a real clear of that same occurrence.
[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]);
}
/// 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).
[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)]);
}
/// 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.
[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();
}
/// 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.
[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);
}
/// A failed reload (compile error) leaves a half-built, Fresh-seeded generation. It must not become the
/// seed: the next good load still restates from the last COMPLETED generation.
[Fact]
public async Task A_failed_reload_keeps_the_last_good_generation_as_the_seed()
{
using var rig = new Rig();
var before = await ActiveAndAcked(rig);
await Should.ThrowAsync(
() => rig.Engine.LoadAsync([Alarm(), Alarm("Broken", "return unknownIdentifier;")], Ct));
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();
}
/// 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.
[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]);
}
/// 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.
[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.Up.Push("Temp", 160); // Good again, still true
await WaitFor(() => rig.Events.Any(e => e.Emission == EmissionKind.QualityChanged)
&& rig.Engine.GetState("HighTemp")!.Acked == AlarmAckedState.Acknowledged
&& rig.Flips.Contains("HighTemp:True"));
rig.Engine.GetState("HighTemp")!.LastTransitionUtc.ShouldBe(before.LastTransitionUtc);
rig.Events.ShouldNotContain(e => e.Emission == EmissionKind.Activated);
}
/// The out-of-process (ScriptedAlarm seam) batch path seeds the same way.
[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();
}
/// Answers Temp > 100 for every predicate, in one batch.
private sealed class ThresholdRunner : IScriptRunner
{
private static ScriptRunOutcome Answer(ScriptInvocation i) => ScriptRunOutcome.Ok((int)i.Inputs["Temp"].Value! > 100);
public Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
=> Task.FromResult(Answer(invocation));
public IReadOnlyList> RunBatch(IReadOnlyList invocations, CancellationToken ct = default)
=> invocations.Select(i => Task.FromResult(Answer(i))).ToArray();
public void Reset(ScriptContextKind kind) { }
public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => [];
}
private static async Task WaitFor(Func 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");
}
}