Files
rpki/scripts/experiments/reuse_eval/sequence_matrix.py

450 lines
27 KiB
Python

#!/usr/bin/env python3
"""Full five-profile, thirteen-epoch correctness pilot on the dedicated 186 host.
This is a pilot controller. Missing sync-union/payload-ready instrumentation
explicitly prevents publishing a seven-metric performance result.
"""
from __future__ import annotations
import argparse
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import re
import shutil
import signal
import socket
import subprocess
import sys
import time
import uuid
from cache_size import account, profile_from_contract
from common import atomic_json, file_sha256, read_json
from prepare_replay import all_hosts, create_network, host_mapping
from scope import COUNTS, outside_archive, require_closure
from smoke_matrix import cache_counters, command_run, require_comparison, snapshot_pre_state
PROFILE_FLAGS = {
"baseline": [], "signature": ["--enable-crypto-signature-cache"],
"object": ["--enable-roa-validation-cache", "--enable-child-certificate-validation-cache"],
"pp": ["--enable-publication-point-validation-cache"],
"hybrid": ["--enable-roa-validation-cache", "--enable-child-certificate-validation-cache",
"--enable-publication-point-validation-cache"],
}
EXPECTED_HOST = "iZrj9bs1xzk2i95si3ghnlZ"
def compare_profile_contracts(actual: dict, baseline: dict) -> dict:
"""Compare policy/time/build and fallback choices across independent caches.
Fallback hashes bind a strategy's own VCIR history, including its last fresh
validation time. They must match that strategy's T2 exactly; they are not
shared configuration. CIR/reject/CCR comparisons still gate every row.
"""
def selections(contract: dict) -> list[dict]:
rows = contract.get("fallbackReplaySelections", [])
if not isinstance(rows, list):
raise ValueError("fallback bindings must be a list")
uris = []
for row in rows:
if (not isinstance(row, dict)
or set(row) != {"manifestRsyncUri", "vcirSha256", "reuseIdentitySha256"}
or not isinstance(row["manifestRsyncUri"], str)
or not row["manifestRsyncUri"].startswith("rsync://")
or any(not isinstance(row[k], str) or re.fullmatch(r"[0-9a-f]{64}", row[k]) is None
for k in ("vcirSha256", "reuseIdentitySha256"))):
raise ValueError("invalid fallback cache binding")
uris.append(row["manifestRsyncUri"])
if uris != sorted(set(uris)):
raise ValueError("fallback bindings must be sorted and unique")
return rows
left, right = selections(baseline), selections(actual)
shared = lambda contract: {k: v for k, v in contract.items()
if k not in ("cache", "fallbackReplaySelections")}
if shared(actual) != shared(baseline):
raise ValueError("non-cache validation configuration differs from baseline")
if [r["manifestRsyncUri"] for r in left] != [r["manifestRsyncUri"] for r in right]:
raise ValueError("fallback Manifest selections differ from baseline")
return {"schema": "rpki-reuse-cross-profile-contract-v1", "pass": True,
"configuration_match": True, "fallback_manifests_match": True,
"baseline_fallback": left, "actual_fallback": right,
"binding_scope": "exact VCIR/identity hashes within each strategy T1/T2"}
def require_t2_fallback_bindings(contract: dict, equivalence: dict) -> None:
expected = contract.get("fallbackReplaySelections", [])
fallback = equivalence.get("fallback", {})
if (fallback.get("matches") is not True or fallback.get("expected") != expected
or fallback.get("actual") != expected or fallback.get("missing") != []
or fallback.get("unexpected") != []):
raise ValueError("T1/T2 exact fallback cache bindings differ")
def call(command: list[str], **kwargs) -> subprocess.CompletedProcess:
return subprocess.run(command, check=True, capture_output=True, text=True, timeout=kwargs.pop("timeout", 30), **kwargs)
def resource_guard(output: Path) -> dict:
free = shutil.disk_usage(output).free
inodes = os.statvfs("/").f_favail
if free < 150 * 1024**3 or inodes < 10_000:
raise ValueError(f"resource guard: data free={free}, root inodes free={inodes}")
return {"data_free_bytes": free, "root_free_inodes": inodes}
def systemd_measure(command: list[str], run: Path, env: dict, timeout: int) -> dict:
"""Keep the completed cgroup alive until CPUUsageNSec/MemoryPeak are read."""
unit = "rpki187-pilot-" + uuid.uuid4().hex
env_args = ["/usr/bin/env"]
for name in ("http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"):
env_args += ["-u", name]
env_args += ["TMPDIR=" + env["TMPDIR"], "LC_ALL=C"]
launcher = ["systemd-run", "--quiet", "--unit", unit, "--service-type=exec",
"-p", "RemainAfterExit=yes", "-p", "MemoryAccounting=yes", "-p", "CPUAccounting=yes",
"-p", "AllowedCPUs=1-3", "-p", "MemoryMax=5G", "-p", f"RuntimeMaxSec={timeout}",
"-p", "StandardOutput=file:" + str(run / "stdout.log"),
"-p", "StandardError=file:" + str(run / "stderr.log"),
"ip", "netns", "exec", "rp187rp"] + env_args + [
"/usr/bin/time", "-v", "-o", str(run / "process-time.txt")] + command
atomic_json(run / "launcher.json", launcher)
began = time.monotonic_ns()
props = {}
try:
call(launcher)
deadline = time.monotonic() + timeout
while True:
raw = call(["systemctl", "show", unit, "-p", "ActiveState", "-p", "SubState", "-p", "Result",
"-p", "ExecMainStatus", "-p", "ExecMainCode", "-p", "ExecMainExitTimestampMonotonic",
"-p", "CPUUsageNSec", "-p", "MemoryPeak", "-p", "ControlGroup"]).stdout
props = dict(line.split("=", 1) for line in raw.splitlines() if "=" in line)
if props.get("ActiveState") in ("failed", "inactive") or props.get("SubState") == "exited":
break
if time.monotonic() >= deadline:
raise TimeoutError(f"RP unit timed out: {unit}")
time.sleep(0.25)
if (props.get("Result") != "success" or props.get("ExecMainCode") != "1"
or props.get("ExecMainStatus") != "0" or props.get("SubState") != "exited"):
raise RuntimeError(f"RP unit failed: {props}")
cpu, memory = int(props["CPUUsageNSec"]), int(props["MemoryPeak"])
if cpu < 0 or memory <= 0 or cpu >= 2**63 or memory >= 2**63:
raise ValueError("cgroup accounting is unavailable")
result = {"unit": unit, "properties": props, "cpu_ns": cpu, "memory_peak_bytes": memory,
"controller_observed_wall_ns": time.monotonic_ns() - began,
"controller_trigger_monotonic_ns": began,
"boundary": "entire RP cgroup including subprocesses; excludes replay server; wall includes unit launch/poll"}
atomic_json(run / "process-resource.json", result)
return result
finally:
atomic_json(run / "systemd-final.json", props)
subprocess.run(["systemctl", "stop", unit], capture_output=True, timeout=30, check=True)
def tal_arguments(root: Path, contract: dict, epoch: dict, run: Path) -> list[str]:
result, selected = [], set()
archive_blobs = root / "blobs/sha256"
for tal in contract["tals"]:
path = root / "inputs" / Path(tal["path"]).name
if file_sha256(path) != tal["sha256"]:
raise ValueError("pinned TAL changed")
uris = [line.strip() for line in path.read_text().splitlines() if line.strip().startswith(("https://", "rsync://"))]
matches = [uri for uri in uris if uri in epoch["ta_object_events"]]
if len(matches) != 1 or matches[0] in selected:
raise ValueError("TAL must bind exactly one distinct archived TA endpoint")
uri = matches[0]
selected.add(uri)
event = read_json(root / "events" / f"{epoch['ta_object_events'][uri]}.json")
if (event["uri"] != uri or event["complete"] is not True or event["transport"] != "http"
or event["completed_ms"] > epoch["validation_time_ms"]):
raise ValueError("TA event binding failed")
ref = event["body"]
source = archive_blobs / ref["sha256"][:2] / ref["sha256"]
if source.stat().st_size != ref["size"] or file_sha256(source) != ref["sha256"]:
raise ValueError("TA bytes changed")
target = run / "ta" / path.with_suffix(".cer").name
target.parent.mkdir(exist_ok=True)
shutil.copyfile(source, target)
result += ["--tal-path", str(path), "--ta-path", str(target), "--cir-tal-uri", tal["cir_tal_uri"]]
if selected != set(epoch["ta_object_events"]):
raise ValueError("not every real TA is consumed")
return result
def rp_command(binary: Path, private: Path, run: Path, manifest: dict, logical_ms: int,
profile: str, tals: list[str], formal_metrics: bool = False) -> list[str]:
logical = datetime.fromtimestamp(logical_ms // 1000, timezone.utc).isoformat().replace("+00:00", "Z")
return [str(binary), "--db", str(private / "state/db"), *tals, "--http-root-cert", manifest["tls"]["ca"],
"--parallel-max-repo-sync-workers-global", "3", "--parallel-phase2-object-workers", "3",
"--rsync-scope", "module-root", "--max-ca-depth", "32", "--http-timeout-secs", "30", "--rsync-timeout-secs", "30",
"--validation-time", logical, "--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"), "--rsync-mirror-root", str(private / "mirror"),
"--analyze", "--analysis-out", str(run / "analysis"), *PROFILE_FLAGS[profile]] + (
["--evaluation-metrics-out", str(run / "evaluation.json")] if formal_metrics else [])
def require_ready(path: Path, server: subprocess.Popen, epoch_hash: str, scope_hash: str) -> dict:
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
if server.poll() is not None:
raise RuntimeError("replay server exited before readiness")
if path.exists():
ready = read_json(path)
if ready.get("epoch") != epoch_hash or ready.get("scope") != scope_hash:
raise ValueError("server readiness belongs to a different epoch/scope")
return ready
time.sleep(0.1)
raise TimeoutError("replay server readiness timeout")
def require_transport(table: dict, scope: dict, epoch_name: str) -> None:
routes = scope["routes"].get(epoch_name, {})
if set(table["rrdp"]) != set(scope["included_repositories"]) | set(scope["excluded_repositories"]):
raise ValueError("native RP transport set differs from the declared repository scope")
for uri in scope["included_repositories"]:
outcome = table["rrdp"][uri]
if uri in routes:
if not isinstance(outcome, dict) or "Failure" not in outcome:
raise ValueError("native RP did not reproduce the declared RRDP failure")
if table["rsync"].get(routes[uri]["rsync_uri"]) != "Success":
raise ValueError("native RP did not use the bound successful rsync view")
elif outcome != "Success":
raise ValueError(f"an included RRDP repository failed: {uri}")
for uri in scope["excluded_repositories"]:
if not isinstance(table["rrdp"][uri], dict) or "Failure" not in table["rrdp"][uri]:
raise ValueError("an excluded repository unexpectedly succeeded")
def payload_counts(run: Path) -> dict:
# Reading the complete ~300 MB JSON report into Python can consume gigabytes.
# The native comparator/T2 read the canonical artifacts independently.
stdout = (run / "stdout.log").read_text(errors="replace")
pairs = re.findall(r"^(vrps|aspas|audit_publication_points)=(\d+)$", stdout, re.MULTILINE)
values = {key: int(value) for key, value in pairs}
if len(pairs) != 3 or set(values) != {"vrps", "aspas", "audit_publication_points"} or min(values.values()) <= 0:
raise ValueError("full-scope payload counters are missing, duplicated or empty")
return {"vrps": values["vrps"], "aspas": values["aspas"], "publication_points": values["audit_publication_points"]}
def run_pilot(config: dict) -> dict:
if socket.gethostname() != EXPECTED_HOST or os.geteuid() != 0:
raise ValueError("pilot execution is restricted to root on the designated 186 host")
root, scope_path, output = (Path(config[k]).resolve() for k in ("archive", "scope", "out"))
outside_archive(root, output)
if not str(output).startswith("/data/rpki187/20261109/results/"):
raise ValueError("pilot outputs must be in the dedicated persistent experiment root")
output.mkdir(parents=True, exist_ok=False)
scope = require_closure(root, scope_path)
if scope["counts"] != COUNTS:
raise ValueError("pilot requires the user-approved 109/8/13/5 scope")
if file_sha256(scope_path) != config["expected_scope_sha256"]:
raise ValueError("scope differs from the reviewed local metadata selection")
source_tools = {name: Path(config[name]).resolve() for name in ("binary", "ccr_compare", "cir_compare", "db_stats")}
if file_sha256(source_tools["binary"]) != config["expected_binary_sha256"]:
raise ValueError("RP binary differs from the reviewed frozen build")
(output / "bin").mkdir()
tools = {}
for name, source in source_tools.items():
target = output / "bin" / name
shutil.copyfile(source, target)
if file_sha256(target) != file_sha256(source):
raise ValueError("copied measurement tool changed")
target.chmod(0o555)
tools[name] = target
env = {k: v for k, v in os.environ.items() if k.lower() not in ("http_proxy", "https_proxy", "all_proxy")}
script = Path(__file__).resolve().parent
formal = config.get("formal_metrics", False)
if type(formal) is not bool:
raise ValueError("formal_metrics must be boolean")
order = config.get("profile_order", list(PROFILE_FLAGS))
if len(order) != 5 or set(order) != set(PROFILE_FLAGS) or order[0] != "baseline":
raise ValueError("profile order must cover all five profiles once with baseline first")
summary = {"status": "running", "pass": False, "purpose": "full-109-repository-all5-formal-repeat" if formal else "full-109-repository-all5-correctness-pilot",
"performance_ready": False, "missing_formal_metrics": [] if formal else ["sync-wall-union", "payload-ready-publication"],
"scope_sha256": file_sha256(scope_path), "tool_sha256": {k: file_sha256(p) for k, p in tools.items()},
"scripts_sha256": {p.name: file_sha256(p) for p in sorted(script.glob("*.py"))},
"config": config, "runs": [], "initial_resources": resource_guard(output)}
atomic_json(output / "summary.json", summary)
panda_was_active = subprocess.run(["systemctl", "is-active", "--quiet", "panda-rpki.service"]).returncode == 0
namespaces_owned = False
panda_stopped = False
try:
if panda_was_active:
# Mark before requesting stop: a timed-out client may leave a completed stop job.
panda_stopped = True
call(["systemctl", "stop", "panda-rpki.service"], timeout=120)
container = call(["docker", "inspect", "--format", "{{.State.Running}}", "panda-rpki-validator-1"]).stdout.strip()
if container != "false":
raise ValueError("original Panda container is still running")
competitors = subprocess.run(["pgrep", "-x", "rpki|rpki-client|routinator"], capture_output=True, text=True)
if competitors.returncode == 0:
raise ValueError("competing RP processes are present")
create_network(host_mapping(all_hosts(root)))
namespaces_owned = True
contract = read_json(root / "contract.json")
baseline_contracts = {}
for profile in order:
private = output / profile
(private / "state").mkdir(parents=True)
(private / "tmp").mkdir()
env["TMPDIR"] = str(private / "tmp")
for step, selection in enumerate(scope["epochs"]):
resources = resource_guard(output)
if ({k: file_sha256(p) for k, p in tools.items()} != summary["tool_sha256"]
or {p.name: file_sha256(p) for p in sorted(script.glob("*.py"))} != summary["scripts_sha256"]):
raise ValueError("tools or controller source changed during the pilot")
epoch_path = root / selection["path"]
epoch = read_json(epoch_path)
run = private / f"step_{step:04d}"
run.mkdir()
assets = output / "assets"
epoch_assets = assets / selection["sha256"]
manifest_path = epoch_assets / "replay.json"
if not manifest_path.exists():
prepared = call([sys.executable, str(script / "prepare_replay.py"), "--archive", str(root),
"--scope", str(scope_path), "--epoch", str(epoch_path), "--out", str(assets)])
atomic_json(run / "prepare-command.json", {"stdout": prepared.stdout})
manifest = read_json(manifest_path)
if manifest["epoch"] != selection["sha256"] or manifest["scope_sha256"] != summary["scope_sha256"]:
raise ValueError("prepared replay manifest changed")
ready = run / "server-ready.json"
server_command = ["ip", "netns", "exec", "rp187srv", "taskset", "-c", "0", sys.executable,
str(script / "run_server.py"), "--manifest", str(manifest_path), "--log",
str(run / "server-requests.jsonl"), "--ready", str(ready)]
atomic_json(run / "server-command.json", server_command)
with (run / "server.log").open("wb") as log:
server = subprocess.Popen(server_command, stdout=log, stderr=log, start_new_session=True, env=env)
try:
ready_proof = require_ready(ready, server, selection["sha256"], summary["scope_sha256"])
atomic_json(run / "server-ready-proof.json", ready_proof)
proof = snapshot_pre_state(private / "state", run / "pre-state")
proof["method"] = "closed-complete-state-copy-before-T1"
atomic_json(run / "pre-state.json", proof)
command = rp_command(tools["binary"], private, run, manifest, epoch["validation_time_ms"],
profile, tal_arguments(root, contract, epoch, run), formal_metrics=formal)
atomic_json(run / "command.json", command)
atomic_json(run / "t1-start.json", {"started_unix_ns": time.time_ns()})
measured = systemd_measure(command, run, env, config.get("run_timeout_secs", 1800))
if server.poll() is not None:
raise RuntimeError("replay server exited during T1")
finally:
if server.poll() is None:
os.killpg(server.pid, signal.SIGTERM)
try:
server.wait(timeout=20)
except subprocess.TimeoutExpired:
os.killpg(server.pid, signal.SIGKILL)
server.wait(timeout=10)
actual = read_json(run / "contract.json")
logical = datetime.fromtimestamp(epoch["validation_time_ms"] // 1000, timezone.utc).isoformat().replace("+00:00", "Z")
if (profile_from_contract(actual)[0] != profile or actual["validationTime"] != logical
or actual["binarySha256"] != summary["tool_sha256"]["binary"]):
raise ValueError("effective profile, time or binary mismatch")
if profile == "baseline":
baseline_contracts[step] = actual
atomic_json(run / "contract-comparison.json",
compare_profile_contracts(actual, baseline_contracts[step]))
anchors = re.findall(r"wrote CIR: .*?trust_anchors=(\d+)", (run / "stderr.log").read_text(errors="replace"))
if not anchors or int(anchors[-1]) != 5:
raise ValueError("full five-TA/payload acceptance failed")
counts = payload_counts(run)
baseline = output / "baseline" / run.name
for kind, command in (
("ccr", [str(tools["ccr_compare"]), "--source-ccr", str(baseline / "result.ccr"),
"--verification-ccr", str(run / "result.ccr"), "--out-json", str(run / "ccr-comparison.json")]),
("cir", [str(tools["cir_compare"]), "--ours-cir", str(baseline / "input.cir"),
"--peer-cir", str(run / "input.cir"), "--out-json", str(run / "cir-comparison.json")])):
command_run(command, run / f"{kind}-compare.stdout", run / f"{kind}-compare.stderr", env, 1800)
require_comparison(run / f"{kind}-comparison.json", kind)
command_run([str(tools["db_stats"]), "--db", str(private / "state/db"), "--exact"],
run / "db-stats.txt", run / "db-stats.stderr", env, 1800)
size = account(private / "state/db", run / "db-stats.txt", run / "contract.json")
atomic_json(run / "cache-size.json", size)
benchmark = private / f"benchmark_{step:04d}"
benchmark_command = [str(tools["binary"]), "--validation-benchmark", "--source-run", str(run),
"--source-state", str(private / "state/db"), "--pre-state",
"empty" if step == 0 else str(run / "pre-state/db"), "--out", str(benchmark)]
atomic_json(run / "benchmark-command.json", benchmark_command)
benchmark_process = run / "benchmark-process"
benchmark_process.mkdir()
benchmark_measured = systemd_measure(benchmark_command, benchmark_process, env, config.get("run_timeout_secs", 1800))
equivalence = read_json(benchmark / "equivalence.json")
require_t2_fallback_bindings(actual, equivalence)
overlay = read_json(benchmark / "input-overlay.json")
if (equivalence.get("pass") is not True or overlay.get("pre_state_files_verified") is not True
or overlay["overlay"].get("background_io_drained") is not True
or overlay["overlay"]["cache_before"] != overlay["overlay"]["cache_after"]):
raise ValueError("T2 equivalence, pre-state or input-drain proof failed")
require_transport(overlay["transport_table"], scope, epoch_path.name)
counters = {"t1": cache_counters(run), "t2": cache_counters(benchmark)}
atomic_json(run / "cache-counters.json", counters)
if counters["t1"] != counters["t2"]:
raise ValueError("T1/T2 hit/miss behavior differs")
metrics = None
if formal:
from formal_metrics import collect
metrics = collect(run, benchmark, measured, size, profile, overlay["transport_table"])
summary["runs"].append({"profile": profile, "step": step, "path": str(run), "pass": True,
"counts": counts, "resources_before": resources, "process": measured,
"benchmark_process": benchmark_measured,
"engine": read_json(benchmark / "engine-timing.json"),
"cache_size_bytes": size["required_serialized_bytes"], "seven_metrics": metrics})
atomic_json(output / "summary.json", summary)
# These two controller-created scratch DBs are reproducible; keep all proof files,
# authoritative T1 state, original captures and complete T1 outputs.
shutil.rmtree(run / "pre-state")
shutil.rmtree(benchmark / "state")
summary.update({"status": "completed", "pass": True, "performance_ready": formal})
except BaseException as exc:
summary.update(status="failed", error=f"{type(exc).__name__}: {exc}")
raise
finally:
restoration = {}
if namespaces_owned:
for name in ("rp187rp", "rp187srv"):
try:
restoration[name] = subprocess.run(["ip", "netns", "delete", name], capture_output=True, timeout=30).returncode
except Exception as exc:
restoration[name] = str(exc)
try:
shutil.rmtree("/etc/netns/rp187rp")
except Exception as exc:
restoration["namespace_hosts_error"] = str(exc)
if panda_stopped:
try:
restored = subprocess.run(["systemctl", "start", "panda-rpki.service"], capture_output=True, timeout=60)
restoration["panda_start_exit"] = restored.returncode
restoration["panda_active"] = subprocess.run(["systemctl", "is-active", "--quiet", "panda-rpki.service"], timeout=15).returncode == 0
container = subprocess.run(["docker", "inspect", "--format", "{{.State.Running}}", "panda-rpki-validator-1"],
capture_output=True, text=True, timeout=15)
restoration["panda_container_running"] = container.returncode == 0 and container.stdout.strip() == "true"
except Exception as exc:
restoration["panda_restore_error"] = str(exc)
summary["restoration"] = restoration
atomic_json(output / "summary.json", summary)
if (any(restoration.get(name, 0) != 0 for name in ("rp187rp", "rp187srv"))
or "namespace_hosts_error" in restoration or "panda_restore_error" in restoration
or (panda_stopped and (restoration.get("panda_active") is not True
or restoration.get("panda_container_running") is not True))):
summary.update({"pass": False, "status": "restoration_failed"})
atomic_json(output / "summary.json", summary)
raise RuntimeError("pilot restoration requires attention; see summary.json")
return summary
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", type=Path, required=True)
args = parser.parse_args()
def interrupted(*_):
raise KeyboardInterrupt("pilot controller interrupted")
signal.signal(signal.SIGTERM, interrupted)
result = run_pilot(read_json(args.config))
print(json.dumps({"pass": result["pass"], "runs": len(result["runs"]), "performance_ready": result["performance_ready"]}))
if __name__ == "__main__":
main()