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
@@ -46,9 +46,51 @@ public static class AlarmCommandsTopic
/// (<c>DateTime.UtcNow + shelvingTime</c>, where the OPC UA <c>Duration</c> <c>shelvingTime</c> is
/// in <b>milliseconds</b>); <c>null</c> for every other operation.
/// </param>
/// <param name="CommandId">
/// #937: an id unique to one operator call, set by a publisher that ALSO hands the same command to its own node's
/// <c>ScriptedAlarmHostActor</c> directly (the bounded ask that answers the OPC UA method): that host applies the
/// direct copy and skips the broadcast copy carrying the same id. Null (every other publisher, and the gRPC mesh
/// wire, which does not carry it) ⇒ no de-duplication. Wire-compatible: a peer built before #937 ignores it.
/// </param>
public sealed record AlarmCommand(
string AlarmId,
string Operation,
string User,
string? Comment,
DateTime? UnshelveAtUtc);
DateTime? UnshelveAtUtc,
string? CommandId = null);
/// <summary>#937: what a scripted-alarm engine did with one <see cref="AlarmCommand"/>.</summary>
public enum AlarmCommandVerdict
{
/// <summary>The engine applied the command (an idempotent no-op — e.g. a re-shelve — included).</summary>
Applied,
/// <summary>
/// Definitely NOT applied, and nothing was persisted: the engine holds no complete generation (its last load
/// failed), the alarm is not loaded on this node, or the command was malformed.
/// </summary>
NotApplied,
/// <summary>
/// The outcome is unknown: the engine op did not finish inside its bound, or failed in a way that may have
/// persisted (a condition-state store fault). Never reported as "not applied".
/// </summary>
OutcomeUnknown,
}
/// <summary>
/// #937: the local scripted-alarm host's answer to one directly-asked <see cref="AlarmCommand"/> — what lets an OPC UA
/// Part 9 method return a Bad status instead of the Good a fire-and-forget topic publish implied.
/// </summary>
/// <param name="AlarmId">The command's alarm.</param>
/// <param name="Operation">The command's operation.</param>
/// <param name="Verdict">What the engine did.</param>
/// <param name="Reason">Operator-facing text for a verdict other than <see cref="AlarmCommandVerdict.Applied"/>.</param>
/// <param name="TimedOut">For <see cref="AlarmCommandVerdict.OutcomeUnknown"/>: the bound expired (vs. a fault).</param>
public sealed record AlarmCommandOutcome(
string AlarmId,
string Operation,
AlarmCommandVerdict Verdict,
string? Reason = null,
bool TimedOut = false);
@@ -55,6 +55,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
private readonly HistorianUpdaterHolder _historianUpdater;
private readonly IHistoryUpdateRoleView? _historyUpdateRoleView;
private readonly NativeAlarmAckPreflightView? _ackPreflightView;
private readonly ScriptedAlarmCommandReadinessView? _scriptedAlarmReadiness;
private readonly OpcUaEndpointState _endpointState;
private readonly bool _rethrowStartFailure;
private readonly DriverWriteBounds _writeBounds;
@@ -172,9 +173,11 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
IFederatedProjectionCatalog? projectedCatalog = null,
IProjectedHistoryAccess? projectedHistoryAccess = null,
IConditionStateSink? conditionStateSink = null,
IProjectedConditionAccess? projectedConditionAccess = null)
IProjectedConditionAccess? projectedConditionAccess = null,
ScriptedAlarmCommandReadinessView? scriptedAlarmReadiness = null)
{
_projectedConditionAccess = projectedConditionAccess;
_scriptedAlarmReadiness = scriptedAlarmReadiness;
_projectedHistoryAccess = projectedHistoryAccess;
_conditionStateSink = conditionStateSink;
_dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get<DataConnectionOptions>() ?? new();
@@ -316,6 +319,14 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
}
});
// #937: a scripted condition's Part 9 method answers with THIS node's engine verdict. The pre-check (one volatile
// read) refuses while the last scripted-alarm load failed; the asker broadcasts the command to the redundant peer
// exactly as the router above does and asks the local engine (via the DriverHostActor) for its verdict. Both run
// under the SDK's Lock and only read / send; the node manager awaits the verdict off Lock.
if (_scriptedAlarmReadiness is { } readiness)
_server.NodeManager.ScriptedAlarmCommandPreflight = readiness.Refusal;
_server.NodeManager.AlarmCommandAsker = AskScriptedAlarmCommand;
// Wire the reverse-path native-alarm-ack router (H6e): a client Acknowledge of a NATIVE (driver-fed,
// e.g. Galaxy) Part 9 condition that passes the node manager's AlarmAck gate routes the acknowledge to
// the owning driver child. The node manager maps the inbound ack to an OpcUaServer-local NativeAlarmAck;
@@ -592,6 +603,57 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
_loggerFactory.CreateLogger<AclRevalidationTimer>());
}
/// <summary>
/// #937: the node manager's <see cref="OtOpcUaNodeManager.AlarmCommandAsker"/>. Broadcasts the command on the
/// <c>alarm-commands</c> topic (the redundant peer applies it, as before) and asks THIS node's scripted-alarm host,
/// through the <c>DriverHostActor</c>, for its verdict; the command carries a fresh <c>CommandId</c>, so the local
/// host applies whichever copy reaches it first and only once. Runs under the SDK's Lock: it only sends. Never
/// faults — no answer inside <paramref name="timeout"/> is an OutcomeUnknown outcome.
/// </summary>
/// <param name="cmd">The command (with its <c>CommandId</c>).</param>
/// <param name="timeout">The caller's bound.</param>
/// <returns>The verdict.</returns>
private Task<AlarmCommandOutcome> AskScriptedAlarmCommand(AlarmCommand cmd, TimeSpan timeout)
{
try
{
DistributedPubSub.Get(_actorSystemAccessor()).Mediator.Tell(new Publish(ScriptedAlarmHostActor.AlarmCommandsTopic, cmd));
}
catch (Exception ex)
{
// The peer's copy only; the local ask below still decides this caller's answer.
_logger.LogWarning(ex, "OtOpcUaServerHostedService: failed to broadcast inbound alarm command {Operation} for {AlarmId}",
cmd.Operation, cmd.AlarmId);
}
if (!_actorRegistry.TryGet<DriverHostActorKey>(out var driverHost))
{
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
"This server runs no scripted-alarm engine; the command was not applied."));
}
return AskAsync(driverHost, cmd, timeout);
static async Task<AlarmCommandOutcome> AskAsync(IActorRef host, AlarmCommand cmd, TimeSpan timeout)
{
try
{
return await host.Ask<AlarmCommandOutcome>(new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd), timeout).ConfigureAwait(false);
}
catch (Exception ex) when (ex is AskTimeoutException or TaskCanceledException or TimeoutException)
{
return new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
$"OutcomeUnknown: the scripted-alarm engine did not answer within {timeout.TotalSeconds:0.#} s; the command may still apply.",
TimedOut: true);
}
catch (Exception ex)
{
return new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
"OutcomeUnknown: " + ex.GetType().Name);
}
}
}
/// <summary>
/// Stops the OPC UA server asynchronously: detaches every sink, then STOPS the SDK so the port closes.
/// </summary>
@@ -635,6 +697,11 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
_server?.SetNativeAlarmAckRouter(null);
_server?.SetNativeAlarmAckPrimaryGate(null);
_server?.SetNativeAlarmAckPreflight(null);
if (_server?.NodeManager is { } stoppingNodeManager)
{
stoppingNodeManager.AlarmCommandAsker = null;
stoppingNodeManager.ScriptedAlarmCommandPreflight = null;
}
_server?.SetHistoryUpdatePrimaryGate(null);
// Restore the Null historian so a late HistoryRead doesn't hit a disposed read client.
_server?.SetHistorianDataSource(null);
@@ -115,7 +115,7 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
(claimed ??= []).Add(i);
}
base.Call(context, methodsToCall, results, errors);
await CallLocalAsync(context, methodsToCall, results, errors).ConfigureAwait(false);
if (claimed is null) return;
var caller = context.UserIdentity as RoleCarryingUserIdentity;
@@ -132,6 +132,40 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
for (var k = 0; k < claimed.Count; k++) errors[claimed[k]] = calls[k].Result;
}
/// <summary>
/// The local (non-imported) requests. Without an <see cref="AlarmCommandAsker"/> this is the unchanged batch
/// <c>base.Call</c>. With one (#937), each request runs through <c>base.Call</c> alone — in batch order, each fully
/// applied by the SDK under its own <c>Lock</c> hold — so a scripted condition method's handler can park the ask it
/// starts against that request; the parked asks are then awaited together, with no <c>Lock</c> held, and each
/// request's status becomes its engine's verdict. Never throws past the SDK's own behaviour (the waits are guarded).
/// </summary>
private async Task CallLocalAsync(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall, IList<CallMethodResult> results,
IList<ServiceResult> errors)
{
if (AlarmCommandAsker is null)
{
base.Call(context, methodsToCall, results, errors);
return;
}
var bound = ScriptedCommandBound(context.OperationDeadline);
List<(int Index, Task<(ServiceResult Status, bool Unknown)> Verdict)>? verdicts = null;
for (var i = 0; i < methodsToCall.Count; i++)
{
if (methodsToCall[i] is not { Processed: false }) continue;
if (CallOneAwaitingVerdict(context, methodsToCall, i, results, errors, bound) is { } pending)
(verdicts ??= []).Add((i, AwaitScriptedVerdictAsync(pending, bound)));
}
if (verdicts is null) return;
// Each verdict task is guarded (never faults), so WhenAll never throws.
await Task.WhenAll(verdicts.Select(v => v.Verdict)).ConfigureAwait(false);
foreach (var (index, verdict) in verdicts)
{
var status = verdict.Result.Status;
if (!ServiceResult.IsGood(status)) errors[index] = status;
}
}
/// <summary>Review S1: <see cref="CallImportedAsync"/> as a task that cannot fault (a synchronous throw included).</summary>
private async Task<ServiceResult> CallImportedGuardedAsync(RoleCarryingUserIdentity? caller, CallMethodRequest request, DateTime deadline,
CancellationToken cancellationToken)
@@ -20,6 +20,15 @@ public interface IOriginConditionSource
/// <param name="call">The call.</param>
/// <returns>The verdict.</returns>
OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call);
/// <summary>#937: see <see cref="OtOpcUaNodeManager.ExecuteConditionMethodAsync"/> — <see cref="TryExecuteConditionMethod"/>
/// plus, for a scripted condition, the engine's verdict awaited (off <c>Lock</c>) within <paramref name="budget"/>. The
/// default (a source with no engine behind it) is the synchronous verdict.</summary>
/// <param name="call">The call.</param>
/// <param name="budget">The caller's remaining budget.</param>
/// <returns>The verdict.</returns>
Task<OriginConditionMethodOutcome> ExecuteConditionMethodAsync(OriginConditionMethodCall call, TimeSpan budget) =>
Task.FromResult(TryExecuteConditionMethod(call));
}
/// <summary>Resolves the port against the SDK sink bound at server start; throws while the server is not running.</summary>
@@ -37,6 +46,11 @@ public sealed class DeferredOriginConditionSource(DeferredAddressSpaceSink defer
public OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call) =>
deferred.GetCapability<IOriginConditionSource>() is { } inner ? inner.TryExecuteConditionMethod(call)
: throw new OriginConditionSourceUnavailableException();
/// <inheritdoc />
public Task<OriginConditionMethodOutcome> ExecuteConditionMethodAsync(OriginConditionMethodCall call, TimeSpan budget) =>
deferred.GetCapability<IOriginConditionSource>() is { } inner ? inner.ExecuteConditionMethodAsync(call, budget)
: throw new OriginConditionSourceUnavailableException();
}
/// <summary>
@@ -26,7 +26,11 @@ public sealed record OriginConditionMethodCall(AddressSpaceRealm Realm, string C
/// <param name="Native">Whether the condition is native (driver-fed): an applied native call is accepted, not confirmed.</param>
/// <param name="StatusCode">The OPC UA status (Good when applied).</param>
/// <param name="Diagnostic">A refusal's reason text, when the gate gave one.</param>
public sealed record OriginConditionMethodOutcome(bool Applied, bool Native, uint StatusCode, string? Diagnostic);
/// <param name="Dispatched">#937: <see cref="Applied"/> is false, but the call reached the scripted-alarm engine — which refused
/// it, or did not answer (<see cref="Unknown"/>). The node manager had already applied its node state.</param>
/// <param name="Unknown">#937: the engine did not answer inside the budget (or failed): the command may still apply.</param>
public sealed record OriginConditionMethodOutcome(bool Applied, bool Native, uint StatusCode, string? Diagnostic,
bool Dispatched = false, bool Unknown = false);
public sealed partial class OtOpcUaNodeManager
{
@@ -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);
}
}
@@ -3210,6 +3210,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// (nothing routed, nothing applied, no event). Unset/None keep today's acceptance.
if (_standby.RefusesMutations) return WarmStandbyState.StandbyRefusal($"call {operation}");
// #937: this node's engine holds no complete generation (its last load failed) and would reject the command —
// refuse it before the SDK applies anything (no event, nothing routed). One volatile read; safe under Lock.
if (ScriptedAlarmCommandPreflight?.Invoke() is { } notReady)
return new ServiceResult(StatusCodes.BadInvalidState, new LocalizedText(notReady));
var cmd = new AlarmCommand(
AlarmId: condition.NodeId.IdentifierAsString,
Operation: operation,
@@ -3217,6 +3222,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
Comment: comment?.Text,
UnshelveAtUtc: unshelveAt);
// #937: inside a Call that awaits the engine's verdict (CallAsync / ExecuteConditionMethodAsync), start the
// bounded ask — non-blocking: it only sends — and let the caller await it once Lock is released.
if (TryStartScriptedCommandAsk(cmd)) return ServiceResult.Good;
// Non-blocking by contract (host wires a fire-and-forget mediator.Tell); safe to call under Lock.
AlarmCommandRouter?.Invoke(cmd);
@@ -40,6 +40,10 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
OriginConditionMethodOutcome IOriginConditionSource.TryExecuteConditionMethod(OriginConditionMethodCall call) =>
_nodeManager.TryExecuteConditionMethod(call);
/// <inheritdoc />
Task<OriginConditionMethodOutcome> IOriginConditionSource.ExecuteConditionMethodAsync(OriginConditionMethodCall call, TimeSpan budget) =>
_nodeManager.ExecuteConditionMethodAsync(call, budget);
/// <summary>Initializes a new instance of the SdkAddressSpaceSink class.</summary>
/// <param name="nodeManager">The OPC UA node manager.</param>
public SdkAddressSpaceSink(OtOpcUaNodeManager nodeManager)
@@ -212,7 +212,7 @@ public sealed partial class LocalDataServices
DataWriteOutcome? outcome = null;
try
{
outcome = Dispatch();
outcome = await DispatchAsync().ConfigureAwait(false);
return (FromOutcome(outcome), false);
}
finally
@@ -230,15 +230,16 @@ public sealed partial class LocalDataServices
registry.ReleaseUndispatched(context.PrincipalId, request.OperationId, owner);
}
DataWriteOutcome Dispatch()
async Task<DataWriteOutcome> DispatchAsync()
{
OriginConditionMethodOutcome verdict;
try
{
verdict = ConditionSource.TryExecuteConditionMethod(new(placement.Condition.Realm, placement.Condition.ConditionId,
// #937: a scripted condition answers only once its engine applied (or refused) the command.
verdict = await ConditionSource.ExecuteConditionMethodAsync(new(placement.Condition.Realm, placement.Condition.ConditionId,
DataConditionMethodSets.Part9Name(request.Method), request.Comment,
new ConditionActivationMarker(request.ExpectedActivation.Incarnation, request.ExpectedActivation.Sequence),
context.PrincipalId, context.ApiKeyId));
context.PrincipalId, context.ApiKeyId), request.RemainingBudget).ConfigureAwait(false);
}
catch (OriginConditionSourceUnavailableException ex)
{
@@ -267,6 +268,15 @@ public sealed partial class LocalDataServices
: new(DataWriteState.AcceptedUnconfirmed, verdict.StatusCode,
"AcceptedUnconfirmed: the comment was applied at the origin (not sent to the driver); it arrives on the condition stream.");
}
else if (verdict.Dispatched)
{
// #937: the scripted engine refused it after the node manager dispatched it (a definite failure), or did
// not answer inside the budget (OutcomeUnknown — it may still apply; never reported as refused).
owner.TryMarkDispatched();
decided = verdict.Unknown
? new(DataWriteState.OutcomeUnknown, verdict.StatusCode, verdict.Diagnostic)
: new(DataWriteState.DriverConfirmedFailure, verdict.StatusCode, verdict.Diagnostic);
}
else decided = new(DataWriteState.RejectedBeforeDispatch, verdict.StatusCode, verdict.Diagnostic);
owner.Complete(decided);
return decided;
@@ -532,6 +532,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// <summary>Where the synchronous native-ack pre-check snapshot is published (lmxopcua#760); null ⇒ none.</summary>
private readonly NativeAlarmAckPreflightView? _ackPreflightView;
/// <summary>#937: where the scripted-alarm host publishes its load outcome (null in tests).</summary>
private readonly ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmCommandReadinessView? _scriptedAlarmReadiness;
/// <summary>The write bounds every child is spawned with and this host's write Ask is derived from
/// (lmxopcua#777).</summary>
private readonly DriverWriteBounds _writeBounds;
@@ -875,7 +878,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
DataConnectionDeploymentRuntime? dataConnections = null,
ActorProjectedValuePublisher? projectedPublisher = null,
ConditionSignalOptions? conditionSignals = null) =>
ConditionSignalOptions? conditionSignals = null,
ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmCommandReadinessView? scriptedAlarmReadiness = null) =>
// WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an
// expression tree. Six IActorRef? parameters and several interface-typed ones mean a
// mis-ordered argument is usually type-compatible and therefore compiles clean, then binds
@@ -891,7 +895,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView,
scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout,
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity, dataConnections, projectedPublisher,
conditionSignals));
conditionSignals, scriptedAlarmReadiness));
/// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary>
/// <param name="dbFactory">Database context factory for configuration database access.</param>
@@ -1034,9 +1038,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
DataConnectionDeploymentRuntime? dataConnections = null,
ActorProjectedValuePublisher? projectedPublisher = null,
ConditionSignalOptions? conditionSignals = null)
ConditionSignalOptions? conditionSignals = null,
ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmCommandReadinessView? scriptedAlarmReadiness = null)
{
_conditionSignals = conditionSignals ?? new ConditionSignalOptions();
_scriptedAlarmReadiness = scriptedAlarmReadiness;
_projectedPublisher = projectedPublisher;
_dataWriteRuntime = dataWriteRuntime;
_dataConnections = dataConnections;
@@ -1399,7 +1405,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
var upstream = new DependencyMuxTagUpstreamSource();
return (upstream, CreateScriptedAlarmEngine(upstream, store, scriptLogger, scripting, alarmRunner));
},
_localNode, telemetryHub: _telemetryHub),
_localNode, telemetryHub: _telemetryHub, readiness: _scriptedAlarmReadiness),
"scripted-alarm-host");
}
@@ -1781,6 +1787,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
Receive<RouteNodeWrite>(HandleRouteNodeWrite);
Receive<RouteRichWrite>(HandleRouteRichWrite);
Receive<RouteNativeAlarmAck>(HandleRouteNativeAlarmAck);
Receive<ScriptedAlarmHostActor.ExecuteAlarmCommand>(HandleExecuteAlarmCommand);
Receive<DriverInstanceActor.AlarmAckFailed>(HandleAlarmAckFailed);
Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
Receive<Akka.Cluster.ClusterEvent.IMemberEvent>(OnDriverMembershipChanged);
@@ -1862,6 +1869,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
Receive<RouteNodeWrite>(HandleRouteNodeWrite);
Receive<RouteRichWrite>(HandleRouteRichWrite);
Receive<RouteNativeAlarmAck>(HandleRouteNativeAlarmAck);
Receive<ScriptedAlarmHostActor.ExecuteAlarmCommand>(HandleExecuteAlarmCommand);
Receive<DriverInstanceActor.AlarmAckFailed>(HandleAlarmAckFailed);
Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
Receive<Akka.Cluster.ClusterEvent.IMemberEvent>(OnDriverMembershipChanged);
@@ -2587,6 +2595,23 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// <see cref="DriverInstanceActor.RouteAlarmAck"/> carrying the wire-ref FullName + principal.</item>
/// </list>
/// </summary>
/// <summary>
/// #937: the node-local ask behind a scripted condition's Part 9 method. Forwarded (sender kept) to this node's
/// <see cref="ScriptedAlarmHostActor"/>, which applies it and answers the asker; with no host (no condition-state
/// store, or not spawned yet) it is answered here — nothing on this node can apply it.
/// </summary>
private void HandleExecuteAlarmCommand(ScriptedAlarmHostActor.ExecuteAlarmCommand msg)
{
if (_scriptedAlarmHost is { } host)
{
host.Forward(msg);
return;
}
Sender.Tell(new AlarmCommandOutcome(msg.Command.AlarmId, msg.Command.Operation, AlarmCommandVerdict.NotApplied,
"This server runs no scripted-alarm engine; the command was not applied."));
}
private void HandleRouteNativeAlarmAck(RouteNativeAlarmAck msg)
{
// PRIMARY GATE FIRST (archreview 03/S4) — only the Primary pushes the ack upstream. Same policy as
@@ -2938,6 +2963,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// An inbound native-condition ack can't be serviced while Stale either (the alarm inverse map is
// empty until an apply runs). The node manager's pre-check refuses it synchronously while Stale (see the
// top of this method); one that raced that refusal is dropped here with a log.
Receive<ScriptedAlarmHostActor.ExecuteAlarmCommand>(HandleExecuteAlarmCommand);
Receive<RouteNativeAlarmAck>(msg =>
_log.Debug("DriverHost {Node}: dropping native-alarm ack for {Node2} while Stale (config DB unreachable)",
_localNode, msg.ConditionNodeId));
@@ -0,0 +1,34 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
/// <summary>
/// #937: the lock-free snapshot the OPC UA node manager consults to refuse, synchronously and before the SDK applies
/// anything, a Part 9 method on a scripted condition while this node's scripted-alarm engine holds no complete
/// generation (its last load failed — the engine would reject the command with
/// <c>ScriptedAlarmCommandRejectedException</c>). <see cref="ScriptedAlarmHostActor"/> publishes the outcome of every
/// completed load; <see cref="Refusal"/> is one volatile read, safe under the SDK node-manager lock.
/// </summary>
/// <remarks>
/// Racy by design against a load completing a moment later: a command it lets through while a load is in flight
/// that then FAILS is still rejected by the engine, and the bounded ask (<c>ScriptedAlarmHostActor.ExecuteAlarmCommand</c>)
/// reports that to the caller. It never refuses anything before the first load completes (unknown ⇒ let it through).
/// </remarks>
public sealed class ScriptedAlarmCommandReadinessView
{
/// <summary>The refusal text while the last completed load failed.</summary>
public const string LoadFailedRefusal =
"The last scripted-alarm deploy failed to load on this server, so the alarm engine holds no trusted condition state; "
+ "the command was not applied. Fix the deployment and redeploy.";
private volatile string? _refusal;
/// <summary>Why a scripted-alarm command would be rejected right now, or null to proceed.</summary>
/// <returns>The refusal reason, or null.</returns>
public string? Refusal() => _refusal;
/// <summary>Records the outcome of the latest completed load. Called by <see cref="ScriptedAlarmHostActor"/> only.</summary>
/// <param name="loaded">True when it completed a generation; false when it failed.</param>
internal void SetLoadOutcome(bool loaded) => _refusal = loaded ? null : LoadFailedRefusal;
/// <summary>Forgets any outcome (a new host incarnation has not loaded yet). Called by the host only.</summary>
internal void Reset() => _refusal = null;
}
@@ -86,6 +86,16 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// <param name="Plans">The desired Equipment-namespace scripted-alarm plans.</param>
public sealed record ApplyScriptedAlarms(IReadOnlyList<EquipmentScriptedAlarmPlan> Plans);
/// <summary>
/// #937: a NODE-LOCAL ask (never published, never serialized) — apply <paramref name="Command"/> to this host's
/// engine and reply an <see cref="AlarmCommandOutcome"/> to the sender, so the OPC UA Part 9 method that issued it
/// can return the engine's verdict instead of the Good a fire-and-forget topic publish implied. The same command
/// (same <see cref="AlarmCommand.CommandId"/>) is also broadcast on <see cref="AlarmCommandsTopic"/> for the
/// redundant peer; this host applies whichever copy arrives first and skips the other.
/// </summary>
/// <param name="Command">The command.</param>
public sealed record ExecuteAlarmCommand(AlarmCommand Command);
/// <summary>
/// Told to the parent from <see cref="PostRestart"/>. A supervision restart is otherwise invisible to the
/// parent, and the new incarnation has an EMPTY engine (factory Props) and no mux interest, so until the
@@ -175,6 +185,19 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// <see cref="OnAlarmsLoaded"/> so out-of-order loads never register superseded dep refs.</summary>
private int _loadGeneration;
/// <summary>#937: the published outcome of the latest completed load (null in tests).</summary>
private readonly ScriptedAlarmCommandReadinessView? _readiness;
/// <summary>#937: the enabled alarm ids of the latest <see cref="ApplyScriptedAlarms"/> — this host's alarms even while
/// the engine's own set is mid-load or (a failed load) half-built.</summary>
private HashSet<string> _plannedAlarmIds = new(StringComparer.Ordinal);
/// <summary>#937: the outcome of each recent command that carried a <see cref="AlarmCommand.CommandId"/>, so the
/// broadcast copy of a directly-asked command (or the other way round) is applied once. Bounded FIFO.</summary>
private readonly Dictionary<string, AlarmCommandOutcome> _recentCommands = new(StringComparer.Ordinal);
private readonly Queue<string> _recentCommandOrder = new();
internal const int RecentCommandCapacity = 1024;
/// <summary>Cached cluster DistributedPubSub mediator, resolved once in <see cref="PreStart"/> (on the
/// actor thread) and reused for every emission instead of re-resolving it per-publish.</summary>
private IActorRef _mediator = null!;
@@ -230,8 +253,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
NodeId? localNode = null,
Func<int>? driverMemberCountProvider = null,
ITelemetryLocalHub? telemetryHub = null,
TimeSpan? commandTimeout = null) =>
Akka.Actor.Props.Create(() => new ScriptedAlarmHostActor(publishActor, mux, engineFactory, localNode, driverMemberCountProvider, telemetryHub, commandTimeout));
TimeSpan? commandTimeout = null,
ScriptedAlarmCommandReadinessView? readiness = null) =>
Akka.Actor.Props.Create(() => new ScriptedAlarmHostActor(publishActor, mux, engineFactory, localNode, driverMemberCountProvider, telemetryHub, commandTimeout, readiness));
/// <summary>Factory-built incarnation: owns (and on every stop disposes) the engine it builds.</summary>
/// <param name="publishActor">The OPC UA publish actor emissions are bridged to.</param>
@@ -241,6 +265,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// <param name="driverMemberCountProvider">Test seam for the alerts-emit gate's driver-member count.</param>
/// <param name="telemetryHub">Optional node-local live-telemetry hub.</param>
/// <param name="commandTimeout">Bound on one inbound alarm command's engine op.</param>
/// <param name="readiness">#937: where the outcome of every completed load is published for the node manager's
/// synchronous pre-check. Null ⇒ none (tests).</param>
public ScriptedAlarmHostActor(
IActorRef publishActor,
IActorRef? mux,
@@ -248,8 +274,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
NodeId? localNode = null,
Func<int>? driverMemberCountProvider = null,
ITelemetryLocalHub? telemetryHub = null,
TimeSpan? commandTimeout = null)
: this(publishActor, mux, Build(engineFactory), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: true, commandTimeout)
TimeSpan? commandTimeout = null,
ScriptedAlarmCommandReadinessView? readiness = null)
: this(publishActor, mux, Build(engineFactory), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: true, commandTimeout, readiness)
{
}
@@ -284,7 +311,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
NodeId? localNode = null,
Func<int>? driverMemberCountProvider = null,
ITelemetryLocalHub? telemetryHub = null)
: this(publishActor, mux, (upstream, engine), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: false, commandTimeout: null)
: this(publishActor, mux, (upstream, engine), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: false, commandTimeout: null, readiness: null)
{
}
@@ -296,8 +323,12 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
Func<int>? driverMemberCountProvider,
ITelemetryLocalHub? telemetryHub,
bool ownsEngine,
TimeSpan? commandTimeout)
TimeSpan? commandTimeout,
ScriptedAlarmCommandReadinessView? readiness)
{
_readiness = readiness;
// A new incarnation has not loaded yet: whatever the previous one published no longer describes this engine.
_readiness?.Reset();
ArgumentNullException.ThrowIfNull(publishActor);
ArgumentNullException.ThrowIfNull(pair.Upstream);
ArgumentNullException.ThrowIfNull(pair.Engine);
@@ -341,6 +372,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// the handler is a Task-returning ReceiveAsync: Akka suspends the mailbox until the op completes
// (ordered, awaited on the actor thread) and routes any escaped fault through supervision.
ReceiveAsync<AlarmCommand>(OnAlarmCommand);
// #937: the node-local ask behind an OPC UA Part 9 method — same op, plus a reply carrying the verdict.
ReceiveAsync<ExecuteAlarmCommand>(OnExecuteAlarmCommand);
// A faulted LoadAsync pipes back a Status.Failure (see OnApply) — log it and stay inert so the
// failure doesn't hit the dead-letter log.
Receive<Status.Failure>(OnLoadFailed);
@@ -369,6 +402,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// Skip disabled plans entirely — the engine has no Enabled flag, so a disabled alarm is simply
// not loaded (no predicate, no upstream subscription, no events).
var enabled = msg.Plans.Where(p => p.Enabled).ToList();
_plannedAlarmIds = new HashSet<string>(enabled.Select(p => p.ScriptedAlarmId), StringComparer.Ordinal);
var defs = enabled.Select(ToDefinition).ToList();
@@ -401,10 +435,19 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
}
private void OnLoadFailed(Status.Failure msg)
=> _log.Warning(msg.Cause, "ScriptedAlarmHost: engine LoadAsync failed — alarms not (re)loaded");
{
// #937: loads serialize on the engine's gate, so completions arrive in start order — this is the latest
// completed load, and the engine now holds no complete generation (it rejects every operator command).
_readiness?.SetLoadOutcome(loaded: false);
_log.Warning(msg.Cause, "ScriptedAlarmHost: engine LoadAsync failed — alarms not (re)loaded; operator commands are refused until the next successful deploy");
}
private void OnAlarmsLoaded(AlarmsLoaded msg)
{
// #937: ANY completed load — even one a newer apply superseded — left the engine holding a complete generation
// until that newer load finishes (which then publishes its own outcome).
_readiness?.SetLoadOutcome(loaded: true);
// Discard a stale completion: if a newer apply has since bumped the generation, this load's
// dep refs are superseded and registering them would re-introduce the old set. The latest
// generation's continuation will (or already did) register the current interest set.
@@ -741,17 +784,74 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// <param name="cmd">The inbound alarm command.</param>
private async Task OnAlarmCommand(AlarmCommand cmd)
{
// #937: the broadcast copy of a command this host already took through ExecuteAlarmCommand (or the other way
// round) is applied once.
if (cmd.CommandId is { } id && _recentCommands.ContainsKey(id))
{
_log.Debug("ScriptedAlarmHost: skipping duplicate AlarmCommand {Op} for {AlarmId} (command {CommandId})",
cmd.Operation, cmd.AlarmId, id);
return;
}
// Ownership filter FIRST: ignore commands for alarms this engine doesn't own. The topic is a
// cluster-wide broadcast, so the same command lands on every host — only the owner acts.
// Note: a concurrent LoadAsync can momentarily clear the loaded set, so a racing command may
// surface a spurious ArgumentException from the engine below — the outer catch absorbs it (benign).
if (!_engine.LoadedAlarmIds.Contains(cmd.AlarmId))
if (!Owns(cmd.AlarmId))
{
_log.Debug("ScriptedAlarmHost: ignoring AlarmCommand {Op} for unowned alarm {AlarmId}",
cmd.Operation, cmd.AlarmId);
return;
}
Remember(cmd, await ApplyCommandAsync(cmd));
}
/// <summary>
/// #937: the node-local ask behind an OPC UA Part 9 method. Applies the command exactly as
/// <see cref="OnAlarmCommand"/> does (once — a broadcast copy that already arrived is not re-applied; its recorded
/// outcome is the answer) and replies the verdict to the sender. Unlike the broadcast, an alarm this host does not
/// own is answered (<see cref="AlarmCommandVerdict.NotApplied"/>): the caller's condition node is on this node.
/// </summary>
private async Task OnExecuteAlarmCommand(ExecuteAlarmCommand msg)
{
var replyTo = Sender;
var cmd = msg.Command;
if (cmd.CommandId is { } id && _recentCommands.TryGetValue(id, out var known))
{
replyTo.Tell(known);
return;
}
var outcome = Owns(cmd.AlarmId)
? await ApplyCommandAsync(cmd)
: new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
_readiness?.Refusal() ?? NotLoadedRefusal);
Remember(cmd, outcome);
replyTo.Tell(outcome);
}
private const string NotLoadedRefusal =
"The alarm is not loaded by this server's scripted-alarm engine; the command was not applied.";
/// <summary>Whether this host owns <paramref name="alarmId"/>: in the latest plan (stable across a load in flight and
/// a failed load's half-built set) or loaded by the engine (a legacy, externally loaded engine).</summary>
private bool Owns(string alarmId) => _plannedAlarmIds.Contains(alarmId) || _engine.LoadedAlarmIds.Contains(alarmId);
private void Remember(AlarmCommand cmd, AlarmCommandOutcome outcome)
{
if (cmd.CommandId is not { } id || !_recentCommands.TryAdd(id, outcome)) return;
_recentCommandOrder.Enqueue(id);
while (_recentCommandOrder.Count > RecentCommandCapacity) _recentCommands.Remove(_recentCommandOrder.Dequeue());
}
/// <summary>
/// Runs one owned command against the engine and classifies the result (#937). Never throws: every failure is
/// logged like <see cref="OnLoadFailed"/> and becomes a verdict.
/// </summary>
private async Task<AlarmCommandOutcome> ApplyCommandAsync(AlarmCommand cmd)
{
AlarmCommandOutcome Refused(string reason) => new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, reason);
// Bounded (R02:H3): every op ends in IAlarmStateStore.SaveAsync (LocalDb/SQLite), and this is a
// ReceiveAsync — the mailbox is suspended until the op returns, so an unbounded await on a hung
// file lock stalled dependency-value ingestion for the duration. Linked to the actor's lifetime
@@ -780,7 +880,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
{
_log.Warning("ScriptedAlarmHost: rejecting TimedShelve for {AlarmId} — missing UnshelveAtUtc",
cmd.AlarmId);
return;
return Refused("TimedShelve requires an unshelve time; the command was not applied.");
}
await _engine.TimedShelveAsync(cmd.AlarmId, cmd.User, unshelveAt, ct);
break;
@@ -797,35 +897,50 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
if (string.IsNullOrWhiteSpace(cmd.Comment))
{
_log.Warning("ScriptedAlarmHost: rejecting AddComment for {AlarmId} — empty comment text", cmd.AlarmId);
return;
return Refused("AddComment requires comment text; the command was not applied.");
}
await _engine.AddCommentAsync(cmd.AlarmId, cmd.User, cmd.Comment, ct);
break;
default:
_log.Warning("ScriptedAlarmHost: ignoring AlarmCommand with unknown operation {Op} for {AlarmId}",
cmd.Operation, cmd.AlarmId);
break;
return Refused($"Unknown alarm operation '{cmd.Operation}'; the command was not applied.");
}
return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied);
}
catch (OperationCanceledException) when (!_cts.IsCancellationRequested)
{
// The op may have been cancelled inside SaveAsync after the store committed: unknown, never "not applied".
_log.Warning("ScriptedAlarmHost: engine op {Op} for alarm {AlarmId} timed out after {Timeout} — the condition-state store is stalled",
cmd.Operation, cmd.AlarmId, _commandTimeout);
return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
$"OutcomeUnknown: the alarm engine did not finish the command within {_commandTimeout.TotalSeconds:0.#} s.", TimedOut: true);
}
catch (ScriptedAlarmCommandRejectedException ex)
{
// #935 review S3: the last LoadAsync failed, so the engine holds no trusted state and refuses the
// command rather than persist one derived from a Fresh seed. The command is a fire-and-forget topic
// broadcast (the OPC UA method / AdminUI already returned), so this Warning is the operator-visible
// record; the next successful deploy re-asserts the condition node from the store.
// command (thrown before anything is saved) rather than persist one derived from a Fresh seed. #937: a
// directly-asked command reports this to its OPC UA caller; a broadcast-only copy (the AdminUI, the
// redundant peer's copy) has only this Warning. The next successful deploy re-asserts the node from the store.
_log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} NOT applied — {Reason}",
cmd.Operation, cmd.AlarmId, ex.Message);
return Refused(ScriptedAlarmCommandReadinessView.LoadFailedRefusal);
}
catch (ArgumentException ex)
{
// The engine's lookup (under its gate, before any save): the alarm is not in the generation the command
// ran against — e.g. the deploy queued ahead of it removed the alarm.
_log.Warning(ex, "ScriptedAlarmHost: engine op {Op} refused for alarm {AlarmId}", cmd.Operation, cmd.AlarmId);
return Refused(NotLoadedRefusal);
}
catch (Exception ex)
{
// A failing engine op must not crash the actor — mirror OnLoadFailed's log-and-stay-inert style.
// A failing engine op must not crash the actor — mirror OnLoadFailed's log-and-stay-inert style. A store
// fault may have left the row written, so this is unknown, not a refusal.
_log.Warning(ex, "ScriptedAlarmHost: engine op {Op} failed for alarm {AlarmId}",
cmd.Operation, cmd.AlarmId);
return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
"OutcomeUnknown: the alarm engine failed while applying the command.");
}
}
@@ -887,6 +1002,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
_engine.OnInputsEstablished -= _onInputsEstablished;
if (_ownsEngine || !_restarting) _engine.Dispose();
_cts.Dispose();
// #937: this engine's load outcome describes nothing once it is gone (the ask path answers for a missing host).
_readiness?.Reset();
base.PostStop();
}
@@ -117,6 +117,8 @@ public static class ServiceCollectionExtensions
// The condition → owning-driver native-ack pre-check snapshot (lmxopcua#760): DriverHostActor publishes
// it, the OPC UA node manager reads it to refuse an acknowledge the driver would refuse anyway.
services.TryAddSingleton<NativeAlarmAckPreflightView>();
// #937: the scripted-alarm engine's load outcome, for the node manager's synchronous Part 9 method pre-check.
services.TryAddSingleton<ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmCommandReadinessView>();
// The node→central ack transport under MeshTransport:Mode = Grpc (mesh gRPC command plane).
// Registered unconditionally but resolved only by the Grpc arm of
@@ -686,7 +688,9 @@ public static class ServiceCollectionExtensions
// raised on the condition-state hub. A malformed value fails host start.
conditionSignals: ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionSignalOptions.FromConfiguration(
resolver.GetService<IConfiguration>(),
resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionStateHub>())),
resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionStateHub>()),
// #937: where the scripted-alarm host publishes its load outcome (the Part 9 method pre-check).
scriptedAlarmReadiness: resolver.GetService<ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmCommandReadinessView>()),
DriverHostActorName);
registry.Register<DriverHostActorKey>(driverHost);