314 lines
19 KiB
Python
314 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""Portable natural 13-step replay; serial state/mirror, historical T2 between steps.
|
|
|
|
No cache drop, fixed seed, prefetch, source diagnostics or online data collection.
|
|
The new consumed bundle path is service-verified separately from historical runs.
|
|
"""
|
|
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
|
|
|
|
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
|
|
from sequence_matrix import (PROFILE_FLAGS, call, resource_guard, systemd_measure, tal_arguments,
|
|
rp_command, require_ready, require_transport, payload_counts,
|
|
compare_profile_contracts, require_t2_fallback_bindings)
|
|
from replay_bundle import load_manifest, verify as verify_bundle
|
|
from serve import uri_key
|
|
|
|
PROTOCOL = "natural-serial-13-v1"
|
|
|
|
|
|
def validate_profiles(order: list[str]) -> None:
|
|
if (not order or len(order) != len(set(order)) or set(order) - set(PROFILE_FLAGS)
|
|
or (len(order) > 1 and order[0] != "baseline")):
|
|
raise ValueError("select one profile or a unique matrix with baseline first")
|
|
|
|
|
|
def require_expected_outputs(run: Path, expected: dict) -> None:
|
|
"""CCR canonical state digests plus CIR census; T2 supplies full row equivalence."""
|
|
ccr = read_json(run / "ccr-comparison.json")
|
|
cir = read_json(run / "cir-comparison.json")
|
|
states = {r["name"]: (r["verificationPresent"], r["verificationHashHex"]) for r in ccr["states"]}
|
|
if states != {k: tuple(v) for k, v in expected["ccr_states"].items()}:
|
|
raise ValueError("CCR differs from pinned canonical outputs")
|
|
if cir["rpkiClient"] != expected["cir_census"]:
|
|
raise ValueError("CIR census differs from pinned historical outputs")
|
|
if payload_counts(run) != expected["counts"]:
|
|
raise ValueError("payload counts differ from pinned outputs")
|
|
|
|
|
|
def check_requests(path: Path, epoch: dict) -> None:
|
|
expected = {uri_key(r["uri"]): r for r in epoch["http_entities"] if r["kind"] != "ta"}
|
|
actual = set()
|
|
statuses = {}
|
|
for line in path.read_text().splitlines():
|
|
event = json.loads(line)
|
|
statuses[str(event["status"])] = statuses.get(str(event["status"]), 0) + 1
|
|
if event["status"] in (200, 304):
|
|
key = uri_key(event["uri"])
|
|
if key not in expected or event["sha256"] != expected[key]["sha256"]:
|
|
raise ValueError("unexpected served entity")
|
|
actual.add(key)
|
|
elif not event.get("controlled_failure"):
|
|
raise ValueError("unexpected unserved request; consumed subset is insufficient")
|
|
if actual != set(expected) or statuses != epoch["expected_transport"]["http_response_status_counts"]:
|
|
raise ValueError("request workload differs from the pinned natural chain")
|
|
|
|
|
|
def run_natural(config: dict) -> dict:
|
|
if socket.gethostname() != config["expected_host"] or os.geteuid() != 0:
|
|
raise ValueError("natural replay requires root on the configured host")
|
|
root, scope_path, output = (Path(config[k]).resolve() for k in ("archive", "scope", "out"))
|
|
outside_archive(root, output)
|
|
bundle_path = Path(config["bundle_manifest"]).resolve()
|
|
bundle = load_manifest(bundle_path, config["expected_bundle_sha256"])
|
|
bundle_proof = verify_bundle(bundle_path.parent, bundle)
|
|
if output.is_relative_to(bundle_path.parent):
|
|
raise ValueError("outputs must be outside the immutable bundle")
|
|
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 = True
|
|
expected_outputs = read_json(Path(config["expected_outputs"]))
|
|
expected_outputs_sha256 = file_sha256(Path(config["expected_outputs"]))
|
|
order = config.get("profile_order", list(PROFILE_FLAGS))
|
|
validate_profiles(order)
|
|
first_profile = order[0]
|
|
summary = {"status": "running", "pass": False, "purpose": "natural-serial-13-step", "protocol": PROTOCOL, "bundle_verification": bundle_proof,
|
|
"performance_ready": False, "missing_formal_metrics": [] if formal else ["sync-wall-union", "payload-ready-publication"],
|
|
"expected_outputs_sha256": expected_outputs_sha256,
|
|
"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, config.get("minimum_free_gib", 150))}
|
|
atomic_json(output / "summary.json", summary)
|
|
namespaces_owned = False
|
|
try:
|
|
if subprocess.run(["systemctl", "is-active", "--quiet", "panda-rpki.service"], capture_output=True).returncode == 0:
|
|
raise ValueError("Panda must already be stopped; this runner never restarts it")
|
|
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, bundle["origin_hosts"])))
|
|
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, config.get("minimum_free_gib", 150))
|
|
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),
|
|
"--bundle-manifest", str(bundle_path), "--bundle-sha256", config["expected_bundle_sha256"]])
|
|
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 == first_profile:
|
|
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 / first_profile / 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)
|
|
if config.get("expected_outputs"):
|
|
expected = expected_outputs["steps"][step]
|
|
require_expected_outputs(run, expected)
|
|
check_requests(run / "server-requests.jsonl", bundle["epochs"][step])
|
|
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)
|
|
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):
|
|
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 interrupted(*_) -> None:
|
|
raise KeyboardInterrupt("natural replay controller interrupted")
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--config", type=Path, default=Path(__file__).parent / "configs/natural13.json")
|
|
parser.add_argument("--dataset", type=Path, required=True)
|
|
parser.add_argument("--binary-dir", type=Path, required=True)
|
|
parser.add_argument("--out", type=Path, required=True)
|
|
parser.add_argument("--profiles", nargs="+", choices=tuple(PROFILE_FLAGS))
|
|
parser.add_argument("--expected-binary-sha256", help="Explicit pin for a future candidate build")
|
|
parser.add_argument("--check-only", action="store_true", help="Hash bundle/config/tools without starting RP")
|
|
args = parser.parse_args()
|
|
config = read_json(args.config)
|
|
if config.get("protocol") != PROTOCOL or config.get("formal_metrics") is not True:
|
|
raise ValueError("config must select the standard natural protocol and all seven metrics")
|
|
config.update(archive=str(args.dataset.resolve() / "archive"), scope=str(args.dataset.resolve() / "config/scope.json"),
|
|
bundle_manifest=str(args.dataset.resolve() / "bundle-manifest.json"), out=str(args.out.resolve()))
|
|
names = {"binary": "rpki", "ccr_compare": "verification_ccr_compare", "cir_compare": "cir_state_compare", "db_stats": "db_stats"}
|
|
for name, filename in names.items():
|
|
config[name] = str(args.binary_dir.resolve() / filename)
|
|
config["expected_outputs"] = str((args.config.parent / config["expected_outputs"]).resolve())
|
|
if args.profiles:
|
|
config["profile_order"] = args.profiles
|
|
if args.expected_binary_sha256:
|
|
config["expected_binary_sha256"] = args.expected_binary_sha256
|
|
validate_profiles(config["profile_order"])
|
|
if args.check_only:
|
|
manifest = load_manifest(Path(config["bundle_manifest"]), config["expected_bundle_sha256"])
|
|
proof = verify_bundle(args.dataset, manifest)
|
|
if file_sha256(Path(config["binary"])) != config["expected_binary_sha256"]:
|
|
raise ValueError("RP binary pin mismatch")
|
|
for name in names:
|
|
proof[name + "_sha256"] = file_sha256(Path(config[name]))
|
|
require_closure(Path(config["archive"]), Path(config["scope"]))
|
|
print(json.dumps(proof))
|
|
return
|
|
signal.signal(signal.SIGTERM, interrupted)
|
|
result = run_natural(config)
|
|
print(json.dumps({"pass": result["pass"], "runs": len(result["runs"]), "protocol": PROTOCOL}))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|