From ec245b84a90a8571431dcb1b6e8e6471bffa4a53 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 25 Nov 2026 10:54:45 -0500 Subject: [PATCH] fix(scripted-alarms): a same-process reload restates a surviving alarm from its in-memory condition (#935) ScriptedAlarmEngine.LoadAsync runs on every deploy and used to seed each alarm from IAlarmStateStore, which in production does not persist Active. A still-true predicate then made every deploy an Inactive->Active transition: Acked reset, Activated emission (duplicate alerts row), LastTransitionUtc moved. Seed is now previous ?? persisted ?? Fresh: the last COMPLETED generation's in-memory condition is captured under _evalGate before the clear and kept across a failed load. Process restart is unchanged. --- .../ScriptedAlarmEngine.cs | 68 +++- ...riptedAlarmEngineReloadRestatementTests.cs | 359 ++++++++++++++++++ 2 files changed, 419 insertions(+), 8 deletions(-) create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs index d66c3a117..8f1eb26d9 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs @@ -217,6 +217,23 @@ public sealed class ScriptedAlarmEngine : IDisposable private Timer? _shelvingTimer; private bool _loaded; + /// + /// #935: whether holds a COMPLETED generation — set at the end of a successful + /// , cleared as soon as a load starts mutating . Only touched + /// under _evalGate. + /// + private bool _generationComplete; + + /// + /// #935: the condition state of every alarm of the last completed generation, captured by + /// before it clears . A same-process reload is a + /// RESTATEMENT, not a new occurrence: an alarm id that survives the reload is seeded from this (in + /// preference to the store, which does not persist Active), so a still-true predicate yields no + /// transition. Kept across a FAILED load (the failed generation is never trusted as a seed) and dropped + /// when a load completes. Only touched under _evalGate. + /// + private Dictionary? _carryOver; + // volatile: written by Dispose and read unsynchronized from every background // path (LoadAsync's guard, OnUpstreamChange, the drain loop, ReevaluateAsync / // ShelvingCheckAsync's post-gate re-checks, TrackBackgroundTask's registration @@ -343,9 +360,13 @@ public sealed class ScriptedAlarmEngine : IDisposable /// /// Load a batch of alarm definitions. Compiles every predicate, aggregates any /// compile failures into one , subscribes - /// to upstream input tags, seeds the value cache, loads persisted state from - /// the store (falling back to Fresh for first-load alarms), and recomputes - /// ActiveState from the current predicate (startup recovery). + /// to upstream input tags, seeds the value cache, seeds each alarm's condition, and + /// recomputes ActiveState from the current predicate (startup recovery). + /// #935: the seed is previous ?? persisted ?? Fresh. An alarm id that was loaded in the + /// last completed generation of THIS engine (a redeploy) keeps its in-memory condition, so a + /// still-true predicate is a restatement (no emission, Ack/Confirm/LastTransitionUtc unchanged); + /// only an alarm new to this process (first load after a restart, or re-added after a deploy that + /// removed / disabled it) reads the store, which does not carry Active. /// /// The alarm definitions to load. /// The cancellation token. @@ -371,6 +392,19 @@ public sealed class ScriptedAlarmEngine : IDisposable _shelvingTimer?.Dispose(); _shelvingTimer = null; + // #935: capture the live generation's conditions BEFORE clearing — a surviving alarm id is seeded + // from them below (previous ?? persisted ?? Fresh). Taken under _evalGate, so it reflects every + // evaluation / operator command that completed before this load; anything queued behind the gate + // runs against the new generation. A failed previous load leaves _generationComplete false, so its + // (untrusted, partly Fresh) entries are not captured and the last good snapshot is kept instead. + if (_generationComplete) + { + _carryOver = new Dictionary(_alarms.Count, StringComparer.Ordinal); + foreach (var (alarmId, prior) in _alarms) _carryOver[alarmId] = prior.Condition; + } + _generationComplete = false; + var carryOver = _carryOver; + UnsubscribeFromUpstream(); _alarms.Clear(); _alarmsReferencing.Clear(); @@ -459,8 +493,9 @@ public sealed class ScriptedAlarmEngine : IDisposable foreach (var path in _alarmsReferencing.Keys) _valueCache[path] = _upstream.ReadTag(path); - // Restore persisted state, falling back to Fresh where nothing was saved, - // then re-derive ActiveState from the current predicate. + // Restore state — the previous generation's in-memory condition for a surviving alarm id (#935: a + // same-process reload is a restatement), else the persisted state (a process restart, or an alarm new + // to this process), else Fresh — then re-derive ActiveState from the current predicate. // Any predicate emissions queue into `pending` and fire after the gate // is released — so a startup-recovery activation event can call back into // the engine without deadlocking. @@ -468,8 +503,7 @@ public sealed class ScriptedAlarmEngine : IDisposable { foreach (var (alarmId, state) in _alarms) { - var persisted = await _store.LoadAsync(alarmId, ct).ConfigureAwait(false); - var seed = persisted ?? state.Condition; + var seed = await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false); var afterPredicate = await EvaluatePredicateToStateAsync(state, seed, nowUtc: _clock(), ct, pending) .ConfigureAwait(false); _alarms[alarmId] = state with { Condition = afterPredicate }; @@ -482,7 +516,7 @@ public sealed class ScriptedAlarmEngine : IDisposable // same order the serial loop above uses. var seeds = new List<(AlarmState State, AlarmConditionState Seed)>(_alarms.Count); foreach (var (alarmId, state) in _alarms) - seeds.Add((state, await _store.LoadAsync(alarmId, ct).ConfigureAwait(false) ?? state.Condition)); + seeds.Add((state, await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false))); var after = await EvaluatePredicateBatchToStatesAsync(seeds, _clock(), ct, pending).ConfigureAwait(false); for (var i = 0; i < seeds.Count; i++) { @@ -493,6 +527,8 @@ public sealed class ScriptedAlarmEngine : IDisposable } _loaded = true; + _generationComplete = true; + _carryOver = null; // Subscribe after _loaded = true and full state restore. If an upstream // implementation pushes its initial value synchronously from inside @@ -520,6 +556,22 @@ public sealed class ScriptedAlarmEngine : IDisposable FirePending(pending); } + /// + /// #935: the state a loaded alarm starts its first evaluation from — previous ?? persisted ?? Fresh. + /// The previous generation's in-memory condition wins for a surviving alarm id: it is exactly what this node + /// is already serving (every node receives every operator command), and it still knows Active, which + /// the production store does not persist. Seeding from the store instead turned every deploy into an + /// Inactive→Active transition for a still-active alarm (Acked reset, Activated emission, a new + /// LastTransitionUtc). Identity is the alarm id alone — an edited predicate, severity, message or + /// placement is the same alarm, and its new predicate decides the next transition. + /// + private async Task SeedAsync( + string alarmId, AlarmState state, Dictionary? carryOver, CancellationToken ct) + { + if (carryOver is not null && carryOver.TryGetValue(alarmId, out var previous)) return previous; + return await _store.LoadAsync(alarmId, ct).ConfigureAwait(false) ?? state.Condition; + } + /// /// Current persisted state for . Returns null for /// unknown alarm. Mainly used for diagnostics + the Admin UI status page. diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs new file mode 100644 index 000000000..861b2c3bb --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs @@ -0,0 +1,359 @@ +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"); + } +}