20261112 完成#187真实序列录制回放与七指标评估
This commit is contained in:
140
scripts/experiments/reuse_eval/formal_metrics.py
Normal file
140
scripts/experiments/reuse_eval/formal_metrics.py
Normal file
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate direct measurement boundaries and preserve seven raw metrics."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
from common import atomic_json, read_json
|
||||
|
||||
|
||||
def interval_union(intervals: list[tuple[int, int]]) -> int:
|
||||
total, left, right = 0, None, None
|
||||
for start, end in sorted(intervals):
|
||||
if type(start) is not int or type(end) is not int or start < 0 or end < start:
|
||||
raise ValueError("invalid sync interval")
|
||||
if right is None:
|
||||
left, right = start, end
|
||||
elif start <= right:
|
||||
right = max(right, end)
|
||||
else:
|
||||
total += right - left
|
||||
left, right = start, end
|
||||
return total + (right - left if right is not None else 0)
|
||||
|
||||
|
||||
def ratio(hits: int, queries: int, enabled: bool, definition: str) -> dict:
|
||||
if type(hits) is not int or type(queries) is not int or not 0 <= hits <= queries:
|
||||
raise ValueError("invalid cache hit denominator")
|
||||
if not enabled and (hits or queries):
|
||||
raise ValueError("disabled cache unexpectedly reported queries")
|
||||
return {"enabled": enabled, "hits": hits, "queries": queries,
|
||||
"ratio": hits / queries if enabled and queries else None, "definition": definition}
|
||||
|
||||
|
||||
def hit_ratios(stage: dict, profile: str) -> dict:
|
||||
counts, roa = stage["analysis_counts"], stage["roa_validation_cache"]
|
||||
signature = stage.get("crypto_signature_cache_observe")
|
||||
stats = list(signature["per_point"].values()) if signature else []
|
||||
return {
|
||||
"signature": ratio(sum(v["verify_skipped"] for v in stats), sum(v["calls"] for v in stats),
|
||||
profile == "signature", "skipped cryptographic verifications / signature cache calls"),
|
||||
"roa": ratio(roa["hit_roas"], roa["hit_roas"] + roa["miss_roas"] + roa["blocked_roas"],
|
||||
profile in ("object", "hybrid"), "reused ROA results / (hits + misses + blocked); context-blocked is a subset of blocked"),
|
||||
"child_certificate": ratio(counts.get("child_certificate_cache_hit", 0), counts.get("child_certificate_cache_lookup", 0),
|
||||
profile in ("object", "hybrid"), "reused child-certificate results / child-certificate cache lookups"),
|
||||
"publication_point": ratio(counts.get("publication_point_cache_reuse_hits", 0), counts.get("publication_point_cache_lookup_total", 0),
|
||||
profile in ("pp", "hybrid"), "actual publication-point reuse / publication-point cache lookups"),
|
||||
}
|
||||
|
||||
|
||||
def compare_transport_measurements(intervals: list[dict], table: dict, rsync_scope: str) -> dict:
|
||||
"""Compare request spans with the fetch scope recorded by the native table."""
|
||||
if rsync_scope not in ("module-root", "publication-point", "host"):
|
||||
raise ValueError("missing or unsupported measured rsync scope")
|
||||
|
||||
def scope_uri(uri: str) -> str:
|
||||
if not isinstance(uri, str) or not uri.startswith("rsync://"):
|
||||
raise ValueError("invalid measured rsync URI")
|
||||
normalized = uri if uri.endswith("/") else uri + "/"
|
||||
authority, _, path = normalized[len("rsync://"):].partition("/")
|
||||
if not authority or any(v in normalized for v in ("?", "#")) or any(v.isspace() for v in normalized):
|
||||
raise ValueError("invalid measured rsync authority/path")
|
||||
segments = [v for v in path.split("/") if v]
|
||||
# Match scoped_rsync_fetch_uri: host scope changes failure deduplication,
|
||||
# but still fetches the original publication point rather than the host.
|
||||
if rsync_scope == "module-root" and segments:
|
||||
return f"rsync://{authority}/{segments[0]}/"
|
||||
return normalized
|
||||
|
||||
measured = {protocol: set() for protocol in ("rrdp", "rsync")}
|
||||
proof = []
|
||||
for row in intervals:
|
||||
protocol = row["protocol"]
|
||||
if protocol not in measured or type(row["success"]) is not bool:
|
||||
raise ValueError("unrecognized measured protocol or outcome")
|
||||
uri = scope_uri(row["uri"]) if protocol == "rsync" else row["uri"]
|
||||
if uri not in table[protocol]:
|
||||
raise ValueError(f"{protocol} measurement coverage differs from native transport table")
|
||||
outcome = table[protocol][uri]
|
||||
if outcome != "Success" and not (isinstance(outcome, dict) and set(outcome) == {"Failure"}
|
||||
and isinstance(outcome["Failure"], str)):
|
||||
raise ValueError("invalid native transport outcome")
|
||||
if row["success"] != (outcome == "Success"):
|
||||
raise ValueError("measured transport outcome differs from T1")
|
||||
measured[protocol].add(uri)
|
||||
proof.append({**row, "scope_uri": uri})
|
||||
for protocol in measured:
|
||||
if measured[protocol] != set(table[protocol]):
|
||||
raise ValueError(f"{protocol} measurement coverage differs from native transport table")
|
||||
return {"schema": "rpki-reuse-transport-measurement-v1", "pass": True,
|
||||
"rsync_scope_policy": rsync_scope, "intervals": proof}
|
||||
|
||||
|
||||
def collect(run: Path, benchmark: Path, process: dict, size: dict, profile: str, table: dict) -> dict:
|
||||
direct = read_json(run / "evaluation.json")
|
||||
if direct.get("schema_version") != 1 or direct.get("clock") != "Linux CLOCK_MONOTONIC nanoseconds":
|
||||
raise ValueError("unsupported evaluation clock/schema")
|
||||
trigger = process["controller_trigger_monotonic_ns"]
|
||||
began, ready = direct["rp_start_ns"], direct["payload_ready_ns"]
|
||||
if not 0 < trigger <= began <= ready:
|
||||
raise ValueError("controller/RP payload clock order mismatch")
|
||||
intervals = direct["sync_intervals"]
|
||||
if not intervals or any(not began <= v["start_ns"] <= v["end_ns"] <= ready or type(v["success"]) is not bool for v in intervals):
|
||||
raise ValueError("sync interval is missing or outside the native run")
|
||||
transport_proof = compare_transport_measurements(
|
||||
intervals, table, read_json(run / "contract.json").get("rsyncScopePolicy"))
|
||||
modes = direct["rrdp_modes"]
|
||||
if any(v not in ("snapshot", "delta", "no_update") for v in modes.values()):
|
||||
raise ValueError("unrecognized RRDP mode")
|
||||
if any(uri not in modes for uri, value in table["rrdp"].items() if value == "Success"):
|
||||
raise ValueError("successful RRDP mode was not measured")
|
||||
union = interval_union([(v["start_ns"], v["end_ns"]) for v in intervals])
|
||||
if union != direct["sync_wall_union_ns"] or union > ready - began:
|
||||
raise ValueError("sync union does not match raw intervals")
|
||||
engine = read_json(benchmark / "engine-timing.json")
|
||||
if "background write drain" not in engine["boundary"] or engine["wall_ns"] <= 0:
|
||||
raise ValueError("T2 timing lacks the required background write boundary")
|
||||
gnu_time = (run / "process-time.txt").read_text()
|
||||
rss = re.findall(r"Maximum resident set size \(kbytes\):\s*(\d+)", gnu_time)
|
||||
if len(rss) != 1 or int(rss[0]) <= 0:
|
||||
raise ValueError("native RP maximum RSS was not measured")
|
||||
result = {
|
||||
"schema": "rpki-reuse-seven-metrics-v1", "profile": profile,
|
||||
"repository_sync_ns": union, "rp_validation_ns": engine["wall_ns"],
|
||||
"update_to_payload_ns": ready - trigger,
|
||||
"cache_hit_ratio": hit_ratios(read_json(run / "stage-timing.json"), profile),
|
||||
"cpu_ns": process["cpu_ns"], "peak_rss_bytes": int(rss[0]) * 1024,
|
||||
"cgroup_memory_peak_bytes": process["memory_peak_bytes"],
|
||||
"cache_size_bytes": size["required_serialized_bytes"],
|
||||
"engine_user_cpu_secs": engine["user_cpu_secs"], "engine_system_cpu_secs": engine["system_cpu_secs"],
|
||||
"rrdp_modes": dict(Counter(modes.values())),
|
||||
"boundaries": {"sync": direct["sync_boundary"], "payload": direct["payload_boundary"],
|
||||
"validation": engine["boundary"], "cpu": "entire T1 RP cgroup including subprocesses; excludes server",
|
||||
"rss": "GNU time maximum resident set size; Linux wait4 ru_maxrss; separate from cgroup charged memory/page cache",
|
||||
"cache": "retained required serialized reuse projection records and sidecar files; raw repository and common disabled projections excluded"},
|
||||
}
|
||||
atomic_json(run / "transport-measurement-comparison.json", transport_proof)
|
||||
atomic_json(run / "seven-metrics.json", result)
|
||||
return result
|
||||
Reference in New Issue
Block a user