fix(alarms): a scripted condition's Part 9 method returns the engine's verdict (#937)

Before: the alarm-commands topic is fire-and-forget, so an OPC UA method (and a
remote gRPC-data condition method) returned Good even when the engine rejected
the command because its last load failed.

- ScriptedAlarmCommandReadinessView: the host's latest load outcome; the node
  manager's handler refuses BadInvalidState before the SDK applies anything
  while the last load failed (lock-free read).
- Bounded ask: inside CallAsync (off Lock) each local request runs base.Call
  alone; the handler only STARTS AlarmCommandAsker (broadcast for the peer +
  DriverHostActor -> ScriptedAlarmHostActor.ExecuteAlarmCommand on the local
  engine, CommandId-deduplicated) and the Call awaits the verdict: refused =>
  BadInvalidState, no answer => BadTimeout OutcomeUnknown.
- Remote CallConditionMethod: ExecuteConditionMethodAsync => DriverConfirmedFailure
  / OutcomeUnknown on the origin.
- Host ownership uses the latest plan set (stable across a load in flight and a
  failed load's half-built set).
- Docs: ScriptedAlarms.md (verdicts, residual, duplicate-activation trade-off),
  DataConnections.md, rules/alarms.md. Live leg scenario F937 + seeder
  scripted_predicate mutation.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-11-28 09:40:35 -05:00
parent 05f431f5d8
commit d6f2a1b5e2
21 changed files with 1074 additions and 38 deletions
@@ -30,8 +30,8 @@ from pathlib import Path
import rig
import scenarios
SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08")
TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720}
SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "F937")
TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720, "F937": 900}
REFRESH_REQUIRED = "RefreshRequiredEventType"
_LOG_TIME = re.compile(r"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?)")
NO_ACK = int(0b111111111111) & ~(1 << 8) # NodePermissions.Admin (4095) without AlarmAcknowledge (1 << 8)
@@ -510,6 +510,65 @@ class ConditionScenarios:
return {"code": code, "output": text[-300:], "good": code == 0 and ("successful" in text or "Comment added" in text),
"event_id_unknown": "BadEventIdUnknown" in text}
def shelve(self, node, condition, kind, tag):
code, text = self.cli(node, "shelve", "-n", condition, "-k", kind, tag=tag)
return {"code": code, "output": text[-300:], "good": code == 0 and "successful" in text,
"invalid_state": "BadInvalidState" in text or "80AF0000" in text.upper()}
# ---- #937 -------------------------------------------------------------------------------------------------------
def scenario_F937(self):
"""#937: after a deploy whose scripted-alarm load FAILS, a Part 9 method on the scripted condition returns
BadInvalidState (it used to return Good and be silently dropped) — locally on the origin and through the consumer's
remote condition method; after a good redeploy the same calls succeed (positive control)."""
source, consumer = self.r.primary("source"), self.r.primary("consumer")
name = self.fixture["conditions"]["scripted"]["condition"]
good = "return Convert.ToInt32(ctx.GetTag(\"modbus/plc/scalar\").Value) > 100;"
origin = self.watch(source, "origin")
imported = self.watch(consumer, "consumer")
time.sleep(6)
self.raise_scripted()
active = wait_for(lambda: self.latest(origin, name, lambda b: b.get("State") == "Active, Unacknowledged"), 120)
remote = wait_for(lambda: self.latest(imported, name, lambda b: b.get("State") == "Active, Unacknowledged"), 120)
if not self.check("origin_and_consumer_see_active_unacked", active and remote):
return
condition = active["ConditionNodeId"]
self.report["condition"] = condition
broken_at = self.utc(-2)
try:
self.r.mutate(scripted_predicate="return unknownIdentifier937;")
failed = wait_for(lambda: self.log_lines(source, broken_at, "engine LoadAsync failed"), 120)
self.check("origin_engine_load_failed", failed)
# The failed load changes no node: the origin still shows the condition Active+Unacked.
latest = self.latest(origin, name) or active
ack = self.ack(source, condition, latest["EventId"], "ack-blind")
self.report["ack_blind"] = ack
# Bad either way; BadInvalidState when the node still holds the pre-deploy occurrence (a deploy that rebuilt the
# address space re-materialised it acknowledged, and the SDK refuses a re-ack before the handler runs).
self.check("origin_ack_not_good", not ack["good"])
self.report["origin_ack_invalid_state"] = "BadInvalidState" in ack["output"]
shelved = self.shelve(source, condition, "OneShot", "shelve-blind")
self.report["shelve_blind"] = shelved
self.check("origin_shelve_refused_BadInvalidState", not shelved["good"] and shelved["invalid_state"])
remote_latest = self.latest(imported, name) or remote
remote_ack = self.ack(consumer, remote_latest["ConditionNodeId"], remote_latest["EventId"], "remote-ack-blind")
self.report["remote_ack_blind"] = remote_ack
self.check("consumer_remote_ack_not_good", not remote_ack["good"])
self.report["remote_ack_invalid_state"] = "BadInvalidState" in remote_ack["output"]
finally:
restored_at = self.utc(-2)
self.r.mutate(scripted_predicate=good)
loaded = wait_for(lambda: self.log_lines(source, restored_at, "ScriptedAlarmEngine loaded"), 120)
self.check("origin_engine_reloaded", loaded)
# Positive control: the first good load after a failed one is a new occurrence (documented); the ack now succeeds.
fresh = wait_for(lambda: self.latest(origin, name, lambda b: b.get("State") == "Active, Unacknowledged"
and b.get("EventId") != active["EventId"]), 120) or self.latest(origin, name)
ack = self.ack(source, condition, fresh["EventId"], "ack-restored")
self.report["ack_restored"] = ack
self.check("origin_ack_good_after_good_deploy", ack["good"])
self.raise_scripted(0)
time.sleep(4)
# ---- part 2 scenarios -------------------------------------------------------------------------------------------
def scenario_A03(self):
"""Origin failover mid-stream with standing active alarms. Phase 1: a consumer stream reset against the SAME origin
+11 -1
View File
@@ -175,7 +175,7 @@ try
var root = mutation.RootElement;
string[] allowedFields = ["connection_id", "target_mode", "target_node_id", "consistency", "consumer_node_ids", "connection_enabled", "connection_allowed_operations",
"mapping_enabled", "write_through", "allowed_operations", "export_id", "export_enabled", "export_allowed_operations", "source_redundancy_mode", "consumer_redundancy_mode",
"control_redundancy_mode", "rename_tag", "upsert_tag", "upsert_reference", "remove_tag_id", "disable_feature", "key_action", "key_expiry_seconds", "upsert_connection", "upsert_mapping", "upsert_export", "remove_mapping_id", "maintenance_mode", "acl_permissions", "bump_mapping_revision"];
"control_redundancy_mode", "rename_tag", "upsert_tag", "upsert_reference", "remove_tag_id", "disable_feature", "key_action", "key_expiry_seconds", "upsert_connection", "upsert_mapping", "upsert_export", "remove_mapping_id", "maintenance_mode", "acl_permissions", "bump_mapping_revision", "scripted_predicate"];
if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Any(property => !allowedFields.Contains(property.Name, StringComparer.Ordinal)))
throw new InvalidOperationException("unknown fixture mutation field");
await using var db = await factory.CreateDbContextAsync();
@@ -197,6 +197,16 @@ try
var maintenanceNode = await db.ClusterNodes.SingleAsync(x => x.NodeId == maintenanceNodeId);
maintenanceNode.MaintenanceMode = maintenance.GetProperty("enabled").GetBoolean();
}
if (root.TryGetProperty("scripted_predicate", out var scriptedPredicate))
{
// #937 live leg: replace the conditions profile's ScalarHigh predicate. Compile is not deploy-gated, so an
// uncompilable source deploys and fails the SOURCE engine's load (the engine then refuses operator commands).
var source = scriptedPredicate.GetString() is { Length: > 0 and <= 4096 } text ? text
: throw new InvalidOperationException("scripted predicate source required");
var script = await db.Scripts.SingleAsync(x => x.ScriptId == "source-scalar-high");
script.SourceCode = source;
script.SourceHash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(source)));
}
if (root.TryGetProperty("upsert_connection", out var newConnection))
{
var candidate = JsonSerializer.Deserialize<DataConnection>(newConnection.GetRawText()) ?? throw new InvalidOperationException();