From 6bf7dc893068f930461293425e7b615a85de9144 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 25 Nov 2026 01:23:14 -0500 Subject: [PATCH] =?UTF-8?q?test(grpc-data):=20A4=20scenarios=20=E2=80=94?= =?UTF-8?q?=20native=20alarm=20on=20EastTank=3FYellow=20(cycles=20live),?= =?UTF-8?q?=20condition=20mappings=20WriteThrough=20(DataMappingOperations?= =?UTF-8?q?Invalid),=20folders=20subscribe=20after=20demand=20opens,=20Con?= =?UTF-8?q?firmedState=20read,=20origin=20audit=20for=20A08=20denial?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../grpc-data/conditions_scenarios.py | 76 +++++++++---------- scripts/validation/grpc-data/seed/Program.cs | 16 ++-- 2 files changed, 47 insertions(+), 45 deletions(-) diff --git a/scripts/validation/grpc-data/conditions_scenarios.py b/scripts/validation/grpc-data/conditions_scenarios.py index 96d60652e..3fa582fcd 100644 --- a/scripts/validation/grpc-data/conditions_scenarios.py +++ b/scripts/validation/grpc-data/conditions_scenarios.py @@ -143,11 +143,11 @@ class ConditionScenarios: 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 its `Id` — resolved, never constructed.""" - rows = self.browse(node, condition_id, depth=2) + """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) - identifier = next((r for r in rows if state and r["name"] == "Id" and r["parent"] == state["node_id"]), None) - return self.read(node, identifier["node_id"], tag) if identifier else {"value": None, "status": "unresolved"} + 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.""" @@ -236,8 +236,8 @@ class ConditionScenarios: 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") == "True") - self.check("origin_confirmed_state_true", (confirmed["origin"] or {}).get("value") == "True") + 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)) @@ -267,7 +267,7 @@ class ConditionScenarios: 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 "successful" in text.lower() and "failed" not in text.lower()) + 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:] @@ -299,39 +299,42 @@ class ConditionScenarios: # 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: - candidates = [folders[alias][0]] + folders[alias][0]["children"][:3] - folder_watches[alias] = [(c["node_id"], self.watch(consumer, f"r{number}-{alias}-{i}", notifier=c["node_id"], refresh=False)) - for i, c in enumerate(candidates)] + folder_watches[alias] = self.watch(consumer, f"r{number}-{alias}", notifier=folders[alias][0]["node_id"], refresh=False) time.sleep(2) - server = self.watch(consumer, f"r{number}-server") - window_start = time.time() + 8 - wait_for(lambda: len([b for b in server.blocks(name) if b.get("EventId")]) >= 4, 120) + 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") and not b.get("Message", "").startswith("Condition refresh")] + server_events = [b for b in server.blocks(name) if b.get("EventId")] ids = {b.get("ConditionNodeId") for b in server_events} - event_ids = [b["EventId"] 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, candidates in folder_watches.items(): - hits = [(node_id, [b["EventId"] for b in w.blocks(name) if b.get("EventId")]) for node_id, w in candidates] - notifier = next(((node_id, events) for node_id, events in hits if events), (None, [])) - per_folder[alias] = {"notifier": notifier[0], "events": len(notifier[1]), - "duplicates": len(notifier[1]) - len(set(notifier[1])), - "condition_ids": sorted({b.get("ConditionNodeId") for _, w in candidates for b in w.blocks(name)})} - # Overlap: every Server-object event raised after all subscribers were up reached each notifier exactly once. - late = [b["EventId"] for b in server_events if self._epoch(b.get("Time")) >= window_start] - for alias, candidates in folder_watches.items(): - seen = [e for node_id, w in candidates if node_id == per_folder[alias]["notifier"] for e in - [b["EventId"] for b in w.blocks(name) if b.get("EventId")]] - per_folder[alias]["late_server_events_missing"] = len([e for e in late if e not in seen]) - rounds.append({"order": order, "condition_ids": sorted(ids), "server_events": len(server_events), - "server_duplicate_event_ids": len(event_ids) - len(set(event_ids)), "late_events": len(late), "folders": 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]["notifier"] and round_["folders"][a]["duplicates"] == 0 for a in mapping_aliases)) + 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)) @@ -383,6 +386,7 @@ class ConditionScenarios: """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") @@ -399,6 +403,10 @@ class ConditionScenarios: 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() @@ -425,14 +433,6 @@ class ConditionScenarios: time.sleep(4) # ---- helpers ---------------------------------------------------------------------------------------------------- - @staticmethod - def _epoch(stamp): - try: - from datetime import datetime - return datetime.fromisoformat((stamp or "")[:26].rstrip("Z") + "+00:00").timestamp() - except ValueError: - return 0 - @staticmethod def _records_summary(result): rows = result.get("results") if isinstance(result, dict) else None diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs index 2e901efd2..2c1974971 100644 --- a/scripts/validation/grpc-data/seed/Program.cs +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -384,8 +384,10 @@ try db.ScriptedAlarms.Add(new() { ScriptedAlarmRowId = Guid.NewGuid(), ScriptedAlarmId = "source-scalar-high", EquipmentId = equipment, Name = "ScalarHigh", AlarmType = "AlarmCondition", MessageTemplate = "scalar high", PredicateScriptId = "source-scalar-high" }); // A4 live scenarios (A02/A04): an OpcUaClient driver against the run-owned opc-plc `--alm` container (compose.conditions.yml), - // one native alarm tag bound 1:1 to the upstream CONDITION node EastTank?Red (several conditions share the EastTank source, - // so the source node would fold them; docs/drivers/OpcUaClient.md "Native alarms"), and a value control tag. The alarm tag is + // one native alarm tag bound 1:1 to the upstream CONDITION node EastTank?Yellow (several conditions share the EastTank source, + // so the source node would fold them; docs/drivers/OpcUaClient.md "Native alarms"), and a value control tag. Yellow, not Red: + // opc-plc's Yellow cycles Active (~40 s) / Inactive (~8 s) on its own, so the origin re-reports it live; Red never leaves + // Active and its heartbeats repeat the last-told state, so once acked it goes silent (live run a4s-1). The alarm tag is // referenced by two NEW equipment (pumpa, pumpb) so the A2a/A3 smokes' `plc` equipment view is unchanged. db.DriverInstances.Add(new() { DriverInstanceRowId = Guid.NewGuid(), DriverInstanceId = "source-opcua", ClusterId = "SOURCE", Name = "opcua", DriverType = "OpcUaClient", DriverConfig = """{"SecurityPolicy":"None","SecurityMode":"None","AuthType":"Anonymous","AutoAcceptCertificates":true}""" }); @@ -393,16 +395,16 @@ try DeviceConfig = """{"EndpointUrl":"opc.tcp://opcplc:50000"}""" }); db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-opcua-fast", DeviceId = "source-opcplc", Name = "FastUInt1", DataType = "UInt32", AccessLevel = TagAccessLevel.Read, WriteIdempotent = false, TagConfig = """{"nodeId":"ns=3;s=FastUInt1"}""" }); - db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-opcua-red", DeviceId = "source-opcplc", Name = "EastTankRed", DataType = "Boolean", + db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-opcua-yellow", DeviceId = "source-opcplc", Name = "EastTankYellow", DataType = "Boolean", AccessLevel = TagAccessLevel.Read, WriteIdempotent = false, - TagConfig = """{"nodeId":"ns=6;s=1:Colours/EastTank?Red","alarm":{"alarmType":"AlarmCondition","severity":500}}""" }); + TagConfig = """{"nodeId":"ns=6;s=1:Colours/EastTank?Yellow","alarm":{"alarmType":"AlarmCondition","severity":500}}""" }); foreach (var pump in new[] { "pumpa", "pumpb" }) { var pumpUuid = Guid.NewGuid(); var pumpId = DraftValidator.DeriveEquipmentId(pumpUuid); pumpEquipment[pump] = pumpId; db.Equipment.Add(new() { EquipmentRowId = Guid.NewGuid(), EquipmentId = pumpId, EquipmentUuid = pumpUuid, UnsLineId = "source-line", Name = pump, MachineCode = "fixture-" + pump }); - db.UnsTagReferences.Add(new() { UnsTagReferenceRowId = Guid.NewGuid(), UnsTagReferenceId = "ref-" + pump + "-red", EquipmentId = pumpId, TagId = "source-opcua-red" }); + db.UnsTagReferences.Add(new() { UnsTagReferenceRowId = Guid.NewGuid(), UnsTagReferenceId = "ref-" + pump + "-yellow", EquipmentId = pumpId, TagId = "source-opcua-yellow" }); } } db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer", ClusterId = "SOURCE", Principal = "fixture-consumer", @@ -453,7 +455,7 @@ try ClusterId = "CONSUMER", DataConnectionId = "consumer-source", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], Realm = realm, RemoteRealm = realm, LocalParentKind = "Cluster", LocalParentId = "CONSUMER", BranchName = "remote-" + id, RemoteRootEntityId = entity, RemoteNamespaceUri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri, - RemoteIdentifierKind = "string", RemoteIdentifier = identifier, AllowedOperations = conditionOps, WriteThrough = false }); + RemoteIdentifierKind = "string", RemoteIdentifier = identifier, AllowedOperations = conditionOps, WriteThrough = true }); } // A04: a UNS-ONLY origin principal (one UNS export, no Raw export) — its condition records must carry no RawPath. db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-pumpa-unsonly", ClusterId = "SOURCE", Enabled = true, @@ -496,7 +498,7 @@ try historized_string = new { raw = "modbus/plc/text", uns = "area/line/plc/text" } } : null, // A4 live scenarios: where the native alarm lives (origin RawPath + equipment) and which consumer mappings place it. conditions = conditions ? new { scripted = new { condition = "ScalarHigh", origin_id = "source-scalar-high", mapping = "map-uns", branch = "remote-source" }, - native = new { condition = "EastTankRed", raw_path = "opcua/opcplc/EastTankRed", upstream = "ns=6;s=1:Colours/EastTank?Red", + native = new { condition = "EastTankYellow", raw_path = "opcua/opcplc/EastTankYellow", upstream = "ns=6;s=1:Colours/EastTank?Yellow", equipment = pumpEquipment, subjects = new { pumpa = "area/line/pumpa", pumpb = "area/line/pumpb" }, raw_root = "opcua/opcplc", mappings = new { raw = "map-opc", pumpa = "map-pumpa", pumpb = "map-pumpb" }, branches = new { raw = "remote-opc", pumpa = "remote-pumpa", pumpb = "remote-pumpb" } } } : null });