fix(grpc-data): A1 review S1 — a scripted condition is established only by a completed predicate

NoteInputsEstablishment raised 'established' before AreInputsReady, the evidence check and the predicate, so a
pushed-but-Bad input (driver down), a runner that was not up or a predicate timeout produced a known-inactive
record though no predicate had completed. The flip is now raised after the first predicate evaluation that
completes since the load or a revert; reverting an input to never-pushed still withdraws it.
This commit is contained in:
Joseph Doherty
2026-11-24 10:19:03 -05:00
parent e9d82a6a5a
commit 6ba5185f10
2 changed files with 102 additions and 17 deletions
@@ -322,18 +322,20 @@ public sealed class ScriptedAlarmEngine : IDisposable
/// <summary>
/// A1 (grpc-data plan §5.1 T2): an alarm's read cache went from holding a never-pushed input
/// (<see cref="StatusNeverPushed"/>) to holding none — its condition state is now ESTABLISHED — or back
/// (<see cref="ScriptedAlarmInputsEventArgs.Established"/> false: an input reverted to never-pushed, e.g. a tag
/// re-created by a deploy). Raised the first time after each <see cref="LoadAsync"/> and on every flip.
/// (<see cref="StatusNeverPushed"/>) to its FIRST COMPLETED predicate evaluation — its condition state is now
/// ESTABLISHED — or back (<see cref="ScriptedAlarmInputsEventArgs.Established"/> false: an input reverted to
/// never-pushed, e.g. a tag re-created by a deploy). "Established" is raised only after a predicate actually
/// completed (review S1): never while an input is Bad, the runner is not up, or the predicate timed out, was
/// refused or threw. Raised the first time after each <see cref="LoadAsync"/> / revert, and on every flip.
/// <para><b>Ordering (F2):</b> queued as the LAST item of the evaluation's pending emissions, so it fires only
/// after that evaluation's own <see cref="OnEvent"/> emissions were dispatched, on the same thread.</para>
/// <para>This is a new predicate: <see cref="WorstInputStatus"/> filters never-pushed values out.</para>
/// </summary>
public event EventHandler<ScriptedAlarmInputsEventArgs>? OnInputsEstablished;
// A1: per alarm, whether its inputs were established at its last evaluation. Only touched under _evalGate;
// A1: the alarms whose state is established (a predicate completed since the last load / revert). Only touched under _evalGate;
// cleared by every LoadAsync so a reload (a rebuild re-materialised the conditions unknown) re-raises it.
private readonly Dictionary<string, bool> _inputsEstablished = new(StringComparer.Ordinal);
private readonly HashSet<string> _inputsEstablished = new(StringComparer.Ordinal);
/// <summary>Gets the collection of loaded alarm identifiers.</summary>
public IReadOnlyCollection<string> LoadedAlarmIds => _alarms.Keys.ToArray();
@@ -909,7 +911,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
state.Definition.AlarmId,
_ => new AlarmScratch(state.Inputs, state.Logger, _clock));
RefillReadCache(scratch.ReadCache, state.Inputs);
NoteInputsEstablishment(state.Definition.AlarmId, scratch.ReadCache, pendingEmissions);
NoteInputsReverted(state.Definition.AlarmId, scratch.ReadCache, pendingEmissions);
var captured = CaptureInputs(state, scratch.ReadCache);
scratch.HasProjectedInputs = captured.Evidence is not null;
if (captured.Evidence is { IsValid: false }) return seed;
@@ -978,6 +980,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
if (captured.Evidence is { IsValid: false }) return seed;
MirrorPredicate(state, scratch, ScriptRunOutcome.Ok(predicateTrue));
scratch.LastNonCompletion = null;
NoteEvaluationCompleted(state.Definition.AlarmId, pendingEmissions);
// Track the bucket only once the predicate has COMPLETED (I3). The tracked bucket is the last
// bucket this alarm was annotated with; tracking the input bucket before the attempt flipped it to
@@ -1068,7 +1071,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
var scratch = scratches[i] = _scratchByAlarmId.GetOrAdd(
state.Definition.AlarmId, _ => new AlarmScratch(state.Inputs, state.Logger, _clock));
RefillReadCache(scratch.ReadCache, state.Inputs);
NoteInputsEstablishment(state.Definition.AlarmId, scratch.ReadCache, pendingEmissions);
NoteInputsReverted(state.Definition.AlarmId, scratch.ReadCache, pendingEmissions);
var captured = capturedInputs[i] = CaptureInputs(state, scratch.ReadCache);
worst[i] = WorstInputStatus(scratch.ReadCache);
if (!AreInputsReady(scratch.ReadCache) || captured.Evidence is { IsValid: false })
@@ -1157,6 +1160,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
return seed;
}
scratch.LastNonCompletion = null;
NoteEvaluationCompleted(state.Definition.AlarmId, pendingEmissions);
// 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);
@@ -1385,22 +1389,30 @@ public sealed class ScriptedAlarmEngine : IDisposable
/// that re-enters the engine (e.g. calls AcknowledgeAsync) would
/// deadlock against the non-reentrant SemaphoreSlim.
/// </summary>
/// <summary>A1: record an established/reverted flip of <paramref name="alarmId"/>'s inputs into the caller's pending
/// list (fired after every emission in it). Only called under <c>_evalGate</c>.</summary>
private void NoteInputsEstablishment(string alarmId, IReadOnlyDictionary<string, DataValueSnapshot> cache,
/// <summary>A1 (review S1): withdraw "established" from <paramref name="alarmId"/> when one of its inputs reverted to
/// never-pushed (e.g. a tag re-created by a deploy). Only called under <c>_evalGate</c>; the flip is fired after every
/// emission in the caller's pending list.</summary>
private void NoteInputsReverted(string alarmId, IReadOnlyDictionary<string, DataValueSnapshot> cache,
List<ScriptedAlarmEvent> pendingEmissions)
{
var established = true;
if (!_inputsEstablished.Contains(alarmId)) return; // not established: an unknown condition is already unknown
foreach (var v in cache.Values)
{
if (v is null || v.StatusCode == StatusNeverPushed) { established = false; break; }
if (v is not null && v.StatusCode != StatusNeverPushed) continue;
_inputsEstablished.Remove(alarmId);
if (pendingEmissions is PendingEmissions pending) pending.Establishments.Add((alarmId, false));
return;
}
}
var had = _inputsEstablished.TryGetValue(alarmId, out var prior);
_inputsEstablished[alarmId] = established;
// First evaluation after a load: raise only "established" (an unknown condition is already unknown).
if (had ? prior == established : !established) return;
if (pendingEmissions is PendingEmissions pending) pending.Establishments.Add((alarmId, established));
/// <summary>A1 (review S1): a predicate evaluation of <paramref name="alarmId"/> COMPLETED — its inputs were ready
/// (none never-pushed, none Bad), its evidence valid and its predicate returned a bool — so the condition's state is
/// established. Raised once per load / revert, never on a Bad input, a refused or timed-out predicate or a runner
/// that was not up. Only called under <c>_evalGate</c>.</summary>
private void NoteEvaluationCompleted(string alarmId, List<ScriptedAlarmEvent> pendingEmissions)
{
if (!_inputsEstablished.Add(alarmId)) return;
if (pendingEmissions is PendingEmissions pending) pending.Establishments.Add((alarmId, true));
}
/// <summary>Fire a caller's pending emissions, then (A1 F2) its input-establishment flips — last.</summary>
@@ -103,6 +103,79 @@ public sealed class ScriptedAlarmEngineInputsEstablishedTests
log.Count(l => l == "inputs:a1:True").ShouldBe(2);
}
// ---------------------------------------------------------------- review S1: established = a COMPLETED predicate
private const uint StatusBad = 0x80000000u;
/// <summary>Review S1: an input that is pushed but Bad (driver down) holds the condition; no predicate ran, so the
/// state is not established. The first Good value runs the predicate and only then establishes it.</summary>
[Fact]
public async Task A_Bad_input_never_establishes_and_the_first_good_evaluation_does()
{
var up = new FakeUpstream();
up.Set("Temp", 150, StatusBad);
var (engine, log) = Build(up);
using var _ = engine;
await engine.LoadAsync([Alarm("a1")], Ct);
up.Push("Temp", 150, StatusBad);
await Task.Delay(200, Ct);
log.ShouldNotContain(l => l.StartsWith("inputs:", StringComparison.Ordinal));
up.Push("Temp", 150);
await WaitForAsync(() => log.Contains("inputs:a1:True"));
log.Last().ShouldBe("inputs:a1:True");
log.ShouldContain("emit:a1:Activated");
}
/// <summary>Review S1: a predicate that times out (or a runner that is not up) never completed, so nothing is
/// established; the first evaluation that completes establishes it.</summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task A_predicate_timeout_or_an_unavailable_runner_never_establishes(bool timeout)
{
var up = new FakeUpstream();
up.Set("Temp", 150);
var runner = new AnsweringRunner
{
Answer = timeout
? ScriptRunOutcome.Failed($"{ZB.MOM.WW.OtOpcUa.Commons.Engines.ScriptEvalFailureReasons.TimedOutPrefix}0.2s")
: ScriptRunOutcome.Unavailable(ScriptRunOutcome.WorkerRestartedReason),
};
var logger = new LoggerConfiguration().CreateLogger();
using var engine = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger,
scriptTimeout: TimeSpan.FromMilliseconds(250), scriptRunner: runner);
var log = new ConcurrentQueue<string>();
engine.OnEvent += (_, e) => log.Enqueue($"emit:{e.AlarmId}:{e.Emission}");
engine.OnInputsEstablished += (_, e) => log.Enqueue($"inputs:{e.AlarmId}:{e.Established}");
await engine.LoadAsync([Alarm("a1")], Ct);
up.Push("Temp", 160);
await Task.Delay(200, Ct);
log.ShouldNotContain(l => l.StartsWith("inputs:", StringComparison.Ordinal));
runner.Answer = ScriptRunOutcome.Ok(true);
up.Push("Temp", 170);
await WaitForAsync(() => log.Contains("inputs:a1:True"));
log.Last().ShouldBe("inputs:a1:True");
}
/// <summary>A runner that answers every predicate with <see cref="Answer"/>.</summary>
private sealed class AnsweringRunner : IScriptRunner
{
public volatile ScriptRunOutcome Answer = ScriptRunOutcome.Ok(false);
public Task<ScriptRunOutcome> RunAsync(ScriptInvocation invocation, CancellationToken ct = default) =>
Task.FromResult(Answer);
public IReadOnlyList<Task<ScriptRunOutcome>> RunBatch(IReadOnlyList<ScriptInvocation> invocations, CancellationToken ct = default) =>
invocations.Select(_ => Task.FromResult(Answer)).ToArray();
public void Reset(ScriptContextKind kind) { }
public IReadOnlyCollection<string> QuarantinedKeys(ScriptContextKind kind) => [];
}
private static async Task WaitForAsync(Func<bool> cond, int timeoutMs = 3000)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);