"""Executable, fail-closed D01-D14 production-rig orchestration. Every result is derived from a production operation, a deployed artifact, or the run-owned device ledger. Missing instrumentation is a failed assertion. Nothing is skipped by ``all``. The only remote control surface is the software device; host-side controls use exact owned Compose services and the fixture file runner. """ from contextlib import contextmanager, nullcontext import base64 import copy from dataclasses import asdict from datetime import datetime, timedelta, timezone import hashlib import json import math import os from pathlib import Path import re import sys import threading import time import uuid import cli_gate from processes import run_process, redact_text import rig SCENARIOS = ("D01", "D01a", *(f"D{number:02}" for number in range(2, 15))) OPERATIONS = 1 | 2 | 4 | 8 | 16 FIXTURE_CLOCK_ALLOWANCE_SECONDS = 1 # The CONTROL fixture uses MeshTransportOptions.ContactRefreshSeconds (60) # plus five seconds for the asynchronous SQL read and actor adoption. MAINTENANCE_CONTACT_SETTLE_SECONDS = 65 D03_TIMESTAMP_BOUNDARY_COMPANIONS = { "kind": "external_phase_gate_source_references", "scope": "Two separate controlled boundary proofs; execution receipts belong to the phase evidence ledger.", "tests": [ {"boundary": "production TLS gRPC read", "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.csproj", "selector": "FullyQualifiedName=ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.DataConnections.GrpcDataSampleFidelityTlsWireTests.Production_tls_read_preserves_one_controlled_samples_independent_timestamps_status_value_and_version", "source": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataSampleFidelityTlsWireTests.cs"}, {"boundary": "mapped OPC UA SDK read", "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", "selector": "FullyQualifiedName=ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections.GrpcDataConfiguredDiscoveryWireTests.Sdk_mapped_read_preserves_one_controlled_samples_independent_timestamps_quality_value_and_version", "source": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSampleFidelityWireTests.cs"} ] } class ScenarioError(RuntimeError): pass def _fixture_utc_timestamp(value): if not isinstance(value, str): raise ScenarioError("fixture read timestamp is missing") try: parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) except (ValueError, TypeError): raise ScenarioError("fixture read timestamp is invalid") from None if parsed.tzinfo is None or parsed.utcoffset() != timedelta(0): raise ScenarioError("fixture read timestamp must be aware UTC") if parsed.year <= 1601 or parsed.year == 9999: raise ScenarioError("fixture read timestamp is a sentinel") return parsed def validate_fixture_read_timestamps(observed, *, modbus_fixture=False): """Validate each cached sample against its own observed CLI completion.""" if not isinstance(observed, dict) or observed.get("status") != "Good": raise ScenarioError("fixture CLI read must be Good") source = _fixture_utc_timestamp(observed.get("source_time")) server = _fixture_utc_timestamp(observed.get("server_time")) completed = _fixture_utc_timestamp(observed.get("completed_at_utc")) latest = completed + timedelta(seconds=FIXTURE_CLOCK_ALLOWANCE_SECONDS) if source > latest or server > latest: raise ScenarioError("fixture read timestamp exceeds its CLI completion clock allowance") # This fixture's Modbus acquisition sets source time before server time. # Other sources can carry independent clocks and have no ordering contract. if modbus_fixture and source > server: raise ScenarioError("Modbus fixture source timestamp exceeds server timestamp") return observed def validate_fixture_read_pair(origin, mapped, *, modbus_fixture=False): """Compare stable fixture values while retaining independent cached sample times.""" validate_fixture_read_timestamps(origin, modbus_fixture=modbus_fixture) validate_fixture_read_timestamps(mapped, modbus_fixture=modbus_fixture) if not origin.get("value") or origin.get("value") != mapped.get("value"): raise ScenarioError("origin and mapped fixture values differ") return {"origin": origin, "mapped": mapped, "clock_allowance_seconds": FIXTURE_CLOCK_ALLOWANCE_SECONDS, "modbus_source_not_after_server": modbus_fixture, "comparison": "independent cached samples with matching fixture values"} def fixture_browse_root(fixture, realm): """UNS container identity is an EquipmentId, separate from leaf paths.""" roots = fixture.get("browse_roots") if isinstance(fixture, dict) else None root = roots.get(realm) if isinstance(roots, dict) else None if realm not in {"raw", "uns"} or not isinstance(root, str) or not root or len(root) > 1024: raise ScenarioError("explicit fixture browse container identity missing") return root def relative_origin_identifier(fixture, realm, identifier, name): return identifier.rsplit("/", 1)[0] + "/" + name if name else fixture_browse_root(fixture, realm) def validate_read_freshness(observed, maximum_age_ms=5000): if (not isinstance(observed, dict) or observed.get("status") != "Good" or observed.get("resultReadiness") != "Ready" or observed.get("maximumAgeMilliseconds") != maximum_age_ms): raise ScenarioError("actual read readiness or requested freshness differs") if maximum_age_ms is not None: bounds = observed.get("ageBounds") lower = bounds.get("lowerMilliseconds") if isinstance(bounds, dict) else None upper = bounds.get("upperMilliseconds") if isinstance(bounds, dict) else None if (type(lower) not in (int, float) or type(upper) not in (int, float) or not math.isfinite(lower) or not math.isfinite(upper) or not 0 <= lower <= upper <= maximum_age_ms): raise ScenarioError("actual read has no finite age within requested bound") return observed def validate_warm_secondary_read(observed, *, expected_node_id): """Validate payloadless API-eligible Secondary data; startup Warm Standby uses selection rejection.""" if (not isinstance(observed, dict) or observed.get("status") not in {"WaitingForInitialData", "Unavailable"} or observed.get("resultReadiness") not in {"WaitingForInitialData", "Unavailable", "Invalidated"} or "sample" not in observed or observed["sample"] is not None): raise ScenarioError("Warm secondary must expose only unavailable or waiting data without a sample") serving, target = observed.get("serving"), observed.get("target") if (not isinstance(serving, dict) or serving.get("nodeId") != expected_node_id or serving.get("role") != "Secondary" or not isinstance(target, dict) or target.get("mode") != "Node" or target.get("consistency") != "ReadyReplica" or target.get("expectedClusterId") != "SOURCE" or target.get("expectedNodeId") != expected_node_id): raise ScenarioError("Warm secondary read moved outside its exact pinned secondary") return observed def validate_startup_warm_state(observed, *, expected_node_id, expected_role=None): if (not isinstance(observed, dict) or observed.get("nodeId") != expected_node_id or observed.get("mode") != "Warm" or observed.get("isWarm") is not True): raise ScenarioError("SOURCE node has not proven startup Warm mode") role, serving, process = observed.get("warmRole"), observed.get("serving"), observed.get("process") if (not isinstance(role, dict) or role.get("role") not in {"Active", "Standby"} or type(role.get("generation")) is not int or role["generation"] <= 0 or expected_role is not None and role["role"] != expected_role or not isinstance(serving, dict) or serving.get("nodeId") != expected_node_id or serving.get("role") != ("Primary" if role["role"] == "Active" else "Standby") or not isinstance(serving.get("incarnation"), str) or not serving["incarnation"] or any(type(serving.get(key)) is not int or serving[key] <= 0 for key in ("catalogEpoch", "authorityEpoch", "servingGeneration")) or not isinstance(process, dict) or type(process.get("id")) is not int or process["id"] <= 0): raise ScenarioError("SOURCE Warm verdict, serving identity or process proof is incomplete") _fixture_utc_timestamp(process.get("startedUtc")) return observed def select_warm_pair(states): if not isinstance(states, dict) or set(states) != {"source-1", "source-2"}: raise ScenarioError("the exact owned SOURCE Warm pair is required") for node, observed in states.items(): validate_startup_warm_state(observed, expected_node_id=node + ":4053") active = [node for node, observed in states.items() if observed["warmRole"]["role"] == "Active"] standby = [node for node, observed in states.items() if observed["warmRole"]["role"] == "Standby"] if len(active) != 1 or len(standby) != 1: raise ScenarioError("SOURCE Warm pair must prove one actual Active and one Standby") return active[0], standby[0] def validate_warm_target_rejection(observed, source_state, *, expected_node_id): validate_startup_warm_state(source_state, expected_node_id=expected_node_id, expected_role="Standby") if not isinstance(observed, dict): raise ScenarioError("Warm Standby target rejection evidence is missing") target, failure = observed.get("target"), observed.get("failureEvidence") chain = failure.get("chain") if isinstance(failure, dict) else None if (observed.get("selectionRejection") != "TargetIneligible" or observed.get("failurePhase") != "GetCapabilities" or observed.get("readiness") != "Unavailable" or observed.get("sample") is not None or not isinstance(target, dict) or target.get("mode") != "Node" or target.get("consistency") != "ReadyReplica" or target.get("expectedClusterId") != "SOURCE" or target.get("expectedNodeId") != expected_node_id or not isinstance(failure, dict) or failure.get("category") != "TargetIneligible" or failure.get("truncated") is not False or not isinstance(chain, list) or not 1 <= len(chain) <= 8 or not all(isinstance(frame, dict) and frame.get("code") in {"NoReadyEndpoint", "TargetIneligible"} and frame.get("rpcStatus") is None for frame in chain) or not any(frame.get("code") == "TargetIneligible" for frame in chain)): raise ScenarioError("Warm Standby requires exact authenticated target-ineligible proof, not transport or TLS failure") return observed def is_key_only_mutation(mutation): return (isinstance(mutation, dict) and isinstance(mutation.get("key_action"), str) and mutation["key_action"] in {"rotate", "rotate_staged", "expire", "retire_old", "revoke"} and set(mutation) <= {"key_action", "key_expiry_seconds"}) def validate_key_only_revision_receipt(receipt, *, action): if (not isinstance(receipt, dict) or set(receipt) != {"keyAction", "revisions"} or receipt.get("keyAction") != action or not is_key_only_mutation({"key_action": action})): raise ScenarioError("credential mutation revision receipt does not match the requested action") revisions = receipt["revisions"] if (not isinstance(revisions, dict) or set(revisions) != {"CredentialOnly", "Before", "After"} or revisions.get("CredentialOnly") is not True): raise ScenarioError("credential mutation was not isolated from configuration revisions") for snapshot in (revisions["Before"], revisions["After"]): if not isinstance(snapshot, dict) or set(snapshot) != {"Connection", "Mappings", "Exports"}: raise ScenarioError("credential revision snapshot is incomplete") values = [snapshot["Connection"]] for kind in ("Mappings", "Exports"): rows = snapshot[kind] if (not isinstance(rows, dict) or len(rows) > 256 or any(not isinstance(identity, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", identity) for identity in rows)): raise ScenarioError("credential revision snapshot has invalid entity identities") values.extend(rows.values()) if any(type(value) is not int or not 0 < value <= 2**63 - 1 for value in values): raise ScenarioError("credential revision snapshot must contain positive numeric revisions") if revisions["Before"] != revisions["After"]: raise ScenarioError("credential-only mutation changed connection, mapping or export revisions") return receipt def metadata_lease_seconds(lease): duration = lease.get("duration") if isinstance(lease, dict) else None if not isinstance(duration, str) or not re.fullmatch(r"\d{2}:\d{2}:\d{2}(?:\.\d{1,7})?", duration): raise ScenarioError("observed metadata lease duration is missing") hours, minutes, seconds = duration.split(":") value = int(hours) * 3600 + int(minutes) * 60 + float(seconds) if not 0 < value <= 60 or int(minutes) >= 60 or float(seconds) >= 60: raise ScenarioError("observed metadata lease exceeds the bounded fixture wait") return value def validate_tls_rejection_counters(before, after): identity = before.get("inboundDataRequestObserverId") if (not isinstance(identity, str) or not identity or after.get("inboundDataRequestObserverId") != identity or type(before.get("inboundDataRequests")) is not int or before["inboundDataRequests"] != 0 or type(after.get("inboundDataRequests")) is not int or after["inboundDataRequests"] != 0): raise ScenarioError("TLS-negative requests reached HTTP or the listener observer changed") return {"observer_id": identity, "http_requests_before": 0, "http_requests_after": 0} class NotificationLines: """Incrementally parse complete CLI notification lines without duplicate arrivals.""" def __init__(self): self.pending = "" def feed(self, chunk): self.pending += chunk if len(self.pending) > 65536: raise ScenarioError("oversized CLI notification line") lines = self.pending.split("\n") self.pending = lines.pop() return [parsed for line in lines if (parsed := cli_gate.parse_notification(line)) is not None] def required_matrix_cells(): """Executable cells from the plan's topology/realm/operation matrix.""" cells = [] def add(scenario, topology, mode, surface, operations, outcome="Good", boundary="primary"): for realm in ("raw", "uns"): for operation in operations: cells.append({"id": ".".join((scenario, topology, mode, surface, boundary, realm, operation)), "scenario": scenario, "topology": topology, "target_mode": mode, "surface": surface, "boundary": boundary, "realm": realm, "operation": operation, "outcome": outcome, "target_consistency": "ReadyReplica" if boundary in {"secondary", "wrong-ca", "wrong-san", "retired-ca"} else "Primary", "caller_cluster": "SOURCE" if topology == "same-cluster" else "CONSUMER", "target_cluster": "SOURCE"}) for topology, mode in (("cross-cluster", "Cluster"), ("cross-cluster", "Node"), ("same-cluster", "Node")): add("D01a", topology, mode, "direct", ("capabilities", "browse", "metadata", "read", "write", "subscribe")) add("D02", "same-cluster", "Node", "direct", ("capabilities", "browse", "metadata", "read", "write", "subscribe")) add("D02", "same-cluster", "Node", "mounted", ("read",)) add("D02", "same-cluster", "Node", "mounted", ("write",), "Denied", "local-standby") add("D02", "same-cluster", "Node", "direct", ("read",), boundary="secondary") add("D02", "same-cluster", "Node", "direct", ("write",), "RejectedBeforeDispatch", "secondary") for mode in ("Node", "Cluster"): add("D03", "cross-cluster", mode, "mounted", ("browse", "read")) add("D03", "cross-cluster", mode, "direct", ("metadata",)) add("D04", "cross-cluster", mode, "mounted", ("write", "subscribe")) add("D07", "cross-cluster", "Node", "direct", ("capabilities",), "Unavailable", "pinned-loss") add("D07", "cross-cluster", "Node", "mounted", ("read",), "Denied", "pinned-loss") add("D07", "cross-cluster", "Cluster", "direct", ("capabilities",), "Unavailable", "maintenance-primary") add("D07", "cross-cluster", "Cluster", "direct", ("read",), boundary="maintenance-exclusion") add("D07", "cross-cluster", "Cluster", "mounted", ("subscribe",), boundary="source-failover") add("D09", "cross-cluster", "Node", "direct", ("read",), boundary="secondary") add("D09", "cross-cluster", "Node", "direct", ("write",), "RejectedBeforeDispatch", "secondary") add("D10", "cross-cluster", "Cluster", "mounted", ("subscribe",), boundary="consumer-failover") for boundary in ("wrong-ca", "wrong-san"): add("D13", "cross-cluster", "Node", "direct", ("capabilities",), "Unavailable", boundary) add("D14", "cross-cluster", "Node", "direct", ("capabilities",), "Unavailable", "retired-ca") return cells MATRIX_CELLS = required_matrix_cells() def matrix_cell_id(scenario, topology, mode, surface, realm, operation, boundary="primary"): return ".".join((scenario, topology, mode, surface, boundary, realm, operation)) def validate_matrix_cells(observed, selected=SCENARIOS): required = {cell["id"]: cell for cell in MATRIX_CELLS if cell["scenario"] in selected} if not isinstance(observed, list): raise ScenarioError("observed matrix cells missing") ids = [cell.get("id") for cell in observed if isinstance(cell, dict)] if len(ids) != len(observed) or len(ids) != len(set(ids)) or set(ids) != set(required): raise ScenarioError("required topology/realm/operation cells missing or duplicated") for cell in observed: expected = required[cell["id"]] if any(cell.get(key) != value for key, value in expected.items()) or cell.get("validated") is not True: raise ScenarioError("observed matrix cell differs from required routing") if not cell.get("caller_node_id") or not isinstance(cell.get("evidence"), dict): raise ScenarioError("matrix cell lacks actual caller and operation evidence") probe = cell["evidence"].get("probe") target = probe.get("target") if isinstance(probe, dict) else None if (not isinstance(target, dict) or probe.get("callerNodeId") != cell["caller_node_id"] or probe.get("callerClusterId") != expected["caller_cluster"] or probe.get("realm", "").lower() != expected["realm"] or target.get("mode") != expected["target_mode"] or target.get("expectedClusterId") != expected["target_cluster"] or target.get("consistency") != expected["target_consistency"] or not probe.get("namespaceUri") or not probe.get("path")): raise ScenarioError("matrix observed caller/target/realm routing evidence invalid") serving = probe.get("serving") if expected["outcome"] == "Unavailable" or expected["boundary"] == "pinned-loss": if probe.get("readiness") != "Unavailable" or serving: raise ScenarioError("matrix unavailable endpoint unexpectedly served") elif not isinstance(serving, dict) or serving.get("nodeId") != cell.get("serving_node_id"): raise ScenarioError("matrix actual serving identity missing") elif serving.get("role") != ("Secondary" if expected["boundary"] == "secondary" else "Primary"): raise ScenarioError("matrix serving role differs from required boundary") if expected["target_mode"] == "Node" and (not target.get("expectedNodeId") or isinstance(serving, dict) and serving["nodeId"] != target["expectedNodeId"]): raise ScenarioError("matrix pinned node substituted another endpoint") if expected["surface"] == "mounted" and not cell["evidence"].get("cli"): raise ScenarioError("matrix mounted operation has no CLI evidence") return True class ControlledFixtureSource: """Keep ordinary changes disjoint from a reserved, one-shot recovery value.""" def __init__(self, device, initial, used_values): self.device = device self.current = initial self.initial_value = initial self.ordinary_wrap_count = 0 self.used_values = used_values self.used_values.add(initial) self.lock = threading.Lock() self.paused = threading.Event() self.sentinel_value = next((value for value in range(65535, 32767, -1) if value not in used_values), None) if self.sentinel_value is None: raise ScenarioError("bounded recovery sentinel space exhausted") self.used_values.add(self.sentinel_value) self.reserved_at = time.monotonic() self.published = False def tick(self): with self.lock: if self.paused.is_set(): return False # Regular production never visits the reserved high UInt16 band. next_value = (self.current + 1) % 32768 if self.current < 32768 and next_value <= self.current: self.ordinary_wrap_count += 1 self.current = next_value self.used_values.add(self.current) self.device("advance", steps=1) self.device("set", address=20, value=self.current) return True @contextmanager def sentinel(self): with self.lock: if self.published or self.paused.is_set(): raise ScenarioError("recovery sentinel may be produced once per controlled source") self.paused.set() self.published = True produced_at = time.monotonic() try: state = self.device("set", address=20, value=self.sentinel_value) except BaseException: self.paused.clear() raise confirmed_at = time.monotonic() if state.get("writable", {}).get("20") != self.sentinel_value: self.paused.clear() raise ScenarioError("fixture did not confirm the recovery sentinel") try: yield {"value": str(self.sentinel_value), "reserved_at": self.reserved_at, "produced_at": produced_at, "confirmed_at": confirmed_at} finally: self.paused.clear() def validate_fault_notifications(notifications, *, fault_at, require_gap, required_sentinel, effective_at=None, withdrawal_at=None, reauthorization_at=None, reauthorization_completed_at=None): """Use arrival times captured once per complete CLI line, not whole-log matches.""" before = [row for row in notifications if row["at"] < fault_at and cli_gate.is_good_status(row["status"])] after = [row for row in notifications if row["at"] >= (effective_at if effective_at is not None else fault_at) and cli_gate.is_good_status(row["status"])] if not before or not after or not any(row["value"] != before[-1]["value"] for row in after): raise ScenarioError("CLI has no fresh changing Good notification after the actual fault") if (not isinstance(required_sentinel, dict) or not isinstance(required_sentinel.get("value"), str) or not required_sentinel["value"].isdigit() or not 32768 <= int(required_sentinel["value"]) <= 65535 or not isinstance(required_sentinel.get("reserved_at"), (int, float)) or not isinstance(required_sentinel.get("produced_at"), (int, float)) or not isinstance(required_sentinel.get("confirmed_at"), (int, float)) or not required_sentinel["reserved_at"] < fault_at or not (effective_at if effective_at is not None else fault_at) <= required_sentinel["produced_at"] <= required_sentinel["confirmed_at"]): raise ScenarioError("unique post-fault source sentinel evidence missing") sentinel_rows = [row for row in notifications if cli_gate.is_good_status(row["status"]) and row["value"] == required_sentinel["value"]] if (not sentinel_rows or any(row["at"] < required_sentinel["produced_at"] for row in sentinel_rows) or not any(row["at"] >= required_sentinel["produced_at"] for row in after if row["value"] == required_sentinel["value"])): raise ScenarioError("CLI did not observe the newly produced recovery sentinel") if require_gap: gaps = [row for row in notifications if row["at"] >= fault_at and row["status"].startswith("Bad")] if not gaps or not any(row["at"] > gaps[0]["at"] for row in after): raise ScenarioError("CLI lacks a fault-time quality gap followed by Good recovery") if withdrawal_at is not None: if reauthorization_at is None or reauthorization_at - withdrawal_at < 1: raise ScenarioError("authorization withdrawal observation interval missing") if any(cli_gate.is_good_status(row["status"]) and withdrawal_at <= row["at"] < reauthorization_at for row in notifications): raise ScenarioError("CLI emitted Good during withdrawn authorization") if not any(row["at"] >= reauthorization_at for row in after): raise ScenarioError("CLI lacks Good after reauthorization") if (reauthorization_completed_at is None or reauthorization_completed_at < reauthorization_at or required_sentinel["produced_at"] < reauthorization_completed_at): raise ScenarioError("recovery sentinel preceded completed reauthorization") return {"fault_at": fault_at, "fault_effective_at": effective_at, "post_fault_good": len(after), "notifications": notifications, "withdrawal_at": withdrawal_at, "reauthorization_at": reauthorization_at, "reauthorization_completed_at": reauthorization_completed_at, "sentinel": required_sentinel, "sentinel_notifications": len(sentinel_rows)} def validate_source_outage_notification(notifications, *, stop_requested_at, stop_completed_at): """Require the latest actual quality to show the current shutdown outage. Graceful shutdown may emit its only Bad before Docker stop completes. That observation remains useful after completion only until a later Good arrives. Callers inspect the notification list while holding its append lock. """ if (any(type(value) not in (int, float) or not math.isfinite(value) for value in (stop_requested_at, stop_completed_at)) or stop_requested_at > stop_completed_at or not notifications): raise ScenarioError("SOURCE outage boundaries or actual notification are missing") latest = notifications[-1] arrival = latest.get("at") if isinstance(latest, dict) else None status = latest.get("status") if isinstance(latest, dict) else None if (type(arrival) not in (int, float) or not math.isfinite(arrival) or not stop_requested_at <= arrival <= stop_requested_at + 45 or not isinstance(status, str) or not status or cli_gate.is_good_status(status)): raise ScenarioError("latest CLI quality does not prove the requested SOURCE outage") return arrival def validate_post_lease_progress(notifications, *, boundary_at, ordinary_floor, ordinary_wrap_count): """Exclude queued pre-boundary data and high-band sentinels from ordinary progress.""" if (type(ordinary_floor) is not int or not 0 <= ordinary_floor < 32768 or type(ordinary_wrap_count) is not int or ordinary_wrap_count != 0): raise ScenarioError("post-lease ordinary source floor is invalid") values, arrivals = [], [] for row in notifications: value = row.get("value") if (row["at"] >= boundary_at and cli_gate.is_good_status(row["status"]) and isinstance(value, str) and value.isdigit() and ordinary_floor < int(value) < 32768 and int(value) not in values): values.append(int(value)); arrivals.append(row["at"]) if len(values) == 2: return {"boundary_at": boundary_at, "ordinary_floor": ordinary_floor, "ordinary_wrap_count": ordinary_wrap_count, "ordinary_values": values, "observed_at": arrivals} raise ScenarioError("live CLI lacks two fresh ordinary changes after the metadata-lease boundary") def validate_probe_result(result, *, expected_id, expected_operation=None): if not isinstance(result, dict) or result.get("id") != expected_id or result.get("passed") is not True: raise ScenarioError("production probe did not pass the requested command") if type(result.get("assertions")) is not int or result["assertions"] <= 0: raise ScenarioError("probe supplied no assertions") if expected_operation is not None and result.get("operation") != expected_operation: raise ScenarioError("probe operation mismatch") if not isinstance(result.get("observations"), dict): raise ScenarioError("probe observations missing") return result def validate_scenario_rows(rows, expected): if len(rows) != len(expected) or [row.get("id") for row in rows] != list(expected): raise ScenarioError("scenario result coverage is incomplete or reordered") if not all(row.get("passed") is True and type(row.get("assertions")) is int and row["assertions"] > 0 and row.get("restored") is True for row in rows): return False try: return all(validate_matrix_cells(row.get("cells"), (row["id"],)) for row in rows) except ScenarioError: return False def restricted_json(path): path = Path(path) if not path.is_absolute() or path.is_symlink() or not path.is_file() or path.stat().st_size > 8 * 1024 * 1024: raise ScenarioError("restricted run file missing or invalid") if os.name != "nt" and path.stat().st_mode & 0o077: raise ScenarioError("run file must not be accessible by group or others") return json.loads(path.read_text()) def probe_timeout_seconds(operation, timeout): """Bound each operation while leaving the default origin write enough dispatch time.""" if timeout is not None: return timeout if operation == "dedup": return 70 if operation in {"write", "mixed-write"}: return 40 return 20 def cli_timeout_seconds(operation, duration): return 60 if operation == "write" else duration + 20 class ScenarioRunner: def __init__(self, run_id, *, manifest_path=None, cli_dll=None, probe_dll=None): self.rig = rig.LocalRig(run_id) self.manifest_path = Path(manifest_path or self.rig.path).resolve() if self.manifest_path != self.rig.path.resolve(): raise ScenarioError("scenario mutations require this run's canonical manifest") self.manifest = restricted_json(self.manifest_path) self.initial_resolved = copy.deepcopy(self.manifest.get("resolved_nodes", {})) rig.validate_manifest(self.manifest, expected_run_id=run_id) if self.manifest.get("state") != "ready": raise ScenarioError("the deployed production fixture must be ready") self.rig.verify_candidate() self.folder = self.rig.folder / "evidence" self.folder.mkdir(mode=0o700, exist_ok=True) self.cli_dll = Path(cli_dll or self.rig.folder / "tools" / "cli" / "ZB.MOM.WW.OtOpcUa.Client.CLI.dll").resolve() self.probe_dll = Path(probe_dll or self.rig.folder / "tools" / "probe" / "GrpcDataProbe.dll").resolve() self.secrets = [] for path in [self.manifest["credentials"]["cli_key_file"], *self.manifest["credentials"]["data_key_files"].values()]: file = Path(path) if not file.is_absolute() or not file.resolve().is_relative_to(self.rig.folder.resolve()) or file.is_symlink() or not file.is_file() or (os.name != "nt" and file.stat().st_mode & 0o077): raise ScenarioError("credential file must be restricted") self.secrets.append(file.read_text().strip()) self.key = self.secrets[0] self.count = 0 self.records = [] self.deadline = 0 self.active = "" self.timeline = [] self.catalog = json.loads((rig.HERE / "scenarios.json").read_text()) if tuple(self.catalog["required_order"]) != SCENARIOS: raise ScenarioError("required scenario catalog is incomplete") if self.catalog.get("required_cells") != MATRIX_CELLS: raise ScenarioError("required topology/realm/operation catalog is incomplete") self.matrix_cells = [] def record_matrix_cell(self, topology, mode, surface, realm, operation, caller, observed, *, boundary="primary", expected_node=None, cli_evidence=None): identity = matrix_cell_id(self.active, topology, mode, surface, realm, operation, boundary) required = next((cell for cell in MATRIX_CELLS if cell["id"] == identity), None) self.check(required is not None, "declared matrix cell") self.check(not any(cell["id"] == identity for cell in self.matrix_cells), "matrix cell recorded exactly once") self.check(observed.get("callerNodeId") == self.node_id(caller) and observed.get("callerClusterId") == self.manifest["nodes"][caller]["cluster_id"] == required["caller_cluster"], "actual caller identity and topology") target = observed.get("target") self.check(isinstance(target, dict) and target.get("mode") == mode and target.get("expectedClusterId") == required["target_cluster"] and target.get("consistency") == required["target_consistency"], "actual configured target mode, cluster and consistency") self.check(observed.get("realm", "").lower() == realm and observed.get("namespaceUri") == self.manifest["fixture"]["namespace_uris"][realm], "executed origin realm and namespace") serving = observed.get("serving") if required["outcome"] != "Unavailable" and boundary != "pinned-loss": self.check(isinstance(serving, dict) and serving.get("nodeId") in { row["node_id"] for row in self.manifest["nodes"].values() if row["cluster_id"] == "SOURCE"}, "observed serving node belongs to origin") if expected_node is not None: self.check(serving["nodeId"] == self.node_id(expected_node), "actual serving node matches selected boundary") self.check(serving.get("role") == ("Secondary" if boundary == "secondary" else "Primary"), "actual target role matches boundary") if mode == "Node": self.check(expected_node is not None and target.get("expectedNodeId") == self.node_id(expected_node), "actual pinned identity") if isinstance(serving, dict): self.check(serving["nodeId"] == target["expectedNodeId"], "pinned target never substitutes partner") if surface == "mounted": self.check(isinstance(cli_evidence, dict) and bool(cli_evidence), "validated actual CLI operation evidence") elif operation == "read": self.check(observed.get("status") == required["outcome"], "observed read outcome") elif operation == "write": self.check(isinstance(observed.get("outcomes"), list) and bool(observed["outcomes"]), "observed write outcome evidence") state = observed["outcomes"][0].get("outcome", {}).get("state") self.check(state in ((1, "RejectedBeforeDispatch") if required["outcome"] == "RejectedBeforeDispatch" else (2, "DriverConfirmedSuccess")), "observed exact write outcome") elif required["outcome"] == "Unavailable": self.check(observed.get("readiness") == "Unavailable" and not serving, "actual pinned endpoint unavailable") evidence = {"probe": observed, **({"cli": cli_evidence} if cli_evidence is not None else {})} self.matrix_cells.append({**required, "validated": True, "caller_node_id": observed["callerNodeId"], "serving_node_id": serving.get("nodeId") if isinstance(serving, dict) else None, "evidence": evidence}) def matrix_probe(self, topology, mode, realm, operation, caller, *, boundary="primary", expected_node=None, connection="consumer-source", **fields): observed = self.probe(caller, operation, realm, connection=connection, **({"expectedNodeId": self.node_id(expected_node)} if expected_node else {}), **fields) self.record_matrix_cell(topology, mode, "direct", realm, "write" if operation == "dedup" else operation, caller, observed, boundary=boundary, expected_node=expected_node) return observed def matrix_cli(self, topology, mode, realm, operation, caller, *, boundary="primary", expected_node=None, connection="consumer-source", observed=None, **fields): evidence = self.cli(operation, caller, realm, **fields) if observed is None: observed = self.probe(caller, "capabilities", realm, connection=connection, **({"expectedNodeId": self.node_id(expected_node)} if expected_node else {})) self.record_matrix_cell(topology, mode, "mounted", realm, operation, caller, observed, boundary=boundary, expected_node=expected_node, cli_evidence=evidence) return evidence def prepare_positive_projection(self, node, realm): """Materialize the exact positive target through the caller's authenticated Browse.""" self.wait_connection_ready(node, realm) return self.cli("browse", node, realm, recursive=True) def wait_connection_ready(self, caller, realm="raw", *, expected_node=None, require_fresh_sample=False): end = time.monotonic() + self.remaining(30) while True: try: timeout = max(1, min(10, int(end - time.monotonic()))) observed = self.probe(caller, "capabilities", realm, expected_state="Ready", timeout=timeout, **({"expectedNodeId": self.node_id(expected_node)} if expected_node else {})) if require_fresh_sample: observed = self.probe(caller, "read", realm, timeout=max(1, min(10, int(end - time.monotonic()))), **({"expectedNodeId": self.node_id(expected_node)} if expected_node else {})) return observed except ScenarioError: if time.monotonic() >= end: raise ScenarioError("actual caller connection did not regain authenticated readiness") time.sleep(min(.5, max(0, end - time.monotonic()))) def remaining(self, maximum=30): remaining = self.deadline - time.monotonic() if remaining <= 0: raise ScenarioError("scenario deadline exceeded") return min(remaining, maximum) def check(self, condition, name): if not condition: raise ScenarioError(name) self.count += 1 def save(self, name, body): text = json.dumps(body, indent=2, sort_keys=True) rig.atomic_write_secret(self.folder / name, redact_text(text, self.secrets) + "\n") def process(self, argv, name, *, timeout=30): result = run_process(argv, timeout=self.remaining(timeout), secrets=self.secrets, cwd=rig.ROOT, environment=self.rig.environment) self.save(name + ".process.json", asdict(result)) return result def publish(self): tools = {} source_hash = rig.source_tree_hash() for project, dll in ((rig.ROOT / "src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/ZB.MOM.WW.OtOpcUa.Client.CLI.csproj", self.cli_dll), (rig.HERE / "probe/GrpcDataProbe.csproj", self.probe_dll)): stamp_path = dll.parent / "published.json" stamp = restricted_json(stamp_path) if stamp_path.exists() else {} digest = hashlib.sha256(dll.read_bytes()).hexdigest() if dll.is_file() else None if (digest and stamp.get("source_revision") == self.manifest.get("source_revision") and stamp.get("source_tree_hash") == source_hash and stamp.get("sha256") == digest): tools[dll.stem] = stamp continue dll.parent.mkdir(mode=0o700, parents=True, exist_ok=True) result = run_process(["dotnet", "publish", str(project), "-c", "Release", "-o", str(dll.parent)], timeout=600, secrets=self.secrets, cwd=rig.ROOT, environment=self.rig.environment) self.save("publish-" + dll.stem + ".json", asdict(result)) if result.returncode != 0 or result.cancelled or result.timed_out or result.truncated or not dll.is_file(): raise ScenarioError("publish did not produce the expected portable DLL") stamp = {"dll": str(dll), "source_revision": self.manifest.get("source_revision"), "source_tree_hash": source_hash, "sha256": hashlib.sha256(dll.read_bytes()).hexdigest()} rig.atomic_write_secret(stamp_path, json.dumps(stamp)) tools[dll.stem] = stamp self.manifest["tools"] = tools self.rig.save(self.manifest) def endpoint(self, node, kind="opcua"): return self.manifest["endpoints"][node + "." + kind]["url"] def primary(self, pair): nodes = [node for node in self.manifest["nodes"] if node.startswith(pair + "-")] try: active = rig.observe_active_endpoint({node: self.endpoint(node, "admin") for node in nodes}, request=rig.http_request, timeout=self.remaining(10)) except rig.RigError as error: raise ScenarioError(str(error)) from None self.check(active is not None, "pair must have one observed active node") return active def wait_primary(self, pair, *, exclude=None): while True: try: node = self.primary(pair) if node != exclude: return node except (OSError, ScenarioError): pass time.sleep(self.remaining(0.5)) def wait_pair_topology(self, pair): nodes = sorted(node for node in self.manifest["nodes"] if node.startswith(pair + "-")) self.check(len(nodes) == 2, "exact fixture pair inventory") expected = {self.node_id(node) for node in nodes} deadline = time.monotonic() + self.remaining(45) while time.monotonic() < deadline: try: observed = [self.probe(node, "topology", timeout=3) for node in nodes] if all(state["self"].endswith("@" + self.node_id(node)) and len(state["members"]) == 2 and {f"{member['host']}:{member['port']}" for member in state["members"] if member["status"] == "Up"} == expected for node, state in zip(nodes, observed, strict=True)): return except (ScenarioError, OSError): pass time.sleep(min(.5, max(0, deadline - time.monotonic()))) raise ScenarioError(f"{pair} pair did not rejoin with both expected Up members") def wait_warm_pair(self): end = time.monotonic() + self.remaining(60) while True: states = {node: self.probe(node, "warm-state") for node in ("source-1", "source-2")} try: select_warm_pair(states) return states except ScenarioError: if time.monotonic() >= end: raise time.sleep(min(.2, max(0, end - time.monotonic()))) def wait_warm_state(self, node, expected_role): end = time.monotonic() + self.remaining(60) while True: observed = self.probe(node, "warm-state") try: return validate_startup_warm_state(observed, expected_node_id=self.node_id(node), expected_role=expected_role) except ScenarioError: if time.monotonic() >= end: raise time.sleep(min(.2, max(0, end - time.monotonic()))) def node_id(self, node): return self.manifest["nodes"][node]["node_id"] def leaf(self, node, realm, *, counter=False): resolved = self.manifest.get("resolved_nodes", self.initial_resolved).get(node, self.initial_resolved[node]) if realm not in resolved.get("aliases", {}): resolved = self.initial_resolved[node] leaf = resolved["aliases"][realm] uri = self.manifest["fixture"]["namespace_uris"][("mapped_" if node.startswith("consumer-") else "") + realm] match = re.fullmatch(r"ns=(\d+);s=(.+)", leaf) self.check(match is not None, "resolved string NodeId required") identifier = match[2] self.check(cli_gate.resolve_node_id(resolved["namespace_uris"], uri, identifier) == leaf, "NamespaceArray identity") if counter: return self.relative_node(node, realm, "counter") return leaf def relative_node(self, node, realm, name, *, mapping_id=None): leaf = self.leaf(node, realm) ns, identifier = leaf.split(";s=", 1) if identifier.startswith("p1."): payload = identifier[3:] decoded = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) origin = decoded["Origin"] origin["Identifier"] = relative_origin_identifier(self.manifest["fixture"], realm, origin["Identifier"], name) if mapping_id is not None: decoded["MappingId"] = mapping_id identifier = "p1." + base64.urlsafe_b64encode(json.dumps(decoded, separators=(",", ":")).encode()).decode().rstrip("=") else: identifier = relative_origin_identifier(self.manifest["fixture"], realm, identifier, name) return ns + ";s=" + identifier def cli(self, command, node, realm="raw", *, value=42, denial=False, partner=None, duration=8, counter=False, recursive=False, target_override=None, expected_nodes=None, absent_nodes=(), denial_statuses=None): identity = self.active + "-" + command + "-" + uuid.uuid4().hex[:8] summary = self.folder / (identity + ".summary.txt") target = self.leaf(node, realm, counter=counter) if command in {"browse", "read", "write", "subscribe"} else None if command == "browse": target = self.relative_node(node, realm, "") if target_override is not None: target = target_override argv = cli_gate.build_cli_argv(self.cli_dll, command, self.endpoint(node), self.key, node=target, value=value, summary_file=summary, duration=duration, recursive=recursive, partner_endpoint=self.endpoint(partner) if partner else None, max_age_ms=5000 if command == "read" else 0) result = self.process(argv, identity, timeout=cli_timeout_seconds(command, duration)) completed_at_utc = datetime.now(timezone.utc).isoformat() if command == "read" else None # Cold mapped reads schedule bounded background work. Retry only the # explicit pending status, preserving each attempt as separate evidence. if command == "read" and not denial: for attempt in range(3): if (result.returncode != 0 or result.cancelled or result.timed_out or result.truncated or "BadWaitingForInitialData" not in result.stdout): break time.sleep(self.remaining(.1)) result = self.process(argv, identity + "-pending-" + str(attempt), timeout=15) completed_at_utc = datetime.now(timezone.utc).isoformat() if denial: evidence = cli_gate.validate_denial(result, command=command, expected_statuses=denial_statuses or ("BadUserAccessDenied", "BadNotWritable", "BadNodeIdUnknown", "BadNotConnected", "BadNoCommunication", "BadServerNotConnected", "BadOutOfService", "BadWaitingForInitialData", "BadInvalidState")) elif command == "read": evidence = cli_gate.validate_read(result, expected_node=target) elif command == "write": evidence = cli_gate.validate_write(result, expected_node=target) elif command == "browse": evidence = cli_gate.validate_browse(result, expected_nodes=expected_nodes or {self.leaf(node, realm)}) self.check(not set(absent_nodes).intersection(evidence["nodes"]), "removed/denied children absent from browse") elif command == "connect": evidence = cli_gate.validate_connect(result, expected_endpoint=self.endpoint(node)) elif command == "subscribe": if not summary.is_file() or summary.is_symlink(): raise ScenarioError("fresh CLI subscription summary missing") evidence = cli_gate.validate_subscription(result, summary_text=summary.read_text(), expected_nodes={target}) else: cli_gate._process_ok(result) self.check(cli_gate._field(result.stdout, "Application URI") == self.manifest["nodes"][node]["application_uri"], "UA application identity") evidence = {"application_uri": cli_gate._field(result.stdout, "Application URI")} if command == "read": evidence["completed_at_utc"] = completed_at_utc if not denial: validate_fixture_read_timestamps(evidence, modbus_fixture=True) self.count += 1 self.save(identity + ".validated.json", evidence) return evidence def probe(self, node, operation, realm="raw", *, connection="consumer-source", path=None, expected_state=None, timeout=None, **fields): timeout = probe_timeout_seconds(operation, timeout) identity = self.active + "-" + uuid.uuid4().hex paths = self.manifest["fixture"]["origin_paths"] command = {"id": identity, "connectionId": connection, "operation": operation, "realm": realm, "originCluster": "SOURCE", "namespaceUri": self.manifest["fixture"]["namespace_uris"][realm], "path": paths[realm] if path is None else path, "timeoutSeconds": min(timeout, int(self.remaining(120))), **fields} if expected_state is not None: command["expectedState"] = expected_state folder = Path(self.manifest["node_probe_dirs"][node]) if not folder.is_absolute() or folder.is_symlink() or not folder.is_dir() or folder.resolve() != (self.rig.folder / "probe" / node).resolve(): raise ScenarioError("run-owned caller probe directory missing") input_file, output_file = folder / (identity + ".request.json"), folder / (identity + ".result.json") rig.atomic_write_secret(input_file, json.dumps(command)) end = time.monotonic() + self.remaining(timeout + 5) try: while not output_file.exists(): if time.monotonic() >= end: raise ScenarioError("caller node file probe deadline") time.sleep(min(0.1, end - time.monotonic())) raw = restricted_json(output_file) self.save(identity + ".probe.json", raw) result = validate_probe_result(raw, expected_id=identity, expected_operation=operation) if operation == "read" and expected_state in (None, "Good"): validate_read_freshness(result["observations"], fields.get("maximumAgeMilliseconds", 5000)) self.count += result["assertions"] self.save(identity + ".probe.json", result) return result["observations"] finally: input_file.unlink(missing_ok=True) def wire(self, scenario="D13", *, previous_key_state=None): identity = self.active + "-wire" output = self.folder / (identity + ".json") arguments = ["dotnet", str(self.probe_dll), "--manifest", str(self.manifest_path), "--scenario", scenario, "--output", str(output)] if previous_key_state is not None: arguments.extend(["--previous-key-state", previous_key_state]) result = self.process(arguments, identity, timeout=90) self.check(result.returncode == 0 and not result.cancelled and not result.timed_out and not result.truncated, "wire process") report = restricted_json(output) self.check(report.get("passed") is True and bool(report.get("results")), "wire report") for item in report["results"]: validate_probe_result(item, expected_id=item["id"]) self.count += item["assertions"] def live_cli_fault(self, consumer, fault_node=None, *, partner=None, require_gap=True, on_fault=None, recovery=None, duration=60, realm="raw", outage_partner=None, post_lease_seconds=None, after_validated_recovery=None): """Fault only after the real subscriber has attached and emitted Good.""" identity = self.active + "-live-" + uuid.uuid4().hex[:8] summary = self.folder / (identity + ".summary.txt") target = self.leaf(consumer, realm) producer = getattr(self, "_controlled_source", None) self.check(isinstance(producer, ControlledFixtureSource), "fault subscriber has an exclusive controlled source") if outage_partner is not None and (fault_node is None or outage_partner == fault_node or partner is not None): raise ScenarioError("extended SOURCE outage requires distinct owned sources and one unchanged CLI endpoint") if post_lease_seconds is not None and (type(post_lease_seconds) not in (int, float) or not math.isfinite(post_lease_seconds) or not 0 < post_lease_seconds <= 65): raise ScenarioError("post-lease progress wait must be finite and fixture bounded") ready = threading.Event() bad = threading.Event() cancellation = threading.Event() line_parser = NotificationLines() notifications = [] notification_lock = threading.Lock() holder = [] failures = [] def observe(stream, chunk): if stream == "stdout": try: parsed = line_parser.feed(chunk) except (ScenarioError, cli_gate.CliGateError): failures.append("invalid CLI notification line") return for notification in parsed: if notification["node"] == target: with notification_lock: if len(notifications) >= 4096: failures.append("CLI notification observation bound exceeded") continue notifications.append({"at": time.monotonic(), "value": notification["value"], "status": notification["status"]}) if cli_gate.is_good_status(notification["status"]): ready.set() else: bad.set() def run(): try: holder.append(run_process(cli_gate.build_cli_argv(self.cli_dll, "subscribe", self.endpoint(consumer), self.key, node=target, summary_file=summary, duration=duration, partner_endpoint=self.endpoint(partner) if partner else None), timeout=self.remaining(duration + 20), secrets=self.secrets, cwd=rig.ROOT, environment=self.rig.environment, observer=observe, cancellation_event=cancellation, cleanup_timeout=1.0)) except BaseException as error: failures.append(type(error).__name__) worker = threading.Thread(target=run, daemon=True) started_at_utc = datetime.now(timezone.utc).isoformat() started_at_monotonic = time.monotonic() worker.start() fault_at = effective_at = withdrawal_at = reauthorization_at = reauthorization_completed_at = None sentinel = None source_outage = post_lease = None try: self.check(ready.wait(self.remaining(15)), "real CLI attachment and Good update before fault") bad.clear() action_started = time.monotonic() def wait_for_non_good(*, stop_requested_at, stop_completed_at): end = stop_requested_at + self.remaining(45) while True: with notification_lock: try: return validate_source_outage_notification(notifications, stop_requested_at=stop_requested_at, stop_completed_at=stop_completed_at) except ScenarioError: pass remaining = end - time.monotonic() if remaining <= 0 or not worker.is_alive() or failures: raise ScenarioError("extended SOURCE outage did not produce an actual CLI non-Good update within 45 seconds") bad.wait(min(.1, remaining)); bad.clear() fault_scope = (self.extended_source_outage(fault_node, outage_partner, wait_for_non_good=wait_for_non_good) if outage_partner is not None else self.stopped(fault_node) if fault_node else nullcontext()) with fault_scope as source_outage: fault_at = action_started effective_at = time.monotonic() if source_outage is not None: with notification_lock: non_good = next(row for row in notifications if row["at"] == source_outage["actual_non_good_at"]) source_outage["actual_non_good_status"] = non_good["status"] source_outage["actual_bad_at"] = non_good["at"] if non_good["status"].startswith("Bad") else None if on_fault is not None: on_fault() if recovery is not None: self.check(bad.wait(self.remaining(25)), "live stream authorization/expiry gate withdrew values") with notification_lock: withdrawal_at = next((row["at"] for row in notifications if row["at"] >= action_started and row["status"].startswith("Bad")), None) self.check(withdrawal_at is not None, "observed authorization withdrawal boundary") time.sleep(self.remaining(2)) reauthorization_at = time.monotonic() recovery() reauthorization_completed_at = time.monotonic() # The old consumer/source remains stopped throughout this # challenge. No queued pre-fault output can contain this value. with producer.sentinel() as sentinel: end = time.monotonic() + self.remaining(20) while True: with notification_lock: observed_at = next((row["at"] for row in notifications if row["at"] >= sentinel["produced_at"] and row["value"] == sentinel["value"] and cli_gate.is_good_status(row["status"])), None) if observed_at is not None: sentinel["observed_at"] = observed_at break if time.monotonic() >= end or not worker.is_alive() or failures: raise ScenarioError("live CLI did not observe the held post-fault recovery sentinel") time.sleep(min(.1, max(0, end - time.monotonic()))) if post_lease_seconds is not None: resumed_at = time.monotonic() time.sleep(self.remaining(post_lease_seconds)) waited = time.monotonic() - resumed_at self.check(waited >= post_lease_seconds, "advertised metadata lease plus margin actually elapsed") with producer.lock: floor = producer.current wraps = producer.ordinary_wrap_count boundary = time.monotonic() post_lease = {"resumed_after_sentinel_at": resumed_at, "wait_seconds": post_lease_seconds, "actual_wait_seconds": waited, "boundary_at": boundary, "ordinary_floor": floor, "ordinary_source_initial_value": producer.initial_value, "ordinary_wrap_count": wraps} self.check(wraps == 0, "post-lease numeric floor requires a nonwrapping ordinary producer sequence") end = boundary + self.remaining(10) while True: with notification_lock: snapshot = list(notifications) with producer.lock: observed_wraps = producer.ordinary_wrap_count post_lease["ordinary_wrap_count_at_observation"] = observed_wraps self.check(observed_wraps == 0, "ordinary producer did not wrap during the post-lease progress observation") try: post_lease.update(validate_post_lease_progress(snapshot, boundary_at=boundary, ordinary_floor=floor, ordinary_wrap_count=observed_wraps)) break except ScenarioError: if time.monotonic() >= end or not worker.is_alive() or failures: raise time.sleep(min(.1, max(0, end - time.monotonic()))) self.save(identity + ".post-lease-progress.json", post_lease) worker.join(timeout=self.remaining(duration + 10)) self.check(not worker.is_alive() and not failures and len(holder) == 1, "bounded fault subscription completion") self.save(identity + ".process.json", asdict(holder[0])) self.check(summary.is_file() and not summary.is_symlink(), "fresh recovery summary") evidence = cli_gate.validate_recovery_subscription(holder[0], summary_text=summary.read_text(), expected_node=target, require_gap=require_gap, require_held_session=outage_partner is not None) evidence["temporal"] = validate_fault_notifications(notifications, fault_at=fault_at, effective_at=effective_at, require_gap=require_gap, required_sentinel=sentinel, withdrawal_at=withdrawal_at, reauthorization_at=reauthorization_at, reauthorization_completed_at=reauthorization_completed_at) evidence["consumer_endpoint"] = self.endpoint(consumer) evidence["partner_endpoint"] = self.endpoint(partner) if partner else None evidence["fault_node"] = fault_node if source_outage is not None: evidence["extended_source_outage"] = source_outage if post_lease is not None: evidence["post_lease_progress"] = post_lease self.save(identity + ".validated.json", evidence) if after_validated_recovery is not None: after_validated_recovery() self.count += 1 return evidence finally: original_failure = sys.exc_info()[1] cancellation_requested = worker.is_alive() if cancellation_requested: cancellation.set() cleanup_started = time.monotonic() cleanup_deadline = cleanup_started + 8 cleanup_errors = [] try: while worker.is_alive() and time.monotonic() < cleanup_deadline: worker.join(timeout=min(.25, max(0, cleanup_deadline - time.monotonic()))) except BaseException as error: cleanup_errors.append(type(error).__name__) worker_collected = not worker.is_alive() if holder: self.save(identity + ".process.json", asdict(holder[0])) with notification_lock: selected = notifications if len(notifications) <= 512 else notifications[:256] + notifications[-256:] bounded_notifications = [{"at": row["at"], "value": redact_text(str(row["value"]), self.secrets)[:256], "status": redact_text(str(row["status"]), self.secrets)[:128]} for row in selected] notification_count = len(notifications) self.save(identity + ".fault-observation.json", { "started_at_utc": started_at_utc, "completed_at_utc": datetime.now(timezone.utc).isoformat(), "started_at_monotonic": started_at_monotonic, "completed_at_monotonic": time.monotonic(), "fault_at": fault_at, "fault_effective_at": effective_at, "withdrawal_at": withdrawal_at, "reauthorization_at": reauthorization_at, "reauthorization_completed_at": reauthorization_completed_at, "sentinel": sentinel, "notifications": bounded_notifications, "notification_count": notification_count, "notifications_truncated": notification_count > len(bounded_notifications), "failures": failures[:32], "worker_collected": worker_collected, "process_collected": len(holder) == 1, "cancellation_requested": cancellation_requested, "cleanup_budget_seconds": 8, "cleanup_duration_seconds": time.monotonic() - cleanup_started, "cleanup_errors": cleanup_errors, "original_failure_type": type(original_failure).__name__ if original_failure is not None else None, "consumer_endpoint": self.endpoint(consumer), "partner_endpoint": self.endpoint(partner) if partner else None, "fault_node": fault_node, "extended_source_outage": source_outage, "post_lease_progress": post_lease}) if original_failure is None and (not worker_collected or cleanup_errors): raise ScenarioError("owned subscriber could not be collected after cancellation") def device(self, action=None, **fields): base = self.manifest["endpoints"]["device.control"]["url"] status, _, body = rig.http_request("POST" if action else "GET", base + ("/control" if action else "/state"), headers={}, json_body={"action": action, **fields} if action else None, timeout=self.remaining(5)) self.check(status == 200 and isinstance(body, dict) and type(body.get("effect_total")) is int, "device ledger response") return body def wait_readback(self, node, realm, expected): end = time.monotonic() + self.remaining(20) while True: result = self.cli("read", node, realm) if result["value"] == expected: self.check(True, "eventual origin cached readback") return result if time.monotonic() >= end: raise ScenarioError("origin did not converge to the accepted fixture write") time.sleep(min(0.2, end - time.monotonic())) @contextmanager def changing(self): done = threading.Event() failures = [] initial = self.device()["writable"]["20"] self.check(getattr(self, "_controlled_source", None) is None, "one controlled fixture producer at a time") if not hasattr(self, "_fixture_used_values"): self._fixture_used_values = set() producer = ControlledFixtureSource(self.device, initial, self._fixture_used_values) self._controlled_source = producer def worker(): try: while not done.wait(0.5): producer.tick() except BaseException as error: failures.append(type(error).__name__) thread = threading.Thread(target=worker, daemon=True) thread.start() try: yield self.check(not failures, "controlled source changes") finally: done.set() thread.join(timeout=6) self._controlled_source = None self.check(not thread.is_alive(), "controlled fixture producer retired") self.device("set", address=20, value=initial) def mutate(self, **mutation): key_only = is_key_only_mutation(mutation) revision_receipt = self.rig.folder / "seed" / "mutation-revisions.json" if key_only: if revision_receipt.is_symlink(): raise ScenarioError("credential revision receipt must be an owned regular file") revision_receipt.unlink(missing_ok=True) rig.atomic_write_secret(self.rig.folder / "seed" / "mutation.json", json.dumps(mutation)) self.rig.seed_helper("mutate") if key_only: receipt = validate_key_only_revision_receipt(restricted_json(revision_receipt), action=mutation["key_action"]) self.save(self.active + "-credential-revisions-" + uuid.uuid4().hex[:8] + ".json", receipt) self.manifest = self.rig.deploy(timeout=self.remaining(180), require_catalog=False) for path in self.manifest["credentials"]["data_key_files"].values(): secret = Path(path).read_text().strip() if secret and secret not in self.secrets: self.secrets.append(secret) self.timeline.append({"event": "deploy", "revision": self.manifest["deployment"]["revision_hash"], "at": time.monotonic()}) def _owned_source_process(self, node): """Read only the recorded owned container's process identity; retain no environment payload.""" if not isinstance(node, str) or not node.startswith("source-") or node not in self.manifest["nodes"]: raise ScenarioError("SOURCE pause target is outside the owned fixture") required = {rig.RUN_LABEL: self.manifest["run_id"], rig.PROJECT_LABEL: self.manifest["project"], "com.docker.compose.service": node} def selected(rows): return [row for row in rows if row.get("kind") == "container" and row.get("labels", {}).get("com.docker.compose.service") == node] recorded = selected(self.manifest.get("resources", [])) observed = selected(self.rig.inspect_resources()) if (len(recorded) != 1 or len(observed) != 1 or recorded[0]["id"] != observed[0]["id"] or any(row.get("labels", {}).get(key) != value for row in (*recorded, *observed) for key, value in required.items())): raise ScenarioError("SOURCE pause ownership or recorded container identity changed") identity = recorded[0]["id"] try: rows = json.loads(rig.run_command([*self.rig.docker, "container", "inspect", identity], timeout=10)) if not isinstance(rows, list) or len(rows) != 1: raise ValueError() row = rows[0] state, labels = row["State"], row["Config"]["Labels"] if (row["Id"] != identity or any(labels.get(key) != value for key, value in required.items()) or state.get("Running") is not True or type(state.get("Pid")) is not int or state["Pid"] <= 0 or not isinstance(state.get("StartedAt"), str) or not state["StartedAt"] or type(state.get("Paused")) is not bool): raise ValueError() return {"node": node, "container_id": identity, "process_id": state["Pid"], "started_at": state["StartedAt"], "paused": state["Paused"]} except (ValueError, KeyError, TypeError, AttributeError): raise ScenarioError("SOURCE pause process inspection is invalid") from None @contextmanager def paused(self, node): before = self._owned_source_process(node) if before["paused"]: raise ScenarioError("SOURCE partner was already paused before this fault") receipt = {"node": node, "container_id": before["container_id"], "process_id_before": before["process_id"], "process_start_before": before["started_at"], "process_identity_kind": "owned Host container init PID and StartedAt", "paused_at": None, "resumed_at": None, "cleanup_succeeded": False} def same_process(state): if (state["container_id"] != before["container_id"] or state["process_id"] != before["process_id"] or state["started_at"] != before["started_at"]): raise ScenarioError("paused SOURCE partner process identity changed") def resume(): current = self._owned_source_process(node) same_process(current) if current["paused"]: self.rig.compose("unpause", node, timeout=30) receipt["resumed_at"] = time.monotonic() self.timeline.append({"event": "unpause", "nodes": [node], "at": receipt["resumed_at"]}) after = self._owned_source_process(node) receipt.update(process_id_after=after["process_id"], process_start_after=after["started_at"]) same_process(after) if after["paused"]: raise ScenarioError("owned SOURCE partner remained paused") receipt["cleanup_succeeded"] = True return dict(receipt) resume.receipt = receipt try: self.rig.compose("pause", node, timeout=self.remaining(20)) paused = self._owned_source_process(node) same_process(paused) if not paused["paused"]: raise ScenarioError("owned SOURCE partner did not pause") receipt["paused_at"] = time.monotonic() self.timeline.append({"event": "pause", "nodes": [node], "at": receipt["paused_at"]}) yield resume finally: original = sys.exc_info()[1] cleanup_error = None try: resume() except BaseException as error: cleanup_error = type(error).__name__ receipt["cleanup_succeeded"] = False receipt["cleanup_error"] = cleanup_error try: self.save(self.active + "-" + node + "-pause-" + uuid.uuid4().hex[:8] + ".json", receipt) except BaseException as error: cleanup_error = cleanup_error or type(error).__name__ if cleanup_error is not None and original is None: raise ScenarioError("owned SOURCE partner pause cleanup failed") @contextmanager def extended_source_outage(self, primary, partner, *, wait_for_non_good): """Hold both sources unavailable until the actual CLI observes the outage.""" with self.paused(partner) as resume: stop_requested_at = time.monotonic() self.timeline.append({"event": "source-outage-stop-request", "nodes": [primary], "at": stop_requested_at}) with self.stopped(primary): stop_completed_at = time.monotonic() self.timeline.append({"event": "source-outage-stop-complete", "nodes": [primary], "at": stop_completed_at}) non_good_at = wait_for_non_good(stop_requested_at=stop_requested_at, stop_completed_at=stop_completed_at) if (any(type(value) not in (int, float) or not math.isfinite(value) for value in (stop_requested_at, stop_completed_at, non_good_at)) or not stop_requested_at <= stop_completed_at or not stop_requested_at <= non_good_at <= stop_requested_at + 45): raise ScenarioError("SOURCE outage observation is outside its actual shutdown boundaries") resumed = resume() yield {"setup": "partner paused and old primary stopped before recovery", "primary": primary, "partner": partner, "primary_stop_requested_at": stop_requested_at, "both_sources_unavailable_at": stop_completed_at, "actual_non_good_at": non_good_at, "partner_pause": resumed} @contextmanager def stopped(self, *nodes): if not nodes or any(node not in self.manifest["nodes"] for node in nodes): raise ScenarioError("stop target is outside recorded nodes") # Re-inspect both ownership labels before every fault mutation. resources = self.rig.inspect_resources() self.check(all(row["labels"].get(rig.RUN_LABEL) == self.manifest["run_id"] for row in resources), "fault resource ownership") try: self.rig.compose("stop", "--timeout", "5", *nodes, timeout=self.remaining(20)) self.timeline.append({"event": "stop", "nodes": nodes, "at": time.monotonic()}) yield finally: original = sys.exc_info()[1] def failure_type(error): return {RuntimeError: "RuntimeError", ValueError: "ValueError", OSError: "OSError", TimeoutError: "TimeoutError", ScenarioError: "ScenarioError", rig.RigError: "RigError"}.get(type(error), "OtherError") cleanup_errors = [] try: self.rig.compose("start", *nodes, timeout=30) self.timeline.append({"event": "start", "nodes": nodes, "at": time.monotonic()}) except BaseException as error: cleanup_errors.append({"operation": "start", "type": failure_type(error)}) # Refresh remains an independent cleanup attempt even if start fails. try: self.manifest = self.rig.refresh_endpoints(nodes) except BaseException as error: cleanup_errors.append({"operation": "refresh", "type": failure_type(error)}) receipt = {"event": "stop-cleanup", "nodes": nodes, "at": time.monotonic(), "original_error": failure_type(original) if original is not None else None, "cleanup_errors": cleanup_errors} self.timeline.append(receipt) try: self.save(self.active + "-stop-cleanup-" + uuid.uuid4().hex[:8] + ".json", receipt) except BaseException as error: cleanup_errors.append({"operation": "record", "type": failure_type(error)}) if cleanup_errors and original is None: raise ScenarioError("owned stopped-node cleanup failed") def baseline(self, *, maintenance_changed=False): # Restoration deliberately uses the rig's independent bounded startup, # deployment and catalog deadlines, even after this scenario expires. self.rig.seed_helper("restore") self.rig.restore_security() if maintenance_changed: # The coordinator reads fresh eligible rows while mesh dispatch uses # cached contacts. Let CONTROL refresh after the restore commits, # then require every real acknowledgement in a single deployment. time.sleep(MAINTENANCE_CONTACT_SETTLE_SECONDS) self.timeline.append({"event": "maintenance-contact-settle", "at": time.monotonic(), "seconds": MAINTENANCE_CONTACT_SETTLE_SECONDS}) self.manifest = self.rig.deploy(timeout=180) def run(self, selection): chosen = SCENARIOS if selection == "all" else (selection,) if any(item not in SCENARIOS for item in chosen): raise ScenarioError("unknown required scenario") self.publish() self.rig.seed_helper("snapshot") self.matrix_cells = [] rows = [] for name in chosen: self.active, self.count = name, 0 catalog = getattr(self, "catalog", {"default_timeout_seconds": 480, "timeouts": {}}) self.deadline = time.monotonic() + catalog["timeouts"].get(name, catalog["default_timeout_seconds"]) started = time.monotonic() error = None restored = False try: getattr(self, "scenario_" + name)() self.check(self.count > 0, "nonempty scenario") validate_matrix_cells([cell for cell in self.matrix_cells if cell["scenario"] == name], (name,)) except Exception as failure: error = type(failure).__name__ + (": " + str(failure) if isinstance(failure, (ScenarioError, cli_gate.CliGateError)) else "") finally: try: self.baseline(maintenance_changed=name == "D07") restored = True except Exception as failure: error = (error + "; " if error else "") + "restoration " + type(failure).__name__ row = {"id": name, "passed": error is None, "assertions": self.count, "restored": restored, "duration_seconds": time.monotonic() - started, "failure": error, "cells": [cell for cell in self.matrix_cells if cell["scenario"] == name]} rows.append(row) self.save("scenario-results.json", {"rows": rows, "complete": len(rows) == len(chosen)}) report = {"schema_version": 1, "run_id": self.manifest["run_id"], "passed": validate_scenario_rows(rows, chosen), "rows": rows} self.deadline = time.monotonic() + 30 self.save("scenario-results.json", report) self.save("fault-timeline.json", self.timeline) self.save("device-ledger.json", self.device()) files = sorted(path for path in self.folder.iterdir() if path.is_file() and path.name != "index.json") self.save("index.json", {"source_revision": self.manifest.get("source_revision"), "files": [ {"path": path.name, "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "bytes": path.stat().st_size} for path in files]}) return report def scenario_D01(self): all_members = set() containers = [row for row in self.rig.inspect_resources() if row["kind"] == "container" and row["labels"].get("com.docker.compose.service") in self.manifest["nodes"]] self.check(len(containers) == 6 and len({row["id"] for row in containers}) == 6, "six distinct host processes") for node in self.manifest["nodes"]: result = self.probe(node, "topology") self.check(result.get("artifactRevision") == self.manifest["deployment"]["revision_hash"], "node cached applied revision") expected = {peer for peer in self.manifest["nodes"] if peer.split("-")[0] == node.split("-")[0]} observed = {member["host"] for member in result["members"]} self.check(observed == expected and observed.isdisjoint(all_members - expected), "independent pair members") all_members.update(observed) self.cli("redundancy", node) deployment = self.manifest["deployment"] self.check(len(deployment["nodes"]) == 6, "six applied revisions") self.check(bool(deployment["revision_hash"]), "artifact revision present") for pair in ("control", "source", "consumer"): self.primary(pair) self.probe(self.primary("consumer"), "capabilities", expected_state="Ready") def direct_suite(self, caller, connection, *, write=True, expected_node=None, topology="cross-cluster", mode="Cluster"): for realm in ("raw", "uns"): parent = fixture_browse_root(self.manifest["fixture"], realm) for operation in ("capabilities", "browse", "metadata", "read"): self.matrix_probe(topology, mode, realm, operation, caller, connection=connection, path=parent if operation == "browse" else None, expected_node=expected_node) with self.changing(): self.matrix_probe(topology, mode, realm, "subscribe", caller, connection=connection, expected_node=expected_node) if write: before = self.device()["effect_total"] self.matrix_probe(topology, mode, realm, "dedup", caller, connection=connection, value=42, expected_node=expected_node) after = self.device() self.check(after["effect_total"] == before + 1 and after["writable"]["20"] == 42, "one remote effect for same operation ID") def scenario_D01a(self): # Removing projection is essential: success cannot be caused by an anchor. self.mutate(mapping_enabled=False) caller = self.primary("consumer") for realm in ("raw", "uns"): self.cli("read", caller, realm, denial=True) self.direct_suite(caller, "consumer-source") primary = self.primary("source") self.mutate(target_mode="Node", target_node_id=self.node_id(primary), consistency="Primary") self.direct_suite(caller, "consumer-source", expected_node=primary, mode="Node") self.same_cluster(direct_only=True) def same_cluster(self, *, direct_only=False): target = self.primary("source") caller = next(node for node in self.manifest["nodes"] if node.startswith("source-") and node != target) spec = {"DataConnectionId": "source-source", "ClusterId": "SOURCE", "Enabled": True, "ConsumerNodeIds": [self.node_id(caller)], "TargetMode": 1, "ExpectedClusterId": "SOURCE", "ExpectedNodeId": self.node_id(target), "Consistency": 1, "EligibleTargetNodeIds": [], "Endpoints": ["https://" + target + ":4057"], "SecretReference": "secret:data/source-source", "SecretScopeClusterId": "SOURCE", "AllowedOperations": OPERATIONS, "Revision": 1} self.mutate(upsert_connection=spec, connection_id="source-source") self.direct_suite(caller, "source-source", expected_node=target, topology="same-cluster", mode="Node") self.probe(target, "capabilities", connection="source-source", expected_state="Unavailable") if not direct_only: baseline = restricted_json(self.rig.folder / "seed" / "baseline.json") for mapping in baseline["Mappings"]: mapping = dict(mapping) realm = "raw" if mapping["Realm"] == 1 else "uns" mapping.update(RemoteNamespaceMappingId="same-" + realm, ClusterId="SOURCE", DataConnectionId="source-source", ConsumerNodeIds=[self.node_id(caller)], LocalParentId="SOURCE") self.mutate(upsert_mapping=mapping, connection_id="source-source") # NamespaceArray was observed for every node at setup; scoped # mappings do not change those registered namespace URIs. Materialize # the exact caller branch instead of globally traversing unrelated # cold projections through the seeder. # A is standby while B is the target primary: runtime positive above, # UA local-primary enforcement remains a negative on the mounted view. for realm in ("raw", "uns"): template_node = next(node for node in self.initial_resolved if node.startswith("consumer-")) projected = self.relative_node(template_node, realm, "scalar", mapping_id="same-" + realm) identifier = projected.split(";s=", 1)[1] resolved = self.manifest["resolved_nodes"][caller] uri = self.manifest["fixture"]["namespace_uris"]["mapped_" + realm] mapped = cli_gate.resolve_node_id(resolved["namespace_uris"], uri, identifier) root = self.relative_node(template_node, realm, "", mapping_id="same-" + realm) root = cli_gate.resolve_node_id(resolved["namespace_uris"], uri, root.split(";s=", 1)[1]) self.cli("browse", caller, realm, recursive=True, target_override=root, expected_nodes={mapped}) self.matrix_cli("same-cluster", "Node", realm, "read", caller, target_override=mapped, expected_node=target, connection="source-source") before = self.device()["effect_total"] self.matrix_cli("same-cluster", "Node", realm, "write", caller, denial=True, target_override=mapped, denial_statuses={"BadInvalidState"}, boundary="local-standby", expected_node=target, connection="source-source") self.check(self.device()["effect_total"] == before, "local standby gate rejected before device dispatch") # Reverse the pinned route: the previous target remains primary, # while the previous caller is the explicit ReadyReplica target. reverse = dict(spec, ConsumerNodeIds=[self.node_id(target)], ExpectedNodeId=self.node_id(caller), Endpoints=["https://" + caller + ":4057"], Consistency=2) self.mutate(upsert_connection=reverse, connection_id="source-source") for realm in ("raw", "uns"): self.matrix_probe("same-cluster", "Node", realm, "read", target, connection="source-source", boundary="secondary", expected_node=caller) before = self.device()["effect_total"] self.matrix_probe("same-cluster", "Node", realm, "write", target, connection="source-source", boundary="secondary", expected_node=caller, expected_state="RejectedBeforeDispatch") self.check(self.device()["effect_total"] == before, "pinned same-cluster secondary write has no effect") def scenario_D02(self): self.same_cluster() def scenario_D03(self): for mode in ("Cluster", "Node"): target = self.primary("source") self.mutate(target_mode=mode, target_node_id=self.node_id(target), consistency="Primary") consumer = self.primary("consumer") for realm in ("raw", "uns"): self.wait_connection_ready(consumer, realm, expected_node=target if mode == "Node" else None) self.matrix_cli("cross-cluster", mode, realm, "browse", consumer, recursive=True, expected_node=target if mode == "Node" else None) origin = self.cli("read", target, realm) mapped = self.matrix_cli("cross-cluster", mode, realm, "read", consumer, expected_node=target if mode == "Node" else None) comparison = validate_fixture_read_pair(origin, mapped, modbus_fixture=True) comparison["controlled_boundary_companions"] = D03_TIMESTAMP_BOUNDARY_COMPANIONS self.check(origin["value"] == mapped["value"], "origin and mapped fixture values agree") self.save(f"D03-{mode}-{realm}-read-timestamps.json", comparison) self.matrix_probe("cross-cluster", mode, realm, "metadata", consumer, expected_node=target if mode == "Node" else None) self.check(self.leaf(consumer, "raw") != self.leaf(consumer, "uns"), "realm aliases remain distinct") baseline = restricted_json(self.rig.folder / "seed" / "baseline.json") tag = dict(next(row for row in baseline["Tags"] if row["TagId"] == "source-array2")) tag.update(TagId="source-new-child", Name="new-child") reference = dict(next(row for row in baseline["References"] if row["TagId"] == "source-array2")) reference.update(UnsTagReferenceId="ref-source-new-child", TagId="source-new-child") self.mutate(upsert_tag=tag, upsert_reference=reference) for realm in ("raw", "uns"): self.cli("browse", consumer, realm, recursive=True, expected_nodes={self.relative_node(consumer, realm, "new-child"), self.relative_node(consumer, realm, "array2")}) self.mutate(rename_tag={"tag_id": "source-new-child", "name": "renamed-child"}) for realm in ("raw", "uns"): self.cli("browse", consumer, realm, recursive=True, expected_nodes={self.relative_node(consumer, realm, "renamed-child")}, absent_nodes={self.relative_node(consumer, realm, "new-child")}) self.mutate(remove_tag_id="source-new-child") for realm in ("raw", "uns"): self.cli("browse", consumer, realm, recursive=True, absent_nodes={self.relative_node(consumer, realm, "renamed-child")}) self.baseline() def scenario_D04(self): for mode in ("Cluster", "Node"): target = self.primary("source") self.mutate(target_mode=mode, target_node_id=self.node_id(target), consistency="Primary") consumer = self.primary("consumer") for realm in ("raw", "uns"): self.prepare_positive_projection(consumer, realm) with self.changing(): self.matrix_cli("cross-cluster", mode, realm, "subscribe", consumer, expected_node=target if mode == "Node" else None) self.prepare_positive_projection(consumer, realm) before = self.device()["effect_total"] self.matrix_cli("cross-cluster", mode, realm, "write", consumer, value=42, expected_node=target if mode == "Node" else None) self.check(self.device()["effect_total"] == before + 1, "CLI write exactly one device effect") self.wait_readback(self.primary("source"), realm, "42") self.check(self.device()["writable"]["20"] == 42, "simulator readback") def scenario_D05(self): for mode in ("Node", "Cluster"): self.mutate(target_mode=mode, target_node_id=self.node_id(self.primary("source")), consistency="Primary") node = self.primary("consumer") for realm in ("raw", "uns"): parent = fixture_browse_root(self.manifest["fixture"], realm) branch = self.probe(node, "browse", realm, path=parent) self.check(branch["complete"] is False and bool(branch["continuation"]), "bounded nonempty continuation page") cursor = branch["continuation"] first = self.probe(node, "continuation", realm, path=parent, continuation=cursor, expected_state="Good") repeated = self.probe(node, "continuation", realm, path=parent, continuation=cursor, expected_state="Good") # Origin HMAC cursors are stateless. The mounted SDK's separate # continuation store consumes its cursor only on a committed page. self.check(isinstance(first.get("items"), list) and isinstance(repeated.get("items"), list) and len(first["items"]) <= 1 and repeated["items"] == first["items"], "origin cursor replay preserves the same ordered bounded metadata page") self.check(type(first.get("complete")) is bool and repeated.get("complete") is first["complete"] and isinstance(first.get("serving"), dict) and all(repeated.get(field) == first.get(field) for field in ("serving", "limits", "operations", "compact", "readiness")), "origin cursor replay preserves completion and full serving capability era") fresh = self.probe(node, "browse", realm, path=parent) self.check(bool(fresh["continuation"]), "unconsumed cursor before revision change") origin_before = fresh["serving"] self.mutate(allowed_operations=OPERATIONS) origin_after = self.probe(node, "capabilities", realm, expected_state="Ready")["serving"] self.check(origin_before != origin_after, "origin serving catalog or authority actually changed before token invalidation") invalid = self.probe(node, "continuation", realm, path=parent, continuation=fresh["continuation"], expected_state="InvalidContinuation") self.check(invalid.get("items") == [], "invalid origin continuation leaks no metadata rows") self.save(f"D05-{mode}-{realm}-origin-continuation.json", { "origin_before": origin_before, "origin_after": origin_after, "first_page": {"items": first["items"], "complete": first["complete"]}, "replay_page": {"items": repeated["items"], "complete": repeated["complete"]}, "invalidated_items": invalid["items"], "origin_same_owner_replay": "Good"}) def scenario_D06(self): node = self.primary("consumer") self.mutate(write_through=False, allowed_operations=OPERATIONS & ~8) for realm in ("raw", "uns"): self.prepare_positive_projection(node, realm) self.cli("read", node, realm) self.cli("write", node, realm, denial=True) quiet_leases = [] for realm in ("raw", "uns"): parent = fixture_browse_root(self.manifest["fixture"], realm) observed = self.probe(node, "browse", realm, path=parent) quiet_leases.append(metadata_lease_seconds(observed.get("lease"))) self.cli("browse", node, realm, recursive=True) quiet_started = time.monotonic() quiet_bound = max(quiet_leases) # No browse/read/metadata traffic renews the quiet projected lease here. time.sleep(self.remaining(quiet_bound + .5)) self.check(time.monotonic() - quiet_started >= quiet_bound, "quiet metadata lease elapsed") for realm in ("raw", "uns"): self.cli("read", node, realm, denial=True, denial_statuses={"BadUserAccessDenied", "BadNodeIdUnknown", "BadNoCommunication"}) self.cli("browse", node, realm, recursive=True) self.cli("read", node, realm) self.save("D06-quiet-lease.json", {"lease_seconds": quiet_leases, "elapsed_seconds": time.monotonic() - quiet_started, "expired_both_realms": True}) baseline = restricted_json(self.rig.folder / "seed" / "baseline.json") export_scopes = [] for export in baseline["Exports"]: # Projection admission needs parent Metadata. This inherited grant # includes descendant Metadata, while scalar-only Browse filters siblings. parent_metadata = dict(export, AllowedOperations=2) self.mutate(upsert_export=parent_metadata) raw = export["Realm"] == 1 scalar = dict(export, DataExportId=export["DataExportId"] + "-scalar", AllowedOperations=OPERATIONS, RootKind="RawTag" if raw else "UnsTagReference", RootEntityId="source-scalar" if raw else "ref-scalar") self.mutate(upsert_export=scalar) export_scopes.append({"realm": "raw" if raw else "uns", "metadata_root": parent_metadata, "scalar_root": scalar}) for realm in ("raw", "uns"): self.prepare_positive_projection(node, realm) self.cli("browse", node, realm, recursive=True, absent_nodes={self.relative_node(node, realm, "counter")}) self.cli("read", node, realm) counter = self.manifest["fixture"]["origin_paths"][realm].rsplit("/", 1)[0] + "/counter" self.probe(node, "read", realm, path=counter, expected_state="Denied") effects = self.device()["effect_total"] self.probe(node, "write", realm, path=counter, expected_state="RejectedBeforeDispatch") self.check(self.device()["effect_total"] == effects, "out-of-scope counter write has zero physical effects") self.save("D06-export-scopes.json", {"grants": export_scopes, "metadata_scope": "Parent Metadata permission is inherited by descendants; it is not an exact-parent-only grant.", "browse_scope": "Full scalar-leaf operations grant allows ancestor discovery and excludes counter from complete browse."}) self.baseline() target = self.primary("source") # Pin the authenticated Primary so a secondary selection failure cannot # replace the explicit origin permission denial in the exception chain. self.mutate(export_allowed_operations=1 | 2, target_mode="Node", target_node_id=self.node_id(target), consistency="Primary", connection_allowed_operations=OPERATIONS) for realm in ("raw", "uns"): self.wait_connection_ready(node, realm, expected_node=target) self.probe(node, "read", realm, expected_state="Denied", expectedNodeId=self.node_id(target), expectedRole="Primary") # The failed Read sets discovery backoff; authenticate readiness # again before the independent actual Write rejection assertion. self.wait_connection_ready(node, realm, expected_node=target) effects = self.device()["effect_total"] self.probe(node, "write", realm, expected_state="RejectedBeforeDispatch", expectedNodeId=self.node_id(target), expectedRole="Primary") self.check(self.device()["effect_total"] == effects, "origin operation-mask write denial has zero physical effects") self.mutate(export_allowed_operations=OPERATIONS, write_through=True, target_mode="Cluster", consistency="Primary") self.prepare_positive_projection(node, "raw") with self.changing(): self.live_cli_fault(node, on_fault=lambda: self.mutate(key_action="revoke"), recovery=lambda: self.mutate(key_action="rotate"), require_gap=True, duration=90) self.mutate(key_action="expire", key_expiry_seconds=20) self.prepare_positive_projection(node, "raw") with self.changing(): self.live_cli_fault(node, recovery=lambda: self.mutate(key_action="rotate"), require_gap=True, duration=90) self.probe(node, "capabilities", expected_state="Ready") def scenario_D07(self): consumer = self.primary("consumer") for realm in ("raw", "uns"): source = self.primary("source") self.wait_connection_ready(consumer, realm, require_fresh_sample=True) capabilities = self.probe(consumer, "capabilities", realm) before = capabilities["serving"] lease_seconds = metadata_lease_seconds({"duration": capabilities["limits"]["maxMetadataLease"]}) source_partner = next(node for node in self.manifest["nodes"] if node.startswith("source-") and node != source) self.prepare_positive_projection(consumer, realm) recovered_observation = [] def recovered(): selected = self.wait_primary("source", exclude=source) self.check(selected == source_partner, "extended outage recovered the unpaused SOURCE partner") self.wait_connection_ready(consumer, realm, expected_node=selected, require_fresh_sample=True) observed = self.probe(consumer, "read", realm, expectedNodeId=self.node_id(selected)) self.check(observed["serving"] != before, "source serving epoch changed") recovered_observation.append(observed) # Prove the unchanged item recovered first, then read through the # same consumer while the old SOURCE is still stopped. with self.changing(): evidence = self.live_cli_fault(consumer, source, require_gap=True, on_fault=recovered, realm=realm, outage_partner=source_partner, duration=120, post_lease_seconds=lease_seconds + 5, after_validated_recovery=lambda: self.cli("read", consumer, realm)) self.record_matrix_cell("cross-cluster", "Cluster", "mounted", realm, "subscribe", consumer, recovered_observation[0], boundary="source-failover", cli_evidence=evidence) self.wait_primary("source") self.wait_primary("source") source = self.primary("source") self.mutate(target_mode="Node", target_node_id=self.node_id(source), consistency="Primary") with self.stopped(source): self.wait_primary("source", exclude=source) for realm in ("raw", "uns"): unavailable = self.matrix_probe("cross-cluster", "Node", realm, "capabilities", consumer, boundary="pinned-loss", expected_node=source, expected_state="Unavailable") self.matrix_cli("cross-cluster", "Node", realm, "read", consumer, boundary="pinned-loss", expected_node=source, observed=unavailable, denial=True) self.wait_pair_topology("source") selected = self.wait_primary("source") self.mutate(target_mode="Cluster", consistency="Primary", maintenance_mode={"node_id": self.node_id(selected), "enabled": True}) # The excluded endpoint remains reachable and active. Unavailability here # proves maintenance policy, rather than merely TCP failure, excludes it. self.check(self.primary("source") == selected, "maintenance endpoint remains operational primary") self.probe(selected, "topology") for realm in ("raw", "uns"): self.matrix_probe("cross-cluster", "Cluster", realm, "capabilities", consumer, boundary="maintenance-primary", expected_state="Unavailable") with self.stopped(selected): partner = self.wait_primary("source", exclude=selected) for realm in ("raw", "uns"): self.wait_connection_ready(consumer, realm, expected_node=partner, require_fresh_sample=True) self.matrix_probe("cross-cluster", "Cluster", realm, "read", consumer, boundary="maintenance-exclusion", expected_node=partner) self.wait_pair_topology("source") def scenario_D08(self): node = self.primary("consumer") self.probe(node, "mixed-write") before = self.device()["effect_total"] self.device("drop_next_write_response") operation = "loss-" + uuid.uuid4().hex self.probe(node, "dedup", expected_state="OutcomeUnknown", operationId=operation) self.check(self.device()["effect_total"] == before + 1, "ambiguous duplicate has one effect") self.rig.compose("restart", node, timeout=self.remaining(40)) self.manifest = self.rig.refresh_endpoints((node,)) self.wait_primary("consumer") self.wait_connection_ready(node, require_fresh_sample=True) self.probe(node, "dedup", expected_state="OutcomeUnknown", operationId=operation) self.check(self.device()["effect_total"] == before + 1, "caller restart same operation has no replay") observed = self.probe(node, "capabilities")["serving"] source = next(name for name in self.manifest["nodes"] if self.node_id(name) == observed["nodeId"]) before_stale = self.device()["effect_total"] with self.stopped(source): selected = self.wait_primary("source", exclude=source) self.wait_connection_ready(node, expected_node=selected, require_fresh_sample=True) current = self.probe(node, "capabilities", expectedNodeId=self.node_id(selected))["serving"] self.check(current != observed, "observed source incarnation changed before stale request") self.probe(node, "write", expectedIncarnation=observed["incarnation"], expectedGeneration=observed["servingGeneration"], expected_state="RejectedBeforeDispatch") self.check(self.device()["effect_total"] == before_stale, "stale incarnation had no device effect") def scenario_D09(self): primary = self.primary("source") secondary = next(node for node in self.manifest["nodes"] if node.startswith("source-") and node != primary) self.mutate(target_mode="Node", target_node_id=self.node_id(secondary), consistency="ReadyReplica") consumer = self.primary("consumer") before = {} for realm in ("raw", "uns"): before[realm] = self.matrix_probe("cross-cluster", "Node", realm, "read", consumer, boundary="secondary", expected_node=secondary)["serving"] effects = self.device()["effect_total"] self.matrix_probe("cross-cluster", "Node", realm, "write", consumer, boundary="secondary", expected_node=secondary, expected_state="RejectedBeforeDispatch") self.check(self.device()["effect_total"] == effects, "pinned secondary write produces no effect") try: with self.rig._configuration_experiment("warm-source", ("source-1", "source-2"), {"OpcUa__Redundancy__Mode": "Warm"}): self.manifest = self.rig.load() # Startup Warm and artifact redundancy policy are separate inputs. # mutate deploys with require_catalog=False while Standby is unservable. self.mutate(source_redundancy_mode="Warm") states = self.wait_warm_pair() active, standby = select_warm_pair(states) self.mutate(target_mode="Node", target_node_id=self.node_id(standby), consistency="ReadyReplica") warm = {"pair": states, "target_node": standby, "realms": {}} for realm in ("raw", "uns"): if realm == "uns": # A rejected selection sets the first discovery backoff # to at most 300 ms. Prove the second realm by a new # eligible attempt, never by accepting that backoff. time.sleep(self.remaining(.35)) source_state = self.wait_warm_state(standby, "Standby") # The actual read command first authenticates capabilities; # a strict GetCapabilities rejection proves no Read dispatch. rejected = self.probe(consumer, "read", realm, expected_state="TargetIneligible", expectedNodeId=self.node_id(standby)) validate_warm_target_rejection(rejected, source_state, expected_node_id=self.node_id(standby)) warm["realms"][realm] = {"source_state": source_state, "read": rejected} self.save("D09-Warm-standby.json", warm) previous = warm["realms"]["raw"]["source_state"] with self.stopped(active): reads_before = self.device()["read_total"] current = self.wait_warm_state(standby, "Active") self.check(current["process"] == previous["process"] and current["serving"]["incarnation"] == previous["serving"]["incarnation"] and current["serving"] != previous["serving"] and current["warmRole"]["generation"] > previous["warmRole"]["generation"], "same pinned Warm process activates with a new actual verdict and serving identity") activated = {} for realm in ("raw", "uns"): self.wait_connection_ready(consumer, realm, expected_node=standby, require_fresh_sample=True) actual = self.probe(consumer, "read", realm, expected_state="Good", expectedNodeId=self.node_id(standby), expectedRole="Primary") validate_read_freshness(actual) self.check(actual.get("sample") is not None and actual["serving"] == current["serving"], "Warm activated primary returns a fresh sample from the unchanged pinned target") activated[realm] = actual reads_after = self.device()["read_total"] self.check(type(reads_before) is int and type(reads_after) is int and reads_after > reads_before, "activated Warm target produces physical reads while former Active remains stopped") self.save("D09-Warm-primary.json", {"state": current, "realms": activated, "physical_reads_before": reads_before, "physical_reads_after": reads_after}) finally: # The startup override restores before run() performs its outer artifact baseline. self.manifest = self.rig.load() def scenario_D10(self): for realm in ("raw", "uns"): consumer = self.primary("consumer") partner = next(node for node in self.manifest["nodes"] if node.startswith("consumer-") and node != consumer) source_before = self.probe(consumer, "capabilities", realm)["serving"]["nodeId"] self.cli("connect", consumer, partner=partner) preparation = {"realm": realm, "nodes": [], "scope": "Both eligible SDK projections are explicitly prepared; this setup does not prove cold or expired partner recovery."} for prepared_node in (consumer, partner): started = time.monotonic() self.prepare_positive_projection(prepared_node, realm) preparation["nodes"].append({"node": prepared_node, "started_at_monotonic": started, "completed_at_monotonic": time.monotonic(), "completed_at_utc": datetime.now(timezone.utc).isoformat()}) # The automatic CLI partner is prepared last. A successful browse # records an observed projection, without claiming a new cache lease. preparation["prepared_before_automatic_failover_at"] = time.monotonic() self.timeline.append({"event": "consumer-failover-projections-prepared", "realm": realm, "nodes": preparation["nodes"], "at": preparation["prepared_before_automatic_failover_at"]}) self.save(f"D10-{realm}-projection-preparation.json", preparation) recovered_observation = [] def recovered(): self.wait_primary("consumer", exclude=consumer) self.wait_connection_ready(partner, realm, require_fresh_sample=True) observed = self.probe(partner, "read", realm) self.check(observed["serving"]["nodeId"] == source_before, "UA client moved while SOURCE serving node stayed fixed") recovered_observation.append(observed) with self.changing(): evidence = self.live_cli_fault(consumer, consumer, partner=partner, require_gap=False, on_fault=recovered, realm=realm) temporal = evidence["temporal"] preparation["attachment_and_fault"] = { "first_good_at": next((row["at"] for row in temporal["notifications"] if cli_gate.is_good_status(row["status"])), None), "fault_at": temporal["fault_at"]} evidence["projection_preparation"] = preparation self.save(f"D10-{realm}-projection-preparation.json", preparation) self.record_matrix_cell("cross-cluster", "Cluster", "mounted", realm, "subscribe", partner, recovered_observation[0], boundary="consumer-failover", cli_evidence=evidence) self.wait_primary("consumer") consumer = self.primary("consumer") partner = next(node for node in self.manifest["nodes"] if node.startswith("consumer-") and node != consumer) self.mutate(consumer_node_ids=[self.node_id(consumer)]) self.probe(partner, "capabilities", expected_state="Unavailable") for realm in ("raw", "uns"): self.cli("read", partner, realm, denial=True) def scenario_D11(self): before = self.device()["effect_total"] with self.stopped("control-1", "control-2"): for realm in ("raw", "uns"): self.cli("read", self.primary("source"), realm) consumer = self.primary("consumer") for operation in ("read", "subscribe"): started = time.monotonic() self.prepare_positive_projection(consumer, realm) self.timeline.append({"event": "control-outage-projection-prepared", "node": consumer, "realm": realm, "operation": operation, "started_at": started, "at": time.monotonic(), "setup": "authenticated Browse while both CONTROL nodes are stopped; no automatic lease-renewal claim"}) if operation == "subscribe": with self.changing(): self.cli(operation, consumer, realm) else: self.cli(operation, consumer, realm) self.wait_primary("control") self.check(self.device()["effect_total"] == before, "controller reconciliation did not replay writes") def scenario_D12(self): consumer = self.primary("consumer") partner = next(node for node in self.manifest["nodes"] if node.startswith("consumer-") and node != consumer) for mutation in ({"consumer_node_ids": [self.node_id(partner)]}, {"export_enabled": False}, {"mapping_enabled": False}, {"connection_enabled": False, "mapping_enabled": False}, {"disable_feature": True}): self.mutate(**mutation) for realm in ("raw", "uns"): self.cli("read", consumer, realm, denial=True) self.cli("write", consumer, realm, denial=True) self.cli("read", self.primary("source"), realm) deployment = self.manifest["deployment"] self.check({row["nodeId"] for row in deployment["nodes"] if row["status"] == "Applied"} == set(deployment["required_node_ids"]), "existing deployment command path applied after withdrawal") telemetry = self.probe(self.primary("control"), "legacy-telemetry", expectedNodeId=self.node_id(self.primary("source")), timeout=20) self.check(telemetry.get("authenticatedSnapshotReceived") is True, "existing authenticated telemetry plane remains usable after withdrawal") if any(key in mutation for key in ("consumer_node_ids", "mapping_enabled", "connection_enabled", "disable_feature")): end = time.monotonic() + self.remaining(30) while True: connections = self.probe(consumer, "topology").get("connections") self.check(isinstance(connections, list), "withdrawal diagnostics available") if all(connection["activeStreams"] == 0 and connection["activeCalls"] == 0 for connection in connections): self.check(True, "projected streams and operations withdrawn") break if time.monotonic() >= end: raise ScenarioError("removed projection retained remote demand") time.sleep(min(0.25, end - time.monotonic())) self.baseline() def scenario_D13(self): self.wire() consumer = self.primary("consumer") certificate_target = self.primary("source") self.mutate(target_mode="Node", target_node_id=self.node_id(certificate_target), consistency="ReadyReplica") for reason in ("wrong-ca", "wrong-san"): for realm in ("raw", "uns"): self.probe(consumer, "read", realm, expectedNodeId=self.node_id(certificate_target)) with self.rig.rejected_server_identity(certificate_target, reason): self.manifest = self.rig.load() self.wait_primary("source") control = self.rig.verify_test_tls_listener(certificate_target, reason) before_tls = self.probe(certificate_target, "topology") for realm in ("raw", "uns"): self.matrix_probe("cross-cluster", "Node", realm, "capabilities", consumer, boundary=reason, expected_node=certificate_target, expected_state="Unavailable") self.cli("read", consumer, realm, denial=True) after_tls = self.probe(certificate_target, "topology") self.save("D13-" + reason + "-tls-boundary.json", {"listener_control": control, **validate_tls_rejection_counters(before_tls, after_tls)}) self.manifest = self.rig.load() self.wait_primary("source") for realm in ("raw", "uns"): self.wait_connection_ready(consumer, realm, expected_node=certificate_target) self.probe(consumer, "read", realm, expectedNodeId=self.node_id(certificate_target)) self.check(self.probe(certificate_target, "topology").get("inboundDataRequests", 0) > 0, "restored actual consumer traffic proves the listener observer") self.mutate(target_mode="Cluster", consistency="Primary") self.probe(consumer, "read", subject="unrelated/claimed/principal", expected_state="Denied") request = {"upsert_export": {"DataExportId": "illegal-peer-reexport", "ClusterId": "CONSUMER", "Enabled": True, "Realm": 1, "RootKind": "RemoteNamespaceMapping", "RootEntityId": "map-raw", "PrincipalId": "fixture-consumer", "AllowedOperations": OPERATIONS}} rig.atomic_write_secret(self.rig.folder / "seed" / "mutation.json", json.dumps(request)) rejected = False try: self.rig.seed_helper("mutate") except rig.RigError: rejection = restricted_json(self.rig.folder / "seed" / "rejection.json") rejected = rejection.get("validator") == "DraftValidator" and bool(rejection.get("codes")) self.save("D13-peer-reexport-rejection.json", rejection) self.check(rejected, "production authoring rejects mounted peer re-export") def scenario_D14(self): consumer = self.primary("consumer") # Missing/retired material exercises the durable P07 store by restarting # the actual caller; changing only this Python process would prove nothing. self.rig.credential_action("remove_consumer_secret") self.rig.compose("restart", consumer, timeout=self.remaining(40)) self.manifest = self.rig.refresh_endpoints((consumer,)) self.wait_primary("consumer") self.probe(consumer, "capabilities", expected_state="Unavailable") self.rig.credential_action("provision_consumer_secret") self.wait_connection_ready(consumer, require_fresh_sample=True) self.probe(consumer, "read") for node in ("consumer-1", "consumer-2"): self.wait_connection_ready(node) self.probe(node, "capabilities", expected_state="Ready") self.mutate(key_action="rotate_staged") self.wait_connection_ready(consumer, require_fresh_sample=True) self.probe(consumer, "read") self.wire(previous_key_state="enabled") self.mutate(key_action="retire_old") self.wait_connection_ready(consumer, require_fresh_sample=True) self.probe(consumer, "read") self.wire(previous_key_state="revoked") self.rig.trust_action("stage_new") self.wait_connection_ready(consumer, require_fresh_sample=True) self.probe(consumer, "read") self.rig.trust_action("rotate_server") self.manifest = self.rig.load() self.wait_primary("source") self.wait_connection_ready(consumer, require_fresh_sample=True) self.probe(consumer, "read") self.rig.trust_action("retire_old") self.manifest = self.rig.load() self.wire() certificate_target = self.primary("source") self.mutate(target_mode="Node", target_node_id=self.node_id(certificate_target), consistency="ReadyReplica") for realm in ("raw", "uns"): self.probe(consumer, "read", realm, expectedNodeId=self.node_id(certificate_target)) with self.rig.retired_server_identity(certificate_target): self.manifest = self.rig.load() self.wait_primary("source") control = self.rig.verify_test_tls_listener(certificate_target, "retired-ca") before_tls = self.probe(certificate_target, "topology") for realm in ("raw", "uns"): self.matrix_probe("cross-cluster", "Node", realm, "capabilities", consumer, boundary="retired-ca", expected_node=certificate_target, expected_state="Unavailable") self.cli("read", consumer, realm, denial=True) after_tls = self.probe(certificate_target, "topology") self.save("D14-retired-ca-tls-boundary.json", {"listener_control": control, **validate_tls_rejection_counters(before_tls, after_tls)}) self.manifest = self.rig.load() self.wait_primary("source") for realm in ("raw", "uns"): self.wait_connection_ready(consumer, realm, expected_node=certificate_target) self.probe(consumer, "read", realm, expectedNodeId=self.node_id(certificate_target)) self.check(self.probe(certificate_target, "topology").get("inboundDataRequests", 0) > 0, "restored current trust produces actual HTTP requests") self.mutate(target_mode="Cluster", consistency="Primary") before = self.device()["effect_total"] operation = "offline-loss-" + uuid.uuid4().hex self.device("drop_next_write_response") self.probe(consumer, "dedup", expected_state="OutcomeUnknown", operationId=operation) self.check(self.device()["effect_total"] == before + 1, "tracked ambiguous effect before offline restart") with self.stopped("control-1", "control-2"): self.rig.compose("restart", consumer, timeout=self.remaining(40)) self.manifest = self.rig.refresh_endpoints((consumer,)) self.wait_primary("consumer") self.wait_connection_ready(consumer, require_fresh_sample=True) self.probe(consumer, "read") self.probe(consumer, "dedup", expected_state="OutcomeUnknown", operationId=operation) self.check(self.device()["effect_total"] == before + 1, "offline restart did not replay in-flight writes") partner = next(node for node in self.manifest["nodes"] if node.startswith("consumer-") and node != consumer) self.mutate(consumer_node_ids=[self.node_id(partner)]) self.rig.credential_action("reload_stale_bundle", node=consumer) self.probe(consumer, "capabilities", expected_state="Unavailable")