#!/usr/bin/env python3 """Functional five-profile/two-step real-TA smoke; never a performance benchmark.""" from __future__ import annotations import argparse from datetime import datetime, timezone import json import os from pathlib import Path import re import signal import shutil import subprocess import time from cache_size import account, profile_from_contract from common import atomic_json, file_sha256, read_json def command_run(command: list[str], output: Path, error: Path, env: dict, timeout: int = 600) -> dict: started = time.monotonic() with output.open("wb") as out, error.open("wb") as err: child = subprocess.Popen(command, stdout=out, stderr=err, env=env, start_new_session=True) try: code = child.wait(timeout=timeout) except BaseException: if child.poll() is None: os.killpg(child.pid, signal.SIGKILL) child.wait(timeout=10) raise if code: raise RuntimeError(f"command exited {code}; see {error}") return {"command": command, "exit_code": code, "wall_secs_functional_only": time.monotonic() - started} def require_comparison(path: Path, kind: str) -> None: # cir_state_compare writes differences but intentionally exits zero. field = {"cir": "allMatch", "ccr": "stateDigestMatch"}[kind] if read_json(path).get(field) is not True: raise ValueError(f"{kind.upper()} semantic comparison failed: {path}") def snapshot_pre_state(state: Path, checkpoint: Path) -> dict: """Copy closed functional-fixture state before T1, including every sidecar.""" if checkpoint.exists(): raise ValueError("pre-step checkpoint already exists") for path in state.rglob("*"): if path.is_symlink() or not (path.is_file() or path.is_dir()): raise ValueError(f"non-regular pre-step state: {path}") shutil.copytree(state, checkpoint) files = {str(path.relative_to(checkpoint)): file_sha256(path) for path in sorted(checkpoint.rglob("*")) if path.is_file()} return {"created_unix_ns": time.time_ns(), "checkpoint_root": str(checkpoint.resolve()), "files_sha256": files, "method": "closed-functional-fixture-copy-before-T1"} def cache_counters(run: Path) -> dict: stage = read_json(run / "stage-timing.json") signature = stage.get("crypto_signature_cache_observe") # Exclude elapsed time, byte accounting and storage/index load telemetry. return {"signature": {"entries_loaded": signature["entries_loaded"], "entries_total": signature["entries_total"], "per_point": {point: {k: v for k, v in counts.items() if "nanos" not in k} for point, counts in signature["per_point"].items()}} if signature else None, "roa": {k: v for k, v in stage["roa_validation_cache"].items() if "nanos" not in k}, "tree_cache": {k: v for k, v in stage["analysis_counts"].items() if "cache" in k and not any(s in k for s in ("index", "bytes", "persist", "load", "nanos", "_ms"))}} def main(): parser = argparse.ArgumentParser(description=__doc__) for name in ("binary", "ccr-compare", "cir-compare", "db-stats-bin", "profiles", "manifest", "tal", "ta", "out"): parser.add_argument("--" + name, type=Path, required=True) parser.add_argument("--with-benchmark", action="store_true", help="also validate frozen-input T2 with a separate pre-step cache copy") parser.add_argument("--max-instances", type=int, default=1, help="bounded functional fixture scope (1..16; default 1)") args = parser.parse_args() if not 1 <= args.max_instances <= 16: raise ValueError("functional fixture scope must be between 1 and 16 instances") args.out.mkdir(parents=True) manifest = read_json(args.manifest) epoch = read_json(Path(manifest["epoch_path"])) profiles = read_json(args.profiles)["profiles"] if set(profiles) != {"baseline", "signature", "object", "pp", "hybrid"}: raise ValueError("requires exactly the confirmed five-profile matrix") env = {key: value for key, value in os.environ.items() if key.lower() not in ("http_proxy", "https_proxy", "all_proxy")} summary = {"status": "running", "pass": False, "purpose": "bounded-no-change-functional-smoke-not-performance", "max_instances": args.max_instances, "binary_sha256": file_sha256(args.binary), "manifest_sha256": file_sha256(args.manifest), "tal_sha256": file_sha256(args.tal), "ta_sha256": file_sha256(args.ta), "constraints_sha256": file_sha256(args.tal.with_suffix(".constraints")) if args.tal.with_suffix(".constraints").exists() else None, "namespace": os.readlink("/proc/self/ns/net"), "profiles": profiles, "runs": []} comparator_bins = {"ccr": str(args.ccr_compare), "cir": str(args.cir_compare), "db_stats": str(args.db_stats_bin)} summary["tool_sha256"] = {key: file_sha256(Path(path)) for key, path in comparator_bins.items()} baseline_contracts = {} try: for profile in ("baseline", "signature", "object", "pp", "hybrid"): private = args.out / profile (private / "state").mkdir(parents=True) (private / "tmp").mkdir() env["TMPDIR"] = str(private / "tmp") for step in range(2): run = private / f"step_{step:04d}" run.mkdir() logical_ms = epoch["validation_time_ms"] + step * 300_000 logical_time = datetime.fromtimestamp(logical_ms // 1000, timezone.utc).isoformat().replace("+00:00", "Z") db = private / "state/db" command = [str(args.binary), "--db", str(db), "--tal-path", str(args.tal), "--ta-path", str(args.ta), "--cir-tal-uri", f"https://capture.rpki187.invalid/tal/{summary['tal_sha256']}/{args.tal.name}", "--http-root-cert", manifest["tls"]["ca"], "--max-instances", str(args.max_instances), "--parallel-max-repo-sync-workers-global", "3", "--parallel-phase2-object-workers", "3", "--validation-time", logical_time, "--validation-contract-out", str(run / "contract.json"), "--report-json", str(run / "report.json"), "--report-json-compact", "--ccr-out", str(run / "result.ccr"), "--cir-enable", "--cir-out", str(run / "input.cir"), "--record-transport-dir", str(run / "transport"), "--rsync-mirror-root", str(private / "mirror"), "--analyze", "--analysis-out", str(run / "analysis")] + profiles[profile] atomic_json(run / "command.json", command) pre_state = "empty" if args.with_benchmark: checkpoint = private / "checkpoints" / f"step_{step:04d}" proof = snapshot_pre_state(private / "state", checkpoint) atomic_json(run / "pre-state.json", proof) if step: pre_state = str(checkpoint / "db") atomic_json(run / "t1-start.json", {"started_unix_ns": time.time_ns()}) result = command_run(command, run / "stdout.log", run / "stderr.log", env) contract = read_json(run / "contract.json") actual_profile, _ = profile_from_contract(contract) if profile != actual_profile or contract["validationTime"] != logical_time: raise ValueError("effective cache profile or logical time differs") shared = {key: value for key, value in contract.items() if key != "cache"} if profile == "baseline": baseline_contracts[step] = shared elif shared != baseline_contracts[step]: raise ValueError("non-cache validation contract differs from baseline") stderr = (run / "stderr.log").read_text(errors="replace") anchors = re.findall(r"wrote CIR: .*?trust_anchors=(\d+)", stderr) report = read_json(run / "report.json") if not anchors or int(anchors[-1]) != 1 or report["tree"]["instances_failed"] != 0 or not 1 <= len(report["publication_points"]) <= args.max_instances: raise ValueError("real-TA bounded verification failed") if args.max_instances > 1 and not (report["vrps"] or report["aspas"] or report.get("router_keys")): raise ValueError("extended functional fixture has no accepted payload") baseline = args.out / "baseline" / f"step_{step:04d}" comparisons = [ [str(args.ccr_compare), "--source-ccr", str(baseline / "result.ccr"), "--verification-ccr", str(run / "result.ccr"), "--out-json", str(run / "ccr-comparison.json")], [str(args.cir_compare), "--ours-cir", str(baseline / "input.cir"), "--peer-cir", str(run / "input.cir"), "--out-json", str(run / "cir-comparison.json")], ] for kind, comparison in zip(("ccr", "cir"), comparisons): command_run(comparison, run / (kind + "-compare.stdout"), run / (kind + "-compare.stderr"), env) require_comparison(run / (kind + "-comparison.json"), kind) command_run([str(args.db_stats_bin), "--db", str(db), "--exact"], run / "db-stats.txt", run / "db-stats.stderr", env) size = account(db, run / "db-stats.txt", run / "contract.json") atomic_json(run / "cache-size.json", size) result.update(profile=profile, step=step, path=str(run), validation_time=logical_time, cache_size_bytes=size["required_serialized_bytes"], comparisons_pass=True) if args.with_benchmark: benchmark = private / f"benchmark_{step:04d}" benchmark_command = [str(args.binary), "--validation-benchmark", "--source-run", str(run), "--source-state", str(db), "--pre-state", pre_state, "--out", str(benchmark)] command_run(benchmark_command, run / "benchmark.stdout", run / "benchmark.stderr", env) if read_json(benchmark / "equivalence.json")["pass"] is not True: raise ValueError("T2 input/payload comparison failed") overlay = read_json(benchmark / "input-overlay.json")["overlay"] if overlay["cache_before"] != overlay["cache_after"]: raise ValueError("raw input overlay changed pre-step validation caches") if overlay.get("background_io_drained") is not True: raise ValueError("input staging background I/O was not drained before measurement") counters = {"t1": cache_counters(run), "t2": cache_counters(benchmark)} atomic_json(run / "benchmark-cache-counters.json", counters) if counters["t1"] != counters["t2"]: raise ValueError("T2 cache hit/miss behavior differs from T1") result["benchmark_functional_pass"] = True summary["runs"].append(result) atomic_json(args.out / "summary.json", summary) summary.update({"status": "completed", "pass": True}) except Exception as exc: summary.update(status="failed", error=f"{type(exc).__name__}: {exc}") raise finally: atomic_json(args.out / "summary.json", summary) print(json.dumps({"pass": summary["pass"], "runs": len(summary["runs"]), "purpose": summary["purpose"]})) if __name__ == "__main__": main()