Merge #937: scripted-alarm Part 9 methods report the engine's verdict (BadInvalidState / BadTimeout outcome-unknown), refused changes reverted, broadcast to the peer only after a local Applied/Unknown; MaxNodesPerMethodCall quota; 2 review rounds
v2-ci / unit-tests (push) Failing after 12m14s

This commit is contained in:
Joseph Doherty
2026-11-28 12:47:33 -05:00
30 changed files with 1996 additions and 57 deletions
+2 -1
View File
@@ -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 |
+73 -3
View File
@@ -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
+106
View File
@@ -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 `<CallAsync>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).