diff --git a/.claude/rules/alarms.md b/.claude/rules/alarms.md index 4f3a5ec8e..5e154ff40 100644 --- a/.claude/rules/alarms.md +++ b/.claude/rules/alarms.md @@ -87,4 +87,23 @@ 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 settles the verdict — one request at a time, before the next runs: refused ⇒ +`BadInvalidState` AND the node reverted to its captured pre-call state with one corrective event (skipped if the node +changed since); no answer (min 5 s / deadline − 250 ms) ⇒ `BadTimeout` "OutcomeUnknown" (never "refused" — it may still +apply; node kept). The peer gets the broadcast only AFTER an applied/unknown local verdict (`ScriptedAlarmCommandDispatch`) +— broadcasting first let the peer apply a command the caller was told failed. ≤ 64 asks in flight node-wide, else +`BadTooManyOperations` before anything applies. A native AddComment skips all of this (no engine owns it). Review r2: a +deadline leaving < 250 ms, or an earlier unanswered scripted method in the same Call, refuses the method `BadTimeout` +unsent; `OpcUa:Quotas:MaxNodesPerMethodCall` (1000) bounds a Call; an ask expired in the host mailbox skips the engine and is +not remembered (its broadcast copy applies); the revert is guarded by a per-condition mutation counter, not field equality. 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 38e6dc2e3..12a1a275a 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -621,7 +621,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..ee9b6d1f7 100644 --- a/docs/ScriptedAlarms.md +++ b/docs/ScriptedAlarms.md @@ -186,9 +186,16 @@ 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` and the node is reverted — see + [Operator command verdicts](#operator-command-verdicts-937). + The AdminUI `/alerts` buttons still publish fire-and-forget ("Ack sent"), so for them the only record remains the host's + Warning `… NOT applied — …`. The next good load re-asserts every node from the store. + **Accepted trade-off:** because the next good load after a failed one reads the store (which has no `Active` column), each + 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 +418,69 @@ 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`; SDK 2.0.1's + `StandardServer.CallAsync` awaits it, so no request thread is held), each local request runs through the SDK's + `base.Call` on its own and is SETTLED before the next request of the batch runs. The handler, under `Lock`, only + *starts* the ask (`AlarmCommandAsker`): the hosted service asks **this node's** `ScriptedAlarmHostActor` (via + `DriverHostActor`, `ExecuteAlarmCommand`) and broadcasts the command on `alarm-commands` for the redundant peer **only + after the local verdict is applied or unknown** (`ScriptedAlarmCommandDispatch`), with a fresh `CommandId` so the local + host applies its two copies once. The SDK applies its node state and reports the one method event exactly as before; + then the Call awaits the verdict with no lock held. **A refusal reverts the node** to its captured pre-call state with + one corrective event — unless something else changed the node since (newer truth wins) — mirroring the #760 native-ack + revert. Cheap refusals the engine would make (a blank scripted AddComment ⇒ `BadInvalidArgument`) happen in the + handler, before the SDK applies anything. +3. **Load bound** — at most 64 asks outstanding node-wide (`MaxScriptedCommandsInFlight`); past it the call is refused + `BadTooManyOperations` before anything is applied or sent. Each request's 5 s bound starts when its own ask is sent and + is cut by the request deadline; a scripted method whose deadline leaves less than 250 ms (after a 250 ms grace) is + refused `BadTimeout` unsent, and after the FIRST scripted method of a batch that got no answer every later scripted + method of that batch is refused `BadTimeout` unsent (non-scripted methods in the batch still run) — so a wedged engine + costs one bound per Call, not one per method. A Call carries at most `OpcUa:Quotas:MaxNodesPerMethodCall` methods + (default 1000; the SDK default 0 was unlimited; 0 restores it). The host answers an ask still queued past its asker's + deadline without touching the engine and without remembering it, so its broadcast copy (which the peer also received — + the asker had reported OutcomeUnknown) is what applies; late work cannot pile up behind a stalled store. + Measured through one host with the production LocalDb store (`ScriptedAlarmCommandThroughputTests`): 300 sequential + acks in 59 ms (max 11 ms each); 300 AddComments with 64 outstanding at once in 49 ms (max 24 ms each). + +| Engine verdict | Method status | +|---|---| +| applied (incl. an idempotent no-op) | `Good` | +| refused — last load failed, alarm not loaded on this node (incl. the window after a host supervision restart before its reload), malformed command, no engine on this node | `BadInvalidState` (node reverted; the peer never received it) | +| no answer within min(5 s, request deadline − 250 ms), or the engine op timed out / failed in the store | `BadTimeout` / `BadInternalError`, diagnostic "OutcomeUnknown" — the command **may still apply**, never reported as refused | + +`BadInvalidState` is Part 4's general "object … uninitialized or in some other invalid state" code; Part 9's method result +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 applies its +broadcast copy independently once the local engine applied it (or did not answer); a locally refused command is never +broadcast, so no engine anywhere applied it and the revert plus the definite failure are true pair-wide. A remote +gRPC-data `CallConditionMethod` on a scripted condition carries the same verdict (`ExecuteConditionMethodAsync`): applied ⇒ +`DriverConfirmedSuccess`, refused after dispatch ⇒ `DriverConfirmedFailure`, no answer ⇒ `OutcomeUnknown`. + +**Behaviour change (review r2 L5).** A scripted method is now REFUSED (`BadInvalidState`), reverted, and NOT broadcast to +the redundant peer when this node has no scripted-alarm host (no condition-state store, or the host not yet spawned) or the +host does not own the alarm — including the window after a host supervision restart before its configuration is re-sent. +Before #937 such a call returned Good and the broadcast let the peer apply it. + +**Revert guard.** A refusal reverts the node only when its per-condition mutation counter (bumped by every projection, +every reported condition event and every accepted method) is unchanged since the method — a field comparison missed a +Timed→Timed re-shelve or a ClientUserId change. The captured raw severity is restored as captured. + +**Residual.** Only the pre-check stops the SDK from applying the node change, so a refusal that arrives through the ask +shows subscribers two events: the method's, then the corrective one. An OutcomeUnknown leaves the node changed (the engine +may still apply it). A command racing the engine's first load queues behind it rather than failing. +**Not covered:** the AdminUI `/alerts` buttons are still fire-and-forget across the central→node transport (they report +"Ack sent", not "applied"). + `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/docs/plans/evidence/followups/937.md b/docs/plans/evidence/followups/937.md new file mode 100644 index 000000000..b6b9280cb --- /dev/null +++ b/docs/plans/evidence/followups/937.md @@ -0,0 +1,106 @@ +# #937 — a rejected scripted-alarm command is reported Good to the caller + +Follow-up to #935. After a failed scripted-alarm load the engine rejects operator commands +(`ScriptedAlarmCommandRejectedException`), but the `alarm-commands` topic is fire-and-forget, so the OPC UA Part 9 method +(and a remote gRPC-data `CallConditionMethod`) had already returned Good. + +## What changed + +| Layer | Change | +|---|---| +| Pre-check | `ScriptedAlarmCommandReadinessView` (Runtime singleton) holds the host's latest completed load outcome. `HandleAlarmCommand` reads it (one volatile read, under `Lock`) after the role/ACL gate and the Warm-standby check: last load failed ⇒ `BadInvalidState`, nothing applied/routed/reported. | +| Bounded ask | `OtOpcUaNodeManager.CallAsync` (off `Lock`) runs each local request through `base.Call` alone with an `AsyncLocal` verdict slot. The handler only STARTS `AlarmCommandAsker` (non-blocking) and returns Good; the Call awaits the verdict after `Lock` is released. Applied ⇒ Good; NotApplied ⇒ `BadInvalidState`; no answer within min(5 s, deadline − 250 ms) ⇒ `BadTimeout` "OutcomeUnknown" (never "refused" — it may still apply). | +| Host | `OtOpcUaServerHostedService.AskScriptedAlarmCommand`: broadcast on `alarm-commands` for the redundant peer (unchanged semantics) + `DriverHostActor` → `ScriptedAlarmHostActor.ExecuteAlarmCommand` on the LOCAL engine. Fresh `AlarmCommand.CommandId` (additive, wire-compatible) ⇒ the local host applies the ask/broadcast copies once (bounded 1024-entry memo). Ownership = latest plan set ∪ engine set (stable across an in-flight / failed load). | +| A2b origin | `IOriginConditionSource.ExecuteConditionMethodAsync` (DIM default = the sync verdict). `LocalDataServices` maps a post-dispatch refusal ⇒ `DriverConfirmedFailure`, no answer ⇒ `OutcomeUnknown`. | +| Redundancy | The verdict is the local engine's (it projects the local node). The peer applies its broadcast copy independently, as before. | + +Status choice: Part 9's method result codes do not cover "the state owner cannot act"; Part 4 `Bad_InvalidState` ("object … +uninitialized or in some other invalid state") does, and the server already uses it for a native ack off-Primary. + +## Residual / not covered + +- A refusal that arrives through the ask (a load in flight when the command queued, which then failed) leaves the SDK-applied + node change (and its one event) until the next good deploy re-asserts the node; the caller gets `BadInvalidState`. +- AdminUI `/alerts` buttons remain fire-and-forget across the central→node transport (DPS fan or one gRPC `Execute` per + node, `ExecuteAck` = "handed to the comm actor") — follow-up. +- Accepted (#935) trade-off, documented: one transient failed deploy = one duplicate activation per still-true alarm. + +## Red / green + +| Test | Red | +|---|---| +| `ScriptedCommandVerdictWireTests` (OpcUaServer.IntegrationTests, 9 incl. the native AddComment exemption; the original 8: refusal ×4 methods, applied + one event, timeout, preflight + sentinel + positive control, remote `ExecuteConditionMethodAsync`) | 8/8 red with the pre-check and the ask disabled in `HandleAlarmCommand` (every call Good) | +| `ScriptedAlarmCommandVerdictTests` (Runtime.Tests, 4) | dedupe theory 2/2 red with the `CommandId` memo disabled; the rest are new API | +| `GrpcDataConditionMethodTests.A_scripted_engine_verdict_after_dispatch_…` | new outcome fields | + +## Gates + +| Gate | Result | +|---|---| +| `dotnet build -c Release` (solution) | 0 warnings / 0 errors | +| OpcUaServer.Tests | 1460 passed, 2 skipped (after `e45012b69`) | +| OpcUaServer.IntegrationTests | 433 passed, 39 skipped (after `e45012b69`) | +| Runtime.Tests | 2097 passed, 3 skipped | +| Host.Tests (incl. `GrpcDataV1CompatibilityTests`) | 497 passed | +| Commons.Tests / Core.ScriptedAlarms.Tests | 512 / 146 passed | +| grpc-data python `tests/test_scenarios.py` | 31 passed | + +## Live leg + +`scripts/validation/grpc-data` conditions profile, new scenario **F937** (`conditions_scenarios.py --only F937`) plus the +seeder mutation `scripted_predicate` (replaces ScalarHigh's predicate; compile is not deploy-gated, so an uncompilable source +deploys and fails the SOURCE engine's load). + +F937: raise ScalarHigh (origin + consumer Active/Unacked) → deploy an uncompilable predicate (origin log: `engine LoadAsync +failed … operator commands are refused`) → Client.CLI on the origin: `ack` ⇒ `Acknowledge failed: BadInvalidState +[0x80AF0000]`, `shelve -k OneShot` ⇒ `BadInvalidState`; Client.CLI `ack` on the CONSUMER's imported condition (remote A2b) ⇒ +`BadInvalidState` (the origin's pre-check, via `ExecuteConditionMethodAsync`) → redeploy the good predicate (`ScriptedAlarmHost: re-asserted`) → +origin `ack` ⇒ `Acknowledge successful` (positive control). + +| Run | Revision | Result | +|---|---|---| +| `fu937-1` | `4d41e6185` | F937 functional checks all PASS (one check failed on a wrong log needle — the engine's "loaded" line rides the script-log topic; fixed to the host's re-assert line, rerun PASS). Regression A01/A04/A05/A08 PASS, **A02 FAIL `comment_good`**: a NATIVE condition's AddComment shares `HandleAlarmCommand` and was sent to the scripted host ⇒ `BadInvalidState`. Fixed in `e45012b69` (native AddComment skips the pre-check and the ask) + wire test `A_native_AddComment_is_not_subject_to_the_scripted_verdict` (red with the fix reverted). | +| `fu937-2` | `e45012b69` | **F937 + A01, A02, A04, A05, A08: 6/6 PASS**; rig down. | + + +## Review round 1 + +| # | Finding | Outcome | Red on revert | +|---|---|---|---| +| 1 | A post-dispatch NotApplied only rewrote the status: the SDK had applied + reported the change (in-flight load, host restart window, no host, removed alarm, blank comment, batch Confirm after a refused Ack) | **Fixed.** `ReportAfterMethod` captures the pre-call state inside a verdict slot; a refusal re-takes `Lock` and restores it with one corrective event (skipped if the node changed since — newer truth wins), mirroring #760. Blank scripted AddComment ⇒ `BadInvalidArgument` in the handler, before the SDK. (A plan-disabled alarm has no condition node — `AddressSpaceApplier` skips it — so the Part 9 Enable case cannot arise.) | `A_command_the_engine_refuses_returns_BadInvalidState` (now 8 methods, asserts the corrective event restores Acked/Confirmed/Enabled/Shelving/Comment/Retain) + `A_mixed_batch_…`: 9 red with the revert disabled | +| 2 | Broadcast BEFORE the local ask: the peer could apply what the caller was told failed (LWW brings it back) | **Fixed.** `ScriptedAlarmCommandDispatch.AskThenBroadcastAsync`: local verdict first; broadcast only on Applied / OutcomeUnknown (an unknown may still apply locally, so the peer must not be left behind). A refusal reached no engine ⇒ the revert and the definite failure are true pair-wide. | `ScriptedAlarmCommandDispatchTests` (4, new seam) | +| 3 | `EnsureLoaded()` before `_evalGate` ⇒ a command racing the first load threw InvalidOperationException ⇒ OutcomeUnknown | **Fixed.** The check is gone; under the gate `!_generationComplete` covers never-loaded (definite `ScriptedAlarmCommandRejectedException`), and a command racing the first load queues behind it and applies. | `A_command_racing_the_first_load_applies_after_it`: red with a pre-gate not-loaded throw restored | +| 4 | One host mailbox + SQLite per command; ack-all tail past 5 s; no in-flight cap | **Fixed + measured.** SDK 2.0.1 `StandardServer.CallAsync` awaits `MasterNodeManager.CallAsync` (decompiled state machine `d__123`), so no request thread is held. One Call's requests are settled sequentially; each request's bound starts when its ask is sent; ≤ 64 asks in flight node-wide, else `BadTooManyOperations` before anything applies. `ScriptedAlarmCommandThroughputTests` (one host, production LocalDb store with replication capture): **300 sequential acks 59 ms total (p50 0.1 ms, max 11.3 ms); 300 AddComments with 64 outstanding 49 ms total (p50 9.2 ms, max 24.3 ms)** — 200× inside the bound. | `Past_the_in_flight_cap_and_for_a_blank_comment_…` | +| 5 | Mixed-batch wire test | **Added** `A_mixed_batch_gets_per_item_status_in_order`: scripted Ack (refused) + native Ack + imported Ack + scripted AddComment (applied) + `Server.GetMonitoredItems` (core manager): statuses `[BadInvalidState, Good, Good, Good, BadSubscriptionIdInvalid]` in order, scripted asks in order with max concurrency 1, refused Ack reverted, native stands, in-flight 0. | — | +| L6 | Readiness inferred "failed" from the task fault | **Fixed.** `ScriptedAlarmEngine.HasCompleteGeneration` (volatile) is published on a load fault. | — | +| L7 | AsyncLocal slot captured by SDK timers | **Fixed** without `SuppressFlow` (which would also strip Activity/log scopes from SDK work): the slot is `Closed` the moment its SDK call returns, so a captured copy can never park an ask. | — | +| L10 | Remote bound floor stretched past `RemainingBudget` | **Fixed.** A budget below the 250 ms dispatch floor is refused unsent (`BadTimeout`, not dispatched). | — | + +### Gates (at `6004a5a56`) + +| Gate | Result | +|---|---| +| `dotnet build -c Release` | 0 warnings / 0 errors | +| OpcUaServer.Tests | 1460 passed, 2 skipped | +| OpcUaServer.IntegrationTests | 439 passed, 39 skipped (a first run concurrent with the live rig build failed 1 unrelated `ProjectedEventDeliveryWireTests` case — event delivery, no Call path; it passed in isolation 3/3 and in the full rerun; cause NOT established) | +| Runtime.Tests | 2121 passed, 3 skipped (a first run concurrent with the live rig build failed 1 unrelated `GrpcDataConfiguredDiscoveryWireTests` case — data-read failover, no condition-method path; it passed 2/2 class reruns and the full rerun; cause NOT established) | +| Host.Tests (incl. `GrpcDataV1CompatibilityTests`) | 503 passed | +| Commons.Tests / Core.ScriptedAlarms.Tests | 513 / 147 passed | +| Live `fu937-3` (`6004a5a56`) | F937 + A01 + A02 3/3 PASS; rig down | + +## Review round 2 + +| # | Finding | Outcome | Red on revert | +|---|---|---|---| +| M1 | Each request floored at 50 ms ⇒ past the deadline every remaining request still applied/asked; TimeoutHint 0 × wedged engine ≈ 5 s per method | **Fixed.** Deadline (− 250 ms grace) leaving < the 250 ms dispatch floor ⇒ the scripted handler refuses `BadTimeout` unsent (the SDK applies nothing); after the first timed-out OutcomeUnknown in a batch the rest of its scripted methods are refused the same way (non-scripted still run). New quota `OpcUa:Quotas:MaxNodesPerMethodCall` = 1000 (SDK default 0 = unlimited; 0 restores it). | `A_too_close_deadline_or_an_earlier_unanswered_command_refuses_scripted_methods_unsent` red with the floor/poison removed; quota pinned in `OpcUaApplicationHostQuotaTests` | +| M2 | Cap released on Ask timeout while the command stays queued in the host ⇒ unbounded late work | **Fixed.** `ExecuteAlarmCommand.DeadlineUtc`; an expired ask is answered without touching the engine and NOT remembered, so its broadcast copy (already sent on Unknown) applies. Answered OutcomeUnknown rather than NotApplied: the broadcast copy may still apply here, so "not applied" would be untrue (nobody is waiting for it anyway). | `An_expired_ask_skips_the_engine_and_leaves_the_broadcast_copy_to_apply` red with the check removed | +| L1 | Revert guard compared delta + comment | **Fixed.** Per-instance mutation counter (`ConditionalWeakTable`), bumped in `ApplyConditionState`, `ReportConditionEvent` and on every accepted method in `ReportAfterMethod`. | `A_refusal_does_not_revert_a_node_changed_since_the_method` (identical re-projection) red with the guard removed | +| L5 | Behaviour change undocumented | `docs/ScriptedAlarms.md`: no local host / not owned (incl. the post-supervision-restart window) ⇒ refused + reverted + no peer broadcast. | docs | +| nits | stale hosted-service comment; severity 0 ⇒ 1 on revert | Fixed (comment says ask-then-broadcast; the raw captured severity is restored). | — | +| SDK check | Does any Part 9 handler call our delegate before its own validation? | **No** (decompiled SDK 2.0.1): Acknowledge/Confirm/AddComment run the delegate at the END of `ProcessBefore*` (after EventId/Enabled/already-acked/IsLive); the three shelve methods after Enabled + `IsCausePermitted` (+ shelving-time range); Enable/Disable after the already-enabled checks. Nothing after a Good delegate can turn the call Bad, so a started ask is always awaited. (Branch acks would recurse into a branch's own delegate — this server creates no branches.) | — | + +Follow-ups (not fixed): **L2** a late refusal that arrives after the ask's timeout (the caller got OutcomeUnknown) is never reverted; **L3** a command cancelled while waiting on `_evalGate` (nothing applied) is reported OutcomeUnknown, not NotApplied; **L4** `OnLoadFailed` reads `HasCompleteGeneration` while a newer load may already be running (transiently refuses during that load). + +Gates (round 2): build 0 warnings / 0 errors; OpcUaServer.Tests 1460 passed / 2 skipped; OpcUaServer.IntegrationTests 441 / 39 skipped; +Runtime.Tests 2122 / 3 skipped; Host.Tests 503; Commons.Tests 513; Core.ScriptedAlarms.Tests 147. No live re-run (the dispatch +order is unchanged; the new refusals are pre-dispatch and the expiry skip is host-local). diff --git a/scripts/validation/grpc-data/conditions_scenarios.py b/scripts/validation/grpc-data/conditions_scenarios.py index 903aa4bd8..899860156 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", "A09") -TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720, "A09": 600} +SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "F937") +TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720, "A09": 600, "F937": 900} REVERT_LOG = "did not reach the alarm system" REFRESH_REQUIRED = "RefreshRequiredEventType" _LOG_TIME = re.compile(r"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?)") @@ -511,6 +511,66 @@ 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) + # The engine's own "loaded" line rides the script-log topic; the host's re-assert of the still-active condition is on stdout. + loaded = wait_for(lambda: self.log_lines(source, restored_at, "ScriptedAlarmHost: re-asserted"), 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) + # ---- lmxopcua#927 ------------------------------------------------------------------------------------------------- def scenario_A09(self): """A remote (A2b CallConditionMethod) ack of the NATIVE EastTankYellow, under the connection's service principal, that diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs index 255304968..6378e106d 100644 --- a/scripts/validation/grpc-data/seed/Program.cs +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -192,7 +192,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(); @@ -214,6 +214,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/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs index b55e6538f..796e16953 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs @@ -215,7 +215,6 @@ public sealed class ScriptedAlarmEngine : IDisposable private readonly List _upstreamSubscriptions = []; private readonly SemaphoreSlim _evalGate = new(1, 1); private Timer? _shelvingTimer; - private bool _loaded; /// /// #935: whether holds a COMPLETED generation — set at the end of a successful @@ -230,6 +229,12 @@ public sealed class ScriptedAlarmEngine : IDisposable /// private bool _generationComplete; + /// + /// #937: whether the engine currently holds a COMPLETED generation (operator commands are accepted). A lock-free + /// read of the flag _evalGate guards: false while a load is in flight and after a failed one. + /// + public bool HasCompleteGeneration => Volatile.Read(ref _generationComplete); + // volatile: written by Dispose and read unsynchronized from every background // path (LoadAsync's guard, OnUpstreamChange, the drain loop, ReevaluateAsync / // ShelvingCheckAsync's post-gate re-checks, TrackBackgroundTask's registration @@ -402,7 +407,7 @@ public sealed class ScriptedAlarmEngine : IDisposable carryOver = new Dictionary(_alarms.Count, StringComparer.Ordinal); foreach (var (alarmId, prior) in _alarms) carryOver[alarmId] = prior.Condition; } - _generationComplete = false; + Volatile.Write(ref _generationComplete, false); UnsubscribeFromUpstream(); _alarms.Clear(); @@ -484,9 +489,9 @@ public sealed class ScriptedAlarmEngine : IDisposable // Seed the value cache with current tag values before subscribing. The // ReadTag calls happen first so that the initial predicate evaluation below // (startup recovery) uses a consistent snapshot. - // Subscriptions are established AFTER _loaded = true so that any synchronous + // Subscriptions are established AFTER the generation completes so that any synchronous // initial-push an ITagUpstreamSource delivers from inside SubscribeTag arrives - // when _alarms is fully initialised. Before _loaded = true, a synchronous push + // when _alarms is fully initialised. Before then, a synchronous push // would race the in-progress state restore and could overwrite the carefully // seeded cache with a push that has no defined ordering relative to ReadTag. foreach (var path in _alarmsReferencing.Keys) @@ -531,10 +536,9 @@ public sealed class ScriptedAlarmEngine : IDisposable } } - _loaded = true; - _generationComplete = true; + Volatile.Write(ref _generationComplete, true); - // Subscribe after _loaded = true and full state restore. If an upstream + // Subscribe after the generation completed and full state restore. If an upstream // implementation pushes its initial value synchronously from inside // SubscribeTag, OnUpstreamChange will queue a ReevaluateAsync that acquires // _evalGate — it will correctly block until LoadAsync releases the gate, then @@ -740,12 +744,13 @@ public sealed class ScriptedAlarmEngine : IDisposable private async Task ApplyAsync(string alarmId, CancellationToken ct, Func op) { - EnsureLoaded(); - ScriptedAlarmEvent? pending = null; await _evalGate.WaitAsync(ct).ConfigureAwait(false); try { + // #937 review: no separate "not loaded" check before the gate any more — a command racing the FIRST load used + // to throw InvalidOperationException there (the host could only classify it as unknown). It now queues behind + // the load; never loaded ⇒ no completed generation ⇒ the refusal below (nothing applied). // #935 review S1: look the alarm up only once the gate is held. Looked up before it, a command racing a // LoadAsync captured either the old generation's entry (and wrote its state over the new one) or the // load's interim Fresh entry (and, an ack being a no-op on Fresh, saved Fresh over the carried Active @@ -1784,12 +1789,6 @@ public sealed class ScriptedAlarmEngine : IDisposable _upstreamSubscriptions.Clear(); } - private void EnsureLoaded() - { - if (!_loaded) throw new InvalidOperationException( - "ScriptedAlarmEngine not loaded. Call LoadAsync first."); - } - /// Disposes the engine, cleaning up resources and waiting for in-flight background tasks. public void Dispose() { 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..4dd46ca08 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,15 @@ 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 asks the local engine (via the DriverHostActor) + // for its verdict FIRST and broadcasts to the redundant peer only after an applied / unknown verdict + // (ScriptedAlarmCommandDispatch). 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 +604,23 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl _loggerFactory.CreateLogger()); } + /// + /// #937: the node manager's — see + /// . Runs under the SDK's Lock: it only sends. + /// + /// The command (with its CommandId). + /// The caller's bound. + /// The verdict. + private Task AskScriptedAlarmCommand(AlarmCommand cmd, TimeSpan timeout) + { + Func>? askLocal = _actorRegistry.TryGet(out var driverHost) + ? (c, t) => driverHost.Ask(new ScriptedAlarmHostActor.ExecuteAlarmCommand(c, DateTime.UtcNow + t), t) + : null; + return ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(cmd, timeout, askLocal, + c => DistributedPubSub.Get(_actorSystemAccessor()).Mediator.Tell(new Publish(ScriptedAlarmHostActor.AlarmCommandsTopic, c)), + _logger); + } + /// /// Stops the OPC UA server asynchronously: detaches every sink, then STOPS the SDK so the port closes. /// @@ -635,6 +664,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.Host/OpcUa/ScriptedAlarmCommandDispatch.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/ScriptedAlarmCommandDispatch.cs new file mode 100644 index 000000000..8ca6f4124 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/ScriptedAlarmCommandDispatch.cs @@ -0,0 +1,79 @@ +using Akka.Actor; +using Microsoft.Extensions.Logging; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; + +namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa; + +/// +/// #937: how an OPC UA Part 9 method on a scripted condition reaches the engines — this node's first, the redundant peer's +/// only after this node's engine applied it (or did not answer). +/// +/// +/// +/// Why the peer goes second (review r1). Broadcasting first let the peer apply a command the local engine then +/// refused: the caller was told a definite failure, the local node was reverted, and the peer's save came back to this +/// node through the last-writer-wins condition-state replication. Asking first makes a refusal true pair-wide +/// (no engine saw the command) — which is what lets the node manager revert the node and answer +/// BadInvalidState. An applied or unknown verdict is broadcast so the peer converges exactly as before (an +/// unknown local outcome may still apply locally, so the peer must not be left behind). +/// +/// +/// No local engine (no driver host, or it runs no scripted-alarm host) ⇒ +/// and nothing is broadcast: this node's condition node is driven by no engine, and a command for it is refused. +/// +/// +internal static class ScriptedAlarmCommandDispatch +{ + /// + /// Asks the local engine, then broadcasts unless it refused. Starts the ask synchronously (safe under the SDK's Lock); + /// never faults — no answer within is an OutcomeUnknown outcome. + /// + /// The command (with its CommandId, which de-duplicates the broadcast copy on the local host). + /// The caller's bound. + /// The ask to this node's scripted-alarm host; null ⇒ none on this node. + /// Publishes the command on the alarm-commands topic. + /// Logger. + /// The local verdict. + internal static async Task AskThenBroadcastAsync(AlarmCommand cmd, TimeSpan timeout, + Func>? askLocal, Action broadcast, ILogger logger) + { + if (askLocal is null) + { + return new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, + "This server runs no scripted-alarm engine; the command was not applied."); + } + + AlarmCommandOutcome outcome; + try + { + outcome = await askLocal(cmd, timeout).ConfigureAwait(false); + } + catch (Exception ex) when (ex is AskTimeoutException or TaskCanceledException or TimeoutException) + { + outcome = new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown, + $"OutcomeUnknown: the scripted-alarm engine did not answer within {timeout.TotalSeconds:0.#} s; the command may still apply.", + TimedOut: true); + } + catch (Exception ex) + { + outcome = new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown, + "OutcomeUnknown: " + ex.GetType().Name); + } + + if (outcome.Verdict != AlarmCommandVerdict.NotApplied) + { + try + { + broadcast(cmd); + } + catch (Exception ex) + { + // The peer's copy only; the caller's answer is the local verdict. + logger.LogWarning(ex, "Failed to broadcast alarm command {Operation} for {AlarmId} to the redundant peer", + cmd.Operation, cmd.AlarmId); + } + } + + return outcome; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs index 5ded216f2..a5b900955 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs @@ -98,8 +98,10 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager /// /// §5.6 step 1: (a) claim every unprocessed request whose ObjectId is in mapped/conditions — a namespace-index - /// test, no lock; (b) the unchanged synchronous base.Call for everything else (it skips claimed requests), run - /// and completed before any remote await; (c) the claimed calls concurrently, bounded by the per-node semaphore. + /// test, no lock; (b) the synchronous base.Call for everything else (it skips claimed requests), run and + /// completed before any remote await — per request, plus the scripted-alarm engine's verdict awaited off Lock, + /// when an is wired (#937, ); (c) the claimed calls + /// concurrently, bounded by the per-node semaphore. /// No Lock is held by this method at any point. Review S1: nothing after base.Call throws — local items are /// already applied by then, so a fault there must become a per-item status, never a ServiceFault for the batch. /// @@ -115,7 +117,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 +134,50 @@ 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 ask is then settled with no Lock held (its verdict becomes the request's + /// status; a refusal reverts the node) before the next request runs. SDK 2.0.1's StandardServer.CallAsync + /// awaits MasterNodeManager.CallAsync (no request thread is held while this waits). 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; + } + + // #937 review r1: one request at a time, each verdict (and any revert) settled before the next request runs, so a + // later request in the batch (e.g. Confirm after a refused Acknowledge) never runs against a node state the engine + // refused. The bound is taken per request, when its ask is sent. + // Review r2 M1: past the request deadline (less the dispatch floor) a scripted method is refused unsent in its + // handler — before the SDK applies anything — and so is every scripted method after the first one of this batch + // that got no answer (a wedged engine would otherwise cost one full bound per remaining request). Non-scripted + // requests in the batch still run. + ServiceResult? poisoned = null; + for (var i = 0; i < methodsToCall.Count; i++) + { + if (methodsToCall[i] is not { Processed: false }) continue; + var bound = ScriptedCommandBound(context.OperationDeadline); + var refusal = poisoned ?? (bound is null + ? new ServiceResult(StatusCodes.BadTimeout, + new LocalizedText("The request deadline leaves no time for the scripted-alarm engine; the command was not sent.")) + : null); + if (CallOneAwaitingVerdict(context, methodsToCall, i, results, errors, bound ?? TimeSpan.Zero, refusal) is not { } pending) + continue; + var (status, unknown) = await SettleScriptedVerdictAsync(pending, bound ?? TimeSpan.Zero).ConfigureAwait(false); + if (!ServiceResult.IsGood(status)) errors[i] = status; + if (unknown && status.StatusCode.Code == StatusCodes.BadTimeout.Code) + poisoned = new ServiceResult(StatusCodes.BadTimeout, + new LocalizedText("An earlier scripted-alarm command in this request got no answer; this one was not sent.")); + } + } + /// 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/OpcUaApplicationHost.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OpcUaApplicationHost.cs index e22f65fed..b123e9d29 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OpcUaApplicationHost.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OpcUaApplicationHost.cs @@ -271,6 +271,14 @@ public sealed class OpcUaQuotaOptions /// burst ceiling review 01 P6 flagged. public int MaxQueuedRequestCount { get; set; } = 200; + /// + /// Most methods one Call request may carry (advertised as OperationLimits/MaxNodesPerMethodCall; a larger + /// request is refused BadTooManyOperations by the SDK). Default 1000 — the SDK default is 0 = unlimited, and + /// #937 settles a batch's scripted-alarm methods one at a time against the engine, so an unbounded batch is an + /// unbounded request. 0 = unlimited. + /// + public uint MaxNodesPerMethodCall { get; set; } = 1000; + /// Per-operation timeout in milliseconds; null keeps the SDK default. public int? OperationTimeoutMs { get; set; } @@ -860,6 +868,8 @@ public sealed class OpcUaApplicationHost : IAsyncDisposable serverConfig.MinRequestThreadCount = quotas.MinRequestThreadCount; serverConfig.MaxRequestThreadCount = quotas.MaxRequestThreadCount; serverConfig.MaxQueuedRequestCount = quotas.MaxQueuedRequestCount; + serverConfig.OperationLimits ??= new OperationLimits(); + serverConfig.OperationLimits.MaxNodesPerMethodCall = quotas.MaxNodesPerMethodCall; } /// 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..a8efd90b4 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ScriptedCommandVerdict.cs @@ -0,0 +1,350 @@ +using Microsoft.Extensions.Logging; +using Opc.Ua; +using Opc.Ua.Server; +using System.Runtime.CompilerServices; +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) settles the verdict once the SDK released +/// Lock: a refusal becomes BadInvalidState AND reverts the node to its pre-call state with one +/// corrective event (review r1 — subscribers and gRPC-data consumers had seen the change); no answer becomes +/// BadTimeout (OutcomeUnknown — the node keeps the change, which the engine may still apply). +/// +/// +/// Consistency with the peer. The host broadcasts the command to the redundant peer only AFTER the local engine +/// applied it (or did not answer). A refused command therefore reached no engine anywhere, which is what makes the +/// revert and the definite BadInvalidState true. +/// +/// +/// Load bound. At most asks are outstanding node-wide; past it the +/// call is refused BadTooManyOperations before the SDK applies anything. One Call's requests are settled one at +/// a time, and each request's bound starts when its ask is sent, so a batch never times out its own tail. +/// +/// +/// 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. +/// +/// +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); + + /// The default node-wide cap on outstanding scripted-command asks. + internal const int DefaultMaxScriptedCommandsInFlight = 64; + + + private static readonly AsyncLocal PendingScriptedCommandSlot = new(); + + private int _scriptedCommandsInFlight; + + /// + /// #937 review r2 L1: a per-condition-instance mutation counter, bumped (under Lock) by every projection, every + /// reported condition event and every accepted method — the proof a pending revert needs that nothing changed the + /// node since its method. A field comparison missed changes that leave every compared field equal (a Timed→Timed + /// re-shelve, a ClientUserId change). Keyed by instance, so a torn-down condition takes its counter with it. + /// + private readonly System.Runtime.CompilerServices.ConditionalWeakTable> _conditionMutations = new(); + + /// Counts one mutation of . Caller holds Lock. + private void BumpConditionMutation(AlarmConditionState condition) => _conditionMutations.GetOrCreateValue(condition).Value++; + + /// The mutation count of . Caller holds Lock. + private long ConditionMutationOf(AlarmConditionState condition) => _conditionMutations.GetOrCreateValue(condition).Value; + + /// + /// #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 + /// broadcasts it to the redundant peer once the local engine applied it). Called under Lock: it MUST only send + /// and return the pending task, and the task must complete (the timeout argument is the caller's bound). Null ⇒ the + /// fire-and-forget 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 node-wide cap on outstanding scripted-command asks (past it: BadTooManyOperations, nothing applied). + internal int MaxScriptedCommandsInFlight { get; set; } = DefaultMaxScriptedCommandsInFlight; + + /// Outstanding scripted-command asks (test/diagnostic observation). + internal int ScriptedCommandsInFlight => Volatile.Read(ref _scriptedCommandsInFlight); + + /// + /// The verdict slot of ONE Call request (installed only around that request's synchronous SDK call). + /// is set the moment that call returns: an AsyncLocal value is captured by anything the SDK starts inside it (a + /// TimedShelve's timer), so a later callback must find the slot closed rather than park an ask nobody awaits. + /// + private sealed class PendingScriptedCommand(TimeSpan timeout, ServiceResult? refusal = null) + { + public TimeSpan Timeout { get; } = timeout; + /// Set ⇒ a scripted method in this request is refused with it in the handler, unsent and unapplied + /// (review r2 M1: the request deadline is too close, or an earlier scripted method of the batch got no answer). + public ServiceResult? Refusal { get; } = refusal; + public Task? Outcome { get; set; } + public ScriptedMethodRevert? Revert { get; set; } + public volatile bool Closed; + } + + /// + /// What a scripted method changed on the node, captured by ReportAfterMethod: the pre-call state to put back if + /// the engine refuses, and the post-call state that proves nothing else has changed the node since. + /// + private sealed record ScriptedMethodRevert(RealmKey Key, AlarmConditionState Alarm, AlarmConditionSnapshot Before, + ushort BeforeSeverity, LocalizedText? BeforeComment, string? BeforeClientUserId, long AfterMutation); + + /// The slot of the request being called on this flow, when it is still open. + private static PendingScriptedCommand? OpenScriptedSlot() => PendingScriptedCommandSlot.Value is { Closed: false } slot ? slot : null; + + /// + /// From (under Lock): when the current Call awaits a verdict, reserve an + /// in-flight slot and start the ask. Null ⇒ not inside such a call (route fire-and-forget); a Bad result ⇒ refused + /// before anything was sent or applied. + /// + private ServiceResult? TryStartScriptedCommandAsk(AlarmCommand cmd) + { + if (OpenScriptedSlot() is not { Outcome: null } pending || AlarmCommandAsker is not { } asker) return null; + if (pending.Refusal is { } refused) return refused; + if (Interlocked.Increment(ref _scriptedCommandsInFlight) > MaxScriptedCommandsInFlight) + { + Interlocked.Decrement(ref _scriptedCommandsInFlight); + return new ServiceResult(StatusCodes.BadTooManyOperations, + new LocalizedText("Too many scripted-alarm commands are in progress on this server; the command was not applied.")); + } + + Task outcome; + try + { + 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. + outcome = Task.FromException(ex); + } + // The slot is held until the ask itself completes (the asker's own bound), not just until the caller stops waiting. + outcome.ContinueWith(static (_, state) => Interlocked.Decrement(ref ((OtOpcUaNodeManager)state!)._scriptedCommandsInFlight), this, + CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + pending.Outcome = outcome; + return ServiceResult.Good; + } + + /// + /// From ReportAfterMethod, under Lock, before the SDK handler runs: the state a refusal would restore — + /// only while a verdict slot is open (nothing is captured on the fire-and-forget path). + /// + private Func? BeginScriptedMethodCapture(AlarmConditionState alarm, RealmKey key) + { + if (OpenScriptedSlot() is null) return null; + var delta = ReadConditionDelta(alarm); + var before = new AlarmConditionSnapshot(delta.Active, delta.Acknowledged, delta.Confirmed, delta.Enabled, delta.Shelving, + delta.MappedSeverity, delta.Message, delta.Quality.Code, + delta.Shelving == AlarmShelvingKind.Timed && _conditionUnshelveAt.TryGetValue(key, out var unshelveAt) ? unshelveAt : null); + var comment = alarm.Comment?.Value; + var clientUserId = alarm.ClientUserId?.Value; + var severity = alarm.Severity?.Value ?? (ushort)0; + return () => new ScriptedMethodRevert(key, alarm, before, severity, comment, clientUserId, ConditionMutationOf(alarm)); + } + + /// From ReportAfterMethod, under Lock, after a Good method applied and reported: park the revert + /// with the ask the handler started for this request. + private static void CompleteScriptedMethodCapture(Func? capture) + { + if (capture is null || OpenScriptedSlot() is not { Outcome: not null, Revert: null } pending) return; + pending.Revert = capture(); + } + + /// + /// Puts the node back to its pre-call state with one corrective event, under Lock — only when the node is still + /// the instance called AND still exactly as the method left it (anything that changed it since is newer truth and + /// wins). Mirrors the #760 native-ack revert. + /// + private void RevertScriptedMethod(ScriptedMethodRevert revert) + { + lock (Lock) + { + if (!_alarmConditions.TryGetValue(revert.Key, out var live) || !ReferenceEquals(live, revert.Alarm) + || ConditionMutationOf(live) != revert.AfterMutation) + { + _logger.LogInformation( + "OtOpcUaNodeManager: refused scripted command on {Condition} not reverted — the condition changed since the call", + revert.Key.Id); + return; + } + + var now = UtcNow; + if (revert.Before.Shelving == AlarmShelvingKind.Timed && revert.Before.UnshelveAtUtc is { } unshelveAt) + _conditionUnshelveAt[revert.Key] = unshelveAt; + else _conditionUnshelveAt.Remove(revert.Key); + ApplyConditionState(live, revert.Before, now); + // The raw captured severity: ApplyConditionState clamps to 1..1000, which would turn a 0 into 1. + if (live.Severity is not null && live.Severity.Value != revert.BeforeSeverity) live.Severity.Value = revert.BeforeSeverity; + if (live.Comment is not null) live.Comment.Value = revert.BeforeComment ?? LocalizedText.Null; + if (live.ClientUserId is not null) live.ClientUserId.Value = revert.BeforeClientUserId ?? string.Empty; + ReportConditionEvent(live, now); + } + } + + /// + /// The bound for one local request: , cut by the request deadline (less a grace, so + /// the answer still lands inside the client's TimeoutHint). Null ⇒ the deadline leaves less than the dispatch floor: + /// a scripted method in this request must be refused unsent (review r2 M1 — it used to be floored and sent anyway). + /// + 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 ? null : bound; + } + + /// + /// Runs the SDK's synchronous base.Call for ONE request with a verdict slot installed, and returns the slot when + /// the handler parked an ask in it (null when it routed nothing: a refusal, a native or non-condition method, or no + /// asker wired). + /// + private PendingScriptedCommand? CallOneAwaitingVerdict(OperationContext context, ArrayOf methodsToCall, int index, + IList results, IList errors, TimeSpan bound, ServiceResult? refusal) + { + var request = methodsToCall[index]; + var singleResults = new List { results[index] }; + var singleErrors = new List { errors[index] }; + var pending = new PendingScriptedCommand(bound, refusal); + PendingScriptedCommandSlot.Value = pending; + try + { + base.Call(context, (ArrayOf)new[] { request }, singleResults, singleErrors); + } + finally + { + pending.Closed = true; + PendingScriptedCommandSlot.Value = null; + } + if (!request.Processed) return null; // not this manager's node: left for the next manager, untouched + results[index] = singleResults[0]; + errors[index] = singleErrors[0]; + return pending.Outcome is not null && ServiceResult.IsGood(singleErrors[0]) ? pending : null; + } + + /// The request's final status from its engine verdict (and whether it is an OutcomeUnknown), reverting the node + /// on a refusal. Never throws. + private async Task<(ServiceResult Status, bool Unknown)> SettleScriptedVerdictAsync(PendingScriptedCommand pending, TimeSpan bound) + { + var (status, unknown) = await AwaitScriptedVerdictAsync(pending.Outcome!, bound).ConfigureAwait(false); + if (!ServiceResult.IsGood(status) && !unknown && pending.Revert is { } revert) + { + try + { + RevertScriptedMethod(revert); + } + catch (Exception ex) + { + _logger.LogError(ex, "OtOpcUaNodeManager: reverting a refused scripted command failed"); + } + } + return (status, unknown); + } + + /// + /// 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 settled (a refusal reverts the node) after it is + /// released, within (capped at , never extended past it). + /// + /// 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) + { + // Review r1 L10: a budget too short to dispatch in is refused unsent — never stretched past what the caller allows. + if (budget < ImportedMethodMinimumDispatchBudget) + return new OriginConditionMethodOutcome(false, false, StatusCodes.BadTimeout.Code, "Budget below the dispatch floor; nothing was sent."); + var bound = budget < ScriptedCommandTimeout ? budget : ScriptedCommandTimeout; + var pending = new PendingScriptedCommand(bound); + PendingScriptedCommandSlot.Value = pending; + OriginConditionMethodOutcome decided; + try + { + decided = TryExecuteConditionMethod(call); + } + finally + { + pending.Closed = true; + PendingScriptedCommandSlot.Value = null; + } + if (!decided.Applied || pending.Outcome is null) return decided; + + var (status, unknown) = await AwaitScriptedVerdictAsync(pending.Outcome, bound).ConfigureAwait(false); + if (ServiceResult.IsGood(status)) return decided; + if (!unknown && pending.Revert is { } revert) + { + try { RevertScriptedMethod(revert); } + catch (Exception ex) { _logger.LogError(ex, "OtOpcUaNodeManager: reverting a refused remote scripted command failed"); } + } + var text = status.LocalizedText.IsNullOrEmpty ? null : status.LocalizedText.Text; + return new OriginConditionMethodOutcome(false, decided.Native, status.StatusCode.Code, text, Dispatched: true, Unknown: unknown); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 2a43854c9..a3dac66b4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -1408,6 +1408,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// when the projection is a genuine change that must be reported as one event. private bool ApplyConditionState(AlarmConditionState condition, AlarmConditionSnapshot state, DateTime sourceTimestampUtc) { + BumpConditionMutation(condition); // #937 r2: any projection is a change a pending scripted revert must not undo var current = ReadConditionDelta(condition); var incoming = ToConditionDelta(state, condition); bool fire = ShouldFireConditionEvent(current, incoming); @@ -1585,6 +1586,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage { // Fresh GUID-bytes EventId per event — mandatory for Part 9 ack correlation (T17 relies on it). alarm.EventId!.Value = ByteString.From(Guid.NewGuid().ToByteArray()); + BumpConditionMutation(alarm); // #937 r2 + // Time/ReceiveTime were already set to sourceTimestampUtc by the WriteAlarmCondition projection // immediately above; the assignment here is a locality repeat (same value, no behavioral change) // so the restamp is co-located with the EventId and ClearChangeMasks in the same method. @@ -2649,7 +2652,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage ? new ServiceResult(StatusCodes.BadNotSupported) : HandleAlarmCommand(context, condition, "Confirm", comment, unshelveAt: null); alarm.OnAddComment = (context, condition, _, comment) => - HandleAlarmCommand(context, condition, "AddComment", comment, unshelveAt: null); + // A native AddComment is applied at the node only (no engine owns it): no scripted pre-check or verdict (#937). + HandleAlarmCommand(context, condition, "AddComment", comment, unshelveAt: null, + scriptedEngine: !IsNativeAlarmNode(alarmNodeId, realm)); alarm.OnShelve = (context, condition, shelving, oneShot, shelvingTime) => { if (IsNativeAlarmNode(alarmNodeId, realm)) return new ServiceResult(StatusCodes.BadNotSupported); @@ -3087,6 +3092,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage { var before = ReadConditionDelta(alarm); var retainBefore = alarm.Retain!.Value; + // #937: inside a verdict-awaiting Call, remember what a refusal must put back. + var revertCapture = BeginScriptedMethodCapture(alarm, conditionKey); var result = sdkHandler(); // A rebuild may have discarded this instance mid-call; its replacement is not what was called. @@ -3098,6 +3105,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage } apply?.Invoke(); + // #937 r2 L1: every accepted method is a mutation, reported or not (a Timed→Timed re-shelve by another + // session changes no delta field but must still stop an older call's revert). + BumpConditionMutation(alarm); if (isAcknowledge && alarm.ConfirmedState is not null) { @@ -3118,6 +3128,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage if (alwaysReport || ReadConditionDelta(alarm) != before) ReportConditionEvent(alarm, UtcNow); + CompleteScriptedMethodCapture(revertCapture); return result; } } @@ -3194,10 +3205,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// The Part 9 operation name (e.g. Acknowledge, TimedShelve). /// The call's comment text, or null when none was supplied. /// For TimedShelve, the computed UTC expiry; otherwise null. + /// #937: false for a NATIVE condition's AddComment (applied at the node; no engine owns it) — + /// no scripted pre-check, no verdict ask; the fire-and-forget router as before. /// ServiceResult.Good when allowed (the SDK then applies state, and the method path /// reports the one condition event);BadUserAccessDenied when the gate vetoes (no route, no state mutation). private ServiceResult HandleAlarmCommand( - ISystemContext context, ConditionState condition, string operation, LocalizedText? comment, DateTime? unshelveAt) + ISystemContext context, ConditionState condition, string operation, LocalizedText? comment, DateTime? unshelveAt, + bool scriptedEngine = true) { // Resolve the principal the SAME way the SDK's own GetCurrentUserId does, then narrow to the // role-carrying identity T17 attached. Anonymous / non-role-carrying identities ⇒ null ⇒ denied. @@ -3210,6 +3224,15 @@ 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 (scriptedEngine && ScriptedAlarmCommandPreflight?.Invoke() is { } notReady) + return new ServiceResult(StatusCodes.BadInvalidState, new LocalizedText(notReady)); + + // #937 review r1: a scripted comment the engine would refuse (blank text) is refused here, before the SDK writes it. + if (scriptedEngine && operation == "AddComment" && string.IsNullOrWhiteSpace(comment?.Text)) + return new ServiceResult(StatusCodes.BadInvalidArgument, new LocalizedText("AddComment requires comment text.")); + var cmd = new AlarmCommand( AlarmId: condition.NodeId.IdentifierAsString, Operation: operation, @@ -3217,6 +3240,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 (scriptedEngine && TryStartScriptedCommandAsk(cmd) is { } started) return started; + // Non-blocking by contract (host wires a fire-and-forget mediator.Tell); safe to call under Lock. AlarmCommandRouter?.Invoke(cmd); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs index a380a6ff9..0eacac57d 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 1538fb5db..998c5ef06 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..427cac6f4 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,19 @@ 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. + /// #937 review r2 M2: when the asker stops waiting. An ask still queued past it is answered + /// without touching the engine (the asker reported OutcomeUnknown and broadcast the command; the broadcast copy decides + /// what this host applies). Null ⇒ no deadline. + public sealed record ExecuteAlarmCommand(AlarmCommand Command, DateTime? DeadlineUtc = null); + /// /// 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 +188,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 +256,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 +268,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 +277,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 +314,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 +326,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 +375,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 +405,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 +438,20 @@ 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. Publish what the ENGINE says rather than infer it from the fault (review r1 L6): a load can fault after it + // completed its generation (e.g. subscribing), and then the engine still accepts commands. + _readiness?.SetLoadOutcome(loaded: _engine.HasCompleteGeneration); + _log.Warning(msg.Cause, "ScriptedAlarmHost: engine LoadAsync failed — alarms not (re)loaded; operator commands are refused until the next successful deploy"); + } 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 +788,89 @@ 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; + } + + // Review r2 M2: the asker already gave up (OutcomeUnknown) and broadcast the command — applying it now, minutes late + // behind a stalled store, would only grow this mailbox. Skipped without touching the engine and NOT remembered, so + // the broadcast copy of the same command (which the peer also got) still applies here. + if (msg.DeadlineUtc is { } deadline && DateTime.UtcNow >= deadline) + { + _log.Warning("ScriptedAlarmHost: {Op} for alarm {AlarmId} skipped on the direct path — its asker stopped waiting; the broadcast copy applies", + cmd.Operation, cmd.AlarmId); + replyTo.Tell(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.OutcomeUnknown, + "OutcomeUnknown: the ask expired before the engine reached it.", TimedOut: true)); + 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 NotYetLoadedRefusal = + "This server's scripted-alarm engine has not completed loading its configuration yet; the command was not applied."; + + private const string NotLoadedRefusal = + "The alarm is not loaded by this server's scripted-alarm engine; the command was not applied."; + + /// 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 +899,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 +916,52 @@ 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); + // Before the first load completes there is no failure to name (the readiness view is clear then). + return Refused(_readiness?.Refusal() ?? (_loadedGeneration == 0 && _readiness is not null ? NotYetLoadedRefusal + : ScriptedAlarmCommandReadinessView.LoadFailedRefusal)); + } + catch (ArgumentException ex) + { + // 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 +1023,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/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs index 887c0dc14..134cf901a 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadRestatementTests.cs @@ -384,6 +384,35 @@ public sealed class ScriptedAlarmEngineReloadRestatementTests rig.Events.Where(e => e.AlarmId == "HighTemp").Select(e => e.Emission).ShouldBe([EmissionKind.Acknowledged]); } + /// + /// #937 review r1: a command racing the engine's FIRST load queues behind it and applies (it used to throw "not loaded" + /// before the gate — an InvalidOperationException the host could only classify as OutcomeUnknown). A command on an + /// engine that never loaded is a definite refusal. + /// + [Fact] + public async Task A_command_racing_the_first_load_applies_after_it() + { + using var rig = new Rig(); + (await Should.ThrowAsync(rig.Engine.AcknowledgeAsync("HighTemp", "alice", null, Ct))) + .AlarmId.ShouldBe("HighTemp"); + + rig.Up.Set("Temp", 150); + using var loadReached = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + rig.Up.OnRead = _ => { loadReached.Set(); release.Wait(TimeSpan.FromSeconds(30)); }; + var load = Task.Run(() => rig.Engine.LoadAsync([Alarm()], Ct), Ct); + loadReached.Wait(TimeSpan.FromSeconds(10), Ct).ShouldBeTrue(); + rig.Up.OnRead = null; + + var ack = rig.Engine.AcknowledgeAsync("HighTemp", "alice", "seen", Ct); + await Task.Delay(100, Ct); + ack.IsCompleted.ShouldBeFalse("the ack waits for the first load's gate"); + release.Set(); + await load; + await ack; + rig.Engine.GetState("HighTemp")!.Acked.ShouldBe(AlarmAckedState.Acknowledged); + } + /// #935 review S1: a command that changes nothing (an uncommented re-ack) writes nothing. [Fact] public async Task An_idempotent_command_does_not_write_the_store() diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/OpcUa/ScriptedAlarmCommandDispatchTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/OpcUa/ScriptedAlarmCommandDispatchTests.cs new file mode 100644 index 000000000..423b52825 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/OpcUa/ScriptedAlarmCommandDispatchTests.cs @@ -0,0 +1,53 @@ +using Akka.Actor; +using Microsoft.Extensions.Logging.Abstractions; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Host.OpcUa; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.OpcUa; + +/// +/// #937 review r1: the redundant peer receives a Part 9 command only after THIS node's engine applied it (or did not +/// answer) — a local refusal must reach no engine anywhere, or the caller's definite failure and the node revert lie. +/// +public sealed class ScriptedAlarmCommandDispatchTests +{ + private static readonly AlarmCommand Cmd = new("alm-1", "Acknowledge", "alice", null, null, "cmd-1"); + + [Theory] + [InlineData(AlarmCommandVerdict.Applied, true)] + [InlineData(AlarmCommandVerdict.OutcomeUnknown, true)] + [InlineData(AlarmCommandVerdict.NotApplied, false)] + public async Task The_peer_broadcast_follows_the_local_verdict(AlarmCommandVerdict verdict, bool broadcast) + { + var order = new List(); + var outcome = await ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(Cmd, TimeSpan.FromSeconds(1), + (c, _) => { order.Add("ask"); return Task.FromResult(new AlarmCommandOutcome(c.AlarmId, c.Operation, verdict)); }, + c => order.Add("broadcast:" + c.CommandId), NullLogger.Instance); + + outcome.Verdict.ShouldBe(verdict); + order.ShouldBe(broadcast ? ["ask", "broadcast:cmd-1"] : ["ask"]); + } + + [Fact] + public async Task No_answer_is_outcome_unknown_and_still_broadcast_and_no_engine_is_a_refusal_with_none() + { + var sent = 0; + var timedOut = await ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(Cmd, TimeSpan.FromMilliseconds(10), + (_, _) => Task.FromException(new AskTimeoutException("no answer")), _ => sent++, NullLogger.Instance); + timedOut.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown); + timedOut.TimedOut.ShouldBeTrue(); + sent.ShouldBe(1, "the local engine may still apply it, so the peer must not be left behind"); + + var none = await ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(Cmd, TimeSpan.FromSeconds(1), null, _ => sent++, NullLogger.Instance); + none.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied); + sent.ShouldBe(1); + + // A failing broadcast never changes the caller's answer. + var applied = await ScriptedAlarmCommandDispatch.AskThenBroadcastAsync(Cmd, TimeSpan.FromSeconds(1), + (c, _) => Task.FromResult(new AlarmCommandOutcome(c.AlarmId, c.Operation, AlarmCommandVerdict.Applied)), + _ => throw new InvalidOperationException("mediator down"), NullLogger.Instance); + applied.Verdict.ShouldBe(AlarmCommandVerdict.Applied); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMethodWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMethodWireTests.cs index a0f61551e..8b4ab4862 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMethodWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMethodWireTests.cs @@ -637,6 +637,79 @@ public sealed class ImportedConditionMethodWireTests f.Port.Calls.Select(c => c.OnBehalfOf).Order().ShouldBe(new[] { "anonymous", Granted }.Order()); } + /// + /// #937 review r1: ONE Call mixing a scripted Acknowledge the engine refuses, a native Acknowledge, an imported-condition + /// Acknowledge, a scripted AddComment the engine applies, and a Server-object method owned by another node manager — + /// each item gets its own status, in request order; scripted items reach the engine one at a time, in order; every + /// item is processed (the core manager answered its own). + /// + [Fact] + public async Task A_mixed_batch_gets_per_item_status_in_order() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("937-mixed", encrypted: false, ct); + rig.Enforce(false, [ServerEventRig.Key()], ServerEventRig.ClusterGrant(ServerEventRig.KeyPrincipal, "acl-key", + NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead + | NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.AlarmShelve | NodePermissions.MethodCall)); + var f = Fixture.Install(rig); + f.Apply(Update(version: 3, active: true, acked: false)); + rig.MaterialiseScripted(); + rig.MaterialiseNative(); + var pre = new AlarmConditionSnapshot(Active: true, Acknowledged: false, Confirmed: true, Enabled: true, + Shelving: AlarmShelvingKind.Unshelved, Severity: 700, Message: "pre"); + rig.Project(false, pre); + rig.Project(true, pre); + await rig.DrainProjectionsAsync(); + var routedNative = 0; + rig.Nm.NativeAlarmAckRouter = _ => Interlocked.Increment(ref routedNative); + var asked = new ConcurrentQueue(); + var concurrent = 0; + var maxConcurrent = 0; + rig.Nm.AlarmCommandAsker = async (cmd, _) => + { + asked.Enqueue(cmd.Operation); + var now = Interlocked.Increment(ref concurrent); + if (now > Volatile.Read(ref maxConcurrent)) Volatile.Write(ref maxConcurrent, now); + await Task.Delay(50).ConfigureAwait(false); + Interlocked.Decrement(ref concurrent); + return new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, + cmd.Operation == "Acknowledge" ? AlarmCommandVerdict.NotApplied : AlarmCommandVerdict.Applied, "engine blind"); + }; + + using var session = await rig.ConnectAsync(anonymous: false, ct); + var scripted = ServerEventRig.ConditionNodeId(session, native: false); + var native = ServerEventRig.ConditionNodeId(session, native: true); + ByteString EventIdOf(bool isNative) => + rig.Nm.TryGetAlarmCondition(isNative ? ServerEventRig.RawAlarmPath : ServerEventRig.ScriptedAlarmId, + isNative ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns)!.EventId!.Value; + CallMethodRequest Ack(NodeId id, ByteString eventId, string text, NodeId? method = null) => new() + { + ObjectId = id, MethodId = method ?? MethodIds.AcknowledgeableConditionType_Acknowledge, + InputArguments = [new Variant(eventId), new Variant(new LocalizedText(text))], + }; + + var response = await session.CallAsync(null, + [ + Ack(scripted, EventIdOf(false), "refused"), + Ack(native, EventIdOf(true), "native"), + Ack(f.ConditionId(session), f.CurrentEventId(), "imported"), + Ack(scripted, EventIdOf(false), "note", MethodIds.ConditionType_AddComment), + new CallMethodRequest { ObjectId = ObjectIds.Server, MethodId = MethodIds.Server_GetMonitoredItems, InputArguments = [new Variant(987654u)] }, + ], ct); + + var codes = response.Results.ToArray()!.Select(r => r.StatusCode.Code).ToArray(); + codes.ShouldBe([StatusCodes.BadInvalidState.Code, StatusCodes.Good.Code, StatusCodes.Good.Code, StatusCodes.Good.Code, + StatusCodes.BadSubscriptionIdInvalid.Code]); + asked.ToArray().ShouldBe(["Acknowledge", "AddComment"], "scripted items reach the engine in request order"); + Volatile.Read(ref maxConcurrent).ShouldBe(1, "one scripted ask at a time within a Call"); + Volatile.Read(ref routedNative).ShouldBe(1); + f.Port.Calls.Single().Method.ShouldBe(DataConditionMethods.Acknowledge); + // The refused Acknowledge was reverted before the AddComment ran; the native one stands. + rig.Nm.TryGetAlarmCondition(ServerEventRig.ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeFalse(); + rig.Nm.TryGetAlarmCondition(ServerEventRig.RawAlarmPath, AddressSpaceRealm.Raw)!.AckedState!.Id!.Value.ShouldBeTrue(); + rig.Nm.ScriptedCommandsInFlight.ShouldBe(0); + } + // --------------------------------------------------------------------------------------------------------------------- private static DataConditionMethodResult Applied() => new(DataWriteState.AcceptedUnconfirmed, 0, null); 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..a6510018b --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ScriptedCommandVerdictWireTests.cs @@ -0,0 +1,422 @@ +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 call fails BadInvalidState, and — review r1 — the node does not keep + /// the change the SDK applied: after the method's event comes exactly one corrective event carrying the pre-call state. + /// + [Theory] + [InlineData("Acknowledge")] + [InlineData("Confirm")] + [InlineData("AddComment")] + [InlineData("OneShotShelve")] + [InlineData("TimedShelve")] + [InlineData("Unshelve")] + [InlineData("Disable")] + [InlineData("Enable")] + public async Task A_command_the_engine_refuses_returns_BadInvalidState(string method) + { + var ct = TestContext.Current.CancellationToken; + 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"); + + // Sentinel AFTER the revert: a late duplicate would already be queued ahead of it. + await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(item, "base").Count >= 3); + rig.Project(false, ConditionMethodEventTests.PreState(method, native: false) with { Message = "sentinel" }); + await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel")); + var baseEvents = events.ConditionEvents(item, "base"); + baseEvents.Count.ShouldBe(3, "the base transition, the method's event, and exactly one corrective event"); + ConditionMethodEventTests.AssertNewState(method, native: false, baseEvents[1]); + foreach (var field in new[] { RecordedEvents.AckedField, RecordedEvents.ConfirmedField, RecordedEvents.EnabledField, + RecordedEvents.ShelvingField, RecordedEvents.CommentField, RecordedEvents.RetainField }) + baseEvents[2][field].ClrValue().ShouldBe(baseEvents[0][field].ClrValue(), $"field {field} is back to its pre-call value"); + await subscription.DeleteAsync(true, ct); + } + finally { await rig.DisposeAsync(); } + } + + /// 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(); } + } + + /// + /// A NATIVE condition's AddComment is applied at the node (no scripted engine owns it): neither the scripted pre-check + /// nor the verdict ask applies, even while the scripted engine is blind (caught live by A02 on fu937-1). + /// + [Fact] + public async Task A_native_AddComment_is_not_subject_to_the_scripted_verdict() + { + var ct = TestContext.Current.CancellationToken; + var rig = await StartAsync("Verdict937NativeComment", encrypted: false, ct); + try + { + rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All)); + rig.MaterialiseNative(); + var asked = 0; + rig.Nm.AlarmCommandAsker = (cmd, _) => + { + Interlocked.Increment(ref asked); + return Task.FromResult(new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "not mine")); + }; + rig.Nm.ScriptedAlarmCommandPreflight = () => "the scripted engine is 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(true, ConditionMethodEventTests.PreState("AddComment", native: true) with { Message = "base" }); + await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base")); + + await ConditionMethodEventTests.CallAsync(session, ConditionNodeId(session, true), "AddComment", + events.LatestEventId(item, "base"), ct); + Volatile.Read(ref asked).ShouldBe(0); + await subscription.DeleteAsync(true, ct); + } + finally { await rig.DisposeAsync(); } + } + + /// + /// #937 review r1: past the node-wide in-flight cap a call is refused BadTooManyOperations BEFORE the SDK applies anything + /// (nothing asked, node unchanged); a blank scripted AddComment is refused BadInvalidArgument the same way. + /// + [Fact] + public async Task Past_the_in_flight_cap_and_for_a_blank_comment_the_call_is_refused_before_any_state_change() + { + var ct = TestContext.Current.CancellationToken; + var rig = await StartAsync("Verdict937Cap", encrypted: false, ct); + try + { + rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All)); + rig.MaterialiseScripted(); + rig.Nm.MaxScriptedCommandsInFlight = 1; + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var asked = new ConcurrentQueue(); + rig.Nm.AlarmCommandAsker = (cmd, _) => { asked.Enqueue(cmd.Operation); return release.Task; }; + rig.Project(false, ConditionMethodEventTests.PreState("OneShotShelve", native: false) with { Message = "base" }); + await rig.DrainProjectionsAsync(); + + using var first = await rig.ConnectAsync(anonymous: false, ct); + using var second = await rig.ConnectAsync(anonymous: false, ct); + var held = ConditionMethodEventTests.CallAsync(first, ConditionNodeId(first, false), "OneShotShelve", null, ct); + for (var i = 0; i < 200 && rig.Nm.ScriptedCommandsInFlight == 0; i++) await Task.Delay(25, ct); + rig.Nm.ScriptedCommandsInFlight.ShouldBe(1); + + var eventId = rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.EventId!.Value; + var refused = await second.CallAsync(null, [new CallMethodRequest + { + ObjectId = ConditionNodeId(second, false), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge, + InputArguments = [new Variant(eventId), new Variant(new LocalizedText("over the cap"))], + }], ct); + refused.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code); + rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeFalse("nothing was applied"); + + var blank = await second.CallAsync(null, [new CallMethodRequest + { + ObjectId = ConditionNodeId(second, false), MethodId = MethodIds.ConditionType_AddComment, + InputArguments = [new Variant(eventId), new Variant(new LocalizedText(" "))], + }], ct); + blank.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadInvalidArgument.Code); + asked.ToArray().ShouldBe(["OneShotShelve"], "neither refused call reached the engine"); + + // Positive control: releasing the held ask frees the slot and the held call completes Good. + release.SetResult(new AlarmCommandOutcome(ScriptedAlarmId, "OneShotShelve", AlarmCommandVerdict.Applied)); + await held; + for (var i = 0; i < 200 && rig.Nm.ScriptedCommandsInFlight != 0; i++) await Task.Delay(25, ct); + rig.Nm.ScriptedCommandsInFlight.ShouldBe(0); + } + finally { await rig.DisposeAsync(); } + } + + /// + /// #937 review r2 M1: a scripted method whose request deadline leaves less than the dispatch floor is refused + /// BadTimeout unsent (nothing asked, nothing applied); after the first unanswered scripted method of a batch the rest + /// of that batch's scripted methods are refused unsent — while a native method in the same batch still runs. + /// + [Fact] + public async Task A_too_close_deadline_or_an_earlier_unanswered_command_refuses_scripted_methods_unsent() + { + var ct = TestContext.Current.CancellationToken; + var rig = await StartAsync("Verdict937Deadline", encrypted: false, ct); + try + { + rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All)); + rig.MaterialiseScripted(); + rig.MaterialiseNative(); + rig.Nm.NativeAlarmAckRouter = _ => { }; + rig.Nm.ScriptedCommandTimeout = TimeSpan.FromMilliseconds(400); + var asked = new ConcurrentQueue(); + var never = new TaskCompletionSource(); + rig.Nm.AlarmCommandAsker = (cmd, _) => { asked.Enqueue(cmd.Operation); return never.Task; }; + var pre = new AlarmConditionSnapshot(Active: true, Acknowledged: false, Confirmed: true, Enabled: true, + Shelving: AlarmShelvingKind.Unshelved, Severity: 700, Message: "pre"); + rig.Project(false, pre); + rig.Project(true, pre); + await rig.DrainProjectionsAsync(); + + using var session = await rig.ConnectAsync(anonymous: false, ct); + ByteString EventIdOf(bool native) => rig.Nm.TryGetAlarmCondition(native ? RawAlarmPath : ScriptedAlarmId, + native ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns)!.EventId!.Value; + CallMethodRequest Request(bool native, NodeId method, string text) => new() + { + ObjectId = ConditionNodeId(session, native), MethodId = method, + InputArguments = [new Variant(EventIdOf(native)), new Variant(new LocalizedText(text))], + }; + + // (a) TimeoutHint 200 ms < grace + dispatch floor: refused unsent. + var tight = await session.CallAsync(new RequestHeader { TimeoutHint = 200 }, + [Request(false, MethodIds.AcknowledgeableConditionType_Acknowledge, "tight")], ct); + tight.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code); + asked.ShouldBeEmpty("nothing was sent"); + rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeFalse("nothing was applied"); + + // (b) one unanswered scripted method poisons the rest of its batch (scripted only). + var started = DateTime.UtcNow; + var batch = await session.CallAsync(null, + [ + Request(false, MethodIds.AcknowledgeableConditionType_Acknowledge, "first"), + Request(false, MethodIds.ConditionType_AddComment, "second"), + Request(true, MethodIds.AcknowledgeableConditionType_Acknowledge, "native"), + Request(false, MethodIds.ConditionType_AddComment, "third"), + ], ct); + batch.Results.ToArray()!.Select(r => r.StatusCode.Code).ToArray().ShouldBe( + [StatusCodes.BadTimeout.Code, StatusCodes.BadTimeout.Code, StatusCodes.Good.Code, StatusCodes.BadTimeout.Code]); + asked.ToArray().ShouldBe(["Acknowledge"], "only the first scripted method was sent"); + (DateTime.UtcNow - started).ShouldBeLessThan(TimeSpan.FromSeconds(3), "one bound for the batch, not one per request"); + } + finally { await rig.DisposeAsync(); } + } + + /// + /// #937 review r2 L1: a refusal does not revert a node something else changed since the method — even a change that + /// leaves every compared field equal (here an identical re-projection, the shape of a Timed→Timed re-shelve). + /// + [Fact] + public async Task A_refusal_does_not_revert_a_node_changed_since_the_method() + { + var ct = TestContext.Current.CancellationToken; + var rig = await StartAsync("Verdict937NoRevert", encrypted: false, ct); + try + { + rig.Enforce(false, [Key()], ClusterGrant(KeyPrincipal, "acl-key", All)); + rig.MaterialiseScripted(); + var acked = ConditionMethodEventTests.PreState("Acknowledge", native: false) with { Acknowledged = true, Message = "base" }; + rig.Nm.AlarmCommandAsker = (cmd, _) => Task.Run(() => + { + // Another writer touches the node after the method (off Lock — the handler runs under it), leaving every + // field as the method left it. + rig.Project(false, acked); + return new AlarmCommandOutcome(cmd.AlarmId, cmd.Operation, AlarmCommandVerdict.NotApplied, "refused"); + }); + rig.Project(false, acked with { Acknowledged = false }); + await rig.DrainProjectionsAsync(); + + using var session = await rig.ConnectAsync(anonymous: false, ct); + var eventId = rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.EventId!.Value; + var refused = await session.CallAsync(null, [new CallMethodRequest + { + ObjectId = ConditionNodeId(session, false), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge, + InputArguments = [new Variant(eventId), new Variant(new LocalizedText("x"))], + }], ct); + refused.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadInvalidState.Code); + rig.Nm.TryGetAlarmCondition(ScriptedAlarmId)!.AckedState!.Id!.Value.ShouldBeTrue("the newer write wins over the revert"); + } + 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.OpcUaServer.Tests/OpcUaApplicationHostQuotaTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OpcUaApplicationHostQuotaTests.cs index 0809e916b..6b98c68af 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OpcUaApplicationHostQuotaTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OpcUaApplicationHostQuotaTests.cs @@ -17,6 +17,7 @@ public sealed class OpcUaApplicationHostQuotaTests config.MinRequestThreadCount.ShouldBe(5); config.MaxRequestThreadCount.ShouldBe(100); config.MaxQueuedRequestCount.ShouldBe(200); + config.OperationLimits.MaxNodesPerMethodCall.ShouldBe(1000u, "#937: a Call is bounded (the SDK default 0 is unlimited)"); } [Fact] 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/ScriptedAlarmCommandThroughputTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandThroughputTests.cs new file mode 100644 index 000000000..3efbf4621 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandThroughputTests.cs @@ -0,0 +1,120 @@ +using System.Diagnostics; +using Akka.Actor; +using Microsoft.Data.Sqlite; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Serilog; +using Shouldly; +using Xunit; +using ZB.MOM.WW.LocalDb; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms; +using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; +using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.ScriptedAlarms; + +/// +/// #937 review r1 (item 4): what an "acknowledge all" costs through the ONE host mailbox with the production LocalDb +/// (SQLite) condition-state store — 300 active alarms, acknowledged one at a time (one Call's requests are settled +/// sequentially) and with the node manager's default in-flight cap of 64 asks outstanding at once. Asserts that no ask +/// waits anywhere near the 5 s verdict bound; the measured numbers are printed for the evidence file. +/// +public sealed class ScriptedAlarmCommandThroughputTests : RuntimeActorTestBase, IDisposable +{ + private const int Alarms = 300; + private const int Cap = 64; // OtOpcUaNodeManager.DefaultMaxScriptedCommandsInFlight + private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"otopcua-937-throughput-{Guid.NewGuid():N}.db"); + private readonly ServiceProvider _provider; + private readonly ITestOutputHelper _output; + + public ScriptedAlarmCommandThroughputTests(ITestOutputHelper output) + { + _output = output; + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary { ["LocalDb:Path"] = _dbPath }).Build(); + _provider = new ServiceCollection() + .AddZbLocalDb(configuration, db => + { + using (var connection = db.CreateConnection()) AlarmConditionStateSchema.Apply(connection); + db.RegisterReplicated(AlarmConditionStateSchema.StateTable); + db.RegisterReplicated(AlarmConditionStateSchema.CommentsTable); + }) + .BuildServiceProvider(); + } + + void IDisposable.Dispose() + { + _provider.Dispose(); + SqliteConnection.ClearAllPools(); + foreach (var path in new[] { _dbPath, $"{_dbPath}-wal", $"{_dbPath}-shm" }) + try { if (File.Exists(path)) File.Delete(path); } catch { /* best effort */ } + } + + private static EquipmentScriptedAlarmPlan Plan(int i) => + new(ScriptedAlarmId: $"alm-{i:D3}", EquipmentId: "Plant/Line1/M", Name: $"alm-{i:D3}", AlarmType: "AlarmCondition", + Severity: 800, MessageTemplate: "m", PredicateScriptId: "always", PredicateSource: "return true;", + DependencyRefs: [], HistorizeToAveva: false, Retain: true, Enabled: true); + + [Fact] + public async Task Three_hundred_acks_through_one_host_stay_far_inside_the_verdict_bound() + { + var ct = TestContext.Current.CancellationToken; + var store = new LocalDbAlarmConditionStateStore(_provider.GetRequiredService(), NullLogger.Instance); + var upstream = new DependencyMuxTagUpstreamSource(); + var logger = new LoggerConfiguration().CreateLogger(); + var engine = new ScriptedAlarmEngine(upstream, store, new ScriptLoggerFactory(logger), logger); + var readiness = new ScriptedAlarmCommandReadinessView(); + var mux = CreateTestProbe(); + var host = Sys.ActorOf(ScriptedAlarmHostActor.Props(CreateTestProbe().Ref, mux.Ref, () => (upstream, engine), readiness: readiness)); + host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms(Enumerable.Range(0, Alarms).Select(Plan).ToList())); + mux.ExpectMsg(TimeSpan.FromSeconds(60), cancellationToken: ct); + + async Task Ack(int i, string op) + { + var started = Stopwatch.GetTimestamp(); + var outcome = await host.Ask(new ScriptedAlarmHostActor.ExecuteAlarmCommand( + new AlarmCommand($"alm-{i:D3}", op, "alice", op == "AddComment" ? "c" : null, null, Guid.NewGuid().ToString("N"))), + TimeSpan.FromSeconds(30), ct); + outcome.Verdict.ShouldBe(AlarmCommandVerdict.Applied); + return Stopwatch.GetElapsedTime(started); + } + + // Sequential: one Call carrying 300 Acknowledge requests (each settled before the next). + var total = Stopwatch.StartNew(); + var sequential = new List(); + for (var i = 0; i < Alarms; i++) sequential.Add(await Ack(i, "Acknowledge")); + var sequentialTotal = total.Elapsed; + engine.GetState("alm-000")!.Active.ShouldBe(AlarmActiveState.Active, "precondition: every alarm is active"); + engine.GetState("alm-299")!.Acked.ShouldBe(AlarmAckedState.Acknowledged, "each ack changed (and saved) its condition"); + (await store.LoadAsync("alm-150", ct))!.Acked.ShouldBe(AlarmAckedState.Acknowledged); + + // Concurrent: many sessions, at most the cap outstanding at once (AddComment always writes a row). + total.Restart(); + var gate = new SemaphoreSlim(Cap); + var concurrent = await Task.WhenAll(Enumerable.Range(0, Alarms).Select(async i => + { + await gate.WaitAsync(ct); + try { return await Ack(i, "AddComment"); } + finally { gate.Release(); } + })); + var concurrentTotal = total.Elapsed; + + static string Stats(IEnumerable s) + { + var ms = s.Select(x => x.TotalMilliseconds).Order().ToArray(); + return $"p50 {ms[ms.Length / 2]:0.0} ms, p99 {ms[(int)(ms.Length * 0.99)]:0.0} ms, max {ms[^1]:0.0} ms"; + } + _output.WriteLine($"sequential 300 acks: total {sequentialTotal.TotalMilliseconds:0} ms; per ask {Stats(sequential)}"); + _output.WriteLine($"cap-{Cap} concurrent 300 comments: total {concurrentTotal.TotalMilliseconds:0} ms; per ask {Stats(concurrent)}"); + + // Far inside the 5 s verdict bound even with a full cap queued behind the one mailbox. + concurrent.Max().ShouldBeLessThan(TimeSpan.FromSeconds(2.5)); + sequential.Max().ShouldBeLessThan(TimeSpan.FromSeconds(2.5)); + } +} 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..b685efb20 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmCommandVerdictTests.cs @@ -0,0 +1,136 @@ +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); + } + + /// + /// #937 review r2 M2: an ask still queued past its asker's deadline never touches the engine (no growth of late work + /// behind a stalled store) and is NOT remembered — the broadcast copy of the same command still applies here. + /// + [Fact] + public async Task An_expired_ask_skips_the_engine_and_leaves_the_broadcast_copy_to_apply() + { + var (host, engine, _, mux) = Spawn(); + host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan("alm-1")])); + mux.ExpectMsg(Timeout, cancellationToken: Ct); + + var cmd = new AlarmCommand("alm-1", "AddComment", "alice", "late", null, "cmd-late"); + var expired = await host.Ask( + new ScriptedAlarmHostActor.ExecuteAlarmCommand(cmd, DateTime.UtcNow.AddSeconds(-1)), Timeout, Ct); + expired.Verdict.ShouldBe(AlarmCommandVerdict.OutcomeUnknown); + engine.GetState("alm-1")!.Comments.ShouldBeEmpty("the expired ask never reached the engine"); + + host.Tell(cmd); // the broadcast copy (same CommandId) + // Positive control behind it in the mailbox: a fresh ask (in time) applies, so the copy was processed first. + (await Ask(host, "alm-1", "AddComment", "after", "cmd-after")).Verdict.ShouldBe(AlarmCommandVerdict.Applied); + engine.GetState("alm-1")!.Comments.Select(c => c.Text).ShouldBe(["late", "after"]); + } + + [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"]); + } +}