fix(alarms): a scripted condition's Part 9 method returns the engine's verdict (#937)

Before: the alarm-commands topic is fire-and-forget, so an OPC UA method (and a
remote gRPC-data condition method) returned Good even when the engine rejected
the command because its last load failed.

- ScriptedAlarmCommandReadinessView: the host's latest load outcome; the node
  manager's handler refuses BadInvalidState before the SDK applies anything
  while the last load failed (lock-free read).
- Bounded ask: inside CallAsync (off Lock) each local request runs base.Call
  alone; the handler only STARTS AlarmCommandAsker (broadcast for the peer +
  DriverHostActor -> ScriptedAlarmHostActor.ExecuteAlarmCommand on the local
  engine, CommandId-deduplicated) and the Call awaits the verdict: refused =>
  BadInvalidState, no answer => BadTimeout OutcomeUnknown.
- Remote CallConditionMethod: ExecuteConditionMethodAsync => DriverConfirmedFailure
  / OutcomeUnknown on the origin.
- Host ownership uses the latest plan set (stable across a load in flight and a
  failed load's half-built set).
- Docs: ScriptedAlarms.md (verdicts, residual, duplicate-activation trade-off),
  DataConnections.md, rules/alarms.md. Live leg scenario F937 + seeder
  scripted_predicate mutation.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-11-28 09:40:35 -05:00
parent 05f431f5d8
commit d6f2a1b5e2
21 changed files with 1074 additions and 38 deletions
@@ -0,0 +1,196 @@
using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>
/// #937: a scripted condition's Part 9 method returns the scripted-alarm engine's verdict, not the Good a fire-and-forget
/// topic publish implied.
/// </summary>
/// <remarks>
/// <para>
/// <b>Two layers.</b> (1) <see cref="ScriptedAlarmCommandPreflight"/> — a lock-free read of this node's engine load
/// outcome — refuses <c>BadInvalidState</c> inside the handler, before the SDK applies anything, while the last load
/// failed (the common case: the engine stays blind until the next good deploy). (2) Everything it lets through is
/// asked of THIS node's engine (<see cref="AlarmCommandAsker"/>, bounded): the handler, still under <c>Lock</c>,
/// only STARTS the ask (it sends; nothing blocks) and returns Good so the SDK applies its node state and the method
/// wrapper reports its one event exactly as before; the Call service (<see cref="CallAsync"/>, or
/// <see cref="ExecuteConditionMethodAsync"/> for a remote gRPC-data call) awaits the verdict once the SDK released
/// <c>Lock</c>, and turns a refusal into <c>BadInvalidState</c> and no answer into <c>BadTimeout</c> (OutcomeUnknown).
/// </para>
/// <para>
/// <b>Status codes.</b> Part 9 defines no result code for "the condition's state owner cannot act" (its method
/// tables cover a bad EventId, an already-acked/confirmed/shelved condition, a disabled condition and an out-of-range
/// shelving time). Part 4's <c>Bad_InvalidState</c> — "the operation cannot be completed because the object is
/// closed, uninitialized or in some other invalid state" — is the general code for exactly that, and is what this
/// server already returns for a native ack off-Primary. A timeout is <c>Bad_Timeout</c> with "OutcomeUnknown" in the
/// diagnostic, as the remote-condition path does: the command may still apply (the engine's own bound is longer),
/// so it is never reported as refused.
/// </para>
/// <para>
/// <b>Residual (documented).</b> In layer 2 the SDK has already applied and reported the node change when a refusal
/// arrives (a load that was in flight when the command queued behind it, and then failed). The node keeps that state
/// until the next successful deploy re-asserts every scripted condition from the store; the caller gets Bad.
/// </para>
/// </remarks>
public sealed partial class OtOpcUaNodeManager
{
/// <summary>How long a scripted condition method waits for the engine's verdict by default (5 s).</summary>
internal static readonly TimeSpan DefaultScriptedCommandTimeout = TimeSpan.FromSeconds(5);
private static readonly AsyncLocal<PendingScriptedCommand?> PendingScriptedCommandSlot = new();
/// <summary>
/// #937 layer 1: returns why this node's scripted-alarm engine would reject any operator command right now (its last
/// load failed), or null to proceed. Called under <c>Lock</c>: MUST be a lock-free read, no I/O. Null ⇒ no pre-check.
/// </summary>
public Func<string?>? ScriptedAlarmCommandPreflight { get; set; }
/// <summary>
/// #937 layer 2: hands one command to THIS node's scripted-alarm engine and completes with its verdict (the host also
/// broadcasts it to the redundant peer, as <see cref="AlarmCommandRouter"/> does). Called under <c>Lock</c>: it MUST
/// only send and return the pending task. The timeout argument is the caller's bound. Null ⇒ the fire-and-forget
/// <see cref="AlarmCommandRouter"/> and an unconditional Good, as before #937.
/// </summary>
public Func<AlarmCommand, TimeSpan, Task<AlarmCommandOutcome>>? AlarmCommandAsker { get; set; }
/// <summary>The longest a scripted condition method waits for the engine's verdict (also capped by the request deadline).</summary>
internal TimeSpan ScriptedCommandTimeout { get; set; } = DefaultScriptedCommandTimeout;
/// <summary>The verdict slot one Call request's handler fills (one per request; flows into the synchronous SDK call).</summary>
private sealed class PendingScriptedCommand(TimeSpan timeout)
{
public TimeSpan Timeout { get; } = timeout;
public Task<AlarmCommandOutcome>? Outcome { get; set; }
}
/// <summary>
/// From <see cref="HandleAlarmCommand"/> (under <c>Lock</c>): when the current Call awaits a verdict, start the ask
/// and park its task. False ⇒ not inside such a call (route fire-and-forget).
/// </summary>
private bool TryStartScriptedCommandAsk(AlarmCommand cmd)
{
if (PendingScriptedCommandSlot.Value is not { Outcome: null } pending || AlarmCommandAsker is not { } asker) return false;
try
{
pending.Outcome = asker(cmd with { CommandId = Guid.NewGuid().ToString("N") }, pending.Timeout);
}
catch (Exception ex)
{
// The asker is contracted not to throw; one that does may still have sent the command.
pending.Outcome = Task.FromException<AlarmCommandOutcome>(ex);
}
return true;
}
/// <summary>The bound for one request: <see cref="ScriptedCommandTimeout"/>, cut by the request deadline (less a grace).</summary>
private TimeSpan ScriptedCommandBound(DateTime deadline)
{
var bound = ScriptedCommandTimeout;
if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue)
{
var byDeadline = deadline - DateTime.UtcNow - ImportedMethodGrace;
if (byDeadline < bound) bound = byDeadline;
}
return bound < ImportedMethodMinimumDispatchBudget ? ImportedMethodMinimumDispatchBudget : bound;
}
/// <summary>
/// Runs the SDK's synchronous <c>base.Call</c> for ONE request with a verdict slot installed, and returns the parked
/// ask (null when the handler routed nothing: a refusal, a native or non-condition method, or no asker wired).
/// </summary>
private Task<AlarmCommandOutcome>? CallOneAwaitingVerdict(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall, int index,
IList<CallMethodResult> results, IList<ServiceResult> errors, TimeSpan bound)
{
var request = methodsToCall[index];
var singleResults = new List<CallMethodResult> { results[index] };
var singleErrors = new List<ServiceResult> { errors[index] };
var pending = new PendingScriptedCommand(bound);
PendingScriptedCommandSlot.Value = pending;
try
{
base.Call(context, (ArrayOf<CallMethodRequest>)new[] { request }, singleResults, singleErrors);
}
finally
{
PendingScriptedCommandSlot.Value = null;
}
if (!request.Processed) return null; // not this manager's node: left for the next manager, untouched
results[index] = singleResults[0];
errors[index] = singleErrors[0];
return ServiceResult.IsGood(singleErrors[0]) ? pending.Outcome : null;
}
/// <summary>
/// The method's final status from the engine's verdict, and whether it is an OutcomeUnknown (the command may still
/// apply). Never throws. The asker answers its own timeout as an <see cref="AlarmCommandVerdict.OutcomeUnknown"/>
/// outcome; the wait here (its bound plus a grace) is the backstop for one that never completes.
/// </summary>
private async Task<(ServiceResult Status, bool Unknown)> AwaitScriptedVerdictAsync(Task<AlarmCommandOutcome> pending, TimeSpan bound)
{
AlarmCommandOutcome outcome;
try
{
outcome = await pending.WaitAsync(bound + ImportedMethodGrace).ConfigureAwait(false);
}
catch (Exception ex) when (ex is TimeoutException or OperationCanceledException)
{
return (ScriptedUnknown(StatusCodes.BadTimeout,
$"OutcomeUnknown: the scripted-alarm engine did not answer within {bound.TotalSeconds:0.#} s; the command may still apply."), true);
}
catch (Exception ex)
{
// The command was (or may have been) sent: unknown, never "refused".
return (ScriptedUnknown(StatusCodes.BadInternalError, "OutcomeUnknown: " + ex.GetType().Name), true);
}
return outcome.Verdict switch
{
AlarmCommandVerdict.Applied => (ServiceResult.Good, false),
AlarmCommandVerdict.NotApplied => (new ServiceResult(StatusCodes.BadInvalidState,
new LocalizedText(outcome.Reason ?? "The scripted-alarm engine did not apply the command.")), false),
_ => (ScriptedUnknown(outcome.TimedOut ? StatusCodes.BadTimeout : StatusCodes.BadInternalError,
outcome.Reason ?? "OutcomeUnknown: the scripted-alarm engine could not confirm the command."), true),
};
}
private ServiceResult ScriptedUnknown(StatusCode status, string diagnostic)
{
_logger.LogWarning("OtOpcUaNodeManager: scripted condition method outcome unknown ({Status}): {Diagnostic}", status, diagnostic);
return new ServiceResult(status, new LocalizedText(diagnostic));
}
/// <summary>
/// #937: <see cref="TryExecuteConditionMethod"/> plus the scripted engine's verdict (A2b remote calls). The node-manager
/// part runs under <c>Lock</c> exactly as before; the verdict is awaited after it is released, bounded by
/// <paramref name="budget"/> (capped at <see cref="ScriptedCommandTimeout"/>).
/// </summary>
/// <param name="call">The call.</param>
/// <param name="budget">The caller's remaining budget.</param>
/// <returns>The verdict: Applied only once the engine applied it; a refusal after dispatch carries
/// <see cref="OriginConditionMethodOutcome.Dispatched"/>; no answer carries <see cref="OriginConditionMethodOutcome.Unknown"/>.</returns>
public async Task<OriginConditionMethodOutcome> ExecuteConditionMethodAsync(OriginConditionMethodCall call, TimeSpan budget)
{
var bound = budget < ScriptedCommandTimeout ? budget : ScriptedCommandTimeout;
if (bound < ImportedMethodMinimumDispatchBudget) bound = ImportedMethodMinimumDispatchBudget;
var pending = new PendingScriptedCommand(bound);
PendingScriptedCommandSlot.Value = pending;
OriginConditionMethodOutcome decided;
try
{
decided = TryExecuteConditionMethod(call);
}
finally
{
PendingScriptedCommandSlot.Value = null;
}
if (!decided.Applied || pending.Outcome is not { } outcome) return decided;
var (status, unknown) = await AwaitScriptedVerdictAsync(outcome, bound).ConfigureAwait(false);
if (ServiceResult.IsGood(status)) return decided;
var text = status.LocalizedText.IsNullOrEmpty ? null : status.LocalizedText.Text;
return new OriginConditionMethodOutcome(false, decided.Native, status.StatusCode.Code, text, Dispatched: true, Unknown: unknown);
}
}