fix(alarms): #937 review r1 — revert a refused scripted method, broadcast to the peer only after the local verdict, settle a batch per request, in-flight cap

1. A post-dispatch refusal now puts the node back to its captured pre-call state
   with one corrective event (skipped when the node changed since) — the SDK had
   already applied and reported the change. Blank scripted AddComment is refused
   in the handler before the SDK runs.
2. ScriptedAlarmCommandDispatch: ask the local engine first, broadcast to the peer
   only on Applied/OutcomeUnknown — a refusal now reached no engine anywhere.
3. ApplyAsync no longer checks 'loaded' before _evalGate: a command racing the
   first load queues behind it; never loaded => refusal (nothing applied).
4. One Call's requests are settled sequentially (no request runs against a node
   state the engine refused); <= 64 asks in flight node-wide, else
   BadTooManyOperations before anything applies; per-request bound starts at send.
   Measured 300 acks through one host + LocalDb: 59 ms sequential, max 24 ms/ask
   with 64 outstanding.
5. Mixed-batch wire test (scripted refused + native + imported + scripted applied
   + core-manager method): per-item status in order, one scripted ask at a time.
L6: readiness from the engine's HasCompleteGeneration on a load fault.
L7: the verdict slot is closed when its SDK call returns (timer-captured
AsyncLocal can no longer park an ask). L10: remote budget never stretched.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-11-28 11:51:28 -05:00
parent 66b75aed0f
commit 6004a5a565
14 changed files with 670 additions and 125 deletions
+6 -2
View File
@@ -95,8 +95,12 @@ activation per still-true alarm on the next good deploy.
while the last load failed. (2) Inside `CallAsync` (off `Lock`) each local request runs `base.Call` alone with an `AsyncLocal`
verdict slot; the handler, under `Lock`, only STARTS `AlarmCommandAsker` (broadcast for the peer + `DriverHostActor` →
`ScriptedAlarmHostActor.ExecuteAlarmCommand` to the LOCAL engine, fresh `CommandId` ⇒ the host applies ask/broadcast copies
once) and returns Good; the Call then awaits the verdict: refused ⇒ `BadInvalidState`, no answer (min 5 s / deadline − 250 ms)
⇒ `BadTimeout` "OutcomeUnknown" (never "refused" — it may still apply). Remote gRPC-data methods ride
once) and returns Good; the Call then settles the verdict — one request at a time, before the next runs: refused ⇒
`BadInvalidState` AND the node reverted to its captured pre-call state with one corrective event (skipped if the node
changed since); no answer (min 5 s / deadline − 250 ms) ⇒ `BadTimeout` "OutcomeUnknown" (never "refused" — it may still
apply; node kept). The peer gets the broadcast only AFTER an applied/unknown local verdict (`ScriptedAlarmCommandDispatch`)
— broadcasting first let the peer apply a command the caller was told failed. ≤ 64 asks in flight node-wide, else
`BadTooManyOperations` before anything applies. A native AddComment skips all of this (no engine owns it). Remote gRPC-data methods ride
`ExecuteConditionMethodAsync` (⇒ `DriverConfirmedFailure` / `OutcomeUnknown`). Never await the verdict inside the handler
(it runs under `Lock`). The sync `base.Call` path (no asker) keeps the old fire-and-forget router. The AdminUI `/alerts` path is
still fire-and-forget. A plain SDK client sees only the status code (diagnostic text needs ReturnDiagnostics).
+24 -13
View File
@@ -189,7 +189,8 @@ after a full rebuild, carrying the unchanged `LastTransitionUtc`. Decisions:
and shelving checks are dropped. **Since #937 an OPC UA Part 9 method (and a remote gRPC-data condition method) on a
scripted condition reports this**: while the last load failed the node manager refuses the call `BadInvalidState` before the
SDK applies anything (no event, nothing routed); a call that passed that pre-check and then met a rejection (it was queued
behind a load that failed) also returns `BadInvalidState` — see [Operator command verdicts](#operator-command-verdicts-937).
behind a load that failed) also returns `BadInvalidState` and the node is reverted — see
[Operator command verdicts](#operator-command-verdicts-937).
The AdminUI `/alerts` buttons still publish fire-and-forget ("Ack sent"), so for them the only record remains the host's
Warning `… NOT applied — …`. The next good load re-asserts every node from the store.
**Accepted trade-off:** because the next good load after a failed one reads the store (which has no `Active` column), each
@@ -425,17 +426,26 @@ of which blocks under the node manager's `Lock`:
1. **Pre-check** — `ScriptedAlarmCommandReadinessView` (Runtime singleton) holds the outcome of the host's latest completed
load; the handler reads it (one volatile read) after the role/ACL gate and the Warm-standby check. While the last load
failed it returns `BadInvalidState` and nothing is applied, routed or reported. It never refuses before the first load.
2. **Bounded ask** — inside the Call service (`OtOpcUaNodeManager.CallAsync`, which the SDK invokes off `Lock`), each local
request runs through the SDK's `base.Call` on its own; the handler, under `Lock`, only *starts* the ask
(`AlarmCommandAsker`): the hosted service broadcasts the command on `alarm-commands` for the redundant peer (as before)
and asks **this node's** `ScriptedAlarmHostActor` (via `DriverHostActor`, `ExecuteAlarmCommand`) for its verdict, with a
fresh `CommandId` so the local host applies whichever copy reaches it first, once. The SDK applies its node state and
reports the one method event exactly as before; then the Call awaits the verdict with no lock held.
2. **Bounded ask** — inside the Call service (`OtOpcUaNodeManager.CallAsync`, which the SDK invokes off `Lock`; SDK 2.0.1's
`StandardServer.CallAsync` awaits it, so no request thread is held), each local request runs through the SDK's
`base.Call` on its own and is SETTLED before the next request of the batch runs. The handler, under `Lock`, only
*starts* the ask (`AlarmCommandAsker`): the hosted service asks **this node's** `ScriptedAlarmHostActor` (via
`DriverHostActor`, `ExecuteAlarmCommand`) and broadcasts the command on `alarm-commands` for the redundant peer **only
after the local verdict is applied or unknown** (`ScriptedAlarmCommandDispatch`), with a fresh `CommandId` so the local
host applies its two copies once. The SDK applies its node state and reports the one method event exactly as before;
then the Call awaits the verdict with no lock held. **A refusal reverts the node** to its captured pre-call state with
one corrective event — unless something else changed the node since (newer truth wins) — mirroring the #760 native-ack
revert. Cheap refusals the engine would make (a blank scripted AddComment ⇒ `BadInvalidArgument`) happen in the
handler, before the SDK applies anything.
3. **Load bound** — at most 64 asks outstanding node-wide (`MaxScriptedCommandsInFlight`); past it the call is refused
`BadTooManyOperations` before anything is applied or sent. Each request's 5 s bound starts when its own ask is sent.
Measured through one host with the production LocalDb store (`ScriptedAlarmCommandThroughputTests`): 300 sequential
acks in 59 ms (max 11 ms each); 300 AddComments with 64 outstanding at once in 49 ms (max 24 ms each).
| Engine verdict | Method status |
|---|---|
| applied (incl. an idempotent no-op) | `Good` |
| refused — last load failed, alarm not loaded on this node, malformed command, no engine on this node | `BadInvalidState` |
| refused — last load failed, alarm not loaded on this node (incl. the window after a host supervision restart before its reload), malformed command, no engine on this node | `BadInvalidState` (node reverted; the peer never received it) |
| no answer within min(5 s, request deadline − 250 ms), or the engine op timed out / failed in the store | `BadTimeout` / `BadInternalError`, diagnostic "OutcomeUnknown" — the command **may still apply**, never reported as refused |
`BadInvalidState` is Part 4's general "object … uninitialized or in some other invalid state" code; Part 9's method result
@@ -443,14 +453,15 @@ codes (bad EventId, already acked/confirmed/shelved, disabled, shelving time out
cannot act", and the server already uses `BadInvalidState` for a native ack off-Primary. The status is the contract: a plain
SDK client sees only the code (the reason text travels in diagnostics, returned only when requested).
**Redundancy.** The verdict is the LOCAL engine's — the one that projects this node's condition node. The peer still applies
its broadcast copy independently (and both engines' saves converge through the replicated LocalDb row). A remote
**Redundancy.** The verdict is the LOCAL engine's — the one that projects this node's condition node. The peer applies its
broadcast copy independently once the local engine applied it (or did not answer); a locally refused command is never
broadcast, so no engine anywhere applied it and the revert plus the definite failure are true pair-wide. A remote
gRPC-data `CallConditionMethod` on a scripted condition carries the same verdict (`ExecuteConditionMethodAsync`): applied ⇒
`DriverConfirmedSuccess`, refused after dispatch ⇒ `DriverConfirmedFailure`, no answer ⇒ `OutcomeUnknown`.
**Residual.** Only the pre-check stops the SDK from applying the node change. A refusal that arrives through the ask (a load
in flight when the command queued behind it, which then failed) leaves the node showing the change — and its one event
reported — until the next good deploy re-asserts the node from the store; the caller gets `BadInvalidState`.
**Residual.** Only the pre-check stops the SDK from applying the node change, so a refusal that arrives through the ask
shows subscribers two events: the method's, then the corrective one. An OutcomeUnknown leaves the node changed (the engine
may still apply it). A command racing the engine's first load queues behind it rather than failing.
**Not covered:** the AdminUI `/alerts` buttons are still fire-and-forget across the central→node transport (they report
"Ack sent", not "applied").
@@ -215,7 +215,6 @@ public sealed class ScriptedAlarmEngine : IDisposable
private readonly List<IDisposable> _upstreamSubscriptions = [];
private readonly SemaphoreSlim _evalGate = new(1, 1);
private Timer? _shelvingTimer;
private bool _loaded;
/// <summary>
/// #935: whether <see cref="_alarms"/> holds a COMPLETED generation — set at the end of a successful
@@ -230,6 +229,12 @@ public sealed class ScriptedAlarmEngine : IDisposable
/// </summary>
private bool _generationComplete;
/// <summary>
/// #937: whether the engine currently holds a COMPLETED generation (operator commands are accepted). A lock-free
/// read of the flag <c>_evalGate</c> guards: false while a load is in flight and after a failed one.
/// </summary>
public bool HasCompleteGeneration => Volatile.Read(ref _generationComplete);
// 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
@@ -402,7 +407,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
carryOver = new Dictionary<string, AlarmConditionState>(_alarms.Count, StringComparer.Ordinal);
foreach (var (alarmId, prior) in _alarms) carryOver[alarmId] = prior.Condition;
}
_generationComplete = false;
Volatile.Write(ref _generationComplete, false);
UnsubscribeFromUpstream();
_alarms.Clear();
@@ -484,9 +489,9 @@ public sealed class ScriptedAlarmEngine : IDisposable
// Seed the value cache with current tag values before subscribing. The
// ReadTag calls happen first so that the initial predicate evaluation below
// (startup recovery) uses a consistent snapshot.
// Subscriptions are established AFTER _loaded = true so that any synchronous
// Subscriptions are established AFTER the generation completes so that any synchronous
// initial-push an ITagUpstreamSource delivers from inside SubscribeTag arrives
// when _alarms is fully initialised. Before _loaded = true, a synchronous push
// when _alarms is fully initialised. Before then, a synchronous push
// would race the in-progress state restore and could overwrite the carefully
// seeded cache with a push that has no defined ordering relative to ReadTag.
foreach (var path in _alarmsReferencing.Keys)
@@ -531,10 +536,9 @@ public sealed class ScriptedAlarmEngine : IDisposable
}
}
_loaded = true;
_generationComplete = true;
Volatile.Write(ref _generationComplete, true);
// Subscribe after _loaded = true and full state restore. If an upstream
// Subscribe after the generation completed and full state restore. If an upstream
// implementation pushes its initial value synchronously from inside
// SubscribeTag, OnUpstreamChange will queue a ReevaluateAsync that acquires
// _evalGate — it will correctly block until LoadAsync releases the gate, then
@@ -740,12 +744,13 @@ public sealed class ScriptedAlarmEngine : IDisposable
private async Task ApplyAsync(string alarmId, CancellationToken ct, Func<AlarmConditionState, TransitionResult> op)
{
EnsureLoaded();
ScriptedAlarmEvent? pending = null;
await _evalGate.WaitAsync(ct).ConfigureAwait(false);
try
{
// #937 review: no separate "not loaded" check before the gate any more — a command racing the FIRST load used
// to throw InvalidOperationException there (the host could only classify it as unknown). It now queues behind
// the load; never loaded ⇒ no completed generation ⇒ the refusal below (nothing applied).
// #935 review S1: look the alarm up only once the gate is held. Looked up before it, a command racing a
// LoadAsync captured either the old generation's entry (and wrote its state over the new one) or the
// load's interim Fresh entry (and, an ack being a no-op on Fresh, saved Fresh over the carried Active
@@ -1784,12 +1789,6 @@ public sealed class ScriptedAlarmEngine : IDisposable
_upstreamSubscriptions.Clear();
}
private void EnsureLoaded()
{
if (!_loaded) throw new InvalidOperationException(
"ScriptedAlarmEngine not loaded. Call LoadAsync first.");
}
/// <summary>Disposes the engine, cleaning up resources and waiting for in-flight background tasks.</summary>
public void Dispose()
{
@@ -604,54 +604,20 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
}
/// <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.
/// #937: the node manager's <see cref="OtOpcUaNodeManager.AlarmCommandAsker"/> — see
/// <see cref="ScriptedAlarmCommandDispatch.AskThenBroadcastAsync"/>. Runs under the SDK's Lock: it only sends.
/// </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);
}
}
Func<AlarmCommand, TimeSpan, Task<AlarmCommandOutcome>>? askLocal = _actorRegistry.TryGet<DriverHostActorKey>(out var driverHost)
? (c, t) => driverHost.Ask<AlarmCommandOutcome>(new ScriptedAlarmHostActor.ExecuteAlarmCommand(c), t)
: null;
return ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(cmd, timeout, askLocal,
c => DistributedPubSub.Get(_actorSystemAccessor()).Mediator.Tell(new Publish(ScriptedAlarmHostActor.AlarmCommandsTopic, c)),
_logger);
}
/// <summary>
@@ -0,0 +1,79 @@
using Akka.Actor;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa;
/// <summary>
/// #937: how an OPC UA Part 9 method on a scripted condition reaches the engines — this node's first, the redundant peer's
/// only after this node's engine applied it (or did not answer).
/// </summary>
/// <remarks>
/// <para>
/// <b>Why the peer goes second (review r1).</b> Broadcasting first let the peer apply a command the local engine then
/// refused: the caller was told a definite failure, the local node was reverted, and the peer's save came back to this
/// node through the last-writer-wins condition-state replication. Asking first makes a refusal true pair-wide
/// (no engine saw the command) — which is what lets the node manager revert the node and answer
/// <c>BadInvalidState</c>. An applied or unknown verdict is broadcast so the peer converges exactly as before (an
/// unknown local outcome may still apply locally, so the peer must not be left behind).
/// </para>
/// <para>
/// No local engine (no driver host, or it runs no scripted-alarm host) ⇒ <see cref="AlarmCommandVerdict.NotApplied"/>
/// and nothing is broadcast: this node's condition node is driven by no engine, and a command for it is refused.
/// </para>
/// </remarks>
internal static class ScriptedAlarmCommandDispatch
{
/// <summary>
/// Asks the local engine, then broadcasts unless it refused. Starts the ask synchronously (safe under the SDK's Lock);
/// never faults — no answer within <paramref name="timeout"/> is an OutcomeUnknown outcome.
/// </summary>
/// <param name="cmd">The command (with its <c>CommandId</c>, which de-duplicates the broadcast copy on the local host).</param>
/// <param name="timeout">The caller's bound.</param>
/// <param name="askLocal">The ask to this node's scripted-alarm host; null ⇒ none on this node.</param>
/// <param name="broadcast">Publishes the command on the <c>alarm-commands</c> topic.</param>
/// <param name="logger">Logger.</param>
/// <returns>The local verdict.</returns>
internal static async Task<AlarmCommandOutcome> AskThenBroadcastAsync(AlarmCommand cmd, TimeSpan timeout,
Func<AlarmCommand, TimeSpan, Task<AlarmCommandOutcome>>? askLocal, Action<AlarmCommand> broadcast, ILogger logger)
{
if (askLocal is null)
{
return new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied,
"This server runs no scripted-alarm engine; the command was not applied.");
}
AlarmCommandOutcome outcome;
try
{
outcome = await askLocal(cmd, timeout).ConfigureAwait(false);
}
catch (Exception ex) when (ex is AskTimeoutException or TaskCanceledException or TimeoutException)
{
outcome = 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)
{
outcome = new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown,
"OutcomeUnknown: " + ex.GetType().Name);
}
if (outcome.Verdict != AlarmCommandVerdict.NotApplied)
{
try
{
broadcast(cmd);
}
catch (Exception ex)
{
// The peer's copy only; the caller's answer is the local verdict.
logger.LogWarning(ex, "Failed to broadcast alarm command {Operation} for {AlarmId} to the redundant peer",
cmd.Operation, cmd.AlarmId);
}
}
return outcome;
}
}
@@ -138,8 +138,10 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
/// 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).
/// starts against that request; the ask is then settled with no <c>Lock</c> held (its verdict becomes the request's
/// status; a refusal reverts the node) before the next request runs. SDK 2.0.1's <c>StandardServer.CallAsync</c>
/// awaits <c>MasterNodeManager.CallAsync</c> (no request thread is held while this waits). 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)
@@ -150,21 +152,16 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
return;
}
var bound = ScriptedCommandBound(context.OperationDeadline);
List<(int Index, Task<(ServiceResult Status, bool Unknown)> Verdict)>? verdicts = null;
// #937 review r1: one request at a time, each verdict (and any revert) settled before the next request runs, so a
// later request in the batch (e.g. Confirm after a refused Acknowledge) never runs against a node state the engine
// refused. The bound is taken per request, when its ask is sent.
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;
var bound = ScriptedCommandBound(context.OperationDeadline);
if (CallOneAwaitingVerdict(context, methodsToCall, i, results, errors, bound) is not { } pending) continue;
var status = await SettleScriptedVerdictAsync(pending, bound).ConfigureAwait(false);
if (!ServiceResult.IsGood(status)) errors[i] = status;
}
}
@@ -17,22 +17,27 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// 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).
/// <see cref="ExecuteConditionMethodAsync"/> for a remote gRPC-data call) settles the verdict once the SDK released
/// <c>Lock</c>: a refusal becomes <c>BadInvalidState</c> AND reverts the node to its pre-call state with one
/// corrective event (review r1 — subscribers and gRPC-data consumers had seen the change); no answer becomes
/// <c>BadTimeout</c> (OutcomeUnknown — the node keeps the change, which the engine may still apply).
/// </para>
/// <para>
/// <b>Consistency with the peer.</b> The host broadcasts the command to the redundant peer only AFTER the local engine
/// applied it (or did not answer). A refused command therefore reached no engine anywhere, which is what makes the
/// revert and the definite <c>BadInvalidState</c> true.
/// </para>
/// <para>
/// <b>Load bound.</b> At most <see cref="MaxScriptedCommandsInFlight"/> asks are outstanding node-wide; past it the
/// call is refused <c>BadTooManyOperations</c> before the SDK applies anything. One Call's requests are settled one at
/// a time, and each request's bound starts when its ask is sent, so a batch never times out its own tail.
/// </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.
/// server already returns for a native ack off-Primary.
/// </para>
/// </remarks>
public sealed partial class OtOpcUaNodeManager
@@ -40,8 +45,17 @@ 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);
/// <summary>The default node-wide cap on outstanding scripted-command asks.</summary>
internal const int DefaultMaxScriptedCommandsInFlight = 64;
/// <summary>The shortest bound a local call is given (the request deadline can be closer than this; the SDK then answers
/// the client's timeout itself).</summary>
private static readonly TimeSpan MinimumScriptedCommandBound = TimeSpan.FromMilliseconds(50);
private static readonly AsyncLocal<PendingScriptedCommand?> PendingScriptedCommandSlot = new();
private int _scriptedCommandsInFlight;
/// <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.
@@ -49,43 +63,132 @@ public sealed partial class OtOpcUaNodeManager
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.
/// #937 layer 2: hands one command to THIS node's scripted-alarm engine and completes with its verdict (the host
/// broadcasts it to the redundant peer once the local engine applied it). Called under <c>Lock</c>: it MUST only send
/// and return the pending task, and the task must complete (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>
/// <summary>The node-wide cap on outstanding scripted-command asks (past it: <c>BadTooManyOperations</c>, nothing applied).</summary>
internal int MaxScriptedCommandsInFlight { get; set; } = DefaultMaxScriptedCommandsInFlight;
/// <summary>Outstanding scripted-command asks (test/diagnostic observation).</summary>
internal int ScriptedCommandsInFlight => Volatile.Read(ref _scriptedCommandsInFlight);
/// <summary>
/// The verdict slot of ONE Call request (installed only around that request's synchronous SDK call). <see cref="Closed"/>
/// is set the moment that call returns: an <c>AsyncLocal</c> value is captured by anything the SDK starts inside it (a
/// TimedShelve's timer), so a later callback must find the slot closed rather than park an ask nobody awaits.
/// </summary>
private sealed class PendingScriptedCommand(TimeSpan timeout)
{
public TimeSpan Timeout { get; } = timeout;
public Task<AlarmCommandOutcome>? Outcome { get; set; }
public ScriptedMethodRevert? Revert { get; set; }
public volatile bool Closed;
}
/// <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).
/// What a scripted method changed on the node, captured by <c>ReportAfterMethod</c>: the pre-call state to put back if
/// the engine refuses, and the post-call state that proves nothing else has changed the node since.
/// </summary>
private bool TryStartScriptedCommandAsk(AlarmCommand cmd)
private sealed record ScriptedMethodRevert(RealmKey Key, AlarmConditionState Alarm, AlarmConditionSnapshot Before,
LocalizedText? BeforeComment, string? BeforeClientUserId, AlarmConditionDelta After, LocalizedText? AfterComment);
/// <summary>The slot of the request being called on this flow, when it is still open.</summary>
private static PendingScriptedCommand? OpenScriptedSlot() => PendingScriptedCommandSlot.Value is { Closed: false } slot ? slot : null;
/// <summary>
/// From <see cref="HandleAlarmCommand"/> (under <c>Lock</c>): when the current Call awaits a verdict, reserve an
/// in-flight slot and start the ask. Null ⇒ not inside such a call (route fire-and-forget); a Bad result ⇒ refused
/// before anything was sent or applied.
/// </summary>
private ServiceResult? TryStartScriptedCommandAsk(AlarmCommand cmd)
{
if (PendingScriptedCommandSlot.Value is not { Outcome: null } pending || AlarmCommandAsker is not { } asker) return false;
if (OpenScriptedSlot() is not { Outcome: null } pending || AlarmCommandAsker is not { } asker) return null;
if (Interlocked.Increment(ref _scriptedCommandsInFlight) > MaxScriptedCommandsInFlight)
{
Interlocked.Decrement(ref _scriptedCommandsInFlight);
return new ServiceResult(StatusCodes.BadTooManyOperations,
new LocalizedText("Too many scripted-alarm commands are in progress on this server; the command was not applied."));
}
Task<AlarmCommandOutcome> outcome;
try
{
pending.Outcome = asker(cmd with { CommandId = Guid.NewGuid().ToString("N") }, pending.Timeout);
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);
outcome = Task.FromException<AlarmCommandOutcome>(ex);
}
return true;
// The slot is held until the ask itself completes (the asker's own bound), not just until the caller stops waiting.
outcome.ContinueWith(static (_, state) => Interlocked.Decrement(ref ((OtOpcUaNodeManager)state!)._scriptedCommandsInFlight), this,
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
pending.Outcome = outcome;
return ServiceResult.Good;
}
/// <summary>The bound for one request: <see cref="ScriptedCommandTimeout"/>, cut by the request deadline (less a grace).</summary>
/// <summary>
/// From <c>ReportAfterMethod</c>, under <c>Lock</c>, before the SDK handler runs: the state a refusal would restore —
/// only while a verdict slot is open (nothing is captured on the fire-and-forget path).
/// </summary>
private Func<ScriptedMethodRevert>? BeginScriptedMethodCapture(AlarmConditionState alarm, RealmKey key)
{
if (OpenScriptedSlot() is null) return null;
var delta = ReadConditionDelta(alarm);
var before = new AlarmConditionSnapshot(delta.Active, delta.Acknowledged, delta.Confirmed, delta.Enabled, delta.Shelving,
delta.MappedSeverity, delta.Message, delta.Quality.Code,
delta.Shelving == AlarmShelvingKind.Timed && _conditionUnshelveAt.TryGetValue(key, out var unshelveAt) ? unshelveAt : null);
var comment = alarm.Comment?.Value;
var clientUserId = alarm.ClientUserId?.Value;
return () => new ScriptedMethodRevert(key, alarm, before, comment, clientUserId, ReadConditionDelta(alarm), alarm.Comment?.Value);
}
/// <summary>From <c>ReportAfterMethod</c>, under <c>Lock</c>, after a Good method applied and reported: park the revert
/// with the ask the handler started for this request.</summary>
private static void CompleteScriptedMethodCapture(Func<ScriptedMethodRevert>? capture)
{
if (capture is null || OpenScriptedSlot() is not { Outcome: not null, Revert: null } pending) return;
pending.Revert = capture();
}
/// <summary>
/// Puts the node back to its pre-call state with one corrective event, under <c>Lock</c> — only when the node is still
/// the instance called AND still exactly as the method left it (anything that changed it since is newer truth and
/// wins). Mirrors the #760 native-ack revert.
/// </summary>
private void RevertScriptedMethod(ScriptedMethodRevert revert)
{
lock (Lock)
{
if (!_alarmConditions.TryGetValue(revert.Key, out var live) || !ReferenceEquals(live, revert.Alarm)
|| ReadConditionDelta(live) != revert.After || !Equals(live.Comment?.Value, revert.AfterComment))
{
_logger.LogInformation(
"OtOpcUaNodeManager: refused scripted command on {Condition} not reverted — the condition changed since the call",
revert.Key.Id);
return;
}
var now = UtcNow;
if (revert.Before.Shelving == AlarmShelvingKind.Timed && revert.Before.UnshelveAtUtc is { } unshelveAt)
_conditionUnshelveAt[revert.Key] = unshelveAt;
else _conditionUnshelveAt.Remove(revert.Key);
ApplyConditionState(live, revert.Before, now);
if (live.Comment is not null) live.Comment.Value = revert.BeforeComment ?? LocalizedText.Null;
if (live.ClientUserId is not null) live.ClientUserId.Value = revert.BeforeClientUserId ?? string.Empty;
ReportConditionEvent(live, now);
}
}
/// <summary>The bound for one local request: <see cref="ScriptedCommandTimeout"/>, cut by the request deadline (less a
/// grace, so the answer still lands inside the client's TimeoutHint).</summary>
private TimeSpan ScriptedCommandBound(DateTime deadline)
{
var bound = ScriptedCommandTimeout;
@@ -94,14 +197,15 @@ public sealed partial class OtOpcUaNodeManager
var byDeadline = deadline - DateTime.UtcNow - ImportedMethodGrace;
if (byDeadline < bound) bound = byDeadline;
}
return bound < ImportedMethodMinimumDispatchBudget ? ImportedMethodMinimumDispatchBudget : bound;
return bound < MinimumScriptedCommandBound ? MinimumScriptedCommandBound : 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).
/// Runs the SDK's synchronous <c>base.Call</c> for ONE request with a verdict slot installed, and returns the slot when
/// the handler parked an ask in it (null when it 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,
private PendingScriptedCommand? CallOneAwaitingVerdict(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall, int index,
IList<CallMethodResult> results, IList<ServiceResult> errors, TimeSpan bound)
{
var request = methodsToCall[index];
@@ -115,12 +219,31 @@ public sealed partial class OtOpcUaNodeManager
}
finally
{
pending.Closed = true;
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;
return pending.Outcome is not null && ServiceResult.IsGood(singleErrors[0]) ? pending : null;
}
/// <summary>The request's final status from its engine verdict, reverting the node on a refusal. Never throws.</summary>
private async Task<ServiceResult> SettleScriptedVerdictAsync(PendingScriptedCommand pending, TimeSpan bound)
{
var (status, unknown) = await AwaitScriptedVerdictAsync(pending.Outcome!, bound).ConfigureAwait(false);
if (!ServiceResult.IsGood(status) && !unknown && pending.Revert is { } revert)
{
try
{
RevertScriptedMethod(revert);
}
catch (Exception ex)
{
_logger.LogError(ex, "OtOpcUaNodeManager: reverting a refused scripted command failed");
}
}
return status;
}
/// <summary>
@@ -164,8 +287,8 @@ public sealed partial class OtOpcUaNodeManager
/// <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"/>).
/// part runs under <c>Lock</c> exactly as before; the verdict is settled (a refusal reverts the node) after it is
/// released, within <paramref name="budget"/> (capped at <see cref="ScriptedCommandTimeout"/>, never extended past it).
/// </summary>
/// <param name="call">The call.</param>
/// <param name="budget">The caller's remaining budget.</param>
@@ -173,8 +296,10 @@ public sealed partial class OtOpcUaNodeManager
/// <see cref="OriginConditionMethodOutcome.Dispatched"/>; no answer carries <see cref="OriginConditionMethodOutcome.Unknown"/>.</returns>
public async Task<OriginConditionMethodOutcome> ExecuteConditionMethodAsync(OriginConditionMethodCall call, TimeSpan budget)
{
// Review r1 L10: a budget too short to dispatch in is refused unsent — never stretched past what the caller allows.
if (budget < ImportedMethodMinimumDispatchBudget)
return new OriginConditionMethodOutcome(false, false, StatusCodes.BadTimeout.Code, "Budget below the dispatch floor; nothing was sent.");
var bound = budget < ScriptedCommandTimeout ? budget : ScriptedCommandTimeout;
if (bound < ImportedMethodMinimumDispatchBudget) bound = ImportedMethodMinimumDispatchBudget;
var pending = new PendingScriptedCommand(bound);
PendingScriptedCommandSlot.Value = pending;
OriginConditionMethodOutcome decided;
@@ -184,12 +309,18 @@ public sealed partial class OtOpcUaNodeManager
}
finally
{
pending.Closed = true;
PendingScriptedCommandSlot.Value = null;
}
if (!decided.Applied || pending.Outcome is not { } outcome) return decided;
if (!decided.Applied || pending.Outcome is null) return decided;
var (status, unknown) = await AwaitScriptedVerdictAsync(outcome, bound).ConfigureAwait(false);
var (status, unknown) = await AwaitScriptedVerdictAsync(pending.Outcome, bound).ConfigureAwait(false);
if (ServiceResult.IsGood(status)) return decided;
if (!unknown && pending.Revert is { } revert)
{
try { RevertScriptedMethod(revert); }
catch (Exception ex) { _logger.LogError(ex, "OtOpcUaNodeManager: reverting a refused remote scripted command failed"); }
}
var text = status.LocalizedText.IsNullOrEmpty ? null : status.LocalizedText.Text;
return new OriginConditionMethodOutcome(false, decided.Native, status.StatusCode.Code, text, Dispatched: true, Unknown: unknown);
}
@@ -3089,6 +3089,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
{
var before = ReadConditionDelta(alarm);
var retainBefore = alarm.Retain!.Value;
// #937: inside a verdict-awaiting Call, remember what a refusal must put back.
var revertCapture = BeginScriptedMethodCapture(alarm, conditionKey);
var result = sdkHandler();
// A rebuild may have discarded this instance mid-call; its replacement is not what was called.
@@ -3120,6 +3122,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (alwaysReport || ReadConditionDelta(alarm) != before)
ReportConditionEvent(alarm, UtcNow);
CompleteScriptedMethodCapture(revertCapture);
return result;
}
}
@@ -3220,6 +3223,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (scriptedEngine && ScriptedAlarmCommandPreflight?.Invoke() is { } notReady)
return new ServiceResult(StatusCodes.BadInvalidState, new LocalizedText(notReady));
// #937 review r1: a scripted comment the engine would refuse (blank text) is refused here, before the SDK writes it.
if (scriptedEngine && operation == "AddComment" && string.IsNullOrWhiteSpace(comment?.Text))
return new ServiceResult(StatusCodes.BadInvalidArgument, new LocalizedText("AddComment requires comment text."));
var cmd = new AlarmCommand(
AlarmId: condition.NodeId.IdentifierAsString,
Operation: operation,
@@ -3229,7 +3236,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// #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 (scriptedEngine && TryStartScriptedCommandAsk(cmd)) return ServiceResult.Good;
if (scriptedEngine && TryStartScriptedCommandAsk(cmd) is { } started) return started;
// Non-blocking by contract (host wires a fire-and-forget mediator.Tell); safe to call under Lock.
AlarmCommandRouter?.Invoke(cmd);
@@ -436,9 +436,10 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
private void OnLoadFailed(Status.Failure msg)
{
// #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);
// #937: loads serialize on the engine's gate, so completions arrive in start order — this is the latest completed
// load. Publish what the ENGINE says rather than infer it from the fault (review r1 L6): a load can fault after it
// completed its generation (e.g. subscribing), and then the engine still accepts commands.
_readiness?.SetLoadOutcome(loaded: _engine.HasCompleteGeneration);
_log.Warning(msg.Cause, "ScriptedAlarmHost: engine LoadAsync failed — alarms not (re)loaded; operator commands are refused until the next successful deploy");
}
@@ -830,6 +831,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
replyTo.Tell(outcome);
}
private const string NotYetLoadedRefusal =
"This server's scripted-alarm engine has not completed loading its configuration yet; the command was not applied.";
private const string NotLoadedRefusal =
"The alarm is not loaded by this server's scripted-alarm engine; the command was not applied.";
@@ -924,7 +928,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// 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);
// Before the first load completes there is no failure to name (the readiness view is clear then).
return Refused(_readiness?.Refusal() ?? (_loadedGeneration == 0 && _readiness is not null ? NotYetLoadedRefusal
: ScriptedAlarmCommandReadinessView.LoadFailedRefusal));
}
catch (ArgumentException ex)
{
@@ -384,6 +384,35 @@ public sealed class ScriptedAlarmEngineReloadRestatementTests
rig.Events.Where(e => e.AlarmId == "HighTemp").Select(e => e.Emission).ShouldBe([EmissionKind.Acknowledged]);
}
/// <summary>
/// #937 review r1: a command racing the engine's FIRST load queues behind it and applies (it used to throw "not loaded"
/// before the gate — an InvalidOperationException the host could only classify as OutcomeUnknown). A command on an
/// engine that never loaded is a definite refusal.
/// </summary>
[Fact]
public async Task A_command_racing_the_first_load_applies_after_it()
{
using var rig = new Rig();
(await Should.ThrowAsync<ScriptedAlarmCommandRejectedException>(rig.Engine.AcknowledgeAsync("HighTemp", "alice", null, Ct)))
.AlarmId.ShouldBe("HighTemp");
rig.Up.Set("Temp", 150);
using var loadReached = new ManualResetEventSlim();
using var release = new ManualResetEventSlim();
rig.Up.OnRead = _ => { loadReached.Set(); release.Wait(TimeSpan.FromSeconds(30)); };
var load = Task.Run(() => rig.Engine.LoadAsync([Alarm()], Ct), Ct);
loadReached.Wait(TimeSpan.FromSeconds(10), Ct).ShouldBeTrue();
rig.Up.OnRead = null;
var ack = rig.Engine.AcknowledgeAsync("HighTemp", "alice", "seen", Ct);
await Task.Delay(100, Ct);
ack.IsCompleted.ShouldBeFalse("the ack waits for the first load's gate");
release.Set();
await load;
await ack;
rig.Engine.GetState("HighTemp")!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
}
/// <summary>#935 review S1: a command that changes nothing (an uncommented re-ack) writes nothing.</summary>
[Fact]
public async Task An_idempotent_command_does_not_write_the_store()
@@ -0,0 +1,53 @@
using Akka.Actor;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Host.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.OpcUa;
/// <summary>
/// #937 review r1: the redundant peer receives a Part 9 command only after THIS node's engine applied it (or did not
/// answer) — a local refusal must reach no engine anywhere, or the caller's definite failure and the node revert lie.
/// </summary>
public sealed class ScriptedAlarmCommandDispatchTests
{
private static readonly AlarmCommand Cmd = new("alm-1", "Acknowledge", "alice", null, null, "cmd-1");
[Theory]
[InlineData(AlarmCommandVerdict.Applied, true)]
[InlineData(AlarmCommandVerdict.OutcomeUnknown, true)]
[InlineData(AlarmCommandVerdict.NotApplied, false)]
public async Task The_peer_broadcast_follows_the_local_verdict(AlarmCommandVerdict verdict, bool broadcast)
{
var order = new List<string>();
var outcome = await ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(Cmd, TimeSpan.FromSeconds(1),
(c, _) => { order.Add("ask"); return Task.FromResult(new AlarmCommandOutcome(c.AlarmId, c.Operation, verdict)); },
c => order.Add("broadcast:" + c.CommandId), NullLogger.Instance);
outcome.Verdict.ShouldBe(verdict);
order.ShouldBe(broadcast ? ["ask", "broadcast:cmd-1"] : ["ask"]);
}
[Fact]
public async Task No_answer_is_outcome_unknown_and_still_broadcast_and_no_engine_is_a_refusal_with_none()
{
var sent = 0;
var timedOut = await ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(Cmd, TimeSpan.FromMilliseconds(10),
(_, _) => Task.FromException<AlarmCommandOutcome>(new AskTimeoutException("no answer")), _ => sent++, NullLogger.Instance);
timedOut.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown);
timedOut.TimedOut.ShouldBeTrue();
sent.ShouldBe(1, "the local engine may still apply it, so the peer must not be left behind");
var none = await ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(Cmd, TimeSpan.FromSeconds(1), null, _ => sent++, NullLogger.Instance);
none.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
sent.ShouldBe(1);
// A failing broadcast never changes the caller's answer.
var applied = await ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(Cmd, TimeSpan.FromSeconds(1),
(c, _) => Task.FromResult(new AlarmCommandOutcome(c.AlarmId, c.Operation, AlarmCommandVerdict.Applied)),
_ => throw new InvalidOperationException("mediator down"), NullLogger.Instance);
applied.Verdict.ShouldBe(AlarmCommandVerdict.Applied);
}
}
@@ -637,6 +637,79 @@ public sealed class ImportedConditionMethodWireTests
f.Port.Calls.Select(c => c.OnBehalfOf).Order().ShouldBe(new[] { "anonymous", Granted }.Order());
}
/// <summary>
/// #937 review r1: ONE Call mixing a scripted Acknowledge the engine refuses, a native Acknowledge, an imported-condition
/// Acknowledge, a scripted AddComment the engine applies, and a Server-object method owned by another node manager —
/// each item gets its own status, in request order; scripted items reach the engine one at a time, in order; every
/// item is processed (the core manager answered its own).
/// </summary>
[Fact]
public async Task A_mixed_batch_gets_per_item_status_in_order()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("937-mixed", encrypted: false, ct);
rig.Enforce(false, [ServerEventRig.Key()], ServerEventRig.ClusterGrant(ServerEventRig.KeyPrincipal, "acl-key",
NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead
| NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.AlarmShelve | NodePermissions.MethodCall));
var f = Fixture.Install(rig);
f.Apply(Update(version: 3, active: true, acked: false));
rig.MaterialiseScripted();
rig.MaterialiseNative();
var pre = new AlarmConditionSnapshot(Active: true, Acknowledged: false, Confirmed: true, Enabled: true,
Shelving: AlarmShelvingKind.Unshelved, Severity: 700, Message: "pre");
rig.Project(false, pre);
rig.Project(true, pre);
await rig.DrainProjectionsAsync();
var routedNative = 0;
rig.Nm.NativeAlarmAckRouter = _ => Interlocked.Increment(ref routedNative);
var asked = new ConcurrentQueue<string>();
var concurrent = 0;
var maxConcurrent = 0;
rig.Nm.AlarmCommandAsker = async (cmd, _) =>
{
asked.Enqueue(cmd.Operation);
var now = Interlocked.Increment(ref concurrent);
if (now > Volatile.Read(ref maxConcurrent)) Volatile.Write(ref maxConcurrent, now);
await Task.Delay(50).ConfigureAwait(false);
Interlocked.Decrement(ref concurrent);
return new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation,
cmd.Operation == "Acknowledge" ? AlarmCommandVerdict.NotApplied : AlarmCommandVerdict.Applied, "engine blind");
};
using var session = await rig.ConnectAsync(anonymous: false, ct);
var scripted = ServerEventRig.ConditionNodeId(session, native: false);
var native = ServerEventRig.ConditionNodeId(session, native: true);
ByteString EventIdOf(bool isNative) =>
rig.Nm.TryGetAlarmCondition(isNative ? ServerEventRig.RawAlarmPath : ServerEventRig.ScriptedAlarmId,
isNative ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns)!.EventId!.Value;
CallMethodRequest Ack(NodeId id, ByteString eventId, string text, NodeId? method = null) => new()
{
ObjectId = id, MethodId = method ?? MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(eventId), new Variant(new LocalizedText(text))],
};
var response = await session.CallAsync(null,
[
Ack(scripted, EventIdOf(false), "refused"),
Ack(native, EventIdOf(true), "native"),
Ack(f.ConditionId(session), f.CurrentEventId(), "imported"),
Ack(scripted, EventIdOf(false), "note", MethodIds.ConditionType_AddComment),
new CallMethodRequest { ObjectId = ObjectIds.Server, MethodId = MethodIds.Server_GetMonitoredItems, InputArguments = [new Variant(987654u)] },
], ct);
var codes = response.Results.ToArray()!.Select(r => r.StatusCode.Code).ToArray();
codes.ShouldBe([StatusCodes.BadInvalidState.Code, StatusCodes.Good.Code, StatusCodes.Good.Code, StatusCodes.Good.Code,
StatusCodes.BadSubscriptionIdInvalid.Code]);
asked.ToArray().ShouldBe(["Acknowledge", "AddComment"], "scripted items reach the engine in request order");
Volatile.Read(ref maxConcurrent).ShouldBe(1, "one scripted ask at a time within a Call");
Volatile.Read(ref routedNative).ShouldBe(1);
f.Port.Calls.Single().Method.ShouldBe(DataConditionMethods.Acknowledge);
// The refused Acknowledge was reverted before the AddComment ran; the native one stands.
rig.Nm.TryGetAlarmCondition(ServerEventRig.ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeFalse();
rig.Nm.TryGetAlarmCondition(ServerEventRig.RawAlarmPath, AddressSpaceRealm.Raw)!.AckedState!.Id!.Value.ShouldBeTrue();
rig.Nm.ScriptedCommandsInFlight.ShouldBe(0);
}
// ---------------------------------------------------------------------------------------------------------------------
private static DataConditionMethodResult Applied() => new(DataWriteState.AcceptedUnconfirmed, 0, null);
@@ -20,12 +20,19 @@ public sealed class ScriptedCommandVerdictWireTests
| NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.AlarmShelve
| NodePermissions.MethodCall;
/// <summary>The engine refuses (no complete generation): the client's Acknowledge fails BadInvalidState with its reason.</summary>
/// <summary>
/// The engine refuses (no complete generation): the call fails BadInvalidState, and — review r1 — the node does not keep
/// the change the SDK applied: after the method's event comes exactly one corrective event carrying the pre-call state.
/// </summary>
[Theory]
[InlineData("Acknowledge")]
[InlineData("Confirm")]
[InlineData("AddComment")]
[InlineData("OneShotShelve")]
[InlineData("TimedShelve")]
[InlineData("Unshelve")]
[InlineData("Disable")]
[InlineData("Enable")]
public async Task A_command_the_engine_refuses_returns_BadInvalidState(string method)
{
var ct = TestContext.Current.CancellationToken;
@@ -55,6 +62,17 @@ public sealed class ScriptedCommandVerdictWireTests
refused.StatusCode.ShouldBe(StatusCodes.BadInvalidState);
asked.Count.ShouldBe(1, "the command reached the engine exactly once");
asked.Single().CommandId.ShouldNotBeNullOrEmpty("the local host de-duplicates the broadcast copy by it");
// Sentinel AFTER the revert: a late duplicate would already be queued ahead of it.
await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(item, "base").Count >= 3);
rig.Project(false, ConditionMethodEventTests.PreState(method, native: false) with { Message = "sentinel" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
var baseEvents = events.ConditionEvents(item, "base");
baseEvents.Count.ShouldBe(3, "the base transition, the method's event, and exactly one corrective event");
ConditionMethodEventTests.AssertNewState(method, native: false, baseEvents[1]);
foreach (var field in new[] { RecordedEvents.AckedField, RecordedEvents.ConfirmedField, RecordedEvents.EnabledField,
RecordedEvents.ShelvingField, RecordedEvents.CommentField, RecordedEvents.RetainField })
baseEvents[2][field].ClrValue().ShouldBe(baseEvents[0][field].ClrValue(), $"field {field} is back to its pre-call value");
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
@@ -226,6 +244,58 @@ public sealed class ScriptedCommandVerdictWireTests
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// #937 review r1: past the node-wide in-flight cap a call is refused BadTooManyOperations BEFORE the SDK applies anything
/// (nothing asked, node unchanged); a blank scripted AddComment is refused BadInvalidArgument the same way.
/// </summary>
[Fact]
public async Task Past_the_in_flight_cap_and_for_a_blank_comment_the_call_is_refused_before_any_state_change()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Cap", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
rig.Nm.MaxScriptedCommandsInFlight = 1;
var release = new TaskCompletionSource<AlarmCommandOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
var asked = new ConcurrentQueue<string>();
rig.Nm.AlarmCommandAsker = (cmd, _) => { asked.Enqueue(cmd.Operation); return release.Task; };
rig.Project(false, ConditionMethodEventTests.PreState("OneShotShelve", native: false) with { Message = "base" });
await rig.DrainProjectionsAsync();
using var first = await rig.ConnectAsync(anonymous: false, ct);
using var second = await rig.ConnectAsync(anonymous: false, ct);
var held = ConditionMethodEventTests.CallAsync(first, ConditionNodeId(first, false), "OneShotShelve", null, ct);
for (var i = 0; i < 200 && rig.Nm.ScriptedCommandsInFlight == 0; i++) await Task.Delay(25, ct);
rig.Nm.ScriptedCommandsInFlight.ShouldBe(1);
var eventId = rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.EventId!.Value;
var refused = await second.CallAsync(null, [new CallMethodRequest
{
ObjectId = ConditionNodeId(second, false), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(eventId), new Variant(new LocalizedText("over the cap"))],
}], ct);
refused.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeFalse("nothing was applied");
var blank = await second.CallAsync(null, [new CallMethodRequest
{
ObjectId = ConditionNodeId(second, false), MethodId = MethodIds.ConditionType_AddComment,
InputArguments = [new Variant(eventId), new Variant(new LocalizedText(" "))],
}], ct);
blank.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadInvalidArgument.Code);
asked.ToArray().ShouldBe(["OneShotShelve"], "neither refused call reached the engine");
// Positive control: releasing the held ask frees the slot and the held call completes Good.
release.SetResult(new AlarmCommandOutcome(ScriptedAlarmId, "OneShotShelve", AlarmCommandVerdict.Applied));
await held;
for (var i = 0; i < 200 && rig.Nm.ScriptedCommandsInFlight != 0; i++) await Task.Delay(25, ct);
rig.Nm.ScriptedCommandsInFlight.ShouldBe(0);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>A2b: a remote (gRPC data) condition method on a scripted condition carries the same verdict.</summary>
[Fact]
public async Task A_remote_condition_method_reports_the_engine_refusal_as_dispatched()
@@ -0,0 +1,120 @@
using System.Diagnostics;
using Akka.Actor;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Serilog;
using Shouldly;
using Xunit;
using ZB.MOM.WW.LocalDb;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.ScriptedAlarms;
/// <summary>
/// #937 review r1 (item 4): what an "acknowledge all" costs through the ONE host mailbox with the production LocalDb
/// (SQLite) condition-state store — 300 active alarms, acknowledged one at a time (one Call's requests are settled
/// sequentially) and with the node manager's default in-flight cap of 64 asks outstanding at once. Asserts that no ask
/// waits anywhere near the 5 s verdict bound; the measured numbers are printed for the evidence file.
/// </summary>
public sealed class ScriptedAlarmCommandThroughputTests : RuntimeActorTestBase, IDisposable
{
private const int Alarms = 300;
private const int Cap = 64; // OtOpcUaNodeManager.DefaultMaxScriptedCommandsInFlight
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"otopcua-937-throughput-{Guid.NewGuid():N}.db");
private readonly ServiceProvider _provider;
private readonly ITestOutputHelper _output;
public ScriptedAlarmCommandThroughputTests(ITestOutputHelper output)
{
_output = output;
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { ["LocalDb:Path"] = _dbPath }).Build();
_provider = new ServiceCollection()
.AddZbLocalDb(configuration, db =>
{
using (var connection = db.CreateConnection()) AlarmConditionStateSchema.Apply(connection);
db.RegisterReplicated(AlarmConditionStateSchema.StateTable);
db.RegisterReplicated(AlarmConditionStateSchema.CommentsTable);
})
.BuildServiceProvider();
}
void IDisposable.Dispose()
{
_provider.Dispose();
SqliteConnection.ClearAllPools();
foreach (var path in new[] { _dbPath, $"{_dbPath}-wal", $"{_dbPath}-shm" })
try { if (File.Exists(path)) File.Delete(path); } catch { /* best effort */ }
}
private static EquipmentScriptedAlarmPlan Plan(int i) =>
new(ScriptedAlarmId: $"alm-{i:D3}", EquipmentId: "Plant/Line1/M", Name: $"alm-{i:D3}", AlarmType: "AlarmCondition",
Severity: 800, MessageTemplate: "m", PredicateScriptId: "always", PredicateSource: "return true;",
DependencyRefs: [], HistorizeToAveva: false, Retain: true, Enabled: true);
[Fact]
public async Task Three_hundred_acks_through_one_host_stay_far_inside_the_verdict_bound()
{
var ct = TestContext.Current.CancellationToken;
var store = new LocalDbAlarmConditionStateStore(_provider.GetRequiredService<ILocalDb>(), NullLogger<LocalDbAlarmConditionStateStore>.Instance);
var upstream = new DependencyMuxTagUpstreamSource();
var logger = new LoggerConfiguration().CreateLogger();
var engine = new ScriptedAlarmEngine(upstream, store, new ScriptLoggerFactory(logger), logger);
var readiness = new ScriptedAlarmCommandReadinessView();
var mux = CreateTestProbe();
var host = Sys.ActorOf(ScriptedAlarmHostActor.Props(CreateTestProbe().Ref, mux.Ref, () => (upstream, engine), readiness: readiness));
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms(Enumerable.Range(0, Alarms).Select(Plan).ToList()));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(TimeSpan.FromSeconds(60), cancellationToken: ct);
async Task<TimeSpan> Ack(int i, string op)
{
var started = Stopwatch.GetTimestamp();
var outcome = await host.Ask<AlarmCommandOutcome>(new ScriptedAlarmHostActor.ExecuteAlarmCommand(
new AlarmCommand($"alm-{i:D3}", op, "alice", op == "AddComment" ? "c" : null, null, Guid.NewGuid().ToString("N"))),
TimeSpan.FromSeconds(30), ct);
outcome.Verdict.ShouldBe(AlarmCommandVerdict.Applied);
return Stopwatch.GetElapsedTime(started);
}
// Sequential: one Call carrying 300 Acknowledge requests (each settled before the next).
var total = Stopwatch.StartNew();
var sequential = new List<TimeSpan>();
for (var i = 0; i < Alarms; i++) sequential.Add(await Ack(i, "Acknowledge"));
var sequentialTotal = total.Elapsed;
engine.GetState("alm-000")!.Active.ShouldBe(AlarmActiveState.Active, "precondition: every alarm is active");
engine.GetState("alm-299")!.Acked.ShouldBe(AlarmAckedState.Acknowledged, "each ack changed (and saved) its condition");
(await store.LoadAsync("alm-150", ct))!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
// Concurrent: many sessions, at most the cap outstanding at once (AddComment always writes a row).
total.Restart();
var gate = new SemaphoreSlim(Cap);
var concurrent = await Task.WhenAll(Enumerable.Range(0, Alarms).Select(async i =>
{
await gate.WaitAsync(ct);
try { return await Ack(i, "AddComment"); }
finally { gate.Release(); }
}));
var concurrentTotal = total.Elapsed;
static string Stats(IEnumerable<TimeSpan> s)
{
var ms = s.Select(x => x.TotalMilliseconds).Order().ToArray();
return $"p50 {ms[ms.Length / 2]:0.0} ms, p99 {ms[(int)(ms.Length * 0.99)]:0.0} ms, max {ms[^1]:0.0} ms";
}
_output.WriteLine($"sequential 300 acks: total {sequentialTotal.TotalMilliseconds:0} ms; per ask {Stats(sequential)}");
_output.WriteLine($"cap-{Cap} concurrent 300 comments: total {concurrentTotal.TotalMilliseconds:0} ms; per ask {Stats(concurrent)}");
// Far inside the 5 s verdict bound even with a full cap queued behind the one mailbox.
concurrent.Max().ShouldBeLessThan(TimeSpan.FromSeconds(2.5));
sequential.Max().ShouldBeLessThan(TimeSpan.FromSeconds(2.5));
}
}