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
+13 -1
View File
@@ -87,4 +87,16 @@ read the store — a new occurrence. Keep (review round 1): `ApplyAsync` looks t
it saved a racing load's `Fresh` entry over the carried Active condition); commands throw it saved a racing load's `Fresh` entry over the carried Active condition); commands throw
`ScriptedAlarmCommandRejectedException` while a failed load left no trusted generation; a value-equal result (load, `ScriptedAlarmCommandRejectedException` while a failed load left no trusted generation; a value-equal result (load,
re-evaluation or command) is not saved — the LocalDb row is replicated last-writer-wins, so re-saving pushed stale state. re-evaluation or command) is not saved — the LocalDb row is replicated last-writer-wins, so re-saving pushed stale state.
See `docs/ScriptedAlarms.md` §"A redeploy is a restatement". See `docs/ScriptedAlarms.md` §"A redeploy is a restatement". Accepted trade-off: one transient failed deploy = one duplicate
activation per still-true alarm on the next good deploy.
**A scripted Part 9 method returns the engine's verdict (#937).** (1) `ScriptedAlarmCommandPreflight` (lock-free read of
`ScriptedAlarmCommandReadinessView`, the host's latest load outcome) refuses `BadInvalidState` before the SDK applies anything
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
`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).
+2 -1
View File
@@ -553,7 +553,8 @@ It also routes once to the driver (`AlarmCommand` unchanged) and keeps the #760
| Answer on the consumer | Meaning | Sent to the origin? | | Answer on the consumer | Meaning | Sent to the origin? |
|---|---|---| |---|---|---|
| `Good` | Scripted: the origin applied it (`DriverConfirmedSuccess`). Native: the origin accepted it and routed it to the driver (`AcceptedUnconfirmed`). The state change arrives on the stream. | yes, applied/accepted | | `Good` | Scripted: the origin's scripted-alarm engine applied it (`DriverConfirmedSuccess` — since #937 the origin waits for the engine's verdict). Native: the origin accepted it and routed it to the driver (`AcceptedUnconfirmed`). The state change arrives on the stream. | yes, applied/accepted |
| `BadInvalidState` (scripted, #937) | the origin's scripted-alarm engine holds no complete generation (its last load failed) — refused before dispatch, or refused by the engine after dispatch (`DriverConfirmedFailure`) | refused / yes, not applied |
| `BadNodeIdUnknown` | not an imported condition this node holds | no | | `BadNodeIdUnknown` | not an imported condition this node holds | no |
| `BadNotSupported` | Shelve / Unshelve / Enable / Disable / unknown method; **native Confirm**; method not in the origin's `supported_methods` (e.g. Galaxy without the opt-in) | no | | `BadNotSupported` | Shelve / Unshelve / Enable / Disable / unknown method; **native Confirm**; method not in the origin's `supported_methods` (e.g. Galaxy without the opt-in) | no |
| `BadUserAccessDenied` | the local caller fails the mapping method gate, or the deployed connection lacks the bit | no | | `BadUserAccessDenied` | the local caller fails the mapping method gate, or the deployed connection lacks the bit | no |
+46 -3
View File
@@ -186,9 +186,15 @@ after a full rebuild, carrying the unchanged `LastTransitionUtc`. Decisions:
occurrence (`Activated`, `Unacknowledged`). Restating the pre-failure snapshot instead would hide an alarm that cleared and occurrence (`Activated`, `Unacknowledged`). Restating the pre-failure snapshot instead would hide an alarm that cleared and
re-fired inside the window. While blind, an operator command is **rejected** with `ScriptedAlarmCommandRejectedException` re-fired inside the window. While blind, an operator command is **rejected** with `ScriptedAlarmCommandRejectedException`
(nothing is persisted — applying it to the half-built Fresh entry would overwrite the real row), and queued re-evaluations (nothing is persisted — applying it to the half-built Fresh entry would overwrite the real row), and queued re-evaluations
and shelving checks are dropped. The command topic is fire-and-forget (the OPC UA method / AdminUI call already returned and shelving checks are dropped. **Since #937 an OPC UA Part 9 method (and a remote gRPC-data condition method) on a
Good), so the rejection's only record is the host's Warning `… NOT applied — …`; the next good load re-asserts the node scripted condition reports this**: while the last load failed the node manager refuses the call `BadInvalidState` before the
from the store, undoing whatever the method showed. 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).
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
alarm whose predicate is still true is a new occurrence — **one transient failed deploy costs one duplicate activation
(`Activated` + `Unacknowledged`, one `alerts` row) per still-true alarm** on the next good deploy.
- **Concurrency.** The capture happens under `_evalGate`, so it includes every evaluation and operator command that completed - **Concurrency.** The capture happens under `_evalGate`, so it includes every evaluation and operator command that completed
before the load. An operator command looks its alarm up only once it holds the gate (review S1 — it used to look up first, before the load. An operator command looks its alarm up only once it holds the gate (review S1 — it used to look up first,
so a command racing a load could save the load's interim `Fresh` entry over the carried Active condition), so a command so a command racing a load could save the load's interim `Fresh` entry over the carried Active condition), so a command
@@ -411,6 +417,43 @@ On allow, the handler publishes a `Commons.OpcUa.AlarmCommand` (containing comma
- **Scripted conditions** — all eight Part 9 operations (including Enable/Disable) route through `AlarmCommandRouter` onto the `alarm-commands` topic, which `ScriptedAlarmHostActor` dispatches to the engine (`EnableAsync` / `DisableAsync` / `AcknowledgeAsync` / …). On enable, `ActiveState` is re-derived from the next predicate evaluation. - **Scripted conditions** — all eight Part 9 operations (including Enable/Disable) route through `AlarmCommandRouter` onto the `alarm-commands` topic, which `ScriptedAlarmHostActor` dispatches to the engine (`EnableAsync` / `DisableAsync` / `AcknowledgeAsync` / …). On enable, `ActiveState` is re-derived from the next predicate evaluation.
- **Native (driver-fed) conditions** — `OnAcknowledge` branches to `NativeAlarmAckRouter` and routes the ack to the owning driver rather than the scripted engine (see §[Native-alarm OPC UA operator operations](#native-alarm-opc-ua-operator-operations) above). `OnEnableDisable`, `OnConfirm` and `OnShelve` return `BadNotSupported` immediately — a native condition supports Acknowledge and AddComment only (no engine-side surface, no upstream path, and the driver projection owns its Confirmed/Shelving; Gitea #587 review). - **Native (driver-fed) conditions** — `OnAcknowledge` branches to `NativeAlarmAckRouter` and routes the ack to the owning driver rather than the scripted engine (see §[Native-alarm OPC UA operator operations](#native-alarm-opc-ua-operator-operations) above). `OnEnableDisable`, `OnConfirm` and `OnShelve` return `BadNotSupported` immediately — a native condition supports Acknowledge and AddComment only (no engine-side surface, no upstream path, and the driver projection owns its Confirmed/Shelving; Gitea #587 review).
### Operator command verdicts (#937)
A scripted condition's Part 9 method no longer returns Good merely because the command was published. Two layers, neither
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.
| 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` |
| 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
codes (bad EventId, already acked/confirmed/shelved, disabled, shelving time out of range) do not cover "the state owner
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
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`.
**Not covered:** the AdminUI `/alerts` buttons are still fire-and-forget across the central→node transport (they report
"Ack sent", not "applied").
`OnTimedUnshelve` (the SDK's internal auto-unshelve timer, armed for the real remaining time since Gitea #597) is a **no-op**: the engine owns timed-shelve expiry via `ApplyShelvingCheck` (`system / AutoUnshelve`), and routing an `Unshelve` from the timer pre-empted that on every expiry as an operator-style unshelve from both pair nodes (review R1 M2). `OnTimedUnshelve` (the SDK's internal auto-unshelve timer, armed for the real remaining time since Gitea #597) is a **no-op**: the engine owns timed-shelve expiry via `ApplyShelvingCheck` (`system / AutoUnshelve`), and routing an `Unshelve` from the timer pre-empted that on every expiry as an operator-style unshelve from both pair nodes (review R1 M2).
### Delta-gate de-duplication ### Delta-gate de-duplication
@@ -30,8 +30,8 @@ from pathlib import Path
import rig import rig
import scenarios import scenarios
SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08") SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "F937")
TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720} TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720, "F937": 900}
REFRESH_REQUIRED = "RefreshRequiredEventType" REFRESH_REQUIRED = "RefreshRequiredEventType"
_LOG_TIME = re.compile(r"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?)") _LOG_TIME = re.compile(r"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?)")
NO_ACK = int(0b111111111111) & ~(1 << 8) # NodePermissions.Admin (4095) without AlarmAcknowledge (1 << 8) NO_ACK = int(0b111111111111) & ~(1 << 8) # NodePermissions.Admin (4095) without AlarmAcknowledge (1 << 8)
@@ -510,6 +510,65 @@ class ConditionScenarios:
return {"code": code, "output": text[-300:], "good": code == 0 and ("successful" in text or "Comment added" in text), return {"code": code, "output": text[-300:], "good": code == 0 and ("successful" in text or "Comment added" in text),
"event_id_unknown": "BadEventIdUnknown" in text} "event_id_unknown": "BadEventIdUnknown" in text}
def shelve(self, node, condition, kind, tag):
code, text = self.cli(node, "shelve", "-n", condition, "-k", kind, tag=tag)
return {"code": code, "output": text[-300:], "good": code == 0 and "successful" in text,
"invalid_state": "BadInvalidState" in text or "80AF0000" in text.upper()}
# ---- #937 -------------------------------------------------------------------------------------------------------
def scenario_F937(self):
"""#937: after a deploy whose scripted-alarm load FAILS, a Part 9 method on the scripted condition returns
BadInvalidState (it used to return Good and be silently dropped) — locally on the origin and through the consumer's
remote condition method; after a good redeploy the same calls succeed (positive control)."""
source, consumer = self.r.primary("source"), self.r.primary("consumer")
name = self.fixture["conditions"]["scripted"]["condition"]
good = "return Convert.ToInt32(ctx.GetTag(\"modbus/plc/scalar\").Value) > 100;"
origin = self.watch(source, "origin")
imported = self.watch(consumer, "consumer")
time.sleep(6)
self.raise_scripted()
active = wait_for(lambda: self.latest(origin, name, lambda b: b.get("State") == "Active, Unacknowledged"), 120)
remote = wait_for(lambda: self.latest(imported, name, lambda b: b.get("State") == "Active, Unacknowledged"), 120)
if not self.check("origin_and_consumer_see_active_unacked", active and remote):
return
condition = active["ConditionNodeId"]
self.report["condition"] = condition
broken_at = self.utc(-2)
try:
self.r.mutate(scripted_predicate="return unknownIdentifier937;")
failed = wait_for(lambda: self.log_lines(source, broken_at, "engine LoadAsync failed"), 120)
self.check("origin_engine_load_failed", failed)
# The failed load changes no node: the origin still shows the condition Active+Unacked.
latest = self.latest(origin, name) or active
ack = self.ack(source, condition, latest["EventId"], "ack-blind")
self.report["ack_blind"] = ack
# Bad either way; BadInvalidState when the node still holds the pre-deploy occurrence (a deploy that rebuilt the
# address space re-materialised it acknowledged, and the SDK refuses a re-ack before the handler runs).
self.check("origin_ack_not_good", not ack["good"])
self.report["origin_ack_invalid_state"] = "BadInvalidState" in ack["output"]
shelved = self.shelve(source, condition, "OneShot", "shelve-blind")
self.report["shelve_blind"] = shelved
self.check("origin_shelve_refused_BadInvalidState", not shelved["good"] and shelved["invalid_state"])
remote_latest = self.latest(imported, name) or remote
remote_ack = self.ack(consumer, remote_latest["ConditionNodeId"], remote_latest["EventId"], "remote-ack-blind")
self.report["remote_ack_blind"] = remote_ack
self.check("consumer_remote_ack_not_good", not remote_ack["good"])
self.report["remote_ack_invalid_state"] = "BadInvalidState" in remote_ack["output"]
finally:
restored_at = self.utc(-2)
self.r.mutate(scripted_predicate=good)
loaded = wait_for(lambda: self.log_lines(source, restored_at, "ScriptedAlarmEngine loaded"), 120)
self.check("origin_engine_reloaded", loaded)
# Positive control: the first good load after a failed one is a new occurrence (documented); the ack now succeeds.
fresh = wait_for(lambda: self.latest(origin, name, lambda b: b.get("State") == "Active, Unacknowledged"
and b.get("EventId") != active["EventId"]), 120) or self.latest(origin, name)
ack = self.ack(source, condition, fresh["EventId"], "ack-restored")
self.report["ack_restored"] = ack
self.check("origin_ack_good_after_good_deploy", ack["good"])
self.raise_scripted(0)
time.sleep(4)
# ---- part 2 scenarios ------------------------------------------------------------------------------------------- # ---- part 2 scenarios -------------------------------------------------------------------------------------------
def scenario_A03(self): def scenario_A03(self):
"""Origin failover mid-stream with standing active alarms. Phase 1: a consumer stream reset against the SAME origin """Origin failover mid-stream with standing active alarms. Phase 1: a consumer stream reset against the SAME origin
+11 -1
View File
@@ -175,7 +175,7 @@ try
var root = mutation.RootElement; var root = mutation.RootElement;
string[] allowedFields = ["connection_id", "target_mode", "target_node_id", "consistency", "consumer_node_ids", "connection_enabled", "connection_allowed_operations", string[] allowedFields = ["connection_id", "target_mode", "target_node_id", "consistency", "consumer_node_ids", "connection_enabled", "connection_allowed_operations",
"mapping_enabled", "write_through", "allowed_operations", "export_id", "export_enabled", "export_allowed_operations", "source_redundancy_mode", "consumer_redundancy_mode", "mapping_enabled", "write_through", "allowed_operations", "export_id", "export_enabled", "export_allowed_operations", "source_redundancy_mode", "consumer_redundancy_mode",
"control_redundancy_mode", "rename_tag", "upsert_tag", "upsert_reference", "remove_tag_id", "disable_feature", "key_action", "key_expiry_seconds", "upsert_connection", "upsert_mapping", "upsert_export", "remove_mapping_id", "maintenance_mode", "acl_permissions", "bump_mapping_revision"]; "control_redundancy_mode", "rename_tag", "upsert_tag", "upsert_reference", "remove_tag_id", "disable_feature", "key_action", "key_expiry_seconds", "upsert_connection", "upsert_mapping", "upsert_export", "remove_mapping_id", "maintenance_mode", "acl_permissions", "bump_mapping_revision", "scripted_predicate"];
if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Any(property => !allowedFields.Contains(property.Name, StringComparer.Ordinal))) if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Any(property => !allowedFields.Contains(property.Name, StringComparer.Ordinal)))
throw new InvalidOperationException("unknown fixture mutation field"); throw new InvalidOperationException("unknown fixture mutation field");
await using var db = await factory.CreateDbContextAsync(); await using var db = await factory.CreateDbContextAsync();
@@ -197,6 +197,16 @@ try
var maintenanceNode = await db.ClusterNodes.SingleAsync(x => x.NodeId == maintenanceNodeId); var maintenanceNode = await db.ClusterNodes.SingleAsync(x => x.NodeId == maintenanceNodeId);
maintenanceNode.MaintenanceMode = maintenance.GetProperty("enabled").GetBoolean(); maintenanceNode.MaintenanceMode = maintenance.GetProperty("enabled").GetBoolean();
} }
if (root.TryGetProperty("scripted_predicate", out var scriptedPredicate))
{
// #937 live leg: replace the conditions profile's ScalarHigh predicate. Compile is not deploy-gated, so an
// uncompilable source deploys and fails the SOURCE engine's load (the engine then refuses operator commands).
var source = scriptedPredicate.GetString() is { Length: > 0 and <= 4096 } text ? text
: throw new InvalidOperationException("scripted predicate source required");
var script = await db.Scripts.SingleAsync(x => x.ScriptId == "source-scalar-high");
script.SourceCode = source;
script.SourceHash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(source)));
}
if (root.TryGetProperty("upsert_connection", out var newConnection)) if (root.TryGetProperty("upsert_connection", out var newConnection))
{ {
var candidate = JsonSerializer.Deserialize<DataConnection>(newConnection.GetRawText()) ?? throw new InvalidOperationException(); var candidate = JsonSerializer.Deserialize<DataConnection>(newConnection.GetRawText()) ?? throw new InvalidOperationException();
@@ -46,9 +46,51 @@ public static class AlarmCommandsTopic
/// (<c>DateTime.UtcNow + shelvingTime</c>, where the OPC UA <c>Duration</c> <c>shelvingTime</c> is /// (<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. /// in <b>milliseconds</b>); <c>null</c> for every other operation.
/// </param> /// </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( public sealed record AlarmCommand(
string AlarmId, string AlarmId,
string Operation, string Operation,
string User, string User,
string? Comment, 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 HistorianUpdaterHolder _historianUpdater;
private readonly IHistoryUpdateRoleView? _historyUpdateRoleView; private readonly IHistoryUpdateRoleView? _historyUpdateRoleView;
private readonly NativeAlarmAckPreflightView? _ackPreflightView; private readonly NativeAlarmAckPreflightView? _ackPreflightView;
private readonly ScriptedAlarmCommandReadinessView? _scriptedAlarmReadiness;
private readonly OpcUaEndpointState _endpointState; private readonly OpcUaEndpointState _endpointState;
private readonly bool _rethrowStartFailure; private readonly bool _rethrowStartFailure;
private readonly DriverWriteBounds _writeBounds; private readonly DriverWriteBounds _writeBounds;
@@ -172,9 +173,11 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
IFederatedProjectionCatalog? projectedCatalog = null, IFederatedProjectionCatalog? projectedCatalog = null,
IProjectedHistoryAccess? projectedHistoryAccess = null, IProjectedHistoryAccess? projectedHistoryAccess = null,
IConditionStateSink? conditionStateSink = null, IConditionStateSink? conditionStateSink = null,
IProjectedConditionAccess? projectedConditionAccess = null) IProjectedConditionAccess? projectedConditionAccess = null,
ScriptedAlarmCommandReadinessView? scriptedAlarmReadiness = null)
{ {
_projectedConditionAccess = projectedConditionAccess; _projectedConditionAccess = projectedConditionAccess;
_scriptedAlarmReadiness = scriptedAlarmReadiness;
_projectedHistoryAccess = projectedHistoryAccess; _projectedHistoryAccess = projectedHistoryAccess;
_conditionStateSink = conditionStateSink; _conditionStateSink = conditionStateSink;
_dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get<DataConnectionOptions>() ?? new(); _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, // 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 // 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; // 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>()); _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> /// <summary>
/// Stops the OPC UA server asynchronously: detaches every sink, then STOPS the SDK so the port closes. /// Stops the OPC UA server asynchronously: detaches every sink, then STOPS the SDK so the port closes.
/// </summary> /// </summary>
@@ -635,6 +697,11 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
_server?.SetNativeAlarmAckRouter(null); _server?.SetNativeAlarmAckRouter(null);
_server?.SetNativeAlarmAckPrimaryGate(null); _server?.SetNativeAlarmAckPrimaryGate(null);
_server?.SetNativeAlarmAckPreflight(null); _server?.SetNativeAlarmAckPreflight(null);
if (_server?.NodeManager is { } stoppingNodeManager)
{
stoppingNodeManager.AlarmCommandAsker = null;
stoppingNodeManager.ScriptedAlarmCommandPreflight = null;
}
_server?.SetHistoryUpdatePrimaryGate(null); _server?.SetHistoryUpdatePrimaryGate(null);
// Restore the Null historian so a late HistoryRead doesn't hit a disposed read client. // Restore the Null historian so a late HistoryRead doesn't hit a disposed read client.
_server?.SetHistorianDataSource(null); _server?.SetHistorianDataSource(null);
@@ -115,7 +115,7 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
(claimed ??= []).Add(i); (claimed ??= []).Add(i);
} }
base.Call(context, methodsToCall, results, errors); await CallLocalAsync(context, methodsToCall, results, errors).ConfigureAwait(false);
if (claimed is null) return; if (claimed is null) return;
var caller = context.UserIdentity as RoleCarryingUserIdentity; 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; 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> /// <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, private async Task<ServiceResult> CallImportedGuardedAsync(RoleCarryingUserIdentity? caller, CallMethodRequest request, DateTime deadline,
CancellationToken cancellationToken) CancellationToken cancellationToken)
@@ -20,6 +20,15 @@ public interface IOriginConditionSource
/// <param name="call">The call.</param> /// <param name="call">The call.</param>
/// <returns>The verdict.</returns> /// <returns>The verdict.</returns>
OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call); 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> /// <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) => public OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call) =>
deferred.GetCapability<IOriginConditionSource>() is { } inner ? inner.TryExecuteConditionMethod(call) deferred.GetCapability<IOriginConditionSource>() is { } inner ? inner.TryExecuteConditionMethod(call)
: throw new OriginConditionSourceUnavailableException(); : 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> /// <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="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="StatusCode">The OPC UA status (Good when applied).</param>
/// <param name="Diagnostic">A refusal's reason text, when the gate gave one.</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 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. // (nothing routed, nothing applied, no event). Unset/None keep today's acceptance.
if (_standby.RefusesMutations) return WarmStandbyState.StandbyRefusal($"call {operation}"); 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( var cmd = new AlarmCommand(
AlarmId: condition.NodeId.IdentifierAsString, AlarmId: condition.NodeId.IdentifierAsString,
Operation: operation, Operation: operation,
@@ -3217,6 +3222,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
Comment: comment?.Text, Comment: comment?.Text,
UnshelveAtUtc: unshelveAt); 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. // Non-blocking by contract (host wires a fire-and-forget mediator.Tell); safe to call under Lock.
AlarmCommandRouter?.Invoke(cmd); AlarmCommandRouter?.Invoke(cmd);
@@ -40,6 +40,10 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
OriginConditionMethodOutcome IOriginConditionSource.TryExecuteConditionMethod(OriginConditionMethodCall call) => OriginConditionMethodOutcome IOriginConditionSource.TryExecuteConditionMethod(OriginConditionMethodCall call) =>
_nodeManager.TryExecuteConditionMethod(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> /// <summary>Initializes a new instance of the SdkAddressSpaceSink class.</summary>
/// <param name="nodeManager">The OPC UA node manager.</param> /// <param name="nodeManager">The OPC UA node manager.</param>
public SdkAddressSpaceSink(OtOpcUaNodeManager nodeManager) public SdkAddressSpaceSink(OtOpcUaNodeManager nodeManager)
@@ -212,7 +212,7 @@ public sealed partial class LocalDataServices
DataWriteOutcome? outcome = null; DataWriteOutcome? outcome = null;
try try
{ {
outcome = Dispatch(); outcome = await DispatchAsync().ConfigureAwait(false);
return (FromOutcome(outcome), false); return (FromOutcome(outcome), false);
} }
finally finally
@@ -230,15 +230,16 @@ public sealed partial class LocalDataServices
registry.ReleaseUndispatched(context.PrincipalId, request.OperationId, owner); registry.ReleaseUndispatched(context.PrincipalId, request.OperationId, owner);
} }
DataWriteOutcome Dispatch() async Task<DataWriteOutcome> DispatchAsync()
{ {
OriginConditionMethodOutcome verdict; OriginConditionMethodOutcome verdict;
try 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, DataConditionMethodSets.Part9Name(request.Method), request.Comment,
new ConditionActivationMarker(request.ExpectedActivation.Incarnation, request.ExpectedActivation.Sequence), new ConditionActivationMarker(request.ExpectedActivation.Incarnation, request.ExpectedActivation.Sequence),
context.PrincipalId, context.ApiKeyId)); context.PrincipalId, context.ApiKeyId), request.RemainingBudget).ConfigureAwait(false);
} }
catch (OriginConditionSourceUnavailableException ex) catch (OriginConditionSourceUnavailableException ex)
{ {
@@ -267,6 +268,15 @@ public sealed partial class LocalDataServices
: new(DataWriteState.AcceptedUnconfirmed, verdict.StatusCode, : new(DataWriteState.AcceptedUnconfirmed, verdict.StatusCode,
"AcceptedUnconfirmed: the comment was applied at the origin (not sent to the driver); it arrives on the condition stream."); "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); else decided = new(DataWriteState.RejectedBeforeDispatch, verdict.StatusCode, verdict.Diagnostic);
owner.Complete(decided); owner.Complete(decided);
return 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> /// <summary>Where the synchronous native-ack pre-check snapshot is published (lmxopcua#760); null ⇒ none.</summary>
private readonly NativeAlarmAckPreflightView? _ackPreflightView; 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 /// <summary>The write bounds every child is spawned with and this host's write Ask is derived from
/// (lmxopcua#777).</summary> /// (lmxopcua#777).</summary>
private readonly DriverWriteBounds _writeBounds; private readonly DriverWriteBounds _writeBounds;
@@ -875,7 +878,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
SubscriptionAcquisitionCapacity? acquisitionCapacity = null, SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
DataConnectionDeploymentRuntime? dataConnections = null, DataConnectionDeploymentRuntime? dataConnections = null,
ActorProjectedValuePublisher? projectedPublisher = 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 // 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 // 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 // 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, sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView,
scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout, scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout,
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity, dataConnections, projectedPublisher, enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity, dataConnections, projectedPublisher,
conditionSignals)); conditionSignals, scriptedAlarmReadiness));
/// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary> /// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary>
/// <param name="dbFactory">Database context factory for configuration database access.</param> /// <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, SubscriptionAcquisitionCapacity? acquisitionCapacity = null,
DataConnectionDeploymentRuntime? dataConnections = null, DataConnectionDeploymentRuntime? dataConnections = null,
ActorProjectedValuePublisher? projectedPublisher = null, ActorProjectedValuePublisher? projectedPublisher = null,
ConditionSignalOptions? conditionSignals = null) ConditionSignalOptions? conditionSignals = null,
ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmCommandReadinessView? scriptedAlarmReadiness = null)
{ {
_conditionSignals = conditionSignals ?? new ConditionSignalOptions(); _conditionSignals = conditionSignals ?? new ConditionSignalOptions();
_scriptedAlarmReadiness = scriptedAlarmReadiness;
_projectedPublisher = projectedPublisher; _projectedPublisher = projectedPublisher;
_dataWriteRuntime = dataWriteRuntime; _dataWriteRuntime = dataWriteRuntime;
_dataConnections = dataConnections; _dataConnections = dataConnections;
@@ -1399,7 +1405,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
var upstream = new DependencyMuxTagUpstreamSource(); var upstream = new DependencyMuxTagUpstreamSource();
return (upstream, CreateScriptedAlarmEngine(upstream, store, scriptLogger, scripting, alarmRunner)); return (upstream, CreateScriptedAlarmEngine(upstream, store, scriptLogger, scripting, alarmRunner));
}, },
_localNode, telemetryHub: _telemetryHub), _localNode, telemetryHub: _telemetryHub, readiness: _scriptedAlarmReadiness),
"scripted-alarm-host"); "scripted-alarm-host");
} }
@@ -1781,6 +1787,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
Receive<RouteNodeWrite>(HandleRouteNodeWrite); Receive<RouteNodeWrite>(HandleRouteNodeWrite);
Receive<RouteRichWrite>(HandleRouteRichWrite); Receive<RouteRichWrite>(HandleRouteRichWrite);
Receive<RouteNativeAlarmAck>(HandleRouteNativeAlarmAck); Receive<RouteNativeAlarmAck>(HandleRouteNativeAlarmAck);
Receive<ScriptedAlarmHostActor.ExecuteAlarmCommand>(HandleExecuteAlarmCommand);
Receive<DriverInstanceActor.AlarmAckFailed>(HandleAlarmAckFailed); Receive<DriverInstanceActor.AlarmAckFailed>(HandleAlarmAckFailed);
Receive<RedundancyStateChanged>(OnRedundancyStateChanged); Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
Receive<Akka.Cluster.ClusterEvent.IMemberEvent>(OnDriverMembershipChanged); Receive<Akka.Cluster.ClusterEvent.IMemberEvent>(OnDriverMembershipChanged);
@@ -1862,6 +1869,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
Receive<RouteNodeWrite>(HandleRouteNodeWrite); Receive<RouteNodeWrite>(HandleRouteNodeWrite);
Receive<RouteRichWrite>(HandleRouteRichWrite); Receive<RouteRichWrite>(HandleRouteRichWrite);
Receive<RouteNativeAlarmAck>(HandleRouteNativeAlarmAck); Receive<RouteNativeAlarmAck>(HandleRouteNativeAlarmAck);
Receive<ScriptedAlarmHostActor.ExecuteAlarmCommand>(HandleExecuteAlarmCommand);
Receive<DriverInstanceActor.AlarmAckFailed>(HandleAlarmAckFailed); Receive<DriverInstanceActor.AlarmAckFailed>(HandleAlarmAckFailed);
Receive<RedundancyStateChanged>(OnRedundancyStateChanged); Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
Receive<Akka.Cluster.ClusterEvent.IMemberEvent>(OnDriverMembershipChanged); 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> /// <see cref="DriverInstanceActor.RouteAlarmAck"/> carrying the wire-ref FullName + principal.</item>
/// </list> /// </list>
/// </summary> /// </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) private void HandleRouteNativeAlarmAck(RouteNativeAlarmAck msg)
{ {
// PRIMARY GATE FIRST (archreview 03/S4) — only the Primary pushes the ack upstream. Same policy as // 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 // 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 // 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. // top of this method); one that raced that refusal is dropped here with a log.
Receive<ScriptedAlarmHostActor.ExecuteAlarmCommand>(HandleExecuteAlarmCommand);
Receive<RouteNativeAlarmAck>(msg => Receive<RouteNativeAlarmAck>(msg =>
_log.Debug("DriverHost {Node}: dropping native-alarm ack for {Node2} while Stale (config DB unreachable)", _log.Debug("DriverHost {Node}: dropping native-alarm ack for {Node2} while Stale (config DB unreachable)",
_localNode, msg.ConditionNodeId)); _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> /// <param name="Plans">The desired Equipment-namespace scripted-alarm plans.</param>
public sealed record ApplyScriptedAlarms(IReadOnlyList<EquipmentScriptedAlarmPlan> Plans); 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> /// <summary>
/// Told to the parent from <see cref="PostRestart"/>. A supervision restart is otherwise invisible to the /// 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 /// 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> /// <see cref="OnAlarmsLoaded"/> so out-of-order loads never register superseded dep refs.</summary>
private int _loadGeneration; 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 /// <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> /// actor thread) and reused for every emission instead of re-resolving it per-publish.</summary>
private IActorRef _mediator = null!; private IActorRef _mediator = null!;
@@ -230,8 +253,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
NodeId? localNode = null, NodeId? localNode = null,
Func<int>? driverMemberCountProvider = null, Func<int>? driverMemberCountProvider = null,
ITelemetryLocalHub? telemetryHub = null, ITelemetryLocalHub? telemetryHub = null,
TimeSpan? commandTimeout = null) => TimeSpan? commandTimeout = null,
Akka.Actor.Props.Create(() => new ScriptedAlarmHostActor(publishActor, mux, engineFactory, localNode, driverMemberCountProvider, telemetryHub, commandTimeout)); 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> /// <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> /// <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="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="telemetryHub">Optional node-local live-telemetry hub.</param>
/// <param name="commandTimeout">Bound on one inbound alarm command's engine op.</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( public ScriptedAlarmHostActor(
IActorRef publishActor, IActorRef publishActor,
IActorRef? mux, IActorRef? mux,
@@ -248,8 +274,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
NodeId? localNode = null, NodeId? localNode = null,
Func<int>? driverMemberCountProvider = null, Func<int>? driverMemberCountProvider = null,
ITelemetryLocalHub? telemetryHub = null, ITelemetryLocalHub? telemetryHub = null,
TimeSpan? commandTimeout = null) TimeSpan? commandTimeout = null,
: this(publishActor, mux, Build(engineFactory), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: true, commandTimeout) 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, NodeId? localNode = null,
Func<int>? driverMemberCountProvider = null, Func<int>? driverMemberCountProvider = null,
ITelemetryLocalHub? telemetryHub = 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, Func<int>? driverMemberCountProvider,
ITelemetryLocalHub? telemetryHub, ITelemetryLocalHub? telemetryHub,
bool ownsEngine, 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(publishActor);
ArgumentNullException.ThrowIfNull(pair.Upstream); ArgumentNullException.ThrowIfNull(pair.Upstream);
ArgumentNullException.ThrowIfNull(pair.Engine); 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 // 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. // (ordered, awaited on the actor thread) and routes any escaped fault through supervision.
ReceiveAsync<AlarmCommand>(OnAlarmCommand); 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 // 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. // failure doesn't hit the dead-letter log.
Receive<Status.Failure>(OnLoadFailed); 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 // 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). // not loaded (no predicate, no upstream subscription, no events).
var enabled = msg.Plans.Where(p => p.Enabled).ToList(); 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(); var defs = enabled.Select(ToDefinition).ToList();
@@ -401,10 +435,19 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
} }
private void OnLoadFailed(Status.Failure msg) 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) 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 // 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 // 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. // 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> /// <param name="cmd">The inbound alarm command.</param>
private async Task OnAlarmCommand(AlarmCommand cmd) 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 // 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. // 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 if (!Owns(cmd.AlarmId))
// surface a spurious ArgumentException from the engine below — the outer catch absorbs it (benign).
if (!_engine.LoadedAlarmIds.Contains(cmd.AlarmId))
{ {
_log.Debug("ScriptedAlarmHost: ignoring AlarmCommand {Op} for unowned alarm {AlarmId}", _log.Debug("ScriptedAlarmHost: ignoring AlarmCommand {Op} for unowned alarm {AlarmId}",
cmd.Operation, cmd.AlarmId); cmd.Operation, cmd.AlarmId);
return; 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 // 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 // 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 // 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", _log.Warning("ScriptedAlarmHost: rejecting TimedShelve for {AlarmId} — missing UnshelveAtUtc",
cmd.AlarmId); cmd.AlarmId);
return; return Refused("TimedShelve requires an unshelve time; the command was not applied.");
} }
await _engine.TimedShelveAsync(cmd.AlarmId, cmd.User, unshelveAt, ct); await _engine.TimedShelveAsync(cmd.AlarmId, cmd.User, unshelveAt, ct);
break; break;
@@ -797,35 +897,50 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
if (string.IsNullOrWhiteSpace(cmd.Comment)) if (string.IsNullOrWhiteSpace(cmd.Comment))
{ {
_log.Warning("ScriptedAlarmHost: rejecting AddComment for {AlarmId} — empty comment text", cmd.AlarmId); _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); await _engine.AddCommentAsync(cmd.AlarmId, cmd.User, cmd.Comment, ct);
break; break;
default: default:
_log.Warning("ScriptedAlarmHost: ignoring AlarmCommand with unknown operation {Op} for {AlarmId}", _log.Warning("ScriptedAlarmHost: ignoring AlarmCommand with unknown operation {Op} for {AlarmId}",
cmd.Operation, cmd.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) 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", _log.Warning("ScriptedAlarmHost: engine op {Op} for alarm {AlarmId} timed out after {Timeout} — the condition-state store is stalled",
cmd.Operation, cmd.AlarmId, _commandTimeout); 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) catch (ScriptedAlarmCommandRejectedException ex)
{ {
// #935 review S3: the last LoadAsync failed, so the engine holds no trusted state and refuses the // #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 // command (thrown before anything is saved) rather than persist one derived from a Fresh seed. #937: a
// broadcast (the OPC UA method / AdminUI already returned), so this Warning is the operator-visible // directly-asked command reports this to its OPC UA caller; a broadcast-only copy (the AdminUI, the
// record; the next successful deploy re-asserts the condition node from the store. // 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}", _log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} NOT applied — {Reason}",
cmd.Operation, cmd.AlarmId, ex.Message); 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) 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}", _log.Warning(ex, "ScriptedAlarmHost: engine op {Op} failed for alarm {AlarmId}",
cmd.Operation, cmd.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; _engine.OnInputsEstablished -= _onInputsEstablished;
if (_ownsEngine || !_restarting) _engine.Dispose(); if (_ownsEngine || !_restarting) _engine.Dispose();
_cts.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(); base.PostStop();
} }
@@ -117,6 +117,8 @@ public static class ServiceCollectionExtensions
// The condition → owning-driver native-ack pre-check snapshot (lmxopcua#760): DriverHostActor publishes // 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. // it, the OPC UA node manager reads it to refuse an acknowledge the driver would refuse anyway.
services.TryAddSingleton<NativeAlarmAckPreflightView>(); 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). // The node→central ack transport under MeshTransport:Mode = Grpc (mesh gRPC command plane).
// Registered unconditionally but resolved only by the Grpc arm of // 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. // raised on the condition-state hub. A malformed value fails host start.
conditionSignals: ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionSignalOptions.FromConfiguration( conditionSignals: ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionSignalOptions.FromConfiguration(
resolver.GetService<IConfiguration>(), 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); DriverHostActorName);
registry.Register<DriverHostActorKey>(driverHost); registry.Register<DriverHostActorKey>(driverHost);
@@ -0,0 +1,219 @@
using System.Collections.Concurrent;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.ServerEventRig;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// Gitea #937 over the wire — a scripted condition's Part 9 method returns the scripted-alarm engine's verdict. Before
/// #937 the command was a fire-and-forget topic publish and every allowed call returned Good, including one the engine
/// then rejected because its last load had failed.
/// </summary>
public sealed class ScriptedCommandVerdictWireTests
{
private const NodePermissions All =
NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead
| 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>
[Theory]
[InlineData("Acknowledge")]
[InlineData("AddComment")]
[InlineData("OneShotShelve")]
[InlineData("Disable")]
public async Task A_command_the_engine_refuses_returns_BadInvalidState(string method)
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync($"Verdict937Refused{method}", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
var asked = new ConcurrentQueue<AlarmCommand>();
rig.Nm.AlarmCommandAsker = (cmd, _) =>
{
asked.Enqueue(cmd);
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "engine blind"));
};
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var item = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
rig.Project(false, ConditionMethodEventTests.PreState(method, native: false) with { Message = "base" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
var refused = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
session, ConditionNodeId(session, false), method, events.LatestEventId(item, "base"), ct));
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");
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>Positive control: an applied verdict is Good, and the method still reports exactly one event.</summary>
[Fact]
public async Task A_command_the_engine_applies_returns_Good_with_one_event()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Applied", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
var current = ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" };
var routed = new ConcurrentQueue<AlarmCommand>();
rig.Nm.AlarmCommandRouter = routed.Enqueue;
rig.Nm.AlarmCommandAsker = (cmd, _) =>
{
// What the engine does: apply, then re-project (the method's own event already covered it).
current = current with { Acknowledged = true };
rig.ProjectLater(native: false, current);
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied));
};
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var item = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
rig.Project(false, current);
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
await ConditionMethodEventTests.CallAsync(session, ConditionNodeId(session, false), "Acknowledge",
events.LatestEventId(item, "base"), ct);
await rig.DrainProjectionsAsync();
rig.Project(false, current = current with { Message = "sentinel" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
events.ConditionEvents(item, "base").Count.ShouldBe(2, "the base transition plus exactly one Acknowledge event");
routed.ShouldBeEmpty("the asker replaces the fire-and-forget router inside a Call");
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>No answer inside the bound: BadTimeout with OutcomeUnknown — never reported as refused.</summary>
[Fact]
public async Task An_unanswered_command_returns_BadTimeout_outcome_unknown()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Timeout", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
rig.Nm.ScriptedCommandTimeout = TimeSpan.FromMilliseconds(500);
var never = new TaskCompletionSource<AlarmCommandOutcome>();
rig.Nm.AlarmCommandAsker = (_, _) => never.Task;
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var item = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
var started = DateTime.UtcNow;
var unknown = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
session, ConditionNodeId(session, false), "Acknowledge", events.LatestEventId(item, "base"), ct));
unknown.StatusCode.ShouldBe(StatusCodes.BadTimeout);
(DateTime.UtcNow - started).ShouldBeLessThan(TimeSpan.FromSeconds(10), "bounded");
await subscription.DeleteAsync(true, ct);
}
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// The synchronous pre-check: while the last load failed, the call is refused BadInvalidState BEFORE the SDK applies
/// anything — nothing is asked or routed, and no condition event is reported (sentinel-checked).
/// </summary>
[Fact]
public async Task The_preflight_refuses_before_any_state_change()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Preflight", encrypted: false, ct);
try
{
rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All));
rig.MaterialiseScripted();
var asked = 0;
var routed = 0;
rig.Nm.AlarmCommandAsker = (cmd, _) =>
{
Interlocked.Increment(ref asked);
return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied));
};
rig.Nm.AlarmCommandRouter = _ => Interlocked.Increment(ref routed);
string? refusal = "the last scripted-alarm deploy failed";
rig.Nm.ScriptedAlarmCommandPreflight = () => refusal;
var current = ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" };
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var item = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
rig.Project(false, current);
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
var refused = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
session, ConditionNodeId(session, false), "Acknowledge", events.LatestEventId(item, "base"), ct));
refused.StatusCode.ShouldBe(StatusCodes.BadInvalidState);
rig.Project(false, current with { Message = "sentinel" });
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
events.ConditionEvents(item, "base").Count.ShouldBe(1, "no Acknowledge event was reported");
events.ConditionEvents(item, "sentinel")[0][RecordedEvents.AckedField].ClrValue()!.ShouldBe(false, "the node was not acknowledged");
Volatile.Read(ref asked).ShouldBe(0);
Volatile.Read(ref routed).ShouldBe(0);
// Positive control: once a load succeeds the same call goes through.
refusal = null;
await ConditionMethodEventTests.CallAsync(session, ConditionNodeId(session, false), "Acknowledge",
events.LatestEventId(item, "sentinel"), ct);
Volatile.Read(ref asked).ShouldBe(1);
await subscription.DeleteAsync(true, ct);
}
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()
{
var ct = TestContext.Current.CancellationToken;
var rig = await StartAsync("Verdict937Remote", encrypted: false, ct);
try
{
rig.MaterialiseScripted();
rig.Project(false, ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Message = "base" });
await rig.DrainProjectionsAsync();
rig.Nm.AlarmCommandAsker = (cmd, _) =>
Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "engine blind"));
var marker = rig.Nm.SnapshotConditions((_, id) => id == ScriptedAlarmId, 10)
.SelectMany(s => s.Records).Single(c => c.ConditionId == ScriptedAlarmId).Activation;
var call = new OriginConditionMethodCall(AddressSpaceRealm.Uns, ScriptedAlarmId, "Acknowledge", "ack", marker, "svc", null);
var refused = await rig.Nm.ExecuteConditionMethodAsync(call, TimeSpan.FromSeconds(5));
refused.Applied.ShouldBeFalse();
refused.Dispatched.ShouldBeTrue();
refused.Unknown.ShouldBeFalse();
refused.StatusCode.ShouldBe(StatusCodes.BadInvalidState.Code);
refused.Diagnostic.ShouldBe("engine blind");
}
finally { await rig.DisposeAsync(); }
}
}
@@ -61,6 +61,24 @@ public sealed class GrpcDataConditionMethodTests
"Acknowledge", "ack", new ConditionActivationMarker("inc", 1), "peer", "peer-key")); "Acknowledge", "ack", new ConditionActivationMarker("inc", 1), "peer", "peer-key"));
} }
/// <summary>#937: a scripted engine's refusal after dispatch is a definite failure; no answer is OutcomeUnknown.</summary>
[Fact]
public async Task A_scripted_engine_verdict_after_dispatch_maps_to_confirmed_failure_or_outcome_unknown()
{
using var refusedFixture = new ConditionFixture(2, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
refusedFixture.Source.Execute = _ => new(false, false, BadInvalidState, "engine blind", Dispatched: true);
var refused = await CallAsync(refusedFixture, Request(RawPlacement(1)));
refused.State.ShouldBe(DataWriteState.DriverConfirmedFailure);
refused.StatusCode.ShouldBe(BadInvalidState);
refused.Diagnostic.ShouldBe("engine blind");
using var unknownFixture = new ConditionFixture(2, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
unknownFixture.Source.Execute = _ => new(false, false, BadTimeout, "OutcomeUnknown: no answer", Dispatched: true, Unknown: true);
var unknown = await CallAsync(unknownFixture, Request(RawPlacement(1)));
unknown.State.ShouldBe(DataWriteState.OutcomeUnknown);
unknown.StatusCode.ShouldBe(BadTimeout);
}
[Fact] [Fact]
public async Task Capabilities_carry_the_method_bits_and_mask_only_on_the_Primary() public async Task Capabilities_carry_the_method_bits_and_mask_only_on_the_Primary()
{ {
@@ -0,0 +1,113 @@
using Akka.Actor;
using Akka.TestKit;
using Serilog;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
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>
/// Gitea #937 — the host answers a directly-asked command with the engine's verdict, publishes its load outcome for
/// the node manager's pre-check, and applies a command reaching it twice (ask + broadcast, same CommandId) once.
/// </summary>
public sealed class ScriptedAlarmCommandVerdictTests : RuntimeActorTestBase
{
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static EquipmentScriptedAlarmPlan Plan(string id, string source = "return (int)ctx.GetTag(\"M.T\").Value > 90;") =>
new(ScriptedAlarmId: id, EquipmentId: "Plant/Line1/M", Name: id, AlarmType: "AlarmCondition", Severity: 800,
MessageTemplate: "condition", PredicateScriptId: $"{id}-script", PredicateSource: source,
DependencyRefs: ["M.T"], HistorizeToAveva: false, Retain: true, Enabled: true);
private static EquipmentScriptedAlarmPlan BadPlan(string id) => Plan(id, "return unknownIdentifier;");
private (IActorRef Host, ScriptedAlarmEngine Engine, ScriptedAlarmCommandReadinessView Readiness, TestProbe Mux) Spawn()
{
var publish = CreateTestProbe();
var mux = CreateTestProbe();
var upstream = new DependencyMuxTagUpstreamSource();
var logger = new LoggerConfiguration().CreateLogger();
var engine = new ScriptedAlarmEngine(upstream, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger);
var readiness = new ScriptedAlarmCommandReadinessView();
var host = Sys.ActorOf(ScriptedAlarmHostActor.Props(publish.Ref, mux.Ref, () => (upstream, engine), readiness: readiness));
return (host, engine, readiness, mux);
}
private static Task<AlarmCommandOutcome> Ask(IActorRef host, string alarmId, string operation, string? comment = null, string? commandId = null) =>
host.Ask<AlarmCommandOutcome>(new ScriptedAlarmHostActor.ExecuteAlarmCommand(
new AlarmCommand(alarmId, operation, "alice", comment, null, commandId)), Timeout, Ct);
[Fact]
public async Task After_a_failed_load_a_command_is_refused_and_the_readiness_view_says_so()
{
var (host, _, readiness, mux) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(Timeout, cancellationToken: Ct);
readiness.Refusal().ShouldBeNull();
// Positive control: a good generation applies (an ack of an inactive alarm is an applied no-op).
(await Ask(host, "alm-1", "AddComment", "first")).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
// A deploy that fails to compile leaves the engine with no complete generation.
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1"), BadPlan("bad-1")]));
AwaitCondition(() => readiness.Refusal() is not null, Timeout, cancellationToken: Ct);
var refused = await Ask(host, "alm-1", "Acknowledge");
refused.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
refused.Reason.ShouldBe(ScriptedAlarmCommandReadinessView.LoadFailedRefusal);
// The alarm that broke the load is still this host's (in the plan, absent from the half-built engine set).
(await Ask(host, "bad-1", "Acknowledge")).Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
// The next good deploy clears it.
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
AwaitCondition(() => readiness.Refusal() is null, Timeout, cancellationToken: Ct);
(await Ask(host, "alm-1", "AddComment", "second")).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
}
[Fact]
public async Task An_alarm_this_host_does_not_own_is_answered_not_applied()
{
var (host, _, _, mux) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(Timeout, cancellationToken: Ct);
var outcome = await Ask(host, "someone-elses", "Acknowledge");
outcome.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task A_command_arriving_as_both_ask_and_broadcast_is_applied_once(bool broadcastFirst)
{
var (host, engine, _, mux) = Spawn();
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")]));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(Timeout, cancellationToken: Ct);
var broadcast = new AlarmCommand("alm-1", "AddComment", "alice", "note", null, "cmd-1");
AlarmCommandOutcome outcome;
if (broadcastFirst)
{
host.Tell(broadcast);
outcome = await Ask(host, "alm-1", "AddComment", "note", "cmd-1");
}
else
{
outcome = await Ask(host, "alm-1", "AddComment", "note", "cmd-1");
host.Tell(broadcast);
}
outcome.Verdict.ShouldBe(AlarmCommandVerdict.Applied);
// Positive control: a different id IS applied — so the count below proves de-duplication, not a dropped copy.
(await Ask(host, "alm-1", "AddComment", "other", "cmd-2")).Verdict.ShouldBe(AlarmCommandVerdict.Applied);
engine.GetState("alm-1")!.Comments.Select(c => c.Text).ShouldBe(["note", "other"]);
}
}