20261112 完成#187真实序列录制回放与七指标评估
This commit is contained in:
166
scripts/experiments/reuse_eval/scope.py
Normal file
166
scripts/experiments/reuse_eval/scope.py
Normal file
@@ -0,0 +1,166 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Declare a fixed successful-repository scope without rewriting the capture."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
from common import atomic_json, file_sha256, read_json
|
||||
|
||||
SCHEMA = "rpki-replay-scope-v1"
|
||||
COUNTS = {"repositories": 109, "excluded": 8, "epochs": 13, "trust_anchors": 5, "step_ms": 300_000}
|
||||
TAL_NAMES = {"afrinic.tal", "apnic.tal", "arin.tal", "lacnic.tal", "ripe.tal"}
|
||||
|
||||
|
||||
def outside_archive(root: Path, target: Path) -> None:
|
||||
if target.absolute().is_relative_to(root.absolute()) or target.resolve().is_relative_to(root.resolve()):
|
||||
raise ValueError("scope and scoped reports must be outside the immutable archive")
|
||||
|
||||
|
||||
def describe(root: Path, routes: dict, counts: dict | None = None) -> dict:
|
||||
"""Check metadata eligibility; this deliberately does not claim blob closure."""
|
||||
counts = dict(COUNTS if counts is None else counts)
|
||||
if set(counts) != set(COUNTS) or any(type(n) is not int or n <= 0 for n in counts.values()):
|
||||
raise ValueError("invalid scope counts")
|
||||
contract = read_json(root / "contract.json")
|
||||
capture = read_json(root / "capture.json")
|
||||
registry = read_json(root / "registry.json")
|
||||
closure = read_json(root / "closure-report.json")
|
||||
if closure.get("errors") != []:
|
||||
raise ValueError("original closure has errors beyond declared coverage gaps")
|
||||
if len(contract["tals"]) != counts["trust_anchors"]:
|
||||
raise ValueError("all original trust anchors must remain in scope")
|
||||
if counts["trust_anchors"] == 5 and {Path(t["path"]).name for t in contract["tals"]} != TAL_NAMES:
|
||||
raise ValueError("requires the five genuine TAL identities")
|
||||
sources = {name: file_sha256(root / name) for name in
|
||||
("contract.json", "capture.json", "registry.json", "closure-report.json")}
|
||||
paths = sorted((root / "epochs").glob("epoch_*.json"))
|
||||
expected_names = [f"epoch_{i:04d}.json" for i in range(counts["epochs"])]
|
||||
if [p.name for p in paths] != expected_names:
|
||||
raise ValueError("missing, extra or noncontiguous epochs")
|
||||
closure_epochs = {e["epoch"]: e for e in closure["epochs"]}
|
||||
if len(closure_epochs) != counts["epochs"] or len(closure["epochs"]) != counts["epochs"]:
|
||||
raise ValueError("original closure epoch set mismatch")
|
||||
if set(routes) - set(expected_names):
|
||||
raise ValueError("route targets an unknown epoch")
|
||||
included, excluded, epochs, ta_uris = None, None, [], None
|
||||
contract_hash = sources["contract.json"]
|
||||
for index, path in enumerate(paths):
|
||||
epoch = read_json(path)
|
||||
present, missing = set(epoch["repositories"]), set(epoch["missing"])
|
||||
if (len(present) != counts["repositories"] or len(missing) != counts["excluded"]
|
||||
or len(missing) != len(epoch["missing"]) or present & missing):
|
||||
raise ValueError("scope repository/exclusion counts mismatch")
|
||||
if present | missing != set(registry):
|
||||
raise ValueError("scope must account for every discovered repository")
|
||||
if included is None:
|
||||
included, excluded = present, missing
|
||||
if present != included or missing != excluded:
|
||||
raise ValueError("repository scope drifts between epochs")
|
||||
if epoch["complete"] is not False or epoch["contract_sha256"] != contract_hash:
|
||||
raise ValueError("original incomplete epoch/contract binding changed")
|
||||
if epoch.get("blocked_latest_attempts"):
|
||||
raise ValueError("a selected repository has a blocked latest attempt")
|
||||
for uri, binding in epoch["repositories"].items():
|
||||
latest = epoch["latest_attempts"].get(uri)
|
||||
if (not latest or latest["complete"] is not True or latest["id"] != binding["id"]
|
||||
or latest["completed_ms"] != binding["completed_ms"]
|
||||
or binding["completed_ms"] > epoch["validation_time_ms"]):
|
||||
raise ValueError("incomplete, stale or future selected observation")
|
||||
for uri in missing:
|
||||
if epoch["latest_attempts"].get(uri, {}).get("complete") is not False:
|
||||
raise ValueError("excluded repository is not a recorded failure")
|
||||
current_tas = set(epoch["ta_object_events"])
|
||||
if len(current_tas) != counts["trust_anchors"] or (ta_uris is not None and current_tas != ta_uris):
|
||||
raise ValueError("trust-anchor event set changed or was reduced")
|
||||
ta_uris = current_tas
|
||||
logical_ms = capture["t0_ms"] + index * counts["step_ms"]
|
||||
if epoch["validation_time_ms"] != logical_ms:
|
||||
raise ValueError("logical epoch time mismatch")
|
||||
original_report = closure_epochs[path.name]
|
||||
if (original_report.get("errors") != [f"missing repositories: {epoch['missing']}"]
|
||||
or original_report.get("pass") is not False
|
||||
or original_report.get("repositories") != counts["repositories"]):
|
||||
raise ValueError("original closure has unapproved epoch errors")
|
||||
epoch_routes = routes.get(path.name, {})
|
||||
for uri, route in epoch_routes.items():
|
||||
if uri not in present or set(route) != {"rsync_uri", "event_id", "http_status"} or route["http_status"] != 503:
|
||||
raise ValueError("invalid controlled RRDP failure route")
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]+", route["event_id"]):
|
||||
raise ValueError("unsafe event identifier")
|
||||
if epoch["rsync_view_events"].get(route["rsync_uri"]) != route["event_id"]:
|
||||
raise ValueError("route is not bound to this epoch's native rsync view")
|
||||
relative = f"events/{route['event_id']}.json"
|
||||
event = read_json(root / relative)
|
||||
if (event["id"] != route["event_id"] or event["uri"] != route["rsync_uri"]
|
||||
or event.get("source") != "rpki" or event.get("transport") != "rsync"
|
||||
or event.get("kind") != "view" or event.get("complete") is not True
|
||||
or event["completed_ms"] > logical_ms
|
||||
or event["started_ms"] > event["completed_ms"]
|
||||
or event["completed_ms"] <= logical_ms - counts["step_ms"]):
|
||||
raise ValueError("route event is incomplete, foreign or outside this step")
|
||||
sources[relative] = file_sha256(root / relative)
|
||||
if set(epoch["rsync_view_events"].values()) != {r["event_id"] for r in epoch_routes.values()}:
|
||||
raise ValueError("every native rsync view requires an explicit route binding")
|
||||
relative = f"epochs/{path.name}"
|
||||
sources[relative] = file_sha256(path)
|
||||
epochs.append({"path": relative, "sha256": sources[relative], "validation_time_ms": logical_ms})
|
||||
if capture["end_ms"] != epochs[-1]["validation_time_ms"]:
|
||||
raise ValueError("capture end does not match the complete target sequence")
|
||||
return {"schema": SCHEMA, "counts": counts, "source_sha256": sources, "epochs": epochs,
|
||||
"included_repositories": sorted(included), "excluded_repositories": sorted(excluded),
|
||||
"trust_anchor_uris": sorted(ta_uris), "routes": routes,
|
||||
"authorization": "user approved the 109 successful repositories on 2026-11-09",
|
||||
"coverage": "fixed observed successful repositories; eight gaps remain; not global RPKI coverage",
|
||||
"failure_policy": "excluded-notifications=503; unknown-entities=404; no upstream; rsync only recorded views",
|
||||
"route_timing": "controlled immediate RRDP failure; original Internet failure latency is not replayed"}
|
||||
|
||||
|
||||
def load_scope(root: Path, scope_path: Path) -> dict:
|
||||
outside_archive(root, scope_path)
|
||||
scope = read_json(scope_path)
|
||||
if scope.get("schema") != SCHEMA:
|
||||
raise ValueError("unsupported replay scope schema")
|
||||
expected = describe(root, scope["routes"], scope["counts"])
|
||||
if scope != expected:
|
||||
raise ValueError("scope provenance or membership mismatch")
|
||||
return scope
|
||||
|
||||
|
||||
def select_epoch(root: Path, scope_path: Path, epoch_path: Path) -> dict:
|
||||
scope = load_scope(root, scope_path)
|
||||
relative = str(epoch_path.resolve().relative_to(root.resolve()))
|
||||
if relative not in {e["path"] for e in scope["epochs"]}:
|
||||
raise ValueError("epoch not selected by this scope")
|
||||
return scope
|
||||
|
||||
|
||||
def require_closure(root: Path, scope_path: Path) -> dict:
|
||||
scope = load_scope(root, scope_path)
|
||||
report = read_json(scope_path.with_name("scoped-closure-report.json"))
|
||||
if (report.get("pass") is not True or report.get("scope_sha256") != file_sha256(scope_path)
|
||||
or report.get("source_contract_sha256") != scope["source_sha256"]["contract.json"]
|
||||
or report.get("errors") != []
|
||||
or [e.get("epoch") for e in report.get("epochs", [])] != [Path(e["path"]).name for e in scope["epochs"]]
|
||||
or any(e.get("pass") is not True or e.get("errors") != []
|
||||
or e.get("repositories") != scope["counts"]["repositories"] for e in report["epochs"])):
|
||||
raise ValueError("scoped blob/transition closure is missing, failed or belongs to another scope")
|
||||
return scope
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--archive", type=Path, required=True)
|
||||
parser.add_argument("--routes", type=Path, required=True)
|
||||
parser.add_argument("--out", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
outside_archive(args.archive, args.out)
|
||||
if args.out.exists():
|
||||
raise ValueError("scope exists; refusing to replace its provenance")
|
||||
atomic_json(args.out, describe(args.archive, read_json(args.routes)))
|
||||
print("Scope metadata eligible: 109 repositories, 8 excluded, 13 epochs, 5 TAs; run scoped verify next.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user