#!/usr/bin/env python3 """Final unfiltered solution gate, with explicit local fixture environment and assembly evidence.""" import argparse import glob import hashlib import importlib.util import json import math import os import platform from pathlib import Path import re import subprocess import sys import time import xml.etree.ElementTree as ET HERE = Path(__file__).resolve().parent ROOT = HERE.parents[2] spec = importlib.util.spec_from_file_location("unit_phase", HERE / "run-unit-phase.py") phase = importlib.util.module_from_spec(spec) spec.loader.exec_module(phase) class FinalGateError(RuntimeError): pass def inventory(root=ROOT): """Inventory all test projects, without relying on an incomplete name suffix.""" projects = [] for path in sorted((root / "tests").rglob("*.csproj")): tree = ET.fromstring(path.read_text()) props = {item.tag.split("}")[-1]: item.text for group in tree if group.tag.endswith("PropertyGroup") for item in group} text = path.read_text() if props.get("IsTestProject", "").lower() != "true" and not any(name in text for name in ("Microsoft.NET.Test.Sdk", "xunit", "NUnit", "MSTest")): continue sources = {source for source in path.parent.rglob("*.cs") if not any(part in {"bin", "obj"} for part in source.relative_to(path.parent).parts)} for item in tree.iter(): if item.tag.rsplit("}", 1)[-1] == "Compile" and item.get("Include"): sources.update(Path(p).resolve() for p in glob.glob(str(path.parent / item.get("Include").replace("\\", "/")), recursive=True) if Path(p).is_file()) content = "\n".join(source.read_text() for source in sources) projects.append({"project": str(path.relative_to(root)), "assembly": props.get("AssemblyName") or path.stem, "framework": props.get("TargetFramework") or props.get("TargetFrameworks"), "sources": len(sources), "categories": sorted(set(re.findall(r'Trait\(\s*"Category"\s*,\s*"([^"\n]+)"', content))), "literal_environment": sorted(set(re.findall(r'GetEnvironmentVariable\(\s*"([^"\n]+)"', content))), "grpc_classes": sorted(set(re.findall(r'class\s+(GrpcData\w*Tests)\b', content)))}) if not projects: raise FinalGateError("test project inventory is empty") return projects REQUIRED_FIXTURES = {"OTOPCUA_CONFIG_TEST_SERVER", "OTOPCUA_CONFIG_TEST_SA_PASSWORD", "SQL_TEST_ENDPOINT", "SQL_TEST_USER", "SQL_TEST_PASSWORD", "SQL_PG_ENDPOINT", "SQL_PG_PASSWORD", "HISTORIAN_SQL_TEST_CONNECTION", "HISTORIAN_QUESTDB_TEST_CONNECTION", "OPCUA_SIM_ENDPOINT", "OPCUA_NAT_ENDPOINT", "OPCUA_NAT_SERVER_CERT", "OTOPCUA_LOCAL_FIXTURE_MODE", "MODBUS_SIM_ENDPOINT", "MODBUS_RTU_SIM_ENDPOINT", "S7_SIM_ENDPOINT", "S7_SIM_ALLOW_WRITES", "AB_SERVER_ENDPOINT", "AB_SERVER_CONTROLLOGIX_ENDPOINT", "AB_SERVER_ALLOW_WRITES", "AB_LEGACY_ENDPOINT", "AB_LEGACY_SLC500_ENDPOINT", "AB_LEGACY_MICROLOGIX_ENDPOINT", "AB_LEGACY_PLC5_ENDPOINT", "OTOPCUA_FOCAS_SIM_ENDPOINT", "OTOPCUA_FOCAS_SIM_PROFILE", "MTCONNECT_AGENT_ENDPOINT", "MTCONNECT_WRITE_TARGET", "MQTT_FIXTURE_ENDPOINT", "MQTT_FIXTURE_PLAIN_ENDPOINT", "MQTT_FIXTURE_USERNAME", "MQTT_FIXTURE_PASSWORD", "MQTT_FIXTURE_CA_CERT", "MQTT_FIXTURE_TOPIC_PREFIX", "OTOPCUA_HARNESS_USE_SQL", "OTOPCUA_HARNESS_SQL_HOST", "OTOPCUA_HARNESS_SQL_PASSWORD", "OTOPCUA_HARNESS_USE_LDAP", "OTOPCUA_HARNESS_LDAP_HOST", "OTOPCUA_HARNESS_LDAP_PORT", "HOST_PROBE_OPCUA_ENDPOINT"} REQUIRED_FIXTURES.update({"SQL_ODBC_CONNECTION_STRING", "SQL_PG_USER", "SQL_MYSQL_ENDPOINT", "SQL_MYSQL_USER", "SQL_MYSQL_PASSWORD", "SQL_ORACLE_ENDPOINT", "SQL_ORACLE_USER", "SQL_ORACLE_PASSWORD", "SQL_ORACLE_SERVICE", "SQL_BLACKHOLE_ENDPOINT", "SQL_BLACKHOLE_USER", "SQL_BLACKHOLE_PASSWORD", "SQL_BLACKHOLE_CONTAINER_ID", "SQL_BLACKHOLE_FIXTURE_OWNER", "SQL_BLACKHOLE_ENV_JSON", "SQL_BLACKHOLE_CONTROL_SCRIPT", "S7_RECONNECT_BOUNCE_CMD", "S7_TIMEOUT_OUTAGE_START_CMD", "S7_TIMEOUT_OUTAGE_STOP_CMD"}) ODBC_DRIVER = Path("/opt/homebrew/opt/psqlodbc/lib/psqlodbcw.so") ODBC_DRIVER_MANAGER = Path("/opt/homebrew/opt/unixodbc/lib/libodbc.2.dylib") SDK_LIFECYCLE_RUN = "sdk-lifecycle-diagnostic" SDK_LIFECYCLE_ASSEMBLY = "ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests" SDK_LIFECYCLE_CASE = SDK_LIFECYCLE_ASSEMBLY + ".Sdk2LifecycleSoakTests.Repeated_lifecycles_return_resources_to_a_steady_baseline" SDK_LIFECYCLE_SKIP = "Opt in with OTOPCUA_SDK2_SOAK=1 and an explicit soak mode." SDK_LIFECYCLE_SECONDS = 90 AB_CIP_ASSEMBLY = "ZB.MOM.WW.OtOpcUa.Driver.AbCip.IntegrationTests" PROFILE_PROJECTS = {**{"modbus-" + p: "ZB.MOM.WW.OtOpcUa.Driver.Modbus.IntegrationTests" for p in ("dl205", "mitsubishi", "s7_1500", "exception_injection")}, **{"ab-" + p: AB_CIP_ASSEMBLY for p in ("compactlogix", "micro800", "guardlogix")}} AB_DIFFERENTIAL_RUN = "ab-software-differential" _TRANSPORT_TESTS = AB_CIP_ASSEMBLY + ".Differential.TransportDifferentialTests." _LATENCY_TESTS = AB_CIP_ASSEMBLY + ".Differential.PollLatencyComparisonTests." AB_DIFFERENTIAL_MIX_CASE = AB_CIP_ASSEMBLY + ".Differential.EvidenceTests.Mixed_string_array_and_scalar_reads_travel_as_one_multiple_service_packet" AB_DIFFERENTIAL_MIX_TAGS = "TestString|String|1;TestArray[1]|DInt|1;TestArray|DInt|16;TestDINT|DInt|1;TestBOOL|Bool|1" AB_DIFFERENTIAL_LIVE_CASES = frozenset({_TRANSPORT_TESTS + method for method in ( "Browse_listings_decode_to_identical_tag_sets_through_both_enumerators", "Every_template_decodes_to_an_identical_shape_through_both_readers", "Every_selected_tag_reads_identically_through_both_transports", "Libplctag_and_native_are_never_connected_at_the_same_time", "No_failed_libplctag_tag_is_left_with_a_live_native_callback", "The_native_side_makes_exactly_one_forward_open_over_the_whole_run", "The_native_side_closes_its_one_connection_with_exactly_one_forward_close", )} | {_LATENCY_TESTS + "Native_poll_p95_is_within_ten_percent_of_libplctag", AB_DIFFERENTIAL_MIX_CASE}) AB_DIFFERENTIAL_CASES = AB_DIFFERENTIAL_LIVE_CASES | {_TRANSPORT_TESTS + method for method in ( "The_harness_is_read_only_by_construction", "The_comparison_flags_every_divergence_and_excuses_only_a_native_type_mismatch", "A_live_value_is_compared_structurally_and_a_stable_one_by_value", )} | {_LATENCY_TESTS + "Tag_pick_takes_atomic_scalars_only_and_repeats_a_short_set_visibly"} AB_DIFFERENTIAL_SKIP = ("AB_DIFF_ENDPOINT is not set — point it at host:port of the one controller to compare " "(e.g. 10.100.0.35:44818 for ab_server).") def ab_loopback_port(value): match = re.fullmatch(r"127\.0\.0\.1:([1-9][0-9]{0,4})", value) if match and 1 < int(match[1]) <= 65535: return int(match[1]) raise FinalGateError("AB software fixtures require an explicit owned loopback port") def child_environment(fixture, inherited=None): """Strip ambient application/fixture settings before adding explicit local-owned values.""" if not isinstance(fixture, dict) or not REQUIRED_FIXTURES.issubset(fixture) or any(not isinstance(k, str) or not isinstance(v, str) or not v for k, v in fixture.items()): raise FinalGateError("required local fixture variables are missing") if fixture.get("OTOPCUA_LOCAL_FIXTURE_MODE") != "1": raise FinalGateError("local fixture mode must be explicit") if any(fixture.get(key) != "1" for key in ("OTOPCUA_HARNESS_USE_SQL", "OTOPCUA_HARNESS_USE_LDAP", "S7_SIM_ALLOW_WRITES", "AB_SERVER_ALLOW_WRITES")): raise FinalGateError("owned software fixture opt-ins must be explicit") odbc = fixture["SQL_ODBC_CONNECTION_STRING"] if "Driver={" + str(ODBC_DRIVER) + "}" not in odbc or re.search(r"(?:^|;)\s*DSN\s*=", odbc, re.I): raise FinalGateError("ODBC requires the explicit installed local driver and no DSN") allowed_keys = REQUIRED_FIXTURES | {"MODBUS_SIM_PROFILE", "AB_SERVER_PROFILE", "AB_SERVER_COMPOSE_PROFILE", "AB_LEGACY_CIP_PATH"} if set(fixture) - allowed_keys: raise FinalGateError("fixture environment contains an unapproved variable") ab_loopback_port(fixture["AB_SERVER_ENDPOINT"]) ab_loopback_port(fixture["AB_SERVER_CONTROLLOGIX_ENDPOINT"]) # Parse actual endpoint/connection hosts, not incidental occurrences of "localhost" # in a password or path. The shared rig validator rejects all external hosts. import rig try: rig.validate_fixture_endpoints(fixture, local_services={"localhost"}) except rig.RigError as error: raise FinalGateError("a fixture endpoint is not loopback") from error base = {k: v for k, v in (os.environ if inherited is None else inherited).items() if k in phase.ENV_ALLOWLIST} base.update(fixture) base.pop("OTOPCUA_UNIT_ONLY_DISCOVERY", None) base["AKKA_TEST_TIMEFACTOR"] = "3" return base def private_text(path, value): """Write empty or populated evidence without secret-writer nonempty semantics.""" fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w") as stream: stream.write(value) def logged_run(name, command, directory, environment, *, timeout=21600): private_json(directory / (name + ".command.json"), command) with private_stream(directory / (name + ".stdout.log")) as out, private_stream(directory / (name + ".stderr.log")) as err: result = subprocess.run(command, cwd=ROOT, env=environment, stdout=out, stderr=err, timeout=timeout) return result.returncode def private_stream(path): return os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") def private_json(path, value): private_text(path, json.dumps(value, indent=2) + "\n") def macos_odbc_testhost_args(): # VSTest launches a native testhost, where the ODBC driver manager is loaded. return ["--environment", f"DYLD_LIBRARY_PATH={ODBC_DRIVER_MANAGER.parent}"] if platform.system() == "Darwin" else [] def solution_commands(directory): solution = "ZB.MOM.WW.OtOpcUa.slnx" return (["dotnet", "build", solution, "-c", "Release", "--no-restore", "-m:1", "-p:TestTfmsInParallel=false"], ["dotnet", "test", solution, "-c", "Release", "--no-build", "-m:1", "-p:TestTfmsInParallel=false", "--nologo", "--settings", "scripts/ci/ci.runsettings", "--blame-hang", "--blame-hang-timeout", "20m", "--blame-hang-dump-type", "none", "--logger", "trx", *macos_odbc_testhost_args(), "--results-directory", str(directory)]) def discover_project(project, directory, environment, *, expression=None): directory.mkdir(parents=True, mode=0o700) command = ["dotnet", "test", project["project"], "-c", "Release", "-m:1", "-p:TestTfmsInParallel=false", "--no-build", "--list-tests", "--settings", "scripts/ci/ci.runsettings", *macos_odbc_testhost_args()] if expression is not None: command.extend(["--filter", expression]) exit_code = logged_run("discovery", command, directory, environment, timeout=1200) names = phase.discover_names((directory / "discovery.stdout.log").read_text()) if exit_code or not names: raise FinalGateError("test discovery failed for " + project["assembly"]) return {"assembly": project["assembly"], "tests": names} def run_profile(project, test, directory, environment, *, selected=None): expression = "|".join("FullyQualifiedName=" + name for name in sorted(selected)) if selected is not None else None discovery = discover_project(project, directory, environment, expression=expression) private_json(directory / "discovery.json", [discovery]) if selected is not None and set(discovery["tests"]) != selected: raise FinalGateError("supplemental discovery differs from the exact test selection") profile_test = test.copy() profile_test[2] = project["project"] profile_test[profile_test.index("--results-directory") + 1] = str(directory / "trx") if expression is not None: profile_test.extend(["--filter", expression]) return logged_run("test", profile_test, directory, environment, timeout=7200) def differential_environment(base): """Enable only the read-only harness against the owned ControlLogix simulator.""" endpoint = base.get("AB_SERVER_ENDPOINT", "") ab_loopback_port(endpoint) if base.get("AB_SERVER_COMPOSE_PROFILE") != "controllogix" or base.get("AB_SERVER_CONTROLLOGIX_ENDPOINT") != endpoint: raise FinalGateError("software differential requires the owned loopback ControlLogix fixture") environment = {key: value for key, value in base.items() if key in phase.ENV_ALLOWLIST} environment.update({"OTOPCUA_LOCAL_FIXTURE_MODE": "1", "AB_SERVER_ENDPOINT": "127.0.0.1:1", "AB_SERVER_CONTROLLOGIX_ENDPOINT": "127.0.0.1:1", "AB_DIFF_ENDPOINT": endpoint, "AB_DIFF_COUNT_OPENS": "1", "AB_DIFF_FAMILY": "ControlLogix", "AB_DIFF_PATH": "1,0", "AB_EVID_MIX": "1", "AB_EVID_TAGS": AB_DIFFERENTIAL_MIX_TAGS}) return environment WORKER_NAME = "ZB.MOM.WW.OtOpcUa.ScriptWorker" WORKER_PROJECT = "src/Server/" + WORKER_NAME + "/" + WORKER_NAME + ".csproj" def native_worker_rid(system=None, architecture=None): system = (platform.system() if system is None else system).lower() architecture = (platform.machine() if architecture is None else architecture).lower() os_name = {"darwin": "osx", "linux": "linux", "windows": "win"}.get(system) cpu = {"arm64": "arm64", "aarch64": "arm64", "x86_64": "x64", "amd64": "x64"}.get(architecture) if os_name is None or cpu is None: raise FinalGateError("unsupported native ScriptWorker publishing platform") return os_name + "-" + cpu def worker_output_identity(output, rid): """Require the named executable, self-contained metadata and matching native RID.""" entry = output / (WORKER_NAME + (".exe" if rid.startswith("win-") else "")) required = [entry, *(output / (WORKER_NAME + suffix) for suffix in (".dll", ".deps.json", ".runtimeconfig.json"))] if any(path.is_symlink() or not path.is_file() for path in required) or not os.access(entry, os.X_OK): raise FinalGateError("published ScriptWorker executable or identity files are missing") options = json.loads((output / (WORKER_NAME + ".runtimeconfig.json")).read_text()).get("runtimeOptions", {}) dependencies = json.loads((output / (WORKER_NAME + ".deps.json")).read_text()) frameworks = options.get("includedFrameworks") target = dependencies.get("runtimeTarget", {}).get("name") if (not isinstance(frameworks, list) or not frameworks or "framework" in options or "frameworks" in options or not isinstance(target, str) or not target.endswith("/" + rid) or not any(name.startswith(WORKER_NAME + "/") and value.get("type") == "project" for name, value in dependencies.get("libraries", {}).items())): raise FinalGateError("published ScriptWorker is not the expected self-contained native worker") files = {} for path in sorted(output.rglob("*")): if path.is_symlink(): raise FinalGateError("published ScriptWorker contains a symlink") if path.is_file(): files[path.relative_to(output).as_posix()] = {"sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "mode": path.stat().st_mode & 0o777} return entry, files def prepare_script_worker(directory, *, environment, identity): """Publish only to this final run's fresh owned artifact directory.""" directory = Path(directory) if (not directory.is_absolute() or directory.is_symlink() or not directory.is_dir() or not isinstance(identity.get("revision"), str) or not identity["revision"] or not re.fullmatch(r"[0-9a-f]{64}", identity.get("execution_input_sha256", ""))): raise FinalGateError("ScriptWorker publishing requires an owned final directory and source identity") rid = native_worker_rid() output = directory / "script-worker" output.mkdir(mode=0o700, exist_ok=False) clean = {key: value for key, value in environment.items() if key in phase.ENV_ALLOWLIST} command = ["dotnet", "publish", str(ROOT / WORKER_PROJECT), "-c", "Release", "--runtime", rid, "--self-contained", "true", "-m:1", "-p:UseAppHost=true", "-p:PublishSingleFile=false", "-p:PublishTrimmed=false", "--output", str(output)] if logged_run("script-worker-publish", command, directory, clean, timeout=1200): raise FinalGateError("self-contained ScriptWorker publishing failed") entry, files = worker_output_identity(output, rid) private_json(directory / "script-worker.json", {"project": WORKER_PROJECT, "runtime_identifier": rid, "source_revision": identity["revision"], "execution_input_sha256": identity["execution_input_sha256"], "entry": str(entry), "files": files}) return {"OTOPCUA_SCRIPTWORKER_TEST_PATH": str(entry)} def script_worker_identity_matches(directory): try: receipt = json.loads((directory / "script-worker.json").read_text()) entry, files = worker_output_identity(directory / "script-worker", receipt["runtime_identifier"]) return receipt["project"] == WORKER_PROJECT and receipt["entry"] == str(entry) and receipt["files"] == files except (FinalGateError, OSError, ValueError, KeyError, TypeError): return False SATURATION_OBSERVER_ENV = "OTOPCUA_SDK2_SATURATION_OBSERVER" SATURATION_OBSERVER_ASSEMBLY = "ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests" SATURATION_OBSERVER_METHOD = SATURATION_OBSERVER_ASSEMBLY + ".Sdk2LifecycleSoakTests.Saturation_protocol_actual_observer_drains_and_rejects_extra_foreign_markers" SATURATION_OBSERVER_TOOLS = ROOT / "scripts/validation/opcua-lifecycle-memory" SATURATION_OBSERVER_BUILDER = SATURATION_OBSERVER_TOOLS / "build_saturation_observer.py" DOTNET_TRACE_VERSION = "9.0.661903" TRACE_LIBRARIES = ("Microsoft.Diagnostics.NETCore.Client.dll", "Microsoft.Diagnostics.Tracing.TraceEvent.dll", "Microsoft.Diagnostics.FastSerialization.dll") def saturation_observer_inputs(libraries): tool_deps = libraries / "dotnet-trace.deps.json" paths = [SATURATION_OBSERVER_BUILDER, SATURATION_OBSERVER_TOOLS / "SaturationObserver.cs", tool_deps, *(libraries / name for name in TRACE_LIBRARIES)] if any(path.is_symlink() or not path.is_file() or not path.stat().st_size for path in paths): raise FinalGateError("saturation observer requires installed dotnet-trace " + DOTNET_TRACE_VERSION + " libraries") dependencies = json.loads(tool_deps.read_text()) if "dotnet-trace/" + DOTNET_TRACE_VERSION not in dependencies.get("libraries", {}): raise FinalGateError("saturation observer dotnet-trace installation has the wrong version") return {path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in paths} def saturation_observer_libraries(): return Path.home() / f".dotnet/tools/.store/dotnet-trace/{DOTNET_TRACE_VERSION}/dotnet-trace/{DOTNET_TRACE_VERSION}/tools/net8.0/any" def saturation_observer_output(directory, inputs): package = directory / "saturation-observer" build = package / "build" runtime = build / "bin/Release/net10.0" entry = runtime / "observer.dll" config = runtime / "observer.runtimeconfig.json" deps = runtime / "observer.deps.json" directories = (package, build, runtime.parent.parent, runtime.parent, runtime) required = (entry, config, deps, *(runtime / name for name in TRACE_LIBRARIES)) if (any(path.is_symlink() or not path.is_dir() for path in directories) or any(path.is_symlink() or not path.is_file() or not path.stat().st_size for path in required)): raise FinalGateError("saturation observer portable build is incomplete") options = json.loads(config.read_text()).get("runtimeOptions", {}) dependencies = json.loads(deps.read_text()) frameworks = options.get("frameworks", []) if (options.get("tfm") != "net10.0" or "includedFrameworks" in options or {item.get("name") for item in frameworks if str(item.get("version", "")).startswith("10.")} != {"Microsoft.NETCore.App", "Microsoft.AspNetCore.App"} or dependencies.get("runtimeTarget", {}).get("name") != ".NETCoreApp,Version=v10.0" or not any(name.startswith("observer/") and item.get("type") == "project" for name, item in dependencies.get("libraries", {}).items())): raise FinalGateError("saturation observer must be a framework-dependent net10.0 build") files = {} for path in sorted(runtime.rglob("*")): if path.is_symlink(): raise FinalGateError("saturation observer output contains a symlink") if path.is_file(): files[path.relative_to(runtime).as_posix()] = {"sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "mode": path.stat().st_mode & 0o777} if any(files[name]["sha256"] != inputs[name] for name in TRACE_LIBRARIES): raise FinalGateError("saturation observer did not copy the exact dotnet-trace libraries") return entry, files def saturation_observer_receipt(directory, identity, inputs): entry, files = saturation_observer_output(directory, inputs) return {"source_revision": identity["revision"], "execution_input_sha256": identity["execution_input_sha256"], "entry": str(entry), "dotnet_trace_version": DOTNET_TRACE_VERSION, "inputs": inputs, "files": files} def prepare_saturation_observer(directory, *, environment, identity): """Build the portable observer for the two short SDK protocol controls.""" if (not directory.is_absolute() or directory.is_symlink() or not directory.is_dir() or not identity.get("revision") or not re.fullmatch(r"[0-9a-f]{64}", identity.get("execution_input_sha256", ""))): raise FinalGateError("saturation observer requires an owned final directory and source identity") libraries = saturation_observer_libraries() inputs = saturation_observer_inputs(libraries) package = directory / "saturation-observer" package.mkdir(mode=0o700) clean = {key: value for key, value in environment.items() if key in phase.ENV_ALLOWLIST} command = [sys.executable, str(SATURATION_OBSERVER_BUILDER), "--output", str(package / "build"), "--libraries", str(libraries)] if logged_run("saturation-observer-build", command, directory, clean, timeout=1200): raise FinalGateError("portable saturation observer build failed") if inputs != saturation_observer_inputs(libraries): raise FinalGateError("saturation observer inputs changed during build") receipt = saturation_observer_receipt(directory, identity, inputs) private_json(directory / "saturation-observer.json", receipt) return {SATURATION_OBSERVER_ENV: receipt["entry"]} def saturation_observer_identity_matches(directory, identity, optins): try: receipt_path = directory / "saturation-observer.json" if receipt_path.is_symlink(): return False receipt = json.loads(receipt_path.read_text()) inputs = saturation_observer_inputs(saturation_observer_libraries()) return (receipt == saturation_observer_receipt(directory, identity, inputs) and optins.get(SATURATION_OBSERVER_ENV) == receipt["entry"]) except (FinalGateError, OSError, ValueError, KeyError, TypeError, AttributeError): return False def saturation_observer_protocol_rows(rows): selected = [row for row in rows if row["assembly"] == SATURATION_OBSERVER_ASSEMBLY and row["test"].split("(", 1)[0] == SATURATION_OBSERVER_METHOD] expected = {f"{SATURATION_OBSERVER_METHOD}(foreignMarker: {marker})" for marker in ("False", "True")} complete = len(selected) == len(expected) and {row["test"] for row in selected if row["outcome"] == "Passed"} == expected return {"rows": selected, "passed": complete} def read_results(directory, projects, *, minimum=12000): """Read concrete TRX rows; do not mistake source method names for theory cases.""" assemblies = {}; skipped = []; failures = []; rows = []; total = 0; seen_classes = set() for path in sorted(Path(directory).rglob("*.trx")): tree = ET.parse(path).getroot(); definitions = {} for definition in tree.findall(".//{*}UnitTest"): method = definition.find("{*}TestMethod") if method is not None: assembly = Path(method.get("codeBase", definition.get("storage", "")).replace("\\", "/")).stem cls = method.get("className", "").split(",")[0] name = method.get("name", "") # xUnit lists delayed theories by their method. Its TRX definition retains # that name and ID while each result carries its concrete argument display. canonical_name = cls + "." + name deferred_parent = None if method.get("adapterTypeName") == "executor://xunit/VsTestRunner3/netcore/" and definition.get("name") == canonical_name: deferred_parent = canonical_name definitions[definition.get("id")] = (assembly, cls, name, deferred_parent) for result in tree.findall("{*}Results/{*}UnitTestResult"): test_id = result.get("testId") assembly, cls, method, deferred_parent = definitions.get(test_id, ("", "", "", None)) if not assembly: raise FinalGateError("result has no test assembly identity") row = assemblies.setdefault(assembly, {"executed": 0, "passed": 0, "failed": 0, "skipped": 0, "files": set()}) row["files"].add(str(path)); outcome = result.get("outcome") display = result.get("testName", "") name = display if display.startswith(cls + ".") else cls + "." + method seen_classes.add((assembly, cls.rsplit(".", 1)[-1])) message = result.find(".//{*}Message"); reason = message.text if message is not None else "No reason supplied" item = {"assembly": assembly, "test": name, "outcome": outcome, "reason": reason, "trx": str(path)} if test_id and deferred_parent and display.startswith(deferred_parent + "(") and display.endswith(")"): item["deferred_theory"] = {"method": deferred_parent, "test_id": test_id, "execution_id": result.get("executionId")} rows.append(item) if outcome == "Passed": row["passed"] += 1; row["executed"] += 1; total += 1 elif outcome == "NotExecuted": row["skipped"] += 1; skipped.append(item) else: row["failed"] += 1; row["executed"] += 1; total += 1; failures.append(item) missing = [p["assembly"] for p in projects if p["assembly"] not in assemblies or not assemblies[p["assembly"]]["executed"]] missing_grpc = sorted({(project["assembly"], name) for project in projects for name in project["grpc_classes"]} - seen_classes) skipped_grpc = [row for row in skipped if ".GrpcData" in row["test"]] for row in assemblies.values(): row["files"] = sorted(row["files"]) return {"executed": total, "assemblies": assemblies, "rows": rows, "skipped": skipped, "failures": failures, "missing_assemblies": missing, "missing_grpc_classes": missing_grpc, "skipped_grpc": skipped_grpc, "passed": total >= minimum and not failures and not missing and not missing_grpc and not skipped} def unavailable_records(path): """An exact, reviewable decision, never a category or pattern exclusion. JSON is a list of {assembly,test,reason,kind,requires,evidence,next_gate}. evidence is an existing absolute private file documenting the observed local prerequisite check. kind is hardware/proprietary/platform/explicit-unavailable. The final report retains its SHA256, exact skip reason and next required gate. """ if path is None: return {} items = json.loads(Path(path).read_text()); result = {} if not isinstance(items, list): raise FinalGateError("unavailable evidence must be a list") for item in items: keys = ("assembly", "test", "reason", "kind", "requires", "evidence", "next_gate") if not isinstance(item, dict) or any(not isinstance(item.get(k), str) or not item[k].strip() for k in keys): raise FinalGateError("unavailable evidence requires exact identity, reason, prerequisite, evidence and next gate") if item["kind"] not in {"hardware", "proprietary", "platform", "explicit-unavailable"} or ".GrpcData" in item["test"]: raise FinalGateError("required feature coverage cannot be marked unavailable") if any(c in item["test"] for c in ("*", "?")): raise FinalGateError("unavailable test patterns are forbidden") evidence = Path(item["evidence"]) if not evidence.is_absolute() or not evidence.is_file(): raise FinalGateError("unavailable evidence file is missing") key = (item["assembly"], item["test"]) if key in result: raise FinalGateError("duplicate unavailable identity") result[key] = {**item, "evidence_sha256": hashlib.sha256(evidence.read_bytes()).hexdigest()} return result def discovery_gaps(expected, rows): observed = {(row["assembly"], row["test"]) for row in rows} enumerated = {(assembly, name.split("(", 1)[0]) for assembly, name in expected if "(" in name} candidates = {} for row in rows: if "deferred_theory" in row: key = (row["assembly"], row["deferred_theory"]["method"]) candidates.setdefault(key, []).append(row) expansions = [] for parent, cases in sorted(candidates.items()): if parent not in expected or parent in observed or parent in enumerated: continue identities = {(case["trx"], case["deferred_theory"]["test_id"]) for case in cases} executions = {case["deferred_theory"]["execution_id"] for case in cases} names = {(case["assembly"], case["test"]) for case in cases} # Different rows can format to the same display, even within one theory. if len(identities) != 1 or len(executions) != len(cases) or not all(executions): continue trx, test_id = next(iter(identities)) expansions.append({"assembly": parent[0], "method": parent[1], "test_id": test_id, "trx": trx, "rows": [{"test": case["test"], "outcome": case["outcome"], "execution_id": case["deferred_theory"]["execution_id"]} for case in sorted(cases, key=lambda case: case["test"])]}) observed.difference_update(names) observed.add(parent) return sorted(expected - observed), sorted(observed - expected), expansions def sdk_lifecycle_receipt(report, discovery, path, revision): """Bind the fresh-process diagnostic to its exact discovered and executed case.""" rows = report["rows"] expected = [{"assembly": SDK_LIFECYCLE_ASSEMBLY, "tests": [SDK_LIFECYCLE_CASE]}] if discovery != expected or len(rows) != 1: return None row = rows[0] if (row["assembly"], row["test"], row["outcome"]) != (SDK_LIFECYCLE_ASSEMBLY, SDK_LIFECYCLE_CASE, "Passed"): return None try: if path.is_symlink(): return None events = [json.loads(line) for line in path.read_text().splitlines()] first, last = events[0], events[-1] observed = last["seconds"] cycles = last["cycles"] if (first["kind"] == "start" and first["mode"] == "diagnostic" and first["build"] == revision and first["requestedSeconds"] == SDK_LIFECYCLE_SECONDS and last["kind"] == "complete" and last["mode"] == "diagnostic" and last["satisfiesTwoHourDuration"] is False and type(observed) in (int, float) and math.isfinite(observed) and observed >= SDK_LIFECYCLE_SECONDS and type(cycles) is int and cycles >= 3 and sum(event.get("kind") == "quiescent" for event in events) == cycles): return {"test": row["test"], "trx": row["trx"], "observed_seconds": observed, "cycles": cycles, "path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} except (OSError, ValueError, IndexError, KeyError, TypeError, AttributeError): return None return None def reconcile(baseline, overlays, discovery, profile_discovery, unavailable, *, differential=None, differential_discovery=None, sdk_lifecycle_verified=False): """Preserve baseline12000 independently; overlays only close explicit profile skips.""" profile_reports = {"baseline": baseline, **overlays} reports = profile_reports.copy() passed = {(r["assembly"], r["test"]) for report in profile_reports.values() for r in report["rows"] if r["outcome"] == "Passed"} differential_gaps = {} differential_passed = set() if differential is not None: reports[AB_DIFFERENTIAL_RUN] = differential selected = {(AB_CIP_ASSEMBLY, name) for name in AB_DIFFERENTIAL_CASES} discovered = {(d["assembly"], name) for d in differential_discovery for name in d["tests"]} actual = {(r["assembly"], r["test"]) for r in differential["rows"]} if (len(differential_discovery) != 1 or selected != discovered or selected != actual or len(actual) != len(differential["rows"]) or differential["missing_assemblies"] or differential["missing_grpc_classes"] or differential["skipped_grpc"]): differential_gaps = {"missing_discovery": sorted(selected - discovered), "unexpected_discovery": sorted(discovered - selected), "missing_results": sorted(selected - actual), "unexpected_results": sorted(actual - selected), "duplicate_rows": len(actual) != len(differential["rows"]), "missing_assemblies": differential["missing_assemblies"], "missing_grpc_classes": differential["missing_grpc_classes"], "skipped_grpc": differential["skipped_grpc"]} else: differential_passed = {(r["assembly"], r["test"]) for r in differential["rows"] if r["outcome"] == "Passed" and r["test"] in AB_DIFFERENTIAL_LIVE_CASES} observed = {(r["assembly"], r["test"]) for r in baseline["rows"]} expected = {(d["assembly"], name) for d in discovery for name in d["tests"]} missing, unexpected, baseline_expansions = discovery_gaps(expected, baseline["rows"]) decisions = []; unresolved = []; used = set() for report_name, report in reports.items(): for row in report["skipped"]: key = (row["assembly"], row["test"]) if (sdk_lifecycle_verified and report_name == "baseline" and key == (SDK_LIFECYCLE_ASSEMBLY, SDK_LIFECYCLE_CASE) and row["reason"] == SDK_LIFECYCLE_SKIP): decisions.append({**row, "run": report_name, "disposition": "executed-in-isolated-diagnostic", "passed_in": [SDK_LIFECYCLE_RUN]}) elif key in unavailable and unavailable[key]["reason"] == row["reason"]: used.add(key); decisions.append({**row, "run": report_name, "disposition": "unavailable", "evidence": unavailable[key]}) elif report_name != AB_DIFFERENTIAL_RUN and key in differential_passed and row["reason"] == AB_DIFFERENTIAL_SKIP: decisions.append({**row, "run": report_name, "disposition": "executed-in-software-differential", "passed_in": [AB_DIFFERENTIAL_RUN]}) elif key in passed and ((row["assembly"].endswith(".Driver.Modbus.IntegrationTests") and row["reason"].startswith("MODBUS_SIM_PROFILE")) or (row["assembly"].endswith(".Driver.AbCip.IntegrationTests") and "AB_SERVER_COMPOSE_PROFILE" in row["reason"])): decisions.append({**row, "run": report_name, "disposition": "executed-in-profile", "passed_in": [n for n, p in profile_reports.items() if any((r["assembly"], r["test"]) == key and r["outcome"] == "Passed" for r in p["rows"])]}) else: unresolved.append({**row, "run": report_name}) # A project with zero executed tests is permitted only when its entire exact # discovery set has evidence and concrete NotExecuted rows, with no missing rows. fully_unavailable = [] missing_assemblies = [] for assembly in baseline["missing_assemblies"]: names = {key for key in expected if key[0] == assembly} if names and names <= used and names <= observed: fully_unavailable.append(assembly) else: missing_assemblies.append(assembly) failed = [r for p in reports.values() for r in p["failures"]] unused = sorted(set(unavailable) - used) overlay_gaps = {} overlay_expansions = {} for name, report in overlays.items(): discovered = profile_discovery.get(name, []) wanted = {(d["assembly"], test) for d in discovered for test in d["tests"]} missing_overlay, unexpected_overlay, overlay_expansions[name] = discovery_gaps(wanted, report["rows"]) discovery_matches_assembly = len(discovered) == 1 and discovered[0]["assembly"] == PROFILE_PROJECTS.get(name) if (not discovery_matches_assembly or not wanted or missing_overlay or unexpected_overlay or not report["executed"] or report["missing_assemblies"] or report["missing_grpc_classes"] or report["skipped_grpc"]): overlay_gaps[name] = {"missing": missing_overlay, "unexpected": unexpected_overlay, "executed": report["executed"], "discovery_matches_assembly": discovery_matches_assembly, "missing_assemblies": report["missing_assemblies"], "missing_grpc_classes": report["missing_grpc_classes"], "skipped_grpc": report["skipped_grpc"]} missing_profiles = sorted(set(PROFILE_PROJECTS) - set(overlays)) return {"baseline_executed": baseline["executed"], "overlay_executed": {n: p["executed"] for n, p in overlays.items()}, "skip_decisions": decisions, "unresolved_skips": unresolved, "failures": failed, "missing_results": missing, "unexpected_results": unexpected, "missing_assemblies": missing_assemblies, "fully_unavailable_projects": fully_unavailable, "unused_unavailable_evidence": unused, "missing_grpc_classes": baseline["missing_grpc_classes"], "overlay_discovery_gaps": overlay_gaps, "missing_profiles": missing_profiles, "deferred_theory_expansions": {"baseline": baseline_expansions, "profiles": overlay_expansions}, "software_differential_discovery_gaps": differential_gaps, "passed": baseline["executed"] >= 12000 and not any((failed, unresolved, missing, unexpected, missing_assemblies, baseline["missing_grpc_classes"], baseline["skipped_grpc"], unused, overlay_gaps, missing_profiles, differential_gaps))} def software_optins(directory, revision): directory.mkdir(mode=0o700) outputs = {"OTOPCUA_SDK2_SOAK_OUTPUT": directory / "sdk-diagnostic.jsonl", "OTOPCUA_EVENT_PERF_OUT": directory / "folder-events.jsonl", "OTOPCUA_SCRIPT_PERF_OUT": directory / "script-perf.txt"} if any(path.exists() for path in outputs.values()): raise FinalGateError("software measurement output must be fresh") return {"OTOPCUA_SDK2_SOAK": "1", "OTOPCUA_SDK2_SOAK_MODE": "diagnostic", "OTOPCUA_SDK2_SOAK_SECONDS": str(SDK_LIFECYCLE_SECONDS), "OTOPCUA_SDK2_CLOSE_CONTROL": "1", "OTOPCUA_SOAK_BUILD_SHA": revision, "OTOPCUA_EVENT_PERF": "1", "OTOPCUA_EVENT_PERF_REPORTS": "1000", "OTOPCUA_EVENT_PERF_ROUNDS": "2", "OTOPCUA_SCRIPT_PERF": "1", "OTOPCUA_SCRIPT_PERF_SECONDS": "10", "HISTORIAN_QUESTDB_STRESS_SECONDS": "60", "AB_LEASE_SOAK_CYCLES": "100", "OTOPCUA_BENCH": "1", **{k: str(v.resolve()) for k, v in outputs.items()}} GENERATED_PARTS = {"bin", "obj", "__pycache__"} RECEIPT_PARTS = {"artifacts", "evidence"} NON_INPUT_SUFFIXES = {".md", ".rst", ".adoc", ".log", ".jsonl", ".trx", ".diff", ".since", ".env", ".key", ".pem", ".pfx", ".p12", ".p8"} CODE_SUFFIXES = {".cs", ".csproj", ".py", ".sh", ".ps1", ".psm1", ".js", ".proto", ".razor", ".css", ".axaml", ".props", ".targets", ".rsp"} def execution_input_path(name): """Include the whole executable source/test/harness tree, not review prose or run artifacts.""" if not name or name.startswith("/") or "\\" in name or any(part in {"", ".", ".."} for part in name.split("/")): raise FinalGateError("unsafe candidate input path") parts = name.split("/") suffix = Path(name).suffix.lower() if parts[0] in {"artifacts", ".playwright-mcp"} or any(part.lower() in GENERATED_PARTS for part in parts[:-1]): return False if any(part.lower() in RECEIPT_PARTS for part in parts[1:-1]) and suffix not in CODE_SUFFIXES: return False if any(part.lower() in {"secrets", "private"} for part in parts[:-1]) and suffix not in CODE_SUFFIXES: return False if suffix in NON_INPUT_SUFFIXES: return False if parts[0] in {"src", "tests", "scripts", "tools", "ci"}: return True # These root files select the solution, compiler/package/toolchain and Docker build behavior. return name == ".config/dotnet-tools.json" or len(parts) == 1 and (name.startswith("Directory.") or name in { "global.json", "NuGet.config", "nuget.config", "ZB.MOM.WW.OtOpcUa.slnx", ".dockerignore", ".editorconfig", ".gitignore"}) def execution_input_inventory(root, names): """Hash actual bytes and mode; index status and HEAD are only provenance.""" files = {} for name in sorted(set(names)): if not execution_input_path(name): continue path = root / name if any(parent.is_symlink() for parent in (path, *list(path.parents)[:len(name.split("/")) - 1])): raise FinalGateError("candidate input contains a symlink") if not path.exists(): continue # a tested deletion remains identical after it is committed if not path.is_file(): raise FinalGateError("candidate input is not a regular file") files[name] = {"sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "mode": path.stat().st_mode & 0o777} if not files: raise FinalGateError("candidate execution input inventory is empty") return files def source_identity(root=ROOT): def git(*args): return subprocess.check_output(["git", *args], cwd=root) names = [name for name in git("ls-files", "--cached", "--others", "--exclude-standard", "-z").decode().split("\0") if name] files = execution_input_inventory(root, names) untracked = git("ls-files", "--others", "--exclude-standard", "-z").decode().split("\0") return {"revision": git("rev-parse", "HEAD").decode().strip(), "diff_sha256": hashlib.sha256(git("diff", "HEAD", "--binary")).hexdigest(), "untracked_sha256": {p: files[p]["sha256"] for p in untracked if p in files}, "execution_input_files": files, "execution_input_sha256": hashlib.sha256(json.dumps(files, sort_keys=True, separators=(",", ":")).encode()).hexdigest()} def execution_inputs_match(before, after): digest = before.get("execution_input_sha256") return isinstance(digest, str) and len(digest) == 64 and bool(before.get("execution_input_files")) and \ bool(after.get("execution_input_files")) and digest == after.get("execution_input_sha256") def profile_environments(path, base): documents = json.loads(Path(path).read_text()) if set(documents) != set(PROFILE_PROJECTS): raise FinalGateError("all seven owned profile environments are required") result = {} control_port = ab_loopback_port(base["AB_SERVER_CONTROLLOGIX_ENDPOINT"]) if base.get("AB_SERVER_COMPOSE_PROFILE") != "controllogix" or base["AB_SERVER_ENDPOINT"] != base["AB_SERVER_CONTROLLOGIX_ENDPOINT"]: raise FinalGateError("baseline AB endpoint must be the owned ControlLogix companion") ab_ports = {control_port} for name, document in documents.items(): environment = child_environment({**document, "HOST_PROBE_OPCUA_ENDPOINT": base["HOST_PROBE_OPCUA_ENDPOINT"]}, inherited=base) kind, profile = name.split("-", 1) endpoint, profile_key = ("MODBUS_SIM_ENDPOINT", "MODBUS_SIM_PROFILE") if kind == "modbus" else ("AB_SERVER_ENDPOINT", "AB_SERVER_COMPOSE_PROFILE") if environment.get(profile_key) != profile: raise FinalGateError("fixture environment does not select profile " + name) allowed = {endpoint, profile_key} if kind == "ab": port = ab_loopback_port(environment[endpoint]) if port in ab_ports: raise FinalGateError("AB profile endpoints and ControlLogix companion must be distinct") ab_ports.add(port) if {key for key in document if document[key] != base.get(key)} - allowed: raise FinalGateError("profile environment modifies unrelated fixture settings") result[name] = environment return result def require_ready_candidate(local): """Reject stale or unavailable P10 processes before starting final fixtures.""" import rig try: manifest = local.load() if manifest.get("state") != "ready": raise FinalGateError("P10 rig is not ready") local.verify_candidate() return manifest except rig.RigError: raise FinalGateError("P10 rig candidate is stale or unavailable; inspect restricted rig diagnostics") from None def result_artifact_hashes(directory, projects): files = [directory / name for name in ("inventory.json", "discovery.json", "execution.json", "software-optins.json", "source-identity.json", "script-worker.json", "test.command.json", "saturation-observer.json", "saturation-observer-build.command.json")] supplements = [directory / "profiles" / name for name in PROFILE_PROJECTS] + [directory / AB_DIFFERENTIAL_RUN, directory / SDK_LIFECYCLE_RUN] diagnostic = directory / "measurements" / "sdk-diagnostic.jsonl" if diagnostic.is_file(): files.append(diagnostic) files.extend(supplement / name for supplement in supplements for name in ("discovery.json", "test.command.json")) discovery_directories = [directory / "discovery" / project["assembly"] for project in projects] + supplements files.extend(discovery / name for discovery in discovery_directories for name in ("discovery.command.json", "discovery.stdout.log", "discovery.stderr.log")) files.extend(directory.rglob("*.trx")) return {str(path.relative_to(directory)): hashlib.sha256(path.read_bytes()).hexdigest() for path in sorted(files)} def final_report(directory, unavailable_path=None): projects = json.loads((directory / "inventory.json").read_text()) discovery = json.loads((directory / "discovery.json").read_text()) profile_discovery = {name: json.loads((directory / "profiles" / name / "discovery.json").read_text()) for name in PROFILE_PROJECTS} commands = json.loads((directory / "execution.json").read_text()) baseline = read_results(directory / "trx", projects) overlays = {name: read_results(directory / "profiles" / name / "trx", [p for p in projects if p["assembly"] == assembly], minimum=1) for name, assembly in PROFILE_PROJECTS.items()} differential_dir = directory / AB_DIFFERENTIAL_RUN differential_discovery = json.loads((differential_dir / "discovery.json").read_text()) differential = read_results(differential_dir / "trx", [p for p in projects if p["assembly"] == AB_CIP_ASSEMBLY], minimum=1) frozen_identity = json.loads((directory / "source-identity.json").read_text()) lifecycle_dir = directory / SDK_LIFECYCLE_RUN lifecycle_discovery = json.loads((lifecycle_dir / "discovery.json").read_text()) lifecycle = read_results(lifecycle_dir / "trx", [p for p in projects if p["assembly"] == SDK_LIFECYCLE_ASSEMBLY], minimum=1) lifecycle_receipt = sdk_lifecycle_receipt(lifecycle, lifecycle_discovery, directory / "measurements" / "sdk-diagnostic.jsonl", frozen_identity["revision"]) report = reconcile(baseline, overlays, discovery, profile_discovery, unavailable_records(unavailable_path), differential=differential, differential_discovery=differential_discovery, sdk_lifecycle_verified=lifecycle_receipt is not None) report["sdk_lifecycle_diagnostic"] = lifecycle_receipt report["sdk_lifecycle_baseline_scope"] = sum(row["disposition"] == "executed-in-isolated-diagnostic" for row in report["skip_decisions"]) == 1 report["baseline_assemblies"] = baseline["assemblies"] report["profile_assemblies"] = {name: result["assemblies"] for name, result in overlays.items()} report["discovered_by_assembly"] = {item["assembly"]: len(item["tests"]) for item in discovery} report["profile_discovered_by_assembly"] = {name: {item["assembly"]: len(item["tests"]) for item in discovered} for name, discovered in profile_discovery.items()} report["software_differential"] = {"executed": differential["executed"], "rows": differential["rows"], "target": "owned loopback ab_server ControlLogix", "latency_mode": "diagnostic", "mixed_packet_tags": AB_DIFFERENTIAL_MIX_TAGS.split(";")} report["command_exit_codes"] = commands report["command_evidence_complete"] = set(commands) == {"baseline", "baseline12000", AB_DIFFERENTIAL_RUN, SDK_LIFECYCLE_RUN, *PROFILE_PROJECTS} report["source_identity_matches"] = execution_inputs_match(frozen_identity, source_identity()) frozen = json.loads((directory / "result-artifacts.json").read_text()) report["result_artifacts_match"] = frozen == result_artifact_hashes(directory, projects) optins = json.loads((directory / "software-optins.json").read_text()) report["software_output_missing"] = [key for key, path in optins.items() if key.endswith(("_OUTPUT", "_OUT")) and (not Path(path).is_file() or not Path(path).stat().st_size)] report["script_worker_identity_matches"] = script_worker_identity_matches(directory) report["saturation_observer_identity_matches"] = saturation_observer_identity_matches(directory, frozen_identity, optins) report["saturation_observer_protocol_controls"] = saturation_observer_protocol_rows(baseline["rows"]) report["limitations"] = ["SDK diagnostic90s and the two short observer protocol controls do not establish full7200s, saturation or qualified late-slope acceptance.", "The software differential measures simulator parity and diagnostic latency; a physical controller gate is separate.", "Controller symbol instance ordering across listing pages remains a physical controller evidence requirement.", "Unavailable rows are unexecuted coverage requiring their recorded next gate; this is not an all-tests-passed claim.", "Whole-solution gate does not replace P10 scenarios, P11 workloads or independent final Astra review."] report["passed"] = (report["passed"] and report["command_evidence_complete"] and not any(commands.values()) and report["source_identity_matches"] and report["result_artifacts_match"] and not report["software_output_missing"] and report["script_worker_identity_matches"] and report["saturation_observer_identity_matches"] and report["saturation_observer_protocol_controls"]["passed"] and report["sdk_lifecycle_baseline_scope"]) return report def cleanup_preserving_failure(action, primary_failed): """Attempt teardown once; an existing test/setup failure retains precedence.""" try: action() except Exception: if not primary_failed: raise FinalGateError("owned fixture cleanup failed; inspect restricted evidence") from None return False return True def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--run-id", required=True) parser.add_argument("--inventory-only", action="store_true") parser.add_argument("--unavailable-evidence", type=Path, help="JSON list of exact assembly/test/reason/kind/requires/evidence/next_gate records") parser.add_argument("--reconcile-only", action="store_true", help="read frozen discovery/TRXs with explicit unavailable evidence; never rebuild or rerun") args = parser.parse_args(argv) import rig if not rig._RUN_PATTERN.fullmatch(args.run_id): raise FinalGateError("invalid run identity") directory = ROOT / "artifacts" / "grpc-data" / args.run_id / "final" os.umask(0o077) if args.reconcile_only: if args.inventory_only: raise FinalGateError("inventory-only cannot reconcile an existing run") report = final_report(directory, args.unavailable_evidence) report["cleanup_succeeded"] = json.loads((directory / "cleanup.json").read_text())["succeeded"] report["passed"] = report["passed"] and report["cleanup_succeeded"] path = directory / ("reconciliation-" + str(time.time_ns()) + ".json") private_json(path, report) print(json.dumps({"baseline_executed": report["baseline_executed"], "passed": report["passed"], "evidence": str(path)})) return 0 if report["passed"] else 1 directory.mkdir(parents=True, exist_ok=False, mode=0o700) projects = inventory(); private_json(directory / "inventory.json", projects) import fixture_inventory private_json(directory / "fixture-source-inventory.json", fixture_inventory.generate()) if args.inventory_only: print(str(directory / "inventory.json")); return 0 solution = ET.parse(ROOT / "ZB.MOM.WW.OtOpcUa.slnx").getroot() included = {item.get("Path", "").replace("\\", "/") for item in solution.iter("Project")} if any(p["project"] not in included for p in projects): raise FinalGateError("test project absent from final solution") if not ODBC_DRIVER.is_file(): raise FinalGateError("required local PostgreSQL ODBC driver is missing") if platform.system() == "Darwin" and not ODBC_DRIVER_MANAGER.is_file(): raise FinalGateError("required local macOS unixODBC manager is missing") # Validate any supplied decisions before starting expensive prerequisites. unavailable_records(args.unavailable_evidence) identity = source_identity(); private_json(directory / "source-identity.json", identity) local = rig.LocalRig(args.run_id); manifest = require_ready_candidate(local) env_path = directory / "fixture-environment.json" setup = {k: v for k, v in os.environ.items() if k in phase.ENV_ALLOWLIST} setup.update({"CI_FIXTURE_LOCAL_OWNED": "1", "CI_FIXTURE_SUFFIX": args.run_id + "-final", "CI_FIXTURE_ENV_JSON": str(env_path), "CI_FIXTURE_ODBC_DRIVER": str(ODBC_DRIVER), "FIXTURE_HOST": "127.0.0.1", "DOCKER_CONTEXT": local.context["Name"]}) fixture = ["bash", "scripts/ci/integration-fixtures.sh"] started = time.monotonic(); report = None; primary_failed = True try: if logged_run("fixtures-up", fixture + ["up"], directory, setup, timeout=7200): raise FinalGateError("local prerequisite setup failed") fixture_environment = json.loads(env_path.read_text()) fixture_environment["HOST_PROBE_OPCUA_ENDPOINT"] = manifest["endpoints"]["control-1.opcua"]["url"] environment = child_environment(fixture_environment) profiles = profile_environments(Path(str(env_path) + ".d") / "profile-environments.json", environment) software_differential = differential_environment(environment) optins = software_optins(directory / "measurements", identity["revision"]) environment.update({key: value for key, value in optins.items() if key != "OTOPCUA_SDK2_SOAK"}) build, test = solution_commands(directory / "trx") restore = ["dotnet", "restore", "ZB.MOM.WW.OtOpcUa.slnx", "--disable-parallel", "-m:1"] if logged_run("restore", restore, directory, environment): raise FinalGateError("final solution restore failed") if logged_run("build", build, directory, environment): raise FinalGateError("final solution build failed") worker = prepare_script_worker(directory, environment=environment, identity=identity) environment.update(worker) optins.update(worker) observer = prepare_saturation_observer(directory, environment=environment, identity=identity) environment.update(observer) private_json(directory / "software-optins.json", {**optins, **observer}) discovery = [discover_project(project, directory / "discovery" / project["assembly"], environment) for project in projects] private_json(directory / "discovery.json", discovery) if not execution_inputs_match(identity, source_identity()): raise FinalGateError("candidate execution inputs changed before the final test command") commands = {"baseline": logged_run("test", test, directory, environment)} baseline_trxs = sorted(str(path) for path in (directory / "trx").rglob("*.trx")) if not baseline_trxs: raise FinalGateError("final solution produced no TRX") commands["baseline12000"] = logged_run("baseline12000", ["bash", "scripts/ci/assert-not-all-skipped.sh", *baseline_trxs], directory, {**environment, "MIN_EXECUTED": "12000"}, timeout=600) for name, assembly in PROFILE_PROJECTS.items(): project = next(p for p in projects if p["assembly"] == assembly) commands[name] = run_profile(project, test, directory / "profiles" / name, {**profiles[name], **optins}) lifecycle_project = next(p for p in projects if p["assembly"] == SDK_LIFECYCLE_ASSEMBLY) commands[SDK_LIFECYCLE_RUN] = run_profile(lifecycle_project, test, directory / SDK_LIFECYCLE_RUN, {**environment, "OTOPCUA_SDK2_SOAK": optins["OTOPCUA_SDK2_SOAK"]}, selected={SDK_LIFECYCLE_CASE}) ab_cip_project = next(p for p in projects if p["assembly"] == AB_CIP_ASSEMBLY) commands[AB_DIFFERENTIAL_RUN] = run_profile(ab_cip_project, test, directory / AB_DIFFERENTIAL_RUN, software_differential, selected=AB_DIFFERENTIAL_CASES) private_json(directory / "execution.json", commands) private_json(directory / "result-artifacts.json", result_artifact_hashes(directory, projects)) report = final_report(directory, args.unavailable_evidence) report["duration_seconds"] = time.monotonic() - started primary_failed = not report["passed"] finally: def down(): if logged_run("fixtures-down", fixture + ["down"], directory, setup, timeout=900): raise FinalGateError("owned fixture teardown returned failure") cleanup = False try: cleanup = cleanup_preserving_failure(down, primary_failed) finally: private_json(directory / "cleanup.json", {"succeeded": cleanup}) if report is not None: report["cleanup_succeeded"] = cleanup report["passed"] = report["passed"] and cleanup private_json(directory / "results.json", report) print(json.dumps({"baseline_executed": report["baseline_executed"], "passed": report["passed"], "evidence": str(directory)})) return 0 if report["passed"] else 1 if __name__ == "__main__": try: raise SystemExit(main()) except (FinalGateError, OSError, ValueError, KeyError, StopIteration, ET.ParseError, subprocess.SubprocessError) as error: print("final gate failed: " + (str(error) if isinstance(error, FinalGateError) else "inspect restricted evidence"), file=sys.stderr) raise SystemExit(2)