From d6f2a1b5e258df5f3187376d403d6112c2a79798 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 28 Nov 2026 09:40:35 -0500 Subject: [PATCH] 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 --- .claude/rules/alarms.md | 14 +- docs/DataConnections.md | 3 +- docs/ScriptedAlarms.md | 49 +++- .../grpc-data/conditions_scenarios.py | 63 ++++- scripts/validation/grpc-data/seed/Program.cs | 12 +- .../OpcUa/AlarmCommand.cs | 44 +++- .../OpcUa/OtOpcUaServerHostedService.cs | 69 +++++- .../ImportedConditionMethods.cs | 36 ++- .../OriginConditionSource.cs | 14 ++ .../OtOpcUaNodeManager.ConditionMethods.cs | 6 +- ...OpcUaNodeManager.ScriptedCommandVerdict.cs | 196 ++++++++++++++++ .../OtOpcUaNodeManager.cs | 9 + .../SdkAddressSpaceSink.cs | 4 + .../LocalDataServices.ConditionMethods.cs | 18 +- .../Drivers/DriverHostActor.cs | 34 ++- .../ScriptedAlarmCommandReadinessView.cs | 34 +++ .../ScriptedAlarms/ScriptedAlarmHostActor.cs | 151 ++++++++++-- .../ServiceCollectionExtensions.cs | 6 +- .../ScriptedCommandVerdictWireTests.cs | 219 ++++++++++++++++++ .../GrpcDataConditionMethodTests.cs | 18 ++ .../ScriptedAlarmCommandVerdictTests.cs | 113 +++++++++ 21 files changed, 1074 insertions(+), 38 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmCommandReadinessView.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs diff --git a/.claude/rules/alarms.md b/.claude/rules/alarms.md index 4f3a5ec8e..81ab0c65b 100644 --- a/.claude/rules/alarms.md +++ b/.claude/rules/alarms.md @@ -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 `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. -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). diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 07fc7c2db..aca10c1fc 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -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? | |---|---|---| -| `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 | | `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 | diff --git a/docs/ScriptedAlarms.md b/docs/ScriptedAlarms.md index 0b0ab7008..98cd5ba59 100644 --- a/docs/ScriptedAlarms.md +++ b/docs/ScriptedAlarms.md @@ -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 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 - and shelving checks are dropped. The command topic is fire-and-forget (the OPC UA method / AdminUI call already returned - Good), so the rejection's only record is the host's Warning `… NOT applied — …`; the next good load re-asserts the node - from the store, undoing whatever the method showed. + and shelving checks are dropped. **Since #937 an OPC UA Part 9 method (and a remote gRPC-data condition method) on a + scripted condition reports this**: while the last load failed the node manager refuses the call `BadInvalidState` before the + SDK applies anything (no event, nothing routed); a call that passed that pre-check and then met a rejection (it was queued + behind a load that failed) also returns `BadInvalidState` — see [Operator command verdicts](#operator-command-verdicts-937). + 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 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 @@ -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. - **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). ### Delta-gate de-duplication diff --git a/scripts/validation/grpc-data/conditions_scenarios.py b/scripts/validation/grpc-data/conditions_scenarios.py index 752ced183..f04db1c69 100644 --- a/scripts/validation/grpc-data/conditions_scenarios.py +++ b/scripts/validation/grpc-data/conditions_scenarios.py @@ -30,8 +30,8 @@ from pathlib import Path import rig import scenarios -SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08") -TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720} +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, "F937": 900} REFRESH_REQUIRED = "RefreshRequiredEventType" _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) @@ -510,6 +510,65 @@ class ConditionScenarios: return {"code": code, "output": text[-300:], "good": code == 0 and ("successful" in text or "Comment added" 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 ------------------------------------------------------------------------------------------- def scenario_A03(self): """Origin failover mid-stream with standing active alarms. Phase 1: a consumer stream reset against the SAME origin diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs index b6b00300c..e01a61384 100644 --- a/scripts/validation/grpc-data/seed/Program.cs +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -175,7 +175,7 @@ try var root = mutation.RootElement; 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", - "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))) throw new InvalidOperationException("unknown fixture mutation field"); await using var db = await factory.CreateDbContextAsync(); @@ -197,6 +197,16 @@ try var maintenanceNode = await db.ClusterNodes.SingleAsync(x => x.NodeId == maintenanceNodeId); 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)) { var candidate = JsonSerializer.Deserialize(newConnection.GetRawText()) ?? throw new InvalidOperationException(); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs index 72e88c379..db6e2a1af 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs @@ -46,9 +46,51 @@ public static class AlarmCommandsTopic /// (DateTime.UtcNow + shelvingTime, where the OPC UA Duration shelvingTime is /// in milliseconds); null for every other operation. /// +/// +/// #937: an id unique to one operator call, set by a publisher that ALSO hands the same command to its own node's +/// ScriptedAlarmHostActor 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. +/// public sealed record AlarmCommand( string AlarmId, string Operation, string User, string? Comment, - DateTime? UnshelveAtUtc); + DateTime? UnshelveAtUtc, + string? CommandId = null); + +/// #937: what a scripted-alarm engine did with one . +public enum AlarmCommandVerdict +{ + /// The engine applied the command (an idempotent no-op — e.g. a re-shelve — included). + Applied, + + /// + /// 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. + /// + NotApplied, + + /// + /// 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". + /// + OutcomeUnknown, +} + +/// +/// #937: the local scripted-alarm host's answer to one directly-asked — what lets an OPC UA +/// Part 9 method return a Bad status instead of the Good a fire-and-forget topic publish implied. +/// +/// The command's alarm. +/// The command's operation. +/// What the engine did. +/// Operator-facing text for a verdict other than . +/// For : the bound expired (vs. a fault). +public sealed record AlarmCommandOutcome( + string AlarmId, + string Operation, + AlarmCommandVerdict Verdict, + string? Reason = null, + bool TimedOut = false); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs index 5175283e4..d2b777ec1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs @@ -55,6 +55,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl private readonly HistorianUpdaterHolder _historianUpdater; private readonly IHistoryUpdateRoleView? _historyUpdateRoleView; private readonly NativeAlarmAckPreflightView? _ackPreflightView; + private readonly ScriptedAlarmCommandReadinessView? _scriptedAlarmReadiness; private readonly OpcUaEndpointState _endpointState; private readonly bool _rethrowStartFailure; private readonly DriverWriteBounds _writeBounds; @@ -172,9 +173,11 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl IFederatedProjectionCatalog? projectedCatalog = null, IProjectedHistoryAccess? projectedHistoryAccess = null, IConditionStateSink? conditionStateSink = null, - IProjectedConditionAccess? projectedConditionAccess = null) + IProjectedConditionAccess? projectedConditionAccess = null, + ScriptedAlarmCommandReadinessView? scriptedAlarmReadiness = null) { _projectedConditionAccess = projectedConditionAccess; + _scriptedAlarmReadiness = scriptedAlarmReadiness; _projectedHistoryAccess = projectedHistoryAccess; _conditionStateSink = conditionStateSink; _dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get() ?? new(); @@ -316,6 +319,14 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl } }); + // #937: a scripted condition's Part 9 method answers with THIS node's engine verdict. The pre-check (one volatile + // read) refuses while the last scripted-alarm load failed; the asker broadcasts the command to the redundant peer + // exactly as the router above does and asks the local engine (via the DriverHostActor) for its verdict. Both run + // under the SDK's Lock and only read / send; the node manager awaits the verdict off Lock. + if (_scriptedAlarmReadiness is { } readiness) + _server.NodeManager.ScriptedAlarmCommandPreflight = readiness.Refusal; + _server.NodeManager.AlarmCommandAsker = AskScriptedAlarmCommand; + // Wire the reverse-path native-alarm-ack router (H6e): a client Acknowledge of a NATIVE (driver-fed, // e.g. Galaxy) Part 9 condition that passes the node manager's AlarmAck gate routes the acknowledge to // the owning driver child. The node manager maps the inbound ack to an OpcUaServer-local NativeAlarmAck; @@ -592,6 +603,57 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl _loggerFactory.CreateLogger()); } + /// + /// #937: the node manager's . Broadcasts the command on the + /// alarm-commands topic (the redundant peer applies it, as before) and asks THIS node's scripted-alarm host, + /// through the DriverHostActor, for its verdict; the command carries a fresh CommandId, 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 is an OutcomeUnknown outcome. + /// + /// The command (with its CommandId). + /// The caller's bound. + /// The verdict. + private Task 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(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 AskAsync(IActorRef host, AlarmCommand cmd, TimeSpan timeout) + { + try + { + return await host.Ask(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); + } + } + } + /// /// Stops the OPC UA server asynchronously: detaches every sink, then STOPS the SDK so the port closes. /// @@ -635,6 +697,11 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl _server?.SetNativeAlarmAckRouter(null); _server?.SetNativeAlarmAckPrimaryGate(null); _server?.SetNativeAlarmAckPreflight(null); + if (_server?.NodeManager is { } stoppingNodeManager) + { + stoppingNodeManager.AlarmCommandAsker = null; + stoppingNodeManager.ScriptedAlarmCommandPreflight = null; + } _server?.SetHistoryUpdatePrimaryGate(null); // Restore the Null historian so a late HistoryRead doesn't hit a disposed read client. _server?.SetHistorianDataSource(null); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs index 5ded216f2..6317f1b0c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs @@ -115,7 +115,7 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager (claimed ??= []).Add(i); } - base.Call(context, methodsToCall, results, errors); + await CallLocalAsync(context, methodsToCall, results, errors).ConfigureAwait(false); if (claimed is null) return; var caller = context.UserIdentity as RoleCarryingUserIdentity; @@ -132,6 +132,40 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager for (var k = 0; k < claimed.Count; k++) errors[claimed[k]] = calls[k].Result; } + /// + /// The local (non-imported) requests. Without an this is the unchanged batch + /// base.Call. With one (#937), each request runs through base.Call alone — in batch order, each fully + /// applied by the SDK under its own Lock 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 Lock held, and each + /// request's status becomes its engine's verdict. Never throws past the SDK's own behaviour (the waits are guarded). + /// + private async Task CallLocalAsync(OperationContext context, ArrayOf methodsToCall, IList results, + IList 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; + } + } + /// Review S1: as a task that cannot fault (a synchronous throw included). private async Task CallImportedGuardedAsync(RoleCarryingUserIdentity? caller, CallMethodRequest request, DateTime deadline, CancellationToken cancellationToken) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginConditionSource.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginConditionSource.cs index cd9a85529..ad9b39e35 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginConditionSource.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginConditionSource.cs @@ -20,6 +20,15 @@ public interface IOriginConditionSource /// The call. /// The verdict. OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call); + + /// #937: see — + /// plus, for a scripted condition, the engine's verdict awaited (off Lock) within . The + /// default (a source with no engine behind it) is the synchronous verdict. + /// The call. + /// The caller's remaining budget. + /// The verdict. + Task ExecuteConditionMethodAsync(OriginConditionMethodCall call, TimeSpan budget) => + Task.FromResult(TryExecuteConditionMethod(call)); } /// Resolves the port against the SDK sink bound at server start; throws while the server is not running. @@ -37,6 +46,11 @@ public sealed class DeferredOriginConditionSource(DeferredAddressSpaceSink defer public OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call) => deferred.GetCapability() is { } inner ? inner.TryExecuteConditionMethod(call) : throw new OriginConditionSourceUnavailableException(); + + /// + public Task ExecuteConditionMethodAsync(OriginConditionMethodCall call, TimeSpan budget) => + deferred.GetCapability() is { } inner ? inner.ExecuteConditionMethodAsync(call, budget) + : throw new OriginConditionSourceUnavailableException(); } /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionMethods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionMethods.cs index e5e61dad5..dd5554b32 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionMethods.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ConditionMethods.cs @@ -26,7 +26,11 @@ public sealed record OriginConditionMethodCall(AddressSpaceRealm Realm, string C /// Whether the condition is native (driver-fed): an applied native call is accepted, not confirmed. /// The OPC UA status (Good when applied). /// A refusal's reason text, when the gate gave one. -public sealed record OriginConditionMethodOutcome(bool Applied, bool Native, uint StatusCode, string? Diagnostic); +/// #937: is false, but the call reached the scripted-alarm engine — which refused +/// it, or did not answer (). The node manager had already applied its node state. +/// #937: the engine did not answer inside the budget (or failed): the command may still apply. +public sealed record OriginConditionMethodOutcome(bool Applied, bool Native, uint StatusCode, string? Diagnostic, + bool Dispatched = false, bool Unknown = false); public sealed partial class OtOpcUaNodeManager { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs new file mode 100644 index 000000000..bd01b05a9 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs @@ -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; + +/// +/// #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. +/// +/// +/// +/// Two layers. (1) — a lock-free read of this node's engine load +/// outcome — refuses BadInvalidState 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 (, bounded): the handler, still under Lock, +/// 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 (, or +/// for a remote gRPC-data call) awaits the verdict once the SDK released +/// Lock, and turns a refusal into BadInvalidState and no answer into BadTimeout (OutcomeUnknown). +/// +/// +/// Status codes. 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 Bad_InvalidState — "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 Bad_Timeout 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. +/// +/// +/// Residual (documented). 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. +/// +/// +public sealed partial class OtOpcUaNodeManager +{ + /// How long a scripted condition method waits for the engine's verdict by default (5 s). + internal static readonly TimeSpan DefaultScriptedCommandTimeout = TimeSpan.FromSeconds(5); + + private static readonly AsyncLocal PendingScriptedCommandSlot = new(); + + /// + /// #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 Lock: MUST be a lock-free read, no I/O. Null ⇒ no pre-check. + /// + public Func? ScriptedAlarmCommandPreflight { get; set; } + + /// + /// #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 does). Called under Lock: it MUST + /// only send and return the pending task. The timeout argument is the caller's bound. Null ⇒ the fire-and-forget + /// and an unconditional Good, as before #937. + /// + public Func>? AlarmCommandAsker { get; set; } + + /// The longest a scripted condition method waits for the engine's verdict (also capped by the request deadline). + internal TimeSpan ScriptedCommandTimeout { get; set; } = DefaultScriptedCommandTimeout; + + /// The verdict slot one Call request's handler fills (one per request; flows into the synchronous SDK call). + private sealed class PendingScriptedCommand(TimeSpan timeout) + { + public TimeSpan Timeout { get; } = timeout; + public Task? Outcome { get; set; } + } + + /// + /// From (under Lock): when the current Call awaits a verdict, start the ask + /// and park its task. False ⇒ not inside such a call (route fire-and-forget). + /// + 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(ex); + } + return true; + } + + /// The bound for one request: , cut by the request deadline (less a grace). + 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; + } + + /// + /// Runs the SDK's synchronous base.Call 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). + /// + private Task? CallOneAwaitingVerdict(OperationContext context, ArrayOf methodsToCall, int index, + IList results, IList errors, TimeSpan bound) + { + var request = methodsToCall[index]; + var singleResults = new List { results[index] }; + var singleErrors = new List { errors[index] }; + var pending = new PendingScriptedCommand(bound); + PendingScriptedCommandSlot.Value = pending; + try + { + base.Call(context, (ArrayOf)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; + } + + /// + /// 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 + /// outcome; the wait here (its bound plus a grace) is the backstop for one that never completes. + /// + private async Task<(ServiceResult Status, bool Unknown)> AwaitScriptedVerdictAsync(Task 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)); + } + + /// + /// #937: plus the scripted engine's verdict (A2b remote calls). The node-manager + /// part runs under Lock exactly as before; the verdict is awaited after it is released, bounded by + /// (capped at ). + /// + /// The call. + /// The caller's remaining budget. + /// The verdict: Applied only once the engine applied it; a refusal after dispatch carries + /// ; no answer carries . + public async Task 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); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index f474f4704..acc50514d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -3210,6 +3210,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // (nothing routed, nothing applied, no event). Unset/None keep today's acceptance. if (_standby.RefusesMutations) return WarmStandbyState.StandbyRefusal($"call {operation}"); + // #937: this node's engine holds no complete generation (its last load failed) and would reject the command — + // refuse it before the SDK applies anything (no event, nothing routed). One volatile read; safe under Lock. + if (ScriptedAlarmCommandPreflight?.Invoke() is { } notReady) + return new ServiceResult(StatusCodes.BadInvalidState, new LocalizedText(notReady)); + var cmd = new AlarmCommand( AlarmId: condition.NodeId.IdentifierAsString, Operation: operation, @@ -3217,6 +3222,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage Comment: comment?.Text, UnshelveAtUtc: unshelveAt); + // #937: inside a Call that awaits the engine's verdict (CallAsync / ExecuteConditionMethodAsync), start the + // bounded ask — non-blocking: it only sends — and let the caller await it once Lock is released. + if (TryStartScriptedCommandAsk(cmd)) return ServiceResult.Good; + // Non-blocking by contract (host wires a fire-and-forget mediator.Tell); safe to call under Lock. AlarmCommandRouter?.Invoke(cmd); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs index e05abc500..dc2c20382 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs @@ -40,6 +40,10 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre OriginConditionMethodOutcome IOriginConditionSource.TryExecuteConditionMethod(OriginConditionMethodCall call) => _nodeManager.TryExecuteConditionMethod(call); + /// + Task IOriginConditionSource.ExecuteConditionMethodAsync(OriginConditionMethodCall call, TimeSpan budget) => + _nodeManager.ExecuteConditionMethodAsync(call, budget); + /// Initializes a new instance of the SdkAddressSpaceSink class. /// The OPC UA node manager. public SdkAddressSpaceSink(OtOpcUaNodeManager nodeManager) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.ConditionMethods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.ConditionMethods.cs index 243ca5569..a610eecbf 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.ConditionMethods.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.ConditionMethods.cs @@ -212,7 +212,7 @@ public sealed partial class LocalDataServices DataWriteOutcome? outcome = null; try { - outcome = Dispatch(); + outcome = await DispatchAsync().ConfigureAwait(false); return (FromOutcome(outcome), false); } finally @@ -230,15 +230,16 @@ public sealed partial class LocalDataServices registry.ReleaseUndispatched(context.PrincipalId, request.OperationId, owner); } - DataWriteOutcome Dispatch() + async Task DispatchAsync() { OriginConditionMethodOutcome verdict; try { - verdict = ConditionSource.TryExecuteConditionMethod(new(placement.Condition.Realm, placement.Condition.ConditionId, + // #937: a scripted condition answers only once its engine applied (or refused) the command. + verdict = await ConditionSource.ExecuteConditionMethodAsync(new(placement.Condition.Realm, placement.Condition.ConditionId, DataConditionMethodSets.Part9Name(request.Method), request.Comment, new ConditionActivationMarker(request.ExpectedActivation.Incarnation, request.ExpectedActivation.Sequence), - context.PrincipalId, context.ApiKeyId)); + context.PrincipalId, context.ApiKeyId), request.RemainingBudget).ConfigureAwait(false); } catch (OriginConditionSourceUnavailableException ex) { @@ -267,6 +268,15 @@ public sealed partial class LocalDataServices : new(DataWriteState.AcceptedUnconfirmed, verdict.StatusCode, "AcceptedUnconfirmed: the comment was applied at the origin (not sent to the driver); it arrives on the condition stream."); } + else if (verdict.Dispatched) + { + // #937: the scripted engine refused it after the node manager dispatched it (a definite failure), or did + // not answer inside the budget (OutcomeUnknown — it may still apply; never reported as refused). + owner.TryMarkDispatched(); + decided = verdict.Unknown + ? new(DataWriteState.OutcomeUnknown, verdict.StatusCode, verdict.Diagnostic) + : new(DataWriteState.DriverConfirmedFailure, verdict.StatusCode, verdict.Diagnostic); + } else decided = new(DataWriteState.RejectedBeforeDispatch, verdict.StatusCode, verdict.Diagnostic); owner.Complete(decided); return decided; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index 3e74d18c4..c5bd882ba 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -532,6 +532,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn /// Where the synchronous native-ack pre-check snapshot is published (lmxopcua#760); null ⇒ none. private readonly NativeAlarmAckPreflightView? _ackPreflightView; + /// #937: where the scripted-alarm host publishes its load outcome (null in tests). + private readonly ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmCommandReadinessView? _scriptedAlarmReadiness; + /// The write bounds every child is spawned with and this host's write Ask is derived from /// (lmxopcua#777). private readonly DriverWriteBounds _writeBounds; @@ -875,7 +878,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn SubscriptionAcquisitionCapacity? acquisitionCapacity = null, DataConnectionDeploymentRuntime? dataConnections = null, ActorProjectedValuePublisher? projectedPublisher = null, - ConditionSignalOptions? conditionSignals = null) => + ConditionSignalOptions? conditionSignals = null, + ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmCommandReadinessView? scriptedAlarmReadiness = null) => // WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an // expression tree. Six IActorRef? parameters and several interface-typed ones mean a // mis-ordered argument is usually type-compatible and therefore compiles clean, then binds @@ -891,7 +895,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView, scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout, enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity, dataConnections, projectedPublisher, - conditionSignals)); + conditionSignals, scriptedAlarmReadiness)); /// Initializes a new DriverHostActor with the specified dependencies. /// Database context factory for configuration database access. @@ -1034,9 +1038,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn SubscriptionAcquisitionCapacity? acquisitionCapacity = null, DataConnectionDeploymentRuntime? dataConnections = null, ActorProjectedValuePublisher? projectedPublisher = null, - ConditionSignalOptions? conditionSignals = null) + ConditionSignalOptions? conditionSignals = null, + ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmCommandReadinessView? scriptedAlarmReadiness = null) { _conditionSignals = conditionSignals ?? new ConditionSignalOptions(); + _scriptedAlarmReadiness = scriptedAlarmReadiness; _projectedPublisher = projectedPublisher; _dataWriteRuntime = dataWriteRuntime; _dataConnections = dataConnections; @@ -1399,7 +1405,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn var upstream = new DependencyMuxTagUpstreamSource(); return (upstream, CreateScriptedAlarmEngine(upstream, store, scriptLogger, scripting, alarmRunner)); }, - _localNode, telemetryHub: _telemetryHub), + _localNode, telemetryHub: _telemetryHub, readiness: _scriptedAlarmReadiness), "scripted-alarm-host"); } @@ -1781,6 +1787,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn Receive(HandleRouteNodeWrite); Receive(HandleRouteRichWrite); Receive(HandleRouteNativeAlarmAck); + Receive(HandleExecuteAlarmCommand); Receive(HandleAlarmAckFailed); Receive(OnRedundancyStateChanged); Receive(OnDriverMembershipChanged); @@ -1862,6 +1869,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn Receive(HandleRouteNodeWrite); Receive(HandleRouteRichWrite); Receive(HandleRouteNativeAlarmAck); + Receive(HandleExecuteAlarmCommand); Receive(HandleAlarmAckFailed); Receive(OnRedundancyStateChanged); Receive(OnDriverMembershipChanged); @@ -2587,6 +2595,23 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn /// carrying the wire-ref FullName + principal. /// /// + /// + /// #937: the node-local ask behind a scripted condition's Part 9 method. Forwarded (sender kept) to this node's + /// , 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. + /// + private void HandleExecuteAlarmCommand(ScriptedAlarmHostActor.ExecuteAlarmCommand msg) + { + if (_scriptedAlarmHost is { } host) + { + host.Forward(msg); + return; + } + + Sender.Tell(new AlarmCommandOutcome(msg.Command.AlarmId, msg.Command.Operation, AlarmCommandVerdict.NotApplied, + "This server runs no scripted-alarm engine; the command was not applied.")); + } + private void HandleRouteNativeAlarmAck(RouteNativeAlarmAck msg) { // PRIMARY GATE FIRST (archreview 03/S4) — only the Primary pushes the ack upstream. Same policy as @@ -2938,6 +2963,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // An inbound native-condition ack can't be serviced while Stale either (the alarm inverse map is // empty until an apply runs). The node manager's pre-check refuses it synchronously while Stale (see the // top of this method); one that raced that refusal is dropped here with a log. + Receive(HandleExecuteAlarmCommand); Receive(msg => _log.Debug("DriverHost {Node}: dropping native-alarm ack for {Node2} while Stale (config DB unreachable)", _localNode, msg.ConditionNodeId)); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmCommandReadinessView.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmCommandReadinessView.cs new file mode 100644 index 000000000..2ca4c2b83 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmCommandReadinessView.cs @@ -0,0 +1,34 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms; + +/// +/// #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 +/// ScriptedAlarmCommandRejectedException). publishes the outcome of every +/// completed load; is one volatile read, safe under the SDK node-manager lock. +/// +/// +/// 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 (ScriptedAlarmHostActor.ExecuteAlarmCommand) +/// reports that to the caller. It never refuses anything before the first load completes (unknown ⇒ let it through). +/// +public sealed class ScriptedAlarmCommandReadinessView +{ + /// The refusal text while the last completed load failed. + 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; + + /// Why a scripted-alarm command would be rejected right now, or null to proceed. + /// The refusal reason, or null. + public string? Refusal() => _refusal; + + /// Records the outcome of the latest completed load. Called by only. + /// True when it completed a generation; false when it failed. + internal void SetLoadOutcome(bool loaded) => _refusal = loaded ? null : LoadFailedRefusal; + + /// Forgets any outcome (a new host incarnation has not loaded yet). Called by the host only. + internal void Reset() => _refusal = null; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs index 9f4aa2223..49bd55908 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs @@ -86,6 +86,16 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor /// The desired Equipment-namespace scripted-alarm plans. public sealed record ApplyScriptedAlarms(IReadOnlyList Plans); + /// + /// #937: a NODE-LOCAL ask (never published, never serialized) — apply to this host's + /// engine and reply an 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 ) is also broadcast on for the + /// redundant peer; this host applies whichever copy arrives first and skips the other. + /// + /// The command. + public sealed record ExecuteAlarmCommand(AlarmCommand Command); + /// /// Told to the parent from . A supervision restart is otherwise invisible to the /// parent, and the new incarnation has an EMPTY engine (factory Props) and no mux interest, so until the @@ -175,6 +185,19 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor /// so out-of-order loads never register superseded dep refs. private int _loadGeneration; + /// #937: the published outcome of the latest completed load (null in tests). + private readonly ScriptedAlarmCommandReadinessView? _readiness; + + /// #937: the enabled alarm ids of the latest — this host's alarms even while + /// the engine's own set is mid-load or (a failed load) half-built. + private HashSet _plannedAlarmIds = new(StringComparer.Ordinal); + + /// #937: the outcome of each recent command that carried a , so the + /// broadcast copy of a directly-asked command (or the other way round) is applied once. Bounded FIFO. + private readonly Dictionary _recentCommands = new(StringComparer.Ordinal); + private readonly Queue _recentCommandOrder = new(); + internal const int RecentCommandCapacity = 1024; + /// Cached cluster DistributedPubSub mediator, resolved once in (on the /// actor thread) and reused for every emission instead of re-resolving it per-publish. private IActorRef _mediator = null!; @@ -230,8 +253,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor NodeId? localNode = null, Func? driverMemberCountProvider = null, ITelemetryLocalHub? telemetryHub = null, - TimeSpan? commandTimeout = null) => - Akka.Actor.Props.Create(() => new ScriptedAlarmHostActor(publishActor, mux, engineFactory, localNode, driverMemberCountProvider, telemetryHub, commandTimeout)); + TimeSpan? commandTimeout = null, + ScriptedAlarmCommandReadinessView? readiness = null) => + Akka.Actor.Props.Create(() => new ScriptedAlarmHostActor(publishActor, mux, engineFactory, localNode, driverMemberCountProvider, telemetryHub, commandTimeout, readiness)); /// Factory-built incarnation: owns (and on every stop disposes) the engine it builds. /// The OPC UA publish actor emissions are bridged to. @@ -241,6 +265,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor /// Test seam for the alerts-emit gate's driver-member count. /// Optional node-local live-telemetry hub. /// Bound on one inbound alarm command's engine op. + /// #937: where the outcome of every completed load is published for the node manager's + /// synchronous pre-check. Null ⇒ none (tests). public ScriptedAlarmHostActor( IActorRef publishActor, IActorRef? mux, @@ -248,8 +274,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor NodeId? localNode = null, Func? driverMemberCountProvider = null, ITelemetryLocalHub? telemetryHub = null, - TimeSpan? commandTimeout = null) - : this(publishActor, mux, Build(engineFactory), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: true, commandTimeout) + TimeSpan? commandTimeout = null, + ScriptedAlarmCommandReadinessView? readiness = null) + : this(publishActor, mux, Build(engineFactory), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: true, commandTimeout, readiness) { } @@ -284,7 +311,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor NodeId? localNode = null, Func? driverMemberCountProvider = null, ITelemetryLocalHub? telemetryHub = null) - : this(publishActor, mux, (upstream, engine), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: false, commandTimeout: null) + : this(publishActor, mux, (upstream, engine), localNode, driverMemberCountProvider, telemetryHub, ownsEngine: false, commandTimeout: null, readiness: null) { } @@ -296,8 +323,12 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor Func? driverMemberCountProvider, ITelemetryLocalHub? telemetryHub, bool ownsEngine, - TimeSpan? commandTimeout) + TimeSpan? commandTimeout, + ScriptedAlarmCommandReadinessView? readiness) { + _readiness = readiness; + // A new incarnation has not loaded yet: whatever the previous one published no longer describes this engine. + _readiness?.Reset(); ArgumentNullException.ThrowIfNull(publishActor); ArgumentNullException.ThrowIfNull(pair.Upstream); ArgumentNullException.ThrowIfNull(pair.Engine); @@ -341,6 +372,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor // the handler is a Task-returning ReceiveAsync: Akka suspends the mailbox until the op completes // (ordered, awaited on the actor thread) and routes any escaped fault through supervision. ReceiveAsync(OnAlarmCommand); + // #937: the node-local ask behind an OPC UA Part 9 method — same op, plus a reply carrying the verdict. + ReceiveAsync(OnExecuteAlarmCommand); // A faulted LoadAsync pipes back a Status.Failure (see OnApply) — log it and stay inert so the // failure doesn't hit the dead-letter log. Receive(OnLoadFailed); @@ -369,6 +402,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor // Skip disabled plans entirely — the engine has no Enabled flag, so a disabled alarm is simply // not loaded (no predicate, no upstream subscription, no events). var enabled = msg.Plans.Where(p => p.Enabled).ToList(); + _plannedAlarmIds = new HashSet(enabled.Select(p => p.ScriptedAlarmId), StringComparer.Ordinal); var defs = enabled.Select(ToDefinition).ToList(); @@ -401,10 +435,19 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor } private void OnLoadFailed(Status.Failure msg) - => _log.Warning(msg.Cause, "ScriptedAlarmHost: engine LoadAsync failed — alarms not (re)loaded"); + { + // #937: loads serialize on the engine's gate, so completions arrive in start order — this is the latest + // completed load, and the engine now holds no complete generation (it rejects every operator command). + _readiness?.SetLoadOutcome(loaded: false); + _log.Warning(msg.Cause, "ScriptedAlarmHost: engine LoadAsync failed — alarms not (re)loaded; operator commands are refused until the next successful deploy"); + } private void OnAlarmsLoaded(AlarmsLoaded msg) { + // #937: ANY completed load — even one a newer apply superseded — left the engine holding a complete generation + // until that newer load finishes (which then publishes its own outcome). + _readiness?.SetLoadOutcome(loaded: true); + // Discard a stale completion: if a newer apply has since bumped the generation, this load's // dep refs are superseded and registering them would re-introduce the old set. The latest // generation's continuation will (or already did) register the current interest set. @@ -741,17 +784,74 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor /// The inbound alarm command. private async Task OnAlarmCommand(AlarmCommand cmd) { + // #937: the broadcast copy of a command this host already took through ExecuteAlarmCommand (or the other way + // round) is applied once. + if (cmd.CommandId is { } id && _recentCommands.ContainsKey(id)) + { + _log.Debug("ScriptedAlarmHost: skipping duplicate AlarmCommand {Op} for {AlarmId} (command {CommandId})", + cmd.Operation, cmd.AlarmId, id); + return; + } + // Ownership filter FIRST: ignore commands for alarms this engine doesn't own. The topic is a // cluster-wide broadcast, so the same command lands on every host — only the owner acts. - // Note: a concurrent LoadAsync can momentarily clear the loaded set, so a racing command may - // surface a spurious ArgumentException from the engine below — the outer catch absorbs it (benign). - if (!_engine.LoadedAlarmIds.Contains(cmd.AlarmId)) + if (!Owns(cmd.AlarmId)) { _log.Debug("ScriptedAlarmHost: ignoring AlarmCommand {Op} for unowned alarm {AlarmId}", cmd.Operation, cmd.AlarmId); return; } + Remember(cmd, await ApplyCommandAsync(cmd)); + } + + /// + /// #937: the node-local ask behind an OPC UA Part 9 method. Applies the command exactly as + /// 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 (): the caller's condition node is on this node. + /// + 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."; + + /// Whether this host owns : 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). + 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()); + } + + /// + /// Runs one owned command against the engine and classifies the result (#937). Never throws: every failure is + /// logged like and becomes a verdict. + /// + private async Task ApplyCommandAsync(AlarmCommand cmd) + { + AlarmCommandOutcome Refused(string reason) => new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, reason); + // Bounded (R02:H3): every op ends in IAlarmStateStore.SaveAsync (LocalDb/SQLite), and this is a // ReceiveAsync — the mailbox is suspended until the op returns, so an unbounded await on a hung // file lock stalled dependency-value ingestion for the duration. Linked to the actor's lifetime @@ -780,7 +880,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor { _log.Warning("ScriptedAlarmHost: rejecting TimedShelve for {AlarmId} — missing UnshelveAtUtc", cmd.AlarmId); - return; + return Refused("TimedShelve requires an unshelve time; the command was not applied."); } await _engine.TimedShelveAsync(cmd.AlarmId, cmd.User, unshelveAt, ct); break; @@ -797,35 +897,50 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor if (string.IsNullOrWhiteSpace(cmd.Comment)) { _log.Warning("ScriptedAlarmHost: rejecting AddComment for {AlarmId} — empty comment text", cmd.AlarmId); - return; + return Refused("AddComment requires comment text; the command was not applied."); } await _engine.AddCommentAsync(cmd.AlarmId, cmd.User, cmd.Comment, ct); break; default: _log.Warning("ScriptedAlarmHost: ignoring AlarmCommand with unknown operation {Op} for {AlarmId}", cmd.Operation, cmd.AlarmId); - break; + return Refused($"Unknown alarm operation '{cmd.Operation}'; the command was not applied."); } + return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.Applied); } catch (OperationCanceledException) when (!_cts.IsCancellationRequested) { + // The op may have been cancelled inside SaveAsync after the store committed: unknown, never "not applied". _log.Warning("ScriptedAlarmHost: engine op {Op} for alarm {AlarmId} timed out after {Timeout} — the condition-state store is stalled", cmd.Operation, cmd.AlarmId, _commandTimeout); + return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown, + $"OutcomeUnknown: the alarm engine did not finish the command within {_commandTimeout.TotalSeconds:0.#} s.", TimedOut: true); } catch (ScriptedAlarmCommandRejectedException ex) { // #935 review S3: the last LoadAsync failed, so the engine holds no trusted state and refuses the - // command rather than persist one derived from a Fresh seed. The command is a fire-and-forget topic - // broadcast (the OPC UA method / AdminUI already returned), so this Warning is the operator-visible - // record; the next successful deploy re-asserts the condition node from the store. + // command (thrown before anything is saved) rather than persist one derived from a Fresh seed. #937: a + // directly-asked command reports this to its OPC UA caller; a broadcast-only copy (the AdminUI, the + // redundant peer's copy) has only this Warning. The next successful deploy re-asserts the node from the store. _log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} NOT applied — {Reason}", cmd.Operation, cmd.AlarmId, ex.Message); + return Refused(ScriptedAlarmCommandReadinessView.LoadFailedRefusal); + } + catch (ArgumentException ex) + { + // The engine's lookup (under its gate, before any save): the alarm is not in the generation the command + // ran against — e.g. the deploy queued ahead of it removed the alarm. + _log.Warning(ex, "ScriptedAlarmHost: engine op {Op} refused for alarm {AlarmId}", cmd.Operation, cmd.AlarmId); + return Refused(NotLoadedRefusal); } catch (Exception ex) { - // A failing engine op must not crash the actor — mirror OnLoadFailed's log-and-stay-inert style. + // A failing engine op must not crash the actor — mirror OnLoadFailed's log-and-stay-inert style. A store + // fault may have left the row written, so this is unknown, not a refusal. _log.Warning(ex, "ScriptedAlarmHost: engine op {Op} failed for alarm {AlarmId}", cmd.Operation, cmd.AlarmId); + return new(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown, + "OutcomeUnknown: the alarm engine failed while applying the command."); } } @@ -887,6 +1002,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor _engine.OnInputsEstablished -= _onInputsEstablished; if (_ownsEngine || !_restarting) _engine.Dispose(); _cts.Dispose(); + // #937: this engine's load outcome describes nothing once it is gone (the ask path answers for a missing host). + _readiness?.Reset(); base.PostStop(); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs index 6350ac3ad..10e6ca045 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs @@ -117,6 +117,8 @@ public static class ServiceCollectionExtensions // The condition → owning-driver native-ack pre-check snapshot (lmxopcua#760): DriverHostActor publishes // it, the OPC UA node manager reads it to refuse an acknowledge the driver would refuse anyway. services.TryAddSingleton(); + // #937: the scripted-alarm engine's load outcome, for the node manager's synchronous Part 9 method pre-check. + services.TryAddSingleton(); // The node→central ack transport under MeshTransport:Mode = Grpc (mesh gRPC command plane). // Registered unconditionally but resolved only by the Grpc arm of @@ -686,7 +688,9 @@ public static class ServiceCollectionExtensions // raised on the condition-state hub. A malformed value fails host start. conditionSignals: ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionSignalOptions.FromConfiguration( resolver.GetService(), - resolver.GetService())), + resolver.GetService()), + // #937: where the scripted-alarm host publishes its load outcome (the Part 9 method pre-check). + scriptedAlarmReadiness: resolver.GetService()), DriverHostActorName); registry.Register(driverHost); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs new file mode 100644 index 000000000..3f628dcda --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs @@ -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; + +/// +/// 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. +/// +public sealed class ScriptedCommandVerdictWireTests +{ + private const NodePermissions All = + NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead + | NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.AlarmShelve + | NodePermissions.MethodCall; + + /// The engine refuses (no complete generation): the client's Acknowledge fails BadInvalidState with its reason. + [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(); + 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(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(); } + } + + /// Positive control: an applied verdict is Good, and the method still reports exactly one event. + [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(); + 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(); } + } + + /// No answer inside the bound: BadTimeout with OutcomeUnknown — never reported as refused. + [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(); + 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(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(); } + } + + /// + /// 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). + /// + [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(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(); } + } + + /// A2b: a remote (gRPC data) condition method on a scripted condition carries the same verdict. + [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(); } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionMethodTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionMethodTests.cs index 9e66c4e43..c6afcd3f2 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionMethodTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionMethodTests.cs @@ -61,6 +61,24 @@ public sealed class GrpcDataConditionMethodTests "Acknowledge", "ack", new ConditionActivationMarker("inc", 1), "peer", "peer-key")); } + /// #937: a scripted engine's refusal after dispatch is a definite failure; no answer is OutcomeUnknown. + [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] public async Task Capabilities_carry_the_method_bits_and_mask_only_on_the_Primary() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs new file mode 100644 index 000000000..e543dce6c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs @@ -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; + +/// +/// 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. +/// +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 Ask(IActorRef host, string alarmId, string operation, string? comment = null, string? commandId = null) => + host.Ask(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(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(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(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"]); + } +}