"""A4 live condition-forwarding scenarios (plan §9 A4, A01–A08) on a `rig.py up --conditions` run. python3 scripts/validation/grpc-data/conditions_scenarios.py --run-id [--only A01,A02,A04,A05,A08] Part 1 implemented A01, A02, A04, A05 and A08; part 2 adds A03 (origin failover + EventId re-binding), A06 (consumer Primary change, both consumer nodes, two principals) and A07 (consumer node restart, ConditionRefresh vs the first snapshot barrier). A09 (lmxopcua#927) is the driver-failure ack revert through DriverHostActor for a remote native ack. Everything else (watchers, browse-resolved ids, per-scenario restore + JSON/markdown result) is shared. Rules every scenario follows: - ids are RESOLVED, never constructed: projected folders by browsing the consumer's address space, imported ConditionIds and EventIds from the `alarms` notifications the CLI prints (`ConditionNodeId`, `EventId`); - every absence assertion has a positive control observed in the same window; - configuration changes go through the seeder's `mutate` (+ deploy) or a rig configuration experiment, and are undone before the next scenario (`restore` + deploy, or the experiment's own restart). Evidence: the run's restricted `evidence/` folder — `A4S--*.txt` CLI logs, `*.process.json`, `*.probe.json`, `A4S-.json` per scenario and `A4S-results.json` / `A4S-results.md` for the selection. """ import argparse import json import os import re import signal import subprocess import sys import time import uuid from pathlib import Path import rig import scenarios 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+)?)") NO_ACK = int(0b111111111111) & ~(1 << 8) # NodePermissions.Admin (4095) without AlarmAcknowledge (1 << 8) ADMIN = 4095 _BROWSE = re.compile(r"^(\s*)\[(\w+)\]\s+(.*?)\s+\(NodeId:\s*(.*)\)\s*$") class Watch: """One CLI `alarms` subscription (Server object by default, or a notifier folder) writing to a restricted log.""" def __init__(self, runner, node, name, *, notifier=None, key=None, refresh=True, extra=()): self.log = runner.folder / name self.started = time.time() descriptor = os.open(self.log, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) argv = ["dotnet", str(runner.cli_dll), "alarms", "-u", runner.endpoint(node), "-U", "apikey", "-P", key or runner.key, "-i", "250"] if notifier: argv += ["-n", notifier] if refresh: argv.append("--refresh") argv += list(extra) self.process = subprocess.Popen(argv, stdout=descriptor, stderr=subprocess.STDOUT, start_new_session=True, cwd=rig.ROOT) os.close(descriptor) def stop(self): if self.process.poll() is None: self.process.send_signal(signal.SIGINT) try: self.process.wait(timeout=20) except subprocess.TimeoutExpired: self.process.kill() self.process.wait(timeout=10) def text(self): return self.log.read_text(errors="replace") if self.log.exists() else "" def blocks(self, condition=None): found = [] for block in self.text().split("\n\n"): header = re.search(r"\[(\S+)\] ALARM\s+(.*)$", block, re.M) if not header: continue fields = {"Time": header.group(1), "Source": header.group(2).strip()} for line in block.splitlines(): match = re.match(r"\s*(Condition|State|Severity|Message|Retain|ConditionNodeId|EventId|EventType):\s*(.*)$", line) if match: fields[match.group(1)] = match.group(2).strip() if condition is None or fields.get("Condition") == condition: found.append(fields) return found def wait_for(predicate, timeout, step=1.0): deadline = time.monotonic() + timeout while time.monotonic() < deadline: value = predicate() if value: return value time.sleep(step) return predicate() def states(blocks): return [b.get("State") for b in blocks] class ConditionScenarios: def __init__(self, run_id): self.r = scenarios.ScenarioRunner(run_id) self.fixture = self.r.manifest["fixture"] if not self.fixture.get("conditions"): raise scenarios.ScenarioError("the run was not seeded with the conditions profile (rig.py up --conditions)") files = self.r.manifest["credentials"]["data_key_files"] self.nogrant_key = Path(files["cli_nogrant"]).read_text().strip() self.alt_key = Path(files["cli_alt"]).read_text().strip() if "cli_alt" in files else None self.report = None # ---- primitives ------------------------------------------------------------------------------------------------- def check(self, name, condition): self.report["checks"][name] = bool(condition) return bool(condition) def watch(self, node, tag, **options): name = f"A4S-{self.r.active}-{tag}.txt" watcher = Watch(self.r, node, name, **options) self.watchers.append(watcher) return watcher def cli(self, node, command, *args, tag, key=None, timeout=60): argv = ["dotnet", str(self.r.cli_dll), command, "-u", self.r.endpoint(node), "-U", "apikey", "-P", key or self.r.key, *args] result = self.r.process(argv, f"A4S-{self.r.active}-{tag}", timeout=timeout) return result.returncode, (result.stdout + result.stderr) def browse(self, node, start="i=85", depth=6): code, text = self.cli(node, "browse", "-n", start, "-r", "-d", str(depth), tag="browse-" + uuid.uuid4().hex[:6], timeout=120) rows, stack = [], [] for line in text.splitlines(): match = _BROWSE.match(line) if not match: continue indent = len(match.group(1)) while stack and stack[-1][0] >= indent: stack.pop() row = {"class": match.group(2), "name": match.group(3), "node_id": match.group(4), "parent": stack[-1][1]["node_id"] if stack else start, "path": "/".join([s[1]["name"] for s in stack] + [match.group(3)])} rows.append(row) stack.append((indent, row)) return rows def read(self, node, node_id, tag): code, text = self.cli(node, "read", "-n", node_id, tag=tag) value = re.search(r"^Value:\s*(.*)$", text, re.M) status = re.search(r"^Status:\s*(\S+)", text, re.M) return {"value": value.group(1).strip() if value else None, "status": status.group(1) if status else None} def condition_child(self, node, condition_id, child, tag): """Browse the condition node for `child` (e.g. ConfirmedState) and read it — resolved, never constructed. A two-state variable reads as its LocalizedText ("Confirmed"/"Unconfirmed"); the CLI's browse shows no property children.""" rows = self.browse(node, condition_id, depth=1) state = next((r for r in rows if r["name"] == child and r["parent"] == condition_id), None) return self.read(node, state["node_id"], tag) if state else {"value": None, "status": "unresolved"} def projected_folders(self, node): """Resolve each condition mapping's projected branch folder (and its child folders) by browsing the consumer.""" rows = self.browse(node) native = self.fixture["conditions"]["native"] folders = {} for alias, branch in [("uns-plc", self.fixture["conditions"]["scripted"]["branch"]), *native["branches"].items()]: matches = [r for r in rows if r["name"] == branch] folders[alias] = [{"node_id": r["node_id"], "path": r["path"], "children": [c for c in rows if c["parent"] == r["node_id"] and c["class"] == "Object"]} for r in matches] self.report["browse"] = {"folders": folders, "rows": len(rows)} return folders def raise_scripted(self, value=150): self.r.device("set", address=20, value=value) def stop_watchers(self): for watcher in self.watchers: watcher.stop() self.watchers = [] def audit(self, node, since): """The origin's DataConnections audit lines (one per remote condition-method call) logged since `since`.""" output = self.r.rig.compose("logs", "--no-color", "--since", since, node, timeout=60) return [line for line in output.splitlines() if "Data-connection condition method" in line] def node_probe_async(self, node, operation, timeout_seconds, **fields): identity = self.r.active + "-" + uuid.uuid4().hex folder = self.r.rig.folder / "probe" / node command = {"id": identity, "connectionId": "consumer-source", "operation": operation, "realm": "raw", "originCluster": "SOURCE", "namespaceUri": "", "path": "", "timeoutSeconds": timeout_seconds, **fields} rig.atomic_write_secret(folder / (identity + ".request.json"), json.dumps(command)) def result(): output = folder / (identity + ".result.json") if not wait_for(output.exists, timeout_seconds + 20, 0.5): raise scenarios.ScenarioError("node probe result missing") raw = scenarios.restricted_json(output) self.r.save(identity + ".probe.json", raw) return raw return result def probe_records(self, tag, **arguments): output = self.r.folder / f"A4S-{self.r.active}-{tag}.json" argv = ["dotnet", str(self.r.probe_dll), "--manifest", str(self.r.manifest_path), "--scenario", "condition-records", "--output", str(output)] for key, value in arguments.items(): argv += ["--" + key.replace("_", "-"), value] self.r.process(argv, f"A4S-{self.r.active}-{tag}", timeout=120) return scenarios.restricted_json(output) if output.exists() else {"passed": False} # ---- scenarios -------------------------------------------------------------------------------------------------- def scenario_A01(self): """Scripted raise, ack, confirm via the consumer; origin and consumer both show each transition exactly once.""" source, consumer = self.r.primary("source"), self.r.primary("consumer") name = self.fixture["conditions"]["scripted"]["condition"] origin = self.watch(source, "origin") imported = self.watch(consumer, "consumer") time.sleep(6) self.raise_scripted() active = wait_for(lambda: next((b for b in imported.blocks(name) if b.get("State") == "Active, Unacknowledged" and b.get("EventId")), None), 120) if not self.check("consumer_imports_active_unacked", active): return condition = active["ConditionNodeId"] self.report["condition_id"] = condition self.check("imported_condition_id_is_opaque", condition.startswith("ns=") and "c1." in condition and "source-scalar-high" not in condition) code, text = self.cli(consumer, "ack", "-n", condition, "-e", active["EventId"], "-c", "A01 consumer ack", tag="ack") self.check("ack_good", code == 0 and "Acknowledge successful" in text) acked = wait_for(lambda: next((b for b in imported.blocks(name) if b.get("State") == "Active, Acknowledged"), None), 30) self.check("consumer_sees_ack", acked) time.sleep(5) before = {"origin": len(origin.blocks(name)), "consumer": len(imported.blocks(name))} self.report["ack_counts"] = {"origin": states(origin.blocks(name)).count("Active, Acknowledged"), "consumer": states(imported.blocks(name)).count("Active, Acknowledged")} self.check("origin_exactly_one_ack_event", self.report["ack_counts"]["origin"] == 1) self.check("consumer_exactly_one_ack_event", self.report["ack_counts"]["consumer"] == 1) latest = imported.blocks(name)[-1] if acked else active code, text = self.cli(consumer, "confirm", "-n", condition, "-e", latest["EventId"], "-c", "A01 consumer confirm", tag="confirm") self.report["confirm_output"] = text[-300:] self.check("confirm_good", code == 0 and "Confirm successful" in text) time.sleep(8) after = {"origin": origin.blocks(name)[before["origin"]:], "consumer": imported.blocks(name)[before["consumer"]:]} self.report["confirm_events"] = {k: [(b.get("State"), b.get("Message")) for b in v] for k, v in after.items()} self.check("origin_exactly_one_confirm_event", len(after["origin"]) == 1) self.check("consumer_exactly_one_confirm_event", len(after["consumer"]) == 1) origin_condition = next((b.get("ConditionNodeId") for b in origin.blocks(name) if b.get("ConditionNodeId")), None) self.report["origin_condition_id"] = origin_condition confirmed = {"consumer": self.condition_child(consumer, condition, "ConfirmedState", "read-confirmed-consumer"), "origin": self.condition_child(source, origin_condition, "ConfirmedState", "read-confirmed-origin") if origin_condition else None} self.report["confirmed_state"] = confirmed self.check("consumer_confirmed_state_true", (confirmed["consumer"] or {}).get("value") == "Confirmed") self.check("origin_confirmed_state_true", (confirmed["origin"] or {}).get("value") == "Confirmed") self.raise_scripted(0) self.check("origin_clears", wait_for(lambda: any(b.get("State", "").startswith("Inactive") for b in origin.blocks(name)), 30)) self.check("consumer_clears", wait_for(lambda: any(b.get("State", "").startswith("Inactive") for b in imported.blocks(name)), 30)) self.report["states"] = {"origin": states(origin.blocks(name)), "consumer": states(imported.blocks(name))} def scenario_A02(self): """Native condition (OpcUaClient → opc-plc --alm): Ack + AddComment forwarded; Confirm refused BadNotSupported, unsent.""" source, consumer = self.r.primary("source"), self.r.primary("consumer") name = self.fixture["conditions"]["native"]["condition"] since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 2)) origin = self.watch(source, "origin") imported = self.watch(consumer, "consumer") event = wait_for(lambda: next((b for b in reversed(imported.blocks(name)) if b.get("EventId") and b.get("ConditionNodeId")), None), 150) self.report["origin_states"] = states(origin.blocks(name))[:20] if not self.check("consumer_imports_native_condition", event): return condition = event["ConditionNodeId"] self.report["condition_id"] = condition self.check("origin_shows_native_condition", origin.blocks(name)) self.check("imported_condition_id_is_opaque", "c1." in condition and "opcua/opcplc" not in condition) code, text = self.cli(consumer, "ack", "-n", condition, "-e", "00" * 16, "-c", "A02 bogus", tag="ack-bogus") self.check("bogus_eventid_refused", "BadEventIdUnknown" in text and "successful" not in text) latest = imported.blocks(name)[-1] code, text = self.cli(consumer, "ack", "-n", condition, "-e", latest["EventId"], "-c", "A02 consumer ack", tag="ack") self.report["ack_output"] = text[-300:] self.check("ack_good", code == 0 and "Acknowledge successful" in text) latest = imported.blocks(name)[-1] code, text = self.cli(consumer, "comment", "-n", condition, "-e", latest["EventId"], "-c", "A02 consumer comment", tag="comment") self.report["comment_output"] = text[-300:] self.check("comment_good", code == 0 and "Comment added" in text and "failed" not in text.lower()) latest = imported.blocks(name)[-1] code, text = self.cli(consumer, "confirm", "-n", condition, "-e", latest["EventId"], "-c", "A02 consumer confirm", tag="confirm") self.report["confirm_output"] = text[-300:] self.check("confirm_refused_bad_not_supported", "BadNotSupported" in text and "Confirm successful" not in text) time.sleep(6) audit = self.audit(source, since) self.report["origin_audit"] = audit[-20:] joined = "\n".join(audit) # Positive control: the ack and the comment reached the origin (audited); the confirm never did. self.check("origin_audited_ack", re.search(r"condition method \W?Acknowledge\b", joined)) self.check("origin_audited_comment", re.search(r"condition method \W?AddComment\b", joined)) self.check("confirm_unsent", not re.search(r"condition method \W?Confirm\b", joined)) self.report["consumer_states"] = states(imported.blocks(name))[-20:] def scenario_A04(self): """One native alarm, three placements (Raw device + two referencing equipment) ⇒ one consumer condition, three notifiers, one Server-object event per transition; the same ConditionId whichever subscriber came first; a UNS-only origin principal's records carry no RawPath.""" consumer, source = self.r.primary("consumer"), self.r.primary("source") native = self.fixture["conditions"]["native"] name = native["condition"] folders = self.projected_folders(consumer) mapping_aliases = ("raw", "pumpa", "pumpb") if not self.check("three_branch_folders_resolved", all(len(folders.get(a, [])) == 1 for a in mapping_aliases)): return rounds = [] for number, order in enumerate((("pumpa", "raw", "pumpb"), ("raw", "pumpb", "pumpa")), start=1): if number == 2: # Let the demand linger (30 s) expire so round 2 re-imports from scratch with a different first subscriber. self.stop_watchers() time.sleep(45) # A folder is an event notifier only while a condition is wired there (A3 deviation 3): a folder item created # before demand is open is refused BadNotSupported. So the Server-object item opens demand first; its # ConditionRefresh replay names the imported condition; then the three placement folders subscribe in `order`. server = self.watch(consumer, f"r{number}-server") replay = wait_for(lambda: next((b for b in server.blocks(name) if b.get("EventId") and b.get("ConditionNodeId")), None), 120) folder_watches = {} for alias in order: folder_watches[alias] = self.watch(consumer, f"r{number}-{alias}", notifier=folders[alias][0]["node_id"], refresh=False) time.sleep(2) time.sleep(3) window_index = len(server.blocks(name)) # Live transitions: the upstream EastTank?Yellow condition cycles Active <-> Inactive (~40 s / ~8 s) on its own. wait_for(lambda: len([b for b in server.blocks(name)[window_index:] if b.get("EventId")]) >= 2, 150) time.sleep(6) server_events = [b for b in server.blocks(name) if b.get("EventId")] ids = {b.get("ConditionNodeId") for b in server_events} late_blocks = [b for b in server.blocks(name)[window_index:] if b.get("EventId")] late = [b["EventId"] for b in late_blocks] per_folder = {} for alias, watcher in folder_watches.items(): events = [b["EventId"] for b in watcher.blocks(name) if b.get("EventId")] refused = "BadNotSupported" in watcher.text() per_folder[alias] = {"node_id": folders[alias][0]["node_id"], "events": len(events), "duplicates": len(events) - len(set(events)), "refused": refused, "condition_ids": sorted({b.get("ConditionNodeId") for b in watcher.blocks(name)}), "late_server_events_missing": len([e for e in late if e not in events]), "extra_events_not_on_server": len([e for e in events if e not in {b["EventId"] for b in server_events}])} rounds.append({"order": order, "replay": bool(replay), "condition_ids": sorted(ids), "server_events": len(server_events), "server_duplicate_event_ids": len(late) - len(set(late)), "late_events": len(late), "late_states": [b.get("State") for b in late_blocks], "folders": per_folder}) self.report["rounds"] = rounds for index, round_ in enumerate(rounds, start=1): self.check(f"r{index}_one_consumer_condition", len(round_["condition_ids"]) == 1) self.check(f"r{index}_server_object_each_event_once", round_["server_events"] >= 1 and round_["server_duplicate_event_ids"] == 0) self.check(f"r{index}_three_notifiers", all(round_["folders"][a]["events"] >= 1 and not round_["folders"][a]["refused"] and round_["folders"][a]["duplicates"] == 0 for a in mapping_aliases)) self.check(f"r{index}_notifiers_carry_only_server_events", all(round_["folders"][a]["extra_events_not_on_server"] == 0 for a in mapping_aliases)) self.check(f"r{index}_notifiers_same_condition", all(round_["folders"][a]["condition_ids"] == round_["condition_ids"] for a in mapping_aliases)) self.check(f"r{index}_late_events_reach_every_notifier", round_["late_events"] >= 1 and all(round_["folders"][a]["late_server_events_missing"] == 0 for a in mapping_aliases)) self.check("same_condition_id_both_orders", len(rounds) == 2 and rounds[0]["condition_ids"] == rounds[1]["condition_ids"]) # UNS-only principal: no RawPath anywhere in its records; positive control = the Raw item under the full principal names it. unsonly = self.probe_records("records-unsonly", node=source, key_name="source_unsonly", realm="uns", identifier=native["equipment"]["pumpa"], subject=native["subjects"]["pumpa"], forbid=native["raw_root"], expect=name) control = self.probe_records("records-raw-control", node=source, key_name="source", realm="raw", identifier=native["raw_root"], subject=native["raw_root"], expect=native["raw_root"]) self.report["records"] = {"unsonly": self._records_summary(unsonly), "raw_control": self._records_summary(control)} self.check("unsonly_records_carry_no_rawpath", unsonly.get("passed")) self.check("raw_principal_records_name_rawpath_positive_control", control.get("passed")) def scenario_A05(self): """ACLs off on the consumer: a session WITHOUT the mapping grant at i=2253 receives zero imported events, live or on refresh, while a granted session sees them in the same window.""" name, native = self.fixture["conditions"]["scripted"]["condition"], self.fixture["conditions"]["native"]["condition"] with self.r.rig._configuration_experiment("a4s-acl-off", ("consumer-1", "consumer-2"), {"Security__Acl__Enabled": "false"}): self.r.manifest = self.r.rig.load() consumer = self.r.wait_primary("consumer") self.report["acl_disabled_on"] = consumer denied = self.watch(consumer, "nogrant", key=self.nogrant_key) granted = self.watch(consumer, "granted") time.sleep(5) self.raise_scripted() wait_for(lambda: granted.blocks(name) and granted.blocks(native), 150) time.sleep(15) # Second refresh pass for the denied session: a fresh subscription's ConditionRefresh replay must also be empty. denied_refresh = self.watch(consumer, "nogrant-refresh", key=self.nogrant_key) time.sleep(12) self.raise_scripted(0) time.sleep(8) self.stop_watchers() imported_denied = [b for w in (denied, denied_refresh) for b in w.blocks() if "c1." in (b.get("ConditionNodeId") or "") or b.get("Condition") in (name, native)] markers = [b for b in denied.blocks() if b.get("Message", "").startswith("Condition refresh")] self.report["granted"] = {"scripted": len(granted.blocks(name)), "native": len(granted.blocks(native))} self.report["denied"] = {"imported_events": len(imported_denied), "refresh_markers": len(markers), "all_events": len(denied.blocks()) + len(denied_refresh.blocks())} self.check("granted_session_sees_scripted_positive_control", granted.blocks(name)) self.check("granted_session_sees_native_positive_control", granted.blocks(native)) self.check("denied_session_alive_refresh_markers", markers) self.check("denied_session_zero_imported_events", not imported_denied) self.r.manifest = self.r.rig.load() self.report["restored"] = "consumer pair restarted with Security__Acl__Enabled from compose.yml" def scenario_A08(self): """Origin ACL loses AlarmAcknowledge ⇒ a consumer ack is denied while state keeps streaming; the consumer publishes no /alerts (alarm-history) transition for imported conditions while the origin does (positive control).""" name = self.fixture["conditions"]["scripted"]["condition"] since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 2)) self.r.mutate(acl_permissions={"node_acl_id": "source-peer", "permission_flags": NO_ACK}) self.r.manifest = self.r.rig.load() source, consumer = self.r.primary("source"), self.r.primary("consumer") origin_alerts = self.node_probe_async(source, "alert-transitions", 110) consumer_alerts = self.node_probe_async(consumer, "alert-transitions", 110) origin = self.watch(source, "origin") imported = self.watch(consumer, "consumer") time.sleep(6) self.raise_scripted() active = wait_for(lambda: next((b for b in imported.blocks(name) if b.get("State") == "Active, Unacknowledged" and b.get("EventId")), None), 120) if self.check("state_streams_after_revocation", active): code, text = self.cli(consumer, "ack", "-n", active["ConditionNodeId"], "-e", active["EventId"], "-c", "A08 denied ack", tag="ack-denied") self.report["denied_ack_output"] = text[-300:] self.check("ack_denied", "Acknowledge successful" not in text and re.search(r"Bad\w*(Denied|Access|Permission)", text)) time.sleep(5) self.check("origin_not_acknowledged", "Active, Acknowledged" not in states(origin.blocks(name))) # The refusal is the ORIGIN's (the consumer's own gate passed: fixture-cli is Admin on CONSUMER): its audit line. audit = self.audit(source, since) self.report["origin_audit"] = audit[-10:] self.check("origin_audited_denied_ack", any(" Acknowledge " in line and "0x801F0000" in line for line in audit)) self.raise_scripted(0) self.check("consumer_still_streams_clear", wait_for(lambda: any(b.get("State", "").startswith("Inactive") for b in imported.blocks(name)), 40)) origin_result, consumer_result = origin_alerts(), consumer_alerts() origin_rows = origin_result.get("observations", {}).get("alarmTransitions", []) consumer_rows = consumer_result.get("observations", {}).get("alarmTransitions", []) self.report["alerts"] = {"origin": origin_rows, "consumer": consumer_rows, "origin_probe_passed": origin_result.get("passed"), "consumer_probe_passed": consumer_result.get("passed")} self.check("origin_alerts_positive_control", origin_result.get("passed") and any(r.get("alarmName") == name for r in origin_rows)) self.check("consumer_alerts_stream_open", consumer_result.get("passed")) self.check("consumer_no_alerts_for_imported", not consumer_rows) # Positive control for the denial: grant restored ⇒ the same consumer ack is applied. self.stop_watchers() self.r.mutate(acl_permissions={"node_acl_id": "source-peer", "permission_flags": ADMIN}) self.r.manifest = self.r.rig.load() consumer = self.r.primary("consumer") imported = self.watch(consumer, "consumer-restored") time.sleep(6) self.raise_scripted() active = wait_for(lambda: next((b for b in imported.blocks(name) if b.get("State") == "Active, Unacknowledged" and b.get("EventId")), None), 120) if self.check("restored_raise_imported", active): code, text = self.cli(consumer, "ack", "-n", active["ConditionNodeId"], "-e", active["EventId"], "-c", "A08 restored ack", tag="ack-restored") self.check("restored_ack_good_positive_control", code == 0 and "Acknowledge successful" in text) self.raise_scripted(0) time.sleep(4) # ---- part 2 primitives ------------------------------------------------------------------------------------------ @staticmethod def utc(offset=0.0): return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + offset)) def log_lines(self, node, since, needle): """Timestamped log lines of `node` since `since` containing `needle` (e.g. the imported-conditions runner lines).""" output = self.r.rig.compose("logs", "--no-color", "--timestamps", "--since", since, node, timeout=60) return [line for line in output.splitlines() if needle in line] def stream_opened(self, node, since, serving=None): return [l for l in self.log_lines(node, since, "Imported conditions: stream") if " opened " in l and (serving is None or serving in l)] def barriers(self, node, since): return self.log_lines(node, since, "snapshot barrier passed") @staticmethod def log_time(line): match = _LOG_TIME.search(line or "") return match.group(1)[:26] if match else None @staticmethod def block_time(block): return (block or {}).get("Time", "")[:26] or None @staticmethod def refresh_required(blocks): return [b for b in blocks if REFRESH_REQUIRED in (b.get("EventType") or "")] @staticmethod def latest(watcher, name, predicate=lambda b: True): return next((b for b in reversed(watcher.blocks(name)) if b.get("EventId") and predicate(b)), None) @staticmethod def unique_event_ids(blocks): ids = [b["EventId"] for b in blocks if b.get("EventId")] return len(ids) == len(set(ids)) @staticmethod def duplicate_transitions(watcher, names): """Live events (after the watcher's RefreshEnd) that repeat a condition's (Time, State, Severity, Message): one origin transition delivered twice under different consumer EventIds — the EventId-uniqueness check cannot see that.""" blocks = watcher.blocks() end = next((i for i, b in enumerate(blocks) if "RefreshEnd" in (b.get("EventType") or "")), -1) seen, dupes = set(), [] for b in blocks[end + 1:]: if b.get("Condition") not in names: continue key = (b.get("Condition"), b.get("Time"), b.get("State"), b.get("Severity"), b.get("Message")) if key in seen: dupes.append(key) seen.add(key) return dupes def partner(self, pair, node): return next(n for n in self.r.manifest["nodes"] if n.startswith(pair + "-") and n != node) def start_watch(self, node, tag, attempts=40, **options): """A watcher on a node that may still be starting: relaunch until the CLI reports the subscription.""" for attempt in range(attempts): watcher = self.watch(node, f"{tag}-{attempt}", **options) wait_for(lambda: "Subscribed to alarm events" in watcher.text() or watcher.process.poll() is not None, 30, 0.25) if watcher.process.poll() is None and "Subscribed to alarm events" in watcher.text(): return watcher watcher.stop() self.watchers.remove(watcher) time.sleep(2) raise scenarios.ScenarioError(f"no alarm subscription on {node}") def ack(self, node, condition, event_id, tag, command="ack"): code, text = self.cli(node, command, "-n", condition, "-e", event_id, "-c", f"{self.r.active} {tag}", tag=tag) 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 the OpcUaClient driver genuinely fails: the run-owned opc-plc is `docker pause`d just before the ack, so the driver's upstream Acknowledge call gets no reply and times out (no test seam). Asserts: the caller gets Good (plan §5.6 step 5: native ⇒ Good, `AcceptedUnconfirmed`; the failure reaches it as the revert); the origin applies the ack then REVERTS it (DriverHostActor `RevertNativeAlarmAck` ⇒ `EstablishesState: false`, logged "did not reach the alarm system … reverting"); the consumer sees the reverted delta; the origin audit records the call on behalf of the end user. The upstream is frozen, so no driver transition can explain the Unacknowledged that follows the ack (control: no upstream event while paused). After unpausing, a second ack of the then-current EventId is not reverted (positive control for the failure).""" source, consumer = self.r.primary("source"), self.r.primary("consumer") name = self.fixture["conditions"]["native"]["condition"] since = self.utc(-2) origin = self.watch(source, "origin") imported = self.watch(consumer, "consumer") unacked = lambda b: b.get("State", "").endswith("Unacknowledged") event = wait_for(lambda: self.latest(imported, name, unacked), 300) origin_event = wait_for(lambda: self.latest(origin, name, unacked), 30) if not self.check("consumer_has_unacknowledged_native_condition", event) or not self.check("origin_has_it_too", origin_event): return condition = event["ConditionNodeId"] self.report["condition_id"] = condition self.report["before"] = {"consumer": event, "origin": origin_event} paused = False try: self.r.rig.compose("pause", "opcplc", timeout=60) paused = True self.report["paused_utc"] = self.utc() origin_mark, consumer_mark = len(origin.blocks(name)), len(imported.blocks(name)) result = self.ack(consumer, condition, event["EventId"], "ack-driver-fails") self.report["ack"] = result self.check("caller_gets_good_accepted_unconfirmed", result["good"]) def reverted(watcher, mark): tail = states(watcher.blocks(name)[mark:]) acked = next((i for i, state in enumerate(tail) if state and state.endswith(", Acknowledged")), None) return tail if acked is not None and any(state and state.endswith("Unacknowledged") for state in tail[acked + 1:]) else None origin_tail = wait_for(lambda: reverted(origin, origin_mark), 60) consumer_tail = wait_for(lambda: reverted(imported, consumer_mark), 30) self.report["origin_after_ack"] = states(origin.blocks(name)[origin_mark:]) self.report["consumer_after_ack"] = states(imported.blocks(name)[consumer_mark:]) self.check("origin_applied_then_reverted", origin_tail) self.check("consumer_saw_the_reverted_delta", consumer_tail) latest = self.latest(imported, name) self.check("consumer_reverted_event_is_a_new_event_id", latest and latest.get("EventId") != event["EventId"]) self.check("consumer_reverted_condition_id_unchanged", latest and latest.get("ConditionNodeId") == condition) reverts = self.log_lines(source, since, REVERT_LOG) failures = self.log_lines(source, since, "native-alarm acknowledge of") self.report["origin_revert_log"] = reverts[-5:] self.report["origin_driver_failure_log"] = failures[-5:] self.check("origin_logged_the_driver_failure_and_revert", any("reverting the condition to unacknowledged" in line for line in reverts)) self.check("driver_instance_logged_the_failed_upstream_ack", any("failed" in line or "refused" in line for line in failures)) audit = self.audit(source, since) self.report["origin_audit"] = audit[-10:] self.check("origin_audited_the_remote_ack", any(re.search(r"condition method \W?Acknowledge\b", line) and "AcceptedUnconfirmed" in line and "fixture-cli" in line for line in audit)) # Control: the upstream is frozen, so the Unacknowledged after the ack cannot be an upstream transition. Every # origin event after the ack is either the ack itself or the revert (plus comms-loss quality, which has no state). self.report["origin_tail_states"] = sorted(set(filter(None, self.report["origin_after_ack"]))) finally: if paused: self.r.rig.compose("unpause", "opcplc", timeout=60) self.report["unpaused_utc"] = self.utc() # Positive control: once opc-plc answers again, an ack of the current EventId is not reverted. (The paused call may # still be applied upstream when the container resumes; then the condition is already acknowledged, also recorded.) time.sleep(30) current = self.latest(imported, name) self.report["after_unpause"] = current if current and current.get("State", "").endswith("Unacknowledged"): mark = len(self.log_lines(source, since, REVERT_LOG)) result = self.ack(consumer, condition, current["EventId"], "ack-after-unpause") self.report["control_ack"] = result self.check("control_ack_good", result["good"]) time.sleep(15) self.check("control_ack_not_reverted", len(self.log_lines(source, since, REVERT_LOG)) == mark) else: self.report["control_note"] = "the upstream applied the paused acknowledge after unpause (condition already acknowledged)" self.check("control_upstream_acknowledged_after_unpause", current and current.get("State", "").endswith(", Acknowledged")) # ---- 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 incarnation (mapping revision bump) keeps the old EventId usable and reports nothing for unchanged state. Phase 2: stop the SOURCE Primary, clear-and-re-raise ScalarHigh during the gap (record time changes, state does not) ⇒ RefreshRequired, the pre-failover EventId is BadEventIdUnknown (never re-bound), ConditionRefresh yields a new EventId that acks Good, nothing still active is retired, no duplicate EventIds, and a real transition after the resync arrives exactly once (positive control).""" name, native = self.fixture["conditions"]["scripted"]["condition"], self.fixture["conditions"]["native"]["condition"] source, consumer = self.r.primary("source"), self.r.primary("consumer") partner = self.partner("source", source) self.report["nodes"] = {"source_primary": source, "source_partner": partner, "consumer": consumer} imported = self.watch(consumer, "consumer") origin = self.watch(source, "origin") time.sleep(6) self.raise_scripted() active = wait_for(lambda: self.latest(imported, name, lambda b: b.get("State") == "Active, Unacknowledged"), 120) native_seen = wait_for(lambda: self.latest(imported, native), 150) if not self.check("scripted_and_native_imported", active and native_seen): return condition, native_condition = active["ConditionNodeId"], native_seen["ConditionNodeId"] self.report["condition_ids"] = {"scripted": condition, "native": native_condition} # Phase 1 — stream reset against the same origin incarnation. since = self.utc(-2) time.sleep(3) e1 = self.latest(imported, name)["EventId"] mark, origin_mark = len(imported.blocks(name)), len(origin.blocks(name)) mark_all_p1 = len(imported.blocks()) self.r.mutate(bump_mapping_revision=self.fixture["conditions"]["native"]["mappings"]["pumpb"]) self.r.manifest = self.r.rig.load() opened = wait_for(lambda: self.stream_opened(consumer, since), 120) barrier = wait_for(lambda: self.barriers(consumer, since), 120) time.sleep(8) reset_events = imported.blocks(name)[mark:] origin_events = origin.blocks(name)[origin_mark:] p1_required = self.refresh_required(imported.blocks()[mark_all_p1:]) self.report["phase1"] = {"stream_opened": opened[-2:], "barrier": barrier[-2:], "events_during_reset": [(b.get("State"), b.get("Time")) for b in reset_events], "origin_events_during_reset": [(b.get("State"), b.get("Time")) for b in origin_events], "origin_reassert_log": self.log_lines(source, since, "re-asserted")[-2:], "watcher_alive": imported.process.poll() is None, "refresh_required": [(b.get("Time"), b.get("Source")) for b in p1_required]} self.check("p1_stream_reopened_same_origin", opened and all(source in line for line in opened)) self.check("p1_barrier_after_reset", barrier) # A deploy is the rig's only stream-reset trigger, and it also makes the origin re-assert its scripted alarms (a new # record time, same activation marker): the consumer must mirror exactly the origin's events — no resync extras. self.check("p1_consumer_events_mirror_origin", len(reset_events) == len(origin_events) and self.unique_event_ids(imported.blocks(name))) # A4 review r2 S3: the runner that takes the HELD set over after the consumer's deploy sends RefreshRequired exactly once # (the rig has one condition-bearing connection) — the resync signal for anything missed during the hold. It is a # Server-object event, not a condition event: the mirror check above still forbids any extra condition event. self.check("p1_exactly_one_refresh_required_after_held_takeover", len(p1_required) == 1) comment = self.ack(consumer, condition, e1, "comment-old-eventid-same-incarnation", command="comment") self.report["phase1"]["comment_with_pre_reset_eventid"] = comment self.check("p1_pre_reset_eventid_still_accepted", comment["good"]) latest_comment = self.ack(consumer, condition, self.latest(imported, name)["EventId"], "comment-latest-eventid-after-reset", command="comment") self.report["phase1"]["comment_with_latest_eventid"] = latest_comment self.check("p1_latest_eventid_accepted_positive_control", latest_comment["good"]) origin.stop() time.sleep(6) # Phase 2 — origin failover with a clear-and-re-raise in the gap. pre = self.latest(imported, name) native_pre = self.latest(imported, native) self.check("p2_pre_failover_active_unacked", pre and pre.get("State") == "Active, Unacknowledged") mark_all, mark_named, mark_native = len(imported.blocks()), len(imported.blocks(name)), len(imported.blocks(native)) since = self.utc(-1) phase2 = self.report["phase2"] = {"pre_eventid": pre["EventId"], "pre_time": pre.get("Time"), "native_pre": native_pre} # The gap: freeze the old Primary (docker pause), clear and re-raise at the device, unfreeze and stop it at once — so # the consumer's stream never carries the clear, and the new Primary's record has a new time with the same state. with self.r.paused(source) as resume: self.r.device("set", address=20, value=0) time.sleep(4) self.raise_scripted() time.sleep(2) phase2["gap_clear_reraise_at"] = self.utc() phase2["pause"] = resume() with self.r.stopped(source): phase2["new_source_primary"] = self.r.wait_primary("source", exclude=source) reopened = wait_for(lambda: self.stream_opened(consumer, since, partner), 240) barrier = wait_for(lambda: self.barriers(consumer, since), 120) required = wait_for(lambda: self.refresh_required(imported.blocks()[mark_all:]), 60) phase2.update(stream_opened=reopened[-2:], barrier=barrier[-2:], refresh_required=required[:3]) during = imported.blocks(name)[mark_named:] phase2["scripted_events_after_failover"] = [(b.get("State"), b.get("Time")) for b in during] self.check("p2_stream_reopened_on_new_primary", reopened and phase2["new_source_primary"] == partner) self.check("p2_gap_covered_no_inactive_seen", not [b for b in during if (b.get("State") or "").startswith("Inactive")]) self.check("p2_refresh_required_received", required) old = self.ack(consumer, condition, pre["EventId"], "ack-pre-failover-eventid") phase2["ack_pre_failover"] = old self.check("p2_pre_failover_eventid_bad_event_id_unknown", old["event_id_unknown"] and not old["good"]) if native_pre: # D7 (informational): the native condition's re-bind depends on whether its record time moved. # AddComment, not Acknowledge: the same EventId check, but an ack forwarded to opc-plc froze the origin's native # condition at Active/Acknowledged for the rest of run a4s-4 (A04 then saw no transitions). phase2["native_comment_pre_failover"] = self.ack(consumer, native_condition, native_pre["EventId"], "comment-native-pre-failover", command="comment") refreshed = self.watch(consumer, "post-failover-refresh") replay = wait_for(lambda: self.latest(refreshed, name), 60) native_replay = wait_for(lambda: self.latest(refreshed, native), 30) phase2["replay"] = {"scripted": replay, "native": native_replay} self.check("p2_refresh_replays_scripted_same_condition_new_eventid", replay and replay["ConditionNodeId"] == condition and replay["EventId"] != pre["EventId"] and replay.get("State") == "Active, Unacknowledged") self.check("p2_native_still_present_same_condition", native_replay and native_replay["ConditionNodeId"] == native_condition) if replay: new = self.ack(consumer, condition, replay["EventId"], "ack-refreshed-eventid") phase2["ack_refreshed"] = new self.check("p2_refreshed_eventid_acks_good", new["good"]) self.check("p2_ack_observed", wait_for(lambda: self.latest(imported, name, lambda b: b.get("State") == "Active, Acknowledged"), 30)) # Positive control: a real transition after the resync must arrive, exactly once. clear_mark = len(imported.blocks(name)) self.r.device("set", address=20, value=0) wait_for(lambda: [b for b in imported.blocks(name)[clear_mark:] if (b.get("State") or "").startswith("Inactive")], 40) time.sleep(6) cleared = [b for b in imported.blocks(name)[clear_mark:] if (b.get("State") or "").startswith("Inactive")] phase2["clear_events"] = [(b.get("State"), b.get("EventId")) for b in cleared] self.check("p2_positive_control_clear_exactly_once", len(cleared) == 1) self.check("p2_no_duplicate_eventids", self.unique_event_ids(imported.blocks(name)[mark_named:]) and self.unique_event_ids(imported.blocks(native)[mark_native:])) self.check("p2_watcher_alive_throughout", imported.process.poll() is None) dupes = self.duplicate_transitions(imported, (name, native)) self.report["duplicate_transitions"] = dupes self.check("no_duplicate_transitions_whole_scenario", not dupes) phase2["source_restarted"] = source def scenario_A06(self): """Consumer Primary change with clients on BOTH consumer nodes (two principals): the same ConditionId everywhere; after the Primary stops, the partner's clients see a real transition exactly once with no duplicate EventIds; the restarted node converges to the same ConditionIds/state. Also records whether a folder item made first on a fresh node (no Server-object demand) is refused (part-1 observation 1).""" if not self.check("alt_principal_seeded", self.alt_key): return name, native = self.fixture["conditions"]["scripted"]["condition"], self.fixture["conditions"]["native"]["condition"] primary = self.r.primary("consumer") partner = self.partner("consumer", primary) self.report["nodes"] = {"consumer_primary": primary, "consumer_partner": partner} watches = {"primary-cli": self.watch(primary, "primary-cli", extra=("-F", self.r.endpoint(partner))), "primary-alt": self.watch(primary, "primary-alt", key=self.alt_key), "partner-cli": self.watch(partner, "partner-cli"), "partner-alt": self.watch(partner, "partner-alt", key=self.alt_key)} time.sleep(6) self.raise_scripted() def ready(w): return self.latest(w, name, lambda b: b.get("State") == "Active, Unacknowledged") and self.latest(w, native) wait_for(lambda: all(ready(w) for w in watches.values()), 150) ids = {k: {"scripted": (self.latest(w, name) or {}).get("ConditionNodeId"), "native": (self.latest(w, native) or {}).get("ConditionNodeId")} for k, w in watches.items()} self.report["condition_ids_before"] = ids reference = ids["primary-cli"] if not self.check("same_condition_ids_both_nodes_both_principals", reference["scripted"] and reference["native"] and all(v == reference for v in ids.values())): return marks = {k: len(w.blocks(name)) for k, w in watches.items()} change = self.report["primary_change"] = {} with self.r.stopped(primary): change["new_primary"] = self.r.wait_primary("consumer", exclude=primary) self.check("partner_became_primary", change["new_primary"] == partner) time.sleep(10) self.r.device("set", address=20, value=0) survivors = ("partner-cli", "partner-alt") wait_for(lambda: all([b for b in watches[k].blocks(name)[marks[k]:] if (b.get("State") or "").startswith("Inactive")] for k in survivors), 60) time.sleep(6) for k, w in watches.items(): after = w.blocks(name)[marks[k]:] change[k] = {"states": states(after), "inactive": len([b for b in after if (b.get("State") or "").startswith("Inactive")]), "unique_eventids": self.unique_event_ids(w.blocks(name)), "alive": w.process.poll() is None, "refresh_required": len(self.refresh_required(w.blocks()))} self.check("partner_clients_see_clear_exactly_once", all(change[k]["inactive"] == 1 for k in survivors)) self.check("partner_clients_no_duplicate_eventids", all(change[k]["unique_eventids"] for k in survivors)) remarks = {k: len(watches[k].blocks(name)) for k in survivors} self.raise_scripted() self.check("partner_clients_see_reraise", wait_for(lambda: all([b for b in watches[k].blocks(name)[remarks[k]:] if b.get("State") == "Active, Unacknowledged"] for k in survivors), 60)) self.stop_watchers() # The old Primary restarted (manifest endpoints refreshed). Observation 1: a folder item made FIRST on this fresh node. restarted = primary folders = wait_for(lambda: self.projected_folders(restarted).get("raw"), 180, 5) folder_first = {"folder": folders[0]["node_id"] if folders else None} if folders: fw = self.watch(restarted, "restarted-folder-first", notifier=folders[0]["node_id"], refresh=False) time.sleep(20) folder_first.update(refused="BadNotSupported" in fw.text(), exited=fw.process.poll() is not None, events_before_server_item=len(fw.blocks()), tail=fw.text()[-400:]) converge = {"restarted-cli": self.start_watch(restarted, "restarted-cli"), "partner-alt2": self.watch(partner, "partner-alt2", key=self.alt_key)} wait_for(lambda: all(ready(w) for w in converge.values()), 150) if folders and not folder_first["exited"]: time.sleep(4) folder_first["events_after_server_item"] = len(fw.blocks()) self.report["folder_first_on_fresh_node"] = folder_first ids_after = {k: {"scripted": (self.latest(w, name) or {}).get("ConditionNodeId"), "native": (self.latest(w, native) or {}).get("ConditionNodeId")} for k, w in converge.items()} self.report["condition_ids_after_restart"] = ids_after self.check("restarted_node_converges_same_condition_ids", all(v == reference for v in ids_after.values())) self.check("restarted_node_same_scripted_state", all((self.latest(w, name) or {}).get("State") == "Active, Unacknowledged" for w in converge.values())) marks = {k: len(w.blocks(name)) for k, w in converge.items()} self.r.device("set", address=20, value=0) wait_for(lambda: all([b for b in w.blocks(name)[marks[k]:] if (b.get("State") or "").startswith("Inactive")] for k, w in converge.items()), 60) time.sleep(6) counts = {k: len([b for b in w.blocks(name)[marks[k]:] if (b.get("State") or "").startswith("Inactive")]) for k, w in converge.items()} self.report["converged_clear_counts"] = counts self.check("converged_clear_exactly_once_both_nodes", all(v == 1 for v in counts.values())) self.check("converged_no_duplicate_eventids", all(self.unique_event_ids(w.blocks(name)) for w in converge.values())) dupes = {k: self.duplicate_transitions(w, (name, native)) for k, w in {**watches, **converge}.items()} self.report["duplicate_transitions"] = dupes self.check("no_duplicate_transitions_any_client", not any(dupes.values())) def scenario_A07(self): """Consumer node restart (the non-Primary member, so no Primary change): a client that subscribes + ConditionRefreshes as soon as the node is up (before the first snapshot barrier) — does it get RefreshRequired, and does it end with the correct view? A ConditionRefresh after the barrier replays the right conditions/state/ConditionIds.""" name, native = self.fixture["conditions"]["scripted"]["condition"], self.fixture["conditions"]["native"]["condition"] source, primary = self.r.primary("source"), self.r.primary("consumer") node = self.partner("consumer", primary) self.report["nodes"] = {"restarted": node, "consumer_primary": primary} origin = self.watch(source, "origin") before = self.watch(node, "before-restart") time.sleep(6) self.raise_scripted() wait_for(lambda: self.latest(before, name, lambda b: b.get("State") == "Active, Unacknowledged") and self.latest(before, native), 150) reference = {"scripted": (self.latest(before, name) or {}).get("ConditionNodeId"), "native": (self.latest(before, native) or {}).get("ConditionNodeId")} self.report["condition_ids_before"] = reference if not self.check("restart_target_imports_before", reference["scripted"] and reference["native"]): return before.stop() since = self.utc(-1) with self.r.stopped(node): time.sleep(3) early = self.start_watch(node, "early") subscribed_at = self.utc() barrier = wait_for(lambda: self.barriers(node, since), 180) time.sleep(10) late = self.watch(node, "late") wait_for(lambda: self.latest(late, name) and self.latest(late, native), 60) time.sleep(3) blocks = early.blocks() end = next((i for i, b in enumerate(blocks) if "RefreshEnd" in (b.get("EventType") or "")), None) end_time = self.block_time(blocks[end]) if end is not None else None barrier_time = self.log_time(barrier[0]) if barrier else None replay_imported = [b for b in blocks[:end] if b.get("Condition") in (name, native)] if end is not None else [] required = self.refresh_required(blocks) self.report["early"] = {"subscribed_at": subscribed_at, "refresh_end_time": end_time, "first_barrier": barrier[:1], "barrier_time": barrier_time, "refresh_preceded_barrier": bool(end_time and barrier_time and end_time < barrier_time), "imported_in_refresh_replay": len(replay_imported), "refresh_required": [(b.get("Time"), b.get("Source")) for b in required], "imported_after_refresh": [(b.get("Condition"), b.get("State"), b.get("Time")) for b in blocks[(end or 0) + 1:] if b.get("Condition") in (name, native)][:10]} self.check("early_refresh_completed", end is not None) self.check("first_barrier_logged", barrier) view = {k: {c: ((self.latest(w, c) or {}).get("ConditionNodeId"), (self.latest(w, c) or {}).get("State")) for c in (name, native)} for k, w in (("early", early), ("late", late))} origin_scripted = (self.latest(origin, name) or {}).get("State") self.report["views"] = {**view, "origin_scripted_state": origin_scripted} self.check("late_refresh_after_snapshot_correct", view["late"][name] == (reference["scripted"], "Active, Unacknowledged") and view["late"][native][0] == reference["native"] and origin_scripted == "Active, Unacknowledged") self.check("early_client_view_matches_after_snapshot", view["early"][name] == view["late"][name] and view["early"][native][0] == view["late"][native][0]) marks = {"early": len(early.blocks(name)), "late": len(late.blocks(name))} self.r.device("set", address=20, value=0) wait_for(lambda: all([b for b in w.blocks(name)[marks[k]:] if (b.get("State") or "").startswith("Inactive")] for k, w in (("early", early), ("late", late))), 60) time.sleep(5) counts = {k: len([b for b in w.blocks(name)[marks[k]:] if (b.get("State") or "").startswith("Inactive")]) for k, w in (("early", early), ("late", late))} self.report["clear_counts"] = counts self.check("positive_control_clear_exactly_once", all(v == 1 for v in counts.values())) self.check("no_duplicate_eventids", self.unique_event_ids(early.blocks(name)) and self.unique_event_ids(late.blocks(name))) dupes = {k: self.duplicate_transitions(w, (name, native)) for k, w in (("early", early), ("late", late))} self.report["duplicate_transitions"] = dupes self.check("no_duplicate_transitions", not any(dupes.values())) # ---- helpers ---------------------------------------------------------------------------------------------------- @staticmethod def _records_summary(result): rows = result.get("results") if isinstance(result, dict) else None row = rows[0] if isinstance(rows, list) and rows else result observations = row.get("observations", row) if isinstance(row, dict) else {} return {"passed": result.get("passed") if isinstance(result, dict) else None, "forbiddenFound": observations.get("forbiddenFound"), "expectedFound": observations.get("expectedFound"), "records": [{"name": (r.get("info") or {}).get("ConditionName"), "placements": (r.get("info") or {}).get("placements")} for r in observations.get("records", [])]} # ---- driver ----------------------------------------------------------------------------------------------------- def run(self, selection): self.r.publish() self.r.rig.seed_helper("snapshot") rows = [] for scenario in selection: self.r.active, self.r.count = "A4S-" + scenario, 0 self.r.deadline = time.monotonic() + TIMEOUTS.get(scenario, 600) self.report = {"id": scenario, "checks": {}, "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} self.watchers = [] error = None try: getattr(self, "scenario_" + scenario)() except Exception as failure: # recorded, never hides restoration error = type(failure).__name__ + ": " + str(failure)[:400] finally: self.stop_watchers() try: # A09 unpauses in its own finally; this covers a failure between its pause and that block. if scenario == "A09" and "paused" in self.r.rig.compose("ps", "--all", "--format", "{{.State}}", "opcplc", timeout=30): self.r.rig.compose("unpause", "opcplc", timeout=60) self.r.device("set", address=20, value=0) if scenario in ("A03", "A08"): self.r.deadline = time.monotonic() + 600 self.r.baseline() self.report["restored"] = self.report.get("restored", True) except Exception as failure: self.report["restored"] = False error = (error + "; " if error else "") + "restoration " + type(failure).__name__ + ": " + str(failure)[:200] self.report["error"] = error self.report["passed"] = error is None and bool(self.report["checks"]) and all(self.report["checks"].values()) self.r.save(f"A4S-{scenario}.json", self.report) rows.append({"id": scenario, "passed": self.report["passed"], "error": error, "failed_checks": [k for k, v in self.report["checks"].items() if not v], "restored": self.report["restored"]}) print(json.dumps(rows[-1]), flush=True) summary = {"run_id": self.r.manifest["run_id"], "source_revision": self.r.manifest.get("source_revision"), "rows": rows, "passed": all(row["passed"] for row in rows)} self.r.save("A4S-results.json", summary) lines = ["| Scenario | Result | Failed checks | Restored |", "|---|---|---|---|"] lines += [f"| {row['id']} | {'PASS' if row['passed'] else 'FAIL'} | {', '.join(row['failed_checks']) or (row['error'] or '—')} | {row['restored']} |" for row in rows] rig.atomic_write_secret(self.r.folder / "A4S-results.md", "\n".join(lines) + "\n") return summary def main(argv=None): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--run-id", required=True) parser.add_argument("--only", default=",".join(SCENARIOS), help="comma-separated scenario ids (default: all implemented)") arguments = parser.parse_args(argv) selection = [item.strip() for item in arguments.only.split(",") if item.strip()] unknown = [item for item in selection if item not in SCENARIOS] if unknown: parser.error("unknown scenario(s): " + ", ".join(unknown)) summary = ConditionScenarios(arguments.run_id).run(selection) print(json.dumps(summary, indent=2)) return 0 if summary["passed"] else 1 if __name__ == "__main__": sys.exit(main())